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..d96cf04d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,3 +10,9 @@ [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 +[submodule "components/bip_nonces_cache/upstream"] + path = components/bip_nonces_cache/upstream + url = https://github.com/pythcoiner/bip_nonces_cache.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/bip_nonces_cache/upstream b/components/bip_nonces_cache/upstream new file mode 160000 index 00000000..c21afab0 --- /dev/null +++ b/components/bip_nonces_cache/upstream @@ -0,0 +1 @@ +Subproject commit c21afab0c8c0136fa1dbdc245988736ef3dfcc6b diff --git a/components/bipqr/CMakeLists.txt b/components/bipqr/CMakeLists.txt new file mode 100644 index 00000000..13bd9ce9 --- /dev/null +++ b/components/bipqr/CMakeLists.txt @@ -0,0 +1,31 @@ +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" + "../bip_nonces_cache/upstream/bip-nonces-cache-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..100aaacd --- /dev/null +++ b/components/bipqr/Cargo.lock @@ -0,0 +1,19 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bip-nonces-cache-ll" +version = "0.0.1" + +[[package]] +name = "bipqr-ll" +version = "0.0.1" + +[[package]] +name = "kern-bipqr" +version = "0.1.0" +dependencies = [ + "bip-nonces-cache-ll", + "bipqr-ll", +] diff --git a/components/bipqr/Cargo.toml b/components/bipqr/Cargo.toml new file mode 100644 index 00000000..36edb4cc --- /dev/null +++ b/components/bipqr/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "kern-bipqr" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["staticlib"] + +[dependencies] +bipqr-ll = { path = "upstream/bipqr-ll", features = ["ffi"] } +bip-nonces-cache-ll = { path = "../bip_nonces_cache/upstream/bip-nonces-cache-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..622502ec --- /dev/null +++ b/components/bipqr/src/lib.rs @@ -0,0 +1,48 @@ +#![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 bip_nonces_cache_ll::ffi::{ + bnc_begin_round_one, bnc_begin_round_two, bnc_begin_signing, bnc_cached_nonce, + bnc_held_session, bnc_issue, bnc_secret_free, bnc_session_field_decode, bnc_sign_musig, + bnc_signer_free, bnc_signer_new, bnc_two_round_session_id, +}; +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/components/libwally-core/CMakeLists.txt b/components/libwally-core/CMakeLists.txt index 470a9eaf..d7e3495b 100644 --- a/components/libwally-core/CMakeLists.txt +++ b/components/libwally-core/CMakeLists.txt @@ -1,9 +1,10 @@ idf_component_register(SRCS "kern_wally.c" - "upstream/src/amalgamation/combined.c" + "kern_combined.c" INCLUDE_DIRS "." "upstream/include" + "upstream/src/secp256k1/include" PRIV_INCLUDE_DIRS "." "upstream" @@ -13,7 +14,7 @@ idf_component_register(SRCS PRIV_REQUIRES mbedtls secure_memory) set_source_files_properties( - upstream/src/amalgamation/combined.c + kern_combined.c PROPERTIES COMPILE_FLAGS "-Wno-error=maybe-uninitialized -Wno-error=array-parameter" ) @@ -25,8 +26,7 @@ target_compile_definitions(${COMPONENT_TARGET} PRIVATE "-DBUILD_MINIMAL=1") # Drops the Elements fields from the public structs. It changes their layout, # so it is PUBLIC: every user of the headers must see it. target_compile_definitions(${COMPONENT_TARGET} PUBLIC "-DWALLY_ABI_NO_ELEMENTS") -# Standard libsecp256k1: drops MuSig2 + ecdsa-s2c/anti-exfil (unused by Kern). -target_compile_definitions(${COMPONENT_TARGET} PRIVATE "-DBUILD_STANDARD_SECP=1") target_compile_definitions(${COMPONENT_TARGET} PRIVATE "-DHAVE_PSA_CRYPTO_H") -# The secp256k1 module set is combined.c's. +# The secp256k1 module set is combined.c's, MuSig2 included, plus the BIP352 +# silentpayments module kern_combined.c enables. target_compile_definitions(${COMPONENT_TARGET} PRIVATE "-DECMULT_WINDOW_SIZE=8") diff --git a/components/libwally-core/kern_bech32.h b/components/libwally-core/kern_bech32.h new file mode 100644 index 00000000..b740aaec --- /dev/null +++ b/components/libwally-core/kern_bech32.h @@ -0,0 +1,12 @@ +#pragma once +#include +#include + +/* BIP352 caps silent payment strings at 1023 chars, past BIP173's 90. */ +#define KERN_BECH32M_MAX_LEN 1023 + +/* Bech32m-encode `version` then `bytes` under `hrp` into `out`, which holds + * `out_len` chars including the NUL. Returns WALLY_OK or WALLY_EINVAL. */ +int kern_bech32m_encode(const char *hrp, uint8_t version, + const unsigned char *bytes, size_t bytes_len, char *out, + size_t out_len); diff --git a/components/libwally-core/kern_combined.c b/components/libwally-core/kern_combined.c new file mode 100644 index 00000000..0abebd83 --- /dev/null +++ b/components/libwally-core/kern_combined.c @@ -0,0 +1,33 @@ +/* libwally amalgamation plus the BIP352 silentpayments module of the bundled + * secp256k1-zkp, which needs the secp256k1 internals of the same translation + * unit. */ +#define ENABLE_MODULE_SILENTPAYMENTS 1 +#include "upstream/src/amalgamation/combined.c" + +#ifndef WALLY_NO_AMALGAMATION +#include "kern_bech32.h" + +int kern_bech32m_encode(const char *hrp, uint8_t version, + const unsigned char *bytes, size_t bytes_len, char *out, + size_t out_len) { + uint8_t data[KERN_BECH32M_MAX_LEN]; + size_t data_len = 0; + /* Version group, then 8-bit bytes regrouped into padded 5-bit groups */ + const size_t groups = 1 + (bytes_len * 8 + 4) / 5; + size_t hrp_len; + + if (!hrp || !bytes || !out || version > 31 || groups > sizeof(data)) + return WALLY_EINVAL; + hrp_len = strlen(hrp); + /* hrp, separator, data groups, 6-char checksum and NUL */ + if (hrp_len + 1 + groups + 6 + 1 > out_len) + return WALLY_EINVAL; + data[0] = version; + convert_bits(data + 1, &data_len, 5, bytes, bytes_len, 8, 1); + ++data_len; + if (!bech32_encode(out, hrp, hrp_len, data, data_len, KERN_BECH32M_MAX_LEN, + true)) + return WALLY_EINVAL; + return WALLY_OK; +} +#endif /* WALLY_NO_AMALGAMATION */ diff --git a/components/libwally-core/upstream b/components/libwally-core/upstream index 501b204e..9098777e 160000 --- a/components/libwally-core/upstream +++ b/components/libwally-core/upstream @@ -1 +1 @@ -Subproject commit 501b204ed3913d1be4be43f116b63b62a86893b2 +Subproject commit 9098777e9ddeb152a7ab6ffedadab1073a7cf5ef 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..6300e312 100644 --- a/main/core/bip138_backup.c +++ b/main/core/bip138_backup.c @@ -13,10 +13,18 @@ #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) +/* Sets the marks of silent payment account records apart from backup marks */ +static const uint8_t sp_account_tag[] = "kern-sp-account"; +#define SP_ACCOUNT_TAG_LEN (sizeof(sp_account_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 +68,47 @@ 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_sp_account_mark(const uint8_t *record, size_t len, + uint8_t mark[BIP138_BACKUP_MARK_LEN]) { + const uint8_t *parts[] = {sp_account_tag, record}; + size_t lens[] = {SP_ACCOUNT_TAG_LEN, len}; + return approval_mac(parts, lens, 2, mark); +} + +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 +132,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 +156,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 +263,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 +323,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 +333,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 +359,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 +384,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 +397,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..0fc28309 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,15 @@ 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); +#define BIP138_BACKUP_MARK_LEN 32 + +/* This seed's approval mark over a silent payment account record: the key of + * the backup marks, with the record set apart from any backup. */ +KERN_WARN_UNUSED_RESULT bool +bip138_backup_sp_account_mark(const uint8_t *record, size_t len, + uint8_t mark[BIP138_BACKUP_MARK_LEN]); /* 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/bip138_keys.c b/main/core/bip138_keys.c index 5e8a98fc..074ed51b 100644 --- a/main/core/bip138_keys.c +++ b/main/core/bip138_keys.c @@ -1,5 +1,6 @@ #include "bip138_keys.h" #include "bip32_path.h" +#include "descriptor_keys.h" #include "wallet.h" #include #include @@ -84,16 +85,87 @@ static bool parse_origin(const char *str, bip138_key_origin *origin) { return true; } -static bool key_origin(const struct wally_descriptor *desc, size_t index, - bip138_key_origin *origin) { - char *str = NULL; - if (wally_descriptor_get_key_origin_path_str(desc, index, &str) != WALLY_OK) - return false; +/* The recipient key of `ref`, if it has one. `derived` is true when a + * derivation follows the key expression at `ref.index`, the whole musig() for a + * participant; a participant with its own derivation qualifies too. */ +static bool ref_recipient_key(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, bool derived, + uint8_t xonly[EC_XONLY_PUBLIC_KEY_LEN]) { + char xpub[XPUB_MAX_LEN]; + char *key_str = descriptor_key_string_alloc(desc, ref); + const char *rest = key_str ? split_key(key_str, xpub, sizeof(xpub)) : NULL; + bool ok = rest && (derived || rest[0] == '/') && xpub_to_xonly(xpub, xonly); + wally_free_string(key_str); + return ok; +} + +static bool ref_origin(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, bip138_key_origin *origin) { + char *str = descriptor_key_origin_path_alloc(desc, ref); bool ok = parse_origin(str, origin); wally_free_string(str); return ok; } +/* Adds the recipient key of `ref` to `keys_out` unless it is there already. A + * key that does not qualify (see ref_recipient_key) is skipped. Fails when + * `keys_out` is full or the origin does not parse. */ +static bool add_key(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, bool derived, uint8_t *keys_out, + bip138_key_origin *origins_out, size_t max_keys, + size_t *count) { + uint8_t xonly[EC_XONLY_PUBLIC_KEY_LEN]; + if (!ref_recipient_key(desc, ref, derived, xonly)) + return true; + for (size_t j = 0; j < *count; j++) { + if (memcmp(keys_out + j * BIP138_KEY_LEN, xonly, BIP138_KEY_LEN) == 0) + return true; + } + if (*count == max_keys) + return false; + if (origins_out && !ref_origin(desc, ref, &origins_out[*count])) + return false; + memcpy(keys_out + *count * BIP138_KEY_LEN, xonly, BIP138_KEY_LEN); + (*count)++; + return true; +} + +/* Adds the origin of the recipient key of `ref` to `origins_out` unless it is + * there already. A key that does not qualify (see ref_recipient_key), or whose + * origin has no path, is skipped. Fails when `origins_out` is full or the + * origin does not parse. */ +static bool add_origin(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, bool derived, + bip138_key_origin *origins_out, size_t max_origins, + size_t *count) { + uint8_t xonly[EC_XONLY_PUBLIC_KEY_LEN]; + bip138_key_origin origin; + if (!ref_recipient_key(desc, ref, derived, xonly)) + return true; + if (!ref_origin(desc, ref, &origin)) + return false; + if (origin.depth == 0) + return true; + for (size_t j = 0; j < *count; j++) { + if (origins_out[j].depth == origin.depth && + memcmp(origins_out[j].child, origin.child, + origin.depth * sizeof(origin.child[0])) == 0) + return true; + } + if (*count == max_origins) + return false; + origins_out[(*count)++] = origin; + return true; +} + +/* Whether a derivation follows key expression `i`. */ +static bool key_derived(const struct wally_descriptor *desc, uint32_t i) { + size_t child_len = 0; + return wally_descriptor_get_key_child_path_str_len(desc, i, &child_len) == + WALLY_OK && + child_len > 0; +} + /* Parses a descriptor without private keys. */ static struct wally_descriptor *parse_public(const char *descriptor, uint32_t wally_network, @@ -111,22 +183,6 @@ static struct wally_descriptor *parse_public(const char *descriptor, return desc; } -/* The recipient key of key expression `i`, if it has one. */ -static bool recipient_key(const struct wally_descriptor *desc, size_t i, - uint8_t xonly[EC_XONLY_PUBLIC_KEY_LEN]) { - size_t child_len = 0; - char *key_str = NULL; - char xpub[XPUB_MAX_LEN]; - if (wally_descriptor_get_key_child_path_str_len(desc, i, &child_len) != - WALLY_OK || - child_len == 0 || wally_descriptor_get_key(desc, i, &key_str) != WALLY_OK) - return false; - bool ok = split_key(key_str, xpub, sizeof(xpub)) != NULL && - xpub_to_xonly(xpub, xonly); - wally_free_string(key_str); - return ok; -} - bool bip138_keys_from_descriptor(const char *descriptor, uint32_t wally_network, uint8_t *keys_out, bip138_key_origin *origins_out, @@ -142,24 +198,16 @@ bool bip138_keys_from_descriptor(const char *descriptor, uint32_t wally_network, if (!desc) return false; - for (size_t i = 0; ok && i < num_keys; i++) { - uint8_t xonly[EC_XONLY_PUBLIC_KEY_LEN]; - if (!recipient_key(desc, i, xonly)) - continue; - size_t j = 0; - while (j < count && - memcmp(keys_out + j * BIP138_KEY_LEN, xonly, BIP138_KEY_LEN) != 0) - j++; - if (j < count) - continue; - if (count == max_keys) { - ok = false; - break; - } - memcpy(keys_out + count * BIP138_KEY_LEN, xonly, BIP138_KEY_LEN); - if (origins_out) - ok = key_origin(desc, i, &origins_out[count]); - count++; + for (uint32_t i = 0; ok && i < num_keys; i++) { + bool derived = key_derived(desc, i); + descriptor_key_ref_t ref = {.index = i, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + size_t participants = descriptor_key_musig_participants(desc, i); + if (participants == 0) + ok = add_key(desc, ref, derived, keys_out, origins_out, max_keys, &count); + for (ref.participant = 0; ok && ref.participant < participants; + ref.participant++) + ok = add_key(desc, ref, derived, keys_out, origins_out, max_keys, &count); } wally_descriptor_free(desc); if (!ok || count == 0) @@ -183,26 +231,16 @@ bool bip138_origins_from_descriptor(const char *descriptor, if (!desc) return false; - for (size_t i = 0; ok && i < num_keys; i++) { - uint8_t xonly[EC_XONLY_PUBLIC_KEY_LEN]; - bip138_key_origin origin; - if (!recipient_key(desc, i, xonly)) - continue; - ok = key_origin(desc, i, &origin); - if (!ok || origin.depth == 0) - continue; - size_t j = 0; - while (j < count && (origins_out[j].depth != origin.depth || - memcmp(origins_out[j].child, origin.child, - origin.depth * sizeof(origin.child[0])) != 0)) - j++; - if (j < count) - continue; - if (count == max_origins) { - ok = false; - break; - } - origins_out[count++] = origin; + for (uint32_t i = 0; ok && i < num_keys; i++) { + bool derived = key_derived(desc, i); + descriptor_key_ref_t ref = {.index = i, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + size_t participants = descriptor_key_musig_participants(desc, i); + if (participants == 0) + ok = add_origin(desc, ref, derived, origins_out, max_origins, &count); + for (ref.participant = 0; ok && ref.participant < participants; + ref.participant++) + ok = add_origin(desc, ref, derived, origins_out, max_origins, &count); } wally_descriptor_free(desc); if (!ok) diff --git a/main/core/bip138_keys.h b/main/core/bip138_keys.h index a84bb58f..94b3f728 100644 --- a/main/core/bip138_keys.h +++ b/main/core/bip138_keys.h @@ -25,8 +25,9 @@ KERN_WARN_UNUSED_RESULT bool bip138_key_from_expression(const char *expr, uint8_t xonly_out[32]); /* Distinct recipient keys of a descriptor, with each key's origin path when - * origins_out is given. Fails when no key qualifies or more than max_keys do. - */ + * origins_out is given. A musig() stands for its participants, which qualify + * when a derivation follows the musig() or them. Fails when no key qualifies + * or more than max_keys do. */ KERN_WARN_UNUSED_RESULT bool bip138_keys_from_descriptor(const char *descriptor, uint32_t wally_network, uint8_t *keys_out, bip138_key_origin *origins_out, diff --git a/main/core/bip322.c b/main/core/bip322.c index fea5709a..48e8e0b2 100644 --- a/main/core/bip322.c +++ b/main/core/bip322.c @@ -29,10 +29,21 @@ static bool get_message_field(const struct wally_psbt *psbt, return true; } +/* The BIP322 to_sign shape: version 0, locktime 0, one input spending + * to_spend:0 with sequence 0, one 0-value OP_RETURN output. */ +static bool is_to_sign_tx(const struct wally_tx *tx) { + return tx && tx->version == 0 && tx->locktime == 0 && tx->num_inputs == 1 && + tx->num_outputs == 1 && tx->inputs[0].index == 0 && + tx->inputs[0].sequence == 0 && tx->outputs[0].satoshi == 0 && + tx->outputs[0].script_len == 1 && + tx->outputs[0].script[0] == OP_RETURN; +} + bool bip322_detect(const struct wally_psbt *psbt) { const unsigned char *msg; size_t msg_len; - return psbt && get_message_field(psbt, &msg, &msg_len); + return psbt && get_message_field(psbt, &msg, &msg_len) && + is_to_sign_tx(psbt->tx); } /* BIP322 tagged hash: SHA256(SHA256(tag) || SHA256(tag) || message). libwally @@ -92,22 +103,11 @@ bool bip322_parse(const struct wally_psbt *psbt, bool is_testnet, return false; } - /* to_sign structure per BIP322 */ const struct wally_tx *tx = psbt->tx; - if (!tx || tx->version != 0 || tx->locktime != 0 || tx->num_inputs != 1 || - tx->num_outputs != 1) { + if (!is_to_sign_tx(tx)) { ESP_LOGW(TAG, "to_sign transaction structure mismatch"); return false; } - if (tx->inputs[0].index != 0 || tx->inputs[0].sequence != 0) { - ESP_LOGW(TAG, "to_sign input must spend to_spend:0 with sequence 0"); - return false; - } - if (tx->outputs[0].satoshi != 0 || tx->outputs[0].script_len != 1 || - tx->outputs[0].script[0] != OP_RETURN) { - ESP_LOGW(TAG, "to_sign output must be 0-value OP_RETURN"); - return false; - } const struct wally_tx_output *utxo = psbt->inputs[0].witness_utxo; if (!utxo || utxo->satoshi != 0 || !utxo->script || utxo->script_len == 0 || diff --git a/main/core/bip322.h b/main/core/bip322.h index 66fc698b..a0c92a4f 100644 --- a/main/core/bip322.h +++ b/main/core/bip322.h @@ -12,7 +12,9 @@ typedef struct { } bip322_request_t; // True if the PSBT carries the PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE (0x09) -// global field, marking it as a BIP322 message-signing request. +// global field over a BIP322 to_sign transaction, marking it as a BIP322 +// message-signing request. A nonce cache session uses the same key on a +// regular transaction. KERN_WARN_UNUSED_RESULT bool bip322_detect(const struct wally_psbt *psbt); // Validates a BIP322 to_sign PSBT: structure (version-0 tx, single input at 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_checksum.c b/main/core/descriptor_checksum.c index 1d1c3dd2..1b0d9c42 100644 --- a/main/core/descriptor_checksum.c +++ b/main/core/descriptor_checksum.c @@ -1,4 +1,5 @@ #include "descriptor_checksum.h" +#include "musig_leaves.h" #include #include #include @@ -101,6 +102,10 @@ bool descriptor_text_has_uppercase_hardened(const char *s) { return false; } +bool descriptor_checksum_from_string(const char *body, char out[9]) { + return body && out && desc_compute_checksum(body, strlen(body), out); +} + bool descriptor_checksum_from_descriptor(const struct wally_descriptor *desc, char out[9]) { if (!desc || !out) @@ -127,9 +132,14 @@ bool descriptor_string_from_descriptor(const struct wally_descriptor *desc, if (!desc || !output) return false; - char *canonical = NULL; + char *wally_canonical = NULL; if (wally_descriptor_canonicalize(desc, WALLY_MS_CANONICAL_NO_CHECKSUM, - &canonical) != WALLY_OK) + &wally_canonical) != WALLY_OK) + return false; + /* The text a leaf musig() was rewritten from, not the rewrite */ + char *canonical = musig_leaves_restore_alloc(wally_canonical); + wally_free_string(wally_canonical); + if (!canonical) return false; size_t body_len = strlen(canonical); @@ -140,13 +150,13 @@ bool descriptor_string_from_descriptor(const struct wally_descriptor *desc, char cksum[9]; if (!desc_compute_checksum(canonical, body_len, cksum)) { - wally_free_string(canonical); + free(canonical); return false; } char *result = malloc(body_len + 1 + 8 + 1); if (!result) { - wally_free_string(canonical); + free(canonical); return false; } memcpy(result, canonical, body_len); @@ -154,7 +164,7 @@ bool descriptor_string_from_descriptor(const struct wally_descriptor *desc, memcpy(result + body_len + 1, cksum, 8); result[body_len + 9] = '\0'; - wally_free_string(canonical); + free(canonical); *output = result; return true; } diff --git a/main/core/descriptor_checksum.h b/main/core/descriptor_checksum.h index 53ec2163..14a7679b 100644 --- a/main/core/descriptor_checksum.h +++ b/main/core/descriptor_checksum.h @@ -9,6 +9,10 @@ struct wally_descriptor; KERN_WARN_UNUSED_RESULT bool descriptor_string_from_descriptor(const struct wally_descriptor *desc, char **output); +/* Checksum of `body` exactly as written, for descriptors libwally cannot + * parse (such as BIP392 sp()). */ +KERN_WARN_UNUSED_RESULT bool descriptor_checksum_from_string(const char *body, + char out[9]); KERN_WARN_UNUSED_RESULT bool descriptor_checksum_from_descriptor(const struct wally_descriptor *desc, char out[9]); diff --git a/main/core/descriptor_keys.c b/main/core/descriptor_keys.c new file mode 100644 index 00000000..7078f83b --- /dev/null +++ b/main/core/descriptor_keys.c @@ -0,0 +1,265 @@ +#include "descriptor_keys.h" + +#include "musig_leaves.h" +#include +#include +#include + +#define FINGERPRINT_HEX_LEN (2 * BIP32_KEY_FINGERPRINT_LEN) +#define CHILD_PATH_FLAGS \ + (BIP32_FLAG_STR_WILDCARD | BIP32_FLAG_STR_BARE | BIP32_FLAG_STR_MULTIPATH) + +/* libwally's own musig(), the tr() internal key */ +static bool is_native_musig(const struct wally_descriptor *desc, + uint32_t index) { + uint32_t features = 0; + return wally_descriptor_get_key_features(desc, index, &features) == + WALLY_OK && + (features & WALLY_MS_IS_MUSIG); +} + +/* The musig(...) expression a leaf key was rewritten from (musig_leaves.h), + * or NULL. */ +static const char *leaf_expression(const struct wally_descriptor *desc, + uint32_t index) { + char *text = NULL; + if (wally_descriptor_get_key(desc, index, &text) != WALLY_OK) { + wally_free_string(text); + return NULL; + } + const char *key = text; + if (*key == '[') { + const char *close = strchr(key, ']'); + key = close ? close + 1 : key; + } + char *path = strchr(key, '/'); + if (path) + *path = '\0'; + const char *expression = musig_leaves_expression(key); + wally_free_string(text); + return expression; +} + +/* Participant `p` of a leaf musig(...) expression, as written. */ +static bool leaf_participant(const char *expression, size_t p, + const char **start, size_t *len) { + const char *participant = strchr(expression, '(') + 1; + for (; p > 0; p--) { + participant = strchr(participant, ','); + if (!participant) + return false; + participant++; + } + size_t n = strcspn(participant, ",)"); + *start = participant; + *len = n; + return true; +} + +/* A string wally_free_string() releases: wally's allocator, as the strings + * libwally hands out. */ +static char *wally_string_alloc(const char *text, size_t len) { + struct wally_operations ops = {.struct_size = sizeof(ops)}; + if (wally_get_operations(&ops) != WALLY_OK) + return NULL; + char *copy = ops.malloc_fn(len + 1); + if (copy) { + memcpy(copy, text, len); + copy[len] = '\0'; + } + return copy; +} + +bool descriptor_key_is_musig(const struct wally_descriptor *desc, + uint32_t index) { + return is_native_musig(desc, index) || leaf_expression(desc, index); +} + +size_t descriptor_key_musig_participants(const struct wally_descriptor *desc, + uint32_t index) { + size_t count = 0; + if (is_native_musig(desc, index)) + return wally_descriptor_get_musig_num_participants(desc, index, &count) == + WALLY_OK + ? count + : 0; + const char *expression = leaf_expression(desc, index); + if (!expression) + return 0; + for (count = 1; *expression; expression++) + count += *expression == ','; + return count; +} + +/* The [fingerprint/path] origin of a leaf participant, without brackets. */ +static bool leaf_origin(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, const char **origin, + size_t *len) { + const char *expression = leaf_expression(desc, ref.index); + const char *participant = NULL; + size_t participant_len = 0; + if (!expression || + !leaf_participant(expression, ref.participant, &participant, + &participant_len) || + participant_len == 0 || participant[0] != '[') + return false; + const char *close = memchr(participant, ']', participant_len); + if (!close) + return false; + *origin = participant + 1; + *len = (size_t)(close - participant - 1); + return true; +} + +bool descriptor_key_origin_fingerprint(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, + unsigned char *fingerprint_out) { + if (ref.participant == DESCRIPTOR_KEY_NOT_MUSIG) + return wally_descriptor_get_key_origin_fingerprint( + desc, ref.index, fingerprint_out, BIP32_KEY_FINGERPRINT_LEN) == + WALLY_OK; + if (is_native_musig(desc, ref.index)) + return wally_descriptor_get_musig_participant_key_origin_fingerprint( + desc, ref.index, ref.participant, fingerprint_out, + BIP32_KEY_FINGERPRINT_LEN) == WALLY_OK; + const char *origin = NULL; + size_t len = 0, written = 0; + return leaf_origin(desc, ref, &origin, &len) && len >= FINGERPRINT_HEX_LEN && + wally_hex_n_to_bytes(origin, FINGERPRINT_HEX_LEN, fingerprint_out, + BIP32_KEY_FINGERPRINT_LEN, + &written) == WALLY_OK && + written == BIP32_KEY_FINGERPRINT_LEN; +} + +static bool key_has_fingerprint(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, + const unsigned char *fingerprint) { + unsigned char key_fp[BIP32_KEY_FINGERPRINT_LEN]; + return descriptor_key_origin_fingerprint(desc, ref, key_fp) && + memcmp(key_fp, fingerprint, BIP32_KEY_FINGERPRINT_LEN) == 0; +} + +bool descriptor_key_holds_fingerprint(const struct wally_descriptor *desc, + uint32_t index, + const unsigned char *fingerprint) { + descriptor_key_ref_t ref = {.index = index, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + size_t participants = descriptor_key_musig_participants(desc, index); + if (participants == 0) + return key_has_fingerprint(desc, ref, fingerprint); + for (ref.participant = 0; ref.participant < participants; ref.participant++) { + if (key_has_fingerprint(desc, ref, fingerprint)) + return true; + } + return false; +} + +bool descriptor_key_find(const struct wally_descriptor *desc, + const unsigned char *fingerprint, + descriptor_key_ref_t *ref_out) { + uint32_t num_keys = 0; + if (!desc || !fingerprint || !ref_out || + wally_descriptor_get_num_keys(desc, &num_keys) != WALLY_OK) + return false; + + for (uint32_t i = 0; i < num_keys; i++) { + descriptor_key_ref_t ref = {.index = i, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + size_t participants = descriptor_key_musig_participants(desc, i); + if (participants == 0 && key_has_fingerprint(desc, ref, fingerprint)) { + *ref_out = ref; + return true; + } + for (ref.participant = 0; ref.participant < participants; + ref.participant++) { + if (key_has_fingerprint(desc, ref, fingerprint)) { + *ref_out = ref; + return true; + } + } + } + return false; +} + +char *descriptor_key_origin_path_alloc(const struct wally_descriptor *desc, + descriptor_key_ref_t ref) { + if (ref.participant != DESCRIPTOR_KEY_NOT_MUSIG && + !is_native_musig(desc, ref.index)) { + const char *origin = NULL; + size_t len = 0; + if (!leaf_origin(desc, ref, &origin, &len) || len < FINGERPRINT_HEX_LEN) + return NULL; + /* the path after the fingerprint and its '/', empty without one */ + size_t skip = len > FINGERPRINT_HEX_LEN ? FINGERPRINT_HEX_LEN + 1 : len; + return wally_string_alloc(origin + skip, len - skip); + } + char *path = NULL; + int ret = + ref.participant == DESCRIPTOR_KEY_NOT_MUSIG + ? wally_descriptor_get_key_origin_path_str(desc, ref.index, &path) + : wally_descriptor_get_musig_participant_key_origin_path_str( + desc, ref.index, ref.participant, &path); + if (ret != WALLY_OK) { + wally_free_string(path); + return NULL; + } + return path; +} + +char *descriptor_key_string_alloc(const struct wally_descriptor *desc, + descriptor_key_ref_t ref) { + if (ref.participant != DESCRIPTOR_KEY_NOT_MUSIG && + !is_native_musig(desc, ref.index)) { + const char *expression = leaf_expression(desc, ref.index); + const char *participant = NULL; + size_t len = 0; + return expression && leaf_participant(expression, ref.participant, + &participant, &len) + ? wally_string_alloc(participant, len) + : NULL; + } + char *key = NULL; + int ret = ref.participant == DESCRIPTOR_KEY_NOT_MUSIG + ? wally_descriptor_get_key(desc, ref.index, &key) + : wally_descriptor_get_musig_participant_key( + desc, ref.index, ref.participant, &key); + if (ret != WALLY_OK) { + wally_free_string(key); + return NULL; + } + return key; +} + +bool descriptor_key_child_steps(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, uint32_t multi_index, + uint32_t child_num, uint32_t *steps, + size_t max_steps, size_t *steps_len) { + char *text = NULL; + const char *path = NULL; + *steps_len = 0; + if (ref.participant == DESCRIPTOR_KEY_NOT_MUSIG) { + if (wally_descriptor_get_key_child_path_str(desc, ref.index, &text) != + WALLY_OK) + return false; + path = text; + } else { + text = descriptor_key_string_alloc(desc, ref); + if (!text) + return false; + const char *key = text; + if (*key == '[') { + const char *close = strchr(key, ']'); + key = close ? close + 1 : key + strlen(key); + } + /* past the '/': a bare path starts with a step */ + path = strchr(key, '/'); + if (path) + path++; + } + bool ok = !path || path[0] == '\0' || + bip32_path_from_str_n(path, strlen(path), child_num, multi_index, + CHILD_PATH_FLAGS, steps, max_steps, + steps_len) == WALLY_OK; + wally_free_string(text); + return ok; +} diff --git a/main/core/descriptor_keys.h b/main/core/descriptor_keys.h new file mode 100644 index 00000000..414a30e6 --- /dev/null +++ b/main/core/descriptor_keys.h @@ -0,0 +1,70 @@ +#ifndef DESCRIPTOR_KEYS_H +#define DESCRIPTOR_KEYS_H + +#include "../utils/attributes.h" +#include +#include +#include +#include + +/* A key of a descriptor: the key expression at `index`, or one participant of + * the BIP-390 musig() expression at `index`. libwally gives a musig() one key + * index and no key string of its own, so its keys are reached through the + * participant. A musig() in a tapscript leaf is the key it was rewritten into + * (musig_leaves.h), and its participants come from the expression it was + * rewritten from. */ +#define DESCRIPTOR_KEY_NOT_MUSIG SIZE_MAX + +typedef struct { + uint32_t index; + /* DESCRIPTOR_KEY_NOT_MUSIG for a plain key expression */ + size_t participant; +} descriptor_key_ref_t; + +KERN_WARN_UNUSED_RESULT bool +descriptor_key_is_musig(const struct wally_descriptor *desc, uint32_t index); + +/* Number of participants of the musig() at `index`, 0 for a plain key. */ +KERN_WARN_UNUSED_RESULT size_t descriptor_key_musig_participants( + const struct wally_descriptor *desc, uint32_t index); + +/* The first key whose origin fingerprint is `fingerprint`, a musig() + * participant included, in key expression order. */ +KERN_WARN_UNUSED_RESULT bool +descriptor_key_find(const struct wally_descriptor *desc, + const unsigned char *fingerprint, + descriptor_key_ref_t *ref_out); + +/* True when the key expression at `index`, or one of its musig() participants, + * has origin fingerprint `fingerprint`. */ +KERN_WARN_UNUSED_RESULT bool +descriptor_key_holds_fingerprint(const struct wally_descriptor *desc, + uint32_t index, + const unsigned char *fingerprint); + +KERN_WARN_UNUSED_RESULT bool +descriptor_key_origin_fingerprint(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, + unsigned char *fingerprint_out); + +/* The origin path without the leading "m/", as a wally string the caller frees + * with wally_free_string(). NULL when the key has none or on failure. */ +KERN_WARN_UNUSED_RESULT char * +descriptor_key_origin_path_alloc(const struct wally_descriptor *desc, + descriptor_key_ref_t ref); + +/* The key expression text, as a wally string freed with wally_free_string(). */ +KERN_WARN_UNUSED_RESULT char * +descriptor_key_string_alloc(const struct wally_descriptor *desc, + descriptor_key_ref_t ref); + +/* The derivation steps after key `ref` at tuple position `multi_index` and + * child `child_num`: a participant's own path, else the key expression's, a + * musig()'s path after its participants. None for a key without a path. */ +KERN_WARN_UNUSED_RESULT bool +descriptor_key_child_steps(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, uint32_t multi_index, + uint32_t child_num, uint32_t *steps, + size_t max_steps, size_t *steps_len); + +#endif // DESCRIPTOR_KEYS_H diff --git a/main/core/descriptor_parse.c b/main/core/descriptor_parse.c index 51a2a94a..f0ec9545 100644 --- a/main/core/descriptor_parse.c +++ b/main/core/descriptor_parse.c @@ -1,4 +1,6 @@ +#include "musig_leaves.h" #include "wallet.h" +#include #include #include @@ -12,7 +14,12 @@ int wallet_descriptor_parse(const char *descriptor, const struct wally_map *vars_in, uint32_t network, struct wally_descriptor **output) { uint32_t flags = KERN_DESCRIPTOR_MAX_DEPTH << WALLY_MINISCRIPT_DEPTH_SHIFT; - return wally_descriptor_parse(descriptor, vars_in, network, flags, output); + char *rewritten = musig_leaves_rewrite_alloc(descriptor, network); + if (!rewritten) + return WALLY_EINVAL; + int ret = wally_descriptor_parse(rewritten, vars_in, network, flags, output); + free(rewritten); + return ret; } uint32_t wallet_wally_network_of(wallet_network_t network) { diff --git a/main/core/descriptor_validator.c b/main/core/descriptor_validator.c index 8547960c..ce082a39 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 @@ -15,6 +16,7 @@ #include "bip32_path.h" #include "descriptor_checksum.h" +#include "descriptor_keys.h" #include "miniscript_policy.h" #include "psbt_internal.h" #include "registry.h" @@ -41,7 +43,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) */ @@ -123,32 +126,13 @@ static void complete_validation(descriptor_validation_result_t result) { void descriptor_validation_cancel(void) { cleanup_context(); } -// Find the first key at or after `start` that carries our fingerprint -// Returns -1 if not found -static int find_matching_key_index(const struct wally_descriptor *descriptor, - uint32_t start) { +// The first key of the descriptor, a musig() participant included, that +// carries our fingerprint +static bool find_own_key(struct wally_descriptor *descriptor, + descriptor_key_ref_t *ref_out) { unsigned char wallet_fp[BIP32_KEY_FINGERPRINT_LEN]; - if (!key_get_fingerprint(wallet_fp)) { - return -1; - } - - uint32_t num_keys = 0; - if (wally_descriptor_get_num_keys(descriptor, &num_keys) != WALLY_OK) { - return -1; - } - - for (uint32_t i = start; i < num_keys; i++) { - unsigned char key_fp[BIP32_KEY_FINGERPRINT_LEN]; - int ret = wally_descriptor_get_key_origin_fingerprint( - descriptor, i, key_fp, BIP32_KEY_FINGERPRINT_LEN); - - if (ret == WALLY_OK && - memcmp(wallet_fp, key_fp, BIP32_KEY_FINGERPRINT_LEN) == 0) { - return (int)i; - } - } - - return -1; + return key_get_fingerprint(wallet_fp) && + descriptor_key_find(descriptor, wallet_fp, ref_out); } static bool key_is_raw(const struct wally_descriptor *descriptor, @@ -159,6 +143,29 @@ static bool key_is_raw(const struct wally_descriptor *descriptor, (features & WALLY_MS_IS_RAW); } +// The xpub of a key expression written "[fingerprint/path]xpub/path", or +// bare. NULL for a key without "pub" (a raw key). +static char *extract_xpub_from_key(const char *key_str) { + if (!key_str) + return NULL; + const char *start = key_str; + if (start[0] == '[') { + const char *close = strchr(start, ']'); + if (!close) + return NULL; + start = close + 1; + } + size_t len = strcspn(start, "/),<"); + if (len < 4 || memcmp(start + 1, "pub", 3) != 0) + return NULL; + char *xpub = malloc(len + 1); + if (xpub) { + memcpy(xpub, start, len); + xpub[len] = '\0'; + } + return xpub; +} + static bool descriptor_has_private_key(const struct wally_descriptor *desc) { uint32_t features = 0; return wally_descriptor_get_features(desc, &features) == WALLY_OK && @@ -206,7 +213,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) { @@ -288,13 +296,22 @@ static bool tr_has_script_tree(const struct wally_descriptor *descriptor) { return (features & WALLY_MS_IS_TAPSCRIPT) != 0; } -/* True if the tr() internal key (index 0) carries key-origin info ([fp/path]). - * An origin-bearing key is attributable to a participant; a bare key without - * one can only be trusted if it is a known NUMS point. */ +/* True if the tr() internal key (index 0) carries key-origin info ([fp/path]), + * for a musig() internal key when every participant does. An origin-bearing key + * is attributable to a participant; a bare key without one can only be trusted + * if it is a known NUMS point. */ static bool tr_internal_key_has_origin(struct wally_descriptor *descriptor) { unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; - return wally_descriptor_get_key_origin_fingerprint(descriptor, 0, fp, - sizeof(fp)) == WALLY_OK; + size_t participants = descriptor_key_musig_participants(descriptor, 0); + descriptor_key_ref_t ref = {.index = 0, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + if (participants == 0) + return descriptor_key_origin_fingerprint(descriptor, ref, fp); + for (ref.participant = 0; ref.participant < participants; ref.participant++) { + if (!descriptor_key_origin_fingerprint(descriptor, ref, fp)) + return false; + } + return true; } /* Reject a tr() script-tree descriptor whose internal (key-path) key is a bare @@ -361,10 +378,55 @@ 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) { +/* A musig() key shows as one entry: our fingerprint and participant xpub when + * we are a participant, the first participant's otherwise, and the + * participants' fingerprints in place of a derivation path. A participant + * without an origin shows as N/A, as a bare key does. */ +static void extract_musig_key_info(struct wally_descriptor *descriptor, + uint32_t index, uint32_t slot, + descriptor_info_t *info) { + char *derivation = info->keys[slot].derivation; + const size_t derivation_size = sizeof(info->keys[slot].derivation); + size_t participants = descriptor_key_musig_participants(descriptor, index); + unsigned char wallet_fp[BIP32_KEY_FINGERPRINT_LEN]; + bool have_wallet_fp = key_get_fingerprint(wallet_fp); + descriptor_key_ref_t shown = {.index = index, .participant = 0}; + char shown_fp[9] = "N/A"; + size_t off = (size_t)snprintf(derivation, derivation_size, "musig("); + for (size_t p = 0; p < participants; p++) { + descriptor_key_ref_t ref = {.index = index, .participant = p}; + unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; + char fp_hex[9] = "N/A"; + bool has_fp = descriptor_key_origin_fingerprint(descriptor, ref, fp); + if (has_fp) + snprintf(fp_hex, sizeof(fp_hex), "%02X%02X%02X%02X", fp[0], fp[1], fp[2], + fp[3]); + if (p == 0 || + (has_fp && have_wallet_fp && memcmp(fp, wallet_fp, sizeof(fp)) == 0)) { + shown = ref; + memcpy(shown_fp, fp_hex, sizeof(shown_fp)); + } + if (off < derivation_size) + off += (size_t)snprintf(derivation + off, derivation_size - off, "%s%s", + p ? "," : "", fp_hex); + } + if (off < derivation_size) + snprintf(derivation + off, derivation_size - off, ")"); + info->musig_participants += (uint32_t)participants; + + memcpy(info->keys[slot].fingerprint_hex, shown_fp, sizeof(shown_fp)); + char *key_str = descriptor_key_string_alloc(descriptor, shown); + char *xpub = extract_xpub_from_key(key_str); + wally_free_string(key_str); + if (xpub) { + snprintf(info->keys[slot].xpub, sizeof(info->keys[slot].xpub), "%s", xpub); + free(xpub); + } +} + +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 +448,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. */ @@ -396,6 +459,10 @@ static bool extract_descriptor_info(struct wally_descriptor *descriptor, first = letters[prev] != k; if (!first) continue; + if (descriptor_key_is_musig(descriptor, e)) { + extract_musig_key_info(descriptor, e, k, info); + continue; + } // Fingerprint unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; @@ -436,9 +503,28 @@ 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->num_keys == 1 && info->musig_participants) + snprintf(out, out_len, "MuSig2 (%u keys)", info->musig_participants); + 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 +532,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 +563,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 +588,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 +601,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 +614,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 +628,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); } @@ -633,19 +704,18 @@ static bool raw_key_matches(const char *hex, const struct ext_key *ours) { return len == EC_PUBLIC_KEY_LEN && memcmp(pub, ours->pub_key, len) == 0; } -/* Our key at key_index's origin path must be the descriptor's key; a raw key's +/* Our key at `ref`'s origin path must be the descriptor's key; a raw key's * origin is its full path. A matching fingerprint alone is - * attacker-controllable text. */ + * attacker-controllable text. `registry_key` marks the first own key, which + * the registry records. */ static descriptor_validation_result_t -verify_own_key(const struct wally_descriptor *descriptor, int key_index, - bool registry_key) { - uint32_t features = 0; - char *path_str = NULL; - if (wally_descriptor_get_key_features(descriptor, key_index, &features) != - WALLY_OK || - wally_descriptor_get_key_origin_path_str(descriptor, (uint32_t)key_index, - &path_str) != WALLY_OK || - !path_str) +verify_own_key(const struct wally_descriptor *descriptor, + descriptor_key_ref_t ref, bool registry_key) { + bool participant = ref.participant != DESCRIPTOR_KEY_NOT_MUSIG; + /* A participant is an xpub; a raw one fails the xpub match below */ + bool raw = !participant && key_is_raw(descriptor, ref.index); + char *path_str = descriptor_key_origin_path_alloc(descriptor, ref); + if (!path_str) return VALIDATION_INTERNAL_ERROR; uint32_t path[KEY_MAX_DERIVATION_DEPTH] = {0}; size_t depth = 0; @@ -653,41 +723,62 @@ verify_own_key(const struct wally_descriptor *descriptor, int key_index, path_str[0] == '\0' || bip32_path_parse(path_str, path, &depth, KEY_MAX_DERIVATION_DEPTH); wally_free_string(path_str); - bool raw = (features & WALLY_MS_IS_RAW) != 0; - /* registry_add_from_string() tracks the first own key by its origin, which + /* registry_add_parsed() tracks the first own key by its origin, which * must parse within MAX_KEYPATH_ORIGIN_DEPTH; registry_match_keypath() needs * a child path after it, which a raw key lacks. Refuse before any dialog. */ if (!path_ok || (registry_key && (raw || depth == 0 || depth > MAX_KEYPATH_ORIGIN_DEPTH))) return VALIDATION_UNSUPPORTED_KEY_ORIGIN; - char *key_str = NULL; + /* libwally lists a plain key bare; a participant may carry its origin and + * path */ + char *key_str = descriptor_key_string_alloc(descriptor, ref); + char *bare = participant ? extract_xpub_from_key(key_str) : NULL; struct ext_key *ours = NULL; - if (wally_descriptor_get_key(descriptor, key_index, &key_str) != WALLY_OK || + if (!key_str || (participant && !bare) || !key_get_derived_key_components(path, depth, &ours)) { wally_free_string(key_str); - return VALIDATION_INTERNAL_ERROR; + free(bare); + return key_str && participant && !bare ? VALIDATION_PARSE_ERROR + : VALIDATION_INTERNAL_ERROR; } - bool match = - raw ? raw_key_matches(key_str, ours) : xpub_matches(key_str, ours); + bool match = raw ? raw_key_matches(key_str, ours) + : xpub_matches(participant ? bare : key_str, ours); bip32_key_free(ours); wally_free_string(key_str); + free(bare); if (!match) ESP_LOGE(TAG, "XPub mismatch"); return match ? VALIDATION_SUCCESS : VALIDATION_XPUB_MISMATCH; } -/* Verify every key carrying our fingerprint, not just the first: the UI shows - * each of them as the wallet's. */ +/* Verify every key carrying our fingerprint, musig() participants included, + * not just the first: the UI shows each of them as the wallet's. */ static descriptor_validation_result_t verify_own_keys(const struct wally_descriptor *descriptor) { - int first = find_matching_key_index(descriptor, 0); - for (int i = first; i >= 0; - i = find_matching_key_index(descriptor, (uint32_t)i + 1)) { - descriptor_validation_result_t result = - verify_own_key(descriptor, i, i == first); - if (result != VALIDATION_SUCCESS) - return result; + unsigned char wallet_fp[BIP32_KEY_FINGERPRINT_LEN]; + uint32_t num_keys = 0; + if (!key_get_fingerprint(wallet_fp) || + wally_descriptor_get_num_keys(descriptor, &num_keys) != WALLY_OK) + return VALIDATION_INTERNAL_ERROR; + bool first = true; + for (uint32_t i = 0; i < num_keys; i++) { + descriptor_key_ref_t ref = {.index = i, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + size_t participants = descriptor_key_musig_participants(descriptor, i); + for (size_t p = 0; p < (participants ? participants : 1); p++) { + unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; + if (participants) + ref.participant = p; + if (!descriptor_key_origin_fingerprint(descriptor, ref, fp) || + memcmp(fp, wallet_fp, sizeof(fp)) != 0) + continue; + descriptor_validation_result_t result = + verify_own_key(descriptor, ref, first); + if (result != VALIDATION_SUCCESS) + return result; + first = false; + } } return VALIDATION_SUCCESS; } @@ -723,7 +814,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; @@ -833,12 +924,9 @@ descriptor_validate_keyed_parsed(const char *descriptor_str, return result; result = static_checks(descriptor); - int key_index = -1; - if (result == VALIDATION_SUCCESS) { - key_index = find_matching_key_index(descriptor, 0); - if (key_index < 0) - result = VALIDATION_FINGERPRINT_NOT_FOUND; - } + descriptor_key_ref_t key; + if (result == VALIDATION_SUCCESS && !find_own_key(descriptor, &key)) + result = VALIDATION_FINGERPRINT_NOT_FOUND; if (result == VALIDATION_SUCCESS) result = verify_own_keys(descriptor); if (result != VALIDATION_SUCCESS) { @@ -847,7 +935,7 @@ descriptor_validate_keyed_parsed(const char *descriptor_str, } *descriptor_out = descriptor; if (key_index_out) - *key_index_out = key_index; + *key_index_out = (int)key.index; return result; } @@ -897,8 +985,8 @@ void descriptor_validate_and_load(const char *descriptor_str, current_ctx->confirm_cb = confirm_cb; current_ctx->id_loc_cb = id_loc_cb; - int key_index = find_matching_key_index(descriptor, 0); - if (key_index < 0) { + descriptor_key_ref_t key; + if (!find_own_key(descriptor, &key)) { ESP_LOGE(TAG, "Wallet fingerprint not found in descriptor"); wally_descriptor_free(descriptor); complete_validation(VALIDATION_FINGERPRINT_NOT_FOUND); @@ -917,13 +1005,53 @@ void descriptor_validate_and_load(const char *descriptor_str, if (!checksum_and_dedup(descriptor)) return; - show_keyed_info(descriptor, key_index); + show_keyed_info(descriptor, (int)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; + + descriptor_key_ref_t key; + if (!find_own_key(descriptor, &key)) { + 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, (int)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..ec041aca 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; @@ -104,13 +106,26 @@ typedef struct { /* Outer script: "pkh", "wpkh", "sh(wpkh)", "sh", "sh(wsh)", "wsh" or "tr"; * NULL if none of these. */ const char *script_type; + /* Participants of the musig() keys, 0 without any. */ + uint32_t musig_participants; } 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 +150,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/dleq.c b/main/core/dleq.c new file mode 100644 index 00000000..66b4a66c --- /dev/null +++ b/main/core/dleq.c @@ -0,0 +1,195 @@ +/* + * BIP374 discrete logarithm equality proofs, ported from bwk's + * sp/src/core/dleq.rs on top of the public libsecp256k1 API. + */ + +#include "dleq.h" +#include "../utils/secure_mem.h" +#include +#include + +#define POINT_LEN 33 +#define SCALAR_LEN 32 + +static const char TAG_AUX[] = "BIP0374/aux"; +static const char TAG_NONCE[] = "BIP0374/nonce"; +static const char TAG_CHALLENGE[] = "BIP0374/challenge"; + +static const unsigned char CURVE_ORDER[SCALAR_LEN] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, + 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41}; + +static bool tagged_hash(const char *tag, const unsigned char *msg, + size_t msg_len, unsigned char *out) { + return secp256k1_tagged_sha256(wally_get_secp_context(), out, + (const unsigned char *)tag, strlen(tag), msg, + msg_len) == 1; +} + +static bool is_below_order(const unsigned char *bytes) { + return memcmp(bytes, CURVE_ORDER, SCALAR_LEN) < 0; +} + +// A 256-bit hash is below twice the order, so one subtraction reduces it. +static void reduce_mod_order(unsigned char *bytes) { + int borrow = 0; + if (is_below_order(bytes)) + return; + for (int i = SCALAR_LEN - 1; i >= 0; i--) { + int value = bytes[i] - CURVE_ORDER[i] - borrow; + bytes[i] = (unsigned char)value; + borrow = value < 0; + } +} + +static bool is_zero(const unsigned char *bytes) { + for (size_t i = 0; i < SCALAR_LEN; i++) + if (bytes[i]) + return false; + return true; +} + +static bool serialize_point(const secp256k1_pubkey *point, unsigned char *out) { + size_t len = POINT_LEN; + return secp256k1_ec_pubkey_serialize(wally_get_secp_context(), out, &len, + point, SECP256K1_EC_COMPRESSED) == 1; +} + +static bool mul_point(const secp256k1_pubkey *point, + const unsigned char *scalar, secp256k1_pubkey *out) { + *out = *point; + return secp256k1_ec_pubkey_tweak_mul(wally_get_secp_context(), out, scalar) == + 1; +} + +// R = response*point - challenge*committed, as BIP374 verification rebuilds it +static bool rebuild_commitment(const secp256k1_pubkey *point, + const secp256k1_pubkey *committed, + const unsigned char *response, + const unsigned char *challenge, + secp256k1_pubkey *out) { + const secp256k1_context *ctx = wally_get_secp_context(); + secp256k1_pubkey response_point, challenge_point; + const secp256k1_pubkey *terms[2] = {&response_point, &challenge_point}; + + return mul_point(point, response, &response_point) && + mul_point(committed, challenge, &challenge_point) && + secp256k1_ec_pubkey_negate(ctx, &challenge_point) == 1 && + secp256k1_ec_pubkey_combine(ctx, out, terms, 2) == 1; +} + +// e = hash_challenge(A || B || C || G || R1 || R2 || m) +static bool challenge_hash(const secp256k1_pubkey *points[6], + const unsigned char *message, unsigned char *out) { + unsigned char buf[6 * POINT_LEN + DLEQ_MESSAGE_LEN]; + size_t len = 0; + + for (size_t i = 0; i < 6; i++, len += POINT_LEN) + if (!serialize_point(points[i], buf + len)) + return false; + if (message) { + memcpy(buf + len, message, DLEQ_MESSAGE_LEN); + len += DLEQ_MESSAGE_LEN; + } + return tagged_hash(TAG_CHALLENGE, buf, len, out); +} + +// k = hash_nonce((a xor hash_aux(r)) || A || C || m), reduced mod n +static bool nonce_scalar(const unsigned char *secret, const unsigned char *aux, + const secp256k1_pubkey *public, + const secp256k1_pubkey *shared_secret, + const unsigned char *message, unsigned char *out) { + unsigned char buf[SCALAR_LEN + 2 * POINT_LEN + DLEQ_MESSAGE_LEN]; + size_t len = SCALAR_LEN; + bool ok = tagged_hash(TAG_AUX, aux, DLEQ_AUX_LEN, buf); + + for (size_t i = 0; ok && i < SCALAR_LEN; i++) + buf[i] ^= secret[i]; + ok = ok && serialize_point(public, buf + len); + len += POINT_LEN; + ok = ok && serialize_point(shared_secret, buf + len); + len += POINT_LEN; + if (ok && message) { + memcpy(buf + len, message, DLEQ_MESSAGE_LEN); + len += DLEQ_MESSAGE_LEN; + } + ok = ok && tagged_hash(TAG_NONCE, buf, len, out); + secure_memzero(buf, sizeof(buf)); + if (ok) + reduce_mod_order(out); + return ok && !is_zero(out); +} + +// s = k + e*a +static bool response_scalar(const unsigned char *secret, + const unsigned char *nonce, + const unsigned char *challenge, + unsigned char *out) { + const secp256k1_context *ctx = wally_get_secp_context(); + memcpy(out, secret, SCALAR_LEN); + return secp256k1_ec_seckey_tweak_mul(ctx, out, challenge) == 1 && + secp256k1_ec_seckey_tweak_add(ctx, out, nonce) == 1; +} + +bool dleq_prove(const unsigned char *secret, const secp256k1_pubkey *base, + const unsigned char *aux, const secp256k1_pubkey *generator, + const unsigned char *message, unsigned char *proof_out) { + secp256k1_pubkey public, shared_secret, r1, r2; + unsigned char nonce[SCALAR_LEN]; + unsigned char challenge[SCALAR_LEN]; + unsigned char challenge_scalar[SCALAR_LEN]; + unsigned char response[SCALAR_LEN]; + bool ok; + + if (!secret || !base || !aux || !generator || !proof_out) + return false; + + ok = mul_point(generator, secret, &public) && + mul_point(base, secret, &shared_secret) && + nonce_scalar(secret, aux, &public, &shared_secret, message, nonce) && + mul_point(generator, nonce, &r1) && mul_point(base, nonce, &r2); + if (ok) { + const secp256k1_pubkey *points[6] = {&public, base, &shared_secret, + generator, &r1, &r2}; + ok = challenge_hash(points, message, challenge); + } + if (ok) { + memcpy(challenge_scalar, challenge, SCALAR_LEN); + reduce_mod_order(challenge_scalar); + ok = response_scalar(secret, nonce, challenge_scalar, response); + } + secure_memzero(nonce, sizeof(nonce)); + if (!ok) + return false; + + // The proof carries the challenge hash as is, the response as a scalar + memcpy(proof_out, challenge, SCALAR_LEN); + memcpy(proof_out + SCALAR_LEN, response, SCALAR_LEN); + return dleq_verify(&public, base, &shared_secret, proof_out, generator, + message); +} + +bool dleq_verify(const secp256k1_pubkey *public, const secp256k1_pubkey *base, + const secp256k1_pubkey *shared_secret, + const unsigned char *proof, const secp256k1_pubkey *generator, + const unsigned char *message) { + const unsigned char *response = proof + SCALAR_LEN; + unsigned char challenge_scalar[SCALAR_LEN]; + unsigned char expected[SCALAR_LEN]; + secp256k1_pubkey r1, r2; + + if (!public || !base || !shared_secret || !proof || !generator || + !is_below_order(response)) + return false; + memcpy(challenge_scalar, proof, SCALAR_LEN); + reduce_mod_order(challenge_scalar); + if (!rebuild_commitment(generator, public, response, challenge_scalar, &r1) || + !rebuild_commitment(base, shared_secret, response, challenge_scalar, &r2)) + return false; + + const secp256k1_pubkey *points[6] = {public, base, shared_secret, + generator, &r1, &r2}; + return challenge_hash(points, message, expected) && + memcmp(expected, proof, SCALAR_LEN) == 0; +} diff --git a/main/core/dleq.h b/main/core/dleq.h new file mode 100644 index 00000000..1f49d33c --- /dev/null +++ b/main/core/dleq.h @@ -0,0 +1,27 @@ +#ifndef DLEQ_H +#define DLEQ_H + +#include "../utils/attributes.h" +#include +#include + +#define DLEQ_PROOF_LEN 64 +#define DLEQ_AUX_LEN 32 +#define DLEQ_MESSAGE_LEN 32 + +// BIP374 proof that `secret` is the discrete log of both secret*generator +// and the shared secret secret*base. `message` is optional (NULL). The proof +// is checked with dleq_verify before it is returned. +KERN_WARN_UNUSED_RESULT bool +dleq_prove(const unsigned char *secret, const secp256k1_pubkey *base, + const unsigned char *aux, const secp256k1_pubkey *generator, + const unsigned char *message, unsigned char *proof_out); + +// True if `proof` shows that `public` (secret*generator) and `shared_secret` +// (secret*base) share the same discrete log. `message` is optional (NULL). +KERN_WARN_UNUSED_RESULT bool +dleq_verify(const secp256k1_pubkey *public, const secp256k1_pubkey *base, + const secp256k1_pubkey *shared_secret, const unsigned char *proof, + const secp256k1_pubkey *generator, const unsigned char *message); + +#endif // DLEQ_H 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/miniscript_policy.c b/main/core/miniscript_policy.c index ad53a8b2..53c5a000 100644 --- a/main/core/miniscript_policy.c +++ b/main/core/miniscript_policy.c @@ -70,6 +70,52 @@ static char *copy_lower(char *dst, const char *src, size_t len) { return dst + len; } +/* The text that identifies key expression `i`: the key, or for a musig(), + * which libwally lists no key for, its participants joined. Freed with + * wally_free_string(), libc free() underneath. */ +static char *key_identity_alloc(const struct wally_descriptor *desc, + uint32_t i) { + char *key = NULL; + uint32_t features = 0; + size_t participants = 0; + if (wally_descriptor_get_key(desc, i, &key) == WALLY_OK) + return key; + if (wally_descriptor_get_key_features(desc, i, &features) != WALLY_OK || + !(features & WALLY_MS_IS_MUSIG) || + wally_descriptor_get_musig_num_participants(desc, i, &participants) != + WALLY_OK) + return NULL; + static const char prefix[] = "musig("; + size_t len = sizeof(prefix) - 1; + char *text = participants ? malloc(len + 1) : NULL; + if (!text) + return NULL; + memcpy(text, prefix, sizeof(prefix)); + for (size_t p = 0; p < participants; p++) { + char *participant = NULL; + if (wally_descriptor_get_musig_participant_key(desc, i, p, &participant) != + WALLY_OK) { + free(text); + return NULL; + } + size_t add = strlen(participant) + 1; /* and its ',' or ')' */ + char *grown = realloc(text, len + add + 1); + if (grown) { + memcpy(grown + len, participant, add - 1); + len += add; + grown[len - 1] = p + 1 < participants ? ',' : ')'; + grown[len] = '\0'; + } + wally_free_string(participant); + if (!grown) { + free(text); + return NULL; + } + text = grown; + } + return text; +} + size_t miniscript_policy_key_letters(const struct wally_descriptor *desc, uint8_t letters[MINISCRIPT_POLICY_MAX_KEY_EXPRS], @@ -84,8 +130,8 @@ miniscript_policy_key_letters(const struct wally_descriptor *desc, size_t num_distinct = 0; bool ok = true; for (uint32_t i = 0; i < num_keys && ok; i++) { - char *key = NULL; - if (wally_descriptor_get_key(desc, i, &key) != WALLY_OK || !key) { + char *key = key_identity_alloc(desc, i); + if (!key) { ok = false; break; } diff --git a/main/core/musig_leaves.c b/main/core/musig_leaves.c new file mode 100644 index 00000000..75ec811e --- /dev/null +++ b/main/core/musig_leaves.c @@ -0,0 +1,300 @@ +#include "musig_leaves.h" + +#include "descriptor_checksum.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define MUSIG_OPEN "musig(" +#define INTERNAL_KEY_OPEN "tr(" +#define CHECKSUM_LEN 8 + +/* A rewritten key and the musig(...) expression it stands for. Kept for the + * life of the process, as libwally keeps no trace of the expression. */ +typedef struct { + char *key; + char *expression; +} rewrite_t; + +static rewrite_t *rewrites; +static size_t num_rewrites; + +typedef struct { + char *text; + size_t len; + size_t cap; +} text_t; + +static bool text_append(text_t *t, const char *s, size_t n) { + if (t->len + n + 1 > t->cap) { + size_t cap = (t->len + n + 1) * 2; + char *text = realloc(t->text, cap); + if (!text) + return false; + t->text = text; + t->cap = cap; + } + memcpy(t->text + t->len, s, n); + t->len += n; + t->text[t->len] = '\0'; + return true; +} + +const char *musig_leaves_expression(const char *key) { + for (size_t i = 0; key && i < num_rewrites; i++) { + if (strcmp(rewrites[i].key, key) == 0) + return rewrites[i].expression; + } + return NULL; +} + +static bool remember(const char *key, const char *expression, + size_t expression_len) { + if (musig_leaves_expression(key)) + return true; + rewrite_t *grown = realloc(rewrites, (num_rewrites + 1) * sizeof(*grown)); + if (!grown) + return false; + rewrites = grown; + rewrite_t *r = &rewrites[num_rewrites]; + r->key = strdup(key); + r->expression = malloc(expression_len + 1); + if (!r->key || !r->expression) { + free(r->key); + free(r->expression); + return false; + } + memcpy(r->expression, expression, expression_len); + r->expression[expression_len] = '\0'; + num_rewrites++; + return true; +} + +/* The compressed key of a participant with no derivation of its own. */ +static bool participant_key(const char *text, size_t len, unsigned char *out) { + if (len && text[0] == '[') { + const char *close = memchr(text, ']', len); + if (!close) + return false; + len -= (size_t)(close + 1 - text); + text = close + 1; + } + if (memchr(text, '/', len)) + return false; + if (len == 2 * EC_PUBLIC_KEY_LEN) { + size_t written = 0; + return wally_hex_n_to_bytes(text, len, out, EC_PUBLIC_KEY_LEN, &written) == + WALLY_OK && + written == EC_PUBLIC_KEY_LEN; + } + struct ext_key xpub; + bool ok = bip32_key_from_base58_n(text, len, &xpub) == WALLY_OK; + if (ok) + memcpy(out, xpub.pub_key, EC_PUBLIC_KEY_LEN); + wally_bzero(&xpub, sizeof(xpub)); + return ok; +} + +static int compare_keys(const void *a, const void *b) { + return memcmp(a, b, EC_PUBLIC_KEY_LEN); +} + +/* The KeyAgg key of the participants `body` lists, sorted as BIP-390 does. */ +static bool aggregate_key(const char *body, size_t len, unsigned char *out) { + size_t n = 1; + for (size_t i = 0; i < len; i++) + n += body[i] == ','; + unsigned char *keys = malloc(n * EC_PUBLIC_KEY_LEN); + bool ok = keys != NULL; + const char *participant = body; + for (size_t p = 0; ok && p < n; p++) { + const char *end = + memchr(participant, ',', (size_t)(body + len - participant)); + if (!end) + end = body + len; + ok = participant_key(participant, (size_t)(end - participant), + keys + p * EC_PUBLIC_KEY_LEN); + participant = end + 1; + } + struct wally_musig_keyagg_cache *cache = NULL; + unsigned char xonly[EC_XONLY_PUBLIC_KEY_LEN]; + if (ok) { + qsort(keys, n, EC_PUBLIC_KEY_LEN, compare_keys); + ok = wally_musig_pubkey_agg(keys, n * EC_PUBLIC_KEY_LEN, xonly, + sizeof(xonly), &cache) == WALLY_OK && + wally_musig_pubkey_get(cache, out, EC_PUBLIC_KEY_LEN) == WALLY_OK; + } + wally_musig_keyagg_cache_free(cache); + free(keys); + return ok; +} + +/* The key a leaf musig() stands for: the synthetic xpub when a path follows, + * the x-only aggregate otherwise. The caller frees it with + * wally_free_string(). */ +static char *leaf_key_alloc(const char *body, size_t len, bool has_path, + uint32_t network) { + unsigned char aggregate[EC_PUBLIC_KEY_LEN]; + char *key = NULL; + if (!aggregate_key(body, len, aggregate)) + return NULL; + if (!has_path) { + if (wally_hex_from_bytes(aggregate + 1, EC_XONLY_PUBLIC_KEY_LEN, &key) != + WALLY_OK) + return NULL; + return key; + } + struct ext_key *synthetic = NULL; + uint32_t version = network == WALLY_NETWORK_BITCOIN_MAINNET + ? BIP32_VER_MAIN_PUBLIC + : BIP32_VER_TEST_PUBLIC; + if (wally_musig_pubkey_to_xpub(aggregate, sizeof(aggregate), version, + &synthetic) == WALLY_OK && + bip32_key_to_base58(synthetic, BIP32_FLAG_KEY_PUBLIC, &key) != WALLY_OK) + key = NULL; + bip32_key_free(synthetic); + return key; +} + +/* Where the derivation path after a key expression ends. */ +static const char *path_end(const char *p) { + if (*p != '/') + return p; + while (*p && *p != ',' && *p != ')' && *p != '}') + p++; + return p; +} + +/* Rewrites the leaf musig() at `open` into `out`, and where it ends. */ +static const char *rewrite_one(const char *open, uint32_t network, + text_t *out) { + const char *body = open + strlen(MUSIG_OPEN); + const char *close = strchr(body, ')'); + if (!close) + return NULL; + const char *end = path_end(close + 1); + char *key = + leaf_key_alloc(body, (size_t)(close - body), end != close + 1, network); + bool ok = key && remember(key, open, (size_t)(close + 1 - open)) && + text_append(out, key, strlen(key)) && + text_append(out, close + 1, (size_t)(end - close - 1)); + wally_free_string(key); + return ok ? end : NULL; +} + +static bool is_internal_key(const char *descriptor, const char *open) { + size_t prefix = strlen(INTERNAL_KEY_OPEN); + return (size_t)(open - descriptor) >= prefix && + memcmp(open - prefix, INTERNAL_KEY_OPEN, prefix) == 0; +} + +/* The descriptor body, checked against its checksum when it carries one. */ +static char *checked_body_alloc(const char *descriptor) { + const char *hash = strchr(descriptor, '#'); + size_t len = hash ? (size_t)(hash - descriptor) : strlen(descriptor); + char *body = malloc(len + 1); + if (!body) + return NULL; + memcpy(body, descriptor, len); + body[len] = '\0'; + char checksum[CHECKSUM_LEN + 1]; + if (hash && (!descriptor_checksum_from_string(body, checksum) || + strcmp(hash + 1, checksum) != 0)) { + free(body); + return NULL; + } + return body; +} + +static bool has_leaf_musig(const char *descriptor) { + for (const char *open = strstr(descriptor, MUSIG_OPEN); open; + open = strstr(open + 1, MUSIG_OPEN)) { + if (!is_internal_key(descriptor, open)) + return true; + } + return false; +} + +char *musig_leaves_rewrite_alloc(const char *descriptor, uint32_t network) { + if (!descriptor) + return NULL; + if (!has_leaf_musig(descriptor)) + return strdup(descriptor); + char *body = checked_body_alloc(descriptor); + if (!body) + return NULL; + + text_t out = {0}; + const char *p = body; + const char *open = NULL; + bool ok = true; + while (ok && (open = strstr(p, MUSIG_OPEN))) { + ok = text_append(&out, p, (size_t)(open - p)); + if (ok && is_internal_key(body, open)) { + ok = text_append(&out, open, strlen(MUSIG_OPEN)); + p = open + strlen(MUSIG_OPEN); + } else if (ok) { + p = rewrite_one(open, network, &out); + ok = p != NULL; + } + } + ok = ok && text_append(&out, p, strlen(p)); + free(body); + if (!ok) { + free(out.text); + return NULL; + } + return out.text; +} + +/* `text` with every occurrence of `from` replaced by `to`. */ +static bool replace_all(text_t *text, const char *from, const char *to) { + text_t out = {0}; + size_t from_len = strlen(from); + const char *p = text->text; + bool replaced = false; + for (const char *hit = strstr(p, from); hit; hit = strstr(p, from)) { + if (!text_append(&out, p, (size_t)(hit - p)) || + !text_append(&out, to, strlen(to))) { + free(out.text); + return false; + } + p = hit + from_len; + replaced = true; + } + if (!replaced) + return true; + if (!text_append(&out, p, strlen(p))) { + free(out.text); + return false; + } + free(text->text); + *text = out; + return true; +} + +char *musig_leaves_restore_alloc(const char *descriptor) { + if (!descriptor) + return NULL; + const char *hash = strchr(descriptor, '#'); + text_t out = {0}; + bool ok = + text_append(&out, descriptor, + hash ? (size_t)(hash - descriptor) : strlen(descriptor)); + for (size_t i = 0; ok && i < num_rewrites; i++) + ok = replace_all(&out, rewrites[i].key, rewrites[i].expression); + char checksum[CHECKSUM_LEN + 1]; + if (ok && hash) + ok = descriptor_checksum_from_string(out.text, checksum) && + text_append(&out, "#", 1) && text_append(&out, checksum, CHECKSUM_LEN); + if (!ok) { + free(out.text); + return NULL; + } + return out.text; +} diff --git a/main/core/musig_leaves.h b/main/core/musig_leaves.h new file mode 100644 index 00000000..5b134a0a --- /dev/null +++ b/main/core/musig_leaves.h @@ -0,0 +1,34 @@ +#ifndef MUSIG_LEAVES_H +#define MUSIG_LEAVES_H + +#include "../utils/attributes.h" +#include + +/* libwally parses a BIP-390 musig() as a tr() internal key only. A musig() in a + * tapscript leaf is rewritten into the key it stands for, which libwally + * parses as any other: the BIP-328 synthetic xpub of the aggregate, keeping + * the path, when a path follows the musig(); the x-only aggregate when none + * does. The rewrite is remembered, so the participants stay known + * (descriptor_keys.h) and the descriptor text can be restored. + * + * Participants with their own derivation make a different aggregate at every + * index, which no single key expression stands for: such a leaf musig() is + * refused. */ + +/* The descriptor with its leaf musig() rewritten, without checksum when it + * had one, which is checked first; an unchanged copy when it has no leaf + * musig(). NULL when a leaf musig() or the checksum is invalid. `network` is a + * WALLY_NETWORK_*. The caller frees it. */ +KERN_WARN_UNUSED_RESULT char *musig_leaves_rewrite_alloc(const char *descriptor, + uint32_t network); + +/* The descriptor with every rewritten key back to its musig() expression, its + * checksum recomputed when it carries one. The caller frees it. */ +KERN_WARN_UNUSED_RESULT char * +musig_leaves_restore_alloc(const char *descriptor); + +/* The musig(...) expression a rewritten key stands for, or NULL. `key` is the + * key without origin or derivation path. */ +KERN_WARN_UNUSED_RESULT const char *musig_leaves_expression(const char *key); + +#endif // MUSIG_LEAVES_H diff --git a/main/core/musig_psbt.c b/main/core/musig_psbt.c new file mode 100644 index 00000000..fb8e8ee1 --- /dev/null +++ b/main/core/musig_psbt.c @@ -0,0 +1,1220 @@ +#include "musig_psbt.h" + +#include "bip32_path.h" +#include "descriptor_keys.h" +#include "key.h" +#include "nonce_cache.h" +#include "psbt_internal.h" +#include "registry.h" +#include "script_templates.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* BIP-371: libwally keeps it among the input's fields with no accessor */ +#define PSBT_IN_TAP_MERKLE_ROOT 0x18 +#define DERIVATION_PATH_FLAGS \ + (BIP32_FLAG_STR_WILDCARD | BIP32_FLAG_STR_BARE | BIP32_FLAG_STR_MULTIPATH) +#define BIP32_TWEAK_DATA_LEN (EC_PUBLIC_KEY_LEN + sizeof(uint32_t)) +#define TAPSCRIPT_LEAF_VERSION 0xc0 +#define COMPACT_SIZE_MAX_LEN 9 +#define CONTROL_BLOCK_BASE_LEN (1 + EC_XONLY_PUBLIC_KEY_LEN) +#define CONTROL_BLOCK_MAX_DEPTH 128 +/* BIP-342 sighash: the key version of BIP-342 public keys */ +#define TAPSCRIPT_KEY_VERSION 0 + +/* True when a musig() key of `desc` has a participant of fingerprint `fp`. */ +static bool descriptor_has_own_musig(const struct wally_descriptor *desc, + const unsigned char *fp) { + uint32_t num_keys = 0; + if (wally_descriptor_get_num_keys(desc, &num_keys) != WALLY_OK) + return false; + for (uint32_t i = 0; i < num_keys; i++) { + if (descriptor_key_is_musig(desc, i) && + descriptor_key_holds_fingerprint(desc, i, fp)) + return true; + } + return false; +} + +static bool entry_generates(const registry_entry_t *entry, uint32_t multi_index, + uint32_t child_num, const unsigned char *spk, + size_t spk_len) { + /* Generation may use the buffer as workspace, as in claim_regenerate. */ + unsigned char script[PSBT_MAX_INNER_SCRIPT_LEN]; + size_t written = 0; + return wally_descriptor_to_script(entry->desc, 0, 0, 0, multi_index, + child_num, 0, script, sizeof(script), + &written) == WALLY_OK && + written == spk_len && memcmp(script, spk, spk_len) == 0; +} + +/* The two unhardened steps an origin ends with: a child number, then the + * child number of the wildcard. */ +static bool origin_tail(const struct wally_map_item *item, uint32_t *tail) { + uint32_t path[MAX_KEYPATH_TOTAL_DEPTH]; + size_t path_len = 0; + if (!bip32_path_from_keypath(item->value, item->value_len, path, &path_len, + MAX_KEYPATH_TOTAL_DEPTH) || + path_len < 2) + return false; + tail[0] = path[path_len - 2]; + tail[1] = path[path_len - 1]; + return !bip32_path_is_hardened(tail[0]) && !bip32_path_is_hardened(tail[1]); +} + +/* True when the steps of `ref` at tuple position `multi_index` end with + * `tail`. */ +static bool key_steps_end_with(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, uint32_t multi_index, + const uint32_t *tail) { + uint32_t steps[MAX_KEYPATH_TOTAL_DEPTH]; + size_t n = 0; + return descriptor_key_child_steps(desc, ref, multi_index, tail[1], steps, + MAX_KEYPATH_TOTAL_DEPTH, &n) && + n >= 2 && steps[n - 2] == tail[0] && steps[n - 1] == tail[1]; +} + +/* True when a musig() key of ours ends with `tail` at tuple position + * `multi_index`: on the musig()'s own path when it has one (aggregate then + * derive), else on our participant's. The origin then names the position the + * script is generated at, not just any position whose script matches. */ +static bool own_musig_tail(const struct wally_descriptor *desc, + const unsigned char *our_fp, uint32_t multi_index, + const uint32_t *tail) { + uint32_t num_keys = 0; + if (wally_descriptor_get_num_keys(desc, &num_keys) != WALLY_OK) + return false; + for (uint32_t i = 0; i < num_keys; i++) { + if (!descriptor_key_is_musig(desc, i) || + !descriptor_key_holds_fingerprint(desc, i, our_fp)) + continue; + descriptor_key_ref_t aggregate = {.index = i, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + if (key_steps_end_with(desc, aggregate, multi_index, tail)) + return true; + size_t participants = descriptor_key_musig_participants(desc, i); + for (size_t p = 0; p < participants; p++) { + descriptor_key_ref_t ref = {.index = i, .participant = p}; + unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; + if (descriptor_key_origin_fingerprint(desc, ref, fp) && + memcmp(fp, our_fp, sizeof(fp)) == 0 && + key_steps_end_with(desc, ref, multi_index, tail)) + return true; + } + } + return false; +} + +static bool entry_claims(const registry_entry_t *entry, + const unsigned char *our_fp, + const struct wally_map *tap_paths, + const unsigned char *spk, size_t spk_len, + claim_t *claim_out) { + for (size_t j = 0; j < tap_paths->num_items; j++) { + uint32_t tail[2]; + if (!origin_tail(&tap_paths->items[j], tail)) + continue; + for (uint32_t k = 0; k < entry->num_paths; k++) { + if (!own_musig_tail(entry->desc, our_fp, k, tail) || + !entry_generates(entry, k, tail[1], spk, spk_len)) + continue; + memset(claim_out, 0, sizeof(*claim_out)); + claim_out->kind = CLAIM_MUSIG; + claim_out->registry.entry = entry; + claim_out->registry.multi_index = k; + claim_out->registry.child_num = tail[1]; + return true; + } + } + return false; +} + +bool musig_psbt_claim(const struct wally_map *tap_paths, + const unsigned char *spk, size_t spk_len, + claim_t *claim_out) { + size_t spk_type = 0; + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; + if (!tap_paths || !spk || !claim_out || + wally_scriptpubkey_get_type(spk, spk_len, &spk_type) != WALLY_OK || + spk_type != WALLY_SCRIPT_TYPE_P2TR || !key_get_fingerprint(our_fp)) + return false; + + for (size_t i = 0; i < registry_count(); i++) { + const registry_entry_t *entry = registry_match_order_get(i); + if (entry && entry->desc && descriptor_has_own_musig(entry->desc, our_fp) && + entry_claims(entry, our_fp, tap_paths, spk, spk_len, claim_out)) + return true; + } + return false; +} + +/* A participant's compressed key at (multi_index, child_num), from its key + * expression in the descriptor, and the derivation steps the expression adds + * after the key. */ +static bool participant_key(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, uint32_t multi_index, + uint32_t child_num, unsigned char *pub_out, + uint32_t *steps, size_t *steps_len) { + char *text = descriptor_key_string_alloc(desc, ref); + if (!text) + return false; + const char *key = text; + if (*key == '[') { + const char *close = strchr(key, ']'); + key = close ? close + 1 : key + strlen(key); + } + const char *path = strchr(key, '/'); + size_t key_len = path ? (size_t)(path - key) : strlen(key); + *steps_len = 0; + + bool ok; + if (!path && key_len == 2 * EC_PUBLIC_KEY_LEN) { + size_t written = 0; + ok = wally_hex_n_to_bytes(key, key_len, pub_out, EC_PUBLIC_KEY_LEN, + &written) == WALLY_OK && + written == EC_PUBLIC_KEY_LEN; + } else { + struct ext_key xpub, child; + ok = bip32_key_from_base58_n(key, key_len, &xpub) == WALLY_OK; + /* past the '/': a bare path starts with a step */ + if (ok && path) + ok = bip32_path_from_str_n(path + 1, strlen(path + 1), child_num, + multi_index, DERIVATION_PATH_FLAGS, steps, + MAX_KEYPATH_TOTAL_DEPTH, + steps_len) == WALLY_OK && + *steps_len <= MAX_KEYPATH_TOTAL_DEPTH; + if (ok && *steps_len) + ok = bip32_key_from_parent_path(&xpub, steps, *steps_len, + BIP32_FLAG_KEY_PUBLIC | + BIP32_FLAG_SKIP_HASH, + &child) == WALLY_OK; + if (ok) + memcpy(pub_out, *steps_len ? child.pub_key : xpub.pub_key, + EC_PUBLIC_KEY_LEN); + wally_bzero(&xpub, sizeof(xpub)); + wally_bzero(&child, sizeof(child)); + } + wally_free_string(text); + return ok; +} + +static int compare_keys(const void *a, const void *b) { + return memcmp(a, b, EC_PUBLIC_KEY_LEN); +} + +/* The keys of every participant of the musig() at `key_index`, at + * (multi_index, child_num), sorted as BIP-390 orders them for KeyAgg. The + * caller frees them. */ +static unsigned char *participant_keys_alloc(const registry_entry_t *entry, + uint32_t key_index, + uint32_t multi_index, + uint32_t child_num, + size_t *count_out) { + size_t n = descriptor_key_musig_participants(entry->desc, key_index); + unsigned char *keys = n ? malloc(n * EC_PUBLIC_KEY_LEN) : NULL; + bool ok = keys != NULL; + for (size_t p = 0; ok && p < n; p++) { + descriptor_key_ref_t ref = {.index = key_index, .participant = p}; + uint32_t steps[MAX_KEYPATH_TOTAL_DEPTH]; + size_t steps_len = 0; + ok = participant_key(entry->desc, ref, multi_index, child_num, + keys + p * EC_PUBLIC_KEY_LEN, steps, &steps_len); + } + if (!ok) { + free(keys); + return NULL; + } + qsort(keys, n, EC_PUBLIC_KEY_LEN, compare_keys); + *count_out = n; + return keys; +} + +/* BIP-328: the plain tweaks of deriving the aggregate along the musig() + * expression's own path, applied to the key aggregation. */ +static bool apply_bip328_path(const registry_entry_t *entry, uint32_t key_index, + uint32_t multi_index, uint32_t child_num, + const unsigned char *aggregate, + struct wally_musig_keyagg_cache *cache) { + char *path_str = NULL; + if (wally_descriptor_get_key_child_path_str(entry->desc, key_index, + &path_str) != WALLY_OK) + return false; + uint32_t steps[MAX_KEYPATH_TOTAL_DEPTH]; + size_t steps_len = 0; + bool ok = true; + if (path_str[0] != '\0') + ok = bip32_path_from_str_n(path_str, strlen(path_str), child_num, + multi_index, DERIVATION_PATH_FLAGS, steps, + MAX_KEYPATH_TOTAL_DEPTH, + &steps_len) == WALLY_OK && + steps_len <= MAX_KEYPATH_TOTAL_DEPTH; + wally_free_string(path_str); + if (!ok || steps_len == 0) + return ok; + + struct ext_key *synthetic = NULL; + if (wally_musig_pubkey_to_xpub(aggregate, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, &synthetic) != WALLY_OK) + return false; + unsigned char data[BIP32_TWEAK_DATA_LEN]; + unsigned char hmac[HMAC_SHA512_LEN]; + unsigned char chain_code[WALLY_MUSIG2_CHAINCODE_LEN]; + memcpy(data, aggregate, EC_PUBLIC_KEY_LEN); + memcpy(chain_code, synthetic->chain_code, sizeof(chain_code)); + bip32_key_free(synthetic); + for (size_t i = 0; ok && i < steps_len; i++) { + for (size_t b = 0; b < sizeof(uint32_t); b++) + data[EC_PUBLIC_KEY_LEN + b] = (unsigned char)(steps[i] >> (24 - 8 * b)); + ok = !bip32_path_is_hardened(steps[i]) && + wally_hmac_sha512(chain_code, sizeof(chain_code), data, sizeof(data), + hmac, sizeof(hmac)) == WALLY_OK && + wally_musig_pubkey_ec_tweak_add(cache, hmac, EC_PRIVATE_KEY_LEN, data, + EC_PUBLIC_KEY_LEN) == WALLY_OK; + memcpy(chain_code, hmac + EC_PRIVATE_KEY_LEN, sizeof(chain_code)); + } + return ok; +} + +/* BIP-341: the taproot tweak of the internal key by the input's merkle root. */ +static bool apply_taproot_tweak(const struct wally_psbt_input *input, + struct wally_musig_keyagg_cache *cache, + unsigned char *output_key) { + unsigned char data[EC_XONLY_PUBLIC_KEY_LEN + SHA256_LEN]; + unsigned char internal[EC_PUBLIC_KEY_LEN]; + unsigned char tweak[SHA256_LEN]; + size_t data_len = EC_XONLY_PUBLIC_KEY_LEN; + if (wally_musig_pubkey_get(cache, internal, sizeof(internal)) != WALLY_OK) + return false; + memcpy(data, internal + 1, EC_XONLY_PUBLIC_KEY_LEN); + const struct wally_map_item *root = + wally_map_get_integer(&input->psbt_fields, PSBT_IN_TAP_MERKLE_ROOT); + if (root) { + if (root->value_len != SHA256_LEN) + return false; + memcpy(data + data_len, root->value, SHA256_LEN); + data_len += SHA256_LEN; + } + return wally_bip340_tagged_hash(data, data_len, "TapTweak", tweak, + sizeof(tweak)) == WALLY_OK && + wally_musig_pubkey_xonly_tweak_add(cache, tweak, sizeof(tweak), + output_key, + EC_PUBLIC_KEY_LEN) == WALLY_OK; +} + +/* The key aggregation of the musig() at `key_index` for one input, with the + * BIP-328 tweaks of a path after the musig(): the participants come from the + * registered descriptor, sorted as BIP-390 orders them, never from the PSBT. + * Writes the untweaked aggregate. */ +static bool musig_key_agg(const registry_entry_t *entry, uint32_t key_index, + uint32_t multi_index, uint32_t child_num, + struct wally_musig_keyagg_cache **cache_out, + unsigned char *aggregate_out) { + size_t n = 0; + unsigned char *keys = + participant_keys_alloc(entry, key_index, multi_index, child_num, &n); + if (!keys) + return false; + + unsigned char xonly[EC_XONLY_PUBLIC_KEY_LEN]; + struct wally_musig_keyagg_cache *cache = NULL; + bool ok = wally_musig_pubkey_agg(keys, n * EC_PUBLIC_KEY_LEN, xonly, + sizeof(xonly), &cache) == WALLY_OK && + wally_musig_pubkey_get(cache, aggregate_out, EC_PUBLIC_KEY_LEN) == + WALLY_OK && + apply_bip328_path(entry, key_index, multi_index, child_num, + aggregate_out, cache); + free(keys); + if (!ok) { + wally_musig_keyagg_cache_free(cache); + return false; + } + *cache_out = cache; + return true; +} + +/* The BIP-341 leaf hash of a tapscript. */ +static bool tap_leaf_hash(uint8_t leaf_version, const unsigned char *script, + size_t script_len, unsigned char *hash_out) { + size_t prefix_len = 0; + unsigned char *data = malloc(1 + COMPACT_SIZE_MAX_LEN + script_len); + if (!data) + return false; + data[0] = leaf_version; + if (wally_varint_to_bytes(script_len, data + 1, COMPACT_SIZE_MAX_LEN, + &prefix_len) != WALLY_OK) { + free(data); + return false; + } + memcpy(data + 1 + prefix_len, script, script_len); + bool ok = + wally_bip340_tagged_hash(data, 1 + prefix_len + script_len, "TapLeaf", + hash_out, SHA256_LEN) == WALLY_OK; + free(data); + return ok; +} + +/* BIP-341 script path verification: true when a TAP_LEAF_SCRIPT entry, + * control block and tapscript, is a leaf of the tree the spent output key + * commits to. Writes its leaf hash. */ +static bool leaf_in_output(const struct wally_map_item *leaf, + const unsigned char *spk, + unsigned char *leaf_hash_out) { + const unsigned char *control = leaf->key; + size_t control_len = leaf->key_len; + if (!control || control_len < CONTROL_BLOCK_BASE_LEN || + (control_len - CONTROL_BLOCK_BASE_LEN) % SHA256_LEN != 0 || + (control_len - CONTROL_BLOCK_BASE_LEN) / SHA256_LEN > + CONTROL_BLOCK_MAX_DEPTH || + (control[0] & 0xfe) != TAPSCRIPT_LEAF_VERSION || + !tap_leaf_hash(TAPSCRIPT_LEAF_VERSION, leaf->value, leaf->value_len, + leaf_hash_out)) + return false; + + unsigned char node[SHA256_LEN], pair[2 * SHA256_LEN]; + memcpy(node, leaf_hash_out, SHA256_LEN); + for (size_t off = CONTROL_BLOCK_BASE_LEN; off < control_len; + off += SHA256_LEN) { + bool node_first = memcmp(node, control + off, SHA256_LEN) < 0; + memcpy(pair, node_first ? node : control + off, SHA256_LEN); + memcpy(pair + SHA256_LEN, node_first ? control + off : node, SHA256_LEN); + if (wally_bip340_tagged_hash(pair, sizeof(pair), "TapBranch", node, + sizeof(node)) != WALLY_OK) + return false; + } + unsigned char internal[EC_PUBLIC_KEY_LEN] = {0x02}; + unsigned char output[EC_PUBLIC_KEY_LEN]; + memcpy(internal + 1, control + 1, EC_XONLY_PUBLIC_KEY_LEN); + return wally_ec_public_key_bip341_tweak(internal, sizeof(internal), node, + sizeof(node), 0, output, + sizeof(output)) == WALLY_OK && + memcmp(output + 1, spk + 2, EC_XONLY_PUBLIC_KEY_LEN) == 0 && + (output[0] == 0x03) == (control[0] & 1); +} + +static const struct wally_map_item *slot_leaf(const struct wally_psbt *psbt, + const musig_slot_t *slot) { + const struct wally_map *leaves = + &psbt->inputs[slot->input_index].taproot_leaf_scripts; + return slot->has_leaf_hash && slot->leaf_item < leaves->num_items + ? &leaves->items[slot->leaf_item] + : NULL; +} + +/* The key aggregation a slot signs with, checked against what it spends: for + * the key path, with the taproot tweak, the spent output key; for a leaf, the + * key its script pushes. */ +static bool slot_key_agg(const struct wally_psbt *psbt, + const musig_slot_t *slot, const unsigned char *spk, + struct wally_musig_keyagg_cache **cache_out) { + const struct wally_psbt_input *input = &psbt->inputs[slot->input_index]; + unsigned char aggregate[EC_PUBLIC_KEY_LEN], key[EC_PUBLIC_KEY_LEN]; + struct wally_musig_keyagg_cache *cache = NULL; + if (!musig_key_agg(slot->entry, slot->key_index, slot->multi_index, + slot->child_num, &cache, aggregate)) + return false; + const struct wally_map_item *leaf = slot_leaf(psbt, slot); + bool ok = + slot->has_leaf_hash + ? leaf && + wally_musig_pubkey_get(cache, key, sizeof(key)) == WALLY_OK && + script_template_pushes_key(leaf->value, leaf->value_len, + key + 1, EC_XONLY_PUBLIC_KEY_LEN) + : apply_taproot_tweak(input, cache, key) && + memcmp(key + 1, spk + 2, EC_XONLY_PUBLIC_KEY_LEN) == 0; + if (!ok) { + wally_musig_keyagg_cache_free(cache); + return false; + } + *cache_out = cache; + return true; +} + +/* The nonce cache key expression index of the key at `key_index`: the number + * of key expressions before it holding a key of fingerprint `fp`, a musig() + * counting once. libwally numbers keys in order of appearance, which is the + * draft's order: the internal key, then the leaves left to right. */ +static uint32_t key_expression_index(const struct wally_descriptor *desc, + uint32_t key_index, + const unsigned char *fp) { + uint32_t index = 0; + for (uint32_t i = 0; i < key_index; i++) + index += descriptor_key_holds_fingerprint(desc, i, fp); + return index; +} + +/* Our participant `ref` of a musig(): its key at the slot's position, and the + * path we derive its private key from, which must give that key. */ +static bool own_participant(const registry_entry_t *entry, + descriptor_key_ref_t ref, musig_slot_t *slot) { + uint32_t steps[MAX_KEYPATH_TOTAL_DEPTH]; + size_t steps_len = 0; + if (!participant_key(entry->desc, ref, slot->multi_index, slot->child_num, + slot->participant, steps, &steps_len)) + return false; + char *origin = descriptor_key_origin_path_alloc(entry->desc, ref); + bool ok = origin && bip32_path_parse(origin, slot->path, &slot->path_len, + MAX_KEYPATH_TOTAL_DEPTH); + wally_free_string(origin); + if (!ok || slot->path_len + steps_len > MAX_KEYPATH_TOTAL_DEPTH) + return false; + memcpy(slot->path + slot->path_len, steps, steps_len * sizeof(steps[0])); + slot->path_len += steps_len; + + struct ext_key *derived = NULL; + ok = key_get_derived_key_components(slot->path, slot->path_len, &derived) && + memcmp(derived->pub_key, slot->participant, EC_PUBLIC_KEY_LEN) == 0; + bip32_key_free(derived); + return ok; +} + +static bool append_slot(musig_plan_t *plan, const musig_slot_t *slot) { + musig_slot_t *slots = + realloc(plan->slots, (plan->num_slots + 1) * sizeof(*slots)); + if (!slots) + return false; + plan->slots = slots; + plan->slots[plan->num_slots++] = *slot; + return true; +} + +/* One slot per participant of ours of the slot's musig(). */ +static musig_psbt_result_t add_own_participants(const musig_slot_t *slot, + const unsigned char *our_fp, + musig_plan_t *plan) { + const struct wally_descriptor *desc = slot->entry->desc; + size_t participants = + descriptor_key_musig_participants(desc, slot->key_index); + for (size_t p = 0; p < participants; p++) { + descriptor_key_ref_t ref = {.index = slot->key_index, .participant = p}; + unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; + if (!descriptor_key_origin_fingerprint(desc, ref, fp) || + memcmp(fp, our_fp, sizeof(fp)) != 0) + continue; + musig_slot_t own = *slot; + /* A fingerprint collision is not ours */ + if (own_participant(slot->entry, ref, &own) && !append_slot(plan, &own)) + return MUSIG_PSBT_ERR_INTERNAL; + } + return MUSIG_PSBT_OK; +} + +/* The leaves of the input pushing the musig()'s key: every TAP_LEAF_SCRIPT is + * proven against the spent output, so a leaf is the registered descriptor's. */ +static musig_psbt_result_t +add_leaf_slots(const struct wally_psbt_input *input, musig_slot_t *slot, + const struct wally_musig_keyagg_cache *cache, + const unsigned char *spk, const unsigned char *our_fp, + musig_plan_t *plan) { + unsigned char key[EC_PUBLIC_KEY_LEN]; + if (wally_musig_pubkey_get(cache, key, sizeof(key)) != WALLY_OK) + return MUSIG_PSBT_ERR_INTERNAL; + memcpy(slot->aggregate, key, EC_PUBLIC_KEY_LEN); + slot->has_leaf_hash = true; + musig_psbt_result_t result = MUSIG_PSBT_OK; + for (size_t j = 0; + result == MUSIG_PSBT_OK && j < input->taproot_leaf_scripts.num_items; + j++) { + const struct wally_map_item *leaf = &input->taproot_leaf_scripts.items[j]; + if (!leaf_in_output(leaf, spk, slot->leaf_hash) || + !script_template_pushes_key(leaf->value, leaf->value_len, key + 1, + EC_XONLY_PUBLIC_KEY_LEN)) + continue; + slot->leaf_item = j; + result = add_own_participants(slot, our_fp, plan); + } + return result; +} + +/* The slots of one musig() key of a claimed input, when the input carries the + * aggregate's PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS, which is how a PSBT asks for + * it: the key path for the tr() internal key (key index 0), every leaf pushing + * its key otherwise. */ +static musig_psbt_result_t +add_key_slots(const struct wally_psbt *psbt, size_t input_index, + const claim_t *claim, uint32_t key_index, + const unsigned char *spk, const unsigned char *our_fp, + musig_plan_t *plan) { + const registry_entry_t *entry = claim->registry.entry; + const struct wally_psbt_input *input = &psbt->inputs[input_index]; + musig_slot_t slot = { + .input_index = input_index, + .entry = entry, + .key_index = key_index, + .multi_index = claim->registry.multi_index, + .child_num = claim->registry.child_num, + .key_expression_index = + key_expression_index(entry->desc, key_index, our_fp), + }; + unsigned char aggregate[EC_PUBLIC_KEY_LEN]; + struct wally_musig_keyagg_cache *cache = NULL; + if (!musig_key_agg(entry, key_index, slot.multi_index, slot.child_num, &cache, + aggregate)) + return MUSIG_PSBT_ERR_INVALID; + + musig_psbt_result_t result = MUSIG_PSBT_OK; + size_t asked = 0; + if (key_index == 0) { + struct wally_musig_keyagg_cache *tweaked = NULL; + if (!slot_key_agg(psbt, &slot, spk, &tweaked) || + wally_musig_pubkey_get(tweaked, slot.aggregate, EC_PUBLIC_KEY_LEN) != + WALLY_OK) + result = MUSIG_PSBT_ERR_INVALID; + wally_musig_keyagg_cache_free(tweaked); + } + if (result == MUSIG_PSBT_OK && + wally_psbt_input_find_musig2_pubkey(input, aggregate, EC_PUBLIC_KEY_LEN, + &asked) == WALLY_OK && + asked) + result = key_index == 0 + ? add_own_participants(&slot, our_fp, plan) + : add_leaf_slots(input, &slot, cache, spk, our_fp, plan); + wally_musig_keyagg_cache_free(cache); + return result; +} + +static musig_psbt_result_t add_input_slots(const struct wally_psbt *psbt, + size_t input_index, + const unsigned char *our_fp, + musig_plan_t *plan) { + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + size_t spk_len = 0; + claim_t claim; + if (!psbt_input_utxo_script(psbt, input_index, spk, sizeof(spk), &spk_len) || + !musig_psbt_claim(&psbt->inputs[input_index].taproot_leaf_paths, spk, + spk_len, &claim)) + return MUSIG_PSBT_OK; + + uint32_t num_keys = 0; + if (wally_descriptor_get_num_keys(claim.registry.entry->desc, &num_keys) != + WALLY_OK) + return MUSIG_PSBT_ERR_INTERNAL; + for (uint32_t k = 0; k < num_keys; k++) { + if (!descriptor_key_is_musig(claim.registry.entry->desc, k)) + continue; + musig_psbt_result_t result = + add_key_slots(psbt, input_index, &claim, k, spk, our_fp, plan); + if (result != MUSIG_PSBT_OK) + return result; + } + return MUSIG_PSBT_OK; +} + +static const unsigned char *slot_leaf_hash(const musig_slot_t *slot) { + return slot->has_leaf_hash ? slot->leaf_hash : NULL; +} + +/* The PSBT_IN_MUSIG2_PUB_NONCE of `participant` for the slot's aggregate and + * leaf, or NULL when the input has none of the right size. */ +static const unsigned char *find_pubnonce(const struct wally_psbt_input *input, + const unsigned char *participant, + const musig_slot_t *slot) { + size_t index = 0; + if (wally_psbt_input_find_musig2_pubnonce( + input, participant, EC_PUBLIC_KEY_LEN, slot->aggregate, + EC_PUBLIC_KEY_LEN, slot_leaf_hash(slot), + slot->has_leaf_hash ? SHA256_LEN : 0, &index) != WALLY_OK || + !index || + input->musig2_pubnonces.items[index - 1].value_len != + WALLY_MUSIG_PUBNONCE_LEN) + return NULL; + return input->musig2_pubnonces.items[index - 1].value; +} + +/* The public nonces of every participant of the slot's musig(), in BIP-390 + * order, into `nonces`, sized for them. False when one is missing. */ +static bool slot_pubnonces(const struct wally_psbt *psbt, + const musig_slot_t *slot, unsigned char *nonces, + size_t *count_out) { + const struct wally_psbt_input *input = &psbt->inputs[slot->input_index]; + size_t n = 0; + unsigned char *keys = participant_keys_alloc( + slot->entry, slot->key_index, slot->multi_index, slot->child_num, &n); + bool ok = keys != NULL; + for (size_t p = 0; ok && p < n; p++) { + const unsigned char *nonce = + find_pubnonce(input, keys + p * EC_PUBLIC_KEY_LEN, slot); + ok = nonce != NULL; + if (ok && nonces) + memcpy(nonces + p * WALLY_MUSIG_PUBNONCE_LEN, nonce, + WALLY_MUSIG_PUBNONCE_LEN); + } + free(keys); + if (ok) + *count_out = n; + return ok; +} + +/* The step of one slot without a nonce cache session. */ +static musig_step_t slot_step(const struct wally_psbt *psbt, + const musig_slot_t *slot) { + size_t count = 0; + if (!find_pubnonce(&psbt->inputs[slot->input_index], slot->participant, slot)) + return MUSIG_STEP_PUB_NONCES; + return slot_pubnonces(psbt, slot, NULL, &count) ? MUSIG_STEP_PARTIAL_SIGS + : MUSIG_STEP_NOTHING; +} + +/* The PSBT_GLOBAL_NONCE_CACHE_SESSION field, if the PSBT carries one. */ +static musig_psbt_result_t session_field(const struct wally_psbt *psbt, + musig_plan_t *plan, bool *found) { + *found = false; + for (size_t i = 0; i < psbt->unknowns.num_items; i++) { + const struct wally_map_item *item = &psbt->unknowns.items[i]; + if (item->key_len == 0 || + item->key[0] != BNC_PSBT_GLOBAL_NONCE_CACHE_SESSION) + continue; + if (bnc_session_field_decode(item->key, item->key_len, item->value, + item->value_len, plan->session_id, + plan->session_ref) != BNC_OK) + return MUSIG_PSBT_ERR_INVALID; + *found = true; + } + return MUSIG_PSBT_OK; +} + +/* The two-round session ID, from the canonical texts of the descriptors the + * slots belong to. */ +static musig_psbt_result_t two_round_session_id(bnc_signer *signer, + musig_plan_t *plan) { + char **texts = calloc(plan->num_slots, sizeof(*texts)); + if (!texts) + return MUSIG_PSBT_ERR_INTERNAL; + bool ok = true; + for (size_t s = 0; ok && s < plan->num_slots; s++) + ok = wally_descriptor_canonicalize(plan->slots[s].entry->desc, + WALLY_MS_CANONICAL_NO_CHECKSUM, + &texts[s]) == WALLY_OK; + ok = ok && + bnc_two_round_session_id(signer, (const char *const *)texts, + plan->num_slots, plan->session_id) == BNC_OK; + for (size_t s = 0; s < plan->num_slots; s++) + wally_free_string(texts[s]); + free(texts); + return ok ? MUSIG_PSBT_OK : MUSIG_PSBT_ERR_INTERNAL; +} + +static musig_psbt_result_t plan_step(const struct wally_psbt *psbt, + musig_plan_t *plan) { + if (plan->num_slots == 0) + return MUSIG_PSBT_OK; + bool cached = false; + musig_psbt_result_t result = session_field(psbt, plan, &cached); + if (result != MUSIG_PSBT_OK) + return result; + if (cached) { + plan->step = MUSIG_STEP_CACHED; + return MUSIG_PSBT_OK; + } + plan->step = MUSIG_STEP_NOTHING; + for (size_t s = 0; s < plan->num_slots; s++) { + musig_step_t step = slot_step(psbt, &plan->slots[s]); + if (step > plan->step) + plan->step = step; + } + bnc_signer *signer = nonce_cache_signer(); + if (!signer) + return MUSIG_PSBT_ERR_INTERNAL; + return two_round_session_id(signer, plan); +} + +musig_psbt_result_t musig_psbt_plan(const struct wally_psbt *psbt, + const bool *signable, + musig_plan_t *plan_out) { + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; + if (!psbt || !plan_out) + return MUSIG_PSBT_ERR_INTERNAL; + memset(plan_out, 0, sizeof(*plan_out)); + if (!key_get_fingerprint(our_fp)) + return MUSIG_PSBT_ERR_INTERNAL; + + musig_psbt_result_t result = MUSIG_PSBT_OK; + for (size_t i = 0; result == MUSIG_PSBT_OK && i < psbt->num_inputs; i++) { + if (!signable || signable[i]) + result = add_input_slots(psbt, i, our_fp, plan_out); + } + if (result == MUSIG_PSBT_OK) + result = plan_step(psbt, plan_out); + if (result != MUSIG_PSBT_OK) + musig_plan_free(plan_out); + return result; +} + +void musig_plan_free(musig_plan_t *plan) { + if (!plan) + return; + free(plan->slots); + memset(plan, 0, sizeof(*plan)); +} + +/* Our participant's private key of the slot, wiped by bip32_key_free(). */ +static bool slot_key(const musig_slot_t *slot, struct ext_key **key_out) { + return key_get_derived_key_components(slot->path, slot->path_len, key_out); +} + +static musig_psbt_result_t cached_nonce(bnc_signer *signer, + const bnc_secret *secret, + const musig_slot_t *slot, + unsigned char *pubnonce_out) { + struct ext_key *key = NULL; + if (!slot_key(slot, &key)) + return MUSIG_PSBT_ERR_INTERNAL; + int32_t status = bnc_cached_nonce( + signer, secret, (uint32_t)slot->input_index, slot->key_expression_index, + key->priv_key + 1, slot->participant, pubnonce_out); + bip32_key_free(key); + return status == BNC_OK ? MUSIG_PSBT_OK : MUSIG_PSBT_ERR_INTERNAL; +} + +/* The slots a step signs: every one from a cached session, those with every + * participant's public nonce in round 2. */ +static bool step_signs_slot(const struct wally_psbt *psbt, + const musig_plan_t *plan, + const musig_slot_t *slot) { + return plan->step == MUSIG_STEP_CACHED || + (plan->step == MUSIG_STEP_PARTIAL_SIGS && + slot_step(psbt, slot) == MUSIG_STEP_PARTIAL_SIGS); +} + +static bool own_pubnonce(const struct wally_psbt *psbt, + const musig_slot_t *slot, unsigned char *pubnonce) { + const unsigned char *nonce = + find_pubnonce(&psbt->inputs[slot->input_index], slot->participant, slot); + if (nonce) + memcpy(pubnonce, nonce, WALLY_MUSIG_PUBNONCE_LEN); + return nonce != NULL; +} + +/* The secret the plan's step signs from: taken for signing, or only read. */ +static musig_psbt_result_t plan_secret(bnc_signer *signer, + const musig_plan_t *plan, bool take, + bnc_secret **secret_out) { + int32_t status; + if (plan->step == MUSIG_STEP_CACHED) + status = take ? bnc_begin_signing(signer, plan->session_id, + plan->session_ref, secret_out) + : bnc_held_session(signer, plan->session_id, + plan->session_ref, secret_out); + else + status = take + ? bnc_begin_round_two(signer, plan->session_id, secret_out) + : bnc_held_session(signer, plan->session_id, NULL, secret_out); + switch (status) { + case BNC_OK: + return MUSIG_PSBT_OK; + case BNC_ERR_UNKNOWN_SESSION: + case BNC_ERR_SESSION_REF_MISMATCH: + return MUSIG_PSBT_ERR_SESSION; + default: + return MUSIG_PSBT_ERR_INTERNAL; + } +} + +/* A slot the step signs needs our nonce to be the one the session gives, then + * every participant's nonce. */ +static musig_psbt_result_t check_slot_nonce(const struct wally_psbt *psbt, + bnc_signer *signer, + const bnc_secret *secret, + const musig_slot_t *slot) { + unsigned char expected[BNC_PUBNONCE_LEN], carried[BNC_PUBNONCE_LEN]; + size_t count = 0; + musig_psbt_result_t result = cached_nonce(signer, secret, slot, expected); + if (result != MUSIG_PSBT_OK) + return result; + if (!own_pubnonce(psbt, slot, carried) || + memcmp(expected, carried, sizeof(expected)) != 0) + return MUSIG_PSBT_ERR_SESSION; + if (!slot_pubnonces(psbt, slot, NULL, &count)) + return MUSIG_PSBT_ERR_INVALID; + return MUSIG_PSBT_OK; +} + +/* True when a slot of the plan is keyed by `item` of input `input_index`'s + * PSBT_IN_MUSIG2_PUB_NONCE map: its participant, aggregate and leaf. */ +static bool plan_keys_pubnonce(const musig_plan_t *plan, size_t input_index, + const struct wally_map_item *item) { + for (size_t s = 0; s < plan->num_slots; s++) { + const musig_slot_t *slot = &plan->slots[s]; + size_t key_len = + 2 * EC_PUBLIC_KEY_LEN + (slot->has_leaf_hash ? SHA256_LEN : 0); + if (slot->input_index == input_index && item->key_len == key_len && + memcmp(item->key, slot->participant, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(item->key + EC_PUBLIC_KEY_LEN, slot->aggregate, + EC_PUBLIC_KEY_LEN) == 0 && + (!slot->has_leaf_hash || memcmp(item->key + 2 * EC_PUBLIC_KEY_LEN, + slot->leaf_hash, SHA256_LEN) == 0)) + return true; + } + return false; +} + +/* True when `participant` is the participant key of a slot of the plan. */ +static bool plan_has_participant(const musig_plan_t *plan, + const unsigned char *participant) { + for (size_t s = 0; s < plan->num_slots; s++) { + if (memcmp(plan->slots[s].participant, participant, EC_PUBLIC_KEY_LEN) == 0) + return true; + } + return false; +} + +/* A cached session prepared the nonces of the plan's slots only: a nonce of + * one of our participant keys keyed by no slot is not one it gave. */ +static musig_psbt_result_t check_unplanned_nonces(const struct wally_psbt *psbt, + const musig_plan_t *plan) { + for (size_t i = 0; i < psbt->num_inputs; i++) { + const struct wally_map *nonces = &psbt->inputs[i].musig2_pubnonces; + for (size_t j = 0; j < nonces->num_items; j++) { + const struct wally_map_item *item = &nonces->items[j]; + if (item->key_len >= EC_PUBLIC_KEY_LEN && + plan_has_participant(plan, item->key) && + !plan_keys_pubnonce(plan, i, item)) + return MUSIG_PSBT_ERR_SESSION; + } + } + return MUSIG_PSBT_OK; +} + +musig_psbt_result_t musig_psbt_check_session(struct wally_psbt *psbt, + const musig_plan_t *plan) { + if (!psbt || !plan) + return MUSIG_PSBT_ERR_INTERNAL; + if (plan->step != MUSIG_STEP_CACHED && plan->step != MUSIG_STEP_PARTIAL_SIGS) + return MUSIG_PSBT_OK; + bnc_signer *signer = nonce_cache_signer(); + bnc_secret *secret = NULL; + if (!signer) + return MUSIG_PSBT_ERR_INTERNAL; + musig_psbt_result_t result = plan_secret(signer, plan, false, &secret); + if (result == MUSIG_PSBT_OK && plan->step == MUSIG_STEP_CACHED) + result = check_unplanned_nonces(psbt, plan); + for (size_t s = 0; result == MUSIG_PSBT_OK && s < plan->num_slots; s++) { + if (step_signs_slot(psbt, plan, &plan->slots[s])) + result = check_slot_nonce(psbt, signer, secret, &plan->slots[s]); + } + bnc_secret_free(secret); + return result; +} + +static musig_psbt_result_t round_one(struct wally_psbt *psbt, + const musig_plan_t *plan, + size_t *added_out) { + bnc_signer *signer = nonce_cache_signer(); + uint8_t fresh[BNC_SECRET_LEN]; + bnc_secret *secret = NULL; + if (!signer || !nonce_cache_fresh_secret(fresh)) + return MUSIG_PSBT_ERR_INTERNAL; + int32_t status = + bnc_begin_round_one(signer, plan->session_id, fresh, &secret); + wally_bzero(fresh, sizeof(fresh)); + if (status != BNC_OK) + return MUSIG_PSBT_ERR_INTERNAL; + + musig_psbt_result_t result = MUSIG_PSBT_OK; + for (size_t s = 0; result == MUSIG_PSBT_OK && s < plan->num_slots; s++) { + const musig_slot_t *slot = &plan->slots[s]; + unsigned char pubnonce[BNC_PUBNONCE_LEN]; + result = cached_nonce(signer, secret, slot, pubnonce); + if (result == MUSIG_PSBT_OK && + wally_psbt_input_add_musig2_pubnonce( + &psbt->inputs[slot->input_index], slot->participant, + EC_PUBLIC_KEY_LEN, slot->aggregate, EC_PUBLIC_KEY_LEN, + slot_leaf_hash(slot), slot->has_leaf_hash ? SHA256_LEN : 0, + pubnonce, sizeof(pubnonce)) != WALLY_OK) + result = MUSIG_PSBT_ERR_INTERNAL; + } + bnc_secret_free(secret); + *added_out = result == MUSIG_PSBT_OK ? plan->num_slots : 0; + return result; +} + +/* BIP-342 sighash of a leaf: libwally's PSBT signature hash covers the key + * path only. Every input's spent script and amount enter it. */ +static musig_psbt_result_t leaf_sighash(const struct wally_psbt *psbt, + const struct wally_tx *tx, + const musig_slot_t *slot, + uint32_t sighash_type, + unsigned char *sighash) { + const struct wally_map_item *leaf = slot_leaf(psbt, slot); + uint64_t *values = calloc(psbt->num_inputs, sizeof(*values)); + struct wally_map scripts = {0}; + bool ok = leaf && values && + wally_map_init(psbt->num_inputs, NULL, &scripts) == WALLY_OK; + for (size_t i = 0; ok && i < psbt->num_inputs; i++) { + unsigned char spk[PSBT_MAX_INNER_SCRIPT_LEN]; + size_t spk_len = 0; + ok = psbt_input_utxo_script(psbt, i, spk, sizeof(spk), &spk_len) && + wally_map_add_integer(&scripts, (uint32_t)i, spk, spk_len) == WALLY_OK; + values[i] = psbt_get_input_value(psbt, i); + } + ok = ok && wally_tx_get_btc_taproot_signature_hash( + tx, slot->input_index, &scripts, values, psbt->num_inputs, + leaf->value, leaf->value_len, TAPSCRIPT_KEY_VERSION, + WALLY_NO_CODESEPARATOR, NULL, 0, sighash_type, 0, sighash, + SHA256_LEN) == WALLY_OK; + wally_map_clear(&scripts); + free(values); + return ok ? MUSIG_PSBT_OK : MUSIG_PSBT_ERR_INVALID; +} + +/* BIP-341 sighash the slot signs, of the input's PSBT_IN_SIGHASH_TYPE: BIP-327 + * signs any message and BIP-373 sets no rule, the aggregator appends the type + * byte. Kern's review allows only ALL and DEFAULT, as for every signature. */ +static musig_psbt_result_t slot_sighash(struct wally_psbt *psbt, + const struct wally_tx *tx, + const musig_slot_t *slot, + unsigned char *sighash) { + uint32_t sighash_type = psbt->inputs[slot->input_index].sighash; + if (!psbt_sighash_is_supported(sighash_type)) + return MUSIG_PSBT_ERR_INVALID; + if (slot->has_leaf_hash) + return leaf_sighash(psbt, tx, slot, + sighash_type ? sighash_type : WALLY_SIGHASH_DEFAULT, + sighash); + return wally_psbt_get_input_signature_hash(psbt, slot->input_index, tx, NULL, + 0, 0, sighash, + SHA256_LEN) == WALLY_OK + ? MUSIG_PSBT_OK + : MUSIG_PSBT_ERR_INVALID; +} + +/* The BIP-327 session context of a slot: its tweaked key aggregation, and + * the session of every participant's nonce and the sighash. */ +static musig_psbt_result_t slot_context(struct wally_psbt *psbt, + const struct wally_tx *tx, + const musig_slot_t *slot, + struct wally_musig_keyagg_cache **cache, + struct wally_musig_session **session) { + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + unsigned char sighash[SHA256_LEN]; + size_t spk_len = 0, count = 0; + size_t n = + descriptor_key_musig_participants(slot->entry->desc, slot->key_index); + unsigned char *nonces = malloc(n * WALLY_MUSIG_PUBNONCE_LEN); + struct wally_musig_aggnonce *aggnonce = NULL; + musig_psbt_result_t result = slot_sighash(psbt, tx, slot, sighash); + if (!nonces) + result = MUSIG_PSBT_ERR_INTERNAL; + if (result == MUSIG_PSBT_OK && + (!psbt_input_utxo_script(psbt, slot->input_index, spk, sizeof(spk), + &spk_len) || + !slot_key_agg(psbt, slot, spk, cache) || + !slot_pubnonces(psbt, slot, nonces, &count))) + result = MUSIG_PSBT_ERR_INVALID; + if (result == MUSIG_PSBT_OK && + (wally_musig_nonce_agg(nonces, count * WALLY_MUSIG_PUBNONCE_LEN, count, + &aggnonce) != WALLY_OK || + wally_musig_nonce_process(aggnonce, sighash, sizeof(sighash), *cache, + NULL, 0, session) != WALLY_OK)) + result = MUSIG_PSBT_ERR_INVALID; + wally_musig_aggnonce_free(aggnonce); + free(nonces); + return result; +} + +static musig_psbt_result_t +sign_slot(struct wally_psbt *psbt, const struct wally_tx *tx, + bnc_signer *signer, const bnc_secret *secret, + const musig_slot_t *slot, unsigned char *partial_sig) { + struct wally_musig_keyagg_cache *cache = NULL; + struct wally_musig_session *session = NULL; + struct ext_key *key = NULL; + bnc_musig_slot bnc_slot = { + .input_index = (uint32_t)slot->input_index, + .key_expression_index = slot->key_expression_index, + }; + memcpy(bnc_slot.participant, slot->participant, BNC_PUBLIC_KEY_LEN); + musig_psbt_result_t result = + own_pubnonce(psbt, slot, bnc_slot.pubnonce) + ? slot_context(psbt, tx, slot, &cache, &session) + : MUSIG_PSBT_ERR_SESSION; + if (result == MUSIG_PSBT_OK && !slot_key(slot, &key)) + result = MUSIG_PSBT_ERR_INTERNAL; + if (result == MUSIG_PSBT_OK) { + nonce_cache_sign_context_t context = {.keyagg_cache = cache, + .session = session}; + int32_t status = bnc_sign_musig(signer, secret, &bnc_slot, + key->priv_key + 1, &context, partial_sig); + if (status == BNC_ERR_PUBNONCE_MISMATCH) + result = MUSIG_PSBT_ERR_SESSION; + else if (status != BNC_OK) + result = MUSIG_PSBT_ERR_INTERNAL; + } + bip32_key_free(key); + wally_musig_session_free(session); + wally_musig_keyagg_cache_free(cache); + return result; +} + +/* Signs every slot the step asks with the session taken, deleted durably + * before this returns, and writes the partial signatures once all are made. */ +static musig_psbt_result_t sign_slots(struct wally_psbt *psbt, + const musig_plan_t *plan, + size_t *added_out) { + bnc_signer *signer = nonce_cache_signer(); + if (!signer) + return MUSIG_PSBT_ERR_INTERNAL; + bool *signs = calloc(plan->num_slots, sizeof(*signs)); + unsigned char *partial_sigs = + calloc(plan->num_slots, WALLY_MUSIG_PARTIAL_SIG_LEN); + struct wally_tx *tx = psbt_tx_alloc(psbt); + bnc_secret *secret = NULL; + musig_psbt_result_t result = + signs && partial_sigs && tx ? MUSIG_PSBT_OK : MUSIG_PSBT_ERR_INTERNAL; + for (size_t s = 0; result == MUSIG_PSBT_OK && s < plan->num_slots; s++) + signs[s] = step_signs_slot(psbt, plan, &plan->slots[s]); + if (result == MUSIG_PSBT_OK) + result = plan_secret(signer, plan, true, &secret); + for (size_t s = 0; result == MUSIG_PSBT_OK && s < plan->num_slots; s++) { + if (signs[s]) + result = sign_slot(psbt, tx, signer, secret, &plan->slots[s], + partial_sigs + s * WALLY_MUSIG_PARTIAL_SIG_LEN); + } + bnc_secret_free(secret); + + size_t added = 0; + for (size_t s = 0; result == MUSIG_PSBT_OK && s < plan->num_slots; s++) { + const musig_slot_t *slot = &plan->slots[s]; + if (!signs[s]) + continue; + if (wally_psbt_input_add_musig2_partial_sig( + &psbt->inputs[slot->input_index], slot->participant, + EC_PUBLIC_KEY_LEN, slot->aggregate, EC_PUBLIC_KEY_LEN, + slot_leaf_hash(slot), slot->has_leaf_hash ? SHA256_LEN : 0, + partial_sigs + s * WALLY_MUSIG_PARTIAL_SIG_LEN, + WALLY_MUSIG_PARTIAL_SIG_LEN) != WALLY_OK) + result = MUSIG_PSBT_ERR_INTERNAL; + added++; + } + wally_tx_free(tx); + free(partial_sigs); + free(signs); + *added_out = result == MUSIG_PSBT_OK ? added : 0; + return result; +} + +musig_psbt_result_t musig_psbt_sign(struct wally_psbt *psbt, + const musig_plan_t *plan, + size_t *added_out) { + if (!psbt || !plan || !added_out) + return MUSIG_PSBT_ERR_INTERNAL; + *added_out = 0; + switch (plan->step) { + case MUSIG_STEP_NONE: + case MUSIG_STEP_NOTHING: + return MUSIG_PSBT_OK; + case MUSIG_STEP_PUB_NONCES: + return round_one(psbt, plan, added_out); + case MUSIG_STEP_PARTIAL_SIGS: + case MUSIG_STEP_CACHED: + return sign_slots(psbt, plan, added_out); + } + return MUSIG_PSBT_ERR_INTERNAL; +} + +/* True when an input of ours is to sign outside MuSig2. */ +static bool signs_other_inputs(const struct wally_psbt *psbt, bool is_testnet) { + for (size_t i = 0; i < psbt->num_inputs; i++) { + input_ownership_t owner = psbt_classify_input(psbt, i, is_testnet); + if (owner.ownership != PSBT_OWNERSHIP_EXTERNAL && + owner.claim.kind != CLAIM_MUSIG) + return true; + } + return false; +} + +musig_psbt_result_t musig_psbt_check_request(const uint8_t *psbt_bytes, + size_t psbt_len, bool is_testnet) { + struct wally_psbt *psbt = NULL; + if (!psbt_parse_payload(psbt_bytes, psbt_len, &psbt)) + return MUSIG_PSBT_OK; + musig_plan_t plan; + musig_psbt_result_t result = musig_psbt_plan(psbt, NULL, &plan); + if (result == MUSIG_PSBT_OK) + result = musig_psbt_check_session(psbt, &plan); + if (result == MUSIG_PSBT_OK && plan.step == MUSIG_STEP_NOTHING && + !signs_other_inputs(psbt, is_testnet)) + result = MUSIG_PSBT_ERR_NOTHING; + musig_plan_free(&plan); + wally_psbt_free(psbt); + return result; +} + +/* True when our participant `ref` is the key at `path`. */ +static bool participant_at_path(const struct wally_descriptor *desc, + descriptor_key_ref_t ref, const uint32_t *path, + size_t path_len) { + uint32_t origin[MAX_KEYPATH_TOTAL_DEPTH]; + size_t origin_len = 0; + char *origin_str = descriptor_key_origin_path_alloc(desc, ref); + bool ok = origin_str && bip32_path_parse(origin_str, origin, &origin_len, + MAX_KEYPATH_TOTAL_DEPTH); + wally_free_string(origin_str); + if (!ok || path_len < origin_len || + memcmp(path, origin, origin_len * sizeof(origin[0])) != 0) + return false; + + uint32_t num_paths = 0; + if (wally_descriptor_get_num_paths(desc, &num_paths) != WALLY_OK) + return false; + /* The step before the child number is a child number too: the position in + * the tuple is the one whose steps `path` ends with. */ + uint32_t child_num = path_len >= origin_len + 2 ? path[path_len - 1] : 0; + for (uint32_t k = 0; k < num_paths; k++) { + unsigned char key[EC_PUBLIC_KEY_LEN]; + uint32_t steps[MAX_KEYPATH_TOTAL_DEPTH]; + size_t steps_len = 0; + if (participant_key(desc, ref, k, child_num, key, steps, &steps_len) && + origin_len + steps_len == path_len && + memcmp(path + origin_len, steps, steps_len * sizeof(steps[0])) == 0) + return true; + } + return false; +} + +bool musig_psbt_is_participant_path(const struct wally_descriptor *desc, + const uint32_t *path, size_t path_len) { + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; + uint32_t num_keys = 0; + if (!desc || !path || !key_get_fingerprint(our_fp) || + wally_descriptor_get_num_keys(desc, &num_keys) != WALLY_OK) + return false; + for (uint32_t k = 0; k < num_keys; k++) { + size_t participants = descriptor_key_musig_participants(desc, k); + for (size_t p = 0; p < participants; p++) { + descriptor_key_ref_t ref = {.index = k, .participant = p}; + unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; + if (descriptor_key_origin_fingerprint(desc, ref, fp) && + memcmp(fp, our_fp, sizeof(fp)) == 0 && + participant_at_path(desc, ref, path, path_len)) + return true; + } + } + return false; +} + +bool musig_psbt_is_own_participant(const struct wally_psbt *psbt, + size_t input_index, + const unsigned char *participant) { + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; + musig_plan_t plan = {0}; + if (!psbt || !participant || input_index >= psbt->num_inputs || + !key_get_fingerprint(our_fp) || + add_input_slots(psbt, input_index, our_fp, &plan) != MUSIG_PSBT_OK) { + musig_plan_free(&plan); + return false; + } + bool own = false; + for (size_t s = 0; !own && s < plan.num_slots; s++) + own = + memcmp(plan.slots[s].participant, participant, EC_PUBLIC_KEY_LEN) == 0; + musig_plan_free(&plan); + return own; +} diff --git a/main/core/musig_psbt.h b/main/core/musig_psbt.h new file mode 100644 index 00000000..90438fa6 --- /dev/null +++ b/main/core/musig_psbt.h @@ -0,0 +1,127 @@ +#ifndef MUSIG_PSBT_H +#define MUSIG_PSBT_H + +#include "../utils/attributes.h" +#include +#include +#include + +#include "psbt.h" + +/* Claims a taproot script for the registered descriptor with a musig() key + * holding one of our participant keys that generates it. The multipath index + * and child number are the last two steps of one of the PSBT_*_TAP_BIP32_ + * DERIVATION origins in `tap_paths`: the aggregate key's when the musig() is + * followed by a path (aggregate then derive), a participant's when its + * participants are (derive then aggregate). The descriptor, not the PSBT, + * decides that the script is ours. */ +KERN_WARN_UNUSED_RESULT bool musig_psbt_claim(const struct wally_map *tap_paths, + const unsigned char *spk, + size_t spk_len, + claim_t *claim_out); + +/* One of our MuSig2 signatures (ENCODING.md, Signing, MuSig2): an input and the + * BIP-373 key `participant | aggregate [| leaf_hash]`, the participant being + * our key. The tr() internal musig() signs the key path, a leaf musig() the + * leaf script it is pushed in (musig_leaves.h). */ +typedef struct { + size_t input_index; + const registry_entry_t *entry; + uint32_t key_index; + uint32_t multi_index; + uint32_t child_num; + /* the nonce cache key expression index of the musig() */ + uint32_t key_expression_index; + unsigned char participant[BNC_PUBLIC_KEY_LEN]; + /* the aggregate of its BIP-373 key, as Bitcoin Core and Ledger key it: the + * Taproot output key on the key path, the key the leaf pushes on a leaf, + * never the KeyAgg key of PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS */ + unsigned char aggregate[BNC_PUBLIC_KEY_LEN]; + uint32_t path[MAX_KEYPATH_TOTAL_DEPTH]; + size_t path_len; + bool has_leaf_hash; + unsigned char leaf_hash[BNC_HASH_LEN]; + /* the input's TAP_LEAF_SCRIPT entry of the leaf, when it has one */ + size_t leaf_item; +} musig_slot_t; + +/* What the PSBT asks of our MuSig2 signatures, in increasing precedence. */ +typedef enum { + /* no MuSig2 signature of ours */ + MUSIG_STEP_NONE, + /* our public nonces are in, another participant's is missing */ + MUSIG_STEP_NOTHING, + /* round 2: the partial signature of each one with every participant's + * public nonce */ + MUSIG_STEP_PARTIAL_SIGS, + /* round 1: the public nonce of each one, and no signature of any kind */ + MUSIG_STEP_PUB_NONCES, + /* PSBT_GLOBAL_NONCE_CACHE_SESSION: the partial signature of each one in one + * round, from the cached session */ + MUSIG_STEP_CACHED, +} musig_step_t; + +typedef struct { + musig_step_t step; + musig_slot_t *slots; + size_t num_slots; + /* CACHED: the session the PSBT names; otherwise the two-round session the + * signer derives from the descriptors of the slots */ + uint8_t session_id[BNC_SESSION_ID_LEN]; + uint8_t session_ref[BNC_SESSION_REF_LEN]; +} musig_plan_t; + +typedef enum { + MUSIG_PSBT_OK, + /* a session missing, consumed or mismatched: ERROR 0x0D */ + MUSIG_PSBT_ERR_SESSION, + /* MuSig2 data the signer cannot sign with */ + MUSIG_PSBT_ERR_INVALID, + /* our public nonces are in and nothing else of ours is to sign: waiting for + * another participant's nonce */ + MUSIG_PSBT_ERR_NOTHING, + MUSIG_PSBT_ERR_INTERNAL, +} musig_psbt_result_t; + +/* Our MuSig2 signatures, on the inputs `signable` clears (every input when + * NULL), and the step the PSBT asks. Free with musig_plan_free(). */ +KERN_WARN_UNUSED_RESULT musig_psbt_result_t +musig_psbt_plan(const struct wally_psbt *psbt, const bool *signable, + musig_plan_t *plan_out); + +void musig_plan_free(musig_plan_t *plan); + +/* Checks, without taking it, that the session the plan signs from is held and + * gives the public nonces the PSBT carries: run before asking the user. */ +KERN_WARN_UNUSED_RESULT musig_psbt_result_t +musig_psbt_check_session(struct wally_psbt *psbt, const musig_plan_t *plan); + +/* Runs the plan's step: round 1 stores a new session then sets our + * PSBT_IN_MUSIG2_PUB_NONCE on every slot; round 2 and CACHED take the session, + * deleted durably before any signature is written, then set our + * PSBT_IN_MUSIG2_PARTIAL_SIG on every slot they sign, all or none. Writes the + * number of entries set to *added_out. */ +KERN_WARN_UNUSED_RESULT musig_psbt_result_t musig_psbt_sign( + struct wally_psbt *psbt, const musig_plan_t *plan, size_t *added_out); + +/* Checks a PSBT to sign before the user is asked: the session its MuSig2 + * signatures need is held and gives the nonces it carries, and it asks + * something of us. A PSBT that does not parse is left to the review. */ +KERN_WARN_UNUSED_RESULT musig_psbt_result_t musig_psbt_check_request( + const uint8_t *psbt_bytes, size_t psbt_len, bool is_testnet); + +/* True when `path` derives one of our participant keys of a musig() of `desc`: + * the participant's own path, followed by the steps its key expression adds + * when it has any, at the multipath index and child number `path` ends + * with. */ +KERN_WARN_UNUSED_RESULT bool +musig_psbt_is_participant_path(const struct wally_descriptor *desc, + const uint32_t *path, size_t path_len); + +/* True when `participant` is the participant key of one of our MuSig2 + * signatures on input `input_index`. */ +KERN_WARN_UNUSED_RESULT bool +musig_psbt_is_own_participant(const struct wally_psbt *psbt, size_t input_index, + const unsigned char *participant); + +#endif // MUSIG_PSBT_H diff --git a/main/core/nonce_cache.c b/main/core/nonce_cache.c new file mode 100644 index 00000000..34794c37 --- /dev/null +++ b/main/core/nonce_cache.c @@ -0,0 +1,349 @@ +#include "nonce_cache.h" + +#include "../utils/secure_mem.h" +#include "crypto_utils.h" +#include "key.h" +#include +#include +#include +#include +#include +#include + +static const char *TAG = "nonce_cache"; + +#define NVS_NAMESPACE "noncecache" +#define NVS_KEY_SESSIONS "sessions" +#define SEQUENCE_LEN 8 +/* A stored session: its ID, creation order (little endian) and secret. */ +#define STORED_SESSION_LEN (BNC_SESSION_ID_LEN + SEQUENCE_LEN + BNC_SECRET_LEN) + +typedef struct { + uint8_t session_id[BNC_SESSION_ID_LEN]; + bnc_record record; +} stored_session_t; + +/* The NVS blob, loaded for one store callback and wiped when it returns, so a + * session secret is in RAM only while the binding uses it. */ +typedef struct { + stored_session_t sessions[NONCE_CACHE_MAX_SESSIONS]; + size_t len; +} session_table_t; + +static nvs_handle_t sessions_nvs; +static bool sessions_nvs_open; +static bnc_signer *signer; + +/* SHA-256 cannot fail on a valid context, and the binding's backend has no + * way to report it: a failure here is a broken device, never a hash to use. */ +static void sha256_cb(void *ctx, const bnc_bytes *parts, size_t parts_len, + uint8_t *out) { + (void)ctx; + psa_hash_operation_t op = PSA_HASH_OPERATION_INIT; + size_t out_len = 0; + bool ok = psa_crypto_init() == PSA_SUCCESS && + psa_hash_setup(&op, PSA_ALG_SHA_256) == PSA_SUCCESS; + for (size_t i = 0; ok && i < parts_len; i++) + ok = psa_hash_update(&op, parts[i].ptr, parts[i].len) == PSA_SUCCESS; + ok = ok && psa_hash_finish(&op, out, 32, &out_len) == PSA_SUCCESS && + out_len == 32; + psa_hash_abort(&op); + if (!ok) { + ESP_LOGE(TAG, "SHA-256 failed"); + abort(); + } +} + +static int32_t nonce_gen_cb(void *ctx, const uint8_t *rand, + const uint8_t *secret_key, + const uint8_t *public_key, void **secnonce_out, + uint8_t *pubnonce_out) { + (void)ctx; + struct wally_musig_secnonce *secnonce = NULL; + struct wally_musig_pubnonce *pubnonce = NULL; + int ret = wally_musig_nonce_gen( + rand, BNC_HASH_LEN, secret_key, BNC_SECRET_KEY_LEN, public_key, + BNC_PUBLIC_KEY_LEN, NULL, NULL, 0, NULL, 0, &secnonce, &pubnonce); + if (ret == WALLY_OK) + ret = wally_musig_pubnonce_serialize(pubnonce, pubnonce_out, + BNC_PUBNONCE_LEN); + wally_musig_pubnonce_free(pubnonce); + if (ret != WALLY_OK) { + wally_musig_secnonce_free(secnonce); + return -1; + } + *secnonce_out = secnonce; + return 0; +} + +static int32_t partial_sign_cb(void *ctx, void *secnonce, + const uint8_t *secret_key, const void *context, + uint8_t *partial_sig_out) { + (void)ctx; + const nonce_cache_sign_context_t *sign_context = context; + struct wally_musig_partial_sig *partial_sig = NULL; + int ret = wally_musig_partial_sign(secnonce, secret_key, BNC_SECRET_KEY_LEN, + sign_context->keyagg_cache, + sign_context->session, &partial_sig); + if (ret == WALLY_OK) + ret = wally_musig_partial_sig_serialize(partial_sig, partial_sig_out, + BNC_PARTIAL_SIG_LEN); + wally_musig_partial_sig_free(partial_sig); + return ret == WALLY_OK ? 0 : -1; +} + +static void secnonce_free_cb(void *ctx, void *secnonce) { + (void)ctx; + wally_musig_secnonce_free(secnonce); +} + +static void table_wipe(session_table_t *table) { + secure_memzero(table, sizeof(*table)); +} + +static bool table_load(session_table_t *table) { + uint8_t blob[NONCE_CACHE_MAX_SESSIONS * STORED_SESSION_LEN]; + size_t blob_len = sizeof(blob); + memset(table, 0, sizeof(*table)); + esp_err_t err = nvs_get_blob(sessions_nvs, NVS_KEY_SESSIONS, blob, &blob_len); + if (err == ESP_ERR_NVS_NOT_FOUND) + return true; + if (err != ESP_OK || blob_len % STORED_SESSION_LEN != 0) { + ESP_LOGE(TAG, "Session store unreadable (%d)", err); + secure_memzero(blob, sizeof(blob)); + return false; + } + table->len = blob_len / STORED_SESSION_LEN; + for (size_t i = 0; i < table->len; i++) { + const uint8_t *stored = blob + i * STORED_SESSION_LEN; + stored_session_t *session = &table->sessions[i]; + memcpy(session->session_id, stored, BNC_SESSION_ID_LEN); + for (size_t b = 0; b < SEQUENCE_LEN; b++) + session->record.sequence |= (uint64_t)stored[BNC_SESSION_ID_LEN + b] + << (8 * b); + memcpy(session->record.secret, stored + BNC_SESSION_ID_LEN + SEQUENCE_LEN, + BNC_SECRET_LEN); + } + secure_memzero(blob, sizeof(blob)); + return true; +} + +/* Written, not committed: the binding's flush commits. */ +static bool table_save(const session_table_t *table) { + if (table->len == 0) { + esp_err_t err = nvs_erase_key(sessions_nvs, NVS_KEY_SESSIONS); + return err == ESP_OK || err == ESP_ERR_NVS_NOT_FOUND; + } + uint8_t blob[NONCE_CACHE_MAX_SESSIONS * STORED_SESSION_LEN]; + for (size_t i = 0; i < table->len; i++) { + uint8_t *stored = blob + i * STORED_SESSION_LEN; + const stored_session_t *session = &table->sessions[i]; + memcpy(stored, session->session_id, BNC_SESSION_ID_LEN); + for (size_t b = 0; b < SEQUENCE_LEN; b++) + stored[BNC_SESSION_ID_LEN + b] = + (uint8_t)(session->record.sequence >> (8 * b)); + memcpy(stored + BNC_SESSION_ID_LEN + SEQUENCE_LEN, session->record.secret, + BNC_SECRET_LEN); + } + esp_err_t err = nvs_set_blob(sessions_nvs, NVS_KEY_SESSIONS, blob, + table->len * STORED_SESSION_LEN); + secure_memzero(blob, sizeof(blob)); + return err == ESP_OK; +} + +/* The position of the session held under `session_id`, or table->len. */ +static size_t table_find(const session_table_t *table, + const uint8_t *session_id) { + for (size_t i = 0; i < table->len; i++) { + if (memcmp(table->sessions[i].session_id, session_id, BNC_SESSION_ID_LEN) == + 0) + return i; + } + return table->len; +} + +static int32_t store_get(void *ctx, const uint8_t *session_id, + bnc_record *record_out, bool *found_out) { + (void)ctx; + session_table_t table; + if (!table_load(&table)) + return -1; + size_t i = table_find(&table, session_id); + *found_out = i < table.len; + if (*found_out) + *record_out = table.sessions[i].record; + table_wipe(&table); + return 0; +} + +static int32_t store_put(void *ctx, const uint8_t *session_id, + const bnc_record *record) { + (void)ctx; + session_table_t table; + if (!table_load(&table)) + return -1; + size_t i = table_find(&table, session_id); + bool ok = i < NONCE_CACHE_MAX_SESSIONS; + if (ok) { + memcpy(table.sessions[i].session_id, session_id, BNC_SESSION_ID_LEN); + table.sessions[i].record = *record; + if (i == table.len) + table.len++; + ok = table_save(&table); + } + table_wipe(&table); + return ok ? 0 : -1; +} + +static int32_t store_remove(void *ctx, const uint8_t *session_id) { + (void)ctx; + session_table_t table; + if (!table_load(&table)) + return -1; + size_t i = table_find(&table, session_id); + bool ok = true; + if (i < table.len) { + memmove(&table.sessions[i], &table.sessions[i + 1], + (table.len - i - 1) * sizeof(table.sessions[0])); + table.len--; + ok = table_save(&table); + } + table_wipe(&table); + return ok ? 0 : -1; +} + +static int32_t store_len(void *ctx, size_t *len_out) { + (void)ctx; + session_table_t table; + if (!table_load(&table)) + return -1; + *len_out = table.len; + table_wipe(&table); + return 0; +} + +static int32_t store_at(void *ctx, size_t index, uint8_t *session_id_out, + bnc_record *record_out) { + (void)ctx; + session_table_t table; + if (!table_load(&table)) + return -1; + bool ok = index < table.len; + if (ok) { + memcpy(session_id_out, table.sessions[index].session_id, + BNC_SESSION_ID_LEN); + *record_out = table.sessions[index].record; + } + table_wipe(&table); + return ok ? 0 : -1; +} + +static int32_t store_flush(void *ctx) { + (void)ctx; + return nvs_commit(sessions_nvs) == ESP_OK ? 0 : -1; +} + +/* One handle for the signer and the erase, so both see the same store. */ +static bool open_sessions_nvs(void) { + if (!sessions_nvs_open) + sessions_nvs_open = + nvs_open(NVS_NAMESPACE, NVS_READWRITE, &sessions_nvs) == ESP_OK; + if (!sessions_nvs_open) + ESP_LOGE(TAG, "Failed to open the session store"); + return sessions_nvs_open; +} + +bnc_signer *nonce_cache_signer(void) { + if (signer) + return signer; + if (!open_sessions_nvs()) + return NULL; + const bnc_crypto crypto = { + .ctx = NULL, + .sha256 = sha256_cb, + .nonce_gen = nonce_gen_cb, + .partial_sign = partial_sign_cb, + .secnonce_free = secnonce_free_cb, + }; + const bnc_store store = { + .ctx = NULL, + .capacity = NONCE_CACHE_MAX_SESSIONS, + .get = store_get, + .put = store_put, + .remove = store_remove, + .len = store_len, + .at = store_at, + .flush = store_flush, + }; + if (bnc_signer_new(&crypto, &store, &signer) != BNC_OK) + signer = NULL; + return signer; +} + +bool nonce_cache_erase(void) { + return open_sessions_nvs() && nvs_erase_all(sessions_nvs) == ESP_OK && + nvs_commit(sessions_nvs) == ESP_OK; +} + +bool nonce_cache_fresh_secret(uint8_t *secret_out) { + return crypto_random_bytes(secret_out, BNC_SECRET_LEN) == CRYPTO_OK; +} + +/* A drawn session ID must name a new session, so its reference is answered. */ +#define SESSION_ID_DRAWS 8 + +static bool draw_session_id(bnc_signer *signer, uint8_t *session_id) { + for (int i = 0; i < SESSION_ID_DRAWS; i++) { + bnc_secret *held = NULL; + if (crypto_random_bytes(session_id, BNC_SESSION_ID_LEN) != CRYPTO_OK) + return false; + int32_t status = bnc_held_session(signer, session_id, NULL, &held); + bnc_secret_free(held); + if (status == BNC_ERR_UNKNOWN_SESSION) + return true; + if (status != BNC_OK) + return false; + } + return false; +} + +static nonce_cache_result_t issue_result(int32_t status) { + switch (status) { + case BNC_OK: + return NONCE_CACHE_OK; + case BNC_ERR_UNKNOWN_SESSION: + case BNC_ERR_SESSION_REF_MISMATCH: + return NONCE_CACHE_ERR_SESSION; + case BNC_ERR_INVALID_BOOL: + case BNC_ERR_BUFFER_LENGTH: + case BNC_ERR_NO_INPUTS: + case BNC_ERR_INVALID_RANGE: + return NONCE_CACHE_ERR_INVALID; + default: + return NONCE_CACHE_ERR_INTERNAL; + } +} + +nonce_cache_result_t nonce_cache_issue(bnc_issuance *request, bool draw_session, + const uint32_t *path, size_t path_len, + uint8_t *nonces_out, size_t nonces_len, + nonce_cache_issued_t *issued_out) { + bnc_signer *signer = nonce_cache_signer(); + if (!signer || + (draw_session && !draw_session_id(signer, request->session_id))) + return NONCE_CACHE_ERR_INTERNAL; + struct ext_key *key = NULL; + if (!path || path_len == 0 || + !key_get_derived_key_components(path, path_len, &key)) + return NONCE_CACHE_ERR_INVALID; + uint8_t fresh[BNC_SECRET_LEN]; + int32_t status = BNC_ERR_CRYPTO; + if (nonce_cache_fresh_secret(fresh)) + status = bnc_issue(signer, request, fresh, key->priv_key + 1, key->pub_key, + issued_out->session_ref, &issued_out->new_session, + nonces_out, nonces_len); + secure_memzero(fresh, sizeof(fresh)); + bip32_key_free(key); + memcpy(issued_out->session_id, request->session_id, BNC_SESSION_ID_LEN); + return issue_result(status); +} diff --git a/main/core/nonce_cache.h b/main/core/nonce_cache.h new file mode 100644 index 00000000..2476dd06 --- /dev/null +++ b/main/core/nonce_cache.h @@ -0,0 +1,63 @@ +#ifndef NONCE_CACHE_H +#define NONCE_CACHE_H + +#include "../utils/attributes.h" +#include +#include +#include +#include +#include + +/* Sessions of the nonce cache BIP draft (bip_nonces_cache, BIP-DRAFT.md): the + * signer of the bip_nonces_cache C binding on libwally's MuSig2 and + * mbedTLS SHA-256, with its sessions in NVS. + * + * A session is a random secret: storing one more than NONCE_CACHE_MAX_SESSIONS + * evicts the oldest. Secret nonces are never stored: the binding recomputes + * them from the session secret when it signs. */ +#define NONCE_CACHE_MAX_SESSIONS 16 + +/* The BIP-327 session context of one MuSig2 signature, handed as is to + * bnc_sign_musig: the key aggregation with its tweaks, and the session of the + * aggregate nonce and message. */ +typedef struct { + const struct wally_musig_keyagg_cache *keyagg_cache; + const struct wally_musig_session *session; +} nonce_cache_sign_context_t; + +/* The process-wide signer, set up on first use. NULL when NVS cannot be + * opened. */ +KERN_WARN_UNUSED_RESULT bnc_signer *nonce_cache_signer(void); + +/* A new session secret from the RNG, never derived from the seed. */ +KERN_WARN_UNUSED_RESULT bool nonce_cache_fresh_secret(uint8_t *secret_out); + +/* Deletes every session, durably: a device wipe leaves none behind. */ +KERN_WARN_UNUSED_RESULT bool nonce_cache_erase(void); + +typedef enum { + NONCE_CACHE_OK, + /* the reference names no session held under the ID, or another one */ + NONCE_CACHE_ERR_SESSION, + NONCE_CACHE_ERR_INVALID, + NONCE_CACHE_ERR_INTERNAL, +} nonce_cache_result_t; + +typedef struct { + uint8_t session_id[BNC_SESSION_ID_LEN]; + uint8_t session_ref[BNC_SESSION_REF_LEN]; + /* the session was created for this request */ + bool new_session; +} nonce_cache_issued_t; + +/* Issuance (Nonce Preparation): the public nonces of the key at `path` from + * the session `request` names, created when it holds none and carries no + * reference, durable before this returns. With `draw_session`, the session + * ID is drawn from the RNG among the IDs no session holds. `nonces_out` takes + * (end - start + 1) * inputs nonces, by key expression index then input. */ +KERN_WARN_UNUSED_RESULT nonce_cache_result_t +nonce_cache_issue(bnc_issuance *request, bool draw_session, + const uint32_t *path, size_t path_len, uint8_t *nonces_out, + size_t nonces_len, nonce_cache_issued_t *issued_out); + +#endif // NONCE_CACHE_H diff --git a/main/core/pin.c b/main/core/pin.c index 41b051c7..97f2ad3d 100644 --- a/main/core/pin.c +++ b/main/core/pin.c @@ -3,6 +3,7 @@ #include "pin.h" #include "../utils/secure_mem.h" #include "crypto_utils.h" +#include "nonce_cache.h" #include "pin_attempt.h" #include "settings.h" #include "storage.h" @@ -442,6 +443,10 @@ void pin_wipe_all(void) { if (err != ESP_OK) ESP_LOGE(TAG, "Settings reset failed: %s", esp_err_to_name(err)); + // MuSig2 nonce cache sessions + if (!nonce_cache_erase()) + ESP_LOGE(TAG, "Nonce cache erase failed"); + // Wipe flash storage. storage_wipe_flash() erases the partition directly, so // a failed mount does not stop it - log and go on rather than skipping it. err = storage_init(); diff --git a/main/core/psbt.c b/main/core/psbt.c index b275af88..93988652 100644 --- a/main/core/psbt.c +++ b/main/core/psbt.c @@ -2,8 +2,10 @@ #include "bip32_path.h" #include "kern_wally.h" #include "key.h" +#include "musig_psbt.h" #include "psbt_internal.h" #include "script_templates.h" +#include "sp_psbt.h" #include "wallet.h" #include #include @@ -599,12 +601,26 @@ input_ownership_t psbt_classify_input(const struct wally_psbt *psbt, size_t i, bool is_testnet) { input_ownership_t result = {0}; + if (sp_psbt_input_is_ours(psbt, i, is_testnet)) { + result.ownership = PSBT_OWNERSHIP_OWNED_SAFE; + result.claim.kind = CLAIM_SILENT_PAYMENT; + return result; + } + unsigned char utxo_script[34]; size_t utxo_script_len = 0; if (!psbt_input_utxo_script(psbt, i, utxo_script, sizeof(utxo_script), &utxo_script_len)) return result; + /* Before the fingerprint match: a participant key's origin is ours but + * derives no key of the script. */ + if (musig_psbt_claim(&psbt->inputs[i].taproot_leaf_paths, utxo_script, + utxo_script_len, &result.claim)) { + result.ownership = PSBT_OWNERSHIP_OWNED_SAFE; + return result; + } + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; if (!key_get_fingerprint(our_fp)) return result; @@ -691,15 +707,44 @@ static bool output_script(const struct wally_psbt *psbt, size_t i, return *script && *script_len; } +// Whose silent payment output `i` is among our account and those of our spend +// key with a scan key not ours +static sp_output_ownership_t sp_output_ownership(const struct wally_psbt *psbt, + size_t i, bool is_testnet) { + sp_output_ownership_t ownership = + sp_psbt_output_ownership(psbt, i, NULL, is_testnet); + for (size_t pos = 0; ownership == SP_OUTPUT_FOREIGN; pos++) { + const unsigned char *scan_secret = registry_sp_scan_key_get(pos); + if (!scan_secret) + break; + ownership = sp_psbt_output_ownership(psbt, i, scan_secret, is_testnet); + } + return ownership; +} + output_ownership_t psbt_classify_output(const struct wally_psbt *psbt, size_t i, bool is_testnet) { output_ownership_t result = {0}; + sp_output_ownership_t sp_ownership = sp_output_ownership(psbt, i, is_testnet); + if (sp_ownership != SP_OUTPUT_FOREIGN) { + result.ownership = PSBT_OWNERSHIP_OWNED_SAFE; + result.source.kind = CLAIM_SILENT_PAYMENT; + result.source.silent_payment.is_change = sp_ownership == SP_OUTPUT_CHANGE; + return result; + } + const unsigned char *out_script = NULL; size_t out_script_len = 0; if (!output_script(psbt, i, &out_script, &out_script_len)) return result; + if (musig_psbt_claim(&psbt->outputs[i].taproot_leaf_paths, out_script, + out_script_len, &result.source)) { + result.ownership = PSBT_OWNERSHIP_OWNED_SAFE; + return result; + } + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; if (!key_get_fingerprint(our_fp)) return result; @@ -745,8 +790,10 @@ output_ownership_t psbt_classify_output(const struct wally_psbt *psbt, size_t i, bool psbt_claims_share_policy(const claim_t *a, const claim_t *b) { if (!a || !b || a->kind != b->kind) return false; - if (a->kind == CLAIM_REGISTRY) + if (a->kind == CLAIM_REGISTRY || a->kind == CLAIM_MUSIG) return a->registry.entry && a->registry.entry == b->registry.entry; + if (a->kind == CLAIM_SILENT_PAYMENT) + return true; return a->whitelist.purpose == b->whitelist.purpose && a->whitelist.coin == b->whitelist.coin && a->whitelist.account == b->whitelist.account; @@ -844,10 +891,18 @@ bool psbt_format_keypath(const unsigned char *raw_keypath, MAX_KEYPATH_TOTAL_DEPTH); } +/* PSBT_IN_MUSIG2_PUB_NONCE and PSBT_IN_MUSIG2_PARTIAL_SIG entries of input + * `i`. */ +static size_t input_musig_count(const struct wally_psbt *psbt, size_t i) { + return psbt->inputs[i].musig2_pubnonces.num_items + + psbt->inputs[i].musig2_partial_sigs.num_items; +} + /* Every place libwally can park a signature for one input: the ECDSA map, the - * taproot key-path field, and the taproot script-path leaf map. Counted before - * and after each signing call so `signed_ok` reflects signatures that actually - * landed, not calls that merely returned WALLY_OK. */ + * taproot key-path field, the taproot script-path leaf map, and the MuSig2 + * public nonce and partial signature maps. Counted before and after each + * signing call so `signed_ok` reflects signatures that actually landed, not + * calls that merely returned WALLY_OK. */ static bool tap_key_sig_present(const struct wally_psbt *psbt, size_t i) { size_t n = 0; return wally_psbt_get_input_taproot_signature_len(psbt, i, &n) == WALLY_OK && @@ -863,6 +918,7 @@ static size_t input_signature_count(const struct wally_psbt *psbt, size_t i) { if (tap_key_sig_present(psbt, i)) count++; count += psbt->inputs[i].taproot_leaf_signatures.num_items; + count += input_musig_count(psbt, i); return count; } @@ -879,9 +935,10 @@ static size_t input_signature_count(const struct wally_psbt *psbt, size_t i) { * after. */ typedef struct { input_ownership_t owner; - bool denied; /* policy refused this input */ - bool tracked; /* a snapshot was taken (denied and it names some key) */ - bool attempted; /* policy cleared it and a signing key was derived */ + bool denied; /* policy refused this input */ + bool tracked; /* a snapshot was taken (denied and it names some key) */ + bool attempted; /* policy cleared it and a signing key was derived */ + bool sighash_set; /* set_sighash_all gave it SIGHASH_ALL for the pass */ /* Signature count before the pass began. One wally_psbt_sign() call signs * every input naming the key it was given, so an input can already be * signed by the time its own turn comes round -- two inputs on one address @@ -889,6 +946,8 @@ typedef struct { * "already signed by us" from "never signed". */ size_t sig_baseline; bool had_tap_key_sig; + /* input_musig_count before the pass */ + size_t musig_baseline; size_t sig_count; struct wally_map signatures; struct wally_map leaf_signatures; @@ -898,6 +957,22 @@ typedef struct { size_t num_signing_pubkeys; } input_plan_t; +/* BIP375: beside silent payment outputs an input naming no sighash type is + * signed with SIGHASH_ALL, not taproot's SIGHASH_DEFAULT. Only the inputs we + * sign get the field, for the signing pass only: psbt_sign removes it after, + * but from inputs given a MuSig2 nonce or partial signature. */ +static bool set_sighash_all(struct wally_psbt *psbt, input_plan_t *plan, + size_t num_inputs) { + for (size_t i = 0; i < num_inputs; i++) { + if (plan[i].denied || psbt->inputs[i].sighash) + continue; + if (wally_psbt_set_input_sighash(psbt, i, WALLY_SIGHASH_ALL) != WALLY_OK) + return false; + plan[i].sighash_set = true; + } + return true; +} + /* Safe on an untouched plan, and safe twice, so every exit can run it over * the whole array without tracking how far the classify loop got. */ static void release_input_state(input_plan_t *plan) { @@ -996,9 +1071,13 @@ static size_t input_signing_paths(const input_ownership_t *own, return count; } - add_signing_path(paths, &count, own->claim.derived_path, - own->claim.derived_path_len); - if (own->claim.kind != CLAIM_REGISTRY || !own->claim.registry.entry) + /* A CLAIM_MUSIG names no key of its own: its participant keys are signed + * by musig_psbt.c, and only the descriptor's other own keys here. */ + if (own->claim.kind != CLAIM_MUSIG) + add_signing_path(paths, &count, own->claim.derived_path, + own->claim.derived_path_len); + if ((own->claim.kind != CLAIM_REGISTRY && own->claim.kind != CLAIM_MUSIG) || + !own->claim.registry.entry) return count; const registry_entry_t *e = own->claim.registry.entry; for (size_t k = 0; k < e->num_own_keys; k++) { @@ -1154,53 +1233,31 @@ static void drop_unverified_key_path_sigs(struct wally_psbt *psbt, } } -size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, - psbt_sign_policy_t policy, psbt_sign_result_t *result) { - if (result) - memset(result, 0, sizeof(*result)); - - if (!psbt) { - ESP_LOGE(TAG, "Invalid PSBT"); - return 0; - } - - size_t num_inputs = 0; - if (wally_psbt_get_num_inputs(psbt, &num_inputs) != WALLY_OK || !num_inputs) { - ESP_LOGE(TAG, "Failed to get number of inputs"); - return 0; - } - - input_plan_t *plan = calloc(num_inputs, sizeof(*plan)); - if (!plan) { - ESP_LOGE(TAG, "Out of memory classifying %zu inputs", num_inputs); - return 0; - } - - size_t signatures_added = 0; - - /* Classify everything up front, then freeze the inputs we will not sign. - * Bailing on a snapshot failure rather than signing unprotected. */ - bool signable_any = false; - for (size_t i = 0; i < num_inputs; i++) { - plan[i].owner = psbt_classify_input(psbt, i, is_testnet); - if (input_is_signable(psbt, i, plan[i].owner.ownership, policy)) { - signable_any = true; - plan[i].sig_baseline = input_signature_count(psbt, i); - plan[i].had_tap_key_sig = tap_key_sig_present(psbt, i); +/* A path derives exactly one key, so two PSBT_IN_TAP_BIP32_DERIVATION entries + * naming it under our fingerprint name two different keys for one private + * key. Signing either would be picking for an attacker, so such an input + * refuses the whole PSBT before anything is signed. */ +static bool input_lists_path_twice(const struct wally_psbt *psbt, size_t i, + const unsigned char *our_fp) { + const struct wally_map *paths = &psbt->inputs[i].taproot_leaf_paths; + for (size_t j = 0; j < paths->num_items; j++) { + const struct wally_map_item *item = &paths->items[j]; + if (!keypath_matches_fingerprint(item->value, item->value_len, our_fp)) continue; - } - plan[i].denied = true; - if (!capture_input_state(psbt, i, &plan[i])) { - ESP_LOGE(TAG, "Failed to snapshot denied input %zu; refusing to sign", i); - goto cleanup; - } + for (size_t k = j + 1; k < paths->num_items; k++) + if (paths->items[k].value_len == item->value_len && + memcmp(paths->items[k].value, item->value, item->value_len) == 0) + return true; } + return false; +} - if (!signable_any) - goto cleanup; - - /* Cache shared sighash midstates so per-input signing is O(n), not O(n^2). */ - wally_psbt_signing_cache_enable(psbt, 0); +/* Signs every input the policy cleared: a silent payment input with its + * tweaked key (sp_psbt.c), any other with each key input_signing_paths gives + * it. */ +static size_t sign_owned_inputs(struct wally_psbt *psbt, bool is_testnet, + input_plan_t *plan, size_t num_inputs) { + size_t signatures_added = 0; for (size_t i = 0; i < num_inputs; i++) { input_ownership_t ownership = plan[i].owner; @@ -1208,9 +1265,20 @@ size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, if (plan[i].denied) continue; + if (ownership.claim.kind == CLAIM_SILENT_PAYMENT) { + plan[i].attempted = true; + if (sp_psbt_sign_input(psbt, i, is_testnet)) + signatures_added++; + else + ESP_LOGE(TAG, "Failed to sign silent payment input %zu", i); + continue; + } + signing_path_t paths[REGISTRY_MAX_OWN_KEYS]; size_t num_paths = input_signing_paths(&ownership, paths); - if (!num_paths) + /* A musig() key of ours is signed by musig_psbt.c, so a MuSig2 input may + * hold no other key of ours. */ + if (!num_paths && ownership.claim.kind != CLAIM_MUSIG) ESP_LOGE(TAG, "Invalid signing path for input %zu", i); struct ext_key *keys[REGISTRY_MAX_OWN_KEYS] = {0}; @@ -1256,6 +1324,126 @@ size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, bip32_key_free(keys[p]); } + return signatures_added; +} + +/* BIP-370 signer rules: a signature under ALL, the only sighash signed, pins + * the input and output sets. libwally's signer clears both tx-modifiable flags + * for each signature it stores, but a MuSig2 partial signature is stored + * beside it, so they are cleared here. */ +static void pin_after_partial_sigs(struct wally_psbt *psbt) { + size_t version = 0, flags = 0; + if (wally_psbt_get_version(psbt, &version) != WALLY_OK || + version != WALLY_PSBT_VERSION_2 || + wally_psbt_get_tx_modifiable_flags(psbt, &flags) != WALLY_OK) + return; + uint32_t pinned = (uint32_t)flags & ~(uint32_t)(WALLY_PSBT_TXMOD_INPUTS | + WALLY_PSBT_TXMOD_OUTPUTS); + if (pinned != (uint32_t)flags && + wally_psbt_set_tx_modifiable_flags(psbt, pinned) != WALLY_OK) + ESP_LOGW(TAG, "Failed to clear tx-modifiable flags after signing"); +} + +/* Our MuSig2 signatures on the inputs the policy cleared (musig_psbt.c). */ +static bool plan_musig(const struct wally_psbt *psbt, const input_plan_t *plan, + size_t num_inputs, musig_plan_t *musig) { + bool *signable = calloc(num_inputs, sizeof(*signable)); + if (!signable) + return false; + for (size_t i = 0; i < num_inputs; i++) + signable[i] = !plan[i].denied; + bool ok = musig_psbt_plan(psbt, signable, musig) == MUSIG_PSBT_OK; + free(signable); + return ok; +} + +static size_t sign_musig_inputs(struct wally_psbt *psbt, input_plan_t *plan, + const musig_plan_t *musig) { + size_t added = 0; + for (size_t s = 0; s < musig->num_slots; s++) + plan[musig->slots[s].input_index].attempted = true; + if (musig_psbt_sign(psbt, musig, &added) != MUSIG_PSBT_OK) + ESP_LOGE(TAG, "MuSig2 signing failed"); + return added; +} + +size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, + psbt_sign_policy_t policy, psbt_sign_result_t *result) { + if (result) + memset(result, 0, sizeof(*result)); + + if (!psbt) { + ESP_LOGE(TAG, "Invalid PSBT"); + return 0; + } + + size_t num_inputs = 0; + if (wally_psbt_get_num_inputs(psbt, &num_inputs) != WALLY_OK || !num_inputs) { + ESP_LOGE(TAG, "Failed to get number of inputs"); + return 0; + } + + input_plan_t *plan = calloc(num_inputs, sizeof(*plan)); + if (!plan) { + ESP_LOGE(TAG, "Out of memory classifying %zu inputs", num_inputs); + return 0; + } + + size_t signatures_added = 0; + musig_plan_t musig = {0}; + + unsigned char our_fp[BIP32_KEY_FINGERPRINT_LEN]; + if (!key_get_fingerprint(our_fp)) { + ESP_LOGE(TAG, "No key loaded"); + goto cleanup; + } + + /* Classify everything up front, then freeze the inputs we will not sign. + * Bailing on a snapshot failure rather than signing unprotected. */ + bool signable_any = false; + for (size_t i = 0; i < num_inputs; i++) { + plan[i].owner = psbt_classify_input(psbt, i, is_testnet); + if (input_is_signable(psbt, i, plan[i].owner.ownership, policy)) { + /* Rejected here rather than in the signing loop, so a refusal hands + * the PSBT back with nothing signed. */ + if (input_lists_path_twice(psbt, i, our_fp)) { + ESP_LOGE(TAG, "Input %zu names two keys on one derivation path", i); + goto cleanup; + } + signable_any = true; + plan[i].sig_baseline = input_signature_count(psbt, i); + plan[i].had_tap_key_sig = tap_key_sig_present(psbt, i); + plan[i].musig_baseline = input_musig_count(psbt, i); + continue; + } + plan[i].denied = true; + if (!capture_input_state(psbt, i, &plan[i])) { + ESP_LOGE(TAG, "Failed to snapshot denied input %zu; refusing to sign", i); + goto cleanup; + } + } + + if (!signable_any) + goto cleanup; + + if (sp_psbt_has_outputs(psbt) && !set_sighash_all(psbt, plan, num_inputs)) + goto cleanup; + + if (!plan_musig(psbt, plan, num_inputs, &musig)) { + ESP_LOGE(TAG, "Invalid MuSig2 inputs; refusing to sign"); + goto cleanup; + } + + /* Cache shared sighash midstates so per-input signing is O(n), not O(n^2). */ + wally_psbt_signing_cache_enable(psbt, 0); + + /* Round 1 of MuSig2 answers with public nonces and no signature of any + * kind. */ + if (musig.step != MUSIG_STEP_PUB_NONCES) + signatures_added = sign_owned_inputs(psbt, is_testnet, plan, num_inputs); + size_t musig_added = sign_musig_inputs(psbt, plan, &musig); + signatures_added += musig_added; + drop_unverified_key_path_sigs(psbt, plan, num_inputs, result); wally_psbt_signing_cache_disable(psbt); @@ -1279,9 +1467,20 @@ size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, } } + /* A public nonce commits to nothing in the transaction */ + if (musig_added && musig.step != MUSIG_STEP_PUB_NONCES) + pin_after_partial_sigs(psbt); + cleanup: - for (size_t i = 0; i < num_inputs; i++) + musig_plan_free(&musig); + for (size_t i = 0; i < num_inputs; i++) { + /* A full signature carries its SIGHASH_ALL byte; a MuSig2 nonce or + * partial signature does not, so the aggregator needs the field. */ + if (plan[i].sighash_set && + input_musig_count(psbt, i) == plan[i].musig_baseline) + wally_psbt_set_input_sighash(psbt, i, 0); release_input_state(&plan[i]); + } free(plan); return signatures_added; @@ -1324,5 +1523,9 @@ struct wally_psbt *psbt_trim(const struct wally_psbt *psbt) { wally_map_clear(&out->unknowns); } + if (!sp_psbt_copy_fields(psbt, trimmed)) { + wally_psbt_free(trimmed); + return NULL; + } return trimmed; } diff --git a/main/core/psbt.h b/main/core/psbt.h index d3ba5bd8..93b1aa30 100644 --- a/main/core/psbt.h +++ b/main/core/psbt.h @@ -13,13 +13,35 @@ /* Parse a serialized PSBT, requiring the parse to consume the whole payload so * a valid prefix followed by trailing bytes is rejected rather than silently * truncated. Trailing whitespace is container padding, not payload: a PSBT - * ends on its 0x00 separator, so it is trimmed before the strict parse. */ + * ends on its 0x00 separator, so it is trimmed before the strict parse. + * A BIP375 PSBT whose silent payment outputs still lack their scripts parses + * loosely; sp_psbt_complete derives them and runs the strict checks again. + * A PSBT with silent payment outputs and an input PSBT_IN_SIGHASH_TYPE other + * than SIGHASH_ALL, an explicit 0 included, is refused (BIP375). */ KERN_WARN_UNUSED_RESULT bool psbt_parse_payload(const uint8_t *data, size_t len, struct wally_psbt **psbt_out); +typedef enum { + PSBT_PARSE_OK, + PSBT_PARSE_INVALID, + /* silent payment outputs beside a PSBT_IN_SIGHASH_TYPE other than + * SIGHASH_ALL */ + PSBT_PARSE_SP_SIGHASH, +} psbt_parse_result_t; + +/* psbt_parse_payload, telling why a PSBT is refused. */ +KERN_WARN_UNUSED_RESULT psbt_parse_result_t psbt_parse_payload_result( + const uint8_t *data, size_t len, struct wally_psbt **psbt_out); + typedef enum { CLAIM_WHITELIST, CLAIM_REGISTRY, + /* our silent payment input, or our silent payment change or self-transfer + * output */ + CLAIM_SILENT_PAYMENT, + /* a registered descriptor whose musig() key holds one of our participant + * keys; the entry, multipath index and child number are in `registry` */ + CLAIM_MUSIG, } claim_kind_t; typedef struct { @@ -38,6 +60,9 @@ typedef struct { uint32_t multi_index; uint32_t child_num; } registry; + struct { + bool is_change; + } silent_payment; }; uint32_t derived_path[MAX_KEYPATH_TOTAL_DEPTH]; size_t derived_path_len; @@ -79,8 +104,9 @@ input_ownership_t psbt_classify_input(const struct wally_psbt *psbt, size_t i, output_ownership_t psbt_classify_output(const struct wally_psbt *psbt, size_t i, bool is_testnet); -// True when two claims name the same wallet: one registered descriptor, or one -// single-sig purpose, coin and account. Chain and index may differ. +// True when two claims name the same wallet: one registered descriptor, its +// musig() keys included, the silent payment account, or one single-sig +// purpose, coin and account. Chain and index may differ. KERN_WARN_UNUSED_RESULT bool psbt_claims_share_policy(const claim_t *a, const claim_t *b); @@ -292,6 +318,9 @@ typedef struct { // `psbt_sign_policy_t`. Callers must still check `partial_signing` upstream // (it gates whether to proceed at all when external inputs exist), since // that's a UX decision rather than a per-input one. +// MuSig2 inputs follow ENCODING.md's MuSig2 rules (musig_psbt.h): in round 1 +// only our public nonces are added, and no signature of any kind. Our MuSig2 +// public nonces and partial signatures count as signatures added. // `result` may be NULL. Returns number of signatures added (0 if none). KERN_WARN_UNUSED_RESULT size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, diff --git a/main/core/psbt_parse.c b/main/core/psbt_parse.c index 760ab614..345c2f32 100644 --- a/main/core/psbt_parse.c +++ b/main/core/psbt_parse.c @@ -1,19 +1,50 @@ #include "psbt.h" +#include "sp_psbt.h" #include "kern_wally.h" #include -bool psbt_parse_payload(const uint8_t *data, size_t len, - struct wally_psbt **psbt_out) { - if (!data || !psbt_out) +// A BIP375 PSBT leaves silent payment output scripts to the signer +static bool parse_pending_outputs(const uint8_t *data, size_t len, + struct wally_psbt **psbt_out) { + if (kern_psbt_from_bytes(data, len, + WALLY_PSBT_PARSE_FLAG_LOOSE | + WALLY_PSBT_PARSE_FLAG_COMPLETE, + psbt_out) != WALLY_OK) return false; + if (sp_psbt_outputs_pending(*psbt_out)) + return true; + wally_psbt_free(*psbt_out); + *psbt_out = NULL; + return false; +} + +psbt_parse_result_t psbt_parse_payload_result(const uint8_t *data, size_t len, + struct wally_psbt **psbt_out) { + if (!data || !psbt_out) + return PSBT_PARSE_INVALID; *psbt_out = NULL; while (len > 0 && (data[len - 1] == '\n' || data[len - 1] == '\r' || data[len - 1] == ' ' || data[len - 1] == '\t')) len--; + if (len == 0) + return PSBT_PARSE_INVALID; + + if (kern_psbt_from_bytes(data, len, WALLY_PSBT_PARSE_FLAG_COMPLETE, + psbt_out) != WALLY_OK && + !parse_pending_outputs(data, len, psbt_out)) + return PSBT_PARSE_INVALID; + if (sp_psbt_has_outputs(*psbt_out) && + !sp_psbt_raw_sighash_is_all(data, len, (*psbt_out)->num_inputs)) { + wally_psbt_free(*psbt_out); + *psbt_out = NULL; + return PSBT_PARSE_SP_SIGHASH; + } + return PSBT_PARSE_OK; +} - return len > 0 && - kern_psbt_from_bytes(data, len, WALLY_PSBT_PARSE_FLAG_COMPLETE, - psbt_out) == WALLY_OK; +bool psbt_parse_payload(const uint8_t *data, size_t len, + struct wally_psbt **psbt_out) { + return psbt_parse_payload_result(data, len, psbt_out) == PSBT_PARSE_OK; } diff --git a/main/core/registry.c b/main/core/registry.c index b1e31d7c..177b1156 100644 --- a/main/core/registry.c +++ b/main/core/registry.c @@ -3,11 +3,15 @@ #include "bip138_backup.h" #include "bip32_path.h" #include "descriptor_checksum.h" +#include "descriptor_keys.h" #include "descriptor_validator.h" #include "key.h" +#include "musig_leaves.h" #include "psbt_internal.h" +#include "silent_payments.h" #include "wallet.h" #include +#include #include #include #include @@ -21,6 +25,28 @@ static registry_entry_t registry_entries[REGISTRY_MAX_ENTRIES]; static size_t registry_len = 0; static size_t registry_rejected = 0; +/* Aliases of the loaded seed's silent payment account on the wallet network, + * with the scan key of an account registered with one not ours */ +typedef struct { + char alias[REGISTRY_ID_MAX_LEN]; + bool has_scan_key; + unsigned char scan_key[SP_SECRET_LEN]; +} sp_account_entry_t; +static sp_account_entry_t sp_accounts[REGISTRY_MAX_ENTRIES]; +static size_t sp_alias_len = 0; +/* Scan keys not ours that the current request names with our spend key */ +static unsigned char sp_named_scan_keys[REGISTRY_MAX_ENTRIES][SP_SECRET_LEN]; +static size_t sp_named_scan_key_len = 0; +/* An account is stored as a record, our fingerprint, the network, the scan + * key when not ours and the alias, followed by the seed's approval mark over + * it. An alias is at most 32 bytes, so a record carries a scan key exactly + * when what its header and mark enclose is longer. */ +#define SP_RECORD_HEADER_LEN (BIP32_KEY_FINGERPRINT_LEN + 1) +#define SP_RECORD_ALIAS_MAX_LEN (REGISTRY_ID_MAX_LEN - 1) +#define SP_RECORD_MAX_LEN \ + (SP_RECORD_HEADER_LEN + SP_SECRET_LEN + SP_RECORD_ALIAS_MAX_LEN + \ + BIP138_BACKUP_MARK_LEN) + size_t registry_count(void) { return registry_len; } size_t registry_rejected_count(void) { return registry_rejected; } @@ -77,10 +103,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; @@ -96,6 +119,9 @@ void registry_clear(void) { } memset(registry_entries, 0, sizeof registry_entries); registry_len = 0; + secure_memzero(sp_accounts, sizeof sp_accounts); + sp_alias_len = 0; + registry_sp_clear_named_scan_keys(); } static bool descriptor_id_from_filename(const char *fname, char *id, @@ -128,6 +154,221 @@ 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) || + storage_descriptor_exists(STORAGE_FLASH, file_id, + STORAGE_DESCRIPTOR_SP_ACCOUNT); +} + +static const sp_account_entry_t *sp_account_find(const char *alias) { + for (size_t i = 0; i < sp_alias_len; i++) { + if (strncmp(sp_accounts[i].alias, alias, REGISTRY_ID_MAX_LEN) == 0) + return &sp_accounts[i]; + } + return NULL; +} + +bool registry_sp_alias_exists(const char *alias) { + return sp_account_find(alias) != NULL; +} + +const unsigned char *registry_sp_alias_scan_key(const char *alias) { + const sp_account_entry_t *account = sp_account_find(alias); + return account && account->has_scan_key ? account->scan_key : NULL; +} + +static bool sp_alias_taken(const char *alias) { + return registry_find_by_id(alias) || registry_sp_alias_exists(alias); +} + +/* The record of `account` with its approval mark, its length in *len_out */ +static bool sp_record(const sp_account_entry_t *account, + uint8_t record[SP_RECORD_MAX_LEN], size_t *len_out) { + size_t alias_len = strlen(account->alias); + size_t len = SP_RECORD_HEADER_LEN; + if (alias_len == 0 || alias_len > SP_RECORD_ALIAS_MAX_LEN || + !key_get_fingerprint(record)) + return false; + record[BIP32_KEY_FINGERPRINT_LEN] = (uint8_t)wallet_get_network(); + if (account->has_scan_key) { + memcpy(record + len, account->scan_key, SP_SECRET_LEN); + len += SP_SECRET_LEN; + } + memcpy(record + len, account->alias, alias_len); + len += alias_len; + *len_out = len + BIP138_BACKUP_MARK_LEN; + return bip138_backup_sp_account_mark(record, len, record + len); +} + +/* The account a record stores, before its mark is checked */ +static bool sp_record_account(const uint8_t *record, size_t len, + sp_account_entry_t *account) { + size_t body_len = len > SP_RECORD_HEADER_LEN + BIP138_BACKUP_MARK_LEN + ? len - SP_RECORD_HEADER_LEN - BIP138_BACKUP_MARK_LEN + : 0; + const uint8_t *body = record + SP_RECORD_HEADER_LEN; + memset(account, 0, sizeof(*account)); + account->has_scan_key = body_len > SP_RECORD_ALIAS_MAX_LEN; + if (account->has_scan_key) { + memcpy(account->scan_key, body, SP_SECRET_LEN); + body += SP_SECRET_LEN; + body_len -= SP_SECRET_LEN; + } + if (body_len == 0 || body_len > SP_RECORD_ALIAS_MAX_LEN) + return false; + memcpy(account->alias, body, body_len); + return strlen(account->alias) == body_len; +} + +bool registry_add_sp_alias(const char *alias, const unsigned char *scan_key) { + sp_account_entry_t account = {.has_scan_key = scan_key != NULL}; + uint8_t record[SP_RECORD_MAX_LEN]; + size_t len = 0; + char file_id[REGISTRY_ALIAS_FILE_ID_LEN + 1]; + if (strlen(alias) > SP_RECORD_ALIAS_MAX_LEN) + return false; + strcpy(account.alias, alias); + if (scan_key) + memcpy(account.scan_key, scan_key, SP_SECRET_LEN); + bool ok = sp_alias_len < REGISTRY_MAX_ENTRIES && !sp_alias_taken(alias) && + !registry_name_registered(alias) && alias_file_id(alias, file_id) && + sp_record(&account, record, &len); + if (ok && storage_save_descriptor(STORAGE_FLASH, file_id, record, len, + STORAGE_DESCRIPTOR_SP_ACCOUNT) != ESP_OK) { + ESP_LOGE(TAG, "registering silent payment alias '%s' failed", alias); + ok = false; + } + if (ok) + sp_accounts[sp_alias_len++] = account; + secure_memzero(&account, sizeof(account)); + secure_memzero(record, sizeof(record)); + return ok; +} + +size_t registry_sp_alias_count(void) { return sp_alias_len; } + +const char *registry_sp_alias_get(size_t i) { + return i < sp_alias_len ? sp_accounts[i].alias : NULL; +} + +bool registry_sp_alias_deregister_at(size_t i) { + char file_id[REGISTRY_ALIAS_FILE_ID_LEN + 1]; + char filename[REGISTRY_FILENAME_MAX_LEN]; + if (i >= sp_alias_len || !alias_file_id(sp_accounts[i].alias, file_id)) + return false; + storage_descriptor_filename(STORAGE_FLASH, file_id, + STORAGE_DESCRIPTOR_SP_ACCOUNT, filename, + sizeof(filename)); + if (storage_delete_descriptor(STORAGE_FLASH, filename) != ESP_OK) { + ESP_LOGE(TAG, "De-registering '%s' failed", sp_accounts[i].alias); + return false; + } + memmove(&sp_accounts[i], &sp_accounts[i + 1], + (sp_alias_len - i - 1) * sizeof(sp_accounts[0])); + sp_alias_len--; + secure_memzero(&sp_accounts[sp_alias_len], sizeof(sp_accounts[0])); + return true; +} + +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); + } + for (size_t i = 0; i < sp_alias_len; i++) { + if (strncmp(sp_accounts[i].alias, alias, REGISTRY_ID_MAX_LEN) == 0) + return registry_sp_alias_deregister_at(i); + } + return false; +} + +bool registry_sp_name_scan_key(const unsigned char *scan_key) { + for (size_t i = 0; i < sp_named_scan_key_len; i++) { + if (memcmp(sp_named_scan_keys[i], scan_key, SP_SECRET_LEN) == 0) + return true; + } + if (sp_named_scan_key_len >= REGISTRY_MAX_ENTRIES) + return false; + memcpy(sp_named_scan_keys[sp_named_scan_key_len++], scan_key, SP_SECRET_LEN); + return true; +} + +void registry_sp_clear_named_scan_keys(void) { + secure_memzero(sp_named_scan_keys, sizeof sp_named_scan_keys); + sp_named_scan_key_len = 0; +} + +const unsigned char *registry_sp_scan_key_get(size_t pos) { + for (size_t i = 0; i < sp_alias_len; i++) { + if (!sp_accounts[i].has_scan_key) + continue; + if (pos == 0) + return sp_accounts[i].scan_key; + pos--; + } + return pos < sp_named_scan_key_len ? sp_named_scan_keys[pos] : NULL; +} + +/* Loads the account of a silent payment account record when it is the loaded + * seed's on the wallet network and carries the seed's approval mark */ +static void load_sp_alias(const char *fname) { + uint8_t *data = NULL; + size_t len = 0; + uint8_t expected[SP_RECORD_MAX_LEN]; + size_t expected_len = 0; + sp_account_entry_t account; + if (storage_load_descriptor(STORAGE_FLASH, fname, &data, &len, NULL) != + ESP_OK) + return; + /* Our fingerprint, network and mark rebuild the stored record exactly */ + bool ours = sp_record_account(data, len, &account) && + sp_record(&account, expected, &expected_len) && + expected_len == len && secure_memcmp(expected, data, len) == 0; + secure_memzero(expected, sizeof(expected)); + secure_memzero(data, len); + free(data); + if (!ours) { + secure_memzero(&account, sizeof(account)); + return; + } + if (sp_alias_taken(account.alias) || sp_alias_len >= REGISTRY_MAX_ENTRIES) + ESP_LOGW(TAG, "Skipping '%s': alias '%s' taken or no room", fname, + account.alias); + else + sp_accounts[sp_alias_len++] = account; + secure_memzero(&account, sizeof(account)); +} + +/* 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 +379,13 @@ 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) + storage_descriptor_format_t format = storage_descriptor_format(fname); + if (format == STORAGE_DESCRIPTOR_SP_ACCOUNT) + load_sp_alias(fname); + if (format != STORAGE_DESCRIPTOR_BIP138 || + registry_len >= REGISTRY_MAX_ENTRIES) continue; uint8_t *data = NULL; size_t data_len = 0; @@ -150,35 +395,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 +522,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 +604,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 +651,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++) { @@ -437,6 +729,27 @@ static void collect_own_keys(registry_entry_t *e, } } +/* Our key at `index`: the key expression itself, or for a musig() its first + * participant carrying `wallet_fp`. */ +static bool own_key_ref(const struct wally_descriptor *desc, uint32_t index, + const unsigned char *wallet_fp, + descriptor_key_ref_t *ref_out) { + descriptor_key_ref_t ref = {.index = index, + .participant = DESCRIPTOR_KEY_NOT_MUSIG}; + size_t participants = descriptor_key_musig_participants(desc, index); + unsigned char fp[BIP32_KEY_FINGERPRINT_LEN]; + for (size_t p = 0; p < (participants ? participants : 1); p++) { + if (participants) + ref.participant = p; + if (descriptor_key_origin_fingerprint(desc, ref, fp) && + memcmp(fp, wallet_fp, sizeof(fp)) == 0) { + *ref_out = ref; + return true; + } + } + return false; +} + bool registry_add_parsed(const char *id, struct wally_descriptor *desc, size_t key_index, storage_location_t loc, bool persist) { @@ -449,17 +762,17 @@ bool registry_add_parsed(const char *id, struct wally_descriptor *desc, unsigned char wallet_fp[BIP32_KEY_FINGERPRINT_LEN]; uint32_t num_keys = 0; + descriptor_key_ref_t key; if (!key_get_fingerprint(wallet_fp) || wally_descriptor_get_num_keys(desc, &num_keys) != WALLY_OK || - key_index >= num_keys) + key_index >= num_keys || + !own_key_ref(desc, (uint32_t)key_index, wallet_fp, &key)) goto fail; - char *path_str = NULL; uint32_t origin_path[MAX_KEYPATH_ORIGIN_DEPTH]; size_t origin_path_len = 0; - if (wally_descriptor_get_key_origin_path_str(desc, (uint32_t)key_index, - &path_str) != WALLY_OK || - !path_str) { + char *path_str = descriptor_key_origin_path_alloc(desc, key); + if (!path_str) { ESP_LOGE(TAG, "failed to get origin path for key %zu", key_index); goto fail; } @@ -532,19 +845,10 @@ bool registry_add_from_string(const char *id, const char *descriptor_str, } unsigned char wallet_fp[BIP32_KEY_FINGERPRINT_LEN]; - uint32_t num_keys = 0; - if (!key_get_fingerprint(wallet_fp) || - wally_descriptor_get_num_keys(desc, &num_keys) != WALLY_OK) { - wally_descriptor_free(desc); - return false; - } - for (uint32_t i = 0; i < num_keys; i++) { - unsigned char kfp[BIP32_KEY_FINGERPRINT_LEN]; - if (wally_descriptor_get_key_origin_fingerprint( - desc, i, kfp, BIP32_KEY_FINGERPRINT_LEN) == WALLY_OK && - memcmp(wallet_fp, kfp, BIP32_KEY_FINGERPRINT_LEN) == 0) - return registry_add_parsed(id, desc, i, loc, persist); - } + descriptor_key_ref_t key; + if (key_get_fingerprint(wallet_fp) && + descriptor_key_find(desc, wallet_fp, &key)) + return registry_add_parsed(id, desc, key.index, loc, persist); ESP_LOGW(TAG, "wallet fingerprint not found in descriptor '%s'", id); wally_descriptor_free(desc); return false; @@ -564,19 +868,25 @@ 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; - if (wally_descriptor_canonicalize(e->desc, 0, &descriptor_str) != WALLY_OK) + char *canonical = NULL; + if (wally_descriptor_canonicalize(e->desc, 0, &canonical) != WALLY_OK) + return false; + /* The backup holds the text a leaf musig() was rewritten from */ + char *descriptor_str = musig_leaves_restore_alloc(canonical); + wally_free_string(canonical); + if (!descriptor_str) 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); + free(descriptor_str); if (!ok) { ESP_LOGE(TAG, "registering '%s' failed", name); return false; @@ -587,9 +897,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..ed98cf3b 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 @@ -88,19 +96,69 @@ registry_add_from_string(const char *id, const char *descriptor_str, storage_location_t loc, bool persist); /* Same for a descriptor descriptor_validate_keyed_parsed accepted: takes * ownership of `desc`, parsed for the wallet's network, whose first own key - * (an xpub with a 1 to MAX_KEYPATH_ORIGIN_DEPTH step origin) is `key_index`. + * (an xpub with a 1 to MAX_KEYPATH_ORIGIN_DEPTH step origin) is `key_index`, + * or its first participant carrying our fingerprint for a musig() key. * Frees `desc` on failure. */ 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); + +/* Silent payment account registrations: aliases naming the loaded seed's + * BIP-352 spend key on the wallet network, with our scan key or the one not + * ours it was registered with, always stored on flash and loaded by + * registry_init. An alias names a descriptor or an account, not both. */ +KERN_WARN_UNUSED_RESULT bool registry_sp_alias_exists(const char *alias); +/* `scan_key` is the 32-byte scan key of an account whose scan key is not + * ours, NULL for ours. */ +KERN_WARN_UNUSED_RESULT bool +registry_add_sp_alias(const char *alias, const unsigned char *scan_key); +/* The scan key `alias` was registered with when not ours, else NULL */ +KERN_WARN_UNUSED_RESULT const unsigned char * +registry_sp_alias_scan_key(const char *alias); +KERN_WARN_UNUSED_RESULT size_t registry_sp_alias_count(void); +KERN_WARN_UNUSED_RESULT const char *registry_sp_alias_get(size_t i); +/* Deletes the alias's record from flash and forgets it. Failure leaves it + * intact. */ +KERN_WARN_UNUSED_RESULT bool registry_sp_alias_deregister_at(size_t i); +/* Removes the registration `alias` names, and only it: its descriptor entry + * with its backup on flash when it has one, or its silent payment account + * record. False for an unknown alias; failure leaves the registration + * intact. */ +KERN_WARN_UNUSED_RESULT bool registry_unregister(const char *alias); +/* Names a scan key not ours that the current request pairs with our spend + * key, until registry_sp_clear_named_scan_keys(). False when there is no room + * left. */ +KERN_WARN_UNUSED_RESULT bool +registry_sp_name_scan_key(const unsigned char *scan_key); +void registry_sp_clear_named_scan_keys(void); +/* The scan keys not ours of our spend key's accounts: those registered, then + * those the current request names. NULL past the last. */ +KERN_WARN_UNUSED_RESULT const unsigned char * +registry_sp_scan_key_get(size_t pos); + +/* 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. */ @@ -123,16 +181,26 @@ registry_session_has_duplicate_scripts(const struct wally_descriptor *desc, char *out_id, size_t out_id_size); void registry_clear(void); -/* Clears the session and registers every flash backup the loaded key opens. */ +/* Clears the session and registers every flash backup the loaded key opens, + * and the silent payment aliases of the loaded seed. */ 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/script_templates.c b/main/core/script_templates.c index 132d6651..909c91f5 100644 --- a/main/core/script_templates.c +++ b/main/core/script_templates.c @@ -145,6 +145,15 @@ bool script_template_pubkey_matches_spk(const uint8_t *pubkey, return false; } +bool script_template_pushes_key(const uint8_t *script, size_t script_len, + const uint8_t *key, size_t key_len) { + for (size_t i = 0; i + 1 + key_len <= script_len; i++) { + if (script[i] == key_len && memcmp(script + i + 1, key, key_len) == 0) + return true; + } + return false; +} + char *script_template_address_from_spk(const unsigned char *script, size_t script_len, bool is_testnet) { if (!script || script_len == 0) diff --git a/main/core/script_templates.h b/main/core/script_templates.h index d64d79bb..3162b0e5 100644 --- a/main/core/script_templates.h +++ b/main/core/script_templates.h @@ -30,6 +30,13 @@ script_template_pubkey_matches_spk(const uint8_t *pubkey, size_t pubkey_len, const uint8_t *target_spk, size_t target_spk_len); +/* True when `script` pushes the `key_len` byte key `key`, compressed or + * x-only. */ +KERN_WARN_UNUSED_RESULT bool script_template_pushes_key(const uint8_t *script, + size_t script_len, + const uint8_t *key, + size_t key_len); + KERN_WARN_UNUSED_RESULT char * script_template_address_from_spk(const unsigned char *script, size_t script_len, bool is_testnet); diff --git a/main/core/silent_payments.c b/main/core/silent_payments.c new file mode 100644 index 00000000..b70739e1 --- /dev/null +++ b/main/core/silent_payments.c @@ -0,0 +1,288 @@ +#include "silent_payments.h" +#include "../utils/secure_mem.h" +#include "descriptor_checksum.h" +#include "key.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SP_PURPOSE 352 +#define SP_ACCOUNT 0 +#define SP_VERSION 0 +#define SP_DESCRIPTOR_PREFIX "sp(" + +#define FINGERPRINT_HEX_LEN 9 +#define CHECKSUM_LEN 9 +// Room for sp([fingerprint/352'/coin'/0'] and the closing parenthesis +#define DESCRIPTOR_WRAPPER_LEN 48 + +static uint32_t sp_coin(bool is_testnet) { return is_testnet ? 1 : 0; } + +void sp_account_key_path(bool is_testnet, uint32_t branch, + uint32_t path[SP_PATH_DEPTH]) { + path[0] = BIP32_INITIAL_HARDENED_CHILD | SP_PURPOSE; + path[1] = BIP32_INITIAL_HARDENED_CHILD | sp_coin(is_testnet); + path[2] = BIP32_INITIAL_HARDENED_CHILD | SP_ACCOUNT; + path[3] = BIP32_INITIAL_HARDENED_CHILD | branch; + path[4] = 0; +} + +static bool derive_sp_key(bool is_testnet, uint32_t branch, + unsigned char *secret_out, + unsigned char *pubkey_out) { + uint32_t path[SP_PATH_DEPTH]; + struct ext_key *key = NULL; + + sp_account_key_path(is_testnet, branch, path); + if (!key_get_derived_key_components(path, SP_PATH_DEPTH, &key)) + return false; + // priv_key carries a leading 0x00 before the 32-byte secret + memcpy(secret_out, key->priv_key + 1, SP_SECRET_LEN); + memcpy(pubkey_out, key->pub_key, SP_PUBKEY_LEN); + bip32_key_free(key); + return true; +} + +bool sp_keys_derive(bool is_testnet, struct sp_keys *out) { + if (!out) + return false; + if (derive_sp_key(is_testnet, SP_SCAN_BRANCH, out->scan_secret, + out->scan_pubkey) && + derive_sp_key(is_testnet, SP_SPEND_BRANCH, out->spend_secret, + out->spend_pubkey)) + return true; + sp_keys_wipe(out); + return false; +} + +void sp_keys_wipe(struct sp_keys *keys) { secure_memzero(keys, sizeof(*keys)); } + +bool sp_path_on_branch(const uint32_t *path, size_t len, bool is_testnet, + uint32_t branch) { + return path && len == SP_PATH_DEPTH && + path[0] == (BIP32_INITIAL_HARDENED_CHILD | SP_PURPOSE) && + path[1] == (BIP32_INITIAL_HARDENED_CHILD | sp_coin(is_testnet)) && + path[2] == (BIP32_INITIAL_HARDENED_CHILD | SP_ACCOUNT) && + path[3] == (BIP32_INITIAL_HARDENED_CHILD | branch); +} + +// m/352'/coin'/0'/branch'/0 +static bool is_account_key_path(const uint32_t *path, size_t len, + bool is_testnet, uint32_t branch) { + return sp_path_on_branch(path, len, is_testnet, branch) && + path[SP_PATH_DEPTH - 1] == 0; +} + +static bool fingerprint_is_ours(const unsigned char *fingerprint) { + unsigned char ours[BIP32_KEY_FINGERPRINT_LEN]; + return key_get_fingerprint(ours) && + memcmp(ours, fingerprint, sizeof(ours)) == 0; +} + +static sp_account_t scan_key_account(const unsigned char *scan_key, + bool is_testnet) { + struct sp_keys keys; + if (!sp_keys_derive(is_testnet, &keys)) + return SP_ACCOUNT_ERR_KEYS; + bool ours = secure_memcmp(keys.scan_secret, scan_key, SP_SECRET_LEN) == 0; + sp_keys_wipe(&keys); + if (ours) + return SP_ACCOUNT_OURS; + return wally_ec_private_key_verify(scan_key, SP_SECRET_LEN) == WALLY_OK + ? SP_ACCOUNT_FOREIGN_SCAN + : SP_ACCOUNT_BAD_SCAN_KEY; +} + +sp_account_t sp_account_classify(const unsigned char *fingerprint, + const uint32_t *spend_path, size_t spend_len, + const uint32_t *scan_path, size_t scan_len, + const unsigned char *scan_key, + bool is_testnet) { + if (!fingerprint_is_ours(fingerprint)) + return SP_ACCOUNT_NOT_OURS; + if (sp_path_on_branch(spend_path, spend_len, !is_testnet, SP_SPEND_BRANCH)) + return SP_ACCOUNT_OTHER_NETWORK; + if (!is_account_key_path(spend_path, spend_len, is_testnet, SP_SPEND_BRANCH)) + return SP_ACCOUNT_NOT_OURS; + if (scan_key) + return scan_key_account(scan_key, is_testnet); + return is_account_key_path(scan_path, scan_len, is_testnet, SP_SCAN_BRANCH) + ? SP_ACCOUNT_OURS + : SP_ACCOUNT_NOT_OURS; +} + +// spscan payload: the scan secret then the spend public key +static bool encode_scan_key(const struct sp_keys *keys, bool is_testnet, + char *out, size_t out_len) { + unsigned char payload[SP_SECRET_LEN + SP_PUBKEY_LEN]; + memcpy(payload, keys->scan_secret, SP_SECRET_LEN); + memcpy(payload + SP_SECRET_LEN, keys->spend_pubkey, SP_PUBKEY_LEN); + bool ok = + kern_bech32m_encode(is_testnet ? "tspscan" : "spscan", SP_VERSION, + payload, sizeof(payload), out, out_len) == WALLY_OK; + secure_memzero(payload, sizeof(payload)); + return ok; +} + +// `body` followed by '#' and its checksum +static char *append_checksum_alloc(const char *body) { + char checksum[CHECKSUM_LEN]; + size_t len = strlen(body); + char *out; + + if (!descriptor_checksum_from_string(body, checksum)) + return NULL; + out = malloc(len + 1 + CHECKSUM_LEN); + if (!out) + return NULL; + memcpy(out, body, len); + out[len] = '#'; + memcpy(out + len + 1, checksum, CHECKSUM_LEN); + return out; +} + +bool sp_descriptor_alloc(bool is_testnet, char **out) { + struct sp_keys keys; + char fingerprint[FINGERPRINT_HEX_LEN]; + char scan_key[KERN_BECH32M_MAX_LEN + 1]; + char body[sizeof(scan_key) + DESCRIPTOR_WRAPPER_LEN]; + bool ok; + + if (!out) + return false; + *out = NULL; + if (!key_get_fingerprint_hex(fingerprint) || + !sp_keys_derive(is_testnet, &keys)) + return false; + ok = encode_scan_key(&keys, is_testnet, scan_key, sizeof(scan_key)); + sp_keys_wipe(&keys); + if (ok) { + int len = + snprintf(body, sizeof(body), "sp([%s/%u'/%u'/%u']%s)", fingerprint, + SP_PURPOSE, sp_coin(is_testnet), SP_ACCOUNT, scan_key); + if (len > 0 && (size_t)len < sizeof(body)) + *out = append_checksum_alloc(body); + } + secure_memzero(scan_key, sizeof(scan_key)); + secure_memzero(body, sizeof(body)); + return *out != NULL; +} + +bool sp_descriptor_is_sp(const char *descriptor) { + return descriptor && strncmp(descriptor, SP_DESCRIPTOR_PREFIX, + sizeof(SP_DESCRIPTOR_PREFIX) - 1) == 0; +} + +// Length of a descriptor without its #checksum +static size_t descriptor_body_len(const char *descriptor) { + const char *checksum = strchr(descriptor, '#'); + return checksum ? (size_t)(checksum - descriptor) : strlen(descriptor); +} + +bool sp_descriptor_is_ours(const char *descriptor, bool is_testnet) { + char *ours = NULL; + bool same; + + if (!descriptor || !sp_descriptor_alloc(is_testnet, &ours)) + return false; + same = descriptor_body_len(descriptor) == descriptor_body_len(ours) && + secure_memcmp(descriptor, ours, descriptor_body_len(ours)) == 0; + SECURE_FREE_STRING(ours); + return same; +} + +bool sp_address_alloc(const unsigned char *scan_pubkey, + const unsigned char *spend_pubkey, bool is_testnet, + char **out) { + unsigned char payload[2 * SP_PUBKEY_LEN]; + char address[KERN_BECH32M_MAX_LEN + 1]; + + if (!scan_pubkey || !spend_pubkey || !out) + return false; + memcpy(payload, scan_pubkey, SP_PUBKEY_LEN); + memcpy(payload + SP_PUBKEY_LEN, spend_pubkey, SP_PUBKEY_LEN); + if (kern_bech32m_encode(is_testnet ? "tsp" : "sp", SP_VERSION, payload, + sizeof(payload), address, + sizeof(address)) != WALLY_OK) + return false; + *out = strdup(address); + return *out != NULL; +} + +static bool serialize_point(const secp256k1_pubkey *point, unsigned char *out) { + size_t len = SP_PUBKEY_LEN; + return secp256k1_ec_pubkey_serialize(wally_get_secp_context(), out, &len, + point, SECP256K1_EC_COMPRESSED) == 1; +} + +bool sp_account_keys_derive(bool is_testnet, const unsigned char *scan_secret, + struct sp_keys *out) { + secp256k1_pubkey scan_point; + if (!sp_keys_derive(is_testnet, out)) + return false; + if (!scan_secret) + return true; + memcpy(out->scan_secret, scan_secret, SP_SECRET_LEN); + if (secp256k1_ec_pubkey_create(wally_get_secp_context(), &scan_point, + scan_secret) && + serialize_point(&scan_point, out->scan_pubkey)) + return true; + sp_keys_wipe(out); + return false; +} + +bool sp_labeled_spend_pubkey(const unsigned char *scan_secret, + const unsigned char *spend_pubkey, uint32_t m, + unsigned char *out) { + const secp256k1_context *ctx = wally_get_secp_context(); + secp256k1_silentpayments_label label; + secp256k1_pubkey spend, labeled; + unsigned char label_tweak[SP_SECRET_LEN]; + bool ok = + secp256k1_silentpayments_recipient_label_create(ctx, &label, label_tweak, + scan_secret, m) && + secp256k1_ec_pubkey_parse(ctx, &spend, spend_pubkey, SP_PUBKEY_LEN) && + secp256k1_silentpayments_recipient_create_labeled_spend_pubkey( + ctx, &labeled, &spend, &label) && + serialize_point(&labeled, out); + secure_memzero(label_tweak, sizeof(label_tweak)); + return ok; +} + +static bool is_label_path(const uint32_t *label_path, size_t label_path_len) { + return label_path_len == 0 || + (label_path_len == 1 && label_path[0] != SP_CHANGE_LABEL); +} + +sp_address_result_t sp_account_address_alloc(const unsigned char *scan_secret, + const unsigned char *spend_pubkey, + const uint32_t *label_path, + size_t label_path_len, + bool is_testnet, char **out) { + secp256k1_pubkey scan_point, spend_point; + unsigned char scan_pubkey[SP_PUBKEY_LEN], spend[SP_PUBKEY_LEN]; + + *out = NULL; + if (!is_label_path(label_path, label_path_len)) + return SP_ADDRESS_ERR_LABEL; + if (!secp256k1_ec_pubkey_create(wally_get_secp_context(), &scan_point, + scan_secret) || + !serialize_point(&scan_point, scan_pubkey) || + !secp256k1_ec_pubkey_parse(wally_get_secp_context(), &spend_point, + spend_pubkey, SP_PUBKEY_LEN)) + return SP_ADDRESS_ERR_KEY; + if (label_path_len == 0) + memcpy(spend, spend_pubkey, SP_PUBKEY_LEN); + else if (!sp_labeled_spend_pubkey(scan_secret, spend_pubkey, label_path[0], + spend)) + return SP_ADDRESS_ERR_KEY; + return sp_address_alloc(scan_pubkey, spend, is_testnet, out) + ? SP_ADDRESS_OK + : SP_ADDRESS_ERR_ALLOC; +} diff --git a/main/core/silent_payments.h b/main/core/silent_payments.h new file mode 100644 index 00000000..b5b3f63c --- /dev/null +++ b/main/core/silent_payments.h @@ -0,0 +1,107 @@ +#ifndef SILENT_PAYMENTS_H +#define SILENT_PAYMENTS_H + +#include "../utils/attributes.h" +#include +#include +#include + +#define SP_SECRET_LEN 32 +#define SP_PUBKEY_LEN 33 +#define SP_SCAN_BRANCH 1 +#define SP_SPEND_BRANCH 0 +// BIP352 reserves label m = 0 for change +#define SP_CHANGE_LABEL 0 +#define SP_PATH_DEPTH 5 + +// BIP352 account keys of the loaded seed, account 0'. +// SENSITIVE: wipe with sp_keys_wipe() once used. +struct sp_keys { + unsigned char scan_secret[SP_SECRET_LEN]; + unsigned char spend_secret[SP_SECRET_LEN]; + unsigned char scan_pubkey[SP_PUBKEY_LEN]; + unsigned char spend_pubkey[SP_PUBKEY_LEN]; +}; + +// Derives the scan key at m/352'/coin'/0'/1'/0 and the spend key at +// m/352'/coin'/0'/0'/0, coin being 1' on test networks and 0' on mainnet. +KERN_WARN_UNUSED_RESULT bool sp_keys_derive(bool is_testnet, + struct sp_keys *out); +void sp_keys_wipe(struct sp_keys *keys); + +// The path of our account key on `branch`: m/352'/coin'/0'/branch'/0 +void sp_account_key_path(bool is_testnet, uint32_t branch, + uint32_t path[SP_PATH_DEPTH]); + +// The keys of our spend key's account with `scan_secret` as its scan key, or +// with ours when NULL. +// SENSITIVE: wipe with sp_keys_wipe() once used. +KERN_WARN_UNUSED_RESULT bool +sp_account_keys_derive(bool is_testnet, const unsigned char *scan_secret, + struct sp_keys *out); + +typedef enum { + SP_ACCOUNT_OURS, // our spend key with our scan key + SP_ACCOUNT_FOREIGN_SCAN, // our spend key with a scan key we do not hold + SP_ACCOUNT_OTHER_NETWORK, // our spend key under the other network's coin + SP_ACCOUNT_NOT_OURS, // another master key, spend key or scan path + SP_ACCOUNT_BAD_SCAN_KEY, // a scan key that is not a valid secret key + SP_ACCOUNT_ERR_KEYS, // our keys could not be derived +} sp_account_t; + +// Whose BIP-352 account the keys of master key `fingerprint` are: the spend +// key at `spend_path`, the scan key at `scan_path`, or `scan_key` (32 bytes) +// when not NULL. Our spend key is the one at index 0 of the spend branch. +sp_account_t sp_account_classify(const unsigned char *fingerprint, + const uint32_t *spend_path, size_t spend_len, + const uint32_t *scan_path, size_t scan_len, + const unsigned char *scan_key, + bool is_testnet); + +// True when `path` is m/352'/coin'/0'/branch'/x, for any x. +bool sp_path_on_branch(const uint32_t *path, size_t len, bool is_testnet, + uint32_t branch); + +// BIP392 sp([fingerprint/352'/coin'/0']spscan1...)#checksum carrying the scan +// secret and the spend public key, as bwk prints it. +// SENSITIVE: on success *out holds the scan secret; wipe and free it with +// SECURE_FREE_STRING(). +KERN_WARN_UNUSED_RESULT bool sp_descriptor_alloc(bool is_testnet, char **out); + +// True for a BIP392 sp() descriptor. +bool sp_descriptor_is_sp(const char *descriptor); + +// True when `descriptor` is the loaded seed's own sp() descriptor, the one +// sp_descriptor_alloc() builds, its checksum aside. +bool sp_descriptor_is_ours(const char *descriptor, bool is_testnet); + +// The sp1/tsp1 address of a scan and spend public key pair. +// On success *out must be freed with free(). +KERN_WARN_UNUSED_RESULT bool sp_address_alloc(const unsigned char *scan_pubkey, + const unsigned char *spend_pubkey, + bool is_testnet, char **out); + +// The spend public key labelled with m: spend_pubkey + hash(scan_secret || m)*G +// (BIP352 labels). +KERN_WARN_UNUSED_RESULT bool +sp_labeled_spend_pubkey(const unsigned char *scan_secret, + const unsigned char *spend_pubkey, uint32_t m, + unsigned char *out); + +typedef enum { + SP_ADDRESS_OK, + SP_ADDRESS_ERR_LABEL, // the label path is neither empty nor one step m >= 1 + SP_ADDRESS_ERR_KEY, // the scan secret or the spend key is invalid + SP_ADDRESS_ERR_ALLOC, // the address could not be allocated +} sp_address_result_t; + +// The address of the account of `scan_secret` and `spend_pubkey` at +// `label_path`: empty for the base address, one step m for the address +// labelled m. Label 0 is change, so it is refused. +// On SP_ADDRESS_OK *out must be freed with free(). +KERN_WARN_UNUSED_RESULT sp_address_result_t sp_account_address_alloc( + const unsigned char *scan_secret, const unsigned char *spend_pubkey, + const uint32_t *label_path, size_t label_path_len, bool is_testnet, + char **out); + +#endif // SILENT_PAYMENTS_H diff --git a/main/core/sp_psbt.c b/main/core/sp_psbt.c new file mode 100644 index 00000000..e3d126bc --- /dev/null +++ b/main/core/sp_psbt.c @@ -0,0 +1,1740 @@ +/* + * BIP375 signer: ECDH shares, DLEQ proofs and silent payment output scripts, + * mirroring bwk's SpSigner (sp/src/signer.rs) and its BIP375 rules + * (sp/src/account/bip375.rs). The BIP352 output derivation is libsecp256k1's. + */ + +#include "sp_psbt.h" +#include "../utils/secure_mem.h" +#include "bip32_path.h" +#include "crypto_utils.h" +#include "dleq.h" +#include "kern_wally.h" +#include "key.h" +#include "silent_payments.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// BIP370 PSBT_GLOBAL_TX_MODIFIABLE +#define GLOBAL_TX_MODIFIABLE 0x06 +// BIP174 PSBT_IN_SIGHASH_TYPE and its 32-bit little endian value +#define PSBT_IN_SIGHASH_TYPE 0x03 +// BIP370 PSBT_OUT_SCRIPT +#define PSBT_OUT_SCRIPT 0x04 +#define OP_RETURN 0x6a +#define SIGHASH_TYPE_LEN 4 +// BIP174 magic bytes "psbt" and 0xff +#define PSBT_MAGIC_LEN 5 +// BIP371 PSBT_IN_TAP_MERKLE_ROOT, held in libwally's psbt_fields map +#define PSBT_IN_TAP_MERKLE_ROOT 0x18 +#define SP_V0_INFO_LEN (2 * SP_PUBKEY_LEN) +#define SP_LABEL_LEN 4 +#define SP_TWEAK_LEN 32 +#define SHARE_KEY_LEN (1 + SP_PUBKEY_LEN) +#define OUTPOINT_LEN (WALLY_TXHASH_LEN + 4) +#define XONLY_LEN 32 +#define P2TR_SCRIPT_LEN 34 +#define P2TR_KEY_OFFSET 2 +#define P2SH_HASH_OFFSET 2 +#define P2WPKH_HASH_OFFSET 2 +#define P2PKH_HASH_OFFSET 3 +#define OP_1 0x51 +#define OP_16 0x60 +#define PUSH_32 0x20 +#define SCHNORR_SIG_LEN 64 +// Smallest and largest witness program, BIP141 +#define WITNESS_PROGRAM_MIN 2 +#define WITNESS_PROGRAM_MAX 40 +// Largest push a P2SH redeem script can be +#define MAX_REDEEM_SCRIPT_LEN 520 +// Deepest derivation path a PSBT key origin may name +#define MAX_KEYPATH_DEPTH 32 +// Tag of the hash that binds the DLEQ aux randomness to the proven secret +#define DLEQ_AUX_HEDGE_TAG "KERN/DLEQAux" +// BIP352 tagged hashes +#define BIP352_INPUTS_TAG "BIP0352/Inputs" +#define BIP352_SHARED_SECRET_TAG "BIP0352/SharedSecret" +// Prefix of a compressed public key with an even Y +#define EVEN_Y_PREFIX 0x02 + +// BIP341 NUMS point H, the provably unspendable internal key +static const unsigned char NUMS_H[XONLY_LEN] = { + 0x50, 0x92, 0x9b, 0x74, 0xc1, 0xa0, 0x49, 0x54, 0xb7, 0x8b, 0x4b, + 0x60, 0x35, 0xe9, 0x7a, 0x5e, 0x07, 0x8a, 0x5a, 0x0f, 0x28, 0xec, + 0x96, 0xd5, 0x47, 0xbf, 0xee, 0x9a, 0xce, 0x80, 0x3a, 0xc0}; + +static const unsigned char SCALAR_ONE[SP_SECRET_LEN] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; + +typedef struct { + unsigned char scan[SP_PUBKEY_LEN]; + unsigned char spend[SP_PUBKEY_LEN]; + size_t output_index; +} sp_recipient_t; + +// An input as BIP352 sees it: whether its key is summed, that key, and +// whether the seed holds its private key +typedef struct { + bool eligible; + bool owned; + unsigned char pubkey[SP_PUBKEY_LEN]; +} sp_input_t; + +// Every input of a PSBT, with the parity-adjusted private keys of the owned +// ones at their input index +typedef struct { + sp_input_t *inputs; + unsigned char (*keys)[SP_SECRET_LEN]; + size_t count; + size_t eligible; + size_t owned; +} input_set_t; + +static const secp256k1_context *secp_ctx(void) { + return wally_get_secp_context(); +} + +static const struct wally_map_item *find_field(const struct wally_map *map, + const unsigned char *key, + size_t key_len) { + size_t index = 0; + if (wally_map_find(map, key, key_len, &index) != WALLY_OK || !index) + return NULL; + return &map->items[index - 1]; +} + +static const struct wally_map_item * +find_unkeyed_field(const struct wally_map *map, unsigned char type) { + return find_field(map, &type, 1); +} + +static bool parse_point(const unsigned char *bytes, secp256k1_pubkey *out) { + return secp256k1_ec_pubkey_parse(secp_ctx(), out, bytes, SP_PUBKEY_LEN) == 1; +} + +static bool serialize_point(const secp256k1_pubkey *point, unsigned char *out) { + size_t len = SP_PUBKEY_LEN; + return secp256k1_ec_pubkey_serialize(secp_ctx(), out, &len, point, + SECP256K1_EC_COMPRESSED) == 1; +} + +// *info is NULL when the output carries no PSBT_OUT_SP_V0_INFO +static sp_psbt_result_t read_output_info(const struct wally_psbt_output *out, + const unsigned char **info) { + const struct wally_map_item *item = + find_unkeyed_field(&out->unknowns, PSBT_OUT_SP_V0_INFO); + const struct wally_map_item *label = + find_unkeyed_field(&out->unknowns, PSBT_OUT_SP_V0_LABEL); + secp256k1_pubkey point; + + *info = NULL; + if (!item) + return label ? SP_PSBT_ERR_FIELD : SP_PSBT_OK; + if (item->value_len != SP_V0_INFO_LEN || + (label && label->value_len != SP_LABEL_LEN) || + !parse_point(item->value, &point) || + !parse_point(item->value + SP_PUBKEY_LEN, &point)) + return SP_PSBT_ERR_FIELD; + *info = item->value; + return SP_PSBT_OK; +} + +bool sp_output_keys(const struct wally_psbt_output *output, + unsigned char *scan_out, unsigned char *spend_out) { + const unsigned char *info = NULL; + if (!output || read_output_info(output, &info) != SP_PSBT_OK || !info) + return false; + memcpy(scan_out, info, SP_PUBKEY_LEN); + memcpy(spend_out, info + SP_PUBKEY_LEN, SP_PUBKEY_LEN); + return true; +} + +static bool output_has_info(const struct wally_psbt_output *out) { + return find_unkeyed_field(&out->unknowns, PSBT_OUT_SP_V0_INFO) != NULL; +} + +bool sp_psbt_has_outputs(const struct wally_psbt *psbt) { + if (!psbt) + return false; + for (size_t i = 0; i < psbt->num_outputs; i++) + if (output_has_info(&psbt->outputs[i])) + return true; + return false; +} + +static bool is_field_type(const struct wally_map_item *item, + unsigned char type) { + return item->key_len && item->key[0] == type; +} + +static bool has_field_type_in(const struct wally_map *map, unsigned char first, + unsigned char last) { + for (size_t i = 0; i < map->num_items; i++) { + const struct wally_map_item *item = &map->items[i]; + if (item->key_len && item->key[0] >= first && item->key[0] <= last) + return true; + } + return false; +} + +bool sp_psbt_has_fields(const struct wally_psbt *psbt) { + if (!psbt) + return false; + if (has_field_type_in(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, + PSBT_GLOBAL_SP_DLEQ)) + return true; + for (size_t i = 0; i < psbt->num_inputs; i++) + if (has_field_type_in(&psbt->inputs[i].unknowns, PSBT_IN_SP_ECDH_SHARE, + PSBT_IN_SP_TWEAK)) + return true; + for (size_t i = 0; i < psbt->num_outputs; i++) + if (has_field_type_in(&psbt->outputs[i].unknowns, PSBT_OUT_SP_V0_INFO, + PSBT_OUT_SP_V0_LABEL)) + return true; + return false; +} + +bool sp_psbt_outputs_pending(const struct wally_psbt *psbt) { + bool pending = false; + if (!psbt) + return false; + for (size_t i = 0; i < psbt->num_outputs; i++) { + const struct wally_psbt_output *out = &psbt->outputs[i]; + if (out->script) + continue; + if (!output_has_info(out)) + return false; + pending = true; + } + return pending; +} + +static int compare_recipients(const void *a, const void *b) { + const sp_recipient_t *ra = a, *rb = b; + int cmp = memcmp(ra->scan, rb->scan, SP_PUBKEY_LEN); + if (cmp) + return cmp; + cmp = memcmp(ra->spend, rb->spend, SP_PUBKEY_LEN); + if (cmp) + return cmp; + return (ra->output_index > rb->output_index) - + (ra->output_index < rb->output_index); +} + +// Sorted by scan key, then spend key, then output index: bwk assigns k in +// this order within a scan key group (bip375.rs output_scripts). +static sp_psbt_result_t collect_recipients(const struct wally_psbt *psbt, + sp_recipient_t **out, + size_t *count) { + sp_recipient_t *recipients = calloc(psbt->num_outputs, sizeof(*recipients)); + size_t n = 0; + + if (!recipients) + return SP_PSBT_ERR_CRYPTO; + for (size_t i = 0; i < psbt->num_outputs; i++) { + const unsigned char *info = NULL; + sp_psbt_result_t result = read_output_info(&psbt->outputs[i], &info); + if (result != SP_PSBT_OK) { + free(recipients); + return result; + } + if (!info) + continue; + memcpy(recipients[n].scan, info, SP_PUBKEY_LEN); + memcpy(recipients[n].spend, info + SP_PUBKEY_LEN, SP_PUBKEY_LEN); + recipients[n].output_index = i; + n++; + } + qsort(recipients, n, sizeof(*recipients), compare_recipients); + *out = recipients; + *count = n; + return SP_PSBT_OK; +} + +static bool same_prevout(const struct wally_tx_output *a, + const struct wally_tx_output *b) { + return a->satoshi == b->satoshi && a->script_len == b->script_len && + memcmp(a->script, b->script, a->script_len) == 0; +} + +// The output an input spends, from witness_utxo and non_witness_utxo, which +// must agree when both are present. +static sp_psbt_result_t input_prevout(const struct wally_psbt_input *in, + const struct wally_tx_output **out) { + const struct wally_tx_output *non_witness = NULL; + unsigned char txid[WALLY_TXHASH_LEN]; + + if (in->utxo) { + if (wally_tx_get_txid(in->utxo, txid, sizeof(txid)) != WALLY_OK || + memcmp(txid, in->txhash, sizeof(txid)) != 0 || + in->index >= in->utxo->num_outputs) + return SP_PSBT_ERR_INPUT; + non_witness = &in->utxo->outputs[in->index]; + } + if (in->witness_utxo && non_witness && + !same_prevout(in->witness_utxo, non_witness)) + return SP_PSBT_ERR_INPUT; + *out = in->witness_utxo ? in->witness_utxo : non_witness; + return *out ? SP_PSBT_OK : SP_PSBT_ERR_INPUT; +} + +// BIP352 defines no input key for segwit v2 and later +static bool is_future_witness_version(const struct wally_tx_output *prevout) { + const unsigned char *script = prevout->script; + size_t len = prevout->script_len; + return len >= WITNESS_PROGRAM_MIN + 2 && len <= WITNESS_PROGRAM_MAX + 2 && + script[0] > OP_1 && script[0] <= OP_16 && script[1] == len - 2; +} + +static uint32_t script_type(const struct wally_tx_output *prevout) { + size_t type = WALLY_SCRIPT_TYPE_UNKNOWN; + if (wally_scriptpubkey_get_type(prevout->script, prevout->script_len, + &type) != WALLY_OK) + return WALLY_SCRIPT_TYPE_UNKNOWN; + return (uint32_t)type; +} + +// The input's BIP371 merkle root, NULL when it commits to no script tree +static const unsigned char * +input_merkle_root(const struct wally_psbt_input *in) { + const struct wally_map_item *item = + wally_map_get_integer(&in->psbt_fields, PSBT_IN_TAP_MERKLE_ROOT); + return item && item->value_len == SHA256_LEN ? item->value : NULL; +} + +static size_t merkle_root_len(const unsigned char *merkle_root) { + return merkle_root ? SHA256_LEN : 0; +} + +// A NUMS internal key excludes the input only when it provably reaches the +// output key: a false claim would drop a real key from the input sum. +static bool commits_to_nums(const struct wally_psbt *psbt, size_t i, + const unsigned char *output_key) { + const unsigned char *merkle_root = input_merkle_root(&psbt->inputs[i]); + unsigned char internal_key[XONLY_LEN], tweaked[EC_PUBLIC_KEY_LEN]; + size_t written = 0; + + if (wally_psbt_get_input_taproot_internal_key( + psbt, i, internal_key, sizeof(internal_key), &written) != WALLY_OK || + written != XONLY_LEN || memcmp(internal_key, NUMS_H, XONLY_LEN) != 0) + return false; + if (memcmp(output_key, NUMS_H, XONLY_LEN) == 0) + return true; + return wally_ec_public_key_bip341_tweak( + NUMS_H, XONLY_LEN, merkle_root, merkle_root_len(merkle_root), 0, + tweaked, sizeof(tweaked)) == WALLY_OK && + memcmp(tweaked + 1, output_key, XONLY_LEN) == 0; +} + +// The redeem script of P2SH input `i`, which must hash to the script it +// spends. *redeem_len is 0 when the PSBT gives none. +static sp_psbt_result_t proven_redeem_script(const struct wally_psbt *psbt, + size_t i, + const unsigned char *script, + unsigned char *redeem, + size_t *redeem_len) { + unsigned char hash[HASH160_LEN]; + + if (wally_psbt_get_input_redeem_script_len(psbt, i, redeem_len) != WALLY_OK || + !*redeem_len) { + *redeem_len = 0; + return SP_PSBT_OK; + } + if (*redeem_len > MAX_REDEEM_SCRIPT_LEN || + wally_psbt_get_input_redeem_script(psbt, i, redeem, MAX_REDEEM_SCRIPT_LEN, + redeem_len) != WALLY_OK || + wally_hash160(redeem, *redeem_len, hash, sizeof(hash)) != WALLY_OK || + memcmp(hash, script + P2SH_HASH_OFFSET, sizeof(hash)) != 0) + return SP_PSBT_ERR_INPUT; + return SP_PSBT_OK; +} + +// P2SH counts only as P2SH-P2WPKH +static sp_psbt_result_t p2sh_eligibility(const struct wally_psbt *psbt, + size_t i, const unsigned char *script, + bool *eligible) { + unsigned char redeem[MAX_REDEEM_SCRIPT_LEN]; + size_t redeem_len = 0, type = WALLY_SCRIPT_TYPE_UNKNOWN; + sp_psbt_result_t result = + proven_redeem_script(psbt, i, script, redeem, &redeem_len); + + *eligible = + result == SP_PSBT_OK && redeem_len && + wally_scriptpubkey_get_type(redeem, redeem_len, &type) == WALLY_OK && + type == WALLY_SCRIPT_TYPE_P2WPKH; + return result; +} + +// Whether BIP352 sums this input's key, from the script it spends alone +static sp_psbt_result_t input_eligibility(const struct wally_psbt *psbt, + size_t i, + const struct wally_tx_output *prevout, + bool *eligible) { + switch (script_type(prevout)) { + case WALLY_SCRIPT_TYPE_P2PKH: + case WALLY_SCRIPT_TYPE_P2WPKH: + *eligible = true; + return SP_PSBT_OK; + case WALLY_SCRIPT_TYPE_P2TR: + *eligible = !commits_to_nums(psbt, i, prevout->script + P2TR_KEY_OFFSET); + return SP_PSBT_OK; + case WALLY_SCRIPT_TYPE_P2SH: + return p2sh_eligibility(psbt, i, prevout->script, eligible); + default: + *eligible = false; + return SP_PSBT_OK; + } +} + +// The fingerprint our key origins carry, and the silent payment keys +typedef struct { + const struct sp_keys *keys; + unsigned char fingerprint[BIP32_KEY_FINGERPRINT_LEN]; +} signer_t; + +// The key a PSBT key origin names, when the origin is our seed. The path only +// locates the key: the caller proves it against the script it spends. +static bool derive_origin_key(const unsigned char *keypath, size_t keypath_len, + const unsigned char *fingerprint, + struct ext_key **key_out) { + uint32_t path[MAX_KEYPATH_DEPTH]; + size_t depth = 0; + + return keypath_len >= BIP32_KEY_FINGERPRINT_LEN && + memcmp(keypath, fingerprint, BIP32_KEY_FINGERPRINT_LEN) == 0 && + bip32_path_from_keypath(keypath, keypath_len, path, &depth, + MAX_KEYPATH_DEPTH) && + key_get_derived_key_components(path, depth, key_out); +} + +// Keeps `key` when its x-only public key is `output_key`, negated to the +// even-Y key BIP352 sums; wipes it otherwise +static sp_psbt_result_t match_output_key(unsigned char *key, + const unsigned char *output_key, + bool *owned) { + secp256k1_keypair keypair; + secp256k1_xonly_pubkey xonly; + unsigned char x[XONLY_LEN]; + int parity = 0; + bool ok = + secp256k1_keypair_create(secp_ctx(), &keypair, key) && + secp256k1_keypair_xonly_pub(secp_ctx(), &xonly, &parity, &keypair) && + secp256k1_xonly_pubkey_serialize(secp_ctx(), x, &xonly); + + *owned = false; + secure_memzero(&keypair, sizeof(keypair)); + if (ok && memcmp(x, output_key, XONLY_LEN) != 0) { + secure_memzero(key, SP_SECRET_LEN); + return SP_PSBT_OK; + } + if (!ok || (parity && !secp256k1_ec_seckey_negate(secp_ctx(), key))) { + secure_memzero(key, SP_SECRET_LEN); + return SP_PSBT_ERR_CRYPTO; + } + *owned = true; + return SP_PSBT_OK; +} + +// d = b_spend + tweak, ours when x(d*G) is the P2TR output key it spends +// (signer.rs reconstruct_signing_key) +static sp_psbt_result_t sp_tweak_signing_key( + const struct wally_psbt_input *in, const struct wally_tx_output *prevout, + const unsigned char *spend_secret, bool *owned, unsigned char *key_out) { + const struct wally_map_item *tweak = + find_unkeyed_field(&in->unknowns, PSBT_IN_SP_TWEAK); + + *owned = false; + if (!tweak) + return SP_PSBT_OK; + if (tweak->value_len != SP_TWEAK_LEN) + return SP_PSBT_ERR_FIELD; + if (script_type(prevout) != WALLY_SCRIPT_TYPE_P2TR) + return SP_PSBT_OK; + memcpy(key_out, spend_secret, SP_SECRET_LEN); + if (!secp256k1_ec_seckey_tweak_add(secp_ctx(), key_out, tweak->value)) { + secure_memzero(key_out, SP_SECRET_LEN); + return SP_PSBT_ERR_FIELD; + } + return match_output_key(key_out, prevout->script + P2TR_KEY_OFFSET, owned); +} + +// One PSBT_IN_TAP_BIP32_DERIVATION entry: its key, BIP341 tweaked by the +// input's merkle root, must be the output key +static sp_psbt_result_t taproot_candidate(const struct wally_map_item *item, + const unsigned char *merkle_root, + const unsigned char *output_key, + const unsigned char *fingerprint, + bool *owned, unsigned char *key_out) { + struct ext_key *key = NULL; + bool ok; + + *owned = false; + if (!derive_origin_key(item->value, item->value_len, fingerprint, &key)) + return SP_PSBT_OK; + // The entry's key must be the one its origin derives + ok = item->key_len == XONLY_LEN && + memcmp(key->pub_key + 1, item->key, XONLY_LEN) == 0 && + wally_ec_private_key_bip341_tweak( + key->priv_key + 1, SP_SECRET_LEN, merkle_root, + merkle_root_len(merkle_root), 0, key_out, SP_SECRET_LEN) == WALLY_OK; + bip32_key_free(key); + if (!ok) { + secure_memzero(key_out, SP_SECRET_LEN); + return SP_PSBT_OK; + } + return match_output_key(key_out, output_key, owned); +} + +static sp_psbt_result_t taproot_origin_key(const struct wally_psbt_input *in, + const unsigned char *output_key, + const unsigned char *fingerprint, + bool *owned, + unsigned char *key_out) { + const struct wally_map *paths = &in->taproot_leaf_paths; + const unsigned char *merkle_root = input_merkle_root(in); + sp_psbt_result_t result = SP_PSBT_OK; + + *owned = false; + for (size_t j = 0; result == SP_PSBT_OK && !*owned && j < paths->num_items; + j++) + result = taproot_candidate(&paths->items[j], merkle_root, output_key, + fingerprint, owned, key_out); + return result; +} + +// A spend of one of our silent payments carries its tweak; any other P2TR +// input is a BIP341 key path spend +static sp_psbt_result_t taproot_signing_key( + const struct wally_psbt_input *in, const struct wally_tx_output *prevout, + const signer_t *signer, bool *owned, unsigned char *key_out) { + if (find_unkeyed_field(&in->unknowns, PSBT_IN_SP_TWEAK)) + return sp_tweak_signing_key(in, prevout, signer->keys->spend_secret, owned, + key_out); + return taproot_origin_key(in, prevout->script + P2TR_KEY_OFFSET, + signer->fingerprint, owned, key_out); +} + +static sp_psbt_result_t p2sh_key_hash(const struct wally_psbt *psbt, size_t i, + const unsigned char *script, + unsigned char *hash_out) { + unsigned char redeem[MAX_REDEEM_SCRIPT_LEN]; + size_t redeem_len = 0; + sp_psbt_result_t result = + proven_redeem_script(psbt, i, script, redeem, &redeem_len); + + if (result != SP_PSBT_OK) + return result; + if (!redeem_len) + return SP_PSBT_ERR_INPUT; + memcpy(hash_out, redeem + P2WPKH_HASH_OFFSET, HASH160_LEN); + return SP_PSBT_OK; +} + +// The key hash a P2WPKH, P2PKH or P2SH-P2WPKH script commits to +static sp_psbt_result_t +committed_key_hash(const struct wally_psbt *psbt, size_t i, + const struct wally_tx_output *prevout, + unsigned char *hash_out) { + switch (script_type(prevout)) { + case WALLY_SCRIPT_TYPE_P2WPKH: + memcpy(hash_out, prevout->script + P2WPKH_HASH_OFFSET, HASH160_LEN); + return SP_PSBT_OK; + case WALLY_SCRIPT_TYPE_P2PKH: + memcpy(hash_out, prevout->script + P2PKH_HASH_OFFSET, HASH160_LEN); + return SP_PSBT_OK; + case WALLY_SCRIPT_TYPE_P2SH: + return p2sh_key_hash(psbt, i, prevout->script, hash_out); + default: + return SP_PSBT_ERR_INPUT; + } +} + +// One PSBT_IN_BIP32_DERIVATION entry: the key its origin derives must be the +// entry's key and hash to the one the script commits to +static bool key_hash_candidate(const struct wally_map_item *item, + const unsigned char *hash, + const unsigned char *fingerprint, + unsigned char *key_out) { + struct ext_key *key = NULL; + unsigned char key_hash[HASH160_LEN]; + bool owned; + + if (!derive_origin_key(item->value, item->value_len, fingerprint, &key)) + return false; + owned = item->key_len == EC_PUBLIC_KEY_LEN && + memcmp(key->pub_key, item->key, EC_PUBLIC_KEY_LEN) == 0 && + wally_hash160(key->pub_key, EC_PUBLIC_KEY_LEN, key_hash, + sizeof(key_hash)) == WALLY_OK && + memcmp(key_hash, hash, HASH160_LEN) == 0; + if (owned) + memcpy(key_out, key->priv_key + 1, SP_SECRET_LEN); + bip32_key_free(key); + return owned; +} + +static sp_psbt_result_t +key_hash_signing_key(const struct wally_psbt *psbt, size_t i, + const struct wally_tx_output *prevout, + const signer_t *signer, bool *owned, + unsigned char *key_out) { + const struct wally_map *keypaths = &psbt->inputs[i].keypaths; + unsigned char hash[HASH160_LEN]; + sp_psbt_result_t result = committed_key_hash(psbt, i, prevout, hash); + + *owned = false; + for (size_t j = 0; result == SP_PSBT_OK && !*owned && j < keypaths->num_items; + j++) + *owned = key_hash_candidate(&keypaths->items[j], hash, signer->fingerprint, + key_out); + return result; +} + +// Our key for an eligible input, found from the script it spends (BIP352): a +// PSBT key origin only names a candidate, kept once it reproduces the script +static sp_psbt_result_t input_signing_key(const struct wally_psbt *psbt, + size_t i, + const struct wally_tx_output *prevout, + const signer_t *signer, bool *owned, + unsigned char *key_out) { + switch (script_type(prevout)) { + case WALLY_SCRIPT_TYPE_P2TR: + return taproot_signing_key(&psbt->inputs[i], prevout, signer, owned, + key_out); + case WALLY_SCRIPT_TYPE_P2WPKH: + case WALLY_SCRIPT_TYPE_P2PKH: + case WALLY_SCRIPT_TYPE_P2SH: + return key_hash_signing_key(psbt, i, prevout, signer, owned, key_out); + default: + *owned = false; + return SP_PSBT_OK; + } +} + +// The key BIP352 sums for a key hash input we do not hold: the +// PSBT_IN_BIP32_DERIVATION key hashing to the one the script commits to. BIP375 +// has the updater add it for that, and its test vectors refuse an input +// without it, so a partial signature's key does not stand in. +static bool key_hash_match(const struct wally_map *map, + const unsigned char *hash, + unsigned char *pubkey_out) { + unsigned char key_hash[HASH160_LEN]; + for (size_t j = 0; j < map->num_items; j++) { + const struct wally_map_item *item = &map->items[j]; + if (item->key_len == SP_PUBKEY_LEN && + wally_hash160(item->key, item->key_len, key_hash, sizeof(key_hash)) == + WALLY_OK && + memcmp(key_hash, hash, HASH160_LEN) == 0) { + memcpy(pubkey_out, item->key, SP_PUBKEY_LEN); + return true; + } + } + return false; +} + +// The public key of an eligible input another signer holds. For P2TR it is +// the even-Y lift of the output key, read from the script, never from a key +// origin a PSBT could make up. +static sp_psbt_result_t foreign_input_key(const struct wally_psbt *psbt, + size_t i, + const struct wally_tx_output *prevout, + unsigned char *pubkey_out) { + const struct wally_psbt_input *in = &psbt->inputs[i]; + unsigned char hash[HASH160_LEN]; + sp_psbt_result_t result; + + if (script_type(prevout) == WALLY_SCRIPT_TYPE_P2TR) { + pubkey_out[0] = EVEN_Y_PREFIX; + memcpy(pubkey_out + 1, prevout->script + P2TR_KEY_OFFSET, XONLY_LEN); + return SP_PSBT_OK; + } + result = committed_key_hash(psbt, i, prevout, hash); + if (result != SP_PSBT_OK) + return result; + return key_hash_match(&in->keypaths, hash, pubkey_out) + ? SP_PSBT_OK + : SP_PSBT_ERR_INPUT_KEY; +} + +static bool secret_pubkey(const unsigned char *secret, + unsigned char *pubkey_out) { + secp256k1_pubkey point; + return secp256k1_ec_pubkey_create(secp_ctx(), &point, secret) && + serialize_point(&point, pubkey_out); +} + +// Input rules checked before deriving the outputs (bip375.rs +// validate_input_eligibility), then the key BIP352 sums for an eligible +// input, with its private key when the seed holds it +static sp_psbt_result_t classify_input(const struct wally_psbt *psbt, size_t i, + const signer_t *signer, + input_set_t *set) { + const struct wally_psbt_input *in = &psbt->inputs[i]; + sp_input_t *input = &set->inputs[i]; + const struct wally_tx_output *prevout = NULL; + bool owned = false; + sp_psbt_result_t result = input_prevout(in, &prevout); + + if (result != SP_PSBT_OK) + return result; + if (is_future_witness_version(prevout)) + return SP_PSBT_ERR_INPUT; + // Any other sighash lets a signer change outputs derived from the inputs + if (in->sighash && in->sighash != WALLY_SIGHASH_ALL) + return SP_PSBT_ERR_SIGHASH; + result = input_eligibility(psbt, i, prevout, &input->eligible); + if (result != SP_PSBT_OK || !input->eligible) + return result; + set->eligible++; + result = input_signing_key(psbt, i, prevout, signer, &owned, set->keys[i]); + if (result != SP_PSBT_OK) + return result; + if (!owned) + return foreign_input_key(psbt, i, prevout, input->pubkey); + input->owned = true; + set->owned++; + return secret_pubkey(set->keys[i], input->pubkey) ? SP_PSBT_OK + : SP_PSBT_ERR_CRYPTO; +} + +static void input_set_free(input_set_t *set) { + if (set->keys) { + secure_memzero(set->keys, set->count * sizeof(*set->keys)); + free(set->keys); + } + free(set->inputs); + memset(set, 0, sizeof(*set)); +} + +// BIP352 needs at least one eligible input, whoever holds it +static sp_psbt_result_t collect_inputs(const struct wally_psbt *psbt, + const signer_t *signer, + input_set_t *set) { + sp_psbt_result_t result = SP_PSBT_OK; + + memset(set, 0, sizeof(*set)); + set->count = psbt->num_inputs; + set->inputs = calloc(set->count, sizeof(*set->inputs)); + set->keys = kern_secret_alloc(set->count * sizeof(*set->keys)); + if (!set->inputs || !set->keys) + result = SP_PSBT_ERR_CRYPTO; + for (size_t i = 0; result == SP_PSBT_OK && i < set->count; i++) + result = classify_input(psbt, i, signer, set); + if (result == SP_PSBT_OK && !set->eligible) + result = SP_PSBT_ERR_INPUT; + if (result != SP_PSBT_OK) + input_set_free(set); + return result; +} + +static bool owns_all_inputs(const input_set_t *set) { + return set->owned == set->eligible; +} + +static bool sum_owned_keys(const input_set_t *set, unsigned char *sum) { + bool first = true; + for (size_t i = 0; i < set->count; i++) { + if (!set->inputs[i].owned) + continue; + if (first) + memcpy(sum, set->keys[i], SP_SECRET_LEN); + else if (!secp256k1_ec_seckey_tweak_add(secp_ctx(), sum, set->keys[i])) + return false; + first = false; + } + return !first; +} + +// A_sum, the sum of every eligible input's public key +static sp_psbt_result_t sum_input_keys(const input_set_t *set, + secp256k1_pubkey *sum) { + secp256k1_pubkey *keys = calloc(set->eligible, sizeof(*keys)); + const secp256k1_pubkey **ptrs = calloc(set->eligible, sizeof(*ptrs)); + sp_psbt_result_t result = keys && ptrs ? SP_PSBT_OK : SP_PSBT_ERR_CRYPTO; + size_t n = 0; + + for (size_t i = 0; result == SP_PSBT_OK && i < set->count; i++) { + if (!set->inputs[i].eligible) + continue; + if (!parse_point(set->inputs[i].pubkey, &keys[n])) + result = SP_PSBT_ERR_INPUT_KEY; + ptrs[n] = &keys[n]; + n++; + } + if (result == SP_PSBT_OK && + !secp256k1_ec_pubkey_combine(secp_ctx(), sum, ptrs, n)) + result = SP_PSBT_ERR_CRYPTO; + free(keys); + free(ptrs); + return result; +} + +static void scan_field_key(unsigned char type, const unsigned char *scan, + unsigned char *key) { + key[0] = type; + memcpy(key + 1, scan, SP_PUBKEY_LEN); +} + +static bool set_scan_field(struct wally_map *map, unsigned char type, + const unsigned char *scan, + const unsigned char *value, size_t value_len) { + unsigned char key[SHARE_KEY_LEN]; + scan_field_key(type, scan, key); + return wally_map_replace(map, key, sizeof(key), value, value_len) == WALLY_OK; +} + +static const struct wally_map_item *find_scan_field(const struct wally_map *map, + unsigned char type, + const unsigned char *scan) { + unsigned char key[SHARE_KEY_LEN]; + scan_field_key(type, scan, key); + return find_field(map, key, sizeof(key)); +} + +// Where a scope keeps its shares and proofs: the global map or an input's +typedef struct { + unsigned char share; + unsigned char proof; +} share_types_t; + +static const share_types_t GLOBAL_SHARE = {PSBT_GLOBAL_SP_ECDH_SHARE, + PSBT_GLOBAL_SP_DLEQ}; +static const share_types_t INPUT_SHARE = {PSBT_IN_SP_ECDH_SHARE, + PSBT_IN_SP_DLEQ}; + +// Every share in `map` has its proof and every proof its share, each of its +// length (bip375.rs validate_share_maps) +static bool share_map_is_paired(const struct wally_map *map, + share_types_t types) { + for (size_t i = 0; i < map->num_items; i++) { + const struct wally_map_item *item = &map->items[i]; + bool is_share = is_field_type(item, types.share); + if (!is_share && !is_field_type(item, types.proof)) + continue; + if (item->key_len != SHARE_KEY_LEN || + item->value_len != (is_share ? SP_PUBKEY_LEN : DLEQ_PROOF_LEN) || + !find_scan_field(map, is_share ? types.proof : types.share, + item->key + 1)) + return false; + } + return true; +} + +static bool share_maps_are_paired(const struct wally_psbt *psbt) { + if (!share_map_is_paired(&psbt->unknowns, GLOBAL_SHARE)) + return false; + for (size_t i = 0; i < psbt->num_inputs; i++) + if (!share_map_is_paired(&psbt->inputs[i].unknowns, INPUT_SHARE)) + return false; + return true; +} + +// H(rng || secret || B_scan): a weak RNG still yields a proof nonce bound to +// the secret it proves (embit _default_aux_rand) +static bool hedged_aux(const unsigned char *secret, const unsigned char *scan, + unsigned char *aux_out) { + unsigned char buf[DLEQ_AUX_LEN + SP_SECRET_LEN + SP_PUBKEY_LEN]; + bool ok = crypto_random_bytes(buf, DLEQ_AUX_LEN) == CRYPTO_OK; + + memcpy(buf + DLEQ_AUX_LEN, secret, SP_SECRET_LEN); + memcpy(buf + DLEQ_AUX_LEN + SP_SECRET_LEN, scan, SP_PUBKEY_LEN); + ok = ok && secp256k1_tagged_sha256( + secp_ctx(), aux_out, (const unsigned char *)DLEQ_AUX_HEDGE_TAG, + sizeof(DLEQ_AUX_HEDGE_TAG) - 1, buf, sizeof(buf)) == 1; + secure_memzero(buf, sizeof(buf)); + return ok; +} + +// BIP375 fixes the DLEQ generator to G +static bool dleq_generator(secp256k1_pubkey *out) { + return secp256k1_ec_pubkey_create(secp_ctx(), out, SCALAR_ONE) == 1; +} + +// The share and proof `map` holds for `scan`, if any, must prove the share +// is the discrete log of `public` times the scan key +static sp_psbt_result_t check_declared_share(const struct wally_map *map, + share_types_t types, + const unsigned char *scan, + const unsigned char *public, + bool *declared) { + const struct wally_map_item *share = find_scan_field(map, types.share, scan); + const struct wally_map_item *proof = find_scan_field(map, types.proof, scan); + secp256k1_pubkey public_point, scan_point, share_point, generator; + + *declared = share != NULL; + if (!share) + return SP_PSBT_OK; + if (!proof || !parse_point(public, &public_point) || + !parse_point(scan, &scan_point) || + !parse_point(share->value, &share_point)) + return SP_PSBT_ERR_FIELD; + if (!dleq_generator(&generator)) + return SP_PSBT_ERR_CRYPTO; + return dleq_verify(&public_point, &scan_point, &share_point, proof->value, + &generator, NULL) + ? SP_PSBT_OK + : SP_PSBT_ERR_FIELD; +} + +// share = secret*B_scan and its DLEQ proof, unless `map` already holds a +// share, which must then verify against `public` +static sp_psbt_result_t write_share(struct wally_map *map, share_types_t types, + const unsigned char *scan, + const unsigned char *secret, + const unsigned char *public) { + secp256k1_pubkey scan_point, share, generator; + unsigned char share_bytes[SP_PUBKEY_LEN], proof[DLEQ_PROOF_LEN]; + unsigned char aux[DLEQ_AUX_LEN]; + bool declared = false, ok; + sp_psbt_result_t result = + check_declared_share(map, types, scan, public, &declared); + + if (result != SP_PSBT_OK || declared) + return result; + if (!parse_point(scan, &scan_point)) + return SP_PSBT_ERR_FIELD; + share = scan_point; + ok = secp256k1_ec_pubkey_tweak_mul(secp_ctx(), &share, secret) && + serialize_point(&share, share_bytes) && dleq_generator(&generator) && + hedged_aux(secret, scan, aux) && + dleq_prove(secret, &scan_point, aux, &generator, NULL, proof) && + set_scan_field(map, types.share, scan, share_bytes, + sizeof(share_bytes)) && + set_scan_field(map, types.proof, scan, proof, sizeof(proof)); + secure_memzero(aux, sizeof(aux)); + return ok ? SP_PSBT_OK : SP_PSBT_ERR_CRYPTO; +} + +// Holding every eligible input, one global share of a_sum (signer.rs +// write_shares) +static sp_psbt_result_t write_global_share(struct wally_psbt *psbt, + const input_set_t *set, + const unsigned char *scan, + const unsigned char *input_sum) { + unsigned char sum[SP_SECRET_LEN]; + sp_psbt_result_t result = + sum_owned_keys(set, sum) + ? write_share(&psbt->unknowns, GLOBAL_SHARE, scan, sum, input_sum) + : SP_PSBT_ERR_CRYPTO; + secure_memzero(sum, sizeof(sum)); + return result; +} + +// Holding some eligible inputs, a share of each, and the other signers' +// shares checked against their inputs' keys (signer.rs +// write_input_ecdh_share) +static sp_psbt_result_t write_input_shares(struct wally_psbt *psbt, + const input_set_t *set, + const unsigned char *scan, + const unsigned char *input_sum) { + bool declared = false; + sp_psbt_result_t result = check_declared_share(&psbt->unknowns, GLOBAL_SHARE, + scan, input_sum, &declared); + + for (size_t i = 0; result == SP_PSBT_OK && i < set->count; i++) { + const sp_input_t *input = &set->inputs[i]; + struct wally_map *map = &psbt->inputs[i].unknowns; + if (input->owned) + result = write_share(map, INPUT_SHARE, scan, set->keys[i], input->pubkey); + else if (input->eligible) + result = check_declared_share(map, INPUT_SHARE, scan, input->pubkey, + &declared); + } + return result; +} + +// One pass per distinct scan key, recipients being sorted by scan key +static sp_psbt_result_t write_shares(struct wally_psbt *psbt, + const input_set_t *set, + const sp_recipient_t *recipients, + size_t count, + const unsigned char *input_sum) { + sp_psbt_result_t result = SP_PSBT_OK; + for (size_t i = 0; result == SP_PSBT_OK && i < count; i++) { + const unsigned char *scan = recipients[i].scan; + if (i && !memcmp(scan, recipients[i - 1].scan, SP_PUBKEY_LEN)) + continue; + result = owns_all_inputs(set) + ? write_global_share(psbt, set, scan, input_sum) + : write_input_shares(psbt, set, scan, input_sum); + } + return result; +} + +// The share every eligible input adds up to for `scan`: the global one, else +// the sum of the per-input ones. *complete is false while an eligible input +// still has none (bip375.rs combined_share). +static sp_psbt_result_t combined_share(const struct wally_psbt *psbt, + const input_set_t *set, + const unsigned char *scan, + secp256k1_pubkey *out, bool *complete) { + const struct wally_map_item *global = + find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, scan); + secp256k1_pubkey *shares; + const secp256k1_pubkey **ptrs; + sp_psbt_result_t result = SP_PSBT_OK; + size_t n = 0; + + *complete = true; + if (global) + return parse_point(global->value, out) ? SP_PSBT_OK : SP_PSBT_ERR_FIELD; + shares = calloc(set->eligible, sizeof(*shares)); + ptrs = calloc(set->eligible, sizeof(*ptrs)); + if (!shares || !ptrs) + result = SP_PSBT_ERR_CRYPTO; + for (size_t i = 0; result == SP_PSBT_OK && *complete && i < set->count; i++) { + const struct wally_map_item *share; + if (!set->inputs[i].eligible) + continue; + share = + find_scan_field(&psbt->inputs[i].unknowns, PSBT_IN_SP_ECDH_SHARE, scan); + if (!share) + *complete = false; + else if (!parse_point(share->value, &shares[n])) + result = SP_PSBT_ERR_FIELD; + ptrs[n] = &shares[n]; + n++; + } + if (result == SP_PSBT_OK && *complete && + !secp256k1_ec_pubkey_combine(secp_ctx(), out, ptrs, n)) + result = SP_PSBT_ERR_CRYPTO; + free(shares); + free(ptrs); + return result; +} + +// BIP352 hashes the smallest outpoint of all inputs, eligible or not +static void smallest_outpoint(const struct wally_psbt *psbt, + unsigned char *out) { + unsigned char candidate[OUTPOINT_LEN]; + for (size_t i = 0; i < psbt->num_inputs; i++) { + const struct wally_psbt_input *in = &psbt->inputs[i]; + memcpy(candidate, in->txhash, WALLY_TXHASH_LEN); + candidate[WALLY_TXHASH_LEN] = in->index & 0xff; + candidate[WALLY_TXHASH_LEN + 1] = (in->index >> 8) & 0xff; + candidate[WALLY_TXHASH_LEN + 2] = (in->index >> 16) & 0xff; + candidate[WALLY_TXHASH_LEN + 3] = (in->index >> 24) & 0xff; + if (!i || memcmp(candidate, out, OUTPOINT_LEN) < 0) + memcpy(out, candidate, OUTPOINT_LEN); + } +} + +// input_hash = hash_BIP0352/Inputs(outpoint_L || A_sum) +static bool input_hash(const struct wally_psbt *psbt, + const unsigned char *input_sum, unsigned char *out) { + unsigned char buf[OUTPOINT_LEN + SP_PUBKEY_LEN]; + smallest_outpoint(psbt, buf); + memcpy(buf + OUTPOINT_LEN, input_sum, SP_PUBKEY_LEN); + return secp256k1_tagged_sha256( + secp_ctx(), out, (const unsigned char *)BIP352_INPUTS_TAG, + sizeof(BIP352_INPUTS_TAG) - 1, buf, sizeof(buf)) == 1; +} + +// P_k = B_spend + t_k*G, t_k = hash_BIP0352/SharedSecret(ser(S) || ser32(k)) +// with S = input_hash*share: BIP352's output key, from the shares alone +static bool output_key(const unsigned char *shared_secret, + const unsigned char *spend, uint32_t k, + secp256k1_xonly_pubkey *out) { + unsigned char buf[SP_PUBKEY_LEN + sizeof(uint32_t)], tweak[SP_SECRET_LEN]; + secp256k1_pubkey point; + bool ok; + + memcpy(buf, shared_secret, SP_PUBKEY_LEN); + buf[SP_PUBKEY_LEN] = (k >> 24) & 0xff; + buf[SP_PUBKEY_LEN + 1] = (k >> 16) & 0xff; + buf[SP_PUBKEY_LEN + 2] = (k >> 8) & 0xff; + buf[SP_PUBKEY_LEN + 3] = k & 0xff; + ok = secp256k1_tagged_sha256( + secp_ctx(), tweak, (const unsigned char *)BIP352_SHARED_SECRET_TAG, + sizeof(BIP352_SHARED_SECRET_TAG) - 1, buf, sizeof(buf)) && + parse_point(spend, &point) && + secp256k1_ec_pubkey_tweak_add(secp_ctx(), &point, tweak) && + secp256k1_xonly_pubkey_from_pubkey(secp_ctx(), out, NULL, &point); + secure_memzero(buf, sizeof(buf)); + secure_memzero(tweak, sizeof(tweak)); + return ok; +} + +// A signer never overwrites a script another party committed to +static sp_psbt_result_t set_output_script(struct wally_psbt *psbt, size_t index, + const secp256k1_xonly_pubkey *key) { + struct wally_psbt_output *out = &psbt->outputs[index]; + unsigned char script[P2TR_SCRIPT_LEN] = {OP_1, PUSH_32}; + + if (!secp256k1_xonly_pubkey_serialize(secp_ctx(), script + P2TR_KEY_OFFSET, + key)) + return SP_PSBT_ERR_CRYPTO; + if (out->script) + return out->script_len == sizeof(script) && + memcmp(out->script, script, sizeof(script)) == 0 + ? SP_PSBT_OK + : SP_PSBT_ERR_SCRIPT; + return wally_psbt_output_set_script(out, script, sizeof(script)) == WALLY_OK + ? SP_PSBT_OK + : SP_PSBT_ERR_CRYPTO; +} + +// S = input_hash*share for the group of `scan` +static sp_psbt_result_t +group_shared_secret(const struct wally_psbt *psbt, const input_set_t *set, + const unsigned char *scan, const unsigned char *hash, + unsigned char *out, bool *complete) { + secp256k1_pubkey share; + sp_psbt_result_t result = combined_share(psbt, set, scan, &share, complete); + + if (result != SP_PSBT_OK || !*complete) + return result; + return secp256k1_ec_pubkey_tweak_mul(secp_ctx(), &share, hash) && + serialize_point(&share, out) + ? SP_PSBT_OK + : SP_PSBT_ERR_CRYPTO; +} + +// The scripts of a group whose shares are all in, k counting up in the +// recipients' order. A group still waiting for a share keeps its outputs +// scriptless: a script set there could not be checked (bip375.rs +// output_scripts). +static sp_psbt_result_t fill_group_scripts(struct wally_psbt *psbt, + const sp_recipient_t *group, + size_t len, + const unsigned char *shared_secret, + bool complete) { + secp256k1_xonly_pubkey key; + sp_psbt_result_t result = SP_PSBT_OK; + + for (size_t k = 0; result == SP_PSBT_OK && k < len; k++) { + if (!complete) + result = psbt->outputs[group[k].output_index].script ? SP_PSBT_ERR_SCRIPT + : SP_PSBT_OK; + else if (!output_key(shared_secret, group[k].spend, (uint32_t)k, &key)) + result = SP_PSBT_ERR_CRYPTO; + else + result = set_output_script(psbt, group[k].output_index, &key); + } + return result; +} + +static size_t group_len(const sp_recipient_t *recipients, size_t count) { + size_t len = 1; + while (len < count && + !memcmp(recipients[len].scan, recipients[0].scan, SP_PUBKEY_LEN)) + len++; + return len; +} + +// The scripts of every group whose shares are all in. *pending says whether +// a group still waits for another signer's share. +static sp_psbt_result_t +fill_output_scripts(struct wally_psbt *psbt, const input_set_t *set, + const sp_recipient_t *recipients, size_t count, + const unsigned char *input_sum, bool *pending) { + unsigned char hash[SHA256_LEN], shared_secret[SP_PUBKEY_LEN]; + sp_psbt_result_t result = + input_hash(psbt, input_sum, hash) ? SP_PSBT_OK : SP_PSBT_ERR_CRYPTO; + size_t len; + + *pending = false; + for (size_t i = 0; result == SP_PSBT_OK && i < count; i += len) { + bool complete = false; + len = group_len(recipients + i, count - i); + // BIP352 fails a group above K_max addresses + if (len > SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT) { + result = SP_PSBT_ERR_FIELD; + break; + } + result = group_shared_secret(psbt, set, recipients[i].scan, hash, + shared_secret, &complete); + if (result == SP_PSBT_OK) + result = fill_group_scripts(psbt, recipients + i, len, shared_secret, + complete); + *pending = *pending || !complete; + } + secure_memzero(shared_secret, sizeof(shared_secret)); + return result; +} + +// The parse let scriptless outputs through, so every check it skipped runs +// again on the completed PSBT +static sp_psbt_result_t reparse_strict(struct wally_psbt **psbt) { + struct wally_psbt *strict = NULL; + unsigned char *bytes = NULL; + size_t len = 0, written = 0; + bool ok = wally_psbt_get_length(*psbt, 0, &len) == WALLY_OK && + (bytes = malloc(len)) != NULL && + wally_psbt_to_bytes(*psbt, 0, bytes, len, &written) == WALLY_OK && + kern_psbt_from_bytes(bytes, written, WALLY_PSBT_PARSE_FLAG_COMPLETE, + &strict) == WALLY_OK; + free(bytes); + if (!ok) + return SP_PSBT_ERR_PSBT; + wally_psbt_free(*psbt); + *psbt = strict; + return SP_PSBT_OK; +} + +// The inputs of `psbt` as BIP352 sees them, for the seed's keys +static sp_psbt_result_t classify_inputs(const struct wally_psbt *psbt, + const struct sp_keys *keys, + input_set_t *set) { + signer_t signer = {.keys = keys}; + if (!key_get_fingerprint(signer.fingerprint)) + return SP_PSBT_ERR_KEYS; + return collect_inputs(psbt, &signer, set); +} + +static bool sp_scripts_set(const struct wally_psbt *psbt) { + for (size_t i = 0; i < psbt->num_outputs; i++) + if (psbt->outputs[i].script && output_has_info(&psbt->outputs[i])) + return true; + return false; +} + +// A script already set means its setter froze the inputs and outputs it +// depends on (BIP375 signer rule) +static bool preset_scripts_frozen(const struct wally_psbt *psbt) { + return !sp_scripts_set(psbt) || + !(psbt->tx_modifiable_flags & + (WALLY_PSBT_TXMOD_INPUTS | WALLY_PSBT_TXMOD_OUTPUTS)); +} + +static sp_psbt_result_t complete_with_keys(struct wally_psbt *psbt, + const struct sp_keys *keys, + bool *pending) { + sp_recipient_t *recipients = NULL; + size_t count = 0; + input_set_t set = {0}; + secp256k1_pubkey input_point; + unsigned char input_sum[SP_PUBKEY_LEN]; + sp_psbt_result_t result = collect_recipients(psbt, &recipients, &count); + + if (result == SP_PSBT_OK && + (!share_maps_are_paired(psbt) || !preset_scripts_frozen(psbt))) + result = SP_PSBT_ERR_FIELD; + if (result == SP_PSBT_OK) + result = classify_inputs(psbt, keys, &set); + if (result == SP_PSBT_OK) + result = sum_input_keys(&set, &input_point); + if (result == SP_PSBT_OK && !serialize_point(&input_point, input_sum)) + result = SP_PSBT_ERR_CRYPTO; + if (result == SP_PSBT_OK) + result = write_shares(psbt, &set, recipients, count, input_sum); + if (result == SP_PSBT_OK) + result = + fill_output_scripts(psbt, &set, recipients, count, input_sum, pending); + // The scripts depend on the exact input and output sets, so freeze both + // once one is set + if (result == SP_PSBT_OK && sp_scripts_set(psbt) && + wally_psbt_set_tx_modifiable_flags(psbt, 0) != WALLY_OK) + result = SP_PSBT_ERR_PSBT; + input_set_free(&set); + free(recipients); + return result; +} + +// No PSBT_OUT_SP_V0_LABEL without its PSBT_OUT_SP_V0_INFO, which a PSBT with +// no silent payment output could still carry +static bool outputs_well_formed(const struct wally_psbt *psbt) { + const unsigned char *info = NULL; + for (size_t i = 0; i < psbt->num_outputs; i++) + if (read_output_info(&psbt->outputs[i], &info) != SP_PSBT_OK) + return false; + return true; +} + +sp_psbt_result_t sp_psbt_complete(struct wally_psbt **psbt, bool is_testnet) { + struct wally_psbt *completed = NULL; + struct sp_keys keys; + bool pending = false; + sp_psbt_result_t result; + + if (!psbt || !*psbt) + return SP_PSBT_ERR_PSBT; + // BIP375 and BIP376 fields only exist in PSBTv2 + if ((*psbt)->version != WALLY_PSBT_VERSION_2 && sp_psbt_has_fields(*psbt)) + return SP_PSBT_ERR_PSBT; + if (!sp_psbt_has_outputs(*psbt)) + return outputs_well_formed(*psbt) ? SP_PSBT_OK : SP_PSBT_ERR_FIELD; + if (!sp_keys_derive(is_testnet, &keys)) + return SP_PSBT_ERR_KEYS; + // Completed on a copy, so a refused PSBT is left as it came + result = kern_psbt_clone_alloc(*psbt, 0, &completed) == WALLY_OK + ? complete_with_keys(completed, &keys, &pending) + : SP_PSBT_ERR_PSBT; + sp_keys_wipe(&keys); + // A pending PSBT keeps scriptless outputs, which only parse loosely + if (result == SP_PSBT_OK && !pending) + result = reparse_strict(&completed); + if (result != SP_PSBT_OK) { + wally_psbt_free(completed); + return result; + } + wally_psbt_free(*psbt); + *psbt = completed; + return pending ? SP_PSBT_PENDING : SP_PSBT_OK; +} + +bool sp_psbt_input_is_ours(const struct wally_psbt *psbt, size_t i, + bool is_testnet) { + const struct wally_tx_output *prevout = NULL; + struct sp_keys keys; + unsigned char key[SP_SECRET_LEN]; + bool owned = false; + + if (!psbt || i >= psbt->num_inputs || + !find_unkeyed_field(&psbt->inputs[i].unknowns, PSBT_IN_SP_TWEAK) || + input_prevout(&psbt->inputs[i], &prevout) != SP_PSBT_OK || + !sp_keys_derive(is_testnet, &keys)) + return false; + if (sp_tweak_signing_key(&psbt->inputs[i], prevout, keys.spend_secret, &owned, + key) != SP_PSBT_OK) + owned = false; + sp_keys_wipe(&keys); + secure_memzero(key, sizeof(key)); + return owned; +} + +static bool is_labeled_spend_key(const struct sp_keys *keys, uint32_t m, + const unsigned char *spend) { + unsigned char labeled[SP_PUBKEY_LEN]; + return sp_labeled_spend_pubkey(keys->scan_secret, keys->spend_pubkey, m, + labeled) && + memcmp(spend, labeled, SP_PUBKEY_LEN) == 0; +} + +// Ownership of an output paying our scan key, from its spend key and the +// label it declares. A declared label that does not give its spend key is +// not trusted. +static sp_output_ownership_t +spend_key_ownership(const struct sp_keys *keys, const unsigned char *spend, + const struct wally_map_item *label) { + uint32_t m; + + if (label) { + m = bip32_path_u32_le(label->value); + if (!is_labeled_spend_key(keys, m, spend)) + return SP_OUTPUT_FOREIGN; + return m == SP_CHANGE_LABEL ? SP_OUTPUT_CHANGE : SP_OUTPUT_SELF; + } + if (is_labeled_spend_key(keys, SP_CHANGE_LABEL, spend)) + return SP_OUTPUT_CHANGE; + return memcmp(spend, keys->spend_pubkey, SP_PUBKEY_LEN) == 0 + ? SP_OUTPUT_SELF + : SP_OUTPUT_FOREIGN; +} + +sp_output_ownership_t sp_psbt_output_ownership(const struct wally_psbt *psbt, + size_t i, + const unsigned char *scan_secret, + bool is_testnet) { + unsigned char scan[SP_PUBKEY_LEN], spend[SP_PUBKEY_LEN]; + struct sp_keys keys; + sp_output_ownership_t ownership = SP_OUTPUT_FOREIGN; + + if (!psbt || i >= psbt->num_outputs || + !sp_output_keys(&psbt->outputs[i], scan, spend) || + !sp_account_keys_derive(is_testnet, scan_secret, &keys)) + return SP_OUTPUT_FOREIGN; + if (memcmp(scan, keys.scan_pubkey, SP_PUBKEY_LEN) == 0) + ownership = spend_key_ownership( + &keys, spend, + find_unkeyed_field(&psbt->outputs[i].unknowns, PSBT_OUT_SP_V0_LABEL)); + sp_keys_wipe(&keys); + return ownership; +} + +// BIP341 key path signature over the input's sighash, the sighash byte +// appended unless it is SIGHASH_DEFAULT +static bool sign_key_path(struct wally_psbt *psbt, size_t i, + const unsigned char *key) { + struct wally_tx *tx = NULL; + unsigned char hash[SHA256_LEN], aux[SP_SECRET_LEN]; + unsigned char sig[SCHNORR_SIG_LEN + 1]; + size_t sig_len = SCHNORR_SIG_LEN; + uint32_t sighash = psbt->inputs[i].sighash; + bool ok = + wally_psbt_extract(psbt, WALLY_PSBT_EXTRACT_NON_FINAL, &tx) == WALLY_OK && + wally_psbt_get_input_signature_hash(psbt, i, tx, NULL, 0, 0, hash, + sizeof(hash)) == WALLY_OK && + crypto_random_bytes(aux, sizeof(aux)) == CRYPTO_OK && + wally_ec_sig_from_bytes_aux(key, SP_SECRET_LEN, hash, sizeof(hash), aux, + sizeof(aux), EC_FLAG_SCHNORR, sig, + SCHNORR_SIG_LEN) == WALLY_OK; + + if (sighash != WALLY_SIGHASH_DEFAULT) + sig[sig_len++] = (unsigned char)sighash; + ok = ok && wally_psbt_set_input_taproot_signature(psbt, i, sig, sig_len) == + WALLY_OK; + wally_tx_free(tx); + secure_memzero(aux, sizeof(aux)); + return ok; +} + +bool sp_psbt_sign_input(struct wally_psbt *psbt, size_t i, bool is_testnet) { + const struct wally_tx_output *prevout = NULL; + struct sp_keys keys; + unsigned char key[SP_SECRET_LEN]; + bool owned = false, ok; + + if (!psbt || i >= psbt->num_inputs || + input_prevout(&psbt->inputs[i], &prevout) != SP_PSBT_OK || + !sp_keys_derive(is_testnet, &keys)) + return false; + ok = sp_tweak_signing_key(&psbt->inputs[i], prevout, keys.spend_secret, + &owned, key) == SP_PSBT_OK && + owned && sign_key_path(psbt, i, key); + sp_keys_wipe(&keys); + secure_memzero(key, sizeof(key)); + return ok; +} + +static bool copy_fields(const struct wally_map *from, struct wally_map *to, + unsigned char type_a, unsigned char type_b) { + for (size_t i = 0; i < from->num_items; i++) { + const struct wally_map_item *item = &from->items[i]; + if ((is_field_type(item, type_a) || is_field_type(item, type_b)) && + wally_map_replace(to, item->key, item->key_len, item->value, + item->value_len) != WALLY_OK) + return false; + } + return true; +} + +bool sp_psbt_copy_fields(const struct wally_psbt *from, struct wally_psbt *to) { + const unsigned char frozen = 0; + unsigned char tx_modifiable = GLOBAL_TX_MODIFIABLE; + + if (!from || !to || from->num_inputs != to->num_inputs || + from->num_outputs != to->num_outputs) + return false; + if (!sp_psbt_has_outputs(from)) + return true; + if (!copy_fields(&from->unknowns, &to->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, + PSBT_GLOBAL_SP_DLEQ)) + return false; + for (size_t i = 0; i < from->num_inputs; i++) + if (!copy_fields(&from->inputs[i].unknowns, &to->inputs[i].unknowns, + PSBT_IN_SP_ECDH_SHARE, PSBT_IN_SP_DLEQ)) + return false; + for (size_t i = 0; i < from->num_outputs; i++) + if (!copy_fields(&from->outputs[i].unknowns, &to->outputs[i].unknowns, + PSBT_OUT_SP_V0_INFO, PSBT_OUT_SP_V0_LABEL)) + return false; + return to->tx_modifiable_flags || + wally_map_replace(&to->unknowns, &tx_modifiable, 1, &frozen, 1) == + WALLY_OK; +} + +static bool share_listed(const sp_share_t *shares, size_t count, + const unsigned char *scan) { + for (size_t i = 0; i < count; i++) + if (memcmp(shares[i].scan, scan, SP_PUBKEY_LEN) == 0) + return true; + return false; +} + +static bool read_share(const struct wally_map *map, share_types_t types, + const unsigned char *scan, sp_share_t *out) { + const struct wally_map_item *share = find_scan_field(map, types.share, scan); + const struct wally_map_item *proof = find_scan_field(map, types.proof, scan); + if (!share || !proof || share->value_len != SP_PUBKEY_LEN || + proof->value_len != DLEQ_PROOF_LEN) + return false; + memcpy(out->scan, scan, SP_PUBKEY_LEN); + memcpy(out->share, share->value, SP_PUBKEY_LEN); + memcpy(out->proof, proof->value, DLEQ_PROOF_LEN); + return true; +} + +// The shares of `scan` the seed contributed: the global one, or one per +// eligible input it holds +static bool read_scan_shares(const struct wally_psbt *psbt, + const input_set_t *set, const unsigned char *scan, + sp_share_t *shares, size_t *n) { + if (owns_all_inputs(set)) { + shares[*n].global = true; + shares[*n].input_index = 0; + return read_share(&psbt->unknowns, GLOBAL_SHARE, scan, &shares[(*n)++]); + } + for (size_t i = 0; i < set->count; i++) { + if (!set->inputs[i].owned) + continue; + shares[*n].global = false; + shares[*n].input_index = i; + if (!read_share(&psbt->inputs[i].unknowns, INPUT_SHARE, scan, + &shares[(*n)++])) + return false; + } + return true; +} + +static bool collect_shares(const struct wally_psbt *psbt, + const input_set_t *set, sp_share_t *shares, + size_t *n) { + unsigned char scan[SP_PUBKEY_LEN], spend[SP_PUBKEY_LEN]; + for (size_t i = 0; i < psbt->num_outputs; i++) { + if (!sp_output_keys(&psbt->outputs[i], scan, spend) || + share_listed(shares, *n, scan)) + continue; + if (!read_scan_shares(psbt, set, scan, shares, n)) + return false; + } + return true; +} + +bool sp_psbt_shares_alloc(const struct wally_psbt *psbt, bool is_testnet, + sp_share_t **out, size_t *count) { + struct sp_keys keys; + input_set_t set = {0}; + sp_share_t *shares = NULL; + size_t n = 0; + bool ok; + + *out = NULL; + *count = 0; + if (!psbt || !sp_psbt_has_outputs(psbt) || !sp_keys_derive(is_testnet, &keys)) + return false; + ok = classify_inputs(psbt, &keys, &set) == SP_PSBT_OK; + sp_keys_wipe(&keys); + if (!ok) + return false; + if (set.owned) { + shares = calloc(psbt->num_outputs * set.owned, sizeof(*shares)); + ok = shares && collect_shares(psbt, &set, shares, &n); + } + input_set_free(&set); + if (!ok) { + free(shares); + return false; + } + *out = shares; + *count = n; + return true; +} + +// A read position in a serialized PSBT +typedef struct { + const uint8_t *pos; + const uint8_t *end; +} raw_cursor_t; + +// One key-value pair of a serialized PSBT map +typedef struct { + const uint8_t *key; + size_t key_len; + const uint8_t *value; + size_t value_len; +} raw_pair_t; + +static bool read_compact_size(raw_cursor_t *c, size_t *out) { + size_t width, value = 0; + + if (c->pos >= c->end) + return false; + switch (*c->pos) { + case 0xfd: + width = 2; + break; + case 0xfe: + width = 4; + break; + case 0xff: + width = 8; + break; + default: + *out = *c->pos++; + return true; + } + c->pos++; + if ((size_t)(c->end - c->pos) < width) + return false; + for (size_t i = width; i > 0; i--) + value = (value << 8) | c->pos[i - 1]; + c->pos += width; + *out = value; + return true; +} + +static bool read_bytes(raw_cursor_t *c, const uint8_t **out, size_t *len) { + if (!read_compact_size(c, len) || *len > (size_t)(c->end - c->pos)) + return false; + *out = c->pos; + c->pos += *len; + return true; +} + +// Reads the next pair of a map: 1 for a pair, 0 at the map's separator, -1 +// for a malformed map +static int read_pair(raw_cursor_t *c, raw_pair_t *pair) { + raw_cursor_t peek = *c; + size_t key_len = 0; + + if (!read_compact_size(&peek, &key_len)) + return -1; + if (!key_len) { + *c = peek; + return 0; + } + return read_bytes(c, &pair->key, &pair->key_len) && + read_bytes(c, &pair->value, &pair->value_len) + ? 1 + : -1; +} + +static bool skip_map(raw_cursor_t *c) { + raw_pair_t pair; + int read; + while ((read = read_pair(c, &pair)) == 1) + ; + return read == 0; +} + +static bool pair_is(const raw_pair_t *pair, uint8_t type) { + return pair->key_len == 1 && pair->key[0] == type; +} + +static bool input_map_sighash_is_all(raw_cursor_t *c) { + raw_pair_t pair; + int read; + while ((read = read_pair(c, &pair)) == 1) + if (pair_is(&pair, PSBT_IN_SIGHASH_TYPE) && + (pair.value_len != SIGHASH_TYPE_LEN || + bip32_path_u32_le(pair.value) != WALLY_SIGHASH_ALL)) + return false; + return read == 0; +} + +bool sp_psbt_raw_sighash_is_all(const uint8_t *data, size_t len, + size_t num_inputs) { + raw_cursor_t c; + + if (!data || len < PSBT_MAGIC_LEN) + return false; + c.pos = data + PSBT_MAGIC_LEN; + c.end = data + len; + if (!skip_map(&c)) + return false; + for (size_t i = 0; i < num_inputs; i++) + if (!input_map_sighash_is_all(&c)) + return false; + return true; +} + +// Copies the pairs of one map, PSBT_OUT_SCRIPT left out when `drop_script` +static bool copy_raw_map(raw_cursor_t *c, bool drop_script, uint8_t **dst) { + raw_pair_t pair; + for (;;) { + const uint8_t *start = c->pos; + int read = read_pair(c, &pair); + if (read < 0) + return false; + if (!read || !(drop_script && pair_is(&pair, PSBT_OUT_SCRIPT))) { + memcpy(*dst, start, (size_t)(c->pos - start)); + *dst += c->pos - start; + } + if (!read) + return true; + } +} + +static bool output_is_pending(const struct wally_psbt_output *out) { + return !out->script && output_has_info(out); +} + +// libwally serializes no PSBTv2 output without a script, so a pending +// output gets PLACEHOLDER_SCRIPT, cut out of the bytes again +static bool serialize_with_placeholders(const struct wally_psbt *psbt, + uint8_t **out, size_t *out_len) { + static const unsigned char PLACEHOLDER_SCRIPT[] = {OP_RETURN}; + struct wally_psbt *copy = NULL; + size_t len = 0; + bool ok = kern_psbt_clone_alloc(psbt, 0, ©) == WALLY_OK; + + for (size_t i = 0; ok && i < copy->num_outputs; i++) + if (output_is_pending(&psbt->outputs[i])) + ok = wally_psbt_output_set_script(©->outputs[i], PLACEHOLDER_SCRIPT, + sizeof(PLACEHOLDER_SCRIPT)) == WALLY_OK; + ok = ok && wally_psbt_get_length(copy, 0, &len) == WALLY_OK && + (*out = malloc(len)) != NULL && + wally_psbt_to_bytes(copy, 0, *out, len, out_len) == WALLY_OK; + wally_psbt_free(copy); + return ok; +} + +bool sp_psbt_serialize_alloc(const struct wally_psbt *psbt, uint8_t **out, + size_t *out_len) { + uint8_t *bytes = NULL, *stripped = NULL, *dst; + size_t len = 0; + raw_cursor_t c; + bool ok; + + *out = NULL; + *out_len = 0; + if (!psbt || !serialize_with_placeholders(psbt, &bytes, &len) || + len < PSBT_MAGIC_LEN || !(stripped = malloc(len))) { + free(bytes); + return false; + } + memcpy(stripped, bytes, PSBT_MAGIC_LEN); + dst = stripped + PSBT_MAGIC_LEN; + c.pos = bytes + PSBT_MAGIC_LEN; + c.end = bytes + len; + ok = copy_raw_map(&c, false, &dst); + for (size_t i = 0; ok && i < psbt->num_inputs; i++) + ok = copy_raw_map(&c, false, &dst); + for (size_t i = 0; ok && i < psbt->num_outputs; i++) + ok = copy_raw_map(&c, output_is_pending(&psbt->outputs[i]), &dst); + free(bytes); + if (!ok || c.pos != c.end) { + free(stripped); + return false; + } + *out = stripped; + *out_len = (size_t)(dst - stripped); + return true; +} + +bool sp_psbt_base64_alloc(const struct wally_psbt *psbt, char **out) { + uint8_t *bytes = NULL; + size_t len = 0; + bool ok = sp_psbt_serialize_alloc(psbt, &bytes, &len) && + wally_base64_from_bytes(bytes, len, 0, out) == WALLY_OK; + free(bytes); + return ok; +} + +const char *sp_psbt_result_message(sp_psbt_result_t result) { + switch (result) { + case SP_PSBT_OK: + return "OK"; + case SP_PSBT_ERR_FIELD: + return "Malformed silent payment field"; + case SP_PSBT_ERR_INPUT: + return "Inputs not usable with silent payment outputs"; + case SP_PSBT_ERR_SIGHASH: + return "Silent payment outputs need SIGHASH_ALL inputs"; + case SP_PSBT_PENDING: + return "Waiting for the other signers' silent payment shares"; + case SP_PSBT_ERR_INPUT_KEY: + return "An input names no key its script commits to"; + case SP_PSBT_ERR_KEYS: + return "Silent payment keys unavailable"; + case SP_PSBT_ERR_CRYPTO: + return "Silent payment output derivation failed"; + case SP_PSBT_ERR_SCRIPT: + return "Output script differs from its silent payment"; + case SP_PSBT_ERR_PSBT: + default: + return "Invalid PSBT"; + } +} diff --git a/main/core/sp_psbt.h b/main/core/sp_psbt.h new file mode 100644 index 00000000..ccef63d0 --- /dev/null +++ b/main/core/sp_psbt.h @@ -0,0 +1,138 @@ +#ifndef SP_PSBT_H +#define SP_PSBT_H + +#include "../utils/attributes.h" +#include "dleq.h" +#include "silent_payments.h" +#include +#include + +// BIP375 and BIP376 field types, held in libwally's unknowns maps +#define PSBT_GLOBAL_SP_ECDH_SHARE 0x07 +#define PSBT_GLOBAL_SP_DLEQ 0x08 +#define PSBT_OUT_SP_V0_INFO 0x09 +#define PSBT_OUT_SP_V0_LABEL 0x0a +#define PSBT_IN_SP_ECDH_SHARE 0x1d +#define PSBT_IN_SP_DLEQ 0x1e +#define PSBT_IN_SP_SPEND_BIP32_DERIVATION 0x1f +#define PSBT_IN_SP_TWEAK 0x20 + +typedef enum { + SP_PSBT_OK, + SP_PSBT_PENDING, // shares written, a script waits for other signers + SP_PSBT_ERR_FIELD, // a silent payment field is malformed + SP_PSBT_ERR_INPUT, // an input breaks the BIP352 input rules + SP_PSBT_ERR_SIGHASH, // an input asks for a sighash other than ALL + SP_PSBT_ERR_INPUT_KEY, // an eligible input names no key its script hashes + SP_PSBT_ERR_KEYS, // the silent payment keys could not be derived + SP_PSBT_ERR_CRYPTO, // a share, proof or output key could not be made + SP_PSBT_ERR_SCRIPT, // a preset output script differs from the derived one + SP_PSBT_ERR_PSBT, // the completed PSBT fails strict validation +} sp_psbt_result_t; + +// True if any output carries PSBT_OUT_SP_V0_INFO. +bool sp_psbt_has_outputs(const struct wally_psbt *psbt); + +// True if the PSBT carries any BIP375 or BIP376 field. Such a PSBT holds no +// key origin to read a network from. +bool sp_psbt_has_fields(const struct wally_psbt *psbt); + +// True if some output has no script and every such output carries +// PSBT_OUT_SP_V0_INFO: the scripts a BIP375 signer derives. +bool sp_psbt_outputs_pending(const struct wally_psbt *psbt); + +// The scan and spend public keys of an output's PSBT_OUT_SP_V0_INFO. False +// when the output has none or it is malformed. +KERN_WARN_UNUSED_RESULT bool +sp_output_keys(const struct wally_psbt_output *output, unsigned char *scan_out, + unsigned char *spend_out); + +// BIP375 signer pass with the loaded seed's keys (signer.rs SpSigner). Holding +// every eligible input, it writes a global ECDH share and DLEQ proof per scan +// key; holding some, a per-input share and proof for each of those. Our keys +// are proven against the scripts they spend; another signer's share must +// verify against its input's key. Once a scan key's shares cover every +// eligible input, its output scripts are derived from them and the +// transaction is frozen. SP_PSBT_OK when every script is set, *psbt replaced +// by its strictly re-parsed copy; SP_PSBT_PENDING when a scan key still waits +// for another signer's share, *psbt holding our shares and no signature may +// be added yet. On failure *psbt is left untouched. A v0 PSBT with silent +// payment fields is refused. +KERN_WARN_UNUSED_RESULT sp_psbt_result_t +sp_psbt_complete(struct wally_psbt **psbt, bool is_testnet); + +// True when input `i` spends one of our silent payment outputs: its +// PSBT_IN_SP_TWEAK added to our spend key reproduces its P2TR output key. +bool sp_psbt_input_is_ours(const struct wally_psbt *psbt, size_t i, + bool is_testnet); + +typedef enum { + SP_OUTPUT_FOREIGN, // not ours, or not a silent payment output + SP_OUTPUT_CHANGE, // the account's scan key, our spend key labeled m = 0 + SP_OUTPUT_SELF, // the account's scan key, our spend key unlabeled or + // labeled m > 0 +} sp_output_ownership_t; + +// Whose silent payment output `i` is, for the account of our spend key with +// `scan_secret`, or with our scan key when NULL. PSBT_OUT_SP_V0_LABEL, when +// present, must label our spend key into the output's one; without it, the +// change label and the unlabeled key are tried. +sp_output_ownership_t sp_psbt_output_ownership(const struct wally_psbt *psbt, + size_t i, + const unsigned char *scan_secret, + bool is_testnet); + +// Key path signature of our silent payment input `i`, made with the tweaked +// spend key and no taproot tweak, since the output key already is BIP352's. +KERN_WARN_UNUSED_RESULT bool sp_psbt_sign_input(struct wally_psbt *psbt, + size_t i, bool is_testnet); + +// Copies the BIP375 global, input share and output fields of `from` into its +// trimmed copy `to`, and writes TX_MODIFIABLE explicitly once frozen: bwk's +// verify_signed wants the field present, while libwally leaves out a zero one. +KERN_WARN_UNUSED_RESULT bool sp_psbt_copy_fields(const struct wally_psbt *from, + struct wally_psbt *to); + +// A BIP375 ECDH share and its DLEQ proof for one scan key: global, or for +// the input at input_index +typedef struct { + bool global; + size_t input_index; + unsigned char scan[SP_PUBKEY_LEN]; + unsigned char share[SP_PUBKEY_LEN]; + unsigned char proof[DLEQ_PROOF_LEN]; +} sp_share_t; + +// The shares and proofs the loaded seed contributed, as sp_psbt_complete() +// writes them: per distinct scan key of the silent payment outputs, in output +// order, the global one when the seed holds every eligible input, else one +// per eligible input it holds. False when one is missing or malformed. +// On success *out must be freed with free(); it is NULL when the seed holds +// no eligible input. +KERN_WARN_UNUSED_RESULT bool sp_psbt_shares_alloc(const struct wally_psbt *psbt, + bool is_testnet, + sp_share_t **out, + size_t *count); + +// BIP174 serialization of `psbt`, leaving out the PSBT_OUT_SCRIPT of a silent +// payment output whose script is still pending, as BIP375 lets it. +// On success *out must be freed with free(). +KERN_WARN_UNUSED_RESULT bool +sp_psbt_serialize_alloc(const struct wally_psbt *psbt, uint8_t **out, + size_t *out_len); + +// sp_psbt_serialize_alloc() in base64. On success *out must be freed with +// wally_free_string(). +KERN_WARN_UNUSED_RESULT bool sp_psbt_base64_alloc(const struct wally_psbt *psbt, + char **out); + +// False when an input map of the serialized PSBT `data` carries a +// PSBT_IN_SIGHASH_TYPE other than SIGHASH_ALL, which BIP375 refuses with +// silent payment outputs. libwally keeps an explicit SIGHASH_DEFAULT (0) the +// way it keeps an absent field, so only the raw maps tell them apart. +bool sp_psbt_raw_sighash_is_all(const uint8_t *data, size_t len, + size_t num_inputs); + +const char *sp_psbt_result_message(sp_psbt_result_t result); + +#endif // SP_PSBT_H diff --git a/main/core/storage.c b/main/core/storage.c index 063a33f5..8c401565 100644 --- a/main/core/storage.c +++ b/main/core/storage.c @@ -521,6 +521,8 @@ static const char *descriptor_ext(storage_descriptor_format_t format) { return STORAGE_DESCRIPTOR_EXT_KEF; case STORAGE_DESCRIPTOR_BIP138: return STORAGE_DESCRIPTOR_EXT_BIP138; + case STORAGE_DESCRIPTOR_SP_ACCOUNT: + return STORAGE_DESCRIPTOR_EXT_SP_ACCOUNT; default: return STORAGE_DESCRIPTOR_EXT_TXT; } @@ -534,6 +536,8 @@ storage_descriptor_format_t storage_descriptor_format(const char *filename) { return STORAGE_DESCRIPTOR_BIP138; if (filename_has_ext(filename, STORAGE_DESCRIPTOR_EXT_KEF)) return STORAGE_DESCRIPTOR_KEF; + if (filename_has_ext(filename, STORAGE_DESCRIPTOR_EXT_SP_ACCOUNT)) + return STORAGE_DESCRIPTOR_SP_ACCOUNT; return STORAGE_DESCRIPTOR_TXT; } @@ -564,8 +568,9 @@ esp_err_t storage_load_descriptor(storage_location_t loc, const char *filename, esp_err_t storage_list_descriptors(storage_location_t loc, char ***filenames_out, int *count_out) { const char *exts[] = {STORAGE_DESCRIPTOR_EXT_KEF, STORAGE_DESCRIPTOR_EXT_TXT, - STORAGE_DESCRIPTOR_EXT_BIP138}; - return item_list(&descriptor_config, loc, exts, 3, filenames_out, count_out); + STORAGE_DESCRIPTOR_EXT_BIP138, + STORAGE_DESCRIPTOR_EXT_SP_ACCOUNT}; + return item_list(&descriptor_config, loc, exts, 4, filenames_out, count_out); } esp_err_t storage_delete_descriptor(storage_location_t loc, diff --git a/main/core/storage.h b/main/core/storage.h index a7ed0c61..9defa9f7 100644 --- a/main/core/storage.h +++ b/main/core/storage.h @@ -41,6 +41,7 @@ typedef enum { #define STORAGE_DESCRIPTOR_EXT_TXT ".txt" #define STORAGE_DESCRIPTOR_EXT_BIP138 ".bip138" #define STORAGE_DESCRIPTOR_EXT_BIP138_TXT ".bip138.txt" +#define STORAGE_DESCRIPTOR_EXT_SP_ACCOUNT ".spa" /* On-disk form of a descriptor file, selected by its extension. KEF files are * raw on flash and base64 text on SD. BIP138 files are raw binary everywhere; @@ -49,6 +50,8 @@ typedef enum { STORAGE_DESCRIPTOR_TXT = 0, /* plaintext descriptor */ STORAGE_DESCRIPTOR_KEF, /* password-encrypted KEF envelope */ STORAGE_DESCRIPTOR_BIP138, /* BIP138 container keyed to the descriptor */ + /* alias registered for the seed's silent payment account, flash only */ + STORAGE_DESCRIPTOR_SP_ACCOUNT, } storage_descriptor_format_t; /** @@ -175,7 +178,7 @@ KERN_WARN_UNUSED_RESULT esp_err_t storage_load_descriptor( storage_descriptor_format_t storage_descriptor_format(const char *filename); /** - * List stored descriptor files (.kef, .txt and .bip138 forms). + * List stored descriptor files (.kef, .txt, .bip138 and .spa forms). */ KERN_WARN_UNUSED_RESULT esp_err_t storage_list_descriptors( storage_location_t loc, char ***filenames_out, int *count_out); diff --git a/main/core/test/.gitignore b/main/core/test/.gitignore index c5602c81..72656786 100644 --- a/main/core/test/.gitignore +++ b/main/core/test/.gitignore @@ -44,3 +44,10 @@ test_self_test fuzz_psbt fuzz_descriptor fuzz_text +test_silentpayments +test_dleq +test_sp_keys +test_sp_psbt +test_musig_psbt +test_nonce_cache +kern_bipqr/ diff --git a/main/core/test/Makefile b/main/core/test/Makefile index 6720b878..c81799cc 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -14,9 +14,9 @@ endif ROOT = ../../.. WALLY_DIR = $(ROOT)/components/libwally-core -WALLY_SRC = $(WALLY_DIR)/upstream/src/amalgamation/combined.c +WALLY_SRC = $(WALLY_DIR)/kern_combined.c WALLY_INC = $(WALLY_DIR)/upstream/include -WALLY_DEPS := $(WALLY_DIR)/config.h $(wildcard $(WALLY_INC)/*.h) \ +WALLY_DEPS := $(WALLY_DIR)/config.h $(WALLY_DIR)/kern_bech32.h $(wildcard $(WALLY_INC)/*.h) \ $(shell find $(WALLY_DIR)/upstream/src -name '*.[ch]' -o -name '*.inl' 2>/dev/null) WALLY_PRIV_INCS = \ @@ -29,7 +29,7 @@ WALLY_PRIV_INCS = \ # HAVE_PSA_CRYPTO_H: hash through PSA like the device build, so its glue and # the uncached BIP341 path are what the tests run. Every libwally link line # then needs -lmbedcrypto. -WALLY_DEFS = -DBUILD_MINIMAL=1 -DBUILD_STANDARD_SECP=1 -DECMULT_WINDOW_SIZE=8 \ +WALLY_DEFS = -DBUILD_MINIMAL=1 -DECMULT_WINDOW_SIZE=8 \ -DHAVE_PSA_CRYPTO_H $(SANITIZE_WALLY_DEFS) WALLY_CFLAGS = $(WALLY_PRIV_INCS) $(WALLY_DEFS) @@ -37,7 +37,8 @@ WALLY_CFLAGS = $(WALLY_PRIV_INCS) $(WALLY_DEFS) ESP_STUBS_INC = stubs # Test includes: wally public headers + esp stubs + main source tree -TEST_INCS = -I$(ROOT)/components/bip138/include -I$(WALLY_INC) -I$(WALLY_DIR) -I$(ROOT)/components/secure_memory/include -I$(ESP_STUBS_INC) -I$(ROOT)/main +TEST_INCS = -I$(ROOT)/components/bip138/include -I$(WALLY_INC) \ + -I$(WALLY_DIR)/upstream/src/secp256k1/include -I$(WALLY_DIR) -I$(ROOT)/components/secure_memory/include -I$(ESP_STUBS_INC) -I$(ROOT)/main # KEF pulls in crypto_utils/entropy_pool/deflate_codec, which need a handful of # ESP-IDF headers. Reuse the simulator's stub headers instead of a second copy; @@ -54,6 +55,18 @@ HOST_PBKDF2 = $(ROOT)/simulator/platform/esp_idf_stubs/pbkdf2_sim.c LIBWALLY = libwally.a +# kern-bipqr, the firmware's Rust staticlib, built for the host: the MuSig2 +# signer reaches its nonce cache sessions through it. Its C headers are those +# of the bipqr and bip_nonces_cache submodules. +BIPQR_INCS = -I$(ROOT)/components/bipqr/upstream/bipqr-ll/include \ + -I$(ROOT)/components/bip_nonces_cache/upstream/bip-nonces-cache-ll/include +KERN_BIPQR_DIR = kern_bipqr +KERN_BIPQR = $(KERN_BIPQR_DIR)/release/libkern_bipqr.a +KERN_BIPQR_LIBS = $(KERN_BIPQR) -lpthread -ldl +# The simulator's NVS, kept in files under the data dir a test sets +NVS_SIM_SRC = $(ROOT)/simulator/platform/esp_idf_stubs/nvs_sim.c +NONCE_CACHE_SRC = ../nonce_cache.c ../nonce_cache.h + # Headers outside main/core that the tests compile, over-approximated: a full # rebuild takes seconds. COMMON_H = ../../utils/attributes.h $(shell find stubs $(SIM_STUBS_INC) -name '*.h') \ @@ -84,20 +97,24 @@ TARGET_PSB = test_purpose_binding SRCS_REG_MATCH = test_registry_match.c TARGET_REG_MATCH = test_registry_match REGISTRY_SRC = ../registry.c $(REGISTRY_H) ../descriptor_validator.h ../miniscript_policy.h \ - ../bip138_backup.h ../bip138_keys.h ../descriptor_checksum.h ../key.h ../../utils/secure_mem.h + ../bip138_backup.h ../bip138_keys.h ../descriptor_checksum.h ../key.h ../../utils/secure_mem.h \ + ../descriptor_keys.c ../descriptor_keys.h ../silent_payments.h DESCRIPTOR_CHECKSUM_SRC = ../descriptor_checksum.c ../descriptor_checksum.h -# Kern's libwally descriptor parse flags, linked by every test that parses. -DESCRIPTOR_PARSE_SRC = ../descriptor_parse.c ../wallet.h +# Kern's libwally descriptor parse flags and its musig() leaf rewrite, linked +# by every test that parses; the rewrite needs descriptor_checksum.c too. +DESCRIPTOR_PARSE_SRC = ../descriptor_parse.c ../wallet.h ../musig_leaves.c ../musig_leaves.h ../descriptor_checksum.c BIP32_PATH_SRC = ../bip32_path.c $(SS_H) 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 -PSBT_SRC = ../psbt.c ../psbt_internal.h ../key.h $(PSBT_H) +PSBT_SRC = ../psbt.c ../psbt_internal.h ../key.h $(PSBT_H) ../musig_psbt.c ../musig_psbt.h SRCS_PSBT_CLASSIFY = test_psbt_classify.c TARGET_PSBT_CLASSIFY = test_psbt_classify PSBT_KEY_OBJ = test_psbt_key.o @@ -193,7 +210,7 @@ SRCS_SELF_TEST = test_self_test.c TARGET_SELF_TEST = test_self_test SELF_TEST_SRC = ../self_test.c ../self_test.h ../crypto_init.c ../crypto_init.h \ ../secp_hardening.c ../secp_hardening.h ../message_sign.c ../message_sign.h \ - ../dice_mnemonic.c ../dice_mnemonic.h ../descriptor_parse.c ../wallet.h \ + ../dice_mnemonic.c ../dice_mnemonic.h ../descriptor_parse.c ../musig_leaves.c ../descriptor_checksum.c ../wallet.h \ $(KEY_SRC) $(SCRIPT_TEMPLATE_SRC) $(CRYPTO_UTILS_SRC) # libwally's own descriptor vectors (taptrees, multi_a), against the library @@ -208,11 +225,35 @@ TARGET_MNEMONIC_WORDS = test_mnemonic_words SRCS_DESCRIPTOR_BRANCH = test_descriptor_branch.c TARGET_DESCRIPTOR_BRANCH = test_descriptor_branch +SRCS_SILENTPAYMENTS = test_silentpayments.c +TARGET_SILENTPAYMENTS = test_silentpayments + +SRCS_DLEQ = test_dleq.c +TARGET_DLEQ = test_dleq +DLEQ_SRC = ../dleq.c ../dleq.h + +SRCS_SP_KEYS = test_sp_keys.c +TARGET_SP_KEYS = test_sp_keys +SP_SRC = ../silent_payments.c ../silent_payments.h + +SRCS_SP_PSBT = test_sp_psbt.c +TARGET_SP_PSBT = test_sp_psbt +# The BIP375 signer and what it pulls in, past key.c and its helpers +SP_PSBT_SRC = ../sp_psbt.c ../sp_psbt.h $(SP_SRC) $(DLEQ_SRC) $(CRYPTO_UTILS_SRC) +SP_PSBT_LINK = ../sp_psbt.c ../silent_payments.c ../dleq.c ../crypto_utils.c \ + ../entropy_pool.c stubs/esp_hw_stub.c $(HOST_PBKDF2) + +SRCS_MUSIG_PSBT = test_musig_psbt.c +TARGET_MUSIG_PSBT = test_musig_psbt + +SRCS_NONCE_CACHE = test_nonce_cache.c +TARGET_NONCE_CACHE = test_nonce_cache + SRCS_MULTISIG_SETUP = test_multisig_setup.c TARGET_MULTISIG_SETUP = test_multisig_setup MULTISIG_SETUP_SRC = ../multisig_setup.c ../multisig_setup.h -all: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) +all: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) $(TARGET_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) $(TARGET_MUSIG_PSBT) $(TARGET_NONCE_CACHE) $(LIBWALLY): $(WALLY_SRC) $(WALLY_DEPS) $(WALLY_DIR)/kern_wally.c $(WALLY_DIR)/kern_wally.h $(ROOT)/components/secure_memory/secret_alloc.c $(ROOT)/components/secure_memory/include/secure_memory.h Makefile $(CC) $(CFLAGS) $(WALLY_CFLAGS) -c -o combined.o $< @@ -220,7 +261,7 @@ $(LIBWALLY): $(WALLY_SRC) $(WALLY_DEPS) $(WALLY_DIR)/kern_wally.c $(WALLY_DIR)/k $(CC) $(CFLAGS) -I$(ROOT)/components/secure_memory/include -c -o secret_alloc.o $(ROOT)/components/secure_memory/secret_alloc.c ar rcs $@ combined.o kern_wally.o secret_alloc.o -$(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) $(CRYPTO_INIT_LIB): $(COMMON_H) +$(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) $(TARGET_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) $(TARGET_MUSIG_PSBT) $(TARGET_NONCE_CACHE) $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) $(CRYPTO_INIT_LIB): $(COMMON_H) $(TARGET_DERIV): $(SRCS_DERIV) $(BIP32_PATH_SRC) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DERIV) ../bip32_path.c @@ -238,19 +279,19 @@ $(TARGET_PSB): $(SRCS_PSB) $(SS_SRC) $(KEY_STUB_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_PSB) ../ss_whitelist.c ../script_templates.c $(KEY_STUB_SRC) $(LIBWALLY) -lmbedcrypto $(TARGET_REG_MATCH): $(SRCS_REG_MATCH) $(REGISTRY_SRC) $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) $(BIP32_PATH_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(REGISTRY_STUB_SRC) $(LIBWALLY) - $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_REG_MATCH) ../registry.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../bip32_path.c ../descriptor_checksum.c ../descriptor_parse.c $(REGISTRY_STUB_SRC) $(LIBWALLY) -lmbedcrypto + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_REG_MATCH) ../registry.c ../descriptor_keys.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../bip32_path.c ../descriptor_checksum.c ../descriptor_parse.c ../musig_leaves.c $(REGISTRY_STUB_SRC) $(LIBWALLY) -lmbedcrypto $(TARGET_REG_PARSE): $(SRCS_REG_PARSE) $(REGISTRY_SRC) $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) $(BIP32_PATH_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(REGISTRY_STUB_SRC) $(LIBWALLY) - $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_REG_PARSE) ../registry.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../bip32_path.c ../descriptor_checksum.c ../descriptor_parse.c $(REGISTRY_STUB_SRC) $(LIBWALLY) -lmbedcrypto + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_REG_PARSE) ../registry.c ../descriptor_keys.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../bip32_path.c ../descriptor_checksum.c ../descriptor_parse.c ../musig_leaves.c $(REGISTRY_STUB_SRC) $(LIBWALLY) -lmbedcrypto $(PSBT_KEY_OBJ): $(KEY_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -Dkey_get_fingerprint=key_get_fingerprint_raw -c -o $@ ../key.c -$(TARGET_PSBT_CLASSIFY): $(SRCS_PSBT_CLASSIFY) ../settings.h $(PSBT_SRC) ../psbt_gate.c ../psbt_gate.h $(SS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(LIBWALLY) $(PSBT_KEY_OBJ) $(CRYPTO_INIT_LIB) - $(CC) $(CFLAGS) $(TEST_INCS) -DPSBT_TESTING -Wl,--wrap=malloc -Wl,--wrap=wally_psbt_signing_cache_disable -Wl,--wrap=wally_descriptor_to_script -o $@ $(SRCS_PSBT_CLASSIFY) $(PSBT_KEY_OBJ) ../ss_whitelist.c ../registry.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../psbt.c ../psbt_gate.c ../bip32_path.c ../script_templates.c ../descriptor_checksum.c ../descriptor_parse.c $(CRYPTO_INIT_LIB) $(LIBWALLY) -lmbedcrypto +$(TARGET_PSBT_CLASSIFY): $(SRCS_PSBT_CLASSIFY) sp_fixture.h ../settings.h $(PSBT_SRC) ../psbt_gate.c ../psbt_gate.h ../psbt_parse.c $(SS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(SP_PSBT_SRC) $(NONCE_CACHE_SRC) $(LIBWALLY) $(PSBT_KEY_OBJ) $(CRYPTO_INIT_LIB) $(KERN_BIPQR) + $(CC) $(CFLAGS) $(KEF_INCS) $(BIPQR_INCS) -DPSBT_TESTING -Wl,--wrap=malloc -Wl,--wrap=wally_psbt_signing_cache_disable -Wl,--wrap=wally_descriptor_to_script -o $@ $(SRCS_PSBT_CLASSIFY) $(PSBT_KEY_OBJ) ../ss_whitelist.c ../registry.c ../descriptor_keys.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../psbt.c ../psbt_gate.c ../psbt_parse.c ../musig_psbt.c ../nonce_cache.c $(NVS_SIM_SRC) ../bip32_path.c ../script_templates.c ../descriptor_checksum.c ../descriptor_parse.c ../musig_leaves.c $(SP_PSBT_LINK) $(CRYPTO_INIT_LIB) $(LIBWALLY) $(KERN_BIPQR_LIBS) -lmbedcrypto -$(TARGET_PSBT_PARSE): $(SRCS_PSBT_PARSE) ../psbt_parse.c $(PSBT_H) $(LIBWALLY) - $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_PSBT_PARSE) ../psbt_parse.c $(LIBWALLY) -lmbedcrypto +$(TARGET_PSBT_PARSE): $(SRCS_PSBT_PARSE) ../psbt_parse.c $(PSBT_H) $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SP_PSBT_SRC) $(LIBWALLY) + $(CC) $(CFLAGS) $(KEF_INCS) -o $@ $(SRCS_PSBT_PARSE) ../psbt_parse.c ../key.c ../bip32_path.c ../descriptor_checksum.c ../musig_leaves.c $(SP_PSBT_LINK) $(LIBWALLY) -lmbedcrypto $(TARGET_MS_POLICY): $(SRCS_MS_POLICY) $(MS_POLICY_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_MS_POLICY) ../miniscript_policy.c $(LIBWALLY) -lmbedcrypto @@ -281,9 +322,9 @@ $(TARGET_FW_UPDATE): $(SRCS_FW_UPDATE) $(FW_UPDATE_SRC) $(wildcard stubs/*.h) # firmware build carries -Wno-format for the same reason. $(TARGET_DESC_VALIDATOR): $(SRCS_DESC_VALIDATOR) $(DESC_VALIDATOR_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(REGISTRY_PERSIST_STUB_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(SS_SRC) $(LIBWALLY) $(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_validator.c ../wallet.c ../descriptor_parse.c ../musig_leaves.c ../key.c ../registry.c ../descriptor_keys.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. @@ -318,21 +359,21 @@ $(TARGET_PBKDF2): $(SRCS_PBKDF2) $(PBKDF2_OBJ) $(CRYPTO_UTILS_SRC) ../entropy_pool.c stubs/esp_hw_stub.c -lmbedcrypto $(TARGET_BIP138_KEYS): $(SRCS_BIP138_KEYS) ../bip138_keys.c ../bip138_keys.h ../bip32_path.h ../storage.h ../wallet.h $(DESCRIPTOR_PARSE_SRC) $(REGISTRY_STUB_SRC) $(BIP138_DIR)/test/vectors.h $(LIBWALLY) - $(CC) $(CFLAGS) $(TEST_INCS) $(BIP138_INCS) -o $@ $(SRCS_BIP138_KEYS) ../bip138_keys.c ../descriptor_parse.c $(REGISTRY_STUB_SRC) $(LIBWALLY) -lmbedcrypto + $(CC) $(CFLAGS) $(TEST_INCS) $(BIP138_INCS) -o $@ $(SRCS_BIP138_KEYS) ../bip138_keys.c ../descriptor_keys.c ../descriptor_parse.c ../musig_leaves.c ../descriptor_checksum.c $(REGISTRY_STUB_SRC) $(LIBWALLY) -lmbedcrypto $(TARGET_BIP138_BACKUP): $(SRCS_BIP138_BACKUP) ../bip138_backup.c ../bip138_backup.h ../bip138_keys.c ../bip138_keys.h ../bip138_crypto.c ../bip138_crypto.h $(CRYPTO_UTILS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(SS_SRC) $(DESC_VALIDATOR_SRC) $(BIP138_SRCS) $(LIBWALLY) $(CC) $(CFLAGS) $(KEF_INCS) $(BIP138_INCS) -DBIP138_BACKUP_TESTING -Wl,--wrap=wally_descriptor_parse -Wno-format-truncation -o $@ $(SRCS_BIP138_BACKUP) \ ../bip138_backup.c ../bip138_keys.c ../bip138_crypto.c \ ../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) + ../wallet.c ../descriptor_parse.c ../musig_leaves.c ../key.c ../registry.c ../descriptor_keys.c ../descriptor_validator.c ../descriptor_checksum.c ../bip32_path.c \ + ../script_templates.c ../ss_whitelist.c ../miniscript_policy.c ../silent_payments.c \ + $(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 + $(CC) $(CFLAGS) $(TEST_INCS) -Wl,--wrap=wally_descriptor_to_script -o $@ $(SRCS_ADDRESS_MATCH) ../address_match.c ../descriptor_branch.c ../descriptor_parse.c ../musig_leaves.c ../descriptor_checksum.c ../ss_whitelist.c ../key.c ../bip32_path.c ../script_templates.c $(LIBWALLY) -lmbedcrypto $(TARGET_DESCRIPTOR_TEXT): $(SRCS_DESCRIPTOR_TEXT) $(DESCRIPTOR_TEXT_SRC) $(DESCRIPTOR_CHECKSUM_SRC) ../../utils/text_file.c ../../utils/text_file.h $(LIBWALLY) - $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DESCRIPTOR_TEXT) ../descriptor_text.c ../descriptor_checksum.c ../../utils/text_file.c $(LIBWALLY) -lmbedcrypto + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DESCRIPTOR_TEXT) ../descriptor_text.c ../descriptor_checksum.c ../musig_leaves.c ../../utils/text_file.c $(LIBWALLY) -lmbedcrypto $(TARGET_MESSAGE_SIGN): $(SRCS_MESSAGE_SIGN) ../message_sign.c ../message_sign.h ../message_validation.h ../crypto_init.c ../crypto_init.h ../secp_hardening.c ../secp_hardening.h $(KEY_SRC) $(SCRIPT_TEMPLATE_SRC) $(CRYPTO_UTILS_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(KEF_INCS) -o $@ $(SRCS_MESSAGE_SIGN) ../message_sign.c ../crypto_init.c ../secp_hardening.c ../key.c ../bip32_path.c ../script_templates.c \ @@ -340,7 +381,7 @@ $(TARGET_MESSAGE_SIGN): $(SRCS_MESSAGE_SIGN) ../message_sign.c ../message_sign.h $(TARGET_SELF_TEST): $(SRCS_SELF_TEST) $(SELF_TEST_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(KEF_INCS) -o $@ $(SRCS_SELF_TEST) ../self_test.c ../crypto_init.c \ - ../secp_hardening.c ../message_sign.c ../dice_mnemonic.c ../descriptor_parse.c \ + ../secp_hardening.c ../message_sign.c ../dice_mnemonic.c ../descriptor_parse.c ../musig_leaves.c ../descriptor_checksum.c \ ../key.c ../bip32_path.c ../script_templates.c ../crypto_utils.c ../entropy_pool.c \ stubs/esp_hw_stub.c $(HOST_PBKDF2) $(LIBWALLY) -lmbedcrypto @@ -354,11 +395,33 @@ $(TARGET_MNEMONIC_WORDS): $(SRCS_MNEMONIC_WORDS) ../../utils/bip39_filter.c ../. $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_MNEMONIC_WORDS) ../../utils/bip39_filter.c ../dice_mnemonic.c $(LIBWALLY) -lmbedcrypto $(TARGET_DESCRIPTOR_BRANCH): $(SRCS_DESCRIPTOR_BRANCH) ../descriptor_branch.c ../descriptor_branch.h ../psbt_internal.h $(PSBT_H) $(DESCRIPTOR_PARSE_SRC) $(LIBWALLY) - $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DESCRIPTOR_BRANCH) ../descriptor_branch.c ../descriptor_parse.c $(LIBWALLY) -lmbedcrypto + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DESCRIPTOR_BRANCH) ../descriptor_branch.c ../descriptor_parse.c ../musig_leaves.c ../descriptor_checksum.c $(LIBWALLY) -lmbedcrypto $(TARGET_MULTISIG_SETUP): $(SRCS_MULTISIG_SETUP) $(MULTISIG_SETUP_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_MULTISIG_SETUP) ../multisig_setup.c $(LIBWALLY) -lmbedcrypto +$(TARGET_SILENTPAYMENTS): $(SRCS_SILENTPAYMENTS) $(LIBWALLY) + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_SILENTPAYMENTS) $(LIBWALLY) -lmbedcrypto + +$(TARGET_DLEQ): $(SRCS_DLEQ) $(DLEQ_SRC) $(LIBWALLY) + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DLEQ) ../dleq.c $(LIBWALLY) -lmbedcrypto + +$(TARGET_SP_KEYS): $(SRCS_SP_KEYS) $(SP_SRC) $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(LIBWALLY) $(KERN_BIPQR) + $(CC) $(CFLAGS) $(TEST_INCS) $(BIPQR_INCS) -o $@ $(SRCS_SP_KEYS) ../silent_payments.c ../key.c ../bip32_path.c ../descriptor_checksum.c ../musig_leaves.c $(LIBWALLY) $(KERN_BIPQR_LIBS) -lmbedcrypto + +$(TARGET_SP_PSBT): $(SRCS_SP_PSBT) sp_fixture.h bip375_fixture.h $(SP_PSBT_SRC) ../psbt_parse.c $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(LIBWALLY) + $(CC) $(CFLAGS) $(KEF_INCS) -o $@ $(SRCS_SP_PSBT) ../psbt_parse.c ../key.c ../bip32_path.c ../descriptor_checksum.c ../musig_leaves.c $(SP_PSBT_LINK) $(LIBWALLY) -lmbedcrypto + +$(TARGET_MUSIG_PSBT): $(SRCS_MUSIG_PSBT) $(PSBT_SRC) ../psbt_gate.c ../psbt_gate.h ../psbt_parse.c $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(DESCRIPTOR_PARSE_SRC) $(SS_SRC) $(SP_PSBT_SRC) $(NONCE_CACHE_SRC) $(LIBWALLY) $(KERN_BIPQR) + $(CC) $(CFLAGS) $(KEF_INCS) $(BIPQR_INCS) -o $@ $(SRCS_MUSIG_PSBT) ../musig_psbt.c ../psbt.c ../psbt_gate.c ../psbt_parse.c ../registry.c ../descriptor_keys.c ../key.c ../wallet.c ../descriptor_parse.c ../musig_leaves.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../bip32_path.c ../descriptor_checksum.c ../ss_whitelist.c ../script_templates.c $(SP_PSBT_LINK) ../nonce_cache.c $(NVS_SIM_SRC) $(LIBWALLY) $(KERN_BIPQR_LIBS) -lmbedcrypto + +$(TARGET_NONCE_CACHE): $(SRCS_NONCE_CACHE) $(NONCE_CACHE_SRC) $(KEY_SRC) $(CRYPTO_UTILS_SRC) $(LIBWALLY) $(KERN_BIPQR) + $(CC) $(CFLAGS) $(KEF_INCS) $(BIPQR_INCS) -o $@ $(SRCS_NONCE_CACHE) ../nonce_cache.c ../key.c ../bip32_path.c ../crypto_utils.c ../entropy_pool.c stubs/esp_hw_stub.c $(HOST_PBKDF2) $(NVS_SIM_SRC) $(LIBWALLY) $(KERN_BIPQR_LIBS) -lmbedcrypto + +# 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 + # Fuzz targets for the glue around libwally that handles untrusted QR and SD # payloads (`just fuzz`). gcc builds link fuzz/fuzz_driver.c, a coverage-blind # mutation driver; with clang, LIBFUZZER=1 links libFuzzer instead. @@ -372,30 +435,30 @@ FUZZ_DEPS = $(FUZZ_DIR)/fuzz.h $(FUZZ_DIR)/fuzz_driver.c $(LIBWALLY) FUZZ_TARGETS = fuzz_psbt fuzz_descriptor fuzz_text FUZZ_ITERATIONS ?= 20000 -fuzz_psbt: $(FUZZ_DIR)/fuzz_psbt.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_DEPS) $(PSBT_SRC) $(REGISTRY_SRC) $(SS_SRC) $(KEY_SRC) $(BIP322_SRC) ../psbt_parse.c - $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(FUZZ_DIR)/fuzz_psbt.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_MAIN) \ - ../psbt.c ../psbt_parse.c ../bip322.c ../message_sign.c ../key.c ../registry.c \ +fuzz_psbt: $(FUZZ_DIR)/fuzz_psbt.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_DEPS) $(PSBT_SRC) $(REGISTRY_SRC) $(SS_SRC) $(KEY_SRC) $(BIP322_SRC) ../psbt_parse.c $(SP_PSBT_SRC) $(NONCE_CACHE_SRC) $(KERN_BIPQR) + $(CC) $(CFLAGS) $(KEF_INCS) $(BIPQR_INCS) -o $@ $(FUZZ_DIR)/fuzz_psbt.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_MAIN) \ + ../psbt.c ../psbt_parse.c ../bip322.c ../message_sign.c ../key.c ../registry.c ../descriptor_keys.c \ ../ss_whitelist.c ../bip32_path.c ../script_templates.c ../descriptor_checksum.c \ - ../descriptor_parse.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) \ - $(LIBWALLY) -lmbedcrypto + ../descriptor_parse.c ../musig_leaves.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) \ + ../musig_psbt.c ../nonce_cache.c $(NVS_SIM_SRC) $(SP_PSBT_LINK) $(LIBWALLY) $(KERN_BIPQR_LIBS) -lmbedcrypto fuzz_descriptor: $(FUZZ_DIR)/fuzz_descriptor.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_DEPS) $(DESC_VALIDATOR_SRC) $(REGISTRY_SRC) $(SS_SRC) $(KEY_SRC) $(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 \ + ../descriptor_validator.c ../wallet.c ../descriptor_parse.c ../musig_leaves.c ../key.c ../registry.c ../descriptor_keys.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 \ ../bip32_path.c ../script_templates.c ../multisig_setup.c ../descriptor_text.c \ - ../descriptor_checksum.c ../../utils/text_file.c $(LIBWALLY) -lmbedcrypto + ../descriptor_checksum.c ../musig_leaves.c ../../utils/text_file.c $(LIBWALLY) -lmbedcrypto fuzz: $(FUZZ_TARGETS) ./fuzz_psbt -n $(FUZZ_ITERATIONS) @json:$(WALLY_DIR)/upstream/src/data/psbt.json ./fuzz_descriptor -n $(FUZZ_ITERATIONS) $(FUZZ_DIR)/corpus/text ./fuzz_text -n $(FUZZ_ITERATIONS) $(FUZZ_DIR)/corpus/text -run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) +run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) $(TARGET_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) $(TARGET_MUSIG_PSBT) $(TARGET_NONCE_CACHE) ./$(TARGET_DERIV) ./$(TARGET_SS_PARSE) ./$(TARGET_SS_WHITELISTED) @@ -428,8 +491,15 @@ run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REG ./$(TARGET_MNEMONIC_WORDS) ./$(TARGET_DESCRIPTOR_BRANCH) ./$(TARGET_SELF_TEST) + ./$(TARGET_SILENTPAYMENTS) + ./$(TARGET_DLEQ) + ./$(TARGET_SP_KEYS) + ./$(TARGET_SP_PSBT) + ./$(TARGET_MUSIG_PSBT) + ./$(TARGET_NONCE_CACHE) clean: - rm -f $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) $(FUZZ_TARGETS) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) $(CRYPTO_INIT_LIB) $(CRYPTO_INIT_OBJS) + rm -f $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REGEN) $(TARGET_PSB) $(TARGET_REG_MATCH) $(TARGET_REG_PARSE) $(TARGET_PSBT_CLASSIFY) $(TARGET_MS_POLICY) $(TARGET_BIP322) $(TARGET_ESTIMATED_ENTROPY) $(TARGET_UTF8) $(TARGET_PIN_ATTEMPT) $(TARGET_KEF) $(TARGET_PSBT_PARSE) $(TARGET_FW_UPDATE) $(TARGET_DESC_VALIDATOR) $(TARGET_STORAGE) $(TARGET_KEY) $(TARGET_CRYPTO_UTILS) $(TARGET_PBKDF2) $(TARGET_BIP138_KEYS) $(TARGET_BIP138_BACKUP) $(TARGET_MULTISIG_SETUP) $(TARGET_ADDRESS_MATCH) $(TARGET_DESCRIPTOR_TEXT) $(TARGET_MESSAGE_SIGN) $(TARGET_WALLY_DESCRIPTOR) $(TARGET_SEEDQR) $(TARGET_MNEMONIC_WORDS) $(TARGET_DESCRIPTOR_BRANCH) $(TARGET_SELF_TEST) $(TARGET_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) $(TARGET_MUSIG_PSBT) $(TARGET_NONCE_CACHE) $(FUZZ_TARGETS) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) $(CRYPTO_INIT_LIB) $(CRYPTO_INIT_OBJS) + rm -rf $(KERN_BIPQR_DIR) -.PHONY: all run clean fuzz +.PHONY: all run clean fuzz $(KERN_BIPQR) diff --git a/main/core/test/bip375_fixture.h b/main/core/test/bip375_fixture.h new file mode 100644 index 00000000..53d46ce1 --- /dev/null +++ b/main/core/test/bip375_fixture.h @@ -0,0 +1,1232 @@ +#ifndef BIP375_FIXTURE_H +#define BIP375_FIXTURE_H + +#include "core/sp_psbt.h" + +/* BIP375 test vectors (bips bip-0375/bip375_test_vectors.json), as hex. */ + +#define BIP375_MAX_OUTPUTS 6 +#define BIP375_PARSE_REFUSED (-1) + +/* A "can finalize" vector with the silent payment output scripts left out, + * and those scripts by output index (NULL for another output) */ +typedef struct { + const char *name; + const char *psbt; + const char *scripts[BIP375_MAX_OUTPUTS]; +} bip375_derivation_t; + +/* A vector and the result sp_psbt_complete() gives it, or + * BIP375_PARSE_REFUSED when psbt_parse_payload() refuses it */ +typedef struct { + const char *name; + const char *psbt; + int result; +} bip375_result_t; + +static const bip375_derivation_t BIP375_DERIVATIONS[] = { + {"can finalize: one P2PKH input single-signer", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "20522748eb17764d28ca494815ec8d49e7d30d52bc73422c7c86eb74e39705729401" + "0f04000000000100550200000001f4c212d5aed1e7f6ff633f2ce09c647c57bedd93" + "0314d98de77503d58e940b330000000000ffffffff01a0860100000000001976a914" + "1e2ad7872d329413a56df0968be338222783163b88ac00000000220202c817bb7521" + "afc35ea96f3bfb270e6eb50ddffa5560627b961fec00f2996508bf473044022039c1" + "0dcbc7cf45c6d94356ff50c12b8d86a9550cf037173d9cebf78714e67c7502207195" + "5a42ed205324320723c4f01425dce89f425f8370284cb4276cfdb6dea3ac01010304" + "01000000220602c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec00" + "f2996508bf080000008000000000011004feffffff221d027a487fc19fb769877b87" + "42d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103eca4ff11b728e2e0f60c" + "e6222943a6ff55b9d95f627bf9a99d084bc872d50a5b221e027a487fc19fb769877b" + "8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068408a13b3985545f72bd6e8" + "9714aeb909b3e354a842a9bb8b56cd0eded21df8a199598b31228a49e0bd7e95ce10" + "53f7c5b28acb543a68707600e3ce89822ee320210001030818730100000000000109" + "42027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068" + "0361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fce03900", + {"5120e140d287b45b46cd4eaafa4377061570babe83d1b8bc950a74a9fea09233d7a6"}}, + {"can finalize: two inputs single-signer using global ECDH share", + "70736274ff01fb040200000001020402000000010401020105010101060100220702" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682102" + "d3262723352607e84fcaf7651f8d2d637e020aea86dfad80d306cd4f48cfcc622208" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06840" + "c653b71f946818a95bdc39f0918445bc903a0876b738060e9e5db1dcec30abdf54e0" + "b5f178573f5119de71aa63ad19b449e3bcb65463936c8baeea4d917392b900010e20" + "18a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a010f" + "040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb81" + "c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec" + "00f2996508bf47304402201705fcda06266edb32b1698677b37f67bb6e45d492ebfc" + "e656a880ee7f138eb602203dcde3239dd90636af64fb2412ca41e397c958a030777c" + "ff9c8940b9c777d74c01220602c817bb7521afc35ea96f3bfb270e6eb50ddffa5560" + "627b961fec00f2996508bf080000008000000000011004feffffff00010e20be9d65" + "c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f040000" + "000001011fa086010000000000160014139350117c577941a985802bb9edefc11393" + "2bc7220202f5b59fa5e492221ebf55ba78ad442605beae95166ba1eba3250d0bbaac" + "7e2edc47304402200389b1e0aeefd7fab609efab018bfb016acff21bb810f3c48c38" + "ba7244180e950220150fec60e256f40c47574dfd129a08eaf7ac1d97abee31f40699" + "f879354619f301220602f5b59fa5e492221ebf55ba78ad442605beae95166ba1eba3" + "250d0bbaac7e2edc080000008001000000011004feffffff00010308187301000000" + "0000010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8" + "fce03900", + {"5120133d6a4f509095b5794f7491fbc3f12c3c45bc2d9b60af25b8bba704c8072aaf"}}, + {"can finalize: two inputs single-signer using per-input ECDH shares", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf47304402201705fcda06266edb32b1698677b37f67bb6e45d492eb" + "fce656a880ee7f138eb602203dcde3239dd90636af64fb2412ca41e397c958a03077" + "7cff9c8940b9c777d74c01220602c817bb7521afc35ea96f3bfb270e6eb50ddffa55" + "60627b961fec00f2996508bf080000008000000000011004feffffff221d027a487f" + "c19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103eca4ff" + "11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b221e027a48" + "7fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068408a13b3" + "985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199598b31228a" + "49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee3202100010e20be9d65" + "c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f040000" + "000001011fa086010000000000160014139350117c577941a985802bb9edefc11393" + "2bc7220202f5b59fa5e492221ebf55ba78ad442605beae95166ba1eba3250d0bbaac" + "7e2edc47304402200389b1e0aeefd7fab609efab018bfb016acff21bb810f3c48c38" + "ba7244180e950220150fec60e256f40c47574dfd129a08eaf7ac1d97abee31f40699" + "f879354619f30101030401000000220602f5b59fa5e492221ebf55ba78ad442605be" + "ae95166ba1eba3250d0bbaac7e2edc080000008001000000011004feffffff221d02" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103" + "34d2cef74eded4464227607fc59ac1de80c12a2433a56271528edccf50fa6c2b221e" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06840" + "37c00c0b42a073f6b65f0c4b6e56e06774b380c1df3de28b640b121ee0b3b4cf7850" + "df456e0b5d8e1975ddff25262c8381e20f852cd870bde3f6a832a6325bcc00010308" + "1873010000000000010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c" + "6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d" + "3f19e57513a8fce03900", + {"5120133d6a4f509095b5794f7491fbc3f12c3c45bc2d9b60af25b8bba704c8072aaf"}}, + {"can finalize: two inputs / two sp outputs with mixed global and " + "per-input ECDH shares", + "70736274ff01fb040200000001020402000000010401020105010201060100220703" + "3361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d282103" + "66cfc7fdce06e08ed49b1b3952b8d151a8f7e075fe5f6dd58dd68f9dadeeca942208" + "033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d2840" + "5eab8b086d4850fe9d1c9f961a91f997b61ca8d0850afc06a78bdf3c749ef54050e6" + "92b53fb5b086e5e78793f01e76d3747f89e3177a7feff6f8c1617f1b06e300010e20" + "18a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a010f" + "040000000001011f400d030000000000160014229a72d34a645bd3496bbbf50bbb81" + "c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec" + "00f2996508bf483045022100d64e9ef024440046e9ca39302eb87b2df60dfc51c9c0" + "a917d682f3cf8105908c02201ebe12a5f1fd2196f2efb5d53afe57ce745b901fe889" + "978ad59aefe14a4f50370101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df47" + "15102103fbd173d9c48d58c5022426d05278bca17b9a8e2282666901a1b00b9e04b7" + "9949221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df" + "47151040c05da410487cfaec378febe6af5005e3ae6c86236818b0e55b214017eb50" + "73edef40179575b5dcdaa9063491ac8b83fd0624d4177a4d2dd4994c4640d6b8ccde" + "00010e20be9d65c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527a" + "b522010f040000000001011f400d030000000000160014139350117c577941a98580" + "2bb9edefc113932bc7220202f5b59fa5e492221ebf55ba78ad442605beae95166ba1" + "eba3250d0bbaac7e2edc47304402205a8279a6c87044f102c85930c89ec2ff019428" + "6241ada38c7854f2e83651d5f202202bcc664a9f9704d57312dbc2bc836867080f22" + "c4758b91dbb92d17a1e411eaa90101030401000000220602f5b59fa5e492221ebf55" + "ba78ad442605beae95166ba1eba3250d0bbaac7e2edc080000008001000000011004" + "feffffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0ab" + "a1df4715102103a6a89b1b986a995533e17bed64500b541bb0d739071efe2ae2b7ef" + "b0a0ca6bcf221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0" + "aba1df47151040c34a6a2940bbe9a7356c1cc6ffe358dd4441db58897cba99c212eb" + "75285e7da1eca11c792c97a380493345ab224de9d94c2b36ee8526ae23528171a323" + "1de73300010308905f010000000000010942033361d3ff72f34e6b4e7a7bef96e5b8" + "151e66a979adce753c39c583cbe5766d28031266581e3e841cbb94de62ea735583a2" + "32c4c888fa6edef2ec2f870789fc1dd400010308905f01000000000001094202a9f1" + "fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df471510024a48d7" + "6e20d40bcf5f2e1a5c3ffeb3dc2a8b3b88d79a486d54c9d9eaa8fa188e00", + {"512080eb98318bcf6dd611ac17a964b091736c04caeadf2e6e874e5cef86c7c60517", + "512010b62fc5a90abca0167961dbff4ceae9aa324efb2c7f246627e8b5a33de37c84"}}, + {"can finalize: one input / one sp output with both global and per-input " + "ECDH shares", + "70736274ff01fb040200000001020402000000010401010105010101060100220703" + "3361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d282103" + "0a18b9bb4199b89330eb17f8ee5ac786e0853dcd2f3ccdf1744b97ce4ede053e2208" + "033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d2840" + "27fb90c5d61c78e3115200ffd183d28d0ab4838062c9541934c6416d4267ce31bd42" + "87e9359452c0817af0ef4d50cff578436b0d28f9ed8f21b79a447640808e00010e20" + "18a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a010f" + "040000000001011f400d030000000000160014229a72d34a645bd3496bbbf50bbb81" + "c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec" + "00f2996508bf4730440220377a8f9f5a33d8fa255c33b39226d3bcf0229dfad96047" + "0ef8016a7142f233580220081bd694887adeeb3621af5a2de4f0d39cb13692d041bf" + "7dbccd34a32b0541e90101030401000000220602c817bb7521afc35ea96f3bfb270e" + "6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffffff" + "221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d" + "2821030a18b9bb4199b89330eb17f8ee5ac786e0853dcd2f3ccdf1744b97ce4ede05" + "3e221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe576" + "6d2840001383d4661be8725ef29048f48c911f89f5f34317d7c0c0acc60ef65f1b52" + "bfff7a96d8339b625df83abab57aa273edcd9a35c794dacbb1c861171bb267075f00" + "010308905f010000000000010942033361d3ff72f34e6b4e7a7bef96e5b8151e66a9" + "79adce753c39c583cbe5766d28031266581e3e841cbb94de62ea735583a232c4c888" + "fa6edef2ec2f870789fc1dd400", + {"5120dc4d44d9e361e5e7436579c78e25925541e229fdc153ad5989ad8ae6b0624c78"}}, + {"can finalize: three sp outputs (different scan keys) with multiple " + "global ECDH shares", + "70736274ff01fb040200000001020402000000010401020105010301060100220702" + "a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df4715102102" + "c2d9df60ee69a5a86604dd9a6282c22ef8e2c9276da6e595a5463f371aadee242207" + "033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d2821" + "02dc7d2ecac568b0115175ba3cd5496ff4c4b6d909422dbccaeb8f252fa54f8bd022" + "07038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007bf27286c" + "210270bef5c06a9a855fc63bff2bd0be2d70033c820b6153413c8d6eda51f25a1b29" + "220802a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df4715" + "1040ec8242bf7b5881cee060566c7f13cc47e4710c89a26458c20301b3031e48173b" + "c0bea01680d3375eb5e80611ab0d508b1e49abb571b1878032aae49f0b02f7d22208" + "033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d2840" + "ea43470e5e1be3291b48a0bcb53f55952c64860e7635efba5003ccaded77dd128e21" + "6697b0f523be217ec687507797cccebc5cd94362af1b46d803642bd5f9402208038e" + "d3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007bf27286c401bdf" + "e54ed4a2a06fff9b0009ae4e3d80fc47616475afdf21244cfe3c6d104df24741a875" + "514d78654fb9ca1118e6d3e552f38f8caba3552e8333c501bf0cbd3f00010e2018a7" + "17663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a010f0400" + "00000001011f20a1070000000000160014229a72d34a645bd3496bbbf50bbb81c906" + "3f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec00f2" + "996508bf4830450221008b8377a46ec1c64e3fd096f2e12305bb86badfcca0cfd9bf" + "57dc96229b9e708402207e7dc7ddeca8555c177ebeffc949ea4c33520fe5beec7ba7" + "e2727e34fbd48dfd01220602c817bb7521afc35ea96f3bfb270e6eb50ddffa556062" + "7b961fec00f2996508bf080000008000000000011004feffffff00010e20be9d65c8" + "3915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f04000000" + "0001011fa0860100000000001600144633d59cad1343479972e0c996921d0a5dadb6" + "5d22020243a0d40e9de0882794161752bae42ba90952784209f063430f0af256354a" + "85bb483045022100f9922defad52c6120904baa5a7005329836ec1c3dae16ca068c0" + "16b26b04d2d8022070f95f24f9c9256e41969469c352acfac8e894323502eacd163c" + "94a2e369ee1f0122060243a0d40e9de0882794161752bae42ba90952784209f06343" + "0f0af256354a85bb080000008001000000011004feffffff00010308905f01000000" + "0000010942033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cb" + "e5766d28031266581e3e841cbb94de62ea735583a232c4c888fa6edef2ec2f870789" + "fc1dd400010308905f01000000000001094202a9f1fac2cc457684f33de90073fe20" + "d22c947c92163b862b14d0aba1df471510024a48d76e20d40bcf5f2e1a5c3ffeb3dc" + "2a8b3b88d79a486d54c9d9eaa8fa188e00010308905f010000000000010942038ed3" + "220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007bf27286c03f81473" + "844c9d74c921ff17a5af410b6337348d7afbff73891bc5cb0cb24cb0c000", + {"5120a14fafdc7edfa404427174b126aca0e9993133fe17e2420aeaed20ef54fc38dc", + "51207df5f24959443414bbefe89d2da894864a5628b68033b923e8686bdcc3de9d94", + "5120b2f12a7f570cc5057840fa6393f71f06900142088181810c34bb88761d92950d"}}, + {"can finalize: one P2WPKH input / two mixed outputs - labeled sp output " + "and BIP 32 change", + "70736274ff01fb04020000000102040200000001040101010501020106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f20a1070000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf483045022100aca5c9844ec9922c81e670817e332da2dd15d2c5d3" + "a9462ab6d65e53b682895e02204df32cea382e72c43c058404fdae705951e6ba3de3" + "3d833c83a95bb018380ac70101030401000000220602c817bb7521afc35ea96f3bfb" + "270e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feff" + "ffff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872" + "d50a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21d" + "f8a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320" + "2100010308a086010000000000010942027a487fc19fb769877b8742d6ea18118f3c" + "4e72b1ea8c6de602a7ad4a41dbe06803ea8f228be2b716dacdefcb2810072874f00a" + "476f5c07bd051917126cc64b3def010a04010000000001030870f305000000000001" + "0416001438c18f35dd8063e380a70ffeb4f98ff4ef348177220202c817bb7521afc3" + "5ea96f3bfb270e6eb50ddffa5560627b961fec00f2996508bf0c0000000000000000" + "0000000100", + {"51202268cf529959f30ac8f7a5471ca4c67536a51f0e5b168af03eed4715edcc72e0", + NULL}}, + {"can finalize: one input / two sp outputs - output 0 has no label / " + "output 1 uses label=0 convention for sp change", + "70736274ff01fb04020000000102040200000001040101010501020106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fe093040000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf4730440220225ae3990f545dfae6ea142a93746ab4aa8127e3c813" + "58eb7c216b4f1a9ebb62022065e3605219102b25075e3955f3f34ce3bcf2a35d1e10" + "15dd5dc3bfed3ecf35a90101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d025f0ec1b38d9984a7eb62f15be403020410f142edf4d69e363f5615afd2a6" + "b6cd2103ce1e3675d90d992649fa9ddb11f902549bb3b02f56f6e89cc0a04c8b8c37" + "dd94221d028b790e0987fde9f0d12398eb6be30c7376793c647865a2a02f2efc960d" + "96656821025581bfaa733156f6b98e71a26f70fd76b3678649f62b1fc5e77b8e9ab8" + "e61050221e025f0ec1b38d9984a7eb62f15be403020410f142edf4d69e363f5615af" + "d2a6b6cd400e89613d1f6b2536db8fa924200db3a6f8efca17225564d56b112e5086" + "5b4d302e058fa6f61c29e2366a4a7269d4555a5c61d65559dbfbfac9e2eadfe53637" + "d5221e028b790e0987fde9f0d12398eb6be30c7376793c647865a2a02f2efc960d96" + "6568407940819eb6e9f258c158387c0a64cc16f517c7ef4409122cceaa94f4e2ff53" + "76c4247bfc170d9b263b0e3d206b668c87e94b34deeafa00a1792b047ad78875bb00" + "010308a086010000000000010942028b790e0987fde9f0d12398eb6be30c7376793c" + "647865a2a02f2efc960d96656803b44347335c63f505e55e268ab280f318b4a6aa14" + "492ff379c3668a1f54ef8c9b0001030830e6020000000000010942025f0ec1b38d99" + "84a7eb62f15be403020410f142edf4d69e363f5615afd2a6b6cd02ce0b3219a5aa5d" + "f8f21ce393e962cdda7d51546da4d35c38ed0188a596e760f3010a040000000000", + {"5120a0480d96679c1936e5abbd48bab0e01ffacb1ee7d1c9e1682f154016996585d9", + "5120e42a181488d8fff6e7161f715f5ef0f47dc6c8480848aad684471bf3ea58f352"}}, + {"can finalize: three sp outputs (same scan key) - output 0 uses label=1, " + "outputs 1 and 2 uses label=2 (same spend key)", + "70736274ff01fb04020000000102040200000001040101010501030106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f801a060000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022056a9940b9a5376880a84dcbf1ad74999c71fa8b8497a" + "5b612bb3a294b207493802203df22505432b0a4b4237b36b070b747c669c9cbcaec9" + "6621343dc8cc7e2367620101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d028b790e0987fde9f0d12398eb6be30c7376793c647865a2a02f2efc960d96" + "656821025581bfaa733156f6b98e71a26f70fd76b3678649f62b1fc5e77b8e9ab8e6" + "1050221e028b790e0987fde9f0d12398eb6be30c7376793c647865a2a02f2efc960d" + "966568407940819eb6e9f258c158387c0a64cc16f517c7ef4409122cceaa94f4e2ff" + "5376c4247bfc170d9b263b0e3d206b668c87e94b34deeafa00a1792b047ad78875bb" + "00010308a186010000000000010942028b790e0987fde9f0d12398eb6be30c737679" + "3c647865a2a02f2efc960d96656803d431588dee61ab3a39725b299c3742dc66a086" + "1decf591b423b0e527070f8234010a04010000000001030832e60200000000000109" + "42028b790e0987fde9f0d12398eb6be30c7376793c647865a2a02f2efc960d966568" + "032193ad0c875fac5243738022900a7724c6175ddac9944165aab457aadf9c4f3c01" + "0a040200000000010308a286010000000000010942028b790e0987fde9f0d12398eb" + "6be30c7376793c647865a2a02f2efc960d966568032193ad0c875fac524373802290" + "0a7724c6175ddac9944165aab457aadf9c4f3c010a040200000000", + {"51201bffa10fdaa2502c2f0c9285fe0af19a50f8515e3b6dfbf56de850d999014400", + "5120884da6708c82b9b56c98bd3be6e5f53894bb1bfd90bfacf894025570f6bd5305", + "5120d291d339280e0c86e2c708a591f8e8e2f892d12a7cfe8510b667799b71131c86"}}, + {"can finalize: two inputs using per-input ECDH shares - only eligible " + "inputs contribute shares (P2SH excluded)", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf4830450221008b4cb7063c8a7b3f921ae000596cd7788e5440e1d6" + "3ef1ee1bcec8c2ac940ca20220370d8e9a85a0cc8dd25b0bb081f31aa2dcc5ba0a22" + "48ea860a81651ca34a0c680101030401000000220602c817bb7521afc35ea96f3bfb" + "270e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feff" + "ffff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872" + "d50a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21d" + "f8a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320" + "2100010e20d222262f268729bb7c84c558129a5d6986185cef535ec149c0df60dd4a" + "92c204010f0400000000010053020000000140e6faa61268f17a10101d6255358288" + "2ae4858bee13363db80fdf281f825ffc0000000000ffffffff01f049020000000000" + "17a914f45f8cca268ec26e4bbe899170f138250d7cf55e8700000000010447522102" + "877ca02f144059bd82d00e1b399ae374f78a52cef7a1ca37f28d788b340d2f792103" + "4c87a44872f5e1f006d34d88a00959282bd4535e7477c3d68c3165991ea1b39652ae" + "011004feffffff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de6" + "02a7ad4a41dbe0682102628b68b6446e6a87025973d93afb194e420a10f3a1ccb38a" + "dd82d464a894a428221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6d" + "e602a7ad4a41dbe06840000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000010308905f010000000000010942027a487fc19fb769877b8742d6" + "ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54" + "b9e0d57ed13938fad56d3f19e57513a8fce03900", + {"5120326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5aa6aa007b6146fd8"}}, + {"can finalize: two inputs using global ECDH share - only eligible inputs " + "contribute shares (P2SH excluded)", + "70736274ff01fb040200000001020402000000010401020105010101060100220702" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103" + "eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b2208" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06840" + "2430479d2da1310a024d2aab8e4c7b49d76cd51f45ee8127c159b0393a675b6f75c5" + "81ebe3d0817ddaf3bb598cfd7a022f1a87ed479664f6b947a47db5941cb200010e20" + "18a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a010f" + "040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb81" + "c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec" + "00f2996508bf4830450221008b4cb7063c8a7b3f921ae000596cd7788e5440e1d63e" + "f1ee1bcec8c2ac940ca20220370d8e9a85a0cc8dd25b0bb081f31aa2dcc5ba0a2248" + "ea860a81651ca34a0c6801220602c817bb7521afc35ea96f3bfb270e6eb50ddffa55" + "60627b961fec00f2996508bf080000008000000000011004feffffff00010e20d222" + "262f268729bb7c84c558129a5d6986185cef535ec149c0df60dd4a92c204010f0400" + "000000010053020000000140e6faa61268f17a10101d62553582882ae4858bee1336" + "3db80fdf281f825ffc0000000000ffffffff01f04902000000000017a914f45f8cca" + "268ec26e4bbe899170f138250d7cf55e8700000000010447522102877ca02f144059" + "bd82d00e1b399ae374f78a52cef7a1ca37f28d788b340d2f7921034c87a44872f5e1" + "f006d34d88a00959282bd4535e7477c3d68c3165991ea1b39652ae011004feffffff" + "00010308905f010000000000010942027a487fc19fb769877b8742d6ea18118f3c4e" + "72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed139" + "38fad56d3f19e57513a8fce03900", + {"5120326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5aa6aa007b6146fd8"}}, + {"can finalize: two mixed input types - only eligible inputs contribute " + "ECDH shares (NUMS internal key excluded)", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2013f106b64b57b5b1376f9f6c47190f40cc06b3bedcb8aaba97850ab3d7f67d0201" + "0f040000000001012b102700000000000022512050929b74c1a04954b78b4b6035e9" + "7a5e078a5a0f28ec96d547bfee9ace803ac0011004feffffff01172050929b74c1a0" + "4954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac000010e20be9d65c8" + "3915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f04000000" + "0001011fa0860100000000001600144633d59cad1343479972e0c996921d0a5dadb6" + "5d22020243a0d40e9de0882794161752bae42ba90952784209f063430f0af256354a" + "85bb483045022100f461b0dff643fc0a56c15221453638162212487e506a59e069d7" + "5ed1f0ab84f6022052c71e94e9312ea8a9001fcd26372be70997ddc2aa629c5a8116" + "dc51f5b7e9a2010103040100000022060243a0d40e9de0882794161752bae42ba909" + "52784209f063430f0af256354a85bb080000008001000000011004feffffff221d02" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682102" + "e57a7adcb018d8fb3154e80c14b97a50994b42356841ea9fc13170614400e637221e" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06840" + "f7fa381de20b3b459c6e426c6213d4175308f2482a44e33284232624d4dafd573299" + "bf3af16ab302c5626363a37d448707f7e7a1ebea0647bccd486203bb2ba600010308" + "1c25000000000000010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c" + "6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d" + "3f19e57513a8fce03900", + {"51200576722524839a8c9bc9d2d9738e98bb40dd2ec5023bdc7da7f70623cd7c85fb"}}, + {"can finalize: three sp outputs (same scan key) - each output has " + "distinct k value", + "70736274ff01fb04020000000102040200000001040101010501040106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f801a060000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf47304402200dfef57078afca55db22b4cdee36cb117f8761e47808" + "29b421d10648acafad8f022064e6f5890f4fd05b77a64a71831c98864d9c984c9ef1" + "febe9a7c50b4f15907210101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "00010308a086010000000000010942027a487fc19fb769877b8742d6ea18118f3c4e" + "72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed139" + "38fad56d3f19e57513a8fce03900010308a086010000000000010942027a487fc19f" + "b769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e" + "42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fce03900010308a0860100" + "00000000010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7" + "ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e575" + "13a8fce03900010308905f010000000000010422512079ef5688a3fa7fefc3922745" + "5b1f1c2f08c70087424d6a00f84c31421aca8da400", + {"5120326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5aa6aa007b6146fd8", + "51203fcbaea49087f8e03d9defd3abcbd6de8c032b583f85a65d057881c4c443cdc0", + "5120971442c89f04786e082728ae116eeab802f3fa9e95fdb0d3753a6840202006de", + NULL}}, + {"can finalize: three sp outputs (same scan key) / two regular outputs - k " + "values assigned independently of output index", + "70736274ff01fb04020000000102040200000001040101010501060106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f20a1070000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf483045022100f7df72806300dddbe4b24cd733f53b32a646b236c2" + "946057de47ae503b2ab16802204c69405b77bedaf3b207ede59749bba3d54c4615a8" + "8bbd36e54824af77c9e7310101030401000000220602c817bb7521afc35ea96f3bfb" + "270e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feff" + "ffff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872" + "d50a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21d" + "f8a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320" + "2100010308a086010000000000010942027a487fc19fb769877b8742d6ea18118f3c" + "4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed1" + "3938fad56d3f19e57513a8fce0390001030850c300000000000001042251209c6a3d" + "23818e820ed1d0cfdeb963657c8ec3277b7d9b865c78d7557f5dedd6a200010308a0" + "86010000000000010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6d" + "e602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f" + "19e57513a8fce0390001030850c3000000000000010422512079ef5688a3fa7fefc3" + "9227455b1f1c2f08c70087424d6a00f84c31421aca8da400010308a0860100000000" + "00010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fc" + "e03900010308c82c01000000000001042251206fc506f8052a9f5a8aa9b990d5e994" + "f495dded6d47bac44caacdadd8d8991cd000", + {"5120326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5aa6aa007b6146fd8", + NULL, + "51203fcbaea49087f8e03d9defd3abcbd6de8c032b583f85a65d057881c4c443cdc0", + NULL, + "5120971442c89f04786e082728ae116eeab802f3fa9e95fdb0d3753a6840202006de", + NULL}}, +}; + +static const bip375_result_t BIP375_RESULTS[] = { + {"in progress: two P2TR inputs, neither is signed", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2013f106b64b57b5b1376f9f6c47190f40cc06b3bedcb8aaba97850ab3d7f67d0201" + "0f040000000001012ba086010000000000225120c817bb7521afc35ea96f3bfb270e" + "6eb50ddffa5560627b961fec00f2996508bf01030401000000011004feffffff0117" + "20c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec00f2996508bf22" + "1d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068" + "2103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b" + "221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0" + "68408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199" + "598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320210001" + "0e202b9037ff41dd174e5522f0f4045c3f40436232af2600d4da5c9ea13cc3cab4b5" + "010f040000000001012b102700000000000022512043a0d40e9de0882794161752ba" + "e42ba90952784209f063430f0af256354a85bb01030401000000011004feffffff01" + "172043a0d40e9de0882794161752bae42ba90952784209f063430f0af256354a85bb" + "221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0" + "682102e57a7adcb018d8fb3154e80c14b97a50994b42356841ea9fc13170614400e6" + "37221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e06840f7fa381de20b3b459c6e426c6213d4175308f2482a44e33284232624d4dafd" + "573299bf3af16ab302c5626363a37d448707f7e7a1ebea0647bccd486203bb2ba600" + "010308b8f90200000000000104225120cb1fbeba50d06ebffb690bda9d5ff39ce2fa" + "db4fcedc96632eff1ba41cc0c07b010942027a487fc19fb769877b8742d6ea18118f" + "3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57e" + "d13938fad56d3f19e57513a8fce03900", + SP_PSBT_OK}, + {"in progress: one P2TR input / one sp output with no ECDH shares when " + "PSBT_OUT_SCRIPT field is not set", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2013f106b64b57b5b1376f9f6c47190f40cc06b3bedcb8aaba97850ab3d7f67d0201" + "0f040000000001012ba086010000000000225120c817bb7521afc35ea96f3bfb270e" + "6eb50ddffa5560627b961fec00f2996508bf011004feffffff011720c817bb7521af" + "c35ea96f3bfb270e6eb50ddffa5560627b961fec00f2996508bf0001030818730100" + "00000000010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7" + "ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e575" + "13a8fce03900", + SP_PSBT_PENDING}, + {"in progress: two inputs / one sp output, input 1 missing ECDH share when " + "PSBT_OUT_SCRIPT field is not set", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f9401030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddf" + "fa5560627b961fec00f2996508bf080000008000000000011004feffffff221d027a" + "487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103ec" + "a4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b221e02" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068408a" + "13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199598b31" + "228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee3202100010e20be" + "9d65c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f04" + "0000000001011ff0490200000000001600144633d59cad1343479972e0c996921d0a" + "5dadb65d22060243a0d40e9de0882794161752bae42ba90952784209f063430f0af2" + "56354a85bb080000008001000000011004feffffff00010308400d03000000000001" + "0942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0" + "680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fce039" + "00", + SP_PSBT_PENDING}, + {"in progress: one input / two sp outputs, input 0 missing ECDH share for " + "output 0 when PSBT_OUT_SCRIPT field is not set", + "70736274ff01fb04020000000102040200000001040101010501020106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f400d030000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f9401030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddf" + "fa5560627b961fec00f2996508bf080000008000000000011004feffffff221d0352" + "d78c41390032ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec210309" + "1fd48039177f44d7b79e96168849c62eb3f87800c46767c50a8f38f98efd15221e03" + "52d78c41390032ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec40be" + "1a723aef55e8981b99599a9bc12b38f87eba0158cc7066890f2269cade463b77341a" + "97d29271964d01c0241cc322fd5390c29b99160f826f329365898cbf020001030890" + "5f01000000000001094203651d2c073fcb02a4d82dda53f1d501d77a035066679854" + "6473b2126b6cd1a7de03f270e0a5632183b6ab01074e877e6800db00f5c7c5d2fafb" + "b68f9c28d485452400010308905f010000000000010422512043581df6c879f9aaad" + "c53660deb156b9f122bd1aeca733203bce87fcf1f386ee0109420352d78c41390032" + "ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec02e0c4c187b7215f99" + "7c8485a75b4591b6c28477b95a1123b996922d3154860bf800", + SP_PSBT_PENDING}, + {"in progress: two mixed input types - only eligible inputs contribute " + "ECDH shares (bare OP_2 excluded, not a segwit v2 witness program)", + "70736274ff0102040200000001040102010501010106010001fb0402000000000101" + "1fa0860100000000001600141e2ad7872d329413a56df0968be338222783163b2202" + "02c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec00f2996508bf47" + "3044022014b2f8870763a7b63ef015974367e7f937df04b1fc81d2792f4806076a86" + "8bcc02201a41a2dbd191546d50a13eb3e9ccd265ac0913830bae4ac0cb92beab296c" + "cc990101030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddffa5560" + "627b961fec00f2996508bf080000008000000000010e20f74edd1f75b4bb3e5d749c" + "15bfdb66348f6805a9b4d45feee1a2e201f503bb71010f0400000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "0001003d0200000001cf988ed779525d5445cb9aa1504b5d1f69a03f4b2450a07603" + "35d45f2e8a25a40000000000ffffffff01f049020000000000015200000000010e20" + "54db73992e71e9d56cd8100ed30edb55d0e8cf0ed254a00d4ef83acab46da25a010f" + "0400000000011004feffffff0001030808bd0300000000000104225120a92a63e9d7" + "022ea3afa99a70f000448bbb68464b34464b173bb26fc765514498010942027a487f" + "c19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9" + "de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_OK}, + {"in progress: large PSBT with nine mixed inputs / six outputs - some " + "inputs signed", + "70736274ff01fb04020000000102040200000001040109010501060106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf4830450221008b35384c5650f3b238170b4a0fb7f4a8aebf028831" + "c70b9d0d318dc551c789c602203199b0296375f4e7427d2fb828c8cb7e41db948b6e" + "61a688282798f31f9122880101030401000000220602c817bb7521afc35ea96f3bfb" + "270e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feff" + "ffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df" + "4715102103fbd173d9c48d58c5022426d05278bca17b9a8e2282666901a1b00b9e04" + "b79949221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cb" + "e5766d2821030a18b9bb4199b89330eb17f8ee5ac786e0853dcd2f3ccdf1744b97ce" + "4ede053e221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d0" + "07bf27286c21037372d179f4f628da82ccbd4e4217bdb0809f1417c9abeaa35fa805" + "d48ad6554c221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0" + "aba1df47151040c05da410487cfaec378febe6af5005e3ae6c86236818b0e55b2140" + "17eb5073edef40179575b5dcdaa9063491ac8b83fd0624d4177a4d2dd4994c4640d6" + "b8ccde221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cb" + "e5766d2840001383d4661be8725ef29048f48c911f89f5f34317d7c0c0acc60ef65f" + "1b52bfff7a96d8339b625df83abab57aa273edcd9a35c794dacbb1c861171bb26707" + "5f221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007bf27" + "286c40a6872d4eb119fe2af70953f752a22236b54a3b57f70e511f10bd8b42ff56b5" + "acf6365093c480ea9f13776784945b59318ac2927d915aae244cfb683f4188a3a700" + "010e20be9d65c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab5" + "22010f040000000001011fa086010000000000160014139350117c577941a985802b" + "b9edefc113932bc7220202f5b59fa5e492221ebf55ba78ad442605beae95166ba1eb" + "a3250d0bbaac7e2edc4730440220605ee9c13dcb912868f1de4ec1c751ac4b462b38" + "f5e5f1063f841ed8550016e9022047a9a69f4b98ce98d6f2cf78d08e85a55568510b" + "7b5cfbae68027f458c7e7e050101030401000000220602f5b59fa5e492221ebf55ba" + "78ad442605beae95166ba1eba3250d0bbaac7e2edc080000008001000000011004fe" + "ffffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1" + "df4715102103a6a89b1b986a995533e17bed64500b541bb0d739071efe2ae2b7efb0" + "a0ca6bcf221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583" + "cbe5766d282102f6ae7b8aac9a0f9c9f04eab484062172df2e38d9f2f6ec31b404bb" + "5a286aabf0221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0" + "d007bf27286c2102b1d3ed2fa4bc316a08eb1485fa75ed7dd54ca7a9ae18d0c4a17d" + "a93f30c385d5221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14" + "d0aba1df47151040c34a6a2940bbe9a7356c1cc6ffe358dd4441db58897cba99c212" + "eb75285e7da1eca11c792c97a380493345ab224de9d94c2b36ee8526ae23528171a3" + "231de733221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583" + "cbe5766d2840334aced8106ebaa4287daca56cca26795f2d2a739784cf6b734da337" + "0757f499e120c0e40be40436cd74c4ef26905706f52fa7fa6e8e76451e8583783051" + "a843221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007bf" + "27286c40d841a373ad2896b972b8cfea1634ff14a30f80d84cfd6ef18893397b8f34" + "6c80519c9b161a72244d0e9b64e5436c98ce9dd4e17a0728fc997b5c7bcf39cecb68" + "00010e20d041c742ca364472d1a18c7a8eae07e6e904a9ea1b85f198525fb83ef276" + "e343010f040000000001011fa0860100000000001600142307fc774ca174b42ada81" + "4bc2e6e444ff3d830c220202655ef5daf05d28d1ca73ba8e211300db2b7041673718" + "3e0fa8c355ee4c1cbac647304402202933a4d71ea4fbb53c9b38d88cb2be6ea21029" + "006bcc4c79ac980518aac86319022028fd19ca2d8c686a0fd0a3b0aea09a9a9580cc" + "38a22b052204be4575f035ad3f0101030401000000220602655ef5daf05d28d1ca73" + "ba8e211300db2b70416737183e0fa8c355ee4c1cbac6080000008002000000011004" + "feffffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0ab" + "a1df4715102103df706ff26d672fe50c6f56a2ca1e7174e75055c920bbd337e1a7d6" + "bf2826f6dc221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c5" + "83cbe5766d282103bfb86253beb96f58b8c469e442cfcf9f78a5413a95423be8e686" + "764f2fa7bd3f221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197e" + "d0d007bf27286c21038604aa8cff309dddf49b1f366f89c269616587fc41db608540" + "f9431536f6646f221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b" + "14d0aba1df47151040fd2e8c22b9b672d3bb9e26d4b6da2dc3f125455a969fd8e2b2" + "c1ba791076ad71b38c01f9218c3d6776fd895d2f3067484996d85e268390c2b433e6" + "c4b21891f1221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c5" + "83cbe5766d284052dffbf0095f29b1de24c9d68d549d1c54bce6900454fe37fd10f5" + "c903dfee85f7bad8a72ada8e52cd9092f51d9e90b5a7e4f36ca04df98e77fbad1347" + "305bc7221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007" + "bf27286c4093e1e5d4888bc1cfe02eecfa9dea144ead84f23a10fc1a301103c1e563" + "93527b63417c6c4a5af45359ff8b6e179af73978e4d62e862eedd2a286f5278e4cb3" + "4000010e2052262cd5d402bf32616d07fc03286a8f7fe78af7ac411dfff41655ddc1" + "011e6f010f040000000001011fa0860100000000001600147018bce965288d8bf0cc" + "f3e0ec48b6f1dbbfe54822020303a0f4528d264e8e95256634b94414e2748f729627" + "04fe57e8b0a2cc44d2383d483045022100db25bbdd1bcf850309663eb88fbbb0eb61" + "13095785d7f6d5338d9dbbc705032702207995d026f56ea99e073dfd0a796c6e74fc" + "61ed08ecd24670cef340dad50ae79a010103040100000022060303a0f4528d264e8e" + "95256634b94414e2748f72962704fe57e8b0a2cc44d2383d08000000800300000001" + "1004feffffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14" + "d0aba1df47151021038029998c73c2b139db75557ec3011ec65ecd21244796300657" + "1852a3e92289cc221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c" + "39c583cbe5766d282102980bac7264e14bf820cc435b69a78df726c177eb026f1b81" + "b52de811272f58eb221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e" + "197ed0d007bf27286c2103a27d9f1fa53e43f70835a6990954b78a35f747066f7b82" + "b4a9ea82e8bb5e06a6221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b" + "862b14d0aba1df47151040381ce3c1ac9fc7f6a51536456252984768e8fbd0140702" + "39f4cb13b16793c74cc5ed677c8a7eacc173e988d353a3f289c7e2141db7a4b4145c" + "5499ec837f36ae221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c" + "39c583cbe5766d284038e03463b6450dbd051065a812a6f2631087f7951e46ac84e6" + "6da811755717c093180e4d49827b8c097ca7093fe92d393f95a5d7ad849a41802dc4" + "e4558abde9221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0" + "d007bf27286c40732aa0957a9db2c759e39aca5d0167ef13d2a34a43c812e9cc9d71" + "2d458f7b2285da7511eb16f61f9600d20be4e94dfdd2bc3ae37fd943fc34947dfc3f" + "dc679700010e20e298eaf24fe1ca68b41e4b6b83cc3d91ced99c6e78d5b992cfb157" + "71b5457064010f040000000001011fa0860100000000001600149332bb020cb03d49" + "eb4d04712c1cc08e2b06d8d8220203a8911beb5a48fe119cb015088cf0c3a118cf02" + "6772448972d1b70c764ac5941247304402206bd612f647392107717c57af95ee8473" + "974f2c323bab7079e81916ecb9021c8e02205a54e82df716d1e40a7a138690df70ea" + "d4a3cc82ce1089ae80a323fb5fee8b550101030401000000220603a8911beb5a48fe" + "119cb015088cf0c3a118cf026772448972d1b70c764ac59412080000008004000000" + "011004feffffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b" + "14d0aba1df4715102102bef4738c6f327f1724b1407988959cdf2bd19210894bfd04" + "3535b61138270818221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce75" + "3c39c583cbe5766d2821027eb7c1c4afcd7e62ab6ad3d2ba2733a3745220641f9190" + "3ebfe7bcc5dbdc6b5d221d038ed3220e73344f91e2d33391e3e1691db39daf06e423" + "7e197ed0d007bf27286c2103ca88bcdb6d1f5291e90c75d3da601a8bd29991eabbf7" + "f94b2f39483e3858c9a1221e02a9f1fac2cc457684f33de90073fe20d22c947c9216" + "3b862b14d0aba1df471510400a584927102820b7b6cad6bcfb031a23a37312ad87d2" + "3f1cb5a8359be2d5ff39b6a2a2fe37cd0d53ee347f13e6b3525769b2e789f0699cb9" + "85588eac2daf10dd221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce75" + "3c39c583cbe5766d284077b1572336d9bd4e2f73411eb8f6a96235a130f444cbeb07" + "a489f447921e37489d71fd3db28a0bbaa35b88c37b7579ecdbf6ce1638700db81dfc" + "86bf79cd1be7221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197e" + "d0d007bf27286c405d0de8a27f0d528802cf3354a1af507bcf0fed419da641c9c080" + "7cd754e07af8790b511c705d5fbf63305ab22afe0497facf070b5afeafcee3a69005" + "4776775600010e201730833ecb5be01362d7149522604484216e1c7b18cf313d1cf1" + "543ef85df3b6010f040000000001012ba086010000000000225120d155713c520ce2" + "d8276164215d659ab623c5f7306f8652c1756e26833e886e01010304010000000110" + "04feffffff011720d155713c520ce2d8276164215d659ab623c5f7306f8652c1756e" + "26833e886e01221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14" + "d0aba1df47151021024f2a15a4b15a6b78f0a632fc7fdf112929f64bd4dd14f67a63" + "cf4fb8f325a204221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c" + "39c583cbe5766d282103802b69b360da4585512b1cf967b184010226d75ce5b762e7" + "7a0128bcb068ccbb221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e" + "197ed0d007bf27286c2102407615505ecbdea881312504eef6f4681a26316ef73d33" + "537a7fd793f4658ea9221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b" + "862b14d0aba1df471510408f223de27986dd8792a03d9d5b662323e8697830ebabb6" + "7363881fe72c86482ae61a09268d083b8354cfc2bad35c148eeb291af622dd460634" + "606332af1b8297221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c" + "39c583cbe5766d2840103ae05c10e43298376c3fee1dc5f0d04389f4f20af49346d4" + "8ead324d615d6f28fca0a318445130ea56a862019b2de0c2637db3c418c0b074b585" + "48ae8b20c9221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0" + "d007bf27286c40f055990738544d099b159290e7f5442cb91226260174aa9d8c1c83" + "10b7cb01ce2b94cc5d2b8fdf81667e02fb796db0e5c27877de0d41a2a0e709b01445" + "baf29600010e20e93532e0eda39c4d39da2d3f91d14529bc435fc2efb9196e25fbaa" + "c4b4e89b81010f040000000001012ba086010000000000225120d00e15fb626a7efe" + "e85c5bce676d636b6048914e9a34ace0b4cbc44bc948077a01030401000000011004" + "feffffff011720d00e15fb626a7efee85c5bce676d636b6048914e9a34ace0b4cbc4" + "4bc948077a221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0" + "aba1df4715102102153fcdfe96ae70363fd1542646d309c2132b8325540e3dd7f88e" + "37f9796079a6221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39" + "c583cbe5766d2821020faa3a0c31ae7695e769546e30aa782abd31fb681b970a13aa" + "35cc21dfd13800221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e19" + "7ed0d007bf27286c2103f313f8f475eb01e3cecbc0eaac2f726d29032c6ff7c3ad6c" + "c3bf8bb10186527c221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b86" + "2b14d0aba1df471510404320e9f60fd3c2a6f737aace546c23b0c7d76e84159c0ad2" + "89c1df4c0f8a500e51209f296f9d7d223a1d292bd41d266faacb1be843becf4b706e" + "b15dba702806221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39" + "c583cbe5766d2840e4074a6ec893eab806d5df9a74ed257e785ff378643dbaa7933c" + "7813a7b5f6c90ca82b62539f39b38c2c72fe5cf81c22a5e641f673644f6c486b3db5" + "77464463221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d0" + "07bf27286c403b29e12cf693f272139f74452f2bccc2bcd07432dce8fb107354c145" + "8a12a47c8544d2d6ca1e33bce0578b6508cf8a5934673f9fc435a5f84a22a54b5adc" + "bcfc00010e20b6368bbc330cddfe9e2550edb7dfc15ae74cac9bcc7d967fe81e6f27" + "f8597b1d010f04000000000100530200000001fea14f3d169b2b0400db14996221b3" + "1182bb9e86ca169e91b9c7bd93f9c73e880000000000ffffffff01a0860100000000" + "0017a9140df101357f73e6658500cf56f3a132d7bb8afbdd8700000000010120a086" + "01000000000017a9140df101357f73e6658500cf56f3a132d7bb8afbdd8722020205" + "00f167cf669e7dac39e6aecda1f28c66b78ec7097eefef25d54f7be785e7f6473044" + "02200d77e3ebac584342b0caf97e8a69f58707c4ab00ccadbe86c44aa187b565fbff" + "02206e6e056eb58b6625e2fefabd1ac5b45aa6a12da39ca908a11a21c637f7a25c30" + "01010304010000000104160014c6bc8105ec6db60c4da53ac35cda204069e90e8a22" + "06020500f167cf669e7dac39e6aecda1f28c66b78ec7097eefef25d54f7be785e7f6" + "080000008007000000011004feffffff221d02a9f1fac2cc457684f33de90073fe20" + "d22c947c92163b862b14d0aba1df4715102102fe7841cddfb46fdb2ca9bde56c9558" + "c2d1b36121665659080224e24031438408221d033361d3ff72f34e6b4e7a7bef96e5" + "b8151e66a979adce753c39c583cbe5766d2821026f027b235a7593ca8943c6d7b7e3" + "7d92eab339617f7f0c344106c58dd0cbc6aa221d038ed3220e73344f91e2d33391e3" + "e1691db39daf06e4237e197ed0d007bf27286c21020611450c6c1944ecdecb78f618" + "16c767fba4368f21f7e9b169779c76f23cf4cc221e02a9f1fac2cc457684f33de900" + "73fe20d22c947c92163b862b14d0aba1df4715104088072551662c3eebee545f188b" + "8dafc682973a2f218e7ca07fc8e42ff57a1134630449fd703177d7a12d0c9ced0248" + "44dc1b9e0ecad67587dd5c479431b36a1a221e033361d3ff72f34e6b4e7a7bef96e5" + "b8151e66a979adce753c39c583cbe5766d284016b58148f7baff783e4310f185503f" + "e92417dba43b966c83a2184322cb1f20424cb9d040ae6a1aea4e7444bdc786258a97" + "5644ce1a0195564c2b9fc3c606a292221e038ed3220e73344f91e2d33391e3e1691d" + "b39daf06e4237e197ed0d007bf27286c404ab36bdd69eb1cd0d4b0aeae403dce4db5" + "228c5ba3a291dc725de23382d1736d265d7bc33f83690a5ca5609719f19e81952d4c" + "8d5e288fd0cb8c6411104b80a300010e2003bceba5379d73daeafe677972b03dcf7e" + "f30b7f10eaa83ad04bc0bf00d8b2f7010f040000000001005502000000012a34ac1b" + "0db77a8198c1e29002cc47bbfcd6ed830960304d2c9a3ab548486b5d0000000000ff" + "ffffff01a0860100000000001976a914569bf311e68a383767b43f83042dfabe6009" + "3ede88ac00000000220203199d2f155f32ebb167aeb0ccca6e5afb7340898df1b7ab" + "9936500f6d4391902a47304402206227fd246ec88705df63545b48be3d12c3d4a548" + "4d4b4ec434409acb84113c5a02203ccbc9b4788efb7fb860da8558a94c7e4c425ad7" + "55e868e2d8f05cfb46125f970101030401000000220603199d2f155f32ebb167aeb0" + "ccca6e5afb7340898df1b7ab9936500f6d4391902a080000008008000000011004fe" + "ffffff221d02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1" + "df4715102102f3c175b08b207637616aa74e67baac1a1807c94bce70800f76f5b17b" + "52c0082d221d033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583" + "cbe5766d282102fa1ced932598a27fa28410b955ea67479b5a4033b69f2c99e4e267" + "67bba0a556221d038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0" + "d007bf27286c210300e0fd1710dc56ad7c173aa9141d731577009bc3dffcba8576a4" + "8e77ab34d970221e02a9f1fac2cc457684f33de90073fe20d22c947c92163b862b14" + "d0aba1df4715104099225658fede7a8c2437eb3821bdc9d3700abc896e8b6dcef84e" + "29347b78bc2b03e6da33836e4f40767390c36644ce016b36b1d546963540fa51d0b0" + "407db6d7221e033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583" + "cbe5766d2840a0948c517d70976c0e39ca67abf19e7217040dbe172bb96534133e6f" + "fa3941c1659416f540662b7561efb70064b4d71a9b17b63bc563f630db4422f273e0" + "df12221e038ed3220e73344f91e2d33391e3e1691db39daf06e4237e197ed0d007bf" + "27286c40ee0aaa65ca73ccc547b31c2b7ed2ae31a4f4ccdaea73f2add24630d608ed" + "e9aea5d808688186ebca42b877efab13f35e60f210d4f620602f850fc0731c201e91" + "00010308307500000000000001042251201afa5d88188cef9b91b3f1002b11e0f9e9" + "4ad3981978c4d12a0605564c081233010942033361d3ff72f34e6b4e7a7bef96e5b8" + "151e66a979adce753c39c583cbe5766d28031266581e3e841cbb94de62ea735583a2" + "32c4c888fa6edef2ec2f870789fc1dd40001030830750000000000000104225120ca" + "bf7e4a0de424ec9bbadd7f7242cce7673e1701f49d6a19a97055da332b1324010942" + "033361d3ff72f34e6b4e7a7bef96e5b8151e66a979adce753c39c583cbe5766d2803" + "1266581e3e841cbb94de62ea735583a232c4c888fa6edef2ec2f870789fc1dd40001" + "0308204e00000000000001042251204aadc9e0a590d21e0c19cb2024f27140f9b19c" + "2a1282d50ea7c5f45eb03fd4a201094202a9f1fac2cc457684f33de90073fe20d22c" + "947c92163b862b14d0aba1df471510024a48d76e20d40bcf5f2e1a5c3ffeb3dc2a8b" + "3b88d79a486d54c9d9eaa8fa188e00010308204e00000000000001042251202fa437" + "00ea1d28fd7ad4dcb332b3e5e5a0d8cb54258f6661c4de0377d72804e501094202a9" + "f1fac2cc457684f33de90073fe20d22c947c92163b862b14d0aba1df471510024a48" + "d76e20d40bcf5f2e1a5c3ffeb3dc2a8b3b88d79a486d54c9d9eaa8fa188e00010308" + "1027000000000000010422512051986faee319436b51b38409c1b300f4396e2b32e3" + "cc9a12ae2a4be135da6f6e010942038ed3220e73344f91e2d33391e3e1691db39daf" + "06e4237e197ed0d007bf27286c03f81473844c9d74c921ff17a5af410b6337348d7a" + "fbff73891bc5cb0cb24cb0c00001030850c300000000000001042251206fc506f805" + "2a9f5a8aa9b990d5e994f495dded6d47bac44caacdadd8d8991cd000", + SP_PSBT_OK}, + {"psbt structure: missing PSBT_OUT_SP_V0_INFO field when " + "PSBT_OUT_SP_V0_LABEL set", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "00010308187301000000000001042251202268cf529959f30ac8f7a5471ca4c67536" + "a51f0e5b168af03eed4715edcc72e0010a040100000000", + SP_PSBT_ERR_FIELD}, + {"psbt structure: incorrect byte length for PSBT_OUT_SP_V0_LABEL field", + "70736274ff01fb04020000000102040200000001040101010501020106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f20a1070000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf483045022100aca5c9844ec9922c81e670817e332da2dd15d2c5d3" + "a9462ab6d65e53b682895e02204df32cea382e72c43c058404fdae705951e6ba3de3" + "3d833c83a95bb018380ac70101030401000000220602c817bb7521afc35ea96f3bfb" + "270e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feff" + "ffff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872" + "d50a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21d" + "f8a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320" + "2100010308a08601000000000001042251202268cf529959f30ac8f7a5471ca4c675" + "36a51f0e5b168af03eed4715edcc72e0010942027a487fc19fb769877b8742d6ea18" + "118f3c4e72b1ea8c6de602a7ad4a41dbe06803ea8f228be2b716dacdefcb28100728" + "74f00a476f5c07bd051917126cc64b3def010a01010001030870f305000000000001" + "0416001438c18f35dd8063e380a70ffeb4f98ff4ef348177220202c817bb7521afc3" + "5ea96f3bfb270e6eb50ddffa5560627b961fec00f2996508bf0c0000000000000000" + "0000000100", + SP_PSBT_ERR_FIELD}, + {"psbt structure: incorrect byte length for PSBT_OUT_SP_V0_INFO field", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "0001030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9" + "ad15ba695cc1e5aa6aa007b6146fd8010941027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d5" + "7ed13938fad56d3f19e57513a8fce000", + SP_PSBT_ERR_FIELD}, + {"psbt structure: incorrect byte length for PSBT_IN_SP_ECDH_SHARE field", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682003eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a1" + "99598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee3202100" + "01030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9ad" + "15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea18118f" + "3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57e" + "d13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"psbt structure: incorrect byte length for PSBT_IN_SP_DLEQ field", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe0683f8a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32000" + "01030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9ad" + "15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea18118f" + "3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57e" + "d13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"psbt structure: PSBT_GLOBAL_TX_MODIFIABLE field is non-zero when " + "PSBT_OUT_SCRIPT set for sp output", + "70736274ff01fb04020000000102040200000001040101010501010106010100010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "0001030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9" + "ad15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d5" + "7ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"psbt structure: missing PSBT_OUT_SCRIPT field when sending to non-sp " + "output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "00010308187301000000000000", + BIP375_PARSE_REFUSED}, + {"ecdh coverage: only one ineligible P2SH multisig input when " + "PSBT_OUT_SCRIPT set for sp output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "20cd381a45508fe3d9cab63b7e0f704a0f569dbfd55a98102d9ea33aee621b75f401" + "0f040000000001005302000000017ca831f3d48909fe68cb0eaaaa11f8773dee7e8c" + "73085337590e24bb06390db40000000000ffffffff01a08601000000000017a914d8" + "e6688714eeed0aa2edd489aa1ca3c171701e4d8700000000010447522102be40afdf" + "62b263cb7dee2b985d1c38fe41b1994d2b05075343d172c218eab1c421027a479253" + "d00a205a10a9438f372019b9f364e0a836800bf839dbd28e7ce6b95552ae011004fe" + "ffffff00010308905f0100000000000104225120cde39d8b05b496f8f18f20b27d0a" + "f9a3233309e0472219e0813ff3b5d3787e29010942027a487fc19fb769877b8742d6" + "ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54" + "b9e0d57ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_INPUT}, + {"ecdh coverage: missing PSBT_IN_SP_ECDH_SHARE field for input 0 when " + "PSBT_OUT_SCRIPT set for sp output", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220602c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf080000008000000000011004feffffff00010e20be9d65c83915fb" + "09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f04000000000101" + "1f10270000000000001600144633d59cad1343479972e0c996921d0a5dadb65d0103" + "040100000022060243a0d40e9de0882794161752bae42ba90952784209f063430f0a" + "f256354a85bb080000008001000000011004feffffff221d027a487fc19fb769877b" + "8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682102e57a7adcb018d8fb31" + "54e80c14b97a50994b42356841ea9fc13170614400e637221e027a487fc19fb76987" + "7b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06840f7fa381de20b3b459c" + "6e426c6213d4175308f2482a44e33284232624d4dafd573299bf3af16ab302c56263" + "63a37d448707f7e7a1ebea0647bccd486203bb2ba600010308187301000000000001" + "04225120cde39d8b05b496f8f18f20b27d0af9a3233309e0472219e0813ff3b5d378" + "7e29010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8" + "fce03900", + SP_PSBT_ERR_SCRIPT}, + {"ecdh coverage: missing PSBT_IN_SP_DLEQ field for input when " + "PSBT_IN_SP_ECDH_SHARE set", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b0001030818730100000000000104225120326df50fe0a07b7acb72070beb3b63" + "2eb9ad15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea" + "18118f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9" + "e0d57ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"ecdh coverage: missing PSBT_GLOBAL_SP_DLEQ field when " + "PSBT_GLOBAL_SP_ECDH_SHARE set", + "70736274ff01fb040200000001020402000000010401010105010101060100220702" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103" + "eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b0001" + "0e2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a" + "010f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50b" + "bb81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b96" + "1fec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac7" + "2349061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8" + "cc79029dc8e76a3c294b0601220602c817bb7521afc35ea96f3bfb270e6eb50ddffa" + "5560627b961fec00f2996508bf080000008000000000011004feffffff0001030818" + "730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9ad15ba695c" + "c1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea18118f3c4e72b1" + "ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fa" + "d56d3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"ecdh coverage: invalid proof in PSBT_IN_SP_DLEQ field", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068406ef1eb783c0597d668565e3bf3b8fde5bed2815295f43e17015124d445dc" + "cbdadd2a49dee7596178f1216e5d4db9174ffdda6334e37c9031108c08ce1374de0f" + "0001030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9" + "ad15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d5" + "7ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"ecdh coverage: invalid proof in PSBT_GLOBAL_SP_DLEQ field", + "70736274ff01fb040200000001020402000000010401010105010101060100220702" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103" + "eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b2208" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06840" + "e7c8fd442b94d88a2a6a2c92b434648fa007c9fe080472a33780d0b5232844d09bd8" + "8b3fee86d12d4386c4657fbb785e2d2f14bfcf9185743fe12ac8250f95d900010e20" + "18a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a010f" + "040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb81" + "c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961fec" + "00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac72349" + "061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc79" + "029dc8e76a3c294b0601220602c817bb7521afc35ea96f3bfb270e6eb50ddffa5560" + "627b961fec00f2996508bf080000008000000000011004feffffff00010308187301" + "00000000000104225120326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5" + "aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c" + "6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d" + "3f19e57513a8fce03900", + SP_PSBT_ERR_FIELD}, + {"ecdh coverage: missing PSBT_IN_BIP32_DERIVATION field for input when " + "PSBT_IN_SP_DLEQ set", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022009077a6aa64ac14ae7a1aa4fe68c02ace206c9eac723" + "49061ae7603900b9226e02206f1432a578f8e330af0b900256746bc9f4e52aa2e8cc" + "79029dc8e76a3c294b060101030401000000011004feffffff221d027a487fc19fb7" + "69877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103eca4ff11b728" + "e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b221e027a487fc19f" + "b769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068408a13b3985545" + "f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199598b31228a49e0bd" + "7e95ce1053f7c5b28acb543a68707600e3ce89822ee3202100010308187301000000" + "00000104225120326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5aa6aa0" + "07b6146fd8010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602" + "a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e5" + "7513a8fce03900", + SP_PSBT_ERR_INPUT_KEY}, + {"ecdh coverage: output 1 missing ECDH share for scan key with one input / " + "three sp outputs (different scan keys)", + "70736274ff01fb04020000000102040200000001040101010501030106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f400d030000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f9401030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddf" + "fa5560627b961fec00f2996508bf080000008000000000011004feffffff221d02b9" + "456157e946ef07f74b54fa09be4a7e938dcafbfb27b4b372c573c059f12ab02102c2" + "864474b084aac81f6e30ac5edf4667393ce604d808d3f499a0984e8b524974221d03" + "651d2c073fcb02a4d82dda53f1d501d77a0350666798546473b2126b6cd1a7de2103" + "76892327c4e780aeeed4ce1bc92bb0122b7b7910d96f0ad5148b496f9c3e92fb221e" + "02b9456157e946ef07f74b54fa09be4a7e938dcafbfb27b4b372c573c059f12ab040" + "f0b11d51c3fd13b38e0a6c8efc2ee0ca71773af674b3151e689214925c4b57c81688" + "c9e078b750885a6cab286b577e93a2497eb49636b1af1b6bc82e7c911251221e0365" + "1d2c073fcb02a4d82dda53f1d501d77a0350666798546473b2126b6cd1a7de4098f1" + "4ac45af6459ab0c84d47da5364cfb144ff90bdac732f9cabc6db000dcf1a95e3b31f" + "7b70a04298a51b6fd4516c81d716c9954f8af10c3d59809aee2bbd3800010308905f" + "0100000000000104225120d397146a82865b54eb12b9ea71d6824feab0f92a48137f" + "7a793a68596b3367a401094203651d2c073fcb02a4d82dda53f1d501d77a03506667" + "98546473b2126b6cd1a7de03f270e0a5632183b6ab01074e877e6800db00f5c7c5d2" + "fafbb68f9c28d48545240001030810270000000000000104225120cde39d8b05b496" + "f8f18f20b27d0af9a3233309e0472219e0813ff3b5d3787e290109420352d78c4139" + "0032ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec02e0c4c187b721" + "5f997c8485a75b4591b6c28477b95a1123b996922d3154860bf800010308204e0000" + "000000000104225120d2d241ece418514aa18e3992ec953c4d4ad5ec704a693e2106" + "ba22c3b05a7a8301094202b9456157e946ef07f74b54fa09be4a7e938dcafbfb27b4" + "b372c573c059f12ab00212681e3f09eae38a8f2f3fecd7dd56fc586cfa028e8ab33f" + "72a90f840a6d225c00", + SP_PSBT_ERR_SCRIPT}, + {"ecdh coverage: input 1 missing ECDH share for output 1 with two inputs / " + "two sp outputs (different scan keys)", + "70736274ff01fb04020000000102040200000001040102010501020106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f9401030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddf" + "fa5560627b961fec00f2996508bf080000008000000000011004feffffff221d0352" + "d78c41390032ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec210309" + "1fd48039177f44d7b79e96168849c62eb3f87800c46767c50a8f38f98efd15221d03" + "651d2c073fcb02a4d82dda53f1d501d77a0350666798546473b2126b6cd1a7de2103" + "76892327c4e780aeeed4ce1bc92bb0122b7b7910d96f0ad5148b496f9c3e92fb221e" + "0352d78c41390032ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec40" + "be1a723aef55e8981b99599a9bc12b38f87eba0158cc7066890f2269cade463b7734" + "1a97d29271964d01c0241cc322fd5390c29b99160f826f329365898cbf02221e0365" + "1d2c073fcb02a4d82dda53f1d501d77a0350666798546473b2126b6cd1a7de4098f1" + "4ac45af6459ab0c84d47da5364cfb144ff90bdac732f9cabc6db000dcf1a95e3b31f" + "7b70a04298a51b6fd4516c81d716c9954f8af10c3d59809aee2bbd3800010e20be9d" + "65c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f0400" + "00000001011fa0860100000000001600144633d59cad1343479972e0c996921d0a5d" + "adb65d0103040100000022060243a0d40e9de0882794161752bae42ba90952784209" + "f063430f0af256354a85bb080000008001000000011004feffffff221d03651d2c07" + "3fcb02a4d82dda53f1d501d77a0350666798546473b2126b6cd1a7de210275044007" + "fe2d030d577c32991cf2a3e75e53504245b3cbe5b3053ae7c5f2205a221e03651d2c" + "073fcb02a4d82dda53f1d501d77a0350666798546473b2126b6cd1a7de4038b9e380" + "6b49bebeefc6cee065c2b066fdb00aececf1e8b5b2aaf47cf0417b299ae0a256ed7c" + "b6c82702eb7137d73bf579271c4284d006e3b59d70a9b967d88900010308905f0100" + "000000000104225120f49c2ef19b670611b86ddefe890cef94268a82ae331e46fe19" + "51d6c6e3723cb101094203651d2c073fcb02a4d82dda53f1d501d77a035066679854" + "6473b2126b6cd1a7de03f270e0a5632183b6ab01074e877e6800db00f5c7c5d2fafb" + "b68f9c28d485452400010308905f01000000000001042251203da1e176c64fb45953" + "ec46e0503634bc7e8e343a768dbeefbb0a3e88cc4a4c9a0109420352d78c41390032" + "ad91816a697fc740d8eb909cf04d70885264b051f2385e25ec02e0c4c187b7215f99" + "7c8485a75b4591b6c28477b95a1123b996922d3154860bf800", + SP_PSBT_ERR_SCRIPT}, + {"ecdh coverage: input 1 missing ECDH share for scan key with two inputs / " + "one sp output", + "70736274ff01fb04020000000102040200000001040102010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011f50c3000000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f9401030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddf" + "fa5560627b961fec00f2996508bf080000008000000000011004feffffff221d027a" + "487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103ec" + "a4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b221e02" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068408a" + "13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199598b31" + "228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee3202100010e20be" + "9d65c83915fb09248abbdfca8ca3eee6ce350c554f65e8d526e5df527ab522010f04" + "0000000001011f50c30000000000001600144633d59cad1343479972e0c996921d0a" + "5dadb65d22060243a0d40e9de0882794161752bae42ba90952784209f063430f0af2" + "56354a85bb080000008001000000011004feffffff00010308187301000000000001" + "04225120cde39d8b05b496f8f18f20b27d0af9a3233309e0472219e0813ff3b5d378" + "7e29010942027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a" + "41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8" + "fce03900", + SP_PSBT_ERR_SCRIPT}, + {"input eligibility: segwit version greater than 1 in transaction inputs " + "with sp output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000165214229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022072f378852fb843726072f25076f0e77560ed4c2e0471" + "66ee6a626c75bfdb39d60220212aae5f09574e341f5886f5fff32f5716eab9030a4a" + "5379e6016b6a4d42dc240101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "0001030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9" + "ad15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d5" + "7ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_INPUT}, + {"input eligibility: segwit version greater than 1 supplied via " + "PSBT_IN_NON_WITNESS_UTXO with sp output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "20c9730c1b925f3b8affba9a1f951f0c38808ec895cb170b67d166471b6b26309601" + "0f0400000000220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022072f378852fb843726072f25076f0e77560ed4c2e0471" + "66ee6a626c75bfdb39d60220212aae5f09574e341f5886f5fff32f5716eab9030a4a" + "5379e6016b6a4d42dc240101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "0100520200000001f4c212d5aed1e7f6ff633f2ce09c647c57bedd930314d98de775" + "03d58e940b330000000000ffffffff01a086010000000000165214229a72d34a645b" + "d3496bbbf50bbb81c9063f4f94000000000001030818730100000000000104225120" + "326df50fe0a07b7acb72070beb3b632eb9ad15ba695cc1e5aa6aa007b6146fd80109" + "42027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068" + "0361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_INPUT}, + {"input eligibility: non-SIGHASH_ALL signature on input with sp output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf473044022072f378852fb843726072f25076f0e77560ed4c2e0471" + "66ee6a626c75bfdb39d60220212aae5f09574e341f5886f5fff32f5716eab9030a4a" + "5379e6016b6a4d42dc240101030402000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "0001030818730100000000000104225120326df50fe0a07b7acb72070beb3b632eb9" + "ad15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d5" + "7ed13938fad56d3f19e57513a8fce03900", + BIP375_PARSE_REFUSED}, + {"output scripts: P2TR input with NUMS internal key cannot derive sp " + "output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2013f106b64b57b5b1376f9f6c47190f40cc06b3bedcb8aaba97850ab3d7f67d0201" + "0f040000000001012b102700000000000022512050929b74c1a04954b78b4b6035e9" + "7a5e078a5a0f28ec96d547bfee9ace803ac001030401000000011004feffffff0117" + "2050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac022" + "1d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068" + "2103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b" + "221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0" + "68408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199" + "598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320210001" + "03081c2500000000000001042251202768c88aeea223225ba3ad84e786352f9829d2" + "d3e9378a393a0bff59af87cdd0010942027a487fc19fb769877b8742d6ea18118f3c" + "4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed1" + "3938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_INPUT}, + {"output scripts: PSBT_OUT_SCRIPT does not match derived sp output", + "70736274ff01fb04020000000102040200000001040101010501010106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f9401030401000000220602c817bb7521afc35ea96f3bfb270e6eb50ddf" + "fa5560627b961fec00f2996508bf080000008000000000011004feffffff221d027a" + "487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe0682103ec" + "a4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d50a5b221e02" + "7a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe068408a" + "13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8a199598b31" + "228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee320210001030818" + "730100000000000104225120cde39d8b05b496f8f18f20b27d0af9a3233309e04722" + "19e0813ff3b5d3787e29010942027a487fc19fb769877b8742d6ea18118f3c4e72b1" + "ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fa" + "d56d3f19e57513a8fce03900", + SP_PSBT_ERR_SCRIPT}, + {"output scripts: two sp outputs (same scan / different spend keys) not " + "sorted lexicographically by spend key", + "70736274ff01fb04020000000102040200000001040101010501020106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf47304402203f6205c468706a46245f1713abb8b8b9a3a7bfd83ac7" + "45f7c0720d4431b4cdfc02207158abfb820f2bf5ad6745f56fc0709c995cccacfe17" + "098d8aa1b61f8c9ff2ff0101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "00010308905f01000000000001042251207547b8163d5bbc549840be4cc146aad095" + "207367b9eb94706de6708d408f93f9010942027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe068028b80f994334895e11bc76c75ab6e78fe" + "2c25bb332f217b211c4017bf1f677d8600010308102700000000000001042251206c" + "e2c35395f170f24b6d2d80d0a40c46f46ba4b4843f6ab311a934b31c5d84dc010942" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06803" + "aaf862aeda98cf92539af7dc3375d1da5fb06b121ef0a1f031a9f7382fd53dbb00", + SP_PSBT_ERR_SCRIPT}, + {"output scripts: k values assigned to wrong output indices with three sp " + "outputs (same scan / spend keys)", + "70736274ff01fb04020000000102040200000001040101010501030106010000010e" + "2018a717663b0bab14b12a1a771323ff1e4079dd532e5dd13e28ea1081c700984a01" + "0f040000000001011fa086010000000000160014229a72d34a645bd3496bbbf50bbb" + "81c9063f4f94220202c817bb7521afc35ea96f3bfb270e6eb50ddffa5560627b961f" + "ec00f2996508bf47304402205837ea183653bb51ac6350abe6c3847be8906a2065dc" + "3048d6d208ea7c0e4c82022010fb4ffab2fed5aa6cb6280a93c479cfb04e46ca9edf" + "17aa305cd1674a242c490101030401000000220602c817bb7521afc35ea96f3bfb27" + "0e6eb50ddffa5560627b961fec00f2996508bf080000008000000000011004feffff" + "ff221d027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41db" + "e0682103eca4ff11b728e2e0f60ce6222943a6ff55b9d95f627bf9a99d084bc872d5" + "0a5b221e027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41" + "dbe068408a13b3985545f72bd6e89714aeb909b3e354a842a9bb8b56cd0eded21df8" + "a199598b31228a49e0bd7e95ce1053f7c5b28acb543a68707600e3ce89822ee32021" + "00010308905f0100000000000104225120326df50fe0a07b7acb72070beb3b632eb9" + "ad15ba695cc1e5aa6aa007b6146fd8010942027a487fc19fb769877b8742d6ea1811" + "8f3c4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d5" + "7ed13938fad56d3f19e57513a8fce039000103081027000000000000010422512097" + "1442c89f04786e082728ae116eeab802f3fa9e95fdb0d3753a6840202006de010942" + "027a487fc19fb769877b8742d6ea18118f3c4e72b1ea8c6de602a7ad4a41dbe06803" + "61e1b1e9de5e42cb2007f7ca54b9e0d57ed13938fad56d3f19e57513a8fce0390001" + "0308102700000000000001042251203fcbaea49087f8e03d9defd3abcbd6de8c032b" + "583f85a65d057881c4c443cdc0010942027a487fc19fb769877b8742d6ea18118f3c" + "4e72b1ea8c6de602a7ad4a41dbe0680361e1b1e9de5e42cb2007f7ca54b9e0d57ed1" + "3938fad56d3f19e57513a8fce03900", + SP_PSBT_ERR_SCRIPT}, +}; + +#endif // BIP375_FIXTURE_H diff --git a/main/core/test/sp_fixture.h b/main/core/test/sp_fixture.h new file mode 100644 index 00000000..bb558e39 --- /dev/null +++ b/main/core/test/sp_fixture.h @@ -0,0 +1,204 @@ +#ifndef SP_FIXTURE_H +#define SP_FIXTURE_H + +/* Built with bwk 24bfd42 (bwk_psbt::PsbtV2): one P2TR input of the test + * mnemonic's spend key tweaked by 0x11..11, paying the BIP352 "Simple send" + * recipient 60000 sats and our m=0 change address 39000 sats, both outputs + * scriptless with PSBT_OUT_SP_V0_INFO (the change one with label 0). */ +static const char UNSIGNED_PSBT[] = + "70736274ff0102040200000001030400000000010401010105010201fb04020000000001" + "012ba086010000000000225120cba15611f961103c8738f27fefa7b774bc6b242f17b55d" + "ae832a3ae2efe332ed010e20222222222222222222222222222222222222222222222222" + "2222222222222222010f0400000000012020111111111111111111111111111111111111" + "11111111111111111111111111110001030860ea0000000000000109420220bcfac5b99e" + "04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4025cc9856d6f8375350e" + "123978daac200c260cb5b5ae83106cab90484dcd8fcf3600010308589800000000000001" + "0942024139b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcdd511beaea1e303" + "1ec096b3e9917a43e81c6d014acab0dfa32151ea7dcdfa56a1dc89f0aec04ef8010a0400" + "00000000"; + +/* The same PSBT with a foreign P2WPKH input added */ +static const char FOREIGN_PSBT[] = + "70736274ff0102040200000001030400000000010401020105010201fb04020000000001" + "012ba086010000000000225120cba15611f961103c8738f27fefa7b774bc6b242f17b55d" + "ae832a3ae2efe332ed010e20222222222222222222222222222222222222222222222222" + "2222222222222222010f0400000000012020111111111111111111111111111111111111" + "11111111111111111111111111110001011f50c3000000000000160014e1fae3324e28a4" + "ef5ee01f14dd337ac6c85d1d90010e203333333333333333333333333333333333333333" + "333333333333333333333333010f04010000000001030860ea0000000000000109420220" + "bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4025cc9856d" + "6f8375350e123978daac200c260cb5b5ae83106cab90484dcd8fcf360001030858980000" + "00000000010942024139b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcdd511" + "beaea1e3031ec096b3e9917a43e81c6d014acab0dfa32151ea7dcdfa56a1dc89f0aec04e" + "f8010a040000000000"; + +/* What bwk's SpSigner writes for UNSIGNED_PSBT */ +static const char EXPECTED_SCRIPT_0[] = + "5120a5675fd49d557606b5b541b345b3b0f83733e6bf21d3442884f9949872b65882"; +static const char EXPECTED_SCRIPT_1[] = + "51206608dcdf249f25bbb94eda8f31ab3c05f6fd3e762a3c9e41152342eb4b38a546"; +static const char RECIPIENT_SCAN[] = + "0220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4"; +static const char RECIPIENT_SHARE[] = + "03828fd168088f316588c4f7523fa8e438160d9db9273b27d720762b02b4ce0b73"; +static const char OUR_SCAN[] = + "024139b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcdd511beaea1e3"; +static const char OUR_SHARE[] = + "030899d7c63650b59990c011ca08c1893f75b62aa9a2038f0125506fbb633a93c9"; +/* Even lift of the input's P2TR output key: the input public key sum */ +static const char INPUT_KEY[] = + "02cba15611f961103c8738f27fefa7b774bc6b242f17b55dae832a3ae2efe332ed"; + +/* Built with embit (diybitcoinhardware/embit#145) for the test mnemonic, all + * paying the BIP352 "Simple send" recipient, and the expected script, global + * share and input public key sum embit derives. Every input is resolved from + * the script it spends, its key origin only naming a candidate key. */ + +/* P2WPKH (84'), P2TR key path (86'), P2TR with a merkle root, P2SH-P2WPKH + * (49') and P2PKH (44', non_witness_utxo only) inputs */ +static const char ALL_TYPES_PSBT[] = + "70736274ff0102040200000001040105010501010106010301fb04020000000001011f50" + "c3000000000000160014c0cebcd6c3d3ca8c75dc5ec62ebe55330ef910e222060330d54f" + "d0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c1873c5da0a5400" + "008000000080000000800000000000000000010e20010101010101010101010101010101" + "0101010101010101010101010101010101010f0400000000011004fdffffff0001012b50" + "c3000000000000225120a60869f0dbcf1dc659c9cecbaf8050135ea9e8cdc487053f1dc6" + "880949dc684c010e20020202020202020202020202020202020202020202020202020202" + "0202020202010f0400000000011004fdffffff2116cc8a4bc64d897bddc5fbc2f670f7a8" + "ba0b386779106cf1223c6fc5d7cd6fc115190073c5da0a56000080000000800000008000" + "00000000000000011720cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6f" + "c5d7cd6fc1150001012b50c3000000000000225120d8027f90b9f311442f38808d990dee" + "8f167947cc1c27d5cd2cba4f5ae12dc47a010e2003030303030303030303030303030303" + "03030303030303030303030303030303010f0400000000011004fdffffff211683dfe85a" + "3151d2517290da461fe2815591ef69f2b18a2ce63f01697a8b313145190073c5da0a5600" + "00800000008000000080000000000100000001172083dfe85a3151d2517290da461fe281" + "5591ef69f2b18a2ce63f01697a8b313145011820d8849a00c2462b085753298081303b8d" + "b550ed0727d4f83edf45ebcbdc62a0150001012050c300000000000017a9143fb6e95812" + "e57bb4691f9a4a628862a61a4f769b870104160014f990679acafe25c27615373b40bf22" + "446d24ff442206039b3b694b8fc5b5e07fb069c783cac754f5d38c3e08bed1960e31fdb1" + "dda35c241873c5da0a3100008000000080000000800000000000000000010e2004040404" + "04040404040404040404040404040404040404040404040404040404010f040000000001" + "1004fdffffff000100550200000001555555555555555555555555555555555555555555" + "55555555555555555555550000000000ffffffff0150c30000000000001976a914d986ed" + "01b7a22225a70edbf2ba7cfb63a15cb3aa88ac00000000220603aaeb52dd7494c361049d" + "e67cc680e83ebcbbbdbeb13637d92cd845f70308af5e1873c5da0a2c0000800000008000" + "0000800000000000000000010e2033c2cbd93dcec6a303966c5b6a5bd4818b1e8d97b814" + "eaaa677153f7ff90f327010f0400000000011004fdffffff00010308409c000000000000" + "0109420220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4" + "025cc9856d6f8375350e123978daac200c260cb5b5ae83106cab90484dcd8fcf3600"; +static const char ALL_TYPES_SCRIPT[] = + "51201e0380df592360ebcbdb3a9ee26fa3fbc50a0bc926613ed420e9b7bdc46cde30"; +static const char ALL_TYPES_SHARE[] = + "03e5501701d04c123f799cbac147d45329b49fdcf4a87390b6b857dbd8ffc92ce2"; +static const char ALL_TYPES_INPUT_KEY[] = + "02c19905d9e7ae41e4fe52cfbe201ef2bd37801e3dfd0236622ee30773c0d4e93f"; + +/* A P2WPKH script over the key m/86'/0'/0'/0/0 derives, its origin naming that + * path: the path is not what decides the input's type */ +static const char PATH_IGNORED_PSBT[] = + "70736274ff0102040200000001040101010501010106010301fb04020000000001011f50" + "c3000000000000160014efddfdb4cd5211ccd5457e6c237cabcad14d4f39220603cc8a4b" + "c64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc1151873c5da0a5600" + "008000000080000000800000000000000000010e20010101010101010101010101010101" + "0101010101010101010101010101010101010f0400000000011004fdffffff0001030840" + "9c0000000000000109420220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d0" + "1a9bc9a16c96d4025cc9856d6f8375350e123978daac200c260cb5b5ae83106cab90484d" + "cd8fcf3600"; +static const char PATH_IGNORED_SCRIPT[] = + "512038e1589a4202a4f933568fc02633b2aaf8fa7208d533d48c998eee2ab69fe167"; +static const char PATH_IGNORED_SHARE[] = + "0228dbd16ac09f093586b7277a8672ab3a57e661a073d57265593ba4722a00ea41"; +static const char PATH_IGNORED_INPUT_KEY[] = + "03cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115"; + +/* A P2WPKH input of ours, and a P2TR input whose NUMS internal key tweaked by + * its merkle root is the output key: excluded from the key sum, yet holding + * the smallest outpoint */ +static const char NUMS_PSBT[] = + "70736274ff0102040200000001040102010501010106010301fb04020000000001011f50" + "c30000000000001600149c90f934ea51fa0f6504177043e0908da6929983220603e775fd" + "51f0dfb8cd865d9ff1cca2a158cf651fe997fdc9fee9c1d3b5e995ea771873c5da0a5400" + "008000000080000000800000000001000000010e20020202020202020202020202020202" + "0202020202020202020202020202020202010f0400000000011004fdffffff0001012b50" + "c3000000000000225120b78cbf213bd25e507b32ed935f2bd5b3357d5c3710fed71d02b3" + "668625e1d407010e20010101010101010101010101010101010101010101010101010101" + "0101010101010f0400000000011004fdffffff01172050929b74c1a04954b78b4b6035e9" + "7a5e078a5a0f28ec96d547bfee9ace803ac0011820d8849a00c2462b085753298081303b" + "8db550ed0727d4f83edf45ebcbdc62a01500010308409c0000000000000109420220bcfa" + "c5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4025cc9856d6f83" + "75350e123978daac200c260cb5b5ae83106cab90484dcd8fcf3600"; +static const char NUMS_SCRIPT[] = + "5120afd478ef0e753e18bc27079b48fb36a3ee0ffb847fc0f36c4f46bab2c7e66376"; +static const char NUMS_SHARE[] = + "0288f702bd2866312b045b012dc7ac985271968b68876149f65a01233c10a0f0f3"; +static const char NUMS_INPUT_KEY[] = + "03e775fd51f0dfb8cd865d9ff1cca2a158cf651fe997fdc9fee9c1d3b5e995ea77"; + +/* A PSBTv0 whose output carries PSBT_OUT_SP_V0_INFO */ +static const char V0_SP_PSBT[] = + "70736274ff0100520200000001aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaa0000000000fdffffff01409c000000000000160014c0cebcd6c3d3" + "ca8c75dc5ec62ebe55330ef910e2000000000001011f50c3000000000000160014c0cebc" + "d6c3d3ca8c75dc5ec62ebe55330ef910e222060330d54fd0dd420a6e5f8d3624f5f3482c" + "ae350f79d5f0753bf5beef9c2d91af3c1873c5da0a540000800000008000000080000000" + "0000000000000109420220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a" + "9bc9a16c96d4025cc9856d6f8375350e123978daac200c260cb5b5ae83106cab90484dcd" + "8fcf3600"; + +/* Our spend key, unlabeled and labeled with m = 0 and m = 3 (embit + * apply_label) */ +static const char OUR_SPEND[] = + "02fa210b3c4a60b80dd1616f48ae53bbdf0db744b3f9083385108f81be0acb58c6"; +static const char OUR_SPEND_LABEL_0[] = + "031ec096b3e9917a43e81c6d014acab0dfa32151ea7dcdfa56a1dc89f0aec04ef8"; +static const char OUR_SPEND_LABEL_3[] = + "023a6704f3dd61516e4dfebc2c2ebfb30c01b9790bed349c44ccdbeec514acfbbd"; + +/* UNSIGNED_PSBT with a second P2TR input another signer holds: secret 0x33..33 + * negated to its even point, outpoint 0x44..44:1, 50000 sats. Built and + * checked with the BIP352 and BIP374 reference code (bips bip-0375/deps): + * its shares and proofs added to input 1 give TWO_SIGNER_SHARED_PSBT, from + * which the outputs are TWO_SIGNER_SCRIPT_0 and _1. */ +static const char TWO_SIGNER_PSBT[] = + "70736274ff0102040200000001030400000000010401020105010201fb04020000000001" + "012ba086010000000000225120cba15611f961103c8738f27fefa7b774bc6b242f17b55d" + "ae832a3ae2efe332ed010e20222222222222222222222222222222222222222222222222" + "2222222222222222010f0400000000012020111111111111111111111111111111111111" + "11111111111111111111111111110001012b50c30000000000002251203c72addb4fdf09" + "af94f0c94d7fe92a386a7e70cf8a1d85916386bb2535c7b1b1010e204444444444444444" + "444444444444444444444444444444444444444444444444010f04010000000001030860" + "ea0000000000000109420220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d0" + "1a9bc9a16c96d4025cc9856d6f8375350e123978daac200c260cb5b5ae83106cab90484d" + "cd8fcf36000103085898000000000000010942024139b0f81042e243a90478e43990c6a2" + "7be0e3346f0c71adbbcdd511beaea1e3031ec096b3e9917a43e81c6d014acab0dfa32151" + "ea7dcdfa56a1dc89f0aec04ef8010a040000000000"; +static const char TWO_SIGNER_SHARED_PSBT[] = + "70736274ff0102040200000001030400000000010401020105010201fb04020000000001" + "012ba086010000000000225120cba15611f961103c8738f27fefa7b774bc6b242f17b55d" + "ae832a3ae2efe332ed010e20222222222222222222222222222222222222222222222222" + "2222222222222222010f0400000000012020111111111111111111111111111111111111" + "11111111111111111111111111110001012b50c30000000000002251203c72addb4fdf09" + "af94f0c94d7fe92a386a7e70cf8a1d85916386bb2535c7b1b1010e204444444444444444" + "444444444444444444444444444444444444444444444444010f0401000000221d0220bc" + "fac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d421026d2014e0" + "26d2c9fdb76beec54230d4d87f82068661ebb64e501045fd991f514b221d024139b0f810" + "42e243a90478e43990c6a27be0e3346f0c71adbbcdd511beaea1e321029b5d9893db8e8a" + "6c06322377f8e904b3e199d774de4e63429aa8bb35d6a9aecb221e0220bcfac5b99e04ad" + "1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d440614489a351f628739ce9f9" + "7fbe5c6ebdb78f643114dab562e081b1dc0781e21e453248eb7a4dd7151c09f6693ee688" + "cdda8fd0cda2ea90314bbb24d7f9c1d2fe221e024139b0f81042e243a90478e43990c6a2" + "7be0e3346f0c71adbbcdd511beaea1e340a6567e0b00b71ffd32f1818c94b164bb2d85b1" + "29a081958e52d710ef80ab78745e0aa3f8d7770ef9fe79bdfeb631d97a14c57fd0b67d45" + "134908bbec69fb13fe0001030860ea0000000000000109420220bcfac5b99e04ad1a06dd" + "fb016ee13582609d60b6291e98d01a9bc9a16c96d4025cc9856d6f8375350e123978daac" + "200c260cb5b5ae83106cab90484dcd8fcf36000103085898000000000000010942024139" + "b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcdd511beaea1e3031ec096b3e9" + "917a43e81c6d014acab0dfa32151ea7dcdfa56a1dc89f0aec04ef8010a040000000000"; +static const char THEIR_INPUT_KEY[] = + "023c72addb4fdf09af94f0c94d7fe92a386a7e70cf8a1d85916386bb2535c7b1b1"; +static const char TWO_SIGNER_SCRIPT_0[] = + "5120c21383f082a7a51714df23e57d8edf801778e0457d1ae7b6c0ce777a184ac0b2"; +static const char TWO_SIGNER_SCRIPT_1[] = + "51203e3aee0eafdb395acc2d907d71e95b7d70a2ef388c831500e56acf1e261465a5"; + +#endif // SP_FIXTURE_H 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..9b9a2aef 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) {} @@ -83,3 +88,11 @@ void storage_descriptor_filename(storage_location_t loc, const char *id, snprintf(out, out_size, "%s%s%s", loc == STORAGE_FLASH ? STORAGE_DESCRIPTOR_PREFIX : "", id, ext); } + +bool bip138_backup_sp_account_mark(const uint8_t *record, size_t len, + uint8_t mark[BIP138_BACKUP_MARK_LEN]) { + (void)record; + (void)len; + memset(mark, 0, BIP138_BACKUP_MARK_LEN); + return true; +} diff --git a/main/core/test/test_bip138_backup.c b/main/core/test/test_bip138_backup.c index c74f38d6..e008250e 100644 --- a/main/core/test/test_bip138_backup.c +++ b/main/core/test/test_bip138_backup.c @@ -6,9 +6,11 @@ #include "../bip138_backup.h" #include "../bip138_crypto.h" #include "../bip138_keys.h" +#include "../descriptor_checksum.h" #include "../descriptor_validator.h" #include "../key.h" #include "../registry.h" +#include "../silent_payments.h" #include "../storage.h" #include "../wallet.h" #include "esp_err.h" @@ -31,7 +33,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 +43,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 +62,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 +103,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 +122,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 +161,20 @@ 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; + else if (format == STORAGE_DESCRIPTOR_SP_ACCOUNT) + ext = STORAGE_DESCRIPTOR_EXT_SP_ACCOUNT; snprintf(out, out_size, "%s%s%s", loc == STORAGE_FLASH ? STORAGE_DESCRIPTOR_PREFIX : "", id, ext); } @@ -151,6 +185,8 @@ storage_descriptor_format_t storage_descriptor_format(const char *filename) { return STORAGE_DESCRIPTOR_BIP138; if (len > 11 && strcmp(filename + len - 11, ".bip138.txt") == 0) return STORAGE_DESCRIPTOR_BIP138; + if (len > 4 && strcmp(filename + len - 4, ".spa") == 0) + return STORAGE_DESCRIPTOR_SP_ACCOUNT; return STORAGE_DESCRIPTOR_TXT; } @@ -200,35 +236,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 +281,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 +313,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 +331,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 +351,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 +377,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 +392,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 +405,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 +447,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 +486,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 +502,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 +512,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 +526,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 +555,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 +612,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 +664,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 +688,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 +731,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 +777,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 +793,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 +819,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 +830,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 +861,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 +871,301 @@ 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_sp_aliases(void) { + char descriptor[256]; + registry_clear(); + stub_storage_reset(); + check("silent payment alias registers", + registry_add_sp_alias("Silent", NULL) && + strcmp(stub_files[0].filename, "d_ddbcf06726488a43.spa") == 0 && + registry_sp_alias_exists("Silent")); + check("a silent payment alias registers once", + !registry_add_sp_alias("Silent", NULL) && stub_saves == 1 && + registry_name_registered("Silent")); + check("descriptor fixture builds", + build_wpkh("m/84'/0'/2'", descriptor, sizeof(descriptor))); + check("a descriptor cannot take a silent payment alias", + !registry_add_from_string("Silent", descriptor, STORAGE_FLASH, true) && + registry_count() == 0); + check("a silent payment alias cannot take a descriptor id", + registry_add_from_string("Wallet", descriptor, STORAGE_FLASH, false) && + !registry_add_sp_alias("Wallet", NULL) && stub_saves == 1); + registry_init(false); + check("the silent payment alias loads on restart", + registry_sp_alias_exists("Silent") && + !registry_sp_alias_exists("Wallet")); + + check("another seed loads", + key_load_from_mnemonic("zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo " + "wrong", + "", false) && + wallet_init(WALLET_NETWORK_MAINNET)); + registry_init(false); + check("another seed does not load it", !registry_sp_alias_exists("Silent")); + check("original seed on testnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", true) && + wallet_init(WALLET_NETWORK_TESTNET)); + registry_init(true); + check("another network does not load it", + !registry_sp_alias_exists("Silent")); + check("original seed on mainnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", false) && + wallet_init(WALLET_NETWORK_MAINNET)); + registry_init(false); + check("the original seed loads it again", registry_sp_alias_exists("Silent")); + check("the silent payment alias is listed", + registry_sp_alias_count() == 1 && + strcmp(registry_sp_alias_get(0), "Silent") == 0); + + /* "Silent" becomes "Silenu": the record no longer matches its mark */ + stub_files[0].data[stub_files[0].len - BIP138_BACKUP_MARK_LEN - 1]++; + registry_init(false); + check("a record whose alias was changed does not load", + !registry_sp_alias_exists("Silent") && + !registry_sp_alias_exists("Silenu")); + stub_files[0].data[stub_files[0].len - BIP138_BACKUP_MARK_LEN - 1]--; + registry_init(false); + check("de-registration deletes the record", + registry_sp_alias_deregister_at(0) && + strcmp(stub_last_deleted, "d_ddbcf06726488a43.spa") == 0 && + !stub_files[0].present && registry_sp_alias_count() == 0); + registry_init(false); + check("a de-registered alias does not return", + !registry_sp_alias_exists("Silent")); + registry_clear(); + stub_storage_reset(); +} + +/* The scan key of Register Descriptor "3f82-9b", not ours, and label 2 of our + * testnet spend key with it, by the BIP352 label tweak computed outside Kern */ +static const uint8_t FOREIGN_SCAN_KEY[SP_SECRET_LEN] = { + 0x95, 0x73, 0xaf, 0xf4, 0x99, 0xb1, 0x75, 0x5c, 0x5f, 0xbf, 0xd1, + 0x27, 0xf5, 0x08, 0xc7, 0xd2, 0xbc, 0xb5, 0xdd, 0x8c, 0xb0, 0x52, + 0xf2, 0x66, 0x61, 0x04, 0xdb, 0x6f, 0xdf, 0x41, 0xe1, 0x4f}; +static const char FOREIGN_SCAN_LABEL_2_ADDRESS[] = + "tsp1qqw27q4xnw5zzpuk8jfqcgf2nu9dneljr7u0mqu2jlvm3jxhjjtnmvqenvk6gmnrhld3a" + "6j0uscckjdyxs9wrkyufzncfmgz2rd2f6c6ynvmrjsqd"; +static const uint8_t TEST_FINGERPRINT[] = {0x73, 0xc5, 0xda, 0x0a}; + +/* The address of `alias`'s account at label `m`, with the scan key the alias + * was registered with */ +static bool sp_alias_address_is(const char *alias, uint32_t m, + const char *expected) { + struct sp_keys keys; + char *address = NULL; + bool ok = + registry_sp_alias_exists(alias) && + sp_account_keys_derive(true, registry_sp_alias_scan_key(alias), &keys) && + sp_account_address_alloc(keys.scan_secret, keys.spend_pubkey, &m, 1, true, + &address) == SP_ADDRESS_OK && + strcmp(address, expected) == 0; + sp_keys_wipe(&keys); + free(address); + return ok; +} + +static void test_sp_scan_key_aliases(void) { + const size_t header = sizeof(TEST_FINGERPRINT) + 1; + const char alias[] = "3f82-9b"; + registry_clear(); + stub_storage_reset(); + check("original seed on testnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", true) && + wallet_init(WALLET_NETWORK_TESTNET)); + check("an alias registers with a scan key not ours", + registry_add_sp_alias(alias, FOREIGN_SCAN_KEY) && stub_saves == 1 && + stub_files[0].len == header + SP_SECRET_LEN + strlen(alias) + + BIP138_BACKUP_MARK_LEN); + check("its record holds our fingerprint, the network, the scan key and the " + "alias", + memcmp(stub_files[0].data, TEST_FINGERPRINT, 4) == 0 && + stub_files[0].data[4] == WALLET_NETWORK_TESTNET && + memcmp(stub_files[0].data + header, FOREIGN_SCAN_KEY, + SP_SECRET_LEN) == 0 && + memcmp(stub_files[0].data + header + SP_SECRET_LEN, alias, + strlen(alias)) == 0); + registry_init(true); + check("the alias loads with its scan key on restart", + registry_sp_alias_exists(alias) && registry_sp_alias_scan_key(alias) && + memcmp(registry_sp_alias_scan_key(alias), FOREIGN_SCAN_KEY, + SP_SECRET_LEN) == 0); + check("the alias's label 2 address uses its scan key", + sp_alias_address_is(alias, 2, FOREIGN_SCAN_LABEL_2_ADDRESS)); + check("output ownership checks the alias's scan key", + registry_sp_scan_key_get(0) && + memcmp(registry_sp_scan_key_get(0), FOREIGN_SCAN_KEY, + SP_SECRET_LEN) == 0 && + !registry_sp_scan_key_get(1)); + check("an alias of our scan key registers without one", + registry_add_sp_alias("Own", NULL) && registry_sp_alias_exists("Own") && + !registry_sp_alias_scan_key("Own") && + stub_files[2].len == + header + strlen("Own") + BIP138_BACKUP_MARK_LEN && + !registry_sp_scan_key_get(1)); + uint8_t named[SP_SECRET_LEN]; + memset(named, 0x11, sizeof(named)); + check("a scan key the request names follows the registered ones", + registry_sp_name_scan_key(named) && registry_sp_name_scan_key(named) && + registry_sp_scan_key_get(1) && + memcmp(registry_sp_scan_key_get(1), named, sizeof(named)) == 0 && + !registry_sp_scan_key_get(2)); + registry_sp_clear_named_scan_keys(); + check("clearing the named scan keys keeps the registered one", + registry_sp_scan_key_get(0) && !registry_sp_scan_key_get(1)); + + stub_files[0].data[header]++; + registry_init(true); + check("a record whose scan key was changed does not load", + !registry_sp_alias_exists(alias) && registry_sp_alias_exists("Own")); + stub_files[0].data[header]--; + registry_init(true); + check("the restored record loads again", registry_sp_alias_exists(alias)); + registry_clear(); + stub_storage_reset(); + + /* A record written before scan keys were stored: fingerprint, network, + * alias, mark */ + uint8_t record[5 + 3 + BIP138_BACKUP_MARK_LEN]; + memcpy(record, TEST_FINGERPRINT, 4); + record[4] = WALLET_NETWORK_TESTNET; + memcpy(record + 5, "Old", 3); + check("an old record is written", + bip138_backup_sp_account_mark(record, 8, record + 8) && + storage_save_descriptor(STORAGE_FLASH, "0123456789abcdef", record, + sizeof(record), + STORAGE_DESCRIPTOR_SP_ACCOUNT) == ESP_OK); + registry_init(true); + check("an old record loads as an alias of our scan key", + registry_sp_alias_exists("Old") && !registry_sp_alias_scan_key("Old") && + !registry_sp_scan_key_get(0)); + registry_clear(); + stub_storage_reset(); + check("original seed on mainnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", false) && + wallet_init(WALLET_NETWORK_MAINNET)); +} + +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); + + check("original seed on testnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", true) && + wallet_init(WALLET_NETWORK_TESTNET)); + check("a silent payment alias with a scan key not ours registers", + registry_add_sp_alias("3f82-9b", FOREIGN_SCAN_KEY)); + check("unregistering it deletes its record", + registry_unregister("3f82-9b") && + strcmp(stub_last_deleted, "d_915557cfec2af8ee.spa") == 0 && + !stub_find(STORAGE_FLASH, "d_915557cfec2af8ee.spa") && + !registry_sp_alias_exists("3f82-9b") && + !registry_sp_scan_key_get(0)); + registry_init(true); + check("the silent payment alias does not return after a restart", + !registry_sp_alias_exists("3f82-9b") && + !registry_unregister("3f82-9b")); + registry_clear(); + stub_storage_reset(); + check("original seed on mainnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", false) && + wallet_init(WALLET_NETWORK_MAINNET)); +} + static void test_many_origins(void) { registry_clear(); stub_storage_reset(); @@ -806,13 +1211,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 && @@ -830,6 +1235,107 @@ static void test_many_origins(void) { free(many_blob); } +#define MUSIG_ACCOUNT "m/87'/1'/0'" +#define LEGAL_MNEMONIC \ + "legal winner thank year wave sausage worth useful legal winner thank " \ + "yellow" +#define LETTER_MNEMONIC \ + "letter advice cage absurd amount doctor acoustic avoid letter advice " \ + "cage above" + +static bool load_testnet(const char *mnemonic) { + return key_load_from_mnemonic(mnemonic, "", true) && + wallet_init(WALLET_NETWORK_TESTNET); +} + +/* "[fingerprint/87'/1'/0']tpub..." of `mnemonic` */ +static bool musig_account_key(const char *mnemonic, char *out, + size_t out_size) { + char fp[9]; + char *xpub = NULL; + bool ok = load_testnet(mnemonic) && key_get_fingerprint_hex(fp) && + key_get_xpub(MUSIG_ACCOUNT, &xpub); + int n = ok ? snprintf(out, out_size, "[%s/%s]%s", fp, MUSIG_ACCOUNT + 2, xpub) + : 0; + wally_free_string(xpub); + return ok && n > 0 && (size_t)n < out_size; +} + +/* `mnemonic` opens the stored backup, which holds `descriptor` */ +static bool opens_backup(const char *mnemonic, const char *descriptor) { + char *recovered = NULL; + bool ok = load_testnet(mnemonic) && + bip138_backup_decrypt(stub_files[0].data, stub_files[0].len, + &recovered, NULL, NULL) && + strcmp(recovered, descriptor) == 0; + free(recovered); + return ok; +} + +/* Registers `descriptor`, whose keys are the 87'/1'/0' accounts of the test, + * legal and letter seeds, with the test seed loaded, and reloads it after a + * reboot. */ +static void check_musig_backup(const char *descriptor) { + uint8_t keys[BIP138_KEYS_MAX * BIP138_KEY_LEN]; + size_t count = 0; + char checksum[9], stored[1024]; + + registry_clear(); + stub_storage_reset(); + check("musig: test seed loads", load_testnet(TEST_MNEMONIC)); + check("musig: every participant is a recipient", + bip138_keys_from_descriptor(descriptor, WALLY_NETWORK_BITCOIN_TESTNET, + keys, NULL, BIP138_KEYS_MAX, &count) && + count == 3); + check("musig: registration is persisted", + registry_add_from_string("Musig", descriptor, STORAGE_FLASH, true) && + stub_saves == 1 && stub_files[0].present && + stub_files[0].format == STORAGE_DESCRIPTOR_BIP138); + registry_clear(); + registry_init(true); + check("musig: registration reloads after a reboot", + registry_count() == 1 && registry_find_by_id("Musig") != NULL && + registry_find_by_id("Musig")->persisted); + check("musig: the backup holds the descriptor with its checksum", + descriptor_checksum_from_string(descriptor, checksum) && + snprintf(stored, sizeof(stored), "%s#%s", descriptor, checksum) < + (int)sizeof(stored)); + check("musig: the device opens its own backup", + opens_backup(TEST_MNEMONIC, stored)); + check("musig: the legal seed opens the backup", + opens_backup(LEGAL_MNEMONIC, stored)); + check("musig: the letter seed opens the backup", + opens_backup(LETTER_MNEMONIC, stored)); + check("musig: a foreign seed does not open the backup", + !opens_backup("zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", + stored)); + registry_clear(); + stub_storage_reset(); +} + +static void test_musig(void) { + char device[256], legal[256], letter[256], descriptor[1024]; + + check("musig: account keys build", + musig_account_key(TEST_MNEMONIC, device, sizeof(device)) && + musig_account_key(LEGAL_MNEMONIC, legal, sizeof(legal)) && + musig_account_key(LETTER_MNEMONIC, letter, sizeof(letter))); + snprintf(descriptor, sizeof(descriptor), "tr(musig(%s,%s,%s)/<0;1>/*)", + device, legal, letter); + check_musig_backup(descriptor); + snprintf(descriptor, sizeof(descriptor), + "tr(musig(%s/<0;1>/*,%s/<0;1>/*,%s/<0;1>/*))", device, legal, + letter); + check_musig_backup(descriptor); + /* the device key is only in the leaf musig() */ + snprintf(descriptor, sizeof(descriptor), + "tr(%s/<0;1>/*,pk(musig(%s,%s)/<0;1>/*))", legal, device, letter); + check_musig_backup(descriptor); + check("musig: mainnet test seed reloads", + key_load_from_mnemonic(TEST_MNEMONIC, "", false) && + wallet_init(WALLET_NETWORK_MAINNET)); +} + int main(void) { /* The host libwally hashes through PSA, as the device does, which needs * wally_init. */ @@ -854,7 +1360,12 @@ int main(void) { test_private_key_rejected(); test_overwrite_and_duplicates(); test_deregister(); + test_aliases(); + test_sp_aliases(); + test_sp_scan_key_aliases(); + test_unregister(); test_many_origins(); + test_musig(); key_unload(); printf("\n%d tests, %d failed\n", tests_run, tests_failed); return tests_failed == 0 ? 0 : 1; diff --git a/main/core/test/test_bip322.c b/main/core/test/test_bip322.c index 8eda1fb2..c8913127 100644 --- a/main/core/test/test_bip322.c +++ b/main/core/test/test_bip322.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "core/bip322.h" @@ -182,6 +183,49 @@ static void test_message_characters(void) { } } +/* A nonce cache session carries global key 0x09 too, on a regular + * transaction: only the to_sign shape makes a request BIP322. Each case breaks + * one field of it. */ +static void test_detect_requires_to_sign(const uint8_t *raw, size_t raw_len) { + static const struct { + const char *name; + uint32_t version, locktime, index, sequence; + uint64_t satoshi; + unsigned char script; + } cases[] = { + {"version 2", 2, 0, 0, 0, 0, OP_RETURN}, + {"locktime 1", 0, 1, 0, 0, 0, OP_RETURN}, + {"input index 1", 0, 0, 1, 0, 0, OP_RETURN}, + {"sequence 0xffffffff", 0, 0, 0, 0xffffffff, 0, OP_RETURN}, + {"output value 1", 0, 0, 0, 0, 1, OP_RETURN}, + {"output OP_TRUE", 0, 0, 0, 0, 0, OP_TRUE}, + }; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + printf("bip322_detect ignores field 0x09 with %s: ", cases[i].name); + struct wally_psbt *psbt = NULL; + if (wally_psbt_from_bytes(raw, raw_len, 0, &psbt) != WALLY_OK) { + FAIL("PSBT failed to parse"); + continue; + } + struct wally_tx *tx = psbt->tx; + tx->version = cases[i].version; + tx->locktime = cases[i].locktime; + tx->inputs[0].index = cases[i].index; + tx->inputs[0].sequence = cases[i].sequence; + tx->outputs[0].satoshi = cases[i].satoshi; + tx->outputs[0].script[0] = cases[i].script; + bip322_request_t req = {0}; + if (bip322_detect(psbt)) + FAIL("detected on a regular transaction"); + else if (bip322_parse(psbt, true, &req)) + FAIL("parsed a regular transaction"); + else + PASS(); + bip322_request_free(&req); + wally_psbt_free(psbt); + } +} + int main(void) { /* The host libwally hashes through PSA, as the device does, which needs * wally_init. */ @@ -275,6 +319,7 @@ int main(void) { PASS(); /* rejected at parse time (current upstream behavior) */ } + test_detect_requires_to_sign(raw, raw_len); test_message_characters(); printf("\nResults: %d passed, %d failed\n", tests_passed, tests_failed); diff --git a/main/core/test/test_descriptor_validator.c b/main/core/test/test_descriptor_validator.c index b0abfe30..3d70eabc 100644 --- a/main/core/test/test_descriptor_validator.c +++ b/main/core/test/test_descriptor_validator.c @@ -9,6 +9,7 @@ * asynchronous flow, including the stale-callback generation guard. */ +#include "../descriptor_checksum.h" #include "../descriptor_validator.h" #include "../key.h" #include "../registry.h" @@ -36,8 +37,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 +139,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 +162,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 +858,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 +867,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)))", @@ -1028,6 +1043,121 @@ static void test_long_policy(void) { registry_clear(); } +static void test_musig(void) { + registry_clear(); + const char *ours = xpub_at("m/86'/0'/0'"); + const char *other = xpub_at("m/86'/0'/1'"); + + const char *aggregate_then_derive = + descf("tr(musig([" FP "/86'/0'/0']%s,[deadbeef/86'/0'/1']%s)/<0;1>/*)", + ours, other); + check("musig() aggregate then derive accepted", + run(aggregate_then_derive) == VALIDATION_SUCCESS); + check("info: one key of two musig() participants", + info_seen.num_keys == 1 && info_seen.musig_participants == 2); + check("info: our participant shown", + strcmp(info_seen.keys[0].fingerprint_hex, FP_UPPER) == 0 && + strcmp(info_seen.keys[0].xpub, ours) == 0); + check("info: participants listed in place of a path", + strcmp(info_seen.keys[0].derivation, "musig(" FP_UPPER ",DEADBEEF)") == + 0); + check("info: musig() internal key with us is ours", + info_seen.tr_keypath == TR_KEYPATH_OURS); + check("musig() labelled MuSig2", registry_has_label("MuSig2 (2 keys)")); + const registry_entry_t *entry = registry_get(0); + check("registry: our key is the musig() at index 0", + registry_count() == 1 && entry->my_key_index == 0); + check("registry: origin of our participant", + entry->origin_path_len == 3 && entry->origin_path[0] == 0x80000056 && + entry->origin_path[1] == 0x80000000 && + entry->origin_path[2] == 0x80000000); + registry_clear(); + + const char *derive_then_aggregate = descf( + "tr(musig([deadbeef/86'/0'/1']%s/<0;1>/*,[" FP "/86'/0'/0']%s/<0;1>/*))", + other, ours); + check("musig() derive then aggregate accepted, our key second", + run(derive_then_aggregate) == VALIDATION_SUCCESS && + strcmp(info_seen.keys[0].derivation, + "musig(DEADBEEF," FP_UPPER ")") == 0); + registry_clear(); + + const char *with_tree = descf("tr(musig([" FP "/86'/0'/0']%s,[deadbeef/86'/" + "0'/1']%s)/<0;1>/*,pk([deadbeef/86'/0'/2']%s/" + "<0;1>/*))", + ours, other, xpub_at("m/86'/0'/2'")); + check("musig() internal key with a script tree accepted", + run(with_tree) == VALIDATION_SUCCESS); + check("musig() with other keys is not labelled MuSig2", + !registry_has_label("MuSig2 (2 keys)")); + registry_clear(); + + const char *no_origin = + descf("tr(musig([" FP "/86'/0'/0']%s,%s)/<0;1>/*,pk([deadbeef/86'/0'/" + "1']%s/<0;1>/*))", + ours, other, other); + check("musig() internal key with a participant of no origin rejected", + run(no_origin) == VALIDATION_TR_INTERNAL_NOT_UNSPENDABLE); + + const char *wrong_xpub = + descf("tr(musig([" FP "/86'/0'/0']%s,[deadbeef/86'/0'/1']%s)/<0;1>/*)", + other, ours); + check("musig() participant with our fingerprint and another xpub rejected", + run(wrong_xpub) == VALIDATION_XPUB_MISMATCH); + + const char *foreign = + descf("tr(musig([deadbeef/86'/0'/0']%s,[f00dbabe/86'/0'/1']%s)/<0;1>/*)", + ours, other); + check("musig() without our fingerprint rejected", + run(foreign) == VALIDATION_FINGERPRINT_NOT_FOUND); + check("musig() rejections register nothing", registry_count() == 0); +} + +static void test_leaf_musig(void) { + registry_clear(); + const char *ours = xpub_at("m/86'/0'/0'"); + const char *other = xpub_at("m/86'/0'/1'"); + const char *internal = xpub_at("m/86'/0'/2'"); + + const char *leaf = descf("tr([deadbeef/86'/0'/2']%s/<0;1>/*,pk(musig([" FP + "/86'/0'/0']%s,[deadbeef/86'/0'/1']%s)/<0;1>/*))", + internal, ours, other); + check("musig() in a leaf accepted", run(leaf) == VALIDATION_SUCCESS); + check("info: the leaf musig() lists its participants", + info_seen.num_keys == 2 && info_seen.musig_participants == 2 && + strcmp(info_seen.keys[1].fingerprint_hex, FP_UPPER) == 0 && + strcmp(info_seen.keys[1].derivation, + "musig(" FP_UPPER ",DEADBEEF)") == 0); + check("info: the internal key is another's", + info_seen.tr_keypath == TR_KEYPATH_EXTERNAL); + char *text = NULL; + check("the leaf musig() is written back as it came", + registry_count() == 1 && + descriptor_string_from_descriptor(registry_get(0)->desc, &text) && + strstr(text, ",pk(musig([" FP "/86h/0h/0h]") != NULL && + strstr(text, ")/<0;1>/*))#") != NULL); + free(text); + registry_clear(); + + char checksum[9]; + check("checksum of the leaf musig() descriptor", + descriptor_checksum_from_string(leaf, checksum)); + check("a leaf musig() descriptor with its checksum accepted", + run(descf("%s#%s", leaf, checksum)) == VALIDATION_SUCCESS); + registry_clear(); + checksum[0] = checksum[0] == 'q' ? 'p' : 'q'; + check("a leaf musig() descriptor with another checksum rejected", + run(descf("%s#%s", leaf, checksum)) == VALIDATION_PARSE_ERROR); + + const char *derived = + descf("tr([deadbeef/86'/0'/2']%s/<0;1>/*,pk(musig([" FP + "/86'/0'/0']%s/<0;1>/*,[deadbeef/86'/0'/1']%s/<0;1>/*)))", + internal, ours, other); + check("a leaf musig() of derived participants rejected", + run(derived) == VALIDATION_PARSE_ERROR); + check("leaf musig() rejections register nothing", registry_count() == 0); +} + static void test_network(void) { registry_clear(); key_unload(); @@ -1117,6 +1247,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(); @@ -1276,8 +1425,11 @@ int main(void) { test_taproot_keypath(); test_key_cap(); test_long_policy(); + test_musig(); + test_leaf_musig(); test_network(); test_dedup(); + test_persistent_registration(); test_generation_guard(); test_watch_only(); diff --git a/main/core/test/test_dleq.c b/main/core/test/test_dleq.c new file mode 100644 index 00000000..1f43996c --- /dev/null +++ b/main/core/test/test_dleq.c @@ -0,0 +1,167 @@ +#include +#include +#include +#include + +#include +#include + +#include "core/dleq.h" + +static int tests_passed = 0; +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() \ + do { \ + printf("PASS\n"); \ + tests_passed++; \ + } while (0) +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +/* BIP374 vectors, as bwk's sp/src/core/dleq.rs tests carry them */ +static const char GEN_SECRET[] = + "07ff93d43f1012a5d4a44aba55240212ed39c87b3344e46757d99f24177fc576"; +static const char GEN_BASE[] = + "02dad4b35c2379ba8334c9a5dda8f6e6d5cd575a7cc9d3ca4faaac51839daaa30f"; +static const char GEN_AUX[] = + "cb979b0fc8ccc7f237751e719d992fcc324b6500af33999cd54a3e5c05fb1ea4"; +static const char GEN_GENERATOR[] = + "02cef38f55e78b321a1f785cb1c6e33dfcef9784c18bdc4e279801c449ccdfb88e"; +static const char GEN_MESSAGE[] = + "efb07d4b382d3da1079fbf24df623ba6c2e4c764993bbfa6dd7a4fe4aaf33859"; +static const char GEN_PROOF[] = + "7e7e934169e0bf4706e6b29e5a621c7fe199a524744a25af80071e111c0e2e94" + "118e730d8add118dd2ee4f7d1cc183e1b87168362d1a6f85c16d8671a3fc7a8a"; + +static const char VER_GENERATOR[] = + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; +static const char VER_PUBLIC[] = + "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9"; +static const char VER_BASE[] = + "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608"; +static const char VER_SHARED_SECRET[] = + "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a"; +static const char VER_PROOF[] = + "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6b" + "de0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb"; +static const char VER_MESSAGE[] = + "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794"; +static const char VER_OTHER_MESSAGE[] = + "22616bb5fb6d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794"; + +static bool hex_to(const char *hex, unsigned char *out, size_t len) { + size_t written; + return wally_hex_to_bytes(hex, out, len, &written) == WALLY_OK && + written == len; +} + +static secp256k1_pubkey point(const char *hex) { + secp256k1_pubkey out; + unsigned char ser[33]; + memset(&out, 0, sizeof(out)); + if (!hex_to(hex, ser, sizeof(ser)) || + !secp256k1_ec_pubkey_parse(wally_get_secp_context(), &out, ser, + sizeof(ser))) + printf("bad test point %s\n", hex); + return out; +} + +static void test_prove_matches_vector(void) { + unsigned char secret[32], aux[DLEQ_AUX_LEN], message[DLEQ_MESSAGE_LEN]; + unsigned char expected[DLEQ_PROOF_LEN], proof[DLEQ_PROOF_LEN]; + secp256k1_pubkey base = point(GEN_BASE); + secp256k1_pubkey generator = point(GEN_GENERATOR); + + TEST("dleq_prove matches the BIP374 generation vector"); + if (hex_to(GEN_SECRET, secret, sizeof(secret)) && + hex_to(GEN_AUX, aux, sizeof(aux)) && + hex_to(GEN_MESSAGE, message, sizeof(message)) && + hex_to(GEN_PROOF, expected, sizeof(expected)) && + dleq_prove(secret, &base, aux, &generator, message, proof) && + memcmp(proof, expected, sizeof(proof)) == 0) + PASS(); + else + FAIL("proof differs from the vector"); +} + +static void test_verify_vectors(void) { + unsigned char proof[DLEQ_PROOF_LEN]; + unsigned char message[DLEQ_MESSAGE_LEN], other[DLEQ_MESSAGE_LEN]; + secp256k1_pubkey generator = point(VER_GENERATOR); + secp256k1_pubkey public = point(VER_PUBLIC); + secp256k1_pubkey base = point(VER_BASE); + secp256k1_pubkey shared_secret = point(VER_SHARED_SECRET); + + if (!hex_to(VER_PROOF, proof, sizeof(proof)) || + !hex_to(VER_MESSAGE, message, sizeof(message)) || + !hex_to(VER_OTHER_MESSAGE, other, sizeof(other))) { + FAIL("bad verification vector"); + return; + } + + TEST("dleq_verify accepts the BIP374 verification vector"); + if (dleq_verify(&public, &base, &shared_secret, proof, &generator, message)) + PASS(); + else + FAIL("valid proof rejected"); + + TEST("dleq_verify rejects swapped public and base points"); + if (!dleq_verify(&base, &public, &shared_secret, proof, &generator, message)) + PASS(); + else + FAIL("swapped points accepted"); + + TEST("dleq_verify rejects another message"); + if (!dleq_verify(&public, &base, &shared_secret, proof, &generator, other)) + PASS(); + else + FAIL("other message accepted"); + + TEST("dleq_verify rejects a tampered response"); + proof[DLEQ_PROOF_LEN - 1] ^= 0x01; + if (!dleq_verify(&public, &base, &shared_secret, proof, &generator, message)) + PASS(); + else + FAIL("tampered proof accepted"); +} + +/* The silent payments use: generator G and no message */ +static void test_prove_without_message(void) { + const secp256k1_context *ctx = wally_get_secp_context(); + unsigned char secret[32], aux[DLEQ_AUX_LEN] = {0}, proof[DLEQ_PROOF_LEN]; + secp256k1_pubkey generator = point(VER_GENERATOR); + secp256k1_pubkey base = point(VER_BASE); + secp256k1_pubkey public, shared_secret; + + shared_secret = base; + TEST("dleq_prove with G and no message verifies"); + if (hex_to(GEN_SECRET, secret, sizeof(secret)) && + secp256k1_ec_pubkey_create(ctx, &public, secret) && + secp256k1_ec_pubkey_tweak_mul(ctx, &shared_secret, secret) && + dleq_prove(secret, &base, aux, &generator, NULL, proof) && + dleq_verify(&public, &base, &shared_secret, proof, &generator, NULL)) + PASS(); + else + FAIL("proof without message failed"); + + TEST("dleq_verify rejects a proof against another base"); + if (!dleq_verify(&public, &generator, &shared_secret, proof, &generator, + NULL)) + PASS(); + else + FAIL("proof accepted for another base"); +} + +int main(void) { + test_prove_matches_vector(); + test_verify_vectors(); + test_prove_without_message(); + + printf("\n%d passed, %d failed\n", tests_passed, tests_failed); + return tests_failed ? 1 : 0; +} 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_musig_psbt.c b/main/core/test/test_musig_psbt.c new file mode 100644 index 00000000..b97f5eea --- /dev/null +++ b/main/core/test/test_musig_psbt.c @@ -0,0 +1,1444 @@ +/* + * MuSig2 PSBT tests (core/musig_psbt.c). + * + * Runs against the real key, wallet, registry and nonce cache modules with the + * BIP39 test mnemonic loaded on testnet; sessions live in the simulator's NVS + * under a fresh temp directory. Our participant is the account 86'/1'/0'; the + * cosigner is the account 86'/1'/1' of the same seed, given another + * fingerprint so the registry takes it for a foreign key, and the test signs + * for it with libwally's own MuSig2 PSBT functions. + */ + +#include "core/key.h" +#include "core/musig_psbt.h" +#include "core/nonce_cache.h" +#include "core/psbt_internal.h" +#include "core/registry.h" +#include "core/sp_psbt.h" +#include "core/storage.h" +#include "core/wallet.h" +#include "esp_err.h" +#include "sim_nvs.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int tests_run = 0; +static int tests_failed = 0; + +static void check(const char *name, bool ok) { + tests_run++; + if (!ok) + tests_failed++; + printf("Testing: %s... %s\n", name, ok ? "PASS" : "FAIL"); +} + +/* ---------- storage stubs (registry persistence is never reached) ---------- + */ + +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) { + (void)loc; + (void)id; + (void)data; + (void)len; + (void)format; + return ESP_OK; +} + +esp_err_t storage_delete_descriptor(storage_location_t loc, + const char *filename) { + (void)loc; + (void)filename; + return ESP_OK; +} + +esp_err_t storage_list_descriptors(storage_location_t loc, + char ***filenames_out, int *count_out) { + (void)loc; + *filenames_out = NULL; + *count_out = 0; + 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) { + (void)loc; + (void)filename; + *data_out = NULL; + *len_out = 0; + *format_out = STORAGE_DESCRIPTOR_TXT; + return -1; +} + +void storage_free_file_list(char **files, int count) { + (void)files; + (void)count; +} + +/* ---------- fixtures ---------- */ + +static const char *TEST_MNEMONIC = "abandon abandon abandon abandon abandon " + "abandon abandon abandon abandon abandon " + "abandon about"; +#define FP "73c5da0a" +#define OURS "m/86'/1'/0'" +#define COSIGNER "m/86'/1'/1'" +#define CHILD 3 +#define AMOUNT 50000 + +/* musig() of the participant keys at 0/CHILD */ +#define DERIVE_THEN_AGGREGATE \ + "tr(musig([" FP "/86'/1'/0']%s/<0;1>/*,[deadbeef/86'/1'/1']%s/<0;1>/*))" +/* musig() of the account keys, derived at 0/CHILD after aggregation */ +#define AGGREGATE_THEN_DERIVE \ + "tr(musig([" FP "/86'/1'/0']%s,[deadbeef/86'/1'/1']%s)/<0;1>/*)" + +/* The same on a recovery path's <2;3> */ +#define AGGREGATE_THEN_DERIVE_RECOVERY \ + "tr(musig([" FP "/86'/1'/0']%s,[deadbeef/86'/1'/1']%s)/<2;3>/*)" +/* musig() of the participant keys at 2/CHILD or 3/CHILD */ +#define DERIVE_THEN_AGGREGATE_RECOVERY \ + "tr(musig([" FP "/86'/1'/0']%s/<2;3>/*,[deadbeef/86'/1'/1']%s/<2;3>/*))" + +static const unsigned char OUR_FP[4] = {0x73, 0xc5, 0xda, 0x0a}; +static const unsigned char SYNTHETIC_FP[4] = {0xaa, 0xbb, 0xcc, 0xdd}; + +static char descriptor_buf[1024]; + +static const char *xpub_at(const char *path, char *out, size_t len) { + char *xpub = NULL; + if (!key_get_xpub(path, &xpub)) + return ""; + snprintf(out, len, "%s", xpub); + wally_free_string(xpub); + return out; +} + +static bool register_descriptor(const char *fmt) { + char ours[128], cosigner[128]; + snprintf(descriptor_buf, sizeof(descriptor_buf), fmt, + xpub_at(OURS, ours, sizeof(ours)), + xpub_at(COSIGNER, cosigner, sizeof(cosigner))); + registry_clear(); + return registry_add_from_string("m", descriptor_buf, STORAGE_FLASH, false); +} + +/* fp | path little endian, as PSBT_IN_TAP_BIP32_DERIVATION carries it */ +static size_t origin(const unsigned char *fp, const uint32_t *path, size_t len, + unsigned char *out) { + memcpy(out, fp, 4); + for (size_t i = 0; i < len; i++) + for (size_t b = 0; b < 4; b++) + out[4 + 4 * i + b] = (unsigned char)(path[i] >> (8 * b)); + return 4 + 4 * len; +} + +static size_t script_at(uint32_t multi_index, uint32_t child_num, + unsigned char *spk) { + unsigned char work[PSBT_MAX_INNER_SCRIPT_LEN]; + size_t written = 0; + if (wally_descriptor_to_script(registry_get(0)->desc, 0, 0, 0, multi_index, + child_num, 0, work, sizeof(work), + &written) != WALLY_OK || + written != WALLY_SCRIPTPUBKEY_P2TR_LEN) + return 0; + memcpy(spk, work, written); + return written; +} + +static bool claims(const unsigned char *fp, uint32_t multi_index, + uint32_t child_num, const unsigned char *spk, size_t spk_len, + claim_t *claim) { + const uint32_t path[] = {multi_index, child_num}; + unsigned char value[4 + 4 * 2]; + struct wally_map map; + wally_map_init(1, NULL, &map); + wally_map_add(&map, spk + 2, 32, value, origin(fp, path, 2, value)); + bool claimed = musig_psbt_claim(&map, spk, spk_len, claim); + wally_map_clear(&map); + return claimed; +} + +/* ---------- claim ---------- */ + +static void test_claim(void) { + check("musig() descriptor registers", + register_descriptor(AGGREGATE_THEN_DERIVE)); + const registry_entry_t *entry = registry_get(0); + unsigned char receive[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + unsigned char change[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + size_t receive_len = script_at(0, 5, receive); + size_t change_len = script_at(1, 5, change); + check("scripts generate", receive_len && change_len); + + claim_t claim; + check("receive script claimed at 0/5", + claims(SYNTHETIC_FP, 0, 5, receive, receive_len, &claim) && + claim.kind == CLAIM_MUSIG && claim.registry.entry == entry && + claim.registry.multi_index == 0 && claim.registry.child_num == 5); + check("change script claimed at 1/5", + claims(SYNTHETIC_FP, 1, 5, change, change_len, &claim) && + claim.registry.multi_index == 1 && claim.registry.child_num == 5); + check("receive script with a change origin refused", + !claims(SYNTHETIC_FP, 1, 5, receive, receive_len, &claim)); + check("receive script with another child refused", + !claims(SYNTHETIC_FP, 0, 6, receive, receive_len, &claim)); + check("hardened child refused", + !claims(SYNTHETIC_FP, 0, 0x80000005, receive, receive_len, &claim)); + check("multipath index past the descriptor's refused", + !claims(SYNTHETIC_FP, 2, 5, receive, receive_len, &claim)); + check("hardened step before the child refused", + !claims(SYNTHETIC_FP, 0x80000000, 5, receive, receive_len, &claim)); + unsigned char p2wpkh[22] = {0x00, 0x14}; + check("non-taproot script refused", + !claims(SYNTHETIC_FP, 0, 5, p2wpkh, sizeof(p2wpkh), &claim)); + + check("musig() descriptor on <2;3> registers", + register_descriptor(AGGREGATE_THEN_DERIVE_RECOVERY)); + entry = registry_get(0); + receive_len = script_at(0, 5, receive); + change_len = script_at(1, 5, change); + check("<2;3> scripts generate", receive_len && change_len); + check("<2;3> script at 2/5 claimed at tuple position 0", + claims(SYNTHETIC_FP, 2, 5, receive, receive_len, &claim) && + claim.kind == CLAIM_MUSIG && claim.registry.entry == entry && + claim.registry.multi_index == 0 && claim.registry.child_num == 5); + check("<2;3> script at 3/5 claimed at tuple position 1", + claims(SYNTHETIC_FP, 3, 5, change, change_len, &claim) && + claim.registry.multi_index == 1 && claim.registry.child_num == 5); + check("<2;3> script with another child refused", + !claims(SYNTHETIC_FP, 3, 6, change, change_len, &claim)); + check("<2;3> receive script with a 3/5 origin refused", + !claims(SYNTHETIC_FP, 3, 5, receive, receive_len, &claim)); + check("<2;3> receive script with a 0/5 origin refused", + !claims(SYNTHETIC_FP, 0, 5, receive, receive_len, &claim)); + + char ours[128]; + snprintf(descriptor_buf, sizeof(descriptor_buf), + "tr([" FP "/86'/1'/0']%s/<0;1>/*)", + xpub_at(OURS, ours, sizeof(ours))); + registry_clear(); + check("plain taproot descriptor registers", + registry_add_from_string("t", descriptor_buf, STORAGE_FLASH, false)); + receive_len = script_at(0, 5, receive); + check("a descriptor without our musig() claims nothing", + receive_len && !claims(OUR_FP, 0, 5, receive, receive_len, &claim)); + registry_clear(); +} + +/* ---------- signing ---------- */ + +/* A key of the test seed, with its private key. */ +static struct ext_key *key_at(const char *path) { + struct ext_key *key = NULL; + return key_get_derived_key(path, &key) ? key : NULL; +} + +/* The key at descriptor key index `index`, at 0/`child_num`, as libwally + * derives it from the registered descriptor: a musig()'s derived aggregate. */ +static bool descriptor_key_at(uint32_t index, uint32_t child_num, + unsigned char *pub_out) { + struct ext_key key; + bool ok = wally_descriptor_derive_bip32_key( + registry_get(0)->desc, index, 0, 0, child_num, + BIP32_FLAG_KEY_PUBLIC, &key) == WALLY_OK; + if (ok) + memcpy(pub_out, key.pub_key, EC_PUBLIC_KEY_LEN); + wally_bzero(&key, sizeof(key)); + return ok; +} + +typedef struct { + struct wally_psbt *psbt; + unsigned char ours[EC_PUBLIC_KEY_LEN]; + unsigned char cosigner[EC_PUBLIC_KEY_LEN]; + unsigned char cosigner_sk[EC_PRIVATE_KEY_LEN]; + /* the KeyAgg key of PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS */ + unsigned char aggregate[EC_PUBLIC_KEY_LEN]; + /* the aggregate of the key path's BIP-373 keys: the output key */ + unsigned char output[EC_PUBLIC_KEY_LEN]; +} fixture_t; + +static void fixture_free(fixture_t *f) { + wally_psbt_free(f->psbt); + wally_bzero(f->cosigner_sk, sizeof(f->cosigner_sk)); + memset(f, 0, sizeof(*f)); +} + +static bool fixture_keys(const char *ours_path, const char *cosigner_path, + fixture_t *f) { + struct ext_key *ours = key_at(ours_path); + struct ext_key *cosigner = key_at(cosigner_path); + bool ok = ours && cosigner; + if (ok) { + memcpy(f->ours, ours->pub_key, EC_PUBLIC_KEY_LEN); + memcpy(f->cosigner, cosigner->pub_key, EC_PUBLIC_KEY_LEN); + memcpy(f->cosigner_sk, cosigner->priv_key + 1, EC_PRIVATE_KEY_LEN); + } + bip32_key_free(ours); + bip32_key_free(cosigner); + return ok; +} + +/* A one-input PSBT spending the registered descriptor's script at + * 0/`child_num`, with the PSBT_IN_TAP_BIP32_DERIVATION `origin` of the x-only + * `key` the claim reads. */ +static bool spend_alloc(uint32_t child_num, const unsigned char *key, + const unsigned char *origin, size_t origin_len, + struct wally_psbt **psbt_out) { + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + size_t spk_len = script_at(0, child_num, spk); + static const unsigned char txid[32] = {7}; + struct wally_tx *tx = NULL; + struct wally_tx_output *utxo = NULL; + bool ok = + spk_len && wally_psbt_init_alloc(0, 1, 1, 1, 0, psbt_out) == WALLY_OK && + wally_tx_init_alloc(2, 0, 1, 1, &tx) == WALLY_OK && + wally_tx_add_raw_input(tx, txid, sizeof(txid), 0, 0xfffffffd, NULL, 0, + NULL, 0) == WALLY_OK && + wally_tx_add_raw_output(tx, AMOUNT - 500, spk, spk_len, 0) == WALLY_OK && + wally_psbt_set_global_tx(*psbt_out, tx) == WALLY_OK && + wally_tx_output_init_alloc(AMOUNT, spk, spk_len, &utxo) == WALLY_OK && + wally_psbt_set_input_witness_utxo(*psbt_out, 0, utxo) == WALLY_OK && + wally_map_add(&(*psbt_out)->inputs[0].taproot_leaf_paths, key, 32, origin, + origin_len) == WALLY_OK && + /* libwally serializes an origin only beside its leaf hashes, none here */ + wally_map_merkle_path_add(&(*psbt_out)->inputs[0].taproot_leaf_hashes, + key, 32, NULL, 0) == WALLY_OK; + wally_tx_free(tx); + wally_tx_output_free(utxo); + return ok; +} + +/* A one-input PSBT spending the registered descriptor's script at 0/CHILD. + * `origin` is the PSBT_IN_TAP_BIP32_DERIVATION value the claim reads, and + * `asked` says whether the input asks for MuSig2 with a 0x1a. */ +static bool fixture(const char *ours_path, const char *cosigner_path, + const unsigned char *origin, size_t origin_len, bool asked, + fixture_t *f) { + memset(f, 0, sizeof(*f)); + if (!fixture_keys(ours_path, cosigner_path, f)) + return false; + + unsigned char keys[2 * EC_PUBLIC_KEY_LEN], xonly[32]; + bool ours_first = memcmp(f->ours, f->cosigner, EC_PUBLIC_KEY_LEN) < 0; + memcpy(keys, ours_first ? f->ours : f->cosigner, EC_PUBLIC_KEY_LEN); + memcpy(keys + EC_PUBLIC_KEY_LEN, ours_first ? f->cosigner : f->ours, + EC_PUBLIC_KEY_LEN); + struct wally_musig_keyagg_cache *cache = NULL; + bool aggregated = wally_musig_pubkey_agg(keys, sizeof(keys), xonly, + sizeof(xonly), &cache) == WALLY_OK && + wally_musig_pubkey_get(cache, f->aggregate, + EC_PUBLIC_KEY_LEN) == WALLY_OK; + wally_musig_keyagg_cache_free(cache); + if (!aggregated) + return false; + + bool ok = spend_alloc(CHILD, f->ours + 1, origin, origin_len, &f->psbt); + if (ok && asked) + ok = wally_psbt_input_add_musig2_participant_pubkeys( + &f->psbt->inputs[0], f->aggregate, EC_PUBLIC_KEY_LEN, keys, + sizeof(keys)) == WALLY_OK; + return ok; +} + +/* The output key of a tr() without a script tree: the internal key libwally + * derives, tweaked, checked against the spent script. */ +static bool key_path_output(fixture_t *f) { + unsigned char internal[EC_PUBLIC_KEY_LEN]; + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + return descriptor_key_at(0, CHILD, internal) && script_at(0, CHILD, spk) && + wally_ec_public_key_bip341_tweak(internal, sizeof(internal), NULL, 0, + 0, f->output, + sizeof(f->output)) == WALLY_OK && + memcmp(f->output + 1, spk + 2, EC_XONLY_PUBLIC_KEY_LEN) == 0; +} + +static bool has_entry(const struct wally_map *map, const unsigned char *a, + const unsigned char *b) { + unsigned char key[2 * EC_PUBLIC_KEY_LEN]; + size_t found = 0; + memcpy(key, a, EC_PUBLIC_KEY_LEN); + memcpy(key + EC_PUBLIC_KEY_LEN, b, EC_PUBLIC_KEY_LEN); + return wally_map_find(map, key, sizeof(key), &found) == WALLY_OK && found; +} + +static musig_step_t step_of(struct wally_psbt *psbt) { + musig_plan_t plan; + if (musig_psbt_plan(psbt, NULL, &plan) != MUSIG_PSBT_OK) + return (musig_step_t)-1; + musig_step_t step = plan.step; + musig_plan_free(&plan); + return step; +} + +static musig_psbt_result_t check_session(struct wally_psbt *psbt) { + musig_plan_t plan; + musig_psbt_result_t result = musig_psbt_plan(psbt, NULL, &plan); + if (result == MUSIG_PSBT_OK) + result = musig_psbt_check_session(psbt, &plan); + musig_plan_free(&plan); + return result; +} + +static musig_psbt_result_t sign(struct wally_psbt *psbt, size_t *added) { + musig_plan_t plan; + *added = 0; + musig_psbt_result_t result = musig_psbt_plan(psbt, NULL, &plan); + if (result == MUSIG_PSBT_OK) + result = musig_psbt_sign(psbt, &plan, added); + musig_plan_free(&plan); + return result; +} + +static musig_psbt_result_t check_request(const struct wally_psbt *psbt) { + unsigned char bytes[4096]; + size_t len = 0; + if (wally_psbt_to_bytes(psbt, 0, bytes, sizeof(bytes), &len) != WALLY_OK || + len > sizeof(bytes)) + return (musig_psbt_result_t)-1; + return musig_psbt_check_request(bytes, len, true); +} + +#define MAX_PARTICIPANTS 3 + +static int compare_keys(const void *a, const void *b) { + return memcmp(a, b, EC_PUBLIC_KEY_LEN); +} + +/* BIP-327 key aggregation of `n` keys in BIP-390 order, then the BIP-328 + * tweaks of `steps` from the synthetic xpub of the aggregate, written here + * apart from musig_psbt.c's own. */ +static struct wally_musig_keyagg_cache *key_agg(const unsigned char *keys, + size_t n, const uint32_t *steps, + size_t num_steps) { + unsigned char sorted[MAX_PARTICIPANTS * EC_PUBLIC_KEY_LEN], xonly[32]; + unsigned char aggregate[EC_PUBLIC_KEY_LEN], data[37], hmac[64]; + unsigned char chain_code[32]; + struct wally_musig_keyagg_cache *cache = NULL; + struct ext_key *synthetic = NULL; + if (n > MAX_PARTICIPANTS) + return NULL; + memcpy(sorted, keys, n * EC_PUBLIC_KEY_LEN); + qsort(sorted, n, EC_PUBLIC_KEY_LEN, compare_keys); + bool ok = + wally_musig_pubkey_agg(sorted, n * EC_PUBLIC_KEY_LEN, xonly, + sizeof(xonly), &cache) == WALLY_OK && + wally_musig_pubkey_get(cache, aggregate, sizeof(aggregate)) == WALLY_OK && + wally_musig_pubkey_to_xpub(aggregate, sizeof(aggregate), + BIP32_VER_TEST_PUBLIC, &synthetic) == WALLY_OK; + if (ok) { + memcpy(chain_code, synthetic->chain_code, sizeof(chain_code)); + memcpy(data, aggregate, EC_PUBLIC_KEY_LEN); + } + bip32_key_free(synthetic); + for (size_t i = 0; ok && i < num_steps; i++) { + data[33] = (unsigned char)(steps[i] >> 24); + data[34] = (unsigned char)(steps[i] >> 16); + data[35] = (unsigned char)(steps[i] >> 8); + data[36] = (unsigned char)steps[i]; + ok = wally_hmac_sha512(chain_code, sizeof(chain_code), data, sizeof(data), + hmac, sizeof(hmac)) == WALLY_OK && + wally_musig_pubkey_ec_tweak_add(cache, hmac, 32, data, 33) == WALLY_OK; + memcpy(chain_code, hmac + 32, sizeof(chain_code)); + } + if (!ok) { + wally_musig_keyagg_cache_free(cache); + return NULL; + } + return cache; +} + +/* The BIP-341 tweak of a key aggregation to sign the key path, by the + * output's `merkle_root`, NULL without a script tree. */ +static bool tap_tweak(struct wally_musig_keyagg_cache *cache, + const unsigned char *merkle_root) { + unsigned char internal[EC_PUBLIC_KEY_LEN], output[EC_PUBLIC_KEY_LEN]; + unsigned char data[2 * SHA256_LEN], tweak[SHA256_LEN]; + size_t data_len = EC_XONLY_PUBLIC_KEY_LEN; + if (wally_musig_pubkey_get(cache, internal, sizeof(internal)) != WALLY_OK) + return false; + memcpy(data, internal + 1, EC_XONLY_PUBLIC_KEY_LEN); + if (merkle_root) { + memcpy(data + data_len, merkle_root, SHA256_LEN); + data_len += SHA256_LEN; + } + return wally_bip340_tagged_hash(data, data_len, "TapTweak", tweak, + sizeof(tweak)) == WALLY_OK && + wally_musig_pubkey_xonly_tweak_add(cache, tweak, sizeof(tweak), output, + sizeof(output)) == WALLY_OK; +} + +/* The key path's BIP-341 sighash, of the input's PSBT_IN_SIGHASH_TYPE. */ +static bool key_path_sighash(struct wally_psbt *psbt, unsigned char *sighash) { + struct wally_tx *tx = psbt_tx_alloc(psbt); + bool ok = tx && wally_psbt_get_input_signature_hash( + psbt, 0, tx, NULL, 0, 0, sighash, SHA256_LEN) == WALLY_OK; + wally_tx_free(tx); + return ok; +} + +/* A cosigner of a musig(), and its secret nonce once it gave one. */ +typedef struct { + const unsigned char *pub; + const unsigned char *sk; + struct wally_musig_secnonce *secnonce; +} cosigner_t; + +/* A BIP-327 nonce of the cosigner, bound to nothing, added under the BIP-373 + * key of `aggregate` and `leaf_hash`, NULL on the key path; its secret nonce + * is kept. */ +static bool cosigner_nonce(struct wally_psbt *psbt, cosigner_t *c, + const unsigned char *aggregate, + const unsigned char *leaf_hash) { + unsigned char rand[32] = {0x42, c->pub[1], aggregate[1]}; + unsigned char nonce[WALLY_MUSIG_PUBNONCE_LEN]; + struct wally_musig_pubnonce *pubnonce = NULL; + bool ok = + wally_musig_nonce_gen(rand, sizeof(rand), c->sk, EC_PRIVATE_KEY_LEN, + c->pub, EC_PUBLIC_KEY_LEN, NULL, NULL, 0, NULL, 0, + &c->secnonce, &pubnonce) == WALLY_OK && + wally_musig_pubnonce_serialize(pubnonce, nonce, sizeof(nonce)) == + WALLY_OK && + wally_psbt_input_add_musig2_pubnonce( + &psbt->inputs[0], c->pub, EC_PUBLIC_KEY_LEN, aggregate, + EC_PUBLIC_KEY_LEN, leaf_hash, leaf_hash ? SHA256_LEN : 0, nonce, + sizeof(nonce)) == WALLY_OK; + wally_musig_pubnonce_free(pubnonce); + return ok; +} + +/* The fixture's cosigner nonce, its secret nonce dropped. */ +static bool add_cosigner_nonce(fixture_t *f, const unsigned char *aggregate, + const unsigned char *leaf_hash) { + cosigner_t cosigner = {.pub = f->cosigner, .sk = f->cosigner_sk}; + bool ok = cosigner_nonce(f->psbt, &cosigner, aggregate, leaf_hash); + wally_musig_secnonce_free(cosigner.secnonce); + return ok; +} + +/* The value of the PSBT's BIP-373 entry `participant | aggregate + * [| leaf_hash]`, or NULL when the map has none of `value_len` bytes. */ +static const unsigned char *entry(const struct wally_map *map, + const unsigned char *participant, + const unsigned char *aggregate, + const unsigned char *leaf_hash, + size_t value_len) { + unsigned char key[2 * EC_PUBLIC_KEY_LEN + SHA256_LEN]; + size_t key_len = 2 * EC_PUBLIC_KEY_LEN, index = 0; + memcpy(key, participant, EC_PUBLIC_KEY_LEN); + memcpy(key + EC_PUBLIC_KEY_LEN, aggregate, EC_PUBLIC_KEY_LEN); + if (leaf_hash) { + memcpy(key + key_len, leaf_hash, SHA256_LEN); + key_len += SHA256_LEN; + } + if (wally_map_find(map, key, key_len, &index) != WALLY_OK || !index || + map->items[index - 1].value_len != value_len) + return NULL; + return map->items[index - 1].value; +} + +/* The BIP-340 signature of every participant: our partial signature the PSBT + * carries under the BIP-373 key of `aggregate` and `leaf_hash`, and each + * cosigner's made on the nonces it carries under that key with `cache`, the + * key aggregation that signs. It must verify against `aggregate` for + * `sighash`. */ +static bool signature_verifies(const struct wally_psbt *psbt, + const unsigned char *ours, cosigner_t *cosigners, + size_t num_cosigners, + struct wally_musig_keyagg_cache *cache, + const unsigned char *aggregate, + const unsigned char *leaf_hash, + const unsigned char *sighash) { + const struct wally_psbt_input *input = &psbt->inputs[0]; + size_t n = num_cosigners + 1; + unsigned char nonces[MAX_PARTICIPANTS * WALLY_MUSIG_PUBNONCE_LEN]; + unsigned char partial_sigs[MAX_PARTICIPANTS * WALLY_MUSIG_PARTIAL_SIG_LEN]; + unsigned char sig[64]; + const unsigned char *our_nonce = + entry(&input->musig2_pubnonces, ours, aggregate, leaf_hash, + WALLY_MUSIG_PUBNONCE_LEN); + const unsigned char *our_partial_sig = + entry(&input->musig2_partial_sigs, ours, aggregate, leaf_hash, + WALLY_MUSIG_PARTIAL_SIG_LEN); + bool ok = n <= MAX_PARTICIPANTS && our_nonce && our_partial_sig; + if (ok) { + memcpy(nonces, our_nonce, WALLY_MUSIG_PUBNONCE_LEN); + memcpy(partial_sigs, our_partial_sig, WALLY_MUSIG_PARTIAL_SIG_LEN); + } + for (size_t i = 0; ok && i < num_cosigners; i++) { + const unsigned char *nonce = + entry(&input->musig2_pubnonces, cosigners[i].pub, aggregate, leaf_hash, + WALLY_MUSIG_PUBNONCE_LEN); + ok = nonce != NULL; + if (ok) + memcpy(nonces + (i + 1) * WALLY_MUSIG_PUBNONCE_LEN, nonce, + WALLY_MUSIG_PUBNONCE_LEN); + } + + struct wally_musig_aggnonce *aggnonce = NULL; + struct wally_musig_session *session = NULL; + ok = ok && + wally_musig_nonce_agg(nonces, n * WALLY_MUSIG_PUBNONCE_LEN, n, + &aggnonce) == WALLY_OK && + wally_musig_nonce_process(aggnonce, sighash, SHA256_LEN, cache, NULL, 0, + &session) == WALLY_OK; + for (size_t i = 0; ok && i < num_cosigners; i++) { + struct wally_musig_partial_sig *partial_sig = NULL; + ok = wally_musig_partial_sign(cosigners[i].secnonce, cosigners[i].sk, + EC_PRIVATE_KEY_LEN, cache, session, + &partial_sig) == WALLY_OK && + wally_musig_partial_sig_serialize( + partial_sig, partial_sigs + (i + 1) * WALLY_MUSIG_PARTIAL_SIG_LEN, + WALLY_MUSIG_PARTIAL_SIG_LEN) == WALLY_OK; + wally_musig_partial_sig_free(partial_sig); + } + ok = + ok && + wally_musig_partial_sig_agg(partial_sigs, n * WALLY_MUSIG_PARTIAL_SIG_LEN, + n, session, sig, sizeof(sig)) == WALLY_OK && + wally_ec_sig_verify(aggregate + 1, EC_XONLY_PUBLIC_KEY_LEN, sighash, + SHA256_LEN, EC_FLAG_SCHNORR, sig, + sizeof(sig)) == WALLY_OK; + wally_musig_session_free(session); + wally_musig_aggnonce_free(aggnonce); + return ok; +} + +/* The fixture's two participants aggregated, then derived along `steps` + * (BIP-328) when the musig() has a path. */ +static struct wally_musig_keyagg_cache * +fixture_key_agg(const fixture_t *f, const uint32_t *steps, size_t num_steps) { + unsigned char participants[2 * EC_PUBLIC_KEY_LEN]; + memcpy(participants, f->ours, EC_PUBLIC_KEY_LEN); + memcpy(participants + EC_PUBLIC_KEY_LEN, f->cosigner, EC_PUBLIC_KEY_LEN); + return key_agg(participants, 2, steps, num_steps); +} + +/* The fixture's key path signature verifies: see signature_verifies(). */ +static bool key_path_verifies(fixture_t *f, cosigner_t *cosigner, + const uint32_t *steps, size_t num_steps) { + unsigned char sighash[SHA256_LEN]; + struct wally_musig_keyagg_cache *cache = fixture_key_agg(f, steps, num_steps); + bool ok = cache && tap_tweak(cache, NULL) && + key_path_sighash(f->psbt, sighash) && + signature_verifies(f->psbt, f->ours, cosigner, 1, cache, f->output, + NULL, sighash); + wally_musig_keyagg_cache_free(cache); + return ok; +} + +/* Derive then aggregate: the cosigner signs with libwally's BIP-327 + * functions, every BIP-373 entry keyed by the output key as Bitcoin Core and + * Ledger key it, and the aggregate must be a BIP-340 signature of the output + * key. */ +static void test_two_rounds(void) { + check("derive then aggregate registers", + register_descriptor(DERIVE_THEN_AGGREGATE)); + const uint32_t path[] = {0x80000056, 0x80000001, 0x80000000, 0, CHILD}; + unsigned char value[4 + 4 * 5]; + size_t value_len = origin(OUR_FP, path, 5, value); + fixture_t f; + check("PSBT builds", + fixture(OURS "/0/3", COSIGNER "/0/3", value, value_len, true, &f) && + key_path_output(&f)); + + musig_plan_t plan; + check("plan has our one signature, keyed by the output key, in round 1", + musig_psbt_plan(f.psbt, NULL, &plan) == MUSIG_PSBT_OK && + plan.num_slots == 1 && plan.step == MUSIG_STEP_PUB_NONCES && + memcmp(plan.slots[0].participant, f.ours, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(plan.slots[0].aggregate, f.output, EC_PUBLIC_KEY_LEN) == 0 && + plan.slots[0].key_expression_index == 0); + musig_plan_free(&plan); + + size_t added = 0; + check( + "round 1 adds our public nonce under the output key", + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + has_entry(&f.psbt->inputs[0].musig2_pubnonces, f.ours, f.output) && + !has_entry(&f.psbt->inputs[0].musig2_pubnonces, f.ours, f.aggregate)); + check("round 1 signs nothing", + f.psbt->inputs[0].musig2_partial_sigs.num_items == 0); + struct wally_psbt *trimmed = psbt_trim(f.psbt); + check("a trimmed answer keeps our public nonce", + trimmed && + has_entry(&trimmed->inputs[0].musig2_pubnonces, f.ours, f.output)); + wally_psbt_free(trimmed); + check("our participant is ours, the cosigner's is not", + musig_psbt_is_own_participant(f.psbt, 0, f.ours) && + !musig_psbt_is_own_participant(f.psbt, 0, f.cosigner)); + check("waiting for the cosigner's nonce asks nothing of us", + step_of(f.psbt) == MUSIG_STEP_NOTHING && + check_request(f.psbt) == MUSIG_PSBT_ERR_NOTHING); + check("a cosigner nonce under the KeyAgg key is not the key path's", + add_cosigner_nonce(&f, f.aggregate, NULL) && + step_of(f.psbt) == MUSIG_STEP_NOTHING); + + cosigner_t cosigner = {.pub = f.cosigner, .sk = f.cosigner_sk}; + check("cosigner adds its nonce under the output key", + cosigner_nonce(f.psbt, &cosigner, f.output, NULL)); + check("every nonce in: round 2 on the held session", + step_of(f.psbt) == MUSIG_STEP_PARTIAL_SIGS && + check_session(f.psbt) == MUSIG_PSBT_OK && + check_request(f.psbt) == MUSIG_PSBT_OK); + check( + "round 2 adds our partial signature under the output key", + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + has_entry(&f.psbt->inputs[0].musig2_partial_sigs, f.ours, f.output)); + check("the session is consumed: no second signature", + check_session(f.psbt) == MUSIG_PSBT_ERR_SESSION && + check_request(f.psbt) == MUSIG_PSBT_ERR_SESSION && + sign(f.psbt, &added) == MUSIG_PSBT_ERR_SESSION && added == 0); + + check("the partial signatures make a BIP-340 signature of the output key", + key_path_verifies(&f, &cosigner, NULL, 0)); + wally_musig_secnonce_free(cosigner.secnonce); + fixture_free(&f); + + check("PSBT without 0x1a builds", + fixture(OURS "/0/3", COSIGNER "/0/3", value, value_len, false, &f)); + check("an input without 0x1a asks no MuSig2 signature", + step_of(f.psbt) == MUSIG_STEP_NONE && + check_request(f.psbt) == MUSIG_PSBT_OK); + fixture_free(&f); + registry_clear(); +} + +/* SIGHASH_ALL: the partial signatures sign the message of the input's type, + * the aggregator appends the type byte. */ +static void test_sighash_all(void) { + check("derive then aggregate registers", + register_descriptor(DERIVE_THEN_AGGREGATE)); + const uint32_t path[] = {0x80000056, 0x80000001, 0x80000000, 0, CHILD}; + unsigned char value[4 + 4 * 5]; + size_t value_len = origin(OUR_FP, path, 5, value); + fixture_t f; + check("PSBT with SIGHASH_ALL builds", + fixture(OURS "/0/3", COSIGNER "/0/3", value, value_len, true, &f) && + key_path_output(&f) && + wally_psbt_set_input_sighash(f.psbt, 0, WALLY_SIGHASH_ALL) == + WALLY_OK); + size_t added = 0; + cosigner_t cosigner = {.pub = f.cosigner, .sk = f.cosigner_sk}; + check("round 1, then the cosigner's nonce", + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + cosigner_nonce(f.psbt, &cosigner, f.output, NULL)); + check("round 2 signs the SIGHASH_ALL message", + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1); + check("the partial signatures make a signature of the SIGHASH_ALL message", + key_path_verifies(&f, &cosigner, NULL, 0)); + wally_musig_secnonce_free(cosigner.secnonce); + fixture_free(&f); + + check("PSBT with SIGHASH_NONE builds", + fixture(OURS "/0/3", COSIGNER "/0/3", value, value_len, true, &f) && + key_path_output(&f) && + wally_psbt_set_input_sighash(f.psbt, 0, WALLY_SIGHASH_NONE) == + WALLY_OK && + sign(f.psbt, &added) == MUSIG_PSBT_OK && + add_cosigner_nonce(&f, f.output, NULL)); + check("SIGHASH_NONE is refused, as Kern refuses it for every signature", + sign(f.psbt, &added) == MUSIG_PSBT_ERR_INVALID && added == 0); + fixture_free(&f); + registry_clear(); +} + +/* Beside silent payment outputs psbt_sign signs with SIGHASH_ALL, and keeps + * the field on an input given a public nonce or partial signature: neither + * carries a sighash byte, so the aggregator reads it from the PSBT. */ +static void test_sighash_all_beside_silent_payments(void) { + check("derive then aggregate registers", + register_descriptor(DERIVE_THEN_AGGREGATE)); + const uint32_t path[] = {0x80000056, 0x80000001, 0x80000000, 0, CHILD}; + unsigned char value[4 + 4 * 5]; + size_t value_len = origin(OUR_FP, path, 5, value); + static const unsigned char info_key[] = {PSBT_OUT_SP_V0_INFO}; + unsigned char info[2 * EC_PUBLIC_KEY_LEN] = {0}; + fixture_t f; + check("PSBT with a silent payment output builds", + fixture(OURS "/0/3", COSIGNER "/0/3", value, value_len, true, &f) && + key_path_output(&f) && + wally_map_add(&f.psbt->outputs[0].unknowns, info_key, + sizeof(info_key), info, sizeof(info)) == WALLY_OK); + psbt_sign_policy_t policy = {0}; + size_t sighash = 0; + check("round 1 keeps SIGHASH_ALL on the input given our public nonce", + psbt_sign(f.psbt, true, policy, NULL) == 1 && + has_entry(&f.psbt->inputs[0].musig2_pubnonces, f.ours, f.output) && + wally_psbt_get_input_sighash(f.psbt, 0, &sighash) == WALLY_OK && + sighash == WALLY_SIGHASH_ALL); + fixture_free(&f); + registry_clear(); +} + +/* Aggregate then derive: our slot exists only when the BIP-328 tweaks give + * libwally's output key for the descriptor. */ +static void test_aggregate_then_derive(void) { + check("aggregate then derive registers", + register_descriptor(AGGREGATE_THEN_DERIVE)); + const uint32_t path[] = {0, CHILD}; + unsigned char value[4 + 4 * 2]; + fixture_t f; + check("PSBT builds", + fixture(OURS, COSIGNER, value, origin(SYNTHETIC_FP, path, 2, value), + true, &f) && + key_path_output(&f)); + size_t added = 0; + check("round 1 adds our public nonce under the output key", + step_of(f.psbt) == MUSIG_STEP_PUB_NONCES && + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + has_entry(&f.psbt->inputs[0].musig2_pubnonces, f.ours, f.output)); + cosigner_t cosigner = {.pub = f.cosigner, .sk = f.cosigner_sk}; + check("cosigner nonce added", + cosigner_nonce(f.psbt, &cosigner, f.output, NULL)); + check( + "round 2 adds our partial signature under the output key", + step_of(f.psbt) == MUSIG_STEP_PARTIAL_SIGS && + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + has_entry(&f.psbt->inputs[0].musig2_partial_sigs, f.ours, f.output)); + check("the partial signatures make a BIP-340 signature of the output key", + key_path_verifies(&f, &cosigner, path, 2)); + wally_musig_secnonce_free(cosigner.secnonce); + fixture_free(&f); + registry_clear(); +} + +static bool issue_session(const unsigned char *session_id, uint8_t *ref_out, + unsigned char *nonce_out) { + bnc_issuance request = {.inputs = 1, .start = 0, .end = 0}; + uint8_t fresh[BNC_SECRET_LEN]; + bool new_session = false; + struct ext_key *key = key_at(OURS); + memcpy(request.session_id, session_id, BNC_SESSION_ID_LEN); + bool ok = key && nonce_cache_fresh_secret(fresh) && + bnc_issue(nonce_cache_signer(), &request, fresh, key->priv_key + 1, + key->pub_key, ref_out, &new_session, nonce_out, + BNC_PUBNONCE_LEN) == BNC_OK && + new_session; + bip32_key_free(key); + return ok; +} + +static bool name_session(struct wally_psbt *psbt, const unsigned char *id, + const uint8_t *ref) { + static const unsigned char key[1] = {BNC_PSBT_GLOBAL_NONCE_CACHE_SESSION}; + unsigned char value[BNC_SESSION_ID_LEN + BNC_SESSION_REF_LEN]; + memcpy(value, id, BNC_SESSION_ID_LEN); + memcpy(value + BNC_SESSION_ID_LEN, ref, BNC_SESSION_REF_LEN); + return wally_map_replace(&psbt->unknowns, key, sizeof(key), value, + sizeof(value)) == WALLY_OK; +} + +/* Our nonce under the BIP-373 key of `aggregate`, on the key path. */ +static bool set_own_nonce(fixture_t *f, const unsigned char *aggregate, + const unsigned char *nonce) { + return wally_psbt_input_add_musig2_pubnonce( + &f->psbt->inputs[0], f->ours, EC_PUBLIC_KEY_LEN, aggregate, + EC_PUBLIC_KEY_LEN, NULL, 0, nonce, BNC_PUBNONCE_LEN) == WALLY_OK; +} + +/* One round from a session issued before the PSBT existed. */ +static void test_cached_session(void) { + static const unsigned char id[BNC_SESSION_ID_LEN] = {9, 8, 7, 6}; + const uint32_t path[] = {0, CHILD}; + unsigned char value[4 + 4 * 2], nonce[BNC_PUBNONCE_LEN]; + unsigned char other_nonce[BNC_PUBNONCE_LEN]; + uint8_t ref[BNC_SESSION_REF_LEN], other_ref[BNC_SESSION_REF_LEN]; + fixture_t f; + check("aggregate then derive registers", + register_descriptor(AGGREGATE_THEN_DERIVE)); + check("session issued", issue_session(id, ref, nonce)); + check("PSBT builds", + fixture(OURS, COSIGNER, value, origin(SYNTHETIC_FP, path, 2, value), + true, &f) && + key_path_output(&f)); + check("cached nonce and cosigner nonce added", + set_own_nonce(&f, f.output, nonce) && + add_cosigner_nonce(&f, f.output, NULL)); + + memcpy(other_ref, ref, sizeof(ref)); + other_ref[0] ^= 1; + check("a session named with another reference is refused", + name_session(f.psbt, id, other_ref) && + step_of(f.psbt) == MUSIG_STEP_CACHED && + check_request(f.psbt) == MUSIG_PSBT_ERR_SESSION); + + memcpy(other_nonce, nonce, sizeof(other_nonce)); + other_nonce[1] ^= 1; + check("a nonce the session does not give is refused", + name_session(f.psbt, id, ref) && + set_own_nonce(&f, f.output, other_nonce) && + check_session(f.psbt) == MUSIG_PSBT_ERR_SESSION); + + fixture_t g; + check("PSBT with only our nonce builds", + fixture(OURS, COSIGNER, value, origin(SYNTHETIC_FP, path, 2, value), + true, &g) && + key_path_output(&g) && name_session(g.psbt, id, ref) && + set_own_nonce(&g, g.output, other_nonce)); + check("a nonce the session does not give is refused before the cosigner's " + "is looked for", + check_session(g.psbt) == MUSIG_PSBT_ERR_SESSION && + check_request(g.psbt) == MUSIG_PSBT_ERR_SESSION); + fixture_free(&g); + + check("PSBT with our nonce under the KeyAgg key builds", + fixture(OURS, COSIGNER, value, origin(SYNTHETIC_FP, path, 2, value), + true, &g) && + key_path_output(&g) && name_session(g.psbt, id, ref) && + set_own_nonce(&g, g.aggregate, nonce) && + add_cosigner_nonce(&g, g.aggregate, NULL)); + check("the KeyAgg key is not the key path's BIP-373 aggregate: refused", + check_session(g.psbt) == MUSIG_PSBT_ERR_SESSION && + check_request(g.psbt) == MUSIG_PSBT_ERR_SESSION); + fixture_free(&g); + + /* A nonce keyed by the cosigner's key as the aggregate: no slot of ours */ + check("PSBT with every nonce builds", + fixture(OURS, COSIGNER, value, origin(SYNTHETIC_FP, path, 2, value), + true, &g) && + key_path_output(&g) && name_session(g.psbt, id, ref) && + set_own_nonce(&g, g.output, nonce) && + add_cosigner_nonce(&g, g.output, NULL)); + check("the cosigner's nonce on another aggregate is not ours to refuse", + wally_psbt_input_add_musig2_pubnonce( + &g.psbt->inputs[0], g.cosigner, EC_PUBLIC_KEY_LEN, g.cosigner, + EC_PUBLIC_KEY_LEN, NULL, 0, nonce, BNC_PUBNONCE_LEN) == WALLY_OK && + check_session(g.psbt) == MUSIG_PSBT_OK); + check("our nonce on an aggregate no slot signs is refused", + wally_psbt_input_add_musig2_pubnonce( + &g.psbt->inputs[0], g.ours, EC_PUBLIC_KEY_LEN, g.cosigner, + EC_PUBLIC_KEY_LEN, NULL, 0, nonce, BNC_PUBNONCE_LEN) == WALLY_OK && + check_session(g.psbt) == MUSIG_PSBT_ERR_SESSION && + check_request(g.psbt) == MUSIG_PSBT_ERR_SESSION); + fixture_free(&g); + + size_t added = 0; + check( + "the named session signs in one round, under the output key", + set_own_nonce(&f, f.output, nonce) && + check_request(f.psbt) == MUSIG_PSBT_OK && + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + has_entry(&f.psbt->inputs[0].musig2_partial_sigs, f.ours, f.output)); + check("the named session is consumed", + check_request(f.psbt) == MUSIG_PSBT_ERR_SESSION); + fixture_free(&f); + registry_clear(); +} + +/* ---------- tapscript leaf ---------- */ + +/* musig() of the account keys in a leaf, beside another internal key */ +#define LEAF \ + "tr([deadbeef/86'/1'/2']%s/<0;1>/*,pk(musig([" FP \ + "/86'/1'/0']%s,[deadbeef/86'/1'/1']%s)/<0;1>/*))" +#define INTERNAL "m/86'/1'/2'" +#define LEAF_SCRIPT_LEN (1 + EC_XONLY_PUBLIC_KEY_LEN + 1) +#define TAPSCRIPT_LEAF_VERSION 0xc0 +#define PSBT_IN_TAP_MERKLE_ROOT 0x18 + +static bool register_leaf_descriptor(void) { + char ours[128], cosigner[128], internal[128]; + snprintf(descriptor_buf, sizeof(descriptor_buf), LEAF, + xpub_at(INTERNAL, internal, sizeof(internal)), + xpub_at(OURS, ours, sizeof(ours)), + xpub_at(COSIGNER, cosigner, sizeof(cosigner))); + registry_clear(); + return registry_add_from_string("l", descriptor_buf, STORAGE_FLASH, false); +} + +typedef struct { + unsigned char key[EC_PUBLIC_KEY_LEN]; + unsigned char script[LEAF_SCRIPT_LEN]; + unsigned char hash[SHA256_LEN]; +} leaf_t; + +/* pk(leaf key) of the descriptor's key 1 at 0/`child_num`, its BIP-341 + * control block in a one-leaf tree under key 0, and the tree's merkle root, + * added to the PSBT's input; checks the output key. */ +static bool add_leaf(struct wally_psbt *psbt, uint32_t child_num, + leaf_t *leaf) { + unsigned char internal[EC_PUBLIC_KEY_LEN], output[EC_PUBLIC_KEY_LEN]; + unsigned char data[2 + LEAF_SCRIPT_LEN], control[1 + 32]; + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + if (!descriptor_key_at(0, child_num, internal) || + !descriptor_key_at(1, child_num, leaf->key) || + !script_at(0, child_num, spk)) + return false; + leaf->script[0] = EC_XONLY_PUBLIC_KEY_LEN; + memcpy(leaf->script + 1, leaf->key + 1, EC_XONLY_PUBLIC_KEY_LEN); + leaf->script[LEAF_SCRIPT_LEN - 1] = 0xac; /* OP_CHECKSIG */ + data[0] = TAPSCRIPT_LEAF_VERSION; + data[1] = LEAF_SCRIPT_LEN; + memcpy(data + 2, leaf->script, LEAF_SCRIPT_LEN); + internal[0] = 0x02; + if (wally_bip340_tagged_hash(data, sizeof(data), "TapLeaf", leaf->hash, + sizeof(leaf->hash)) != WALLY_OK || + wally_ec_public_key_bip341_tweak(internal, sizeof(internal), leaf->hash, + sizeof(leaf->hash), 0, output, + sizeof(output)) != WALLY_OK || + memcmp(output + 1, spk + 2, 32) != 0) + return false; + control[0] = TAPSCRIPT_LEAF_VERSION | (output[0] == 0x03); + memcpy(control + 1, internal + 1, 32); + return wally_psbt_input_add_taproot_leaf_script( + &psbt->inputs[0], control, sizeof(control), leaf->script, + sizeof(leaf->script)) == WALLY_OK && + wally_map_add_integer(&psbt->inputs[0].psbt_fields, + PSBT_IN_TAP_MERKLE_ROOT, leaf->hash, + sizeof(leaf->hash)) == WALLY_OK; +} + +/* The leaf's BIP-342 sighash, SIGHASH_DEFAULT. */ +static bool leaf_sighash(struct wally_psbt *psbt, const leaf_t *leaf, + unsigned char *sighash) { + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + size_t spk_len = 0; + const uint64_t values[] = {psbt_get_input_value(psbt, 0)}; + struct wally_map scripts = {0}; + struct wally_tx *tx = psbt_tx_alloc(psbt); + bool ok = tx && psbt_input_utxo_script(psbt, 0, spk, sizeof(spk), &spk_len) && + wally_map_init(1, NULL, &scripts) == WALLY_OK && + wally_map_add_integer(&scripts, 0, spk, spk_len) == WALLY_OK && + wally_tx_get_btc_taproot_signature_hash( + tx, 0, &scripts, values, 1, leaf->script, sizeof(leaf->script), + 0, WALLY_NO_CODESEPARATOR, NULL, 0, WALLY_SIGHASH_DEFAULT, 0, + sighash, SHA256_LEN) == WALLY_OK; + wally_map_clear(&scripts); + wally_tx_free(tx); + return ok; +} + +/* Two rounds on a leaf: every BIP-373 entry keyed by the key the leaf + * pushes, as Bitcoin Core and Ledger key it, and the aggregate must be a + * BIP-340 signature of that key, which libwally derives from the + * descriptor. */ +static void test_leaf(void) { + check("musig() in a leaf registers", register_leaf_descriptor()); + const uint32_t path[] = {0, CHILD}; + unsigned char value[4 + 4 * 2]; + fixture_t f; + leaf_t leaf; + check("PSBT with the leaf builds", + fixture(OURS, COSIGNER, value, origin(SYNTHETIC_FP, path, 2, value), + true, &f) && + add_leaf(f.psbt, CHILD, &leaf)); + + musig_plan_t plan; + check("plan has our leaf signature, keyed by the leaf key, in round 1", + musig_psbt_plan(f.psbt, NULL, &plan) == MUSIG_PSBT_OK && + plan.num_slots == 1 && plan.step == MUSIG_STEP_PUB_NONCES && + plan.slots[0].has_leaf_hash && + memcmp(plan.slots[0].leaf_hash, leaf.hash, SHA256_LEN) == 0 && + memcmp(plan.slots[0].aggregate, leaf.key, EC_PUBLIC_KEY_LEN) == 0 && + plan.slots[0].key_expression_index == 0); + musig_plan_free(&plan); + + size_t added = 0; + check("round 1 adds our leaf public nonce under the leaf key", + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + entry(&f.psbt->inputs[0].musig2_pubnonces, f.ours, leaf.key, + leaf.hash, WALLY_MUSIG_PUBNONCE_LEN) && + !entry(&f.psbt->inputs[0].musig2_pubnonces, f.ours, f.aggregate, + leaf.hash, WALLY_MUSIG_PUBNONCE_LEN)); + check("a cosigner nonce under the KeyAgg key is not the leaf's", + add_cosigner_nonce(&f, f.aggregate, leaf.hash) && + step_of(f.psbt) == MUSIG_STEP_NOTHING); + + cosigner_t cosigner = {.pub = f.cosigner, .sk = f.cosigner_sk}; + check("cosigner adds its leaf nonce under the leaf key", + cosigner_nonce(f.psbt, &cosigner, leaf.key, leaf.hash)); + check("round 2 adds our leaf partial signature under the leaf key", + step_of(f.psbt) == MUSIG_STEP_PARTIAL_SIGS && + sign(f.psbt, &added) == MUSIG_PSBT_OK && added == 1 && + entry(&f.psbt->inputs[0].musig2_partial_sigs, f.ours, leaf.key, + leaf.hash, WALLY_MUSIG_PARTIAL_SIG_LEN)); + + unsigned char key[EC_PUBLIC_KEY_LEN], sighash[SHA256_LEN]; + struct wally_musig_keyagg_cache *cache = fixture_key_agg(&f, path, 2); + check("the BIP-328 tweaks give libwally's leaf key", + cache && wally_musig_pubkey_get(cache, key, sizeof(key)) == WALLY_OK && + memcmp(key, leaf.key, EC_PUBLIC_KEY_LEN) == 0); + check("the partial signatures make a BIP-340 signature of the leaf key", + cache && leaf_sighash(f.psbt, &leaf, sighash) && + signature_verifies(f.psbt, f.ours, &cosigner, 1, cache, leaf.key, + leaf.hash, sighash)); + wally_musig_keyagg_cache_free(cache); + wally_musig_secnonce_free(cosigner.secnonce); + fixture_free(&f); + registry_clear(); +} + +/* ---------- nonce preparation ---------- */ + +static const uint32_t ACCOUNT_PATH[] = {0x80000056, 0x80000001, 0x80000000}; + +static nonce_cache_result_t prepare(bnc_issuance *request, bool draw, + const uint32_t *path, size_t path_len, + uint8_t *nonces, size_t count, + nonce_cache_issued_t *issued) { + return nonce_cache_issue(request, draw, path, path_len, nonces, + count * BNC_PUBNONCE_LEN, issued); +} + +static void test_nonce_preparation(void) { + bnc_issuance request = {.inputs = 2, .start = 0, .end = 2}; + uint8_t nonces[6 * BNC_PUBNONCE_LEN], chunk[2 * BNC_PUBNONCE_LEN]; + nonce_cache_issued_t issued, again; + check("a request without session ID draws one for a new session", + prepare(&request, true, ACCOUNT_PATH, 3, nonces, 6, &issued) == + NONCE_CACHE_OK && + issued.new_session && + memcmp(issued.session_id, request.session_id, BNC_SESSION_ID_LEN) == + 0); + + bnc_issuance extend = { + .has_session_ref = 1, .inputs = 2, .start = 2, .end = 2}; + memcpy(extend.session_id, issued.session_id, BNC_SESSION_ID_LEN); + memcpy(extend.session_ref, issued.session_ref, BNC_SESSION_REF_LEN); + check("a chunk of the session comes from it, positioned by index then input", + prepare(&extend, false, ACCOUNT_PATH, 3, chunk, 2, &again) == + NONCE_CACHE_OK && + !again.new_session && + memcmp(again.session_ref, issued.session_ref, + BNC_SESSION_REF_LEN) == 0 && + memcmp(chunk, nonces + 4 * BNC_PUBNONCE_LEN, sizeof(chunk)) == 0); + + extend.session_ref[0] ^= 1; + check("a reference of another session is refused", + prepare(&extend, false, ACCOUNT_PATH, 3, chunk, 2, &again) == + NONCE_CACHE_ERR_SESSION); + bnc_issuance unknown = extend; + unknown.session_id[0] ^= 1; + bnc_secret *secret = NULL; + check("a reference without a held session is refused and creates none", + prepare(&unknown, false, ACCOUNT_PATH, 3, chunk, 2, &again) == + NONCE_CACHE_ERR_SESSION && + bnc_held_session(nonce_cache_signer(), unknown.session_id, NULL, + &secret) == BNC_ERR_UNKNOWN_SESSION); + check("a request without a key path is refused", + prepare(&request, false, ACCOUNT_PATH, 0, nonces, 6, &issued) == + NONCE_CACHE_ERR_INVALID); + check("a nonce buffer of another size is refused", + prepare(&request, false, ACCOUNT_PATH, 3, nonces, 5, &issued) == + NONCE_CACHE_ERR_INVALID); +} + +/* ---------- key path and leaf of three seeds ---------- */ + +/* musig() of the accounts 87'/1'/0' of three seeds on the key path, of the + * first two in a leaf; the expected keys are the ones a Bitcoin Core or + * Ledger coordinator keys its BIP-373 entries by at 0/7 */ +#define THREE_SEEDS \ + "tr(musig([73c5da0a/87'/1'/0']tpubDCChhoz5Qdrkn7Z7KXawq6Ad6r3A4MUkCoVTqeWx" \ + "fTkA6bHNJ3CHUEtALQdkNeixNz4446PcAmw4WKcj3mV2vb29H7sg9EPzbyCU1y2merw,[b868" \ + "8df1/87'/1'/0']tpubDC44ZFebbFm5ZXnG5Xt8k9PpdSZXUQ4HyuU8e8u5zfutYuu8EW4MLK" \ + "S54EFTfGYgeqt7P2jEEd1iCF5kSPi7Xrj6EZcsStCcAjPy97DSiLb,[28645006/87'/1'/0'" \ + "]tpubDCs6kWyAq2CsViTz5YR3tKpCQ4kq2xwDmERmF5cGet45CsHAqR8wbQGRin6fzLJgCdrK" \ + "fYts4ddyTJ7Zo4ocmG1zHK3vw71mh32wj25WmsT)/<0;1>/*,pk(musig([73c5da0a/87'/1" \ + "'/0']tpubDCChhoz5Qdrkn7Z7KXawq6Ad6r3A4MUkCoVTqeWxfTkA6bHNJ3CHUEtALQdkNeix" \ + "Nz4446PcAmw4WKcj3mV2vb29H7sg9EPzbyCU1y2merw,[b8688df1/87'/1'/0']tpubDC44Z" \ + "FebbFm5ZXnG5Xt8k9PpdSZXUQ4HyuU8e8u5zfutYuu8EW4MLKS54EFTfGYgeqt7P2jEEd1iCF" \ + "5kSPi7Xrj6EZcsStCcAjPy97DSiLb)/<0;1>/*))#dqt5r5m9" +#define SEED_B \ + "legal winner thank year wave sausage worth useful legal winner thank " \ + "yellow" +#define SEED_C \ + "letter advice cage absurd amount doctor acoustic avoid letter advice cage " \ + "above" +#define THREE_SEEDS_CHILD 7 + +static const uint32_t ACCOUNT_87[] = {0x80000057, 0x80000001, 0x80000000}; + +static bool from_hex(const char *hex, unsigned char *out, size_t len) { + size_t written = 0; + return wally_hex_to_bytes(hex, out, len, &written) == WALLY_OK && + written == len; +} + +/* The account 87'/1'/0' of a BIP-39 seed without passphrase. */ +static struct ext_key *seed_account(const char *mnemonic) { + unsigned char seed[BIP39_SEED_LEN_512]; + struct ext_key *root = NULL, *account = NULL; + bool ok = + bip39_mnemonic_to_seed512(mnemonic, NULL, seed, sizeof(seed)) == + WALLY_OK && + bip32_key_from_seed_alloc(seed, sizeof(seed), BIP32_VER_TEST_PRIVATE, 0, + &root) == WALLY_OK && + bip32_key_from_parent_path_alloc( + root, ACCOUNT_87, 3, BIP32_FLAG_KEY_PRIVATE, &account) == WALLY_OK; + wally_bzero(seed, sizeof(seed)); + bip32_key_free(root); + return ok ? account : NULL; +} + +/* PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS of `n` keys, in BIP-390 order, under + * their KeyAgg key, written to `aggregate_out`. */ +static bool add_participants(struct wally_psbt *psbt, const unsigned char *keys, + size_t n, unsigned char *aggregate_out) { + unsigned char sorted[MAX_PARTICIPANTS * EC_PUBLIC_KEY_LEN]; + struct wally_musig_keyagg_cache *cache = key_agg(keys, n, NULL, 0); + memcpy(sorted, keys, n * EC_PUBLIC_KEY_LEN); + qsort(sorted, n, EC_PUBLIC_KEY_LEN, compare_keys); + bool ok = cache && + wally_musig_pubkey_get(cache, aggregate_out, EC_PUBLIC_KEY_LEN) == + WALLY_OK && + wally_psbt_input_add_musig2_participant_pubkeys( + &psbt->inputs[0], aggregate_out, EC_PUBLIC_KEY_LEN, sorted, + n * EC_PUBLIC_KEY_LEN) == WALLY_OK; + wally_musig_keyagg_cache_free(cache); + return ok; +} + +/* Our nonce from the prepared session under the BIP-373 key of `aggregate` + * and `leaf_hash`, as the coordinator places it. */ +static bool add_own_nonce(struct wally_psbt *psbt, const unsigned char *ours, + const unsigned char *aggregate, + const unsigned char *leaf_hash, + const unsigned char *nonce) { + return wally_psbt_input_add_musig2_pubnonce( + &psbt->inputs[0], ours, EC_PUBLIC_KEY_LEN, aggregate, + EC_PUBLIC_KEY_LEN, leaf_hash, leaf_hash ? SHA256_LEN : 0, nonce, + BNC_PUBNONCE_LEN) == WALLY_OK; +} + +/* One round from a prepared nonce cache session on the key path and the leaf, + * every BIP-373 entry keyed as Bitcoin Core and Ledger key it; the partial + * signatures of the three seeds must make BIP-340 signatures of the output + * key and of the leaf key. */ +static void test_three_seeds(void) { + unsigned char a_key[EC_PUBLIC_KEY_LEN], b_key[EC_PUBLIC_KEY_LEN]; + unsigned char c_key[EC_PUBLIC_KEY_LEN], keyagg_abc[EC_PUBLIC_KEY_LEN]; + unsigned char keyagg_ab[EC_PUBLIC_KEY_LEN], output[EC_PUBLIC_KEY_LEN]; + unsigned char spk[WALLY_SCRIPTPUBKEY_P2TR_LEN]; + unsigned char internal[EC_XONLY_PUBLIC_KEY_LEN]; + unsigned char leaf_key[EC_PUBLIC_KEY_LEN], leaf_hash[SHA256_LEN]; + check("expected keys parse", + from_hex("024fa60842fe43fd476291703aa69974a2322e835f37c6acd4f22d4b152f1" + "5039b", + a_key, sizeof(a_key)) && + from_hex("0208c426b56c36540026267f37e3ca01126ac96da1e2c704836a76a7" + "b78dc93590", + b_key, sizeof(b_key)) && + from_hex("031fea37b0a22086455bc208edf029696ca8cdbee9a1243085f53239" + "b52fd2c375", + c_key, sizeof(c_key)) && + from_hex("028cbbd5f38ab6a0ec50c0888428caccc00cb660a152efd9b54fa3eb" + "e330eaa7bd", + keyagg_abc, sizeof(keyagg_abc)) && + from_hex("021e4240bacca55cb106a7546000c79549350df61064a51d2d6154f5" + "7bec0d75fb", + keyagg_ab, sizeof(keyagg_ab)) && + from_hex("02b213d1062e1202e6e390daea9ba20a0d79adcced3130979966469f" + "a5166c8ff1", + output, sizeof(output)) && + from_hex("5120b213d1062e1202e6e390daea9ba20a0d79adcced313097996646" + "9fa5166c8ff1", + spk, sizeof(spk)) && + from_hex("e7e775f5f6020d5d286b223d1f2e6d0934d635caf43f440f8276f727" + "7d00d567", + internal, sizeof(internal)) && + from_hex("020c5727de797ed735ac403e1a5cc96defda99935bfb8c023ea9b9c7" + "e5b378b365", + leaf_key, sizeof(leaf_key)) && + from_hex("e75d416537d0f55af33cf851edb7ea99749fc681c655c57f0572e53b" + "6cef5754", + leaf_hash, sizeof(leaf_hash))); + + registry_clear(); + check("the three seeds' wallet registers", + registry_add_from_string("w", THREE_SEEDS, STORAGE_FLASH, false)); + struct ext_key *a = key_at("m/87'/1'/0'"); + struct ext_key *b = seed_account(SEED_B); + struct ext_key *c = seed_account(SEED_C); + check("each seed gives its participant key", + a && b && c && memcmp(a->pub_key, a_key, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(b->pub_key, b_key, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(c->pub_key, c_key, EC_PUBLIC_KEY_LEN) == 0); + + unsigned char script[WALLY_SCRIPTPUBKEY_P2TR_LEN], key[EC_PUBLIC_KEY_LEN]; + check("the script at 0/7 pays the output key", + script_at(0, THREE_SEEDS_CHILD, script) && + memcmp(script, spk, sizeof(spk)) == 0); + check("the internal key is the musig() of the three, derived at 0/7", + descriptor_key_at(0, THREE_SEEDS_CHILD, key) && + memcmp(key + 1, internal, sizeof(internal)) == 0); + + const uint32_t path[] = {0, THREE_SEEDS_CHILD}; + static const unsigned char aggregate_fp[4] = {0xe9, 0x56, 0xe2, 0xc2}; + unsigned char value[4 + 4 * 2], abc[3 * EC_PUBLIC_KEY_LEN]; + unsigned char computed_abc[EC_PUBLIC_KEY_LEN], computed_ab[EC_PUBLIC_KEY_LEN]; + struct wally_psbt *psbt = NULL; + leaf_t leaf; + memcpy(abc, a_key, EC_PUBLIC_KEY_LEN); + memcpy(abc + EC_PUBLIC_KEY_LEN, b_key, EC_PUBLIC_KEY_LEN); + memcpy(abc + 2 * EC_PUBLIC_KEY_LEN, c_key, EC_PUBLIC_KEY_LEN); + check("PSBT with the key path and the leaf builds", + spend_alloc(THREE_SEEDS_CHILD, internal, value, + origin(aggregate_fp, path, 2, value), &psbt) && + add_participants(psbt, abc, 3, computed_abc) && + add_participants(psbt, abc, 2, computed_ab) && + add_leaf(psbt, THREE_SEEDS_CHILD, &leaf)); + check("0x1a is keyed by each musig()'s KeyAgg key", + memcmp(computed_abc, keyagg_abc, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(computed_ab, keyagg_ab, EC_PUBLIC_KEY_LEN) == 0); + check("the leaf pushes the musig() of the first two, derived at 0/7", + memcmp(leaf.key, leaf_key, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(leaf.hash, leaf_hash, SHA256_LEN) == 0); + + bnc_issuance request = {.inputs = 1, .start = 0, .end = 1}; + uint8_t nonces[2 * BNC_PUBNONCE_LEN]; + nonce_cache_issued_t issued; + check("Nonce Preparation prepares a session of the two musig()", + prepare(&request, true, ACCOUNT_87, 3, nonces, 2, &issued) == + NONCE_CACHE_OK && + issued.new_session); + cosigner_t key_path[] = {{.pub = b_key, .sk = b->priv_key + 1}, + {.pub = c_key, .sk = c->priv_key + 1}}; + cosigner_t in_leaf = {.pub = b_key, .sk = b->priv_key + 1}; + check("every nonce in, keyed by the output key and the leaf key", + name_session(psbt, issued.session_id, issued.session_ref) && + add_own_nonce(psbt, a_key, output, NULL, nonces) && + add_own_nonce(psbt, a_key, leaf_key, leaf_hash, + nonces + BNC_PUBNONCE_LEN) && + cosigner_nonce(psbt, &key_path[0], output, NULL) && + cosigner_nonce(psbt, &key_path[1], output, NULL) && + cosigner_nonce(psbt, &in_leaf, leaf_key, leaf_hash)); + + musig_plan_t plan; + check("plan signs the key path under the output key, the leaf under its key", + musig_psbt_plan(psbt, NULL, &plan) == MUSIG_PSBT_OK && + plan.step == MUSIG_STEP_CACHED && plan.num_slots == 2 && + !plan.slots[0].has_leaf_hash && + memcmp(plan.slots[0].aggregate, output, EC_PUBLIC_KEY_LEN) == 0 && + plan.slots[1].has_leaf_hash && + memcmp(plan.slots[1].aggregate, leaf_key, EC_PUBLIC_KEY_LEN) == 0 && + memcmp(plan.slots[1].leaf_hash, leaf_hash, SHA256_LEN) == 0); + musig_plan_free(&plan); + check("the session is held and gives the nonces the PSBT carries", + check_request(psbt) == MUSIG_PSBT_OK); + + struct wally_psbt *keyagg_keyed = NULL; + unsigned char nonce_key[2 * EC_PUBLIC_KEY_LEN]; + memcpy(nonce_key, a_key, EC_PUBLIC_KEY_LEN); + memcpy(nonce_key + EC_PUBLIC_KEY_LEN, output, EC_PUBLIC_KEY_LEN); + check("our key path nonce under the KeyAgg key is refused", + wally_psbt_clone_alloc(psbt, 0, &keyagg_keyed) == WALLY_OK && + wally_map_remove(&keyagg_keyed->inputs[0].musig2_pubnonces, + nonce_key, sizeof(nonce_key)) == WALLY_OK && + add_own_nonce(keyagg_keyed, a_key, keyagg_abc, NULL, nonces) && + check_request(keyagg_keyed) == MUSIG_PSBT_ERR_SESSION); + wally_psbt_free(keyagg_keyed); + + size_t added = 0; + check("one round adds our two partial signatures", + sign(psbt, &added) == MUSIG_PSBT_OK && added == 2 && + entry(&psbt->inputs[0].musig2_partial_sigs, a_key, output, NULL, + WALLY_MUSIG_PARTIAL_SIG_LEN) && + entry(&psbt->inputs[0].musig2_partial_sigs, a_key, leaf_key, + leaf_hash, WALLY_MUSIG_PARTIAL_SIG_LEN)); + check("the session is consumed", + check_request(psbt) == MUSIG_PSBT_ERR_SESSION); + + unsigned char sighash[SHA256_LEN]; + struct wally_musig_keyagg_cache *cache = key_agg(abc, 3, path, 2); + check("the three partial signatures make a signature of the output key", + cache && tap_tweak(cache, leaf_hash) && + key_path_sighash(psbt, sighash) && + signature_verifies(psbt, a_key, key_path, 2, cache, output, NULL, + sighash)); + wally_musig_keyagg_cache_free(cache); + cache = key_agg(abc, 2, path, 2); + check("the two partial signatures make a signature of the leaf key", + cache && leaf_sighash(psbt, &leaf, sighash) && + signature_verifies(psbt, a_key, &in_leaf, 1, cache, leaf_key, + leaf_hash, sighash)); + wally_musig_keyagg_cache_free(cache); + + wally_musig_secnonce_free(key_path[0].secnonce); + wally_musig_secnonce_free(key_path[1].secnonce); + wally_musig_secnonce_free(in_leaf.secnonce); + wally_psbt_free(psbt); + bip32_key_free(a); + bip32_key_free(b); + bip32_key_free(c); + registry_clear(); +} + +static void test_participant_path(void) { + const uint32_t cosigner[] = {0x80000056, 0x80000001, 0x80000001}; + const uint32_t child[] = {0x80000056, 0x80000001, 0x80000000, 0, CHILD}; + check("aggregate then derive registers", + register_descriptor(AGGREGATE_THEN_DERIVE)); + const struct wally_descriptor *desc = registry_get(0)->desc; + check("our account key is a participant", + musig_psbt_is_participant_path(desc, ACCOUNT_PATH, 3)); + check("the cosigner's account key is not ours", + !musig_psbt_is_participant_path(desc, cosigner, 3)); + check("a key derived under our participant is not one", + !musig_psbt_is_participant_path(desc, child, 5)); + + check("derive then aggregate registers", + register_descriptor(DERIVE_THEN_AGGREGATE)); + desc = registry_get(0)->desc; + check("our key at 0/3 is a participant", + musig_psbt_is_participant_path(desc, child, 5)); + check("our account key alone is not", + !musig_psbt_is_participant_path(desc, ACCOUNT_PATH, 3)); + + const uint32_t recovery[] = {0x80000056, 0x80000001, 0x80000000, 3, CHILD}; + check("derive then aggregate on <2;3> registers", + register_descriptor(DERIVE_THEN_AGGREGATE_RECOVERY)); + desc = registry_get(0)->desc; + check("our key at 3/3 of <2;3> is a participant", + musig_psbt_is_participant_path(desc, recovery, 5)); + check("our key at 0/3 is not one of <2;3>", + !musig_psbt_is_participant_path(desc, child, 5)); + registry_clear(); +} + +int main(void) { + char dir[] = "/tmp/kern_musig_psbt_XXXXXX"; + if (!mkdtemp(dir)) { + perror("mkdtemp"); + return 1; + } + sim_nvs_set_data_dir(dir); + printf("=== musig_psbt tests ===\n\n"); + check("test mnemonic loads on testnet", + key_load_from_mnemonic(TEST_MNEMONIC, "", true) && + wallet_init(WALLET_NETWORK_TESTNET)); + test_claim(); + test_two_rounds(); + test_sighash_all(); + test_sighash_all_beside_silent_payments(); + test_aggregate_then_derive(); + test_leaf(); + test_cached_session(); + test_nonce_preparation(); + test_three_seeds(); + test_participant_path(); + registry_clear(); + key_unload(); + wallet_cleanup(); + printf("\nResults: %d passed, %d failed\n", tests_run - tests_failed, + tests_failed); + return tests_failed == 0 ? 0 : 1; +} diff --git a/main/core/test/test_nonce_cache.c b/main/core/test/test_nonce_cache.c new file mode 100644 index 00000000..696bb985 --- /dev/null +++ b/main/core/test/test_nonce_cache.c @@ -0,0 +1,296 @@ +/* + * Nonce cache tests (core/nonce_cache.c). + * + * The bip_nonces_cache signer on Kern's backend: libwally's MuSig2, + * mbedTLS SHA-256 and sessions in the simulator's NVS, under a fresh temp + * directory. The values are the nonce cache BIP draft's test vectors + * (bip_nonces_cache/test_vectors). + */ + +#include "core/nonce_cache.h" +#include "sim_nvs.h" +#include +#include +#include +#include +#include +#include +#include +#include + +static int tests_run = 0; +static int tests_failed = 0; + +static void check(const char *name, bool ok) { + tests_run++; + if (!ok) + tests_failed++; + printf("Testing: %s... %s\n", name, ok ? "PASS" : "FAIL"); +} + +/* nonce.json, session_ref.json and musig2_signing.json */ +#define SECRET_A \ + "6b85ef3dff7bb6fea77cd2b8662cb19b7a6895139e8e86e307e1875e456dab7e" +#define SECRET_B \ + "5485cb5d03981cc3bd989290a6be33ca392c013279a5c3c3fd10a1cae57e1460" +#define REF_A "c29ef5ec" +#define REF_B "9981509f" +#define SK_A "ba36730b8ca1fb220a1b35736c0091cc9bd0ecfa9d87c52ed3750f4cffa7445b" +#define PK_A \ + "021936c5746965205425e26e6e19e3c2eeb91378843363de0267caf2f968991a12" +#define SK_B "54adb8575a8947c289dd1223d5777429765b0317f5f4dc0df0e7ba8f449d2603" +#define PK_B \ + "028b43c3be504aee9a0001905774a3d0e8f8392b668223336a50cd227ca7f91904" +#define NONCE_A_0_0 \ + "0344b9a89f4636ec139b31380d614afbcde1f1469095b3cc603e9558e3ae6e0613" \ + "03e4c43e42b40fc9b046d88e7b2412606c592935287e92a5ec8847a3fe3c8bdcab" +#define NONCE_A_1_0 \ + "0276cfe291bc50c29859f8738b8c761472131ecf35ed7b92ee051ec64db16c56f4" \ + "02168db564eb109e1d0145df593947c74e07ff2ddd5fafddb17639206542795551" +#define NONCE_A_0_1 \ + "02f8a183a65d7be47916663dbfa45349c589afef5bacd8f64b1d5c47e472091a43" \ + "0365e690f58195af734871374fc970616f3d2f264ce31684441bcf9a7476c17a4d" +#define NONCE_B_0_0 \ + "037f5d7ac2b57b2ec40a2b000ac080a084cfb273e7f604629cdb6a14589658b4b4" \ + "027bb594d43cd6330351fc0f0dcacd4e94cff69b877b9e606b4296a8de67545e53" +#define AGGNONCE \ + "02729b58c1772d16a5a8521dd115efc7da7034bf7ad5e55f6dbd460e8c551942af" \ + "02609aac6b5d08912d07ab60f915745b7bfb998962c9dc7833497e96ac08efccc8" +#define MSG "ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cea1afbf02b460c6d1d" +#define PSIG_A \ + "6490a1dbc816a01db4340a05e9e51a14cc6cbe5abcbd23a50b0723ca3acb628c" +#define PSIG_B \ + "3696113d4bf29a72098c7ab6c8ea0ef428f9b554da718ee01d13ba8e7f135ac7" +#define AGGPK "edc088407bc106814307f3002afce9bd44f672c833bdc64bea1520bf243c6833" +#define SIG \ + "c69f9a646539fec456fb5f7c4372eb3d0ff4e143a9c2421d71a61bc873c4a06d" \ + "9b26b31914093a8fbdc084bcb2cf2908f56673af972eb285281ade58b9debd53" + +#define STORED_SESSION_LEN 44 + +static void hex(const char *text, unsigned char *out, size_t len) { + size_t written = 0; + if (wally_hex_to_bytes(text, out, len, &written) != WALLY_OK || + written != len) { + printf("bad test hex %s\n", text); + exit(1); + } +} + +static bool equals_hex(const unsigned char *bytes, size_t len, + const char *expected) { + unsigned char decoded[BNC_PUBNONCE_LEN]; + hex(expected, decoded, len); + return memcmp(bytes, decoded, len) == 0; +} + +typedef struct { + int32_t status; + uint8_t session_ref[BNC_SESSION_REF_LEN]; + bool new_session; + uint8_t nonces[4 * BNC_PUBNONCE_LEN]; +} issued_t; + +/* Issues `inputs` inputs and the key expressions start..=end, for the key + * sk/pk; `fresh` is the secret a new session gets. */ +static issued_t issue(uint8_t id, const char *ref, uint32_t inputs, + uint32_t start, uint32_t end, const char *fresh, + const char *sk, const char *pk) { + issued_t issued = {0}; + bnc_issuance request = {.inputs = inputs, .start = start, .end = end}; + unsigned char fresh_bytes[BNC_SECRET_LEN], sk_bytes[BNC_SECRET_KEY_LEN], + pk_bytes[BNC_PUBLIC_KEY_LEN]; + memset(request.session_id, id, sizeof(request.session_id)); + if (ref) { + request.has_session_ref = 1; + hex(ref, request.session_ref, sizeof(request.session_ref)); + } + hex(fresh, fresh_bytes, sizeof(fresh_bytes)); + hex(sk, sk_bytes, sizeof(sk_bytes)); + hex(pk, pk_bytes, sizeof(pk_bytes)); + issued.status = + bnc_issue(nonce_cache_signer(), &request, fresh_bytes, sk_bytes, pk_bytes, + issued.session_ref, &issued.new_session, issued.nonces, + (size_t)(end - start + 1) * inputs * BNC_PUBNONCE_LEN); + return issued; +} + +static size_t stored_sessions(void) { + nvs_handle_t handle; + uint8_t blob[NONCE_CACHE_MAX_SESSIONS * STORED_SESSION_LEN]; + size_t len = sizeof(blob); + if (nvs_open("noncecache", NVS_READONLY, &handle) != 0) + return SIZE_MAX; + esp_err_t err = nvs_get_blob(handle, "sessions", blob, &len); + nvs_close(handle); + if (err == ESP_ERR_NVS_NOT_FOUND) + return 0; + return err == ESP_OK ? len / STORED_SESSION_LEN : SIZE_MAX; +} + +static void test_draft_vectors(void) { + issued_t issued = issue(0xa1, NULL, 2, 0, 1, SECRET_A, SK_A, PK_A); + check("a new session issues", issued.status == BNC_OK && issued.new_session); + check("session reference of the secret", + equals_hex(issued.session_ref, BNC_SESSION_REF_LEN, REF_A)); + check("nonce of input 0, key expression 0", + equals_hex(issued.nonces, BNC_PUBNONCE_LEN, NONCE_A_0_0)); + check("nonce of input 1, key expression 0", + equals_hex(issued.nonces + BNC_PUBNONCE_LEN, BNC_PUBNONCE_LEN, + NONCE_A_1_0)); + check("nonce of input 0, key expression 1", + equals_hex(issued.nonces + 2 * BNC_PUBNONCE_LEN, BNC_PUBNONCE_LEN, + NONCE_A_0_1)); + check("the session is stored", stored_sessions() == 1); + + issued = issue(0xa2, NULL, 1, 0, 0, SECRET_A, SK_B, PK_B); + check("another key at the same position gets another nonce", + issued.status == BNC_OK && + equals_hex(issued.nonces, BNC_PUBNONCE_LEN, NONCE_B_0_0)); + + issued = issue(0xa3, NULL, 1, 0, 0, SECRET_B, SK_A, PK_A); + check("session reference of another secret", + issued.status == BNC_OK && + equals_hex(issued.session_ref, BNC_SESSION_REF_LEN, REF_B)); +} + +static void test_held_session(void) { + issued_t again = issue(0xa1, NULL, 2, 0, 1, SECRET_B, SK_A, PK_A); + check("a held session answers again with its nonces, not a new secret", + again.status == BNC_OK && !again.new_session && + equals_hex(again.nonces, BNC_PUBNONCE_LEN, NONCE_A_0_0) && + equals_hex(again.session_ref, BNC_SESSION_REF_LEN, REF_A)); + + issued_t extended = issue(0xa1, REF_A, 2, 1, 1, SECRET_B, SK_A, PK_A); + check("extending with the reference gives key expression 1 first", + extended.status == BNC_OK && !extended.new_session && + equals_hex(extended.nonces, BNC_PUBNONCE_LEN, NONCE_A_0_1)); + + check("a reference of another session is refused", + issue(0xa1, REF_B, 2, 0, 1, SECRET_B, SK_A, PK_A).status == + BNC_ERR_SESSION_REF_MISMATCH); + check("a reference without a held session is refused", + issue(0xb0, REF_A, 2, 0, 1, SECRET_A, SK_A, PK_A).status == + BNC_ERR_UNKNOWN_SESSION); + check("a refused reference creates no session", stored_sessions() == 3); +} + +/* musig2_signing.json: A signs with its cached nonce, no tweaks. */ +static void test_musig2_signing(void) { + issued_t issued = issue(0xc1, NULL, 1, 0, 0, SECRET_A, SK_A, PK_A); + check("signer A's cached nonce", + issued.status == BNC_OK && + equals_hex(issued.nonces, BNC_PUBNONCE_LEN, NONCE_A_0_0)); + + unsigned char pubkeys[2 * BNC_PUBLIC_KEY_LEN], xonly[32], msg[32]; + unsigned char aggnonce_bytes[BNC_PUBNONCE_LEN]; + struct wally_musig_keyagg_cache *cache = NULL; + struct wally_musig_aggnonce *aggnonce = NULL; + struct wally_musig_session *session = NULL; + hex(PK_A, pubkeys, BNC_PUBLIC_KEY_LEN); + hex(PK_B, pubkeys + BNC_PUBLIC_KEY_LEN, BNC_PUBLIC_KEY_LEN); + hex(AGGNONCE, aggnonce_bytes, sizeof(aggnonce_bytes)); + hex(MSG, msg, sizeof(msg)); + bool context_ok = + wally_musig_pubkey_agg(pubkeys, sizeof(pubkeys), xonly, sizeof(xonly), + &cache) == WALLY_OK && + equals_hex(xonly, sizeof(xonly), AGGPK) && + wally_musig_aggnonce_parse(aggnonce_bytes, sizeof(aggnonce_bytes), + &aggnonce) == WALLY_OK && + wally_musig_nonce_process(aggnonce, msg, sizeof(msg), cache, NULL, 0, + &session) == WALLY_OK; + check("session context of the vector", context_ok); + + bnc_secret *secret = NULL; + check("the named session is taken", + bnc_begin_signing(nonce_cache_signer(), + (const uint8_t[]){0xc1, 0xc1, 0xc1, 0xc1}, + issued.session_ref, &secret) == BNC_OK); + check("a taken session is deleted", + bnc_begin_signing(nonce_cache_signer(), + (const uint8_t[]){0xc1, 0xc1, 0xc1, 0xc1}, + issued.session_ref, + &(bnc_secret *){NULL}) == BNC_ERR_UNKNOWN_SESSION); + + nonce_cache_sign_context_t context = {.keyagg_cache = cache, + .session = session}; + bnc_musig_slot slot = {.input_index = 0, .key_expression_index = 0}; + unsigned char sk[BNC_SECRET_KEY_LEN], partial_sig[BNC_PARTIAL_SIG_LEN]; + hex(PK_A, slot.participant, sizeof(slot.participant)); + hex(NONCE_A_1_0, slot.pubnonce, sizeof(slot.pubnonce)); + hex(SK_A, sk, sizeof(sk)); + check("a nonce of another position is refused", + bnc_sign_musig(nonce_cache_signer(), secret, &slot, sk, &context, + partial_sig) == BNC_ERR_PUBNONCE_MISMATCH); + memcpy(slot.pubnonce, issued.nonces, sizeof(slot.pubnonce)); + check("partial signature of signer A", + bnc_sign_musig(nonce_cache_signer(), secret, &slot, sk, &context, + partial_sig) == BNC_OK && + equals_hex(partial_sig, sizeof(partial_sig), PSIG_A)); + bnc_secret_free(secret); + + unsigned char partial_sigs[2 * BNC_PARTIAL_SIG_LEN], sig[64]; + memcpy(partial_sigs, partial_sig, BNC_PARTIAL_SIG_LEN); + hex(PSIG_B, partial_sigs + BNC_PARTIAL_SIG_LEN, BNC_PARTIAL_SIG_LEN); + check("both partial signatures aggregate to the vector's signature", + wally_musig_partial_sig_agg(partial_sigs, sizeof(partial_sigs), 2, + session, sig, sizeof(sig)) == WALLY_OK && + equals_hex(sig, sizeof(sig), SIG)); + wally_musig_session_free(session); + wally_musig_aggnonce_free(aggnonce); + wally_musig_keyagg_cache_free(cache); + + issued_t reissued = issue(0xc1, NULL, 1, 0, 0, SECRET_B, SK_A, PK_A); + check("the session ID issued again gets a new secret and nonce", + reissued.status == BNC_OK && reissued.new_session && + !equals_hex(reissued.nonces, BNC_PUBNONCE_LEN, NONCE_A_0_0)); +} + +static void test_eviction(void) { + size_t held = stored_sessions(); + check("sessions held before filling the store", + held > 0 && held < NONCE_CACHE_MAX_SESSIONS); + for (uint8_t id = 0xe0; id < 0xe0 + NONCE_CACHE_MAX_SESSIONS; id++) + issue(id, NULL, 1, 0, 0, SECRET_A, SK_A, PK_A); + check("the store keeps at most its capacity", + stored_sessions() == NONCE_CACHE_MAX_SESSIONS); + bnc_secret *secret = NULL; + check("the oldest session is evicted", + bnc_held_session(nonce_cache_signer(), + (const uint8_t[]){0xa1, 0xa1, 0xa1, 0xa1}, NULL, + &secret) == BNC_ERR_UNKNOWN_SESSION); + check("the newest session is held", + bnc_held_session(nonce_cache_signer(), + (const uint8_t[]){0xef, 0xef, 0xef, 0xef}, NULL, + &secret) == BNC_OK); + bnc_secret_free(secret); +} + +static void test_erase(void) { + check("erasing deletes every session", + nonce_cache_erase() && stored_sessions() == 0); + bnc_secret *secret = NULL; + check("an erased session is no longer held", + bnc_held_session(nonce_cache_signer(), + (const uint8_t[]){0xef, 0xef, 0xef, 0xef}, NULL, + &secret) == BNC_ERR_UNKNOWN_SESSION); +} + +int main(void) { + char dir[] = "/tmp/kern_nonce_cache_XXXXXX"; + if (!mkdtemp(dir)) { + perror("mkdtemp"); + return 1; + } + sim_nvs_set_data_dir(dir); + printf("=== nonce_cache tests ===\n\n"); + check("signer sets up", nonce_cache_signer() != NULL); + test_draft_vectors(); + test_held_session(); + test_musig2_signing(); + test_eviction(); + test_erase(); + printf("\nResults: %d passed, %d failed\n", tests_run - tests_failed, + tests_failed); + return tests_failed == 0 ? 0 : 1; +} diff --git a/main/core/test/test_psbt_classify.c b/main/core/test/test_psbt_classify.c index 1a95a769..b243a386 100644 --- a/main/core/test/test_psbt_classify.c +++ b/main/core/test/test_psbt_classify.c @@ -22,8 +22,10 @@ #include "core/psbt_gate.h" #include "core/psbt_internal.h" #include "core/registry.h" +#include "core/sp_psbt.h" #include "core/storage.h" #include "core/wallet.h" +#include "sp_fixture.h" /* --- Storage stubs (registry.c persist=false path never calls these) --- */ esp_err_t storage_save_descriptor(storage_location_t loc, const char *id, @@ -3478,6 +3480,435 @@ static void test_trim_v0_keeps_signatures(void) { bip32_key_free(cosigner); } +static struct wally_psbt *parse_silent_payment_psbt(const char *hex) { + unsigned char bytes[1024]; + size_t written = 0; + struct wally_psbt *psbt = NULL; + if (wally_hex_to_bytes(hex, bytes, sizeof(bytes), &written) != WALLY_OK || + wally_psbt_from_bytes(bytes, written, + WALLY_PSBT_PARSE_FLAG_LOOSE | + WALLY_PSBT_PARSE_FLAG_COMPLETE, + &psbt) != WALLY_OK) + return NULL; + return psbt; +} + +/* The bwk-built silent payment PSBT, with its output scripts derived */ +static struct wally_psbt *make_silent_payment_psbt(void) { + struct wally_psbt *psbt = parse_silent_payment_psbt(UNSIGNED_PSBT); + if (!psbt) + return NULL; + if (sp_psbt_complete(&psbt, false) == SP_PSBT_OK) + return psbt; + wally_psbt_free(psbt); + return NULL; +} + +static void test_silent_payment_classify(void) { + struct wally_psbt *psbt = make_silent_payment_psbt(); + + TEST("psbt_classify_input: our silent payment input is owned safe"); + input_ownership_t in = + psbt ? psbt_classify_input(psbt, 0, false) : (input_ownership_t){0}; + if (in.ownership == PSBT_OWNERSHIP_OWNED_SAFE && + in.claim.kind == CLAIM_SILENT_PAYMENT) + PASS(); + else + FAIL("silent payment input not owned"); + + TEST("psbt_classify_output: our silent payment change is owned safe, the " + "recipient external"); + output_ownership_t change = + psbt ? psbt_classify_output(psbt, 1, false) : (output_ownership_t){0}; + output_ownership_t recipient = + psbt ? psbt_classify_output(psbt, 0, false) : (output_ownership_t){0}; + if (change.ownership == PSBT_OWNERSHIP_OWNED_SAFE && + change.source.kind == CLAIM_SILENT_PAYMENT && + change.source.silent_payment.is_change && + recipient.ownership == PSBT_OWNERSHIP_EXTERNAL) + PASS(); + else + FAIL("silent payment outputs misclassified"); + wally_psbt_free(psbt); +} + +/* Output 1 of the silent payment PSBT paying our spend key labeled with + * m = 0 under the BIP352 receiving vectors' scan key, not ours */ +static bool pay_change_to_scan_key_not_ours(struct wally_psbt *psbt) { + static const char scan[] = + "0220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4"; + static const char spend_label_0[] = + "02e673195a3b1a0c7cdfdde5649e6e13be05d01791be238329bb58fdb3ea386f56"; + unsigned char info_key = PSBT_OUT_SP_V0_INFO, + label_key = PSBT_OUT_SP_V0_LABEL; + unsigned char info[66]; + size_t written = 0; + struct wally_map *unknowns = &psbt->outputs[1].unknowns; + return wally_hex_to_bytes(scan, info, 33, &written) == WALLY_OK && + wally_hex_to_bytes(spend_label_0, info + 33, 33, &written) == + WALLY_OK && + wally_map_replace(unknowns, &info_key, 1, info, sizeof(info)) == + WALLY_OK && + wally_map_remove(unknowns, &label_key, 1) == WALLY_OK; +} + +static void test_silent_payment_scan_key_not_ours(void) { + static const char scan_secret_hex[] = + "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"; + unsigned char scan_secret[32]; + size_t written = 0; + struct wally_psbt *psbt = make_silent_payment_psbt(); + bool ready = psbt && pay_change_to_scan_key_not_ours(psbt) && + wally_hex_to_bytes(scan_secret_hex, scan_secret, + sizeof(scan_secret), &written) == WALLY_OK; + + TEST("psbt_classify_output: change under a scan key not ours is external " + "until a request names that scan key"); + output_ownership_t unnamed = + ready ? psbt_classify_output(psbt, 1, false) : (output_ownership_t){0}; + bool named = ready && registry_sp_name_scan_key(scan_secret); + output_ownership_t change = + named ? psbt_classify_output(psbt, 1, false) : (output_ownership_t){0}; + output_ownership_t recipient = + named ? psbt_classify_output(psbt, 0, false) : (output_ownership_t){0}; + registry_sp_clear_named_scan_keys(); + output_ownership_t cleared = + ready ? psbt_classify_output(psbt, 1, false) : (output_ownership_t){0}; + if (unnamed.ownership == PSBT_OWNERSHIP_EXTERNAL && + change.ownership == PSBT_OWNERSHIP_OWNED_SAFE && + change.source.kind == CLAIM_SILENT_PAYMENT && + change.source.silent_payment.is_change && + recipient.ownership == PSBT_OWNERSHIP_EXTERNAL && + cleared.ownership == PSBT_OWNERSHIP_EXTERNAL) + PASS(); + else + FAIL("change under a named scan key misclassified"); + wally_psbt_free(psbt); +} + +static void test_sign_silent_payment_input(void) { + struct wally_psbt *psbt = make_silent_payment_psbt(); + psbt_sign_policy_t policy = {0}; + unsigned char sig[65]; + size_t sig_len = 0, sighash = 0; + + TEST("psbt_sign: signs our silent payment input with SIGHASH_ALL (BIP375) " + "and adds no PSBT_IN_SIGHASH_TYPE"); + if (psbt && psbt_sign(psbt, false, policy, NULL) == 1 && + wally_psbt_get_input_taproot_signature(psbt, 0, sig, sizeof(sig), + &sig_len) == WALLY_OK && + sig_len == 65 && sig[64] == WALLY_SIGHASH_ALL && + wally_psbt_get_input_sighash(psbt, 0, &sighash) == WALLY_OK && + sighash == 0) + PASS(); + else + FAIL("silent payment input not signed, or its sighash type left set"); + + struct wally_psbt *trimmed = psbt ? psbt_trim(psbt) : NULL; + unsigned char share_key[1 + 33]; + size_t index = 0; + TEST("psbt_trim: keeps the ECDH shares of a silent payment PSBT"); + share_key[0] = PSBT_GLOBAL_SP_ECDH_SHARE; + if (trimmed && + wally_hex_to_bytes(OUR_SCAN, share_key + 1, 33, &index) == WALLY_OK && + wally_map_find(&trimmed->unknowns, share_key, sizeof(share_key), + &index) == WALLY_OK && + index && sp_psbt_has_outputs(trimmed)) + PASS(); + else + FAIL("BIP375 fields trimmed away"); + wally_psbt_free(trimmed); + wally_psbt_free(psbt); +} + +static void test_sign_silent_payment_keeps_sighash_all(void) { + struct wally_psbt *psbt = make_silent_payment_psbt(); + psbt_sign_policy_t policy = {0}; + unsigned char sig[65]; + size_t sig_len = 0, sighash = 0; + + TEST("psbt_sign: a silent payment input naming SIGHASH_ALL keeps it"); + if (psbt && + wally_psbt_set_input_sighash(psbt, 0, WALLY_SIGHASH_ALL) == WALLY_OK && + psbt_sign(psbt, false, policy, NULL) == 1 && + wally_psbt_get_input_taproot_signature(psbt, 0, sig, sizeof(sig), + &sig_len) == WALLY_OK && + sig_len == 65 && sig[64] == WALLY_SIGHASH_ALL && + wally_psbt_get_input_sighash(psbt, 0, &sighash) == WALLY_OK && + sighash == WALLY_SIGHASH_ALL) + PASS(); + else + FAIL("silent payment input not signed, or its sighash type removed"); + wally_psbt_free(psbt); +} + +static bool has_input_share(const struct wally_psbt *psbt, size_t i) { + for (size_t j = 0; j < psbt->inputs[i].unknowns.num_items; j++) { + const struct wally_map_item *item = &psbt->inputs[i].unknowns.items[j]; + if (item->key_len && item->key[0] == PSBT_IN_SP_ECDH_SHARE) + return true; + } + return false; +} + +static bool has_global_share(const struct wally_psbt *psbt) { + for (size_t j = 0; j < psbt->unknowns.num_items; j++) { + const struct wally_map_item *item = &psbt->unknowns.items[j]; + if (item->key_len && item->key[0] == PSBT_GLOBAL_SP_ECDH_SHARE) + return true; + } + return false; +} + +/* The pre-review gate over a fresh classification of `psbt`, as the scan flow + * runs it before a silent payment share round */ +static psbt_gate_t share_round_gate(struct wally_psbt *psbt, + psbt_gate_settings_t settings, + psbt_gate_report_t *report) { + input_ownership_t *inputs = calloc(psbt->num_inputs, sizeof(*inputs)); + output_ownership_t *outputs = calloc(psbt->num_outputs, sizeof(*outputs)); + psbt_gate_t gate = PSBT_GATE_NOTHING_SIGNABLE; + if (inputs && outputs) { + for (size_t i = 0; i < psbt->num_inputs; i++) + inputs[i] = psbt_classify_input(psbt, i, false); + for (size_t i = 0; i < psbt->num_outputs; i++) + outputs[i] = psbt_classify_output(psbt, i, false); + gate = psbt_gate_check(psbt, inputs, outputs, &settings, report); + } + free(inputs); + free(outputs); + return gate; +} + +/* TWO_SIGNER_PSBT: input 0 ours, input 1 another signer's. Partial signing off + * refuses it before the share round, so no share is made. */ +static void test_partial_signing_refuses_share_round(void) { + struct wally_psbt *psbt = parse_silent_payment_psbt(TWO_SIGNER_PSBT); + psbt_gate_settings_t settings = {.partial = false}; + psbt_gate_report_t report; + + TEST("psbt_gate_check: Partial signing off, a share round with another " + "signer's input is refused, input 1 listed, no share made"); + if (psbt && share_round_gate(psbt, settings, &report) == PSBT_GATE_PARTIAL && + report.external_count == 1 && report.external_inputs[0] == 1 && + !has_input_share(psbt, 0) && !has_input_share(psbt, 1)) + PASS(); + else + FAIL("share round with a foreign input not refused"); + wally_psbt_free(psbt); +} + +static void test_partial_signing_allows_share_round(void) { + struct wally_psbt *psbt = parse_silent_payment_psbt(TWO_SIGNER_PSBT); + psbt_gate_settings_t settings = {.partial = true}; + psbt_gate_report_t report; + sp_share_t *shares = NULL; + size_t count = 0; + + TEST("psbt_gate_check: Partial signing on, the share round gives the " + "per-input shares of input 0 only"); + if (psbt && share_round_gate(psbt, settings, &report) == PSBT_GATE_ALLOW && + sp_psbt_complete(&psbt, false) == SP_PSBT_PENDING && + sp_psbt_shares_alloc(psbt, false, &shares, &count) && count == 2 && + !shares[0].global && shares[0].input_index == 0 && !shares[1].global && + shares[1].input_index == 0 && !has_input_share(psbt, 1)) + PASS(); + else + FAIL("per-input shares of our input not made"); + free(shares); + wally_psbt_free(psbt); +} + +/* UNSIGNED_PSBT holds input 0 only, ours */ +static void test_partial_signing_own_inputs(bool partial_signing) { + struct wally_psbt *psbt = parse_silent_payment_psbt(UNSIGNED_PSBT); + psbt_gate_settings_t settings = {.partial = partial_signing}; + psbt_gate_report_t report; + sp_share_t *shares = NULL; + size_t count = 0; + + TEST(partial_signing ? "psbt_gate_check: Partial signing on, every input " + "ours, global shares made" + : "psbt_gate_check: Partial signing off, every input " + "ours, global shares made"); + if (psbt && share_round_gate(psbt, settings, &report) == PSBT_GATE_ALLOW && + report.external_count == 0 && + sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + sp_psbt_shares_alloc(psbt, false, &shares, &count) && count == 2 && + shares[0].global && shares[1].global) + PASS(); + else + FAIL("shares of a PSBT owning every input not made"); + free(shares); + wally_psbt_free(psbt); +} + +/* TWO_SIGNER_PSBT without our input 0: nothing to sign, not Partial signing, + * refuses it */ +static void test_partial_signing_no_own_input(void) { + struct wally_psbt *psbt = parse_silent_payment_psbt(TWO_SIGNER_PSBT); + psbt_gate_settings_t settings = {.partial = false}; + psbt_gate_report_t report; + + TEST("psbt_gate_check: Partial signing off, a PSBT owning no input is left " + "to the nothing to sign refusal"); + if (psbt && + wally_psbt_set_tx_modifiable_flags(psbt, WALLY_PSBT_TXMOD_INPUTS) == + WALLY_OK && + wally_psbt_remove_input(psbt, 0) == WALLY_OK && + share_round_gate(psbt, settings, &report) == PSBT_GATE_NOTHING_SIGNABLE && + report.external_count == 1 && report.external_inputs[0] == 0) + PASS(); + else + FAIL("a PSBT owning no input refused by Partial signing"); + wally_psbt_free(psbt); +} + +/* UNSIGNED_PSBT with a P2WPKH input 1 of 50000 sats at outpoint 0x55..55:0, + * spending `spk` and naming `pubkey` at the key origin `origin` */ +static struct wally_psbt *add_p2wpkh_input(const uint8_t *spk, size_t spk_len, + const unsigned char *pubkey, + const uint8_t *origin, + size_t origin_len) { + struct wally_psbt *psbt = parse_silent_payment_psbt(UNSIGNED_PSBT); + unsigned char txid[32]; + struct wally_tx_input *txin = NULL; + struct wally_tx_output *utxo = NULL; + size_t flags = 0; + memset(txid, 0x55, sizeof(txid)); + bool ok = + psbt && wally_psbt_get_tx_modifiable_flags(psbt, &flags) == WALLY_OK && + wally_psbt_set_tx_modifiable_flags(psbt, WALLY_PSBT_TXMOD_INPUTS) == + WALLY_OK && + wally_tx_input_init_alloc(txid, sizeof(txid), 0, 0xffffffff, NULL, 0, + NULL, &txin) == WALLY_OK && + wally_psbt_add_tx_input_at(psbt, 1, 0, txin) == WALLY_OK && + wally_psbt_set_tx_modifiable_flags(psbt, (uint32_t)flags) == WALLY_OK && + wally_tx_output_init_alloc(50000, spk, spk_len, &utxo) == WALLY_OK && + wally_psbt_set_input_witness_utxo(psbt, 1, utxo) == WALLY_OK && + wally_map_add(&psbt->inputs[1].keypaths, pubkey, EC_PUBLIC_KEY_LEN, + origin, origin_len) == WALLY_OK; + wally_tx_input_free(txin); + wally_tx_output_free(utxo); + if (ok) + return psbt; + wally_psbt_free(psbt); + return NULL; +} + +/* Input 1 ours on the non-standard path m/9999'/0'/0'/0/0: Permissive signing + * off refuses the share round before any share, on gives the global shares of + * a PSBT owning every input */ +static void test_permissive_signing_share_round(bool permissive_signing) { + struct ext_key *derived = NULL; + uint8_t spk[22]; + size_t spk_len = 0; + uint8_t origin[] = { + 0x00, 0x00, 0x00, 0x00, /* fp = 00000000 */ + 0x0F, 0x27, 0x00, 0x80, /* 9999' */ + 0x00, 0x00, 0x00, 0x80, /* 0' */ + 0x00, 0x00, 0x00, 0x80, /* 0' */ + 0x00, 0x00, 0x00, 0x00, /* 0 */ + 0x00, 0x00, 0x00, 0x00, /* 0 */ + }; + struct wally_psbt *psbt = NULL; + if (key_get_derived_key("m/9999'/0'/0'/0/0", &derived) && + wally_witness_program_from_bytes(derived->pub_key, EC_PUBLIC_KEY_LEN, + WALLY_SCRIPT_HASH160, spk, sizeof(spk), + &spk_len) == WALLY_OK) + psbt = add_p2wpkh_input(spk, spk_len, derived->pub_key, origin, + sizeof(origin)); + bip32_key_free(derived); + + psbt_gate_settings_t settings = {.permissive = permissive_signing}; + psbt_gate_report_t report; + sp_share_t *shares = NULL; + size_t count = 0; + + if (!permissive_signing) { + TEST("psbt_gate_check: Permissive signing off, a share round with our " + "input on a non-standard path is refused, input 1 flagged, no share " + "made"); + if (psbt && + share_round_gate(psbt, settings, &report) == PSBT_GATE_PERMISSIVE && + report.flagged_is_input && report.flagged_index == 1 && + strcmp(report.flagged_path, "m/9999'/0'/0'/0/0") == 0 && + !has_global_share(psbt) && !has_input_share(psbt, 0) && + !has_input_share(psbt, 1)) + PASS(); + else + FAIL("share round with an input on a non-standard path not refused"); + } else { + TEST("psbt_gate_check: Permissive signing on, a share round with our " + "input on a non-standard path gives the global shares"); + if (psbt && share_round_gate(psbt, settings, &report) == PSBT_GATE_ALLOW && + sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + sp_psbt_shares_alloc(psbt, false, &shares, &count) && count == 2 && + shares[0].global && shares[1].global) + PASS(); + else + FAIL("global shares of a PSBT owning every input not made"); + } + free(shares); + wally_psbt_free(psbt); +} + +/* Input 1 names our m/84'/0'/0'/0/0 key at the origin m/99'/0'/0'/0/0, which + * does not derive it: Expected-owned signing off refuses the share round + * before any share, on gives the per-input shares of input 0, input 1 left to + * the other signer */ +static void +test_expected_owned_signing_share_round(bool expected_owned_signing) { + struct ext_key *derived = NULL; + uint8_t origin[] = { + 0x00, 0x00, 0x00, 0x00, /* fp = 00000000 */ + 0x63, 0x00, 0x00, 0x80, /* 99' */ + 0x00, 0x00, 0x00, 0x80, /* 0' */ + 0x00, 0x00, 0x00, 0x80, /* 0' */ + 0x00, 0x00, 0x00, 0x00, /* 0 */ + 0x00, 0x00, 0x00, 0x00, /* 0 */ + }; + struct wally_psbt *psbt = NULL; + if (key_get_derived_key("m/84'/0'/0'/0/0", &derived)) + psbt = add_p2wpkh_input(REF_SPK_P2WPKH, sizeof(REF_SPK_P2WPKH), + derived->pub_key, origin, sizeof(origin)); + bip32_key_free(derived); + + psbt_gate_settings_t settings = {.expected_owned = expected_owned_signing}; + psbt_gate_report_t report; + sp_share_t *shares = NULL; + size_t count = 0; + + if (!expected_owned_signing) { + TEST("psbt_gate_check: Expected-owned signing off, a share round with an " + "input its key origin cannot re-derive is refused, input 1 flagged, " + "no share made"); + if (psbt && + share_round_gate(psbt, settings, &report) == PSBT_GATE_EXPECTED_OWNED && + report.flagged_is_input && report.flagged_index == 1 && + strcmp(report.flagged_path, "m/99'/0'/0'/0/0") == 0 && + !has_global_share(psbt) && !has_input_share(psbt, 0) && + !has_input_share(psbt, 1)) + PASS(); + else + FAIL("share round with an expected owned input not refused"); + } else { + TEST("psbt_gate_check: Expected-owned signing on, a share round with an " + "input its key origin cannot re-derive gives the per-input shares of " + "input 0 only"); + if (psbt && share_round_gate(psbt, settings, &report) == PSBT_GATE_ALLOW && + sp_psbt_complete(&psbt, false) == SP_PSBT_PENDING && + sp_psbt_shares_alloc(psbt, false, &shares, &count) && count == 2 && + !shares[0].global && shares[0].input_index == 0 && !shares[1].global && + shares[1].input_index == 0 && !has_input_share(psbt, 1)) + PASS(); + else + FAIL("per-input shares of our input not made"); + } + free(shares); + wally_psbt_free(psbt); +} + static void test_trim_psbt_v2_in_place(void) { TEST("psbt_trim: a v2 PSBT is trimmed in place"); @@ -4037,6 +4468,187 @@ static void test_overlong_keypaths_skipped(void) { memset(stub_fp, 0, sizeof(stub_fp)); } +/* Liana shape: our key on <0;1> in the primary path and on <2;3> in the + * recovery path. */ +#define LIANA_REGISTRY_DESC \ + "wsh(or_d(multi(2,[00000000/84'/0'/0']" XPUB_84 "/<0;1>/*," \ + "[11111111/86'/0'/0']" XPUB_86 "/<0;1>/*)," \ + "and_v(v:multi(1,[00000000/84'/0'/0']" XPUB_84 "/<2;3>/*," \ + "[11111111/86'/0'/0']" XPUB_86 "/<2;3>/*),older(1008))))" + +/* Our key on m/84'/0'/0'//5 and its keypath value. */ +static bool liana_key(uint8_t chain, unsigned char *pub_out, + uint8_t kp_out[24]) { + const uint8_t kp_val[24] = { + 0x00, 0x00, 0x00, 0x00, /* fp = 00000000 (stub) */ + 0x54, 0x00, 0x00, 0x80, /* 84' */ + 0x00, 0x00, 0x00, 0x80, /* 0' */ + 0x00, 0x00, 0x00, 0x80, /* 0' */ + chain, 0x00, 0x00, 0x00, /* chain */ + 0x05, 0x00, 0x00, 0x00, /* index 5 */ + }; + char path[32]; + snprintf(path, sizeof(path), "m/84'/0'/0'/%u/5", (unsigned)chain); + struct ext_key *derived = NULL; + if (!key_get_derived_key(path, &derived)) + return false; + memcpy(pub_out, derived->pub_key, EC_PUBLIC_KEY_LEN); + memcpy(kp_out, kp_val, sizeof(kp_val)); + bip32_key_free(derived); + return true; +} + +/* The P2WSH script pubkey and witness script of the registered + * LIANA_REGISTRY_DESC at multipath index `k`, child 5. libwally needs room for + * the witness script to build the script pubkey. */ +static bool liana_scripts(uint32_t k, unsigned char *spk, + unsigned char *witness, size_t *witness_len) { + const struct wally_descriptor *desc = registry_get(0)->desc; + unsigned char work[PSBT_MAX_INNER_SCRIPT_LEN]; + size_t spk_len = 0; + if (wally_descriptor_to_script(desc, 0, 0, 0, k, 5, 0, work, sizeof(work), + &spk_len) != WALLY_OK || + spk_len != WALLY_SCRIPTPUBKEY_P2WSH_LEN || + wally_descriptor_to_script(desc, 1, 0, 0, k, 5, 0, witness, + PSBT_MAX_INNER_SCRIPT_LEN, + witness_len) != WALLY_OK || + *witness_len > PSBT_MAX_INNER_SCRIPT_LEN) + return false; + memcpy(spk, work, spk_len); + return true; +} + +/* Spends LIANA_REGISTRY_DESC at multipath index `k`, child 5. The keypaths name + * our primary key (chain k), our recovery key (chain 2 + k) and our key on the + * other primary chain, which the script does not hold: the first two sign, the + * third never does. */ +static void test_psbt_sign_registry_recovery_keys(uint32_t k) { + TEST(k ? "psbt_sign: liana change spend signs with both our keys" + : "psbt_sign: liana receive spend signs with both our keys"); + + registry_clear(); + if (!registry_add_from_string("l", LIANA_REGISTRY_DESC, STORAGE_FLASH, + false)) { + FAIL("registry_add_from_string"); + return; + } + + unsigned char spk[WALLY_SCRIPTPUBKEY_P2WSH_LEN], + witness[PSBT_MAX_INNER_SCRIPT_LEN]; + size_t witness_len = 0; + if (!liana_scripts(k, spk, witness, &witness_len)) { + FAIL("script generation"); + registry_clear(); + return; + } + + unsigned char primary[EC_PUBLIC_KEY_LEN], recovery[EC_PUBLIC_KEY_LEN], + other[EC_PUBLIC_KEY_LEN]; + uint8_t kp_primary[24], kp_recovery[24], kp_other[24]; + if (!liana_key(k, primary, kp_primary) || + !liana_key(2 + k, recovery, kp_recovery) || + !liana_key(1 - k, other, kp_other)) { + FAIL("key derivation"); + registry_clear(); + return; + } + + /* The key the script does not hold comes first, so it is the one the + * input classifies on. */ + struct wally_psbt *psbt = make_test_psbt( + spk, sizeof(spk), other, sizeof(other), kp_other, sizeof(kp_other)); + if (!psbt || + wally_psbt_set_input_witness_script(psbt, 0, witness, witness_len) != + WALLY_OK || + wally_map_add(&psbt->inputs[0].keypaths, recovery, sizeof(recovery), + kp_recovery, sizeof(kp_recovery)) != WALLY_OK || + wally_map_add(&psbt->inputs[0].keypaths, primary, sizeof(primary), + kp_primary, sizeof(kp_primary)) != WALLY_OK) { + FAIL("PSBT construction"); + wally_psbt_free(psbt); + registry_clear(); + return; + } + + input_ownership_t r = psbt_classify_input(psbt, 0, false); + psbt_sign_policy_t policy = {0}; + psbt_sign_result_t res; + (void)psbt_sign(psbt, false, policy, &res); + + const struct wally_map *sigs = &psbt->inputs[0].signatures; + size_t primary_ix = 0, recovery_ix = 0, other_ix = 0; + wally_map_find(sigs, primary, sizeof(primary), &primary_ix); + wally_map_find(sigs, recovery, sizeof(recovery), &recovery_ix); + wally_map_find(sigs, other, sizeof(other), &other_ix); + size_t num_sigs = sigs->num_items; + wally_psbt_free(psbt); + registry_clear(); + + if (r.ownership != PSBT_OWNERSHIP_OWNED_SAFE || + r.claim.kind != CLAIM_REGISTRY) + FAIL("expected OWNED_SAFE via CLAIM_REGISTRY"); + else if (r.claim.registry.multi_index != k || r.claim.registry.child_num != 5) + FAIL("wrong multi_index or child_num"); + else if (!primary_ix) + FAIL("primary key did not sign"); + else if (!recovery_ix) + FAIL("recovery key did not sign"); + else if (other_ix) + FAIL("signed with a key the script does not hold"); + else if (num_sigs != 2) + FAIL("expected exactly two signatures"); + else if (res.attempted != 1 || res.signed_ok != 1) + FAIL("input not tallied as signed"); + else + PASS(); +} + +/* A keypath on the other primary chain names our key at tuple position 1, so + * it cannot claim the script generated at position 0, though the descriptor + * generates it. */ +static void test_psbt_classify_registry_other_chain_refused(void) { + TEST("psbt_classify_input: keypath on chain 1 does not claim the chain 0 " + "script -> EXPECTED_OWNED"); + + registry_clear(); + if (!registry_add_from_string("l", LIANA_REGISTRY_DESC, STORAGE_FLASH, + false)) { + FAIL("registry_add_from_string"); + return; + } + + unsigned char spk[WALLY_SCRIPTPUBKEY_P2WSH_LEN], + witness[PSBT_MAX_INNER_SCRIPT_LEN]; + size_t witness_len = 0; + unsigned char other[EC_PUBLIC_KEY_LEN]; + uint8_t kp_other[24]; + if (!liana_scripts(0, spk, witness, &witness_len) || + !liana_key(1, other, kp_other)) { + FAIL("script generation or key derivation"); + registry_clear(); + return; + } + + struct wally_psbt *psbt = make_test_psbt( + spk, sizeof(spk), other, sizeof(other), kp_other, sizeof(kp_other)); + if (!psbt || wally_psbt_set_input_witness_script(psbt, 0, witness, + witness_len) != WALLY_OK) { + FAIL("PSBT construction"); + wally_psbt_free(psbt); + registry_clear(); + return; + } + + input_ownership_t r = psbt_classify_input(psbt, 0, false); + wally_psbt_free(psbt); + registry_clear(); + + if (r.ownership != PSBT_OWNERSHIP_EXPECTED_OWNED) + FAIL("expected EXPECTED_OWNED"); + else + PASS(); +} + /* Mixed two-input PSBT: input 0 is OWNED_SAFE (BIP84 verified), input 1 is * EXTERNAL (foreign fp). Verifies each input is classified independently and * that the per-input policy gate in psbt_sign signs exactly one of them. */ @@ -4108,6 +4720,281 @@ static void test_psbt_classify_multi_input_mixed(void) { PASS(); } +/* ================================================================ + * Taptree signing + * + * A tr() whose internal key is spendable and whose leaves also name our keys + * gets a PSBT_IN_TAP_BIP32_DERIVATION entry per key, which is the coordinator + * asking for a signature from each. The internal key signs the key path, a + * leaf key signs its leaves. + * ================================================================ */ + +/* Internal key on m/86'/0'/0', one leaf key on m/84'/0'/0'. Two different + * keys, so no reuse between the internal key and the leaf. */ +#define DESC_TAPTREE \ + "tr([00000000/86'/0'/0']" XPUB_86 "/0/*," \ + "pk([00000000/84'/0'/0']" XPUB_84 "/0/*))" + +/* Add one PSBT_IN_TAP_BIP32_DERIVATION entry: the keypath in taproot_leaf_paths + * and the tapleaf hashes it covers in taproot_leaf_hashes, both keyed by the + * x-only pubkey. An empty hash list marks the internal key. */ +static bool add_taproot_key(struct wally_psbt *psbt, const unsigned char *xonly, + const uint8_t *keypath, size_t keypath_len, + const unsigned char *leaf_hashes, + size_t leaf_hashes_len) { + return wally_map_add(&psbt->inputs[0].taproot_leaf_paths, xonly, + EC_XONLY_PUBLIC_KEY_LEN, keypath, + keypath_len) == WALLY_OK && + wally_map_merkle_path_add(&psbt->inputs[0].taproot_leaf_hashes, xonly, + EC_XONLY_PUBLIC_KEY_LEN, leaf_hashes, + leaf_hashes_len) == WALLY_OK; +} + +/* Build a single-input PSBT spending DESC_TAPTREE at child 0, populated the + * way a coordinator would: internal key, merkle root, leaf script with its + * control block, and a taproot keypath per key we are asked to sign with. + * `leaf_first` puts the leaf key ahead of the internal key in the derivation + * map, which is what a single-key signer would have picked. */ +static struct wally_psbt *make_taptree_psbt(bool leaf_first) { + struct wally_descriptor *desc = NULL; + struct wally_tx *tx = NULL; + struct wally_psbt *psbt = NULL; + struct wally_tx_output *utxo = NULL; + struct ext_key *internal = NULL, *leaf = NULL; + unsigned char spk[64], merkle[32], leaf_hash[32]; + unsigned char script[128], control[128]; + unsigned char txid[32]; + size_t spk_len = 0, script_len = 0, control_len = 0; + /* fp(4) then little-endian path components, as PSBT keypath values are + * serialized: m/86'/0'/0'/0/0 and m/84'/0'/0'/0/0 under our fingerprint. */ + const uint8_t kp_internal[] = { + 0x00, 0x00, 0x00, 0x00, 0x56, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, + 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + const uint8_t kp_leaf[] = { + 0x00, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, + 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + + if (wally_descriptor_parse(DESC_TAPTREE, NULL, WALLY_NETWORK_BITCOIN_MAINNET, + 0, &desc) != WALLY_OK) + return NULL; + + if (wally_descriptor_to_script(desc, 0, 0, 0, 0, 0, 0, spk, sizeof(spk), + &spk_len) != WALLY_OK || + wally_descriptor_get_taproot_merkle_root(desc, 0, 0, 0, merkle, + sizeof(merkle)) != WALLY_OK || + wally_descriptor_get_taproot_leaf_hash(desc, 0, 0, 0, 0, leaf_hash, + sizeof(leaf_hash)) != WALLY_OK || + wally_descriptor_get_taproot_leaf_script( + desc, 0, 0, 0, 0, script, sizeof(script), &script_len) != WALLY_OK || + wally_descriptor_get_taproot_control_block( + desc, 0, 0, 0, 0, control, sizeof(control), &control_len) != WALLY_OK) + goto fail; + + if (!key_get_derived_key("m/86'/0'/0'/0/0", &internal) || + !key_get_derived_key("m/84'/0'/0'/0/0", &leaf)) + goto fail; + + memset(txid, 0xab, sizeof(txid)); + if (wally_tx_init_alloc(2, 0, 1, 1, &tx) != WALLY_OK) + goto fail; + wally_tx_add_raw_input(tx, txid, sizeof(txid), 0, 0xffffffff, NULL, 0, NULL, + 0); + { + unsigned char op_return[] = {0x6a}; + wally_tx_add_raw_output(tx, 0, op_return, sizeof(op_return), 0); + } + if (wally_psbt_from_tx(tx, 0, 0, &psbt) != WALLY_OK) + goto fail; + + if (wally_tx_output_init_alloc(100000, spk, spk_len, &utxo) != WALLY_OK || + wally_psbt_set_input_witness_utxo(psbt, 0, utxo) != WALLY_OK) + goto fail; + + if (wally_psbt_input_set_taproot_internal_key( + &psbt->inputs[0], internal->pub_key + 1, EC_XONLY_PUBLIC_KEY_LEN) != + WALLY_OK || + wally_psbt_input_add_taproot_leaf_script(&psbt->inputs[0], control, + control_len, script, + script_len) != WALLY_OK) + goto fail; + if (wally_map_add_integer(&psbt->inputs[0].psbt_fields, + 0x18 /* merkle root */, merkle, + sizeof(merkle)) != WALLY_OK) + goto fail; + + /* An empty tapleaf hash list marks the internal key; the leaf key lists the + * leaf it can spend. */ + if (leaf_first && + !add_taproot_key(psbt, leaf->pub_key + 1, kp_leaf, sizeof(kp_leaf), + leaf_hash, sizeof(leaf_hash))) + goto fail; + if (!add_taproot_key(psbt, internal->pub_key + 1, kp_internal, + sizeof(kp_internal), NULL, 0)) + goto fail; + if (!leaf_first && + !add_taproot_key(psbt, leaf->pub_key + 1, kp_leaf, sizeof(kp_leaf), + leaf_hash, sizeof(leaf_hash))) + goto fail; + + wally_tx_output_free(utxo); + wally_tx_free(tx); + bip32_key_free(internal); + bip32_key_free(leaf); + wally_descriptor_free(desc); + return psbt; + +fail: + if (utxo) + wally_tx_output_free(utxo); + if (tx) + wally_tx_free(tx); + if (psbt) + wally_psbt_free(psbt); + if (internal) + bip32_key_free(internal); + if (leaf) + bip32_key_free(leaf); + if (desc) + wally_descriptor_free(desc); + return NULL; +} + +/* Registers DESC_TAPTREE so the input classifies against it, runs psbt_sign, + * and reports the signature counts. */ +static const char *sign_taptree(bool leaf_first, size_t *key_sig_len, + size_t *leaf_sigs, psbt_sign_result_t *res) { + struct wally_psbt *psbt = make_taptree_psbt(leaf_first); + if (!psbt) + return "make_taptree_psbt"; + + registry_clear(); + if (!registry_add_from_string("tt", DESC_TAPTREE, STORAGE_FLASH, false)) { + wally_psbt_free(psbt); + return "registry_add_from_string"; + } + + if (psbt_classify_input(psbt, 0, false).ownership != + PSBT_OWNERSHIP_OWNED_SAFE) { + wally_psbt_free(psbt); + registry_clear(); + return "taptree input did not classify OWNED_SAFE"; + } + + psbt_sign_policy_t policy = {0}; + (void)psbt_sign(psbt, false, policy, res); + + *key_sig_len = 0; + wally_psbt_get_input_taproot_signature_len(psbt, 0, key_sig_len); + *leaf_sigs = psbt->inputs[0].taproot_leaf_signatures.num_items; + + wally_psbt_free(psbt); + registry_clear(); + return NULL; +} + +static void test_psbt_sign_taptree_signs_every_listed_key(void) { + TEST("psbt_sign: taptree input signs both the internal key and the leaf"); + + size_t key_sig_len = 0, leaf_sigs = 0; + psbt_sign_result_t res; + const char *err = sign_taptree(false, &key_sig_len, &leaf_sigs, &res); + if (err) { + FAIL(err); + return; + } + + if (!key_sig_len) + FAIL("no key-path signature from the internal key"); + else if (leaf_sigs != 1) + FAIL("expected exactly one leaf signature"); + else if (res.attempted != 1 || res.signed_ok != 1) + FAIL("input not tallied as signed"); + else + PASS(); +} + +static void test_psbt_sign_taptree_order_independent(void) { + TEST("psbt_sign: taptree signs both keys whichever is listed first"); + + size_t key_sig_len = 0, leaf_sigs = 0; + psbt_sign_result_t res; + const char *err = sign_taptree(true, &key_sig_len, &leaf_sigs, &res); + if (err) { + FAIL(err); + return; + } + + if (!key_sig_len || leaf_sigs != 1) + FAIL("leaf-first ordering lost a signature"); + else + PASS(); +} + +/* A derivation path derives exactly one key, so two entries claiming the same + * path name two different keys for one private key. Signing either would be + * choosing on an attacker's behalf. */ +static void test_psbt_sign_taptree_duplicate_path_refused(void) { + TEST("psbt_sign: two keys on one derivation path signs nothing"); + + struct wally_psbt *psbt = make_taptree_psbt(false); + if (!psbt) { + FAIL("make_taptree_psbt"); + return; + } + + struct ext_key *other = NULL; + if (!key_get_derived_key("m/84'/0'/0'/0/1", &other)) { + wally_psbt_free(psbt); + FAIL("key derivation failed"); + return; + } + + /* A third key on the leaf key's exact path. */ + const uint8_t kp_leaf[] = { + 0x00, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, + 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + unsigned char leaf_hash[32]; + memcpy(leaf_hash, psbt->inputs[0].taproot_leaf_hashes.items[1].value, + sizeof(leaf_hash)); + bool added = add_taproot_key(psbt, other->pub_key + 1, kp_leaf, + sizeof(kp_leaf), leaf_hash, sizeof(leaf_hash)); + bip32_key_free(other); + if (!added) { + wally_psbt_free(psbt); + FAIL("could not add the colliding keypath"); + return; + } + + registry_clear(); + if (!registry_add_from_string("tt", DESC_TAPTREE, STORAGE_FLASH, false)) { + wally_psbt_free(psbt); + FAIL("registry_add_from_string"); + return; + } + + psbt_sign_policy_t policy = {0}; + psbt_sign_result_t res; + size_t signed_count = psbt_sign(psbt, false, policy, &res); + + size_t key_sig_len = 0; + wally_psbt_get_input_taproot_signature_len(psbt, 0, &key_sig_len); + size_t leaf_sigs = psbt->inputs[0].taproot_leaf_signatures.num_items; + wally_psbt_free(psbt); + registry_clear(); + + if (signed_count != 0) + FAIL("signing reported success"); + else if (key_sig_len || leaf_sigs) + FAIL("a signature was written despite the refusal"); + else if (res.signed_ok != 0 || res.attempted != 0) + FAIL("refused input was tallied as attempted"); + else + PASS(); +} + /* The signing gate is only real if it survives libwally signing the whole * PSBT at once. Input 1 here is a second UTXO at an address we own, labelled * with someone else's fingerprint so it classifies EXTERNAL; its keypath still @@ -4896,6 +5783,9 @@ int main(void) { test_psbt_sign_gate_external_always_skipped(); test_psbt_classify_multi_input_mixed(); test_overlong_keypaths_skipped(); + test_psbt_sign_taptree_signs_every_listed_key(); + test_psbt_sign_taptree_order_independent(); + test_psbt_sign_taptree_duplicate_path_refused(); test_psbt_sign_denied_input_keeps_no_signature(); test_psbt_classify_registry_wsh_owned(); test_psbt_classify_registry_wsh_tampered_witness(); @@ -4928,6 +5818,9 @@ int main(void) { test_sign_every_own_key_wsh(); test_sign_every_own_key_tr(); } + test_psbt_sign_registry_recovery_keys(0); + test_psbt_sign_registry_recovery_keys(1); + test_psbt_classify_registry_other_chain_refused(); printf("\n=== PSBTv2 tests ===\n\n"); @@ -4941,6 +5834,22 @@ int main(void) { test_trim_psbt_v2_in_place(); test_trim_v0_keeps_signatures(); + printf("\n=== silent payment tests ===\n\n"); + + test_silent_payment_classify(); + test_silent_payment_scan_key_not_ours(); + test_sign_silent_payment_input(); + test_sign_silent_payment_keeps_sighash_all(); + test_partial_signing_refuses_share_round(); + test_partial_signing_allows_share_round(); + test_partial_signing_own_inputs(false); + test_partial_signing_own_inputs(true); + test_partial_signing_no_own_input(); + test_permissive_signing_share_round(false); + test_permissive_signing_share_round(true); + test_expected_owned_signing_share_round(false); + test_expected_owned_signing_share_round(true); + key_unload(); printf("\n=== Results: %d passed, %d failed ===\n", tests_passed, diff --git a/main/core/test/test_psbt_parse.c b/main/core/test/test_psbt_parse.c index bbcdb7bd..4e2e34f3 100644 --- a/main/core/test/test_psbt_parse.c +++ b/main/core/test/test_psbt_parse.c @@ -50,6 +50,39 @@ static const char PSBT_HEX[] = static const char PSET_HEX[] = "70736574ff01020402000000010401000105010001fb040200000000"; static const char PSET_BASE64[] = "cHNldP8BAgQCAAAAAQQBAAEFAQAB+wQCAAAAAA=="; +/* sp_fixture.h's UNSIGNED_PSBT, a silent payment send, with an explicit + * PSBT_IN_SIGHASH_TYPE on its input: SIGHASH_DEFAULT (0), then SIGHASH_ALL */ +static const char SP_SIGHASH_DEFAULT_PSBT_HEX[] = + "70736274ff0102040200000001030400000000010401010105010201fb04020000000001" + "012ba086010000000000225120cba15611f961103c8738f27fefa7b774bc6b242f17b55d" + "ae832a3ae2efe332ed010e20222222222222222222222222222222222222222222222222" + "2222222222222222010f0400000000012020111111111111111111111111111111111111" + "1111111111111111111111111111010304000000000001030860ea000000000000010942" + "0220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4025cc9" + "856d6f8375350e123978daac200c260cb5b5ae83106cab90484dcd8fcf36000103085898" + "000000000000010942024139b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcd" + "d511beaea1e3031ec096b3e9917a43e81c6d014acab0dfa32151ea7dcdfa56a1dc89f0ae" + "c04ef8010a040000000000"; +static const char SP_SIGHASH_ALL_PSBT_HEX[] = + "70736274ff0102040200000001030400000000010401010105010201fb04020000000001" + "012ba086010000000000225120cba15611f961103c8738f27fefa7b774bc6b242f17b55d" + "ae832a3ae2efe332ed010e20222222222222222222222222222222222222222222222222" + "2222222222222222010f0400000000012020111111111111111111111111111111111111" + "1111111111111111111111111111010304010000000001030860ea000000000000010942" + "0220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4025cc9" + "856d6f8375350e123978daac200c260cb5b5ae83106cab90484dcd8fcf36000103085898" + "000000000000010942024139b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcd" + "d511beaea1e3031ec096b3e9917a43e81c6d014acab0dfa32151ea7dcdfa56a1dc89f0ae" + "c04ef8010a040000000000"; + +/* PSBT_HEX with its explicit SIGHASH_ALL turned into SIGHASH_DEFAULT (0) */ +static const char SIGHASH_DEFAULT_PSBT_HEX[] = + "70736274ff01003d00000000017189d386a21d477ce6809ef31f0dfe076f32b6c82d065b" + "2b50cc5c9867fd85f6000000000000000000010000000000000000016a00000000010" + "90b48656c6c6f20576f726c640001011f000000000000000016001481407ea42dd4f1e3" + "8cfff569aea3b2b85b9d53dc01030400000000220603c4c806d0c119b335e39b144bc4ba" + "b1a51006cf3d975dbe7407e31ee75939e9e01865fb43fe5400008001000080000000800" + "0000000010000000000"; static size_t hex_decode(const char *hex, uint8_t *out, size_t out_size) { size_t len = strlen(hex) / 2; @@ -140,6 +173,22 @@ static void test_pset_rejected(void) { wally_psbt_free(psbt); } +/* Parse the PSBT `hex` and assert psbt_parse_payload_result's verdict. */ +static void check_hex(const char *name, const char *hex, + psbt_parse_result_t want) { + uint8_t buf[640]; + size_t len = hex_decode(hex, buf, sizeof(buf)); + struct wally_psbt *psbt = NULL; + TEST(name); + if (len && psbt_parse_payload_result(buf, len, &psbt) == want && + (psbt != NULL) == (want == PSBT_PARSE_OK)) + PASS(); + else + FAIL(want == PSBT_PARSE_OK ? "expected the parse to succeed" + : "expected the parse to fail for that reason"); + wally_psbt_free(psbt); +} + int main(void) { /* The host libwally hashes through PSA, as the device does, which needs * wally_init. */ @@ -218,6 +267,24 @@ int main(void) { } test_pset_rejected(); + check_hex("an explicit SIGHASH_DEFAULT with silent payment outputs is " + "refused for its sighash", + SP_SIGHASH_DEFAULT_PSBT_HEX, PSBT_PARSE_SP_SIGHASH); + check_hex("an explicit SIGHASH_ALL with silent payment outputs parses", + SP_SIGHASH_ALL_PSBT_HEX, PSBT_PARSE_OK); + check_hex("an explicit SIGHASH_DEFAULT without silent payment outputs " + "parses", + SIGHASH_DEFAULT_PSBT_HEX, PSBT_PARSE_OK); + + TEST("a truncated PSBT is invalid, not refused for its sighash"); + psbt = NULL; + if (psbt_parse_payload_result(base, base_len - 8, &psbt) == + PSBT_PARSE_INVALID && + !psbt) + PASS(); + else + FAIL("expected PSBT_PARSE_INVALID"); + wally_psbt_free(psbt); printf("\nResults: %d passed, %d failed\n", tests_run - tests_failed, tests_failed); diff --git a/main/core/test/test_registry_match.c b/main/core/test/test_registry_match.c index 011d65b9..d34cd056 100644 --- a/main/core/test/test_registry_match.c +++ b/main/core/test/test_registry_match.c @@ -200,6 +200,18 @@ int main(void) { } else { FAIL("register two-group miniscript"); } + { + seed_registry(); + /* e[3]: 87'/0'/0', <2;3> as a recovery path key */ + if (!registry_add_from_string( + "e3", "wpkh([00000000/87'/0'/0']" XPUB_84 "/<2;3>/*)", + STORAGE_FLASH, false)) { + FAIL("registry_add_from_string e3"); + } else { + n = keypath(kp, 5, H(87), H(0), H(0), 3u, 7u); + expect_match("<2;3> entry with mp=3 is group 1", kp, n, "e3", 1, 7); + } + } printf("\n--- cursor pagination ---\n"); seed_registry(); @@ -221,6 +233,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_silentpayments.c b/main/core/test/test_silentpayments.c new file mode 100644 index 00000000..2d99b46b --- /dev/null +++ b/main/core/test/test_silentpayments.c @@ -0,0 +1,226 @@ +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "kern_bech32.h" + +static int tests_passed = 0; +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() \ + do { \ + printf("PASS\n"); \ + tests_passed++; \ + } while (0) +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +#define MAX_KEYS 2 +#define MAX_RECIPIENTS 3 +#define OUTPOINT_LEN 36 + +/* A BIP352 sending vector (bip352_send_and_receive_test_vectors.json of + * secp256k1 PR #1765). Outputs are listed as the vector does, unordered. */ +struct sender_vector { + const char *name; + const char *seckeys[MAX_KEYS]; + size_t n_seckeys; + const char *taproot_seckeys[MAX_KEYS]; + size_t n_taproot_seckeys; + const char *outpoint_smallest; + const char *scan_pubkeys[MAX_RECIPIENTS]; + const char *spend_pubkeys[MAX_RECIPIENTS]; + size_t n_recipients; + const char *outputs[MAX_RECIPIENTS]; +}; + +static const char SCAN_A[] = + "0220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4"; +static const char SPEND_A[] = + "025cc9856d6f8375350e123978daac200c260cb5b5ae83106cab90484dcd8fcf36"; +static const char SCAN_B[] = + "02062d49ffc02787d586c608dfbec184aa91a6597d97b463ea5c6babd9d17a95a3"; +static const char SPEND_B[] = + "0381eb9a9a9ec739d527c1631b31b421566f5c2a47b4ab5b1f6a686dfb68eab716"; +static const char OUTPOINT_F418[] = + "169e1e83e930853391bc6f35f605c6754cfead57cf8387639d3b4096c54f18f400000000"; + +static const struct sender_vector VECTORS[] = { + { + .name = "Simple send: two inputs", + .seckeys = {"eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5" + "dff3b1", + "93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a940" + "8aad16"}, + .n_seckeys = 2, + .outpoint_smallest = OUTPOINT_F418, + .scan_pubkeys = {SCAN_A}, + .spend_pubkeys = {SPEND_A}, + .n_recipients = 1, + .outputs = {"3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de" + "46e3c1"}, + }, + { + .name = "Single recipient: taproot only with mixed even/odd y-values", + .taproot_seckeys = {"eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b4215" + "4201b8e5dff3b1", + "1d37787c2b7116ee983e9f9c13269df29091b391c04db94239" + "e0d2bc2182c3bf"}, + .n_taproot_seckeys = 2, + .outpoint_smallest = OUTPOINT_F418, + .scan_pubkeys = {SCAN_A}, + .spend_pubkeys = {SPEND_A}, + .n_recipients = 1, + .outputs = {"77cab7dd12b10259ee82c6ea4b509774e33e7078e7138f568092241bf2" + "6b99f1"}, + }, + { + .name = "Multiple outputs: multiple outputs, multiple recipients", + .seckeys = {"eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5" + "dff3b1", + "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164" + "fad66a"}, + .n_seckeys = 2, + .outpoint_smallest = OUTPOINT_F418, + .scan_pubkeys = {SCAN_A, SCAN_B, SCAN_B}, + .spend_pubkeys = {SPEND_A, SPEND_B, SPEND_B}, + .n_recipients = 3, + .outputs = {"2e847bb01d1b491da512ddd760b8509617ee38057003d6115d00ba5624" + "51323a", + "841792c33c9dc6193e76744134125d40add8f2f4a96475f28ba150be03" + "2d64e8", + "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325" + "db33ac"}, + }, +}; + +static bool hex_to(const char *hex, unsigned char *out, size_t len) { + size_t written; + return wally_hex_to_bytes(hex, out, len, &written) == WALLY_OK && + written == len; +} + +static bool parse_pubkey(const secp256k1_context *ctx, const char *hex, + secp256k1_pubkey *out) { + unsigned char ser[33]; + return hex_to(hex, ser, sizeof(ser)) && + secp256k1_ec_pubkey_parse(ctx, out, ser, sizeof(ser)); +} + +static bool output_expected(const struct sender_vector *v, + const unsigned char *xonly) { + for (size_t i = 0; i < v->n_recipients; i++) { + unsigned char expected[32]; + if (hex_to(v->outputs[i], expected, sizeof(expected)) && + memcmp(expected, xonly, sizeof(expected)) == 0) + return true; + } + return false; +} + +static bool sender_vector_passes(const struct sender_vector *v) { + const secp256k1_context *ctx = wally_get_secp_context(); + unsigned char seckeys[MAX_KEYS][32]; + const unsigned char *seckey_ptrs[MAX_KEYS]; + secp256k1_keypair keypairs[MAX_KEYS]; + const secp256k1_keypair *keypair_ptrs[MAX_KEYS]; + secp256k1_silentpayments_recipient recipients[MAX_RECIPIENTS]; + const secp256k1_silentpayments_recipient *recipient_ptrs[MAX_RECIPIENTS]; + secp256k1_xonly_pubkey outputs[MAX_RECIPIENTS]; + secp256k1_xonly_pubkey *output_ptrs[MAX_RECIPIENTS]; + unsigned char outpoint[OUTPOINT_LEN]; + + for (size_t i = 0; i < v->n_seckeys; i++) { + if (!hex_to(v->seckeys[i], seckeys[i], 32)) + return false; + seckey_ptrs[i] = seckeys[i]; + } + for (size_t i = 0; i < v->n_taproot_seckeys; i++) { + unsigned char seckey[32]; + if (!hex_to(v->taproot_seckeys[i], seckey, sizeof(seckey)) || + !secp256k1_keypair_create(ctx, &keypairs[i], seckey)) + return false; + keypair_ptrs[i] = &keypairs[i]; + } + for (size_t i = 0; i < v->n_recipients; i++) { + if (!parse_pubkey(ctx, v->scan_pubkeys[i], &recipients[i].scan_pubkey) || + !parse_pubkey(ctx, v->spend_pubkeys[i], &recipients[i].spend_pubkey)) + return false; + recipients[i].index = i; + recipient_ptrs[i] = &recipients[i]; + output_ptrs[i] = &outputs[i]; + } + if (!hex_to(v->outpoint_smallest, outpoint, sizeof(outpoint))) + return false; + + if (!secp256k1_silentpayments_sender_create_outputs( + ctx, output_ptrs, recipient_ptrs, v->n_recipients, outpoint, + v->n_taproot_seckeys ? keypair_ptrs : NULL, v->n_taproot_seckeys, + v->n_seckeys ? seckey_ptrs : NULL, v->n_seckeys)) + return false; + + for (size_t i = 0; i < v->n_recipients; i++) { + unsigned char xonly[32]; + if (!secp256k1_xonly_pubkey_serialize(ctx, xonly, &outputs[i]) || + !output_expected(v, xonly)) + return false; + } + return true; +} + +static bool address_encodes(const char *scan_hex, const char *spend_hex, + const char *expected) { + unsigned char keys[66]; + char address[KERN_BECH32M_MAX_LEN + 1]; + return hex_to(scan_hex, keys, 33) && hex_to(spend_hex, keys + 33, 33) && + kern_bech32m_encode("sp", 0, keys, sizeof(keys), address, + sizeof(address)) == WALLY_OK && + strcmp(address, expected) == 0; +} + +int main(void) { + for (size_t i = 0; i < sizeof(VECTORS) / sizeof(VECTORS[0]); i++) { + TEST(VECTORS[i].name); + if (sender_vector_passes(&VECTORS[i])) + PASS(); + else + FAIL("generated outputs differ from the vector"); + } + + TEST("kern_bech32m_encode builds the vector's sp1 address"); + if (address_encodes( + SCAN_A, SPEND_A, + "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6m" + "urw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv") && + address_encodes( + SCAN_B, SPEND_B, + "sp1qqgrz6j0lcqnc04vxccydl0kpsj4frfje0ktmgcl2t346hkw30226xqupawdf48" + "k8882j0strrvcmgg2kdawz53a54dd376ngdhak364hzcmynqtn")) + PASS(); + else + FAIL("address mismatch"); + + TEST("kern_bech32m_encode refuses a buffer too small"); + { + unsigned char keys[66] = {0}; + char address[90]; + if (kern_bech32m_encode("sp", 0, keys, sizeof(keys), address, + sizeof(address)) == WALLY_EINVAL) + PASS(); + else + FAIL("encoded into a 90-char buffer"); + } + + printf("\n%d passed, %d failed\n", tests_passed, tests_failed); + return tests_failed ? 1 : 0; +} diff --git a/main/core/test/test_sp_keys.c b/main/core/test/test_sp_keys.c new file mode 100644 index 00000000..30ebfdb6 --- /dev/null +++ b/main/core/test/test_sp_keys.c @@ -0,0 +1,489 @@ +#include +#include +#include +#include +#include + +#include +#include + +#include "core/key.h" +#include "core/silent_payments.h" + +static int tests_passed = 0; +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() \ + do { \ + printf("PASS\n"); \ + tests_passed++; \ + } while (0) +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +/* BIP39 test mnemonic, empty passphrase */ +static const char *TEST_MNEMONIC = + "abandon abandon abandon abandon abandon abandon " + "abandon abandon abandon abandon abandon about"; + +/* Printed by bwk's SpDescriptor (bwk 24bfd42) for the test mnemonic, built as + * Silent's hot.rs sp_descriptor builds it */ +static const char MAINNET_DESCRIPTOR[] = + "sp([73c5da0a/352'/0'/0']spscan1q0rnl6lft0gkpg4nsn528qgdpytfdej40atdqgrxpq" + "qsg8c5r8vys973ppv7y5c9cphgkzm6g4efmhhcdkazt87ggxwz3pruphc9vkkxxhtvyag)#" + "429s66dn"; +static const char TESTNET_DESCRIPTOR[] = + "sp([73c5da0a/352'/1'/0']tspscan1q8pjcdy7qzlzxl44chw2tsanvzg7dtwhkqf3nsvzm" + "davls2ekl8qq9qesshy6w9knddr825kqp442302zuwddh6vtqk7zqvgszace9aczgnuqn3)#" + "ke33wu3h"; +static const char MAINNET_SCAN_PUBKEY[] = + "024139b0f81042e243a90478e43990c6a27be0e3346f0c71adbbcdd511beaea1e3"; +static const char MAINNET_SPEND_PUBKEY[] = + "02fa210b3c4a60b80dd1616f48ae53bbdf0db744b3f9083385108f81be0acb58c6"; + +/* BIP352 vector "Simple send: two inputs" recipient */ +static const char VECTOR_SCAN_PUBKEY[] = + "0220bcfac5b99e04ad1a06ddfb016ee13582609d60b6291e98d01a9bc9a16c96d4"; +static const char VECTOR_SPEND_PUBKEY[] = + "025cc9856d6f8375350e123978daac200c260cb5b5ae83106cab90484dcd8fcf36"; +static const char VECTOR_ADDRESS[] = + "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56s" + "uy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"; + +/* BIP352 receiving vectors' scan secret, whose public key is + * VECTOR_SCAN_PUBKEY, and its labelled addresses with VECTOR_SPEND_PUBKEY */ +static const char VECTOR_SCAN_SECRET[] = + "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"; +static const char VECTOR_LABEL_1_ADDRESS[] = + "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cg" + "hth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj"; +static const char VECTOR_LABEL_2_ADDRESS[] = + "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjex54dmqmmv6rw" + "353tsuqhs99ydvadxzrsy9nuvk74epvee55drs734pqq"; +static const char VECTOR_LABEL_1001337_ADDRESS[] = + "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgq7c2zfthc6x3a5y" + "ecwc52nxa0kfd20xuz08zyrjpfw4l2j257yq6qgnkdh5"; +static const char VECTOR_TESTNET_LABEL_1_ADDRESS[] = + "tsp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05c" + "ghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y9weewf"; +static const char VECTOR_LABEL_1_SPEND_PUBKEY[] = + "03a6739499dc667d308baefea4de0c4a85cc72aece181bc05712d3919662610ff1"; + +static bool hex_to(const char *hex, unsigned char *out, size_t len) { + size_t written; + return wally_hex_to_bytes(hex, out, len, &written) == WALLY_OK && + written == len; +} + +static void test_descriptor(const char *name, bool is_testnet, + const char *expected) { + char *descriptor = NULL; + TEST(name); + if (sp_descriptor_alloc(is_testnet, &descriptor) && + strcmp(descriptor, expected) == 0) + PASS(); + else + FAIL(descriptor ? descriptor : "sp_descriptor_alloc failed"); + free(descriptor); +} + +static void test_keys(void) { + struct sp_keys keys; + unsigned char scan[SP_PUBKEY_LEN], spend[SP_PUBKEY_LEN]; + TEST("sp_keys_derive gives bwk's mainnet scan and spend keys"); + if (hex_to(MAINNET_SCAN_PUBKEY, scan, sizeof(scan)) && + hex_to(MAINNET_SPEND_PUBKEY, spend, sizeof(spend)) && + sp_keys_derive(false, &keys) && + memcmp(keys.scan_pubkey, scan, sizeof(scan)) == 0 && + memcmp(keys.spend_pubkey, spend, sizeof(spend)) == 0) + PASS(); + else + FAIL("derived keys differ"); + sp_keys_wipe(&keys); +} + +static void test_address(void) { + unsigned char scan[SP_PUBKEY_LEN], spend[SP_PUBKEY_LEN]; + char *address = NULL; + TEST("sp_address_alloc builds the BIP352 vector address"); + if (hex_to(VECTOR_SCAN_PUBKEY, scan, sizeof(scan)) && + hex_to(VECTOR_SPEND_PUBKEY, spend, sizeof(spend)) && + sp_address_alloc(scan, spend, false, &address) && + strcmp(address, VECTOR_ADDRESS) == 0) + PASS(); + else + FAIL(address ? address : "sp_address_alloc failed"); + free(address); +} + +static void expect_account_address(const char *name, const uint32_t *label, + size_t label_len, bool is_testnet, + const char *expected) { + unsigned char scan_secret[SP_SECRET_LEN], spend[SP_PUBKEY_LEN]; + char *address = NULL; + TEST(name); + if (hex_to(VECTOR_SCAN_SECRET, scan_secret, sizeof(scan_secret)) && + hex_to(VECTOR_SPEND_PUBKEY, spend, sizeof(spend)) && + sp_account_address_alloc(scan_secret, spend, label, label_len, is_testnet, + &address) == SP_ADDRESS_OK && + strcmp(address, expected) == 0) + PASS(); + else + FAIL(address ? address : "sp_account_address_alloc failed"); + free(address); +} + +static void expect_account_address_error(const char *name, + const char *scan_secret_hex, + const uint32_t *label, + size_t label_len, + sp_address_result_t expected) { + unsigned char scan_secret[SP_SECRET_LEN], spend[SP_PUBKEY_LEN]; + char *address = NULL; + TEST(name); + if (hex_to(scan_secret_hex, scan_secret, sizeof(scan_secret)) && + hex_to(VECTOR_SPEND_PUBKEY, spend, sizeof(spend)) && + sp_account_address_alloc(scan_secret, spend, label, label_len, false, + &address) == expected && + !address) + PASS(); + else + FAIL(address ? address : "unexpected result"); + free(address); +} + +static void test_account_address(void) { + const uint32_t label_0[] = {0}; + const uint32_t label_1[] = {1}; + const uint32_t label_2[] = {2}; + const uint32_t label_1001337[] = {1001337}; + const uint32_t two_steps[] = {1, 2}; + unsigned char scan_secret[SP_SECRET_LEN], spend[SP_PUBKEY_LEN]; + unsigned char labeled[SP_PUBKEY_LEN], expected[SP_PUBKEY_LEN]; + + expect_account_address("sp_account_address_alloc gives the base address", + NULL, 0, false, VECTOR_ADDRESS); + expect_account_address("sp_account_address_alloc labels with m = 1", label_1, + 1, false, VECTOR_LABEL_1_ADDRESS); + expect_account_address("sp_account_address_alloc labels with m = 2", label_2, + 1, false, VECTOR_LABEL_2_ADDRESS); + expect_account_address("sp_account_address_alloc labels with m = 1001337", + label_1001337, 1, false, VECTOR_LABEL_1001337_ADDRESS); + expect_account_address("sp_account_address_alloc encodes tsp on testnet", + label_1, 1, true, VECTOR_TESTNET_LABEL_1_ADDRESS); + expect_account_address_error( + "sp_account_address_alloc refuses the change label", VECTOR_SCAN_SECRET, + label_0, 1, SP_ADDRESS_ERR_LABEL); + expect_account_address_error( + "sp_account_address_alloc refuses a two step label path", + VECTOR_SCAN_SECRET, two_steps, 2, SP_ADDRESS_ERR_LABEL); + expect_account_address_error( + "sp_account_address_alloc refuses a zero scan secret", + "0000000000000000000000000000000000000000000000000000000000000000", NULL, + 0, SP_ADDRESS_ERR_KEY); + + TEST("sp_labeled_spend_pubkey labels the spend key with m = 1"); + if (hex_to(VECTOR_SCAN_SECRET, scan_secret, sizeof(scan_secret)) && + hex_to(VECTOR_SPEND_PUBKEY, spend, sizeof(spend)) && + hex_to(VECTOR_LABEL_1_SPEND_PUBKEY, expected, sizeof(expected)) && + sp_labeled_spend_pubkey(scan_secret, spend, 1, labeled) && + memcmp(labeled, expected, sizeof(expected)) == 0) + PASS(); + else + FAIL("labelled spend key differs"); +} + +static void test_descriptor_ownership(void) { + char without_checksum[sizeof(MAINNET_DESCRIPTOR)]; + size_t body_len = strchr(MAINNET_DESCRIPTOR, '#') - MAINNET_DESCRIPTOR; + memcpy(without_checksum, MAINNET_DESCRIPTOR, body_len); + without_checksum[body_len] = '\0'; + + TEST("sp_descriptor_is_sp tells sp() descriptors apart"); + if (sp_descriptor_is_sp(MAINNET_DESCRIPTOR) && + !sp_descriptor_is_sp("tr([73c5da0a/86'/0'/0']xpub)") && + !sp_descriptor_is_sp(NULL)) + PASS(); + else + FAIL("sp() detection wrong"); + + TEST("sp_descriptor_is_ours accepts our descriptor, its checksum aside"); + if (sp_descriptor_is_ours(MAINNET_DESCRIPTOR, false) && + sp_descriptor_is_ours(without_checksum, false) && + sp_descriptor_is_ours(TESTNET_DESCRIPTOR, true)) + PASS(); + else + FAIL("own descriptor rejected"); + + TEST("sp_descriptor_is_ours rejects another network or account"); + without_checksum[body_len - 2] ^= 1; + if (!sp_descriptor_is_ours(MAINNET_DESCRIPTOR, true) && + !sp_descriptor_is_ours(TESTNET_DESCRIPTOR, false) && + !sp_descriptor_is_ours(without_checksum, false)) + PASS(); + else + FAIL("foreign descriptor accepted"); +} + +#define H(n) ((n) | BIP32_INITIAL_HARDENED_CHILD) + +static void test_path_on_branch(void) { + const uint32_t scan_0[] = {H(352), H(0), H(0), H(1), 0}; + const uint32_t scan_5[] = {H(352), H(0), H(0), H(1), 5}; + const uint32_t unhardened_purpose[] = {352, H(0), H(0), H(1), 0}; + const uint32_t spend[] = {H(352), H(0), H(0), H(0), 0}; + + TEST("sp_path_on_branch matches the scan branch at any index"); + if (sp_path_on_branch(scan_0, 5, false, SP_SCAN_BRANCH) && + sp_path_on_branch(scan_5, 5, false, SP_SCAN_BRANCH)) + PASS(); + else + FAIL("scan path rejected"); + + TEST("sp_path_on_branch rejects other coins, purposes, depths, branches"); + if (!sp_path_on_branch(scan_0, 5, true, SP_SCAN_BRANCH) && + !sp_path_on_branch(unhardened_purpose, 5, false, SP_SCAN_BRANCH) && + !sp_path_on_branch(scan_0, 4, false, SP_SCAN_BRANCH) && + !sp_path_on_branch(spend, 5, false, SP_SCAN_BRANCH)) + PASS(); + else + FAIL("foreign path accepted"); +} + +/* Register Descriptor "3f82-9b" for our testnet spend key m/352'/1'/0'/0'/0 + * with the scan key REQUEST_SCAN_SECRET, not ours (SCAN_PATH absent) */ +static const char REGISTER_FOREIGN_SCAN_REQUEST[] = + "4249505858580103000607336638322d3962010373c5da0a058000016080000001800000" + "00800000000000000000019573aff499b1755c5fbfd127f508c7d2bcb5dd8cb052f26661" + "04db6fdf41e14f"; +static const char REQUEST_SCAN_SECRET[] = + "9573aff499b1755c5fbfd127f508c7d2bcb5dd8cb052f2666104db6fdf41e14f"; +static const char REQUEST_SCAN_PUBKEY[] = + "0395e054d3750420f2c79241842553e15b3cfe43f71fb07152fb37191af292e7b6"; +/* bipqr test vector address_verification_sp_foreign_scan_request (7178668): + * label 2 of our testnet spend key with VECTOR_SCAN_SECRET */ +static const char VERIFY_FOREIGN_SCAN_REQUEST[] = + "42495058585801040001046d61696e010000000201077370317178797a010373c5da0a05" + "800001608000000180000000800000000000000000010f694e068028a717f8af6b9411f9" + "a133dd3565258714cc226594b34db90c1f2c00"; +/* Label 2 of our testnet spend key with VECTOR_SCAN_SECRET, by the BIP352 + * label tweak computed outside Kern */ +static const char VECTOR_SCAN_OUR_SPEND_LABEL_2_TESTNET_ADDRESS[] = + "tsp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqugu2zk2789znj8" + "xw9343a505wg8yymzuxxl9fg5e2utfgrm3tjhseudh47"; +/* Our testnet scan secret, in TESTNET_DESCRIPTOR */ +static const char TESTNET_SCAN_SECRET[] = + "38658693c017c46fd6b8bb94b8766c123cd5baf6026338305b6f59f82b36f9c0"; +/* The secp256k1 group order, not a valid secret key */ +static const char CURVE_ORDER[] = + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"; + +static const unsigned char OUR_FINGERPRINT[4] = {0x73, 0xc5, 0xda, 0x0a}; +static const unsigned char OTHER_FINGERPRINT[4] = {0x73, 0xc5, 0xda, 0x0b}; +static const uint32_t TESTNET_SPEND[] = {H(352), H(1), H(0), H(0), 0}; +static const uint32_t TESTNET_SPEND_1[] = {H(352), H(1), H(0), H(0), 1}; +static const uint32_t TESTNET_SCAN[] = {H(352), H(1), H(0), H(1), 0}; +static const uint32_t TESTNET_SCAN_1[] = {H(352), H(1), H(0), H(1), 1}; +static const uint32_t MAINNET_SPEND[] = {H(352), H(0), H(0), H(0), 0}; + +static void expect_account(const char *name, const unsigned char *fingerprint, + const uint32_t *spend, const uint32_t *scan_path, + const char *scan_key_hex, bool is_testnet, + sp_account_t expected) { + unsigned char scan_key[SP_SECRET_LEN]; + TEST(name); + if (scan_key_hex && !hex_to(scan_key_hex, scan_key, sizeof(scan_key))) + FAIL("bad scan key fixture"); + else if (sp_account_classify( + fingerprint, spend, 5, scan_path, scan_path ? 5 : 0, + scan_key_hex ? scan_key : NULL, is_testnet) != expected) + FAIL("unexpected account"); + else + PASS(); +} + +static void test_account_classify(void) { + expect_account("our spend key with our scan path is our account", + OUR_FINGERPRINT, TESTNET_SPEND, TESTNET_SCAN, NULL, true, + SP_ACCOUNT_OURS); + expect_account("our spend key with our scan key by value is our account", + OUR_FINGERPRINT, TESTNET_SPEND, NULL, TESTNET_SCAN_SECRET, + true, SP_ACCOUNT_OURS); + expect_account("our spend key with a scan key not ours is taken", + OUR_FINGERPRINT, TESTNET_SPEND, NULL, REQUEST_SCAN_SECRET, + true, SP_ACCOUNT_FOREIGN_SCAN); + expect_account("the BIP352 vectors' scan key is not ours", OUR_FINGERPRINT, + TESTNET_SPEND, NULL, VECTOR_SCAN_SECRET, true, + SP_ACCOUNT_FOREIGN_SCAN); + expect_account("a zero scan key is refused", OUR_FINGERPRINT, TESTNET_SPEND, + NULL, + "0000000000000000000000000000000000000000000000000000000000" + "000000", + true, SP_ACCOUNT_BAD_SCAN_KEY); + expect_account("a scan key equal to the group order is refused", + OUR_FINGERPRINT, TESTNET_SPEND, NULL, CURVE_ORDER, true, + SP_ACCOUNT_BAD_SCAN_KEY); + expect_account("another master key is not ours", OTHER_FINGERPRINT, + TESTNET_SPEND, NULL, REQUEST_SCAN_SECRET, true, + SP_ACCOUNT_NOT_OURS); + expect_account("another spend index is not ours", OUR_FINGERPRINT, + TESTNET_SPEND_1, NULL, REQUEST_SCAN_SECRET, true, + SP_ACCOUNT_NOT_OURS); + expect_account("a spend path on the scan branch is not ours", OUR_FINGERPRINT, + TESTNET_SCAN, NULL, REQUEST_SCAN_SECRET, true, + SP_ACCOUNT_NOT_OURS); + expect_account("another scan index is not ours", OUR_FINGERPRINT, + TESTNET_SPEND, TESTNET_SCAN_1, NULL, true, + SP_ACCOUNT_NOT_OURS); + expect_account("a scan path on the spend branch is not ours", OUR_FINGERPRINT, + TESTNET_SPEND, TESTNET_SPEND, NULL, true, SP_ACCOUNT_NOT_OURS); + expect_account("a testnet spend key on mainnet is the other network", + OUR_FINGERPRINT, TESTNET_SPEND, NULL, REQUEST_SCAN_SECRET, + false, SP_ACCOUNT_OTHER_NETWORK); + expect_account("a mainnet spend key on testnet is the other network", + OUR_FINGERPRINT, MAINNET_SPEND, TESTNET_SCAN, NULL, true, + SP_ACCOUNT_OTHER_NETWORK); +} + +static void test_account_keys(void) { + unsigned char scan_secret[SP_SECRET_LEN], scan_pubkey[SP_PUBKEY_LEN]; + struct sp_keys ours, account; + bool ok = hex_to(REQUEST_SCAN_SECRET, scan_secret, sizeof(scan_secret)) && + hex_to(REQUEST_SCAN_PUBKEY, scan_pubkey, sizeof(scan_pubkey)) && + sp_keys_derive(true, &ours); + + TEST("sp_account_keys_derive without a scan key gives our keys"); + if (ok && sp_account_keys_derive(true, NULL, &account) && + memcmp(&account, &ours, sizeof(ours)) == 0) + PASS(); + else + FAIL("keys differ"); + + TEST("sp_account_keys_derive pairs our spend key with the scan key"); + if (ok && sp_account_keys_derive(true, scan_secret, &account) && + memcmp(account.scan_secret, scan_secret, SP_SECRET_LEN) == 0 && + memcmp(account.scan_pubkey, scan_pubkey, SP_PUBKEY_LEN) == 0 && + memcmp(account.spend_secret, ours.spend_secret, SP_SECRET_LEN) == 0 && + memcmp(account.spend_pubkey, ours.spend_pubkey, SP_PUBKEY_LEN) == 0) + PASS(); + else + FAIL("account keys wrong"); + sp_keys_wipe(&ours); + sp_keys_wipe(&account); +} + +static const bipqr_request *decode_hex(const char *hex) { + unsigned char bytes[256]; + size_t len = 0; + const bipqr_request *request = NULL; + if (wally_hex_to_bytes(hex, bytes, sizeof(bytes), &len) != WALLY_OK || + bipqr_request_decode(bytes, len, &request, NULL) != BIPQR_OK) + return NULL; + return request; +} + +static sp_account_t request_account(const bipqr_sp_keys *sp, bool is_testnet) { + bool by_path = sp->scan_kind == BIPQR_SCAN_PATH; + return sp_account_classify( + sp->fingerprint, sp->spend_path.ptr, sp->spend_path.len, + by_path ? sp->scan.path.ptr : NULL, by_path ? sp->scan.path.len : 0, + by_path ? NULL : sp->scan.key, is_testnet); +} + +static void test_register_foreign_scan_request(void) { + unsigned char scan_secret[SP_SECRET_LEN]; + const bipqr_request *request = decode_hex(REGISTER_FOREIGN_SCAN_REQUEST); + const bipqr_register_descriptor *reg = + request ? &request->body.register_descriptor : NULL; + const bipqr_descriptor_body *body = reg ? reg->descriptor : NULL; + const bipqr_sp_keys *sp = body ? &body->value.sp_keys : NULL; + + TEST("the Register Descriptor request with a scan key decodes"); + if (sp && request->message_type == BIPQR_MESSAGE_REGISTER_DESCRIPTOR && + strcmp(reg->descriptor_alias, "3f82-9b") == 0 && + body->tag == BIPQR_DESCRIPTOR_SP_KEYS && + memcmp(sp->fingerprint, OUR_FINGERPRINT, 4) == 0 && + sp->spend_path.len == 5 && + memcmp(sp->spend_path.ptr, TESTNET_SPEND, sizeof(TESTNET_SPEND)) == 0 && + sp->scan_kind == BIPQR_SCAN_KEY && + hex_to(REQUEST_SCAN_SECRET, scan_secret, sizeof(scan_secret)) && + memcmp(sp->scan.key, scan_secret, SP_SECRET_LEN) == 0) + PASS(); + else + FAIL("unexpected request"); + + TEST("its keys are our spend key with a scan key not ours"); + if (sp && request_account(sp, true) == SP_ACCOUNT_FOREIGN_SCAN) + PASS(); + else + FAIL("account refused"); + bipqr_request_free(request); +} + +static void test_verify_foreign_scan_request(void) { + const bipqr_request *request = decode_hex(VERIFY_FOREIGN_SCAN_REQUEST); + const bipqr_verify_address *verify = + request ? &request->body.verify_address : NULL; + const bipqr_sp_keys *sp = + verify && verify->descriptor ? &verify->descriptor->value.sp_keys : NULL; + struct sp_keys keys; + char *address = NULL; + + TEST("the bipqr labelled scan key vector names our spend key"); + if (sp && request->message_type == BIPQR_MESSAGE_ADDRESS_VERIFICATION && + request_account(sp, true) == SP_ACCOUNT_FOREIGN_SCAN) + PASS(); + else + FAIL("account refused"); + + TEST("its label 2 address is computed with its scan key"); + if (sp && verify->derivation_path.len == 1 && + verify->derivation_path.ptr[0] == 2 && + sp_account_keys_derive(true, sp->scan.key, &keys) && + sp_account_address_alloc( + keys.scan_secret, keys.spend_pubkey, verify->derivation_path.ptr, + verify->derivation_path.len, true, &address) == SP_ADDRESS_OK && + strcmp(address, VECTOR_SCAN_OUR_SPEND_LABEL_2_TESTNET_ADDRESS) == 0) + PASS(); + else + FAIL(address ? address : "no address"); + sp_keys_wipe(&keys); + free(address); + bipqr_request_free(request); +} + +int main(void) { + test_path_on_branch(); + test_account_address(); + + TEST("sp_descriptor_alloc fails without a loaded key"); + char *descriptor = NULL; + if (!sp_descriptor_alloc(false, &descriptor) && !descriptor) + PASS(); + else + FAIL("descriptor built without a key"); + + if (!key_load_from_mnemonic(TEST_MNEMONIC, NULL, false)) { + printf("FAIL: could not load the test mnemonic\n"); + return 1; + } + test_keys(); + test_descriptor("sp_descriptor_alloc matches bwk on mainnet", false, + MAINNET_DESCRIPTOR); + test_descriptor("sp_descriptor_alloc matches bwk on testnet", true, + TESTNET_DESCRIPTOR); + test_address(); + test_descriptor_ownership(); + test_account_classify(); + test_account_keys(); + test_register_foreign_scan_request(); + test_verify_foreign_scan_request(); + key_unload(); + + printf("\n%d passed, %d failed\n", tests_passed, tests_failed); + return tests_failed ? 1 : 0; +} diff --git a/main/core/test/test_sp_psbt.c b/main/core/test/test_sp_psbt.c new file mode 100644 index 00000000..536ecaca --- /dev/null +++ b/main/core/test/test_sp_psbt.c @@ -0,0 +1,905 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bip375_fixture.h" +#include "core/dleq.h" +#include "core/key.h" +#include "core/psbt.h" +#include "core/silent_payments.h" +#include "core/sp_psbt.h" +#include "sp_fixture.h" + +// libwally keeps these input fields in psbt_fields +#define PSBT_IN_REDEEM_SCRIPT 0x04 +#define PSBT_IN_TAP_MERKLE_ROOT 0x18 + +static int tests_passed = 0; +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() \ + do { \ + printf("PASS\n"); \ + tests_passed++; \ + } while (0) +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +static const char *TEST_MNEMONIC = + "abandon abandon abandon abandon abandon abandon " + "abandon abandon abandon abandon abandon about"; + +/* BIP352 receiving vectors' scan secret, whose public key is RECIPIENT_SCAN, + * and our spend key labeled with it with m = 0 and m = 3 */ +static const char RECIPIENT_SCAN_SECRET[] = + "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"; +static const char RECIPIENT_SCAN_SPEND_LABEL_0[] = + "02e673195a3b1a0c7cdfdde5649e6e13be05d01791be238329bb58fdb3ea386f56"; +static const char RECIPIENT_SCAN_SPEND_LABEL_3[] = + "039a85d8ee2d462711a2f76c45d84243634a445caa32f2509f181101ba23eb24da"; + +static const unsigned char SCALAR_ONE[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; + +static bool hex_to(const char *hex, unsigned char *out, size_t len) { + size_t written; + return wally_hex_to_bytes(hex, out, len, &written) == WALLY_OK && + written == len; +} + +static struct wally_psbt *parse_hex(const char *hex) { + size_t len = strlen(hex) / 2, written = 0; + unsigned char *bytes = malloc(len); + struct wally_psbt *psbt = NULL; + if (!bytes || wally_hex_to_bytes(hex, bytes, len, &written) != WALLY_OK || + !psbt_parse_payload(bytes, written, &psbt)) + psbt = NULL; + free(bytes); + return psbt; +} + +static bool script_is(const struct wally_psbt *psbt, size_t index, + const char *hex) { + unsigned char expected[34]; + const struct wally_psbt_output *out = &psbt->outputs[index]; + return hex_to(hex, expected, sizeof(expected)) && out->script && + out->script_len == sizeof(expected) && + memcmp(out->script, expected, sizeof(expected)) == 0; +} + +static const struct wally_map_item *find_scan_field(const struct wally_map *map, + unsigned char type, + const char *scan_hex) { + unsigned char key[1 + SP_PUBKEY_LEN]; + size_t index = 0; + key[0] = type; + if (!hex_to(scan_hex, key + 1, SP_PUBKEY_LEN) || + wally_map_find(map, key, sizeof(key), &index) != WALLY_OK || !index) + return NULL; + return &map->items[index - 1]; +} + +static bool share_is(const struct wally_psbt *psbt, const char *scan_hex, + const char *share_hex) { + unsigned char expected[SP_PUBKEY_LEN]; + const struct wally_map_item *item = + find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, scan_hex); + return item && hex_to(share_hex, expected, sizeof(expected)) && + item->value_len == sizeof(expected) && + memcmp(item->value, expected, sizeof(expected)) == 0; +} + +static bool parse_point(const char *hex, secp256k1_pubkey *out) { + unsigned char bytes[SP_PUBKEY_LEN]; + return hex_to(hex, bytes, sizeof(bytes)) && + secp256k1_ec_pubkey_parse(wally_get_secp_context(), out, bytes, + sizeof(bytes)) == 1; +} + +static bool proof_verifies(const struct wally_psbt *psbt, + const char *input_key_hex, const char *scan_hex, + const char *share_hex) { + secp256k1_pubkey input_key, scan, share, generator; + const struct wally_map_item *proof = + find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_DLEQ, scan_hex); + return proof && proof->value_len == DLEQ_PROOF_LEN && + parse_point(input_key_hex, &input_key) && + parse_point(scan_hex, &scan) && parse_point(share_hex, &share) && + secp256k1_ec_pubkey_create(wally_get_secp_context(), &generator, + SCALAR_ONE) && + dleq_verify(&input_key, &scan, &share, proof->value, &generator, NULL); +} + +static void test_parse(void) { + unsigned char bytes[1024]; + size_t written = 0; + struct wally_psbt *strict = NULL; + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + + TEST("psbt_parse_payload accepts scriptless silent payment outputs"); + if (psbt && sp_psbt_outputs_pending(psbt) && + wally_hex_to_bytes(UNSIGNED_PSBT, bytes, sizeof(bytes), &written) == + WALLY_OK && + wally_psbt_from_bytes(bytes, written, WALLY_PSBT_PARSE_FLAG_COMPLETE, + &strict) != WALLY_OK) + PASS(); + else + FAIL("scriptless silent payment outputs rejected"); + + TEST("a scriptless output without PSBT_OUT_SP_V0_INFO is not pending"); + unsigned char info_key = PSBT_OUT_SP_V0_INFO; + if (psbt && + wally_map_remove(&psbt->outputs[0].unknowns, &info_key, 1) == WALLY_OK && + !sp_psbt_outputs_pending(psbt)) + PASS(); + else + FAIL("output without info counted as pending"); + wally_psbt_free(strict); + wally_psbt_free(psbt); +} + +static void test_complete(void) { + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + size_t flags = 1; + + TEST("sp_psbt_complete writes bwk's output scripts"); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + script_is(psbt, 0, EXPECTED_SCRIPT_0) && + script_is(psbt, 1, EXPECTED_SCRIPT_1)) + PASS(); + else + FAIL("output scripts differ from bwk"); + + TEST("sp_psbt_complete writes bwk's global ECDH shares"); + if (psbt && share_is(psbt, RECIPIENT_SCAN, RECIPIENT_SHARE) && + share_is(psbt, OUR_SCAN, OUR_SHARE)) + PASS(); + else + FAIL("global shares differ from bwk"); + + TEST("each global DLEQ proof verifies against the input key"); + if (psbt && + proof_verifies(psbt, INPUT_KEY, RECIPIENT_SCAN, RECIPIENT_SHARE) && + proof_verifies(psbt, INPUT_KEY, OUR_SCAN, OUR_SHARE)) + PASS(); + else + FAIL("DLEQ proof does not verify"); + + TEST("sp_psbt_complete freezes the transaction"); + if (psbt && wally_psbt_get_tx_modifiable_flags(psbt, &flags) == WALLY_OK && + flags == 0) + PASS(); + else + FAIL("tx_modifiable not frozen"); + + struct wally_psbt *trimmed = NULL; + unsigned char tx_modifiable = 0x06; + size_t index = 0; + TEST("sp_psbt_copy_fields keeps the BIP375 fields and a frozen " + "TX_MODIFIABLE"); + if (psbt && wally_psbt_clone_alloc(psbt, 0, &trimmed) == WALLY_OK && + wally_map_clear(&trimmed->unknowns) == WALLY_OK && + wally_map_clear(&trimmed->outputs[0].unknowns) == WALLY_OK && + sp_psbt_copy_fields(psbt, trimmed) && + share_is(trimmed, RECIPIENT_SCAN, RECIPIENT_SHARE) && + find_scan_field(&trimmed->unknowns, PSBT_GLOBAL_SP_DLEQ, OUR_SCAN) && + sp_psbt_has_outputs(trimmed) && + wally_map_find(&trimmed->unknowns, &tx_modifiable, 1, &index) == + WALLY_OK && + index && trimmed->unknowns.items[index - 1].value_len == 1 && + trimmed->unknowns.items[index - 1].value[0] == 0) + PASS(); + else + FAIL("BIP375 fields dropped"); + wally_psbt_free(trimmed); + wally_psbt_free(psbt); +} + +// `share` holds `scan_hex`, `share_hex` and the proof `map` keeps for it +static bool share_entry_is(const sp_share_t *share, const struct wally_map *map, + unsigned char proof_type, const char *scan_hex, + const char *share_hex) { + unsigned char scan[SP_PUBKEY_LEN], expected[SP_PUBKEY_LEN]; + const struct wally_map_item *proof = + find_scan_field(map, proof_type, scan_hex); + return proof && hex_to(scan_hex, scan, sizeof(scan)) && + hex_to(share_hex, expected, sizeof(expected)) && + memcmp(share->scan, scan, sizeof(scan)) == 0 && + memcmp(share->share, expected, sizeof(expected)) == 0 && + memcmp(share->proof, proof->value, DLEQ_PROOF_LEN) == 0; +} + +static bool global_share_is(const sp_share_t *share, + const struct wally_psbt *psbt, const char *scan_hex, + const char *share_hex) { + return share->global && share->input_index == 0 && + share_entry_is(share, &psbt->unknowns, PSBT_GLOBAL_SP_DLEQ, scan_hex, + share_hex); +} + +static void test_shares(void) { + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + sp_share_t *shares = NULL; + size_t count = 0; + + TEST("sp_psbt_shares_alloc fails before the shares are written"); + if (psbt && !sp_psbt_shares_alloc(psbt, false, &shares, &count) && !shares && + count == 0) + PASS(); + else + FAIL("shares read from an uncompleted PSBT"); + + TEST("sp_psbt_shares_alloc reads each scan key's global share and proof in " + "output order"); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + sp_psbt_shares_alloc(psbt, false, &shares, &count) && count == 2 && + global_share_is(&shares[0], psbt, RECIPIENT_SCAN, RECIPIENT_SHARE) && + global_share_is(&shares[1], psbt, OUR_SCAN, OUR_SHARE)) + PASS(); + else + FAIL("shares differ from the PSBT fields"); + free(shares); + shares = NULL; + + TEST("sp_psbt_shares_alloc fails when a proof is missing"); + unsigned char proof_key[1 + SP_PUBKEY_LEN] = {PSBT_GLOBAL_SP_DLEQ}; + if (psbt && hex_to(OUR_SCAN, proof_key + 1, SP_PUBKEY_LEN) && + wally_map_remove(&psbt->unknowns, proof_key, sizeof(proof_key)) == + WALLY_OK && + !sp_psbt_shares_alloc(psbt, false, &shares, &count) && !shares) + PASS(); + else + FAIL("share without its proof accepted"); + wally_psbt_free(psbt); +} + +static void expect_refusal(const char *name, struct wally_psbt *psbt, + sp_psbt_result_t expected) { + TEST(name); + if (psbt && sp_psbt_complete(&psbt, false) == expected) + PASS(); + else + FAIL(sp_psbt_result_message(expected)); + wally_psbt_free(psbt); +} + +// Another signer holds an eligible input and has not shared yet: no global +// share, every silent payment output still scriptless +static void expect_waiting(const char *name, struct wally_psbt *psbt) { + TEST(name); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_PENDING && + sp_psbt_outputs_pending(psbt) && + !find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, + RECIPIENT_SCAN)) + PASS(); + else + FAIL("not left waiting for the other signer"); + wally_psbt_free(psbt); +} + +static void test_refusals(void) { + unsigned char tweak_key = PSBT_IN_SP_TWEAK; + unsigned char info_key = PSBT_OUT_SP_V0_INFO; + unsigned char wrong_tweak[32], script[34]; + struct wally_psbt *psbt; + + expect_refusal("a foreign key hash input naming no key is refused", + parse_hex(FOREIGN_PSBT), SP_PSBT_ERR_INPUT_KEY); + + psbt = parse_hex(UNSIGNED_PSBT); + if (psbt && + wally_psbt_set_input_sighash(psbt, 0, WALLY_SIGHASH_NONE) != WALLY_OK) { + wally_psbt_free(psbt); + psbt = NULL; + } + expect_refusal("a SIGHASH_NONE input is refused", psbt, SP_PSBT_ERR_SIGHASH); + + memset(wrong_tweak, 0x12, sizeof(wrong_tweak)); + psbt = parse_hex(UNSIGNED_PSBT); + if (psbt && wally_map_replace(&psbt->inputs[0].unknowns, &tweak_key, 1, + wrong_tweak, sizeof(wrong_tweak)) != WALLY_OK) { + wally_psbt_free(psbt); + psbt = NULL; + } + expect_waiting("an input with a wrong tweak is another signer's", psbt); + + psbt = parse_hex(UNSIGNED_PSBT); + if (psbt && (!hex_to(EXPECTED_SCRIPT_1, script, sizeof(script)) || + wally_psbt_set_output_script(psbt, 0, script, sizeof(script)) != + WALLY_OK)) { + wally_psbt_free(psbt); + psbt = NULL; + } + expect_refusal("a preset script differing from the derived one is refused", + psbt, SP_PSBT_ERR_SCRIPT); + + psbt = parse_hex(UNSIGNED_PSBT); + if (psbt && wally_map_replace(&psbt->outputs[0].unknowns, &info_key, 1, + script, SP_PUBKEY_LEN) != WALLY_OK) { + wally_psbt_free(psbt); + psbt = NULL; + } + expect_refusal("a short PSBT_OUT_SP_V0_INFO is refused", psbt, + SP_PSBT_ERR_FIELD); +} + +// Completes `psbt_hex` and checks embit's script, share and proof +static void expect_completion(const char *name, const char *psbt_hex, + const char *script, const char *share, + const char *input_key) { + struct wally_psbt *psbt = parse_hex(psbt_hex); + TEST(name); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + script_is(psbt, 0, script) && share_is(psbt, RECIPIENT_SCAN, share) && + proof_verifies(psbt, input_key, RECIPIENT_SCAN, share)) + PASS(); + else + FAIL("output, share or proof differs from embit"); + wally_psbt_free(psbt); +} + +static void test_bip352_inputs(void) { + expect_completion("P2WPKH, P2TR, P2SH-P2WPKH and P2PKH keys are summed", + ALL_TYPES_PSBT, ALL_TYPES_SCRIPT, ALL_TYPES_SHARE, + ALL_TYPES_INPUT_KEY); + expect_completion("a P2WPKH input keyed on a BIP86 path is P2WPKH", + PATH_IGNORED_PSBT, PATH_IGNORED_SCRIPT, PATH_IGNORED_SHARE, + PATH_IGNORED_INPUT_KEY); + expect_completion("a NUMS input proven by its merkle root is not summed", + NUMS_PSBT, NUMS_SCRIPT, NUMS_SHARE, NUMS_INPUT_KEY); +} + +// Flips the last byte of an input field libwally keeps in psbt_fields +static bool flip_input_field(struct wally_psbt *psbt, size_t i, uint32_t type) { + const struct wally_map_item *item = + wally_map_get_integer(&psbt->inputs[i].psbt_fields, type); + if (!item || !item->value_len) + return false; + item->value[item->value_len - 1] ^= 1; + return true; +} + +static struct wally_psbt *checked(struct wally_psbt *psbt, bool mutated) { + if (psbt && !mutated) { + wally_psbt_free(psbt); + return NULL; + } + return psbt; +} + +static void test_input_refusals(void) { + struct wally_psbt *psbt = parse_hex(PATH_IGNORED_PSBT); + // The origin still names our key, the script now hashes another one + if (psbt && psbt->inputs[0].witness_utxo) + psbt->inputs[0].witness_utxo->script[2] ^= 1; + expect_refusal("a key origin our key not hashed by the script is refused", + psbt, SP_PSBT_ERR_INPUT_KEY); + + psbt = parse_hex(ALL_TYPES_PSBT); + expect_waiting("a P2TR key not reaching the output key is another signer's", + checked(psbt, psbt && flip_input_field( + psbt, 2, PSBT_IN_TAP_MERKLE_ROOT))); + + psbt = parse_hex(ALL_TYPES_PSBT); + expect_refusal( + "a redeem script not hashing to its script is refused", + checked(psbt, psbt && flip_input_field(psbt, 3, PSBT_IN_REDEEM_SCRIPT)), + SP_PSBT_ERR_INPUT); + + psbt = parse_hex(NUMS_PSBT); + expect_waiting( + "an unproven NUMS input stays eligible, and is another signer's", + checked(psbt, + psbt && flip_input_field(psbt, 1, PSBT_IN_TAP_MERKLE_ROOT))); +} + +static bool copy_global_field(const struct wally_psbt *from, + struct wally_psbt *to, unsigned char type) { + for (size_t i = 0; i < from->unknowns.num_items; i++) { + const struct wally_map_item *item = &from->unknowns.items[i]; + if (item->key_len && item->key[0] == type) + return wally_map_replace(&to->unknowns, item->key, item->key_len, + item->value, item->value_len) == WALLY_OK; + } + return false; +} + +// UNSIGNED_PSBT holding the share and proof of RECIPIENT_SCAN that a first +// completion wrote +static struct wally_psbt *with_declared_share(void) { + struct wally_psbt *completed = parse_hex(UNSIGNED_PSBT); + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + bool ok = completed && psbt && + sp_psbt_complete(&completed, false) == SP_PSBT_OK && + copy_global_field(completed, psbt, PSBT_GLOBAL_SP_ECDH_SHARE) && + copy_global_field(completed, psbt, PSBT_GLOBAL_SP_DLEQ); + wally_psbt_free(completed); + return checked(psbt, ok); +} + +static bool flip_global_field(struct wally_psbt *psbt, unsigned char type) { + for (size_t i = 0; i < psbt->unknowns.num_items; i++) { + struct wally_map_item *item = &psbt->unknowns.items[i]; + if (item->key_len && item->key[0] == type) { + item->value[item->value_len - 1] ^= 1; + return true; + } + } + return false; +} + +static void expect_untouched_refusal(const char *name, struct wally_psbt *psbt, + sp_psbt_result_t expected) { + struct wally_psbt *before = psbt; + TEST(name); + if (psbt && sp_psbt_complete(&psbt, false) == expected && psbt == before && + sp_psbt_outputs_pending(psbt)) + PASS(); + else + FAIL(sp_psbt_result_message(expected)); + wally_psbt_free(psbt); +} + +static void test_field_checks(void) { + struct wally_psbt *psbt = parse_hex(V0_SP_PSBT); + expect_refusal("silent payment fields in a PSBTv0 are refused", psbt, + SP_PSBT_ERR_PSBT); + + psbt = with_declared_share(); + const struct wally_map_item *proof = NULL; + unsigned char declared[DLEQ_PROOF_LEN]; + TEST("a declared share and proof that match ours are kept"); + proof = psbt ? find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_DLEQ, + RECIPIENT_SCAN) + : NULL; + if (proof) + memcpy(declared, proof->value, sizeof(declared)); + if (proof && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + share_is(psbt, RECIPIENT_SCAN, RECIPIENT_SHARE) && + (proof = find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_DLEQ, + RECIPIENT_SCAN)) && + memcmp(proof->value, declared, sizeof(declared)) == 0) + PASS(); + else + FAIL("declared share or proof replaced"); + wally_psbt_free(psbt); + + psbt = with_declared_share(); + expect_untouched_refusal( + "a declared share differing from ours is refused, the PSBT untouched", + checked(psbt, psbt && flip_global_field(psbt, PSBT_GLOBAL_SP_ECDH_SHARE)), + SP_PSBT_ERR_FIELD); + + psbt = with_declared_share(); + expect_untouched_refusal( + "a declared proof that does not verify is refused, the PSBT untouched", + checked(psbt, psbt && flip_global_field(psbt, PSBT_GLOBAL_SP_DLEQ)), + SP_PSBT_ERR_FIELD); +} + +static bool input_share_is(const struct wally_psbt *psbt, size_t i, + const char *scan_hex, const char *share_hex) { + unsigned char expected[SP_PUBKEY_LEN]; + const struct wally_map_item *item = find_scan_field( + &psbt->inputs[i].unknowns, PSBT_IN_SP_ECDH_SHARE, scan_hex); + return item && hex_to(share_hex, expected, sizeof(expected)) && + item->value_len == sizeof(expected) && + memcmp(item->value, expected, sizeof(expected)) == 0; +} + +static bool input_proof_verifies(const struct wally_psbt *psbt, size_t i, + const char *input_key_hex, + const char *scan_hex, const char *share_hex) { + secp256k1_pubkey input_key, scan, share, generator; + const struct wally_map_item *proof = + find_scan_field(&psbt->inputs[i].unknowns, PSBT_IN_SP_DLEQ, scan_hex); + return proof && proof->value_len == DLEQ_PROOF_LEN && + parse_point(input_key_hex, &input_key) && + parse_point(scan_hex, &scan) && parse_point(share_hex, &share) && + secp256k1_ec_pubkey_create(wally_get_secp_context(), &generator, + SCALAR_ONE) && + dleq_verify(&input_key, &scan, &share, proof->value, &generator, NULL); +} + +static bool input_entry_is(const sp_share_t *share, + const struct wally_psbt *psbt, size_t i, + const char *scan_hex, const char *share_hex) { + return !share->global && share->input_index == i && + share_entry_is(share, &psbt->inputs[i].unknowns, PSBT_IN_SP_DLEQ, + scan_hex, share_hex); +} + +// Holding input 0 of two, our per-input shares are a_0*B_scan, the global +// shares UNSIGNED_PSBT gets for the same key +static void test_first_signer(void) { + struct wally_psbt *psbt = parse_hex(TWO_SIGNER_PSBT); + sp_share_t *shares = NULL; + size_t count = 0; + + TEST("holding some inputs, sp_psbt_complete writes per-input shares and " + "waits"); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_PENDING && + input_share_is(psbt, 0, RECIPIENT_SCAN, RECIPIENT_SHARE) && + input_share_is(psbt, 0, OUR_SCAN, OUR_SHARE) && + input_proof_verifies(psbt, 0, INPUT_KEY, RECIPIENT_SCAN, + RECIPIENT_SHARE) && + input_proof_verifies(psbt, 0, INPUT_KEY, OUR_SCAN, OUR_SHARE) && + !find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, + RECIPIENT_SCAN) && + !find_scan_field(&psbt->inputs[1].unknowns, PSBT_IN_SP_ECDH_SHARE, + RECIPIENT_SCAN) && + sp_psbt_outputs_pending(psbt)) + PASS(); + else + FAIL("per-input shares missing or outputs derived"); + + TEST("sp_psbt_shares_alloc reads the per-input shares of input 0"); + if (psbt && sp_psbt_shares_alloc(psbt, false, &shares, &count) && + count == 2 && + input_entry_is(&shares[0], psbt, 0, RECIPIENT_SCAN, RECIPIENT_SHARE) && + input_entry_is(&shares[1], psbt, 0, OUR_SCAN, OUR_SHARE)) + PASS(); + else + FAIL("per-input shares not read"); + free(shares); + wally_psbt_free(psbt); +} + +static bool flip_input_unknown(struct wally_psbt *psbt, size_t i, + unsigned char type) { + for (size_t j = 0; j < psbt->inputs[i].unknowns.num_items; j++) { + struct wally_map_item *item = &psbt->inputs[i].unknowns.items[j]; + if (item->key_len && item->key[0] == type) { + item->value[item->value_len - 1] ^= 1; + return true; + } + } + return false; +} + +// The other signer's shares on input 1 complete both scan keys: the scripts +// come from the summed shares alone +static void test_second_signer(void) { + struct wally_psbt *psbt = parse_hex(TWO_SIGNER_SHARED_PSBT); + size_t flags = 1; + + TEST("the other signer's shares complete the outputs"); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + script_is(psbt, 0, TWO_SIGNER_SCRIPT_0) && + script_is(psbt, 1, TWO_SIGNER_SCRIPT_1) && + input_share_is(psbt, 0, RECIPIENT_SCAN, RECIPIENT_SHARE) && + input_share_is(psbt, 0, OUR_SCAN, OUR_SHARE) && + wally_psbt_get_tx_modifiable_flags(psbt, &flags) == WALLY_OK && + flags == 0) + PASS(); + else + FAIL("scripts differ from the BIP352 reference"); + wally_psbt_free(psbt); + + psbt = parse_hex(TWO_SIGNER_SHARED_PSBT); + expect_untouched_refusal( + "another signer's share failing its proof is refused, the PSBT untouched", + checked(psbt, psbt && flip_input_unknown(psbt, 1, PSBT_IN_SP_DLEQ)), + SP_PSBT_ERR_FIELD); + + psbt = parse_hex(TWO_SIGNER_SHARED_PSBT); + unsigned char proof_key[1 + SP_PUBKEY_LEN] = {PSBT_IN_SP_DLEQ}; + bool removed = psbt && hex_to(OUR_SCAN, proof_key + 1, SP_PUBKEY_LEN) && + wally_map_remove(&psbt->inputs[1].unknowns, proof_key, + sizeof(proof_key)) == WALLY_OK; + expect_untouched_refusal( + "another signer's share without its proof is refused, the PSBT " + "untouched", + checked(psbt, removed), SP_PSBT_ERR_FIELD); +} + +// The pending PSBT serializes without PSBT_OUT_SCRIPT on its scriptless +// outputs and parses back with its shares +static void test_serialize_pending(void) { + struct wally_psbt *psbt = parse_hex(TWO_SIGNER_PSBT), *back = NULL; + uint8_t *bytes = NULL; + size_t len = 0; + + TEST("sp_psbt_serialize_alloc writes a pending PSBT BIP375 parses back"); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_PENDING && + sp_psbt_serialize_alloc(psbt, &bytes, &len) && + psbt_parse_payload(bytes, len, &back) && sp_psbt_outputs_pending(back) && + !back->outputs[0].script && !back->outputs[1].script && + input_share_is(back, 0, RECIPIENT_SCAN, RECIPIENT_SHARE) && + input_share_is(back, 0, OUR_SCAN, OUR_SHARE)) + PASS(); + else + FAIL("pending PSBT does not round trip"); + free(bytes); + wally_psbt_free(back); + wally_psbt_free(psbt); + + TEST("sp_psbt_serialize_alloc writes a complete PSBT as libwally does"); + psbt = parse_hex(UNSIGNED_PSBT); + bytes = NULL; + size_t wally_len = 0, written = 0; + unsigned char *wally_bytes = NULL; + bool same = psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + sp_psbt_serialize_alloc(psbt, &bytes, &len) && + wally_psbt_get_length(psbt, 0, &wally_len) == WALLY_OK && + (wally_bytes = malloc(wally_len)) != NULL && + wally_psbt_to_bytes(psbt, 0, wally_bytes, wally_len, &written) == + WALLY_OK && + written == len && memcmp(bytes, wally_bytes, len) == 0; + if (same) + PASS(); + else + FAIL("serialization differs from libwally's"); + free(wally_bytes); + free(bytes); + wally_psbt_free(psbt); +} + +// The BIP375 vectors' P2WPKH inputs pay a key hash other than their +// PSBT_IN_BIP32_DERIVATION key's, a key BIP352 never sums: pay that key's hash, +// as a spendable input does +static struct wally_psbt *parse_vector(const char *hex) { + struct wally_psbt *psbt = parse_hex(hex); + for (size_t i = 0; psbt && i < psbt->num_inputs; i++) { + struct wally_psbt_input *in = &psbt->inputs[i]; + struct wally_tx_output *utxo = in->witness_utxo; + size_t type = 0, written = 0; + if (!utxo || !in->keypaths.num_items || + wally_scriptpubkey_get_type(utxo->script, utxo->script_len, &type) != + WALLY_OK || + type != WALLY_SCRIPT_TYPE_P2WPKH) + continue; + if (wally_witness_program_from_bytes( + in->keypaths.items[0].key, in->keypaths.items[0].key_len, + WALLY_SCRIPT_HASH160, utxo->script, utxo->script_len, + &written) != WALLY_OK || + written != utxo->script_len) { + wally_psbt_free(psbt); + psbt = NULL; + } + } + return psbt; +} + +static bool scripts_match(const struct wally_psbt *psbt, + const bip375_derivation_t *vector) { + for (size_t i = 0; i < psbt->num_outputs && i < BIP375_MAX_OUTPUTS; i++) + if (vector->scripts[i] && !script_is(psbt, i, vector->scripts[i])) + return false; + return true; +} + +// Every "can finalize" vector, its silent payment scripts left out: they are +// derived again from its shares, which other signers made +static void test_bip375_derivations(void) { + size_t n = sizeof(BIP375_DERIVATIONS) / sizeof(BIP375_DERIVATIONS[0]); + for (size_t i = 0; i < n; i++) { + struct wally_psbt *psbt = parse_vector(BIP375_DERIVATIONS[i].psbt); + TEST(BIP375_DERIVATIONS[i].name); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + scripts_match(psbt, &BIP375_DERIVATIONS[i])) + PASS(); + else + FAIL("scripts differ from the vector's"); + wally_psbt_free(psbt); + } + expect_refusal("a foreign P2WPKH input whose script does not hash its key " + "is refused", + parse_hex(BIP375_DERIVATIONS[1].psbt), SP_PSBT_ERR_INPUT_KEY); +} + +static int bip375_result(const char *hex) { + struct wally_psbt *psbt = parse_vector(hex); + int result; + if (!psbt) + return BIP375_PARSE_REFUSED; + result = sp_psbt_complete(&psbt, false); + wally_psbt_free(psbt); + return result; +} + +// Every other vector, in progress or invalid, gives its result +static void test_bip375_results(void) { + size_t n = sizeof(BIP375_RESULTS) / sizeof(BIP375_RESULTS[0]); + for (size_t i = 0; i < n; i++) { + TEST(BIP375_RESULTS[i].name); + if (bip375_result(BIP375_RESULTS[i].psbt) == BIP375_RESULTS[i].result) + PASS(); + else + FAIL("unexpected result"); + } +} + +static void test_ownership(void) { + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + + TEST("sp_psbt_input_is_ours recognizes our tweaked spend key"); + if (psbt && sp_psbt_input_is_ours(psbt, 0, false) && + !sp_psbt_input_is_ours(psbt, 0, true)) + PASS(); + else + FAIL("input ownership wrong"); + + TEST("sp_psbt_output_ownership spots only our m=0 change output"); + if (psbt && + sp_psbt_output_ownership(psbt, 1, NULL, false) == SP_OUTPUT_CHANGE && + sp_psbt_output_ownership(psbt, 0, NULL, false) == SP_OUTPUT_FOREIGN && + sp_psbt_output_ownership(psbt, 1, NULL, true) == SP_OUTPUT_FOREIGN) + PASS(); + else + FAIL("change detection wrong"); + wally_psbt_free(psbt); +} + +// Ownership of output 1 of UNSIGNED_PSBT once it pays `scan_hex` and +// `spend_hex`, with PSBT_OUT_SP_V0_LABEL `label`, or none when it is NULL, +// for our spend key's account with `scan_secret_hex`, ours when NULL +static sp_output_ownership_t ownership_of(const char *scan_hex, + const char *spend_hex, + const uint32_t *label, + const char *scan_secret_hex) { + unsigned char scan_secret[SP_SECRET_LEN]; + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + unsigned char info_key = PSBT_OUT_SP_V0_INFO, + label_key = PSBT_OUT_SP_V0_LABEL; + unsigned char info[2 * SP_PUBKEY_LEN], label_bytes[sizeof(uint32_t)]; + sp_output_ownership_t ownership = SP_OUTPUT_FOREIGN; + struct wally_map *unknowns; + bool ok; + + if (!psbt) + return SP_OUTPUT_FOREIGN; + unknowns = &psbt->outputs[1].unknowns; + ok = hex_to(scan_hex, info, SP_PUBKEY_LEN) && + hex_to(spend_hex, info + SP_PUBKEY_LEN, SP_PUBKEY_LEN) && + wally_map_replace(unknowns, &info_key, 1, info, sizeof(info)) == + WALLY_OK && + wally_map_remove(unknowns, &label_key, 1) == WALLY_OK; + if (ok && label) { + for (size_t i = 0; i < sizeof(label_bytes); i++) + label_bytes[i] = (unsigned char)(*label >> (8 * i)); + ok = wally_map_replace(unknowns, &label_key, 1, label_bytes, + sizeof(label_bytes)) == WALLY_OK; + } + if (ok && scan_secret_hex) + ok = hex_to(scan_secret_hex, scan_secret, sizeof(scan_secret)); + if (ok) + ownership = sp_psbt_output_ownership( + psbt, 1, scan_secret_hex ? scan_secret : NULL, false); + wally_psbt_free(psbt); + return ownership; +} + +static void expect_ownership(const char *name, const char *scan_hex, + const char *spend_hex, const uint32_t *label, + const char *scan_secret_hex, + sp_output_ownership_t expected) { + TEST(name); + if (ownership_of(scan_hex, spend_hex, label, scan_secret_hex) == expected) + PASS(); + else + FAIL("output ownership wrong"); +} + +static void test_labels(void) { + const uint32_t change = 0, three = 3; + + expect_ownership("label 0 on the m=0 key is change", OUR_SCAN, + OUR_SPEND_LABEL_0, &change, NULL, SP_OUTPUT_CHANGE); + expect_ownership("label 3 on the m=3 key is a self-transfer", OUR_SCAN, + OUR_SPEND_LABEL_3, &three, NULL, SP_OUTPUT_SELF); + expect_ownership("no label on the unlabeled key is a self-transfer", OUR_SCAN, + OUR_SPEND, NULL, NULL, SP_OUTPUT_SELF); + expect_ownership("no label on the m=0 key is change", OUR_SCAN, + OUR_SPEND_LABEL_0, NULL, NULL, SP_OUTPUT_CHANGE); + expect_ownership("label 3 on the m=0 key is not ours", OUR_SCAN, + OUR_SPEND_LABEL_0, &three, NULL, SP_OUTPUT_FOREIGN); + expect_ownership("a foreign scan key with our m=0 key is not ours", + RECIPIENT_SCAN, OUR_SPEND_LABEL_0, &change, NULL, + SP_OUTPUT_FOREIGN); + expect_ownership("our account does not take the other scan key's change", + RECIPIENT_SCAN, RECIPIENT_SCAN_SPEND_LABEL_0, NULL, NULL, + SP_OUTPUT_FOREIGN); + expect_ownership("label 0 with the account's scan key is change", + RECIPIENT_SCAN, RECIPIENT_SCAN_SPEND_LABEL_0, &change, + RECIPIENT_SCAN_SECRET, SP_OUTPUT_CHANGE); + expect_ownership("no label with the account's scan key is change", + RECIPIENT_SCAN, RECIPIENT_SCAN_SPEND_LABEL_0, NULL, + RECIPIENT_SCAN_SECRET, SP_OUTPUT_CHANGE); + expect_ownership("label 3 with the account's scan key is a self-transfer", + RECIPIENT_SCAN, RECIPIENT_SCAN_SPEND_LABEL_3, &three, + RECIPIENT_SCAN_SECRET, SP_OUTPUT_SELF); + expect_ownership("our unlabeled key with the account's scan key is ours", + RECIPIENT_SCAN, OUR_SPEND, NULL, RECIPIENT_SCAN_SECRET, + SP_OUTPUT_SELF); + expect_ownership("the account does not take our scan key's change", OUR_SCAN, + OUR_SPEND_LABEL_0, &change, RECIPIENT_SCAN_SECRET, + SP_OUTPUT_FOREIGN); +} + +static bool signature_verifies(struct wally_psbt *psbt, size_t i) { + unsigned char key_bytes[SP_PUBKEY_LEN], hash[32], sig[64]; + struct wally_tx *tx = NULL; + secp256k1_xonly_pubkey key; + size_t written = 0; + bool ok = + hex_to(INPUT_KEY, key_bytes, sizeof(key_bytes)) && + secp256k1_xonly_pubkey_parse(wally_get_secp_context(), &key, + key_bytes + 1) && + wally_psbt_get_input_taproot_signature(psbt, i, sig, sizeof(sig), + &written) == WALLY_OK && + written == sizeof(sig) && + wally_psbt_extract(psbt, WALLY_PSBT_EXTRACT_NON_FINAL, &tx) == WALLY_OK && + wally_psbt_get_input_signature_hash(psbt, i, tx, NULL, 0, 0, hash, + sizeof(hash)) == WALLY_OK && + secp256k1_schnorrsig_verify(wally_get_secp_context(), sig, hash, + sizeof(hash), &key); + wally_tx_free(tx); + return ok; +} + +static void test_sign(void) { + struct wally_psbt *psbt = parse_hex(UNSIGNED_PSBT); + TEST("sp_psbt_sign_input makes a key path signature of the output key"); + if (psbt && sp_psbt_complete(&psbt, false) == SP_PSBT_OK && + sp_psbt_sign_input(psbt, 0, false) && signature_verifies(psbt, 0)) + PASS(); + else + FAIL("no valid signature"); + wally_psbt_free(psbt); + + psbt = parse_hex(FOREIGN_PSBT); + TEST("sp_psbt_sign_input refuses an input that is not ours"); + size_t written = 0; + if (psbt && !sp_psbt_sign_input(psbt, 1, false) && + wally_psbt_get_input_taproot_signature_len(psbt, 1, &written) == + WALLY_OK && + written == 0) + PASS(); + else + FAIL("signed a foreign input"); + wally_psbt_free(psbt); +} + +int main(void) { + if (!key_load_from_mnemonic(TEST_MNEMONIC, NULL, false)) { + printf("FAIL: could not load the test mnemonic\n"); + return 1; + } + test_parse(); + test_complete(); + test_shares(); + test_refusals(); + test_bip352_inputs(); + test_input_refusals(); + test_field_checks(); + test_first_signer(); + test_second_signer(); + test_serialize_pending(); + test_bip375_derivations(); + test_bip375_results(); + test_ownership(); + test_labels(); + test_sign(); + key_unload(); + + printf("\n%d passed, %d failed\n", tests_passed, tests_failed); + return tests_failed ? 1 : 0; +} 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/core/test/test_storage.c b/main/core/test/test_storage.c index 33727d7c..59d50f50 100644 --- a/main/core/test/test_storage.c +++ b/main/core/test/test_storage.c @@ -446,8 +446,14 @@ static void test_descriptor_path(void) { out, sizeof(out)); check("path: sd bip138", strcmp(out, "/sdcard/kern/descriptors/My_Wallet.bip138") == 0); + storage_descriptor_path(STORAGE_FLASH, "0123456789abcdef", + STORAGE_DESCRIPTOR_SP_ACCOUNT, out, sizeof(out)); + check("path: flash silent payment account", + strcmp(out, "/spiffs/d_0123456789abcdef.spa") == 0); check("format: by extension", storage_descriptor_format("d_x.bip138") == STORAGE_DESCRIPTOR_BIP138 && + storage_descriptor_format("d_x.spa") == + STORAGE_DESCRIPTOR_SP_ACCOUNT && storage_descriptor_format("x.bip138.txt") == STORAGE_DESCRIPTOR_BIP138 && storage_descriptor_format("x.kef") == STORAGE_DESCRIPTOR_KEF && diff --git a/main/core/wallet.h b/main/core/wallet.h index d6b4f832..94cd3dcc 100644 --- a/main/core/wallet.h +++ b/main/core/wallet.h @@ -26,9 +26,10 @@ struct wally_map; /* Parse an output descriptor with Kern's standard flags. Identical to * wally_descriptor_parse() except the recursion depth is capped at - * KERN_DESCRIPTOR_MAX_DEPTH. Returns the libwally result code (WALLY_OK on - * success); on success *output owns the descriptor (free with - * wally_descriptor_free). */ + * KERN_DESCRIPTOR_MAX_DEPTH and a musig() in a tapscript leaf is first + * rewritten into the key it stands for (musig_leaves.h). Returns the libwally + * result code (WALLY_OK on success); on success *output owns the descriptor + * (free with wally_descriptor_free). */ KERN_WARN_UNUSED_RESULT int wallet_descriptor_parse(const char *descriptor, const struct wally_map *vars_in, uint32_t network, struct wally_descriptor **output); 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..31cc8d00 --- /dev/null +++ b/main/pages/bip_flow/bip_flow.c @@ -0,0 +1,1784 @@ +#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/musig_psbt.h" +#include "../../core/nonce_cache.h" +#include "../../core/psbt.h" +#include "../../core/registry.h" +#include "../../core/settings.h" +#include "../../core/silent_payments.h" +#include "../../core/sp_psbt.h" +#include "../../core/storage.h" +#include "../../core/wallet.h" +#include "../../qr/encoder.h" +#include "../../qr/parser.h" +#include "../../qr/viewer.h" +#include "../../ui/address_label.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 + +#define KERN_CAPABILITIES \ + (BIPQR_CAPABILITY_BIP380_DESCRIPTORS | \ + BIPQR_CAPABILITY_BIP388_WALLET_POLICIES | \ + BIPQR_CAPABILITY_MINISCRIPT_SEGWIT_V0 | \ + BIPQR_CAPABILITY_MINISCRIPT_TAPROOT | \ + BIPQR_CAPABILITY_SILENT_PAYMENT_SENDS | \ + BIPQR_CAPABILITY_SILENT_PAYMENT_ACCOUNTS | \ + BIPQR_CAPABILITY_UNREGISTER_DESCRIPTOR | BIPQR_CAPABILITY_MUSIG2 | \ + BIPQR_CAPABILITY_NONCE_CACHE) + +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(); + registry_sp_clear_named_scan_keys(); + 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); + // A Get Keys response can hold a private key + secure_memzero(encoded.ptr, encoded.len); + 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 bool private_key_to_wire(const bipqr_path *path, + bipqr_extended_key *out) { + struct ext_key *key = NULL; + if (!key_get_derived_key_components(path->ptr, path->len, &key)) + return false; + bool ok = bip32_key_serialize(key, BIP32_FLAG_KEY_PRIVATE, out->bytes, + sizeof(out->bytes)) == WALLY_OK; + bip32_key_free(key); + 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]; + bool ok = key->kind == BIPQR_KEY_PRIVATE + ? private_key_to_wire(&key->derivation_path, &keys[i]) + : public_key_to_wire(&key->derivation_path, &keys[i]); + if (!ok) { + 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; +} + +// Only the BIP352 scan key leaves the device, so a wallet can scan +static bool get_keys_private_allowed(const bipqr_key_request_list *keys) { + for (size_t i = 0; i < keys->len; i++) { + const bipqr_path *path = &keys->ptr[i].derivation_path; + if (keys->ptr[i].kind == BIPQR_KEY_PRIVATE && + !sp_path_on_branch(path->ptr, path->len, wallet_is_testnet(), + SP_SCAN_BRANCH)) + return false; + } + return true; +} + +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; + } + if (!get_keys_private_allowed(&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); + off = append_key_request_paths(msg, sizeof(msg), off, &req->keys); + if (get_keys_has_private(&req->keys)) + appendf(msg, sizeof(msg), off, + "\n\nIncludes the scan private key: whoever holds it sees every " + "payment this account receives, but cannot spend them."); + 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, or our silent payment account, always stored +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); + bool sp_account = registry_sp_alias_exists(alias); + bipqr_response response; + fill_response_header(&response); + response.body.registration.descriptor_alias = alias; + response.body.registration.registered = entry || sp_account; + response.body.registration.stored = (entry && entry->persisted) || sp_account; + 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))) || + registry_sp_alias_exists(alias)) { + 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); +} + +static void register_sp_account(const bipqr_register_descriptor *req); + +// 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; + } + if (req->descriptor->tag == BIPQR_DESCRIPTOR_SP_KEYS) { + register_sp_account(req); + 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; +} + +// Whose account the request's silent payment keys are +static sp_account_t request_sp_account(const bipqr_sp_keys *sp) { + bool scan_by_path = sp->scan_kind == BIPQR_SCAN_PATH; + return sp_account_classify( + sp->fingerprint, sp->spend_path.ptr, sp->spend_path.len, + scan_by_path ? sp->scan.path.ptr : NULL, + scan_by_path ? sp->scan.path.len : 0, scan_by_path ? NULL : sp->scan.key, + wallet_is_testnet()); +} + +// The scan key of an account whose scan key is not ours, else NULL +static const unsigned char *scan_key_not_ours(const bipqr_sp_keys *sp, + sp_account_t account) { + return account == SP_ACCOUNT_FOREIGN_SCAN ? sp->scan.key : NULL; +} + +// True for an account of our spend key, else the error is answered +static bool sp_account_ok(sp_account_t account) { + switch (account) { + case SP_ACCOUNT_OURS: + case SP_ACCOUNT_FOREIGN_SCAN: + return true; + case SP_ACCOUNT_OTHER_NETWORK: + show_error_response(BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH, + "Silent payment account is for another network"); + return false; + case SP_ACCOUNT_NOT_OURS: + show_error_response(BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED, + "Not this device's silent payment account"); + return false; + case SP_ACCOUNT_BAD_SCAN_KEY: + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Invalid scan key"); + return false; + case SP_ACCOUNT_ERR_KEYS: + default: + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Key failed"); + return false; + } +} + +static void sp_register_confirm_cb(bool confirmed, void *user_data) { + (void)user_data; + if (!confirmed) { + show_error_response(BIPQR_RESPONSE_ERROR_USER_DECLINED, "Declined"); + return; + } + const bipqr_register_descriptor *req = &ctx.request->body.register_descriptor; + const bipqr_sp_keys *sp = &req->descriptor->value.sp_keys; + if (!registry_add_sp_alias(req->descriptor_alias, + scan_key_not_ours(sp, request_sp_account(sp)))) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, + "Storing the registration failed"); + return; + } + answer_registration(); +} + +// Registers the request's alias for our silent payment spend key with our +// scan key or the one the request gives, so later requests may name the +// account by its alias alone +static void register_sp_account(const bipqr_register_descriptor *req) { + const bipqr_sp_keys *sp = &req->descriptor->value.sp_keys; + const char *alias = req->descriptor_alias; + sp_account_t account = request_sp_account(sp); + if (!sp_account_ok(account)) + return; + if (registry_find_by_id(alias) || registry_sp_alias_exists(alias)) { + 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; + } + if (registry_sp_alias_count() >= REGISTRY_MAX_ENTRIES) { + show_error_response(BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED, + "No room for another silent payment account"); + return; + } + char msg[128]; + snprintf( + msg, sizeof(msg), "Register silent payment keys?\n\nAlias: %s%s", alias, + scan_key_not_ours(sp, account) ? "\nScan key: external, not this device's" + : ""); + dialog_show_confirm(msg, sp_register_confirm_cb, NULL, DIALOG_STYLE_OVERLAY); +} + +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 = + address_label_create(content, pending_verified_address); + 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)); + + 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 verify_sp_address_with(const bipqr_verify_address *req, + const unsigned char *scan_secret, + const unsigned char *spend_pubkey) { + char *address = NULL; + switch (sp_account_address_alloc( + scan_secret, spend_pubkey, req->derivation_path.ptr, + req->derivation_path.len, wallet_is_testnet(), &address)) { + case SP_ADDRESS_OK: + break; + case SP_ADDRESS_ERR_LABEL: + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Label must be one step m >= 1"); + return; + case SP_ADDRESS_ERR_KEY: + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Invalid scan key"); + return; + case SP_ADDRESS_ERR_ALLOC: + default: + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Address failed"); + return; + } + if (req->address && strcasecmp(req->address, address) != 0) { + free(address); + show_error_response(BIPQR_RESPONSE_ERROR_ADDRESS_MISMATCH, + "Address mismatch"); + return; + } + char caption[sizeof(pending_verify_caption)]; + if (req->derivation_path.len == 1) + snprintf(caption, sizeof(caption), "%s label %" PRIu32, + req->descriptor_alias, req->derivation_path.ptr[0]); + else + snprintf(caption, sizeof(caption), "%s base address", + req->descriptor_alias); + show_verified_address(address, "bitcoin:?sp=", caption); +} + +// An address with the HRP of the other network or of regtest +static bool sp_address_on_other_network(const char *address) { + const char *other = wallet_is_testnet() ? "sp1" : "tsp1"; + return strncasecmp(address, other, strlen(other)) == 0 || + strncasecmp(address, "sprt1", strlen("sprt1")) == 0; +} + +// The address of our spend key with our scan key, or with `scan_key` when +// not NULL +static void verify_own_sp_address(const bipqr_verify_address *req, + const unsigned char *scan_key) { + if (req->address && sp_address_on_other_network(req->address)) { + show_error_response(BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH, + "Address is for another network"); + return; + } + struct sp_keys keys; + if (!sp_account_keys_derive(wallet_is_testnet(), scan_key, &keys)) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Key failed"); + return; + } + verify_sp_address_with(req, keys.scan_secret, keys.spend_pubkey); + sp_keys_wipe(&keys); +} + +// The spend key must be ours, the scan key ours or the one the request gives +static void verify_sp_address(const bipqr_verify_address *req) { + const bipqr_sp_keys *sp = &req->descriptor->value.sp_keys; + sp_account_t account = request_sp_account(sp); + if (sp_account_ok(account)) + verify_own_sp_address(req, scan_key_not_ours(sp, account)); +} + +// A registered alias names what it was registered for, whatever the body +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; + } + bool sp_body = + req->descriptor && req->descriptor->tag == BIPQR_DESCRIPTOR_SP_KEYS; + if (registry_sp_alias_exists(req->descriptor_alias)) + verify_own_sp_address(req, + registry_sp_alias_scan_key(req->descriptor_alias)); + else if (sp_body && !registry_find_by_id(req->descriptor_alias)) + verify_sp_address(req); + else + 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; +} + +#define MUSIG_KEY_LEN (2 * BIPQR_PUBLIC_KEY_LEN) +#define MUSIG_LEAF_KEY_LEN (MUSIG_KEY_LEN + BIPQR_TAP_LEAF_HASH_LEN) + +/* The BIP-373 key participant | aggregate [| leaf_hash] of a MuSig2 entry. */ +static void musig_entry_key(const struct wally_map_item *item, + uint8_t *participant, uint8_t *aggregate, + uint8_t *has_leaf_hash, uint8_t *leaf_hash) { + memcpy(participant, item->key, BIPQR_PUBLIC_KEY_LEN); + memcpy(aggregate, item->key + BIPQR_PUBLIC_KEY_LEN, BIPQR_PUBLIC_KEY_LEN); + *has_leaf_hash = item->key_len == MUSIG_LEAF_KEY_LEN; + if (*has_leaf_hash) + memcpy(leaf_hash, item->key + MUSIG_KEY_LEN, BIPQR_TAP_LEAF_HASH_LEN); +} + +/* A PSBT_IN_MUSIG2_PUB_NONCE entry. */ +static bool musig_pub_nonce_entry(const struct wally_map_item *item, + bipqr_signature *sig) { + bipqr_musig_pub_nonce *nonce = &sig->value.musig_pub_nonce; + if (item->value_len != sizeof(nonce->nonce)) + return false; + musig_entry_key(item, nonce->participant, nonce->aggregate, + &nonce->has_leaf_hash, nonce->leaf_hash); + memcpy(nonce->nonce, item->value, sizeof(nonce->nonce)); + return true; +} + +/* A PSBT_IN_MUSIG2_PARTIAL_SIG entry. */ +static bool musig_partial_sig_entry(const struct wally_map_item *item, + bipqr_signature *sig) { + bipqr_musig_partial_sig *partial_sig = &sig->value.musig_partial_sig; + if (item->value_len != sizeof(partial_sig->signature)) + return false; + musig_entry_key(item, partial_sig->participant, partial_sig->aggregate, + &partial_sig->has_leaf_hash, partial_sig->leaf_hash); + memcpy(partial_sig->signature, item->value, sizeof(partial_sig->signature)); + return true; +} + +/* The entries of `map` whose participant is ours, as `kind` signatures. */ +static bool append_musig_entries(const struct wally_psbt *psbt, + size_t input_index, + const struct wally_map *map, uint8_t kind, + bipqr_signature **signatures, size_t *len, + size_t *cap) { + for (size_t j = 0; j < map->num_items; j++) { + const struct wally_map_item *item = &map->items[j]; + if ((item->key_len != MUSIG_KEY_LEN && + item->key_len != MUSIG_LEAF_KEY_LEN) || + !musig_psbt_is_own_participant(psbt, input_index, item->key)) + continue; + bipqr_signature sig = {.input_index = (uint32_t)input_index, .kind = kind}; + bool filled = kind == BIPQR_SIGNATURE_MUSIG_PUB_NONCE + ? musig_pub_nonce_entry(item, &sig) + : musig_partial_sig_entry(item, &sig); + if (!filled || !append_signature(signatures, len, cap, &sig)) + return false; + } + 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; + } + } + + if (!append_musig_entries(psbt, input_index, &input->musig2_pubnonces, + BIPQR_SIGNATURE_MUSIG_PUB_NONCE, &signatures, + &len, &cap) || + !append_musig_entries(psbt, input_index, &input->musig2_partial_sigs, + BIPQR_SIGNATURE_MUSIG_PARTIAL_SIG, &signatures, + &len, &cap)) { + free_signature_list(signatures, len); + return false; + } + } + + *signatures_out = signatures; + *len_out = len; + return true; +} + +// The ECDH shares and DLEQ proofs Kern contributed: global when it holds +// every eligible input, else one per eligible input it holds +static bool append_sp_shares(const struct wally_psbt *psbt, + bipqr_signature **signatures, size_t *len, + size_t *cap) { + sp_share_t *shares = NULL; + size_t count = 0; + if (!sp_psbt_shares_alloc(psbt, wallet_is_testnet(), &shares, &count)) + return false; + bool ok = true; + for (size_t i = 0; ok && i < count; i++) { + uint32_t input_index = (uint32_t)shares[i].input_index; + bipqr_signature share = {.input_index = input_index, + .kind = BIPQR_SIGNATURE_SP_ECDH_SHARE}; + share.value.sp_ecdh_share.global = shares[i].global; + memcpy(share.value.sp_ecdh_share.scan_key, shares[i].scan, SP_PUBKEY_LEN); + memcpy(share.value.sp_ecdh_share.share, shares[i].share, SP_PUBKEY_LEN); + bipqr_signature proof = {.input_index = input_index, + .kind = BIPQR_SIGNATURE_SP_DLEQ_PROOF}; + proof.value.sp_dleq_proof.global = shares[i].global; + memcpy(proof.value.sp_dleq_proof.scan_key, shares[i].scan, SP_PUBKEY_LEN); + memcpy(proof.value.sp_dleq_proof.proof, shares[i].proof, + BIPQR_DLEQ_PROOF_LEN); + ok = append_signature(signatures, len, cap, &share) && + append_signature(signatures, len, cap, &proof); + } + free(shares); + return ok; +} + +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; + } + // While another signer owes a share there is no signature, only shares + size_t cap = len; + if (sp_psbt_has_outputs(psbt) && + !append_sp_shares(psbt, &signatures, &len, &cap)) { + free_signature_list(signatures, len); + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, + "Silent payment share 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 = + sp_psbt_serialize_alloc(export_psbt, &signed_bytes, &signed_len); + 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); +} + +// Whose account an sp() descriptor is: ours, on our network or the other one, +// or not ours +static sp_account_t sp_descriptor_account(const char *descriptor) { + bool testnet = wallet_is_testnet(); + if (sp_descriptor_is_ours(descriptor, testnet)) + return SP_ACCOUNT_OURS; + if (sp_descriptor_is_ours(descriptor, !testnet)) + return SP_ACCOUNT_OTHER_NETWORK; + return SP_ACCOUNT_NOT_OURS; +} + +// True for an account of our spend key, whose scan key, when not ours, the +// review then pairs with our spend key, else the error is answered +static bool sign_sp_account_ok(const bipqr_sp_keys *sp) { + sp_account_t account = request_sp_account(sp); + if (!sp_account_ok(account)) + return false; + const unsigned char *scan_key = scan_key_not_ours(sp, account); + if (scan_key && !registry_sp_name_scan_key(scan_key)) { + show_error_response(BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED, + "Too many silent payment accounts"); + return false; + } + return true; +} + +// 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; + // A registered alias names what it was registered for, whatever the body + if (registry_sp_alias_exists(descriptor->alias)) + return true; + if (body && body->tag == BIPQR_DESCRIPTOR_SP_KEYS && + !registry_find_by_id(descriptor->alias)) + return sign_sp_account_ok(&body->value.sp_keys); + char *descriptor_str = request_descriptor_alloc(body); + // An sp() descriptor carries our scan secret and is never registered + if (sp_descriptor_is_sp(descriptor_str)) { + sp_account_t account = sp_descriptor_account(descriptor_str); + SECURE_FREE_STRING(descriptor_str); + return sp_account_ok(account); + } + free(descriptor_str); + const registry_entry_t *entry = NULL; + uint8_t error = resolve_descriptor(descriptor->alias, body, &entry); + if (error) + show_descriptor_error(error); + return !error; +} + +/* A MuSig2 session or step refused before the user is asked. */ +static bool refuse_musig_request(const bipqr_sign *req) { + switch (musig_psbt_check_request(req->psbt.ptr, req->psbt.len, + wallet_is_testnet())) { + case MUSIG_PSBT_OK: + return false; + case MUSIG_PSBT_ERR_SESSION: + show_error_response(BIPQR_RESPONSE_ERROR_MUSIG_SESSION, + "MuSig2 session missing, consumed or mismatched"); + return true; + case MUSIG_PSBT_ERR_NOTHING: + show_error_response(BIPQR_RESPONSE_ERROR_NOTHING_TO_SIGN, + "Waiting for another participant's MuSig2 nonce"); + return true; + case MUSIG_PSBT_ERR_INVALID: + show_error_response(BIPQR_RESPONSE_ERROR_INVALID_PSBT, + "Invalid MuSig2 fields"); + return true; + case MUSIG_PSBT_ERR_INTERNAL: + default: + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "MuSig2 check failed"); + return true; + } +} + +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_musig_request(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); +} + +/* The optional DESCRIPTOR names a descriptor whose musig() has our key at the + * request's path as a participant. */ +static bool prepare_descriptor_ok(const bipqr_prepare_nonces *req) { + const bipqr_descriptor_body *body = req->descriptor->body; + if (body && body->tag == BIPQR_DESCRIPTOR_SP_KEYS) { + show_descriptor_error(BIPQR_RESPONSE_ERROR_UNSUPPORTED_DESCRIPTOR_FORM); + return false; + } + // Our silent payment account holds no MuSig2 key + if (registry_sp_alias_exists(req->descriptor->alias)) { + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Not a MuSig2 participant key of the descriptor"); + return false; + } + const registry_entry_t *entry = NULL; + uint8_t error = + resolve_descriptor(req->descriptor->alias, req->descriptor->body, &entry); + if (error) { + show_descriptor_error(error); + return false; + } + if (!musig_psbt_is_participant_path(entry->desc, req->derivation_path.ptr, + req->derivation_path.len)) { + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Not a MuSig2 participant key of the descriptor"); + return false; + } + return true; +} + +static void show_issue_error(nonce_cache_result_t result) { + switch (result) { + case NONCE_CACHE_ERR_SESSION: + show_error_response(BIPQR_RESPONSE_ERROR_MUSIG_SESSION, + "Nonce session missing or mismatched"); + break; + case NONCE_CACHE_ERR_INVALID: + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Invalid nonce request"); + break; + case NONCE_CACHE_OK: + case NONCE_CACHE_ERR_INTERNAL: + default: + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Nonce issuance failed"); + break; + } +} + +static void handle_prepare_nonces(void) { + const bipqr_prepare_nonces *req = &ctx.request->body.prepare_nonces; + if (req->descriptor && !prepare_descriptor_ok(req)) + return; + bnc_issuance issuance = { + .has_session_ref = req->has_session_ref, + .inputs = req->max_inputs, + .start = req->start, + .end = req->has_end ? req->end : req->start, + }; + memcpy(issuance.session_id, req->session_id, sizeof(issuance.session_id)); + memcpy(issuance.session_ref, req->session_ref, sizeof(issuance.session_ref)); + + /* The codec rejects an empty input count and a reversed range */ + size_t count = (size_t)(issuance.end - issuance.start) + 1; + if (count > SIZE_MAX / sizeof(bipqr_pub_nonce) / issuance.inputs) { + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Too many nonces"); + return; + } + count *= issuance.inputs; + bipqr_pub_nonce *nonces = calloc(count, sizeof(*nonces)); + if (!nonces) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Out of memory"); + return; + } + nonce_cache_issued_t issued; + nonce_cache_result_t result = + nonce_cache_issue(&issuance, !req->has_session_id, + req->derivation_path.ptr, req->derivation_path.len, + (uint8_t *)nonces, count * sizeof(*nonces), &issued); + if (result != NONCE_CACHE_OK) { + free(nonces); + show_issue_error(result); + return; + } + + bipqr_response response; + fill_response_header(&response); + bipqr_nonces_prepared *prepared = &response.body.nonces_prepared; + prepared->has_session = issued.new_session; + memcpy(prepared->session_id, issued.session_id, sizeof(prepared->session_id)); + memcpy(prepared->session_ref, issued.session_ref, + sizeof(prepared->session_ref)); + prepared->nonces.ptr = nonces; + prepared->nonces.len = count; + show_response(&response); + free(nonces); +} + +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); +} + +// Our silent payment account under `alias`: our fingerprint, our spend key +// and whether its scan key is not ours +static void confirm_sp_unregister(const char *alias) { + char fingerprint[9]; + uint32_t spend_path[SP_PATH_DEPTH]; + char spend[64]; + sp_account_key_path(wallet_is_testnet(), SP_SPEND_BRANCH, spend_path); + if (!key_get_fingerprint_hex(fingerprint) || + !bip32_path_format(spend_path, SP_PATH_DEPTH, spend, sizeof(spend))) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Key failed"); + return; + } + char msg[192]; + snprintf(msg, sizeof(msg), + "Unregister silent payment keys?\n\nAlias: %s\nFingerprint: " + "%s\nSpend key: %s%s", + alias, fingerprint, spend, + registry_sp_alias_scan_key(alias) + ? "\nScan key: external, not this device's" + : ""); + dialog_show_danger_confirm(msg, unregister_confirm_cb, NULL, + DIALOG_STYLE_OVERLAY); +} + +// 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 if (registry_sp_alias_exists(alias)) { + confirm_sp_unregister(alias); + } 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); + 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_NONCE_PREPARATION: + handle_prepare_nonces(); + 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..722506f9 --- /dev/null +++ b/main/pages/bip_flow/bip_flow.h @@ -0,0 +1,81 @@ +#ifndef BIP_FLOW_H +#define BIP_FLOW_H + +#include +#include +#include +#include +#include + +#include "../../core/descriptor_validator.h" +#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; + } +} +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..94e9fa7e --- /dev/null +++ b/main/pages/bip_flow/test/test_bip388.c @@ -0,0 +1,93 @@ +#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("/** after musig() is expanded", "tr(musig(@0,@1)/**)", + KEYS, 2, "tr(musig(" KEY_A "," KEY_B ")/<0;1>/*)"); + 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..03cc30c6 --- /dev/null +++ b/main/pages/bip_flow/test/test_bip_flow_header.c @@ -0,0 +1,189 @@ +#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); +} + +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(); + + 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/addresses.c b/main/pages/home/addresses.c index cee309b2..d9673014 100644 --- a/main/pages/home/addresses.c +++ b/main/pages/home/addresses.c @@ -9,6 +9,7 @@ #include "../../qr/encoder.h" #include "../../qr/scanner.h" #include "../../qr/viewer.h" +#include "../../ui/address_label.h" #include "../../ui/assets/icons.h" #include "../../ui/dialog.h" #include "../../ui/input_helpers.h" @@ -70,30 +71,6 @@ static void refresh_address_list(void); static void scan_button_cb(lv_event_t *e); static void return_from_scan_cb(void); -// Format address as 4-char blocks with alternating main/highlight colors -static void format_address_colored_blocks(char *dest, size_t dest_size, - const char *address) { - lv_color32_t c1 = lv_color_to_32(primary_color(), LV_OPA_COVER); - lv_color32_t c2 = lv_color_to_32(highlight_color(), LV_OPA_COVER); - uint32_t hex1 = (c1.red << 16) | (c1.green << 8) | c1.blue; - uint32_t hex2 = (c2.red << 16) | (c2.green << 8) | c2.blue; - - size_t len = strlen(address); - size_t written = 0; - dest[0] = '\0'; - - for (size_t pos = 0; pos < len; pos += 4) { - uint32_t color = ((pos / 4) % 2 == 0) ? hex1 : hex2; - size_t chunk = (len - pos < 4) ? (len - pos) : 4; - int n = snprintf(dest + written, dest_size - written, "%s#%06X %.*s#", - (pos > 0) ? " " : "", (unsigned)color, (int)chunk, - address + pos); - if (n < 0 || (size_t)n >= dest_size - written) - break; - written += n; - } -} - static void show_address_detail(int index); static void back_button_cb(lv_event_t *e) { @@ -235,19 +212,11 @@ static void show_address_detail(int index) { qr_viewer_attach_fullscreen(qr_container, qr_payload, title); free(upper); - // Full address text with alternating colored 4-char blocks - char colored_addr[512]; - format_address_colored_blocks(colored_addr, sizeof(colored_addr), address); - lv_obj_t *addr_label = lv_label_create(content); - lv_label_set_recolor(addr_label, true); - lv_label_set_text(addr_label, colored_addr); + lv_obj_t *addr_label = address_label_create(content, address); 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); // Back button detail_back_button = ui_create_back_button(parent, detail_back_cb); 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..2321da10 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; @@ -228,24 +228,21 @@ static void sd_desc_on_file_selected(const char *full_path, const char *dir, /* ---------- Display name ---------- */ /* A registered backup is already in the session and is managed from Session - * Descriptors, so the flash list leaves it out. Other BIP138 files stay + * Descriptors, so the flash list leaves it out, as it does silent payment + * account registrations, which hold no descriptor. 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; + if (storage_descriptor_format(filename) == STORAGE_DESCRIPTOR_SP_ACCOUNT) + return true; + 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..70217fcd 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 @@ -209,15 +218,15 @@ static void finish_dispatch(char *qr_content, size_t qr_content_len, } else { scan_ctx.qr_format = detected_format; - if (scan_psbt_check_mismatch()) { + if (scan_psbt_complete_silent_payments() || scan_psbt_check_mismatch()) { return; } 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,8 +237,24 @@ 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 @@ -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,34 @@ 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(); + psbt_parse_result_t parsed = + psbt_parse_payload_result(data, len, &scan_ctx.psbt); + if (parsed == PSBT_PARSE_SP_SIGHASH) { + scan_psbt_fail(SCAN_PSBT_INVALID, + "Silent payment inputs must use SIGHASH_ALL", + scan_ctx.return_cb, 0); + return; + } + finish_dispatch(NULL, len, parsed == PSBT_PARSE_OK, 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 +525,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 +578,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..2a72870d 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,9 +64,14 @@ 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); +void scan_create_sign_action_row(lv_obj_t *parent, const char *sign_label, + lv_event_cb_t sign_cb); lv_obj_t *scan_create_address_label(lv_obj_t *parent, const char *address, lv_color_t highlight, int32_t pad_left); lv_obj_t *scan_create_btc_value_row(lv_obj_t *parent, const char *prefix, @@ -70,11 +82,17 @@ void scan_create_review_note(lv_obj_t *parent, const char *text, /* scan_psbt_review.c */ bool scan_psbt_parse_base64(const char *base64_data); void scan_psbt_cleanup(void); +// Runs the BIP375 signer pass on a PSBT carrying silent payment fields. +// True when it failed and an error dialog took over. +bool scan_psbt_complete_silent_payments(void); bool scan_psbt_check_mismatch(void); void scan_psbt_resume_review(bool offer_descriptor); /* scan_psbt_sign.c */ void scan_psbt_sign_button_cb(lv_event_t *e); +// Hands the unsigned PSBT holding our silent payment shares back, as a +// signed one would go +void scan_psbt_export_shares(void); void scan_qr_viewer_return_cb(void); void scan_export_destroy_menu(void); diff --git a/main/pages/scan/scan_message_sign.c b/main/pages/scan/scan_message_sign.c index 8d369e4b..3853d5b0 100644 --- a/main/pages/scan/scan_message_sign.c +++ b/main/pages/scan/scan_message_sign.c @@ -66,7 +66,8 @@ void scan_message_create_display(void) { lv_obj_set_width(msg_label, LV_PCT(100)); lv_label_set_long_mode(msg_label, LV_LABEL_LONG_WRAP); - scan_create_sign_action_row(scan_ctx.info_container, message_sign_button_cb); + scan_create_sign_action_row(scan_ctx.info_container, "Sign", + message_sign_button_cb); } // Review screen for a PSBT-based BIP322 signing request. Signing goes through @@ -102,7 +103,7 @@ void scan_bip322_create_display(void) { lv_obj_set_width(msg_label, LV_PCT(100)); lv_label_set_long_mode(msg_label, LV_LABEL_LONG_WRAP); - scan_create_sign_action_row(scan_ctx.info_container, + scan_create_sign_action_row(scan_ctx.info_container, "Sign", scan_psbt_sign_button_cb); } diff --git a/main/pages/scan/scan_psbt_review.c b/main/pages/scan/scan_psbt_review.c index 26c919b3..ba101755 100644 --- a/main/pages/scan/scan_psbt_review.c +++ b/main/pages/scan/scan_psbt_review.c @@ -5,6 +5,8 @@ #include "../../core/psbt.h" #include "../../core/registry.h" +#include "../../core/silent_payments.h" +#include "../../core/sp_psbt.h" #include "../../core/wallet.h" #include "../../qr/parser.h" #include "../../qr/scanner.h" @@ -13,7 +15,6 @@ #include "../../ui/theme_widgets.h" #include "../load_descriptor_storage.h" #include "../shared/descriptor_loader.h" -#include "kern_wally.h" #include "psbt_sign_policy.h" #include "scan_internal.h" #include @@ -40,7 +41,8 @@ typedef struct { size_t num_outputs; } psbt_owners_t; -static bool create_psbt_info_display(const psbt_owners_t *owners); +static bool create_psbt_info_display(const psbt_owners_t *owners, + bool shares_only); // Fee share of the inputs at which the review screen stops calling it normal. #define HIGH_FEE_PERCENT 10u @@ -64,6 +66,7 @@ typedef struct { output_type_t type; uint64_t value; char *address; + char *sp_address; /* sp1 address of a silent payment output, else NULL */ uint32_t address_index; bool change_chain; /* owned output on its wallet's change chain */ bool is_dust; /* below the relay dust threshold for its script type */ @@ -112,13 +115,22 @@ static const char *ss_script_label(ss_script_type_t script) { static void format_claim_policy(const claim_t *claim, char *out, size_t out_size) { out[0] = '\0'; - if (claim->kind == CLAIM_WHITELIST) { + switch (claim->kind) { + case CLAIM_WHITELIST: snprintf(out, out_size, "%s @ account %u", ss_script_label(claim->whitelist.script), (unsigned)claim->whitelist.account); - } else if (claim->kind == CLAIM_REGISTRY && claim->registry.entry) { - const registry_entry_t *entry = claim->registry.entry; - snprintf(out, out_size, "%s", entry->label[0] ? entry->label : entry->id); + break; + case CLAIM_REGISTRY: + case CLAIM_MUSIG: + if (claim->registry.entry) { + const registry_entry_t *entry = claim->registry.entry; + snprintf(out, out_size, "%s", entry->label[0] ? entry->label : entry->id); + } + break; + case CLAIM_SILENT_PAYMENT: + snprintf(out, out_size, "Silent Payments"); + break; } } @@ -141,12 +153,19 @@ static void classify_output(const classified_input_t *inputs, size_t num_inputs, classified_output_t *out) { switch (ownership.ownership) { case PSBT_OWNERSHIP_OWNED_SAFE: - if (ownership.source.kind == CLAIM_WHITELIST) { + switch (ownership.source.kind) { + case CLAIM_WHITELIST: out->change_chain = (ownership.source.whitelist.chain == 1); out->address_index = ownership.source.whitelist.index; - } else { + break; + case CLAIM_REGISTRY: + case CLAIM_MUSIG: out->change_chain = (ownership.source.registry.multi_index == 1); out->address_index = ownership.source.registry.child_num; + break; + case CLAIM_SILENT_PAYMENT: + out->change_chain = ownership.source.silent_payment.is_change; + break; } format_claim_policy(&ownership.source, out->policy, sizeof(out->policy)); out->type = out->change_chain && output_shares_input_policy( @@ -172,8 +191,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(); } @@ -187,7 +225,7 @@ static void owners_free(psbt_owners_t *o) { memset(o, 0, sizeof(*o)); } -static bool owners_classify(psbt_owners_t *o) { +static bool owners_classify(psbt_owners_t *o, bool is_testnet) { memset(o, 0, sizeof(*o)); if (!scan_ctx.psbt || wally_psbt_get_num_inputs(scan_ctx.psbt, &o->num_inputs) != WALLY_OK || @@ -201,24 +239,27 @@ static bool owners_classify(psbt_owners_t *o) { return false; } for (size_t i = 0; i < o->num_inputs; i++) - o->inputs[i] = psbt_classify_input(scan_ctx.psbt, i, scan_ctx.is_testnet); + o->inputs[i] = psbt_classify_input(scan_ctx.psbt, i, is_testnet); for (size_t i = 0; i < o->num_outputs; i++) - o->outputs[i] = psbt_classify_output(scan_ctx.psbt, i, scan_ctx.is_testnet); + o->outputs[i] = psbt_classify_output(scan_ctx.psbt, i, is_testnet); return true; } 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); + if (!owners_classify(&owners, scan_ctx.is_testnet)) { + 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) && - !create_psbt_info_display(&owners)) - dialog_show_error_timeout("Invalid PSBT data", scan_ctx.return_cb, 0); + : NULL, + &policy_refusal) && + !create_psbt_info_display(&owners, false)) + scan_psbt_fail(SCAN_PSBT_INVALID, "Invalid PSBT data", scan_ctx.return_cb, + 0); owners_free(&owners); } @@ -290,8 +331,16 @@ bool scan_psbt_parse_base64(const char *base64_data) { scan_psbt_cleanup(); - int ret = kern_psbt_from_base64(base64_data, 0, &scan_ctx.psbt); - if (ret != WALLY_OK) { + // Decoded and parsed as a binary payload, so it gets the same checks + size_t max_len = 0, len = 0; + unsigned char *bytes = NULL; + bool parsed = + wally_base64_get_maximum_length(base64_data, 0, &max_len) == WALLY_OK && + (bytes = malloc(max_len)) != NULL && + wally_base64_to_bytes(base64_data, 0, bytes, max_len, &len) == WALLY_OK && + psbt_parse_payload(bytes, len, &scan_ctx.psbt); + free(bytes); + if (!parsed) { scan_psbt_cleanup(); return false; } @@ -302,21 +351,94 @@ 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(); } } +static scan_psbt_failure_t sp_psbt_failure(sp_psbt_result_t result) { + switch (result) { + case SP_PSBT_ERR_KEYS: + case SP_PSBT_ERR_CRYPTO: + return SCAN_PSBT_INTERNAL; + default: + return SCAN_PSBT_INVALID; + } +} + +// Another signer still owes a share, so no output can be derived and nothing +// may be signed (BIP375): the review offers to send our shares back alone +static void offer_shares_only(bool is_testnet) { + sp_share_t *shares = NULL; + size_t count = 0; + if (!sp_psbt_shares_alloc(scan_ctx.psbt, is_testnet, &shares, &count)) { + scan_psbt_fail(SCAN_PSBT_INTERNAL, "Silent payment shares unavailable", + scan_ctx.return_cb, 0); + return; + } + free(shares); + if (!count) { + scan_psbt_fail(SCAN_PSBT_NOTHING_TO_SIGN, + sp_psbt_result_message(SP_PSBT_PENDING), scan_ctx.return_cb, + 0); + return; + } + psbt_owners_t owners; + if (!owners_classify(&owners, is_testnet) || + !create_psbt_info_display(&owners, true)) + scan_psbt_fail(SCAN_PSBT_INVALID, "Invalid PSBT data", scan_ctx.return_cb, + 0); + owners_free(&owners); +} + +bool scan_psbt_complete_silent_payments(void) { + if (!scan_ctx.psbt || !sp_psbt_has_fields(scan_ctx.psbt)) + return false; + bool is_testnet = wallet_get_network() == WALLET_NETWORK_TESTNET; + // The signing policy gates our shares as it gates our signatures. A + // descriptor loaded from the expected-owned refusal would resume the + // signature review, not this round, so none is offered. + psbt_owners_t owners; + if (!owners_classify(&owners, is_testnet)) { + scan_psbt_fail(SCAN_PSBT_INVALID, "Invalid PSBT data", scan_ctx.return_cb, + 0); + return true; + } + bool allowed = psbt_sign_policy_allows_review( + scan_ctx.psbt, owners.inputs, owners.outputs, policy_reject_dismissed_cb, + NULL, &policy_refusal); + owners_free(&owners); + if (!allowed) + return true; + sp_psbt_result_t result = sp_psbt_complete(&scan_ctx.psbt, is_testnet); + if (result == SP_PSBT_OK) + return false; + if (result == SP_PSBT_PENDING) + offer_shares_only(is_testnet); + else + scan_psbt_fail(sp_psbt_failure(result), sp_psbt_result_message(result), + scan_ctx.return_cb, 0); + return true; +} + bool scan_psbt_check_mismatch(void) { if (!scan_ctx.psbt) { return false; } - scan_ctx.is_testnet = psbt_detect_network(scan_ctx.psbt); - wallet_network_t wallet_net = wallet_get_network(); bool wallet_is_testnet = (wallet_net == WALLET_NETWORK_TESTNET); + // Silent payment fields carry no key origin, so the wallet network applies + scan_ctx.is_testnet = sp_psbt_has_fields(scan_ctx.psbt) + ? wallet_is_testnet + : psbt_detect_network(scan_ctx.psbt); + bool network_mismatch = (scan_ctx.is_testnet != wallet_is_testnet); if (!network_mismatch) { @@ -365,12 +487,23 @@ static void review_data_free(review_data_t *d) { free_address(d->inputs[i].address); free(d->inputs); if (d->outputs) - for (size_t i = 0; i < d->num_outputs; i++) + for (size_t i = 0; i < d->num_outputs; i++) { free_address(d->outputs[i].address); + free(d->outputs[i].sp_address); + } free(d->outputs); memset(d, 0, sizeof(*d)); } +// The sp1 address a silent payment output pays, left NULL for other outputs +static bool output_sp_address(size_t output_index, char **out) { + unsigned char scan[SP_PUBKEY_LEN], spend[SP_PUBKEY_LEN]; + *out = NULL; + if (!sp_output_keys(&scan_ctx.psbt->outputs[output_index], scan, spend)) + return true; + return sp_address_alloc(scan, spend, scan_ctx.is_testnet, out); +} + static bool review_data_collect(review_data_t *d, const psbt_owners_t *owners) { memset(d, 0, sizeof(*d)); d->num_inputs = owners->num_inputs; @@ -451,6 +584,10 @@ static bool review_data_collect(review_data_t *d, const psbt_owners_t *owners) { out->address = psbt_output_destination( txo->script, txo->script_len, scan_ctx.is_testnet, &out->dest_kind); out->script_len = txo->script_len; + if (!output_sp_address(i, &out->sp_address)) { + wally_tx_free(tx); + goto fail; + } classify_output(d->inputs, d->num_inputs, owners->outputs[i], out); out->is_dust = out->value < psbt_output_dust_threshold(txo->script, txo->script_len); @@ -795,12 +932,18 @@ static void render_self_transfers(lv_obj_t *parent, const review_data_t *d) { if (out->type != OUTPUT_TYPE_SELF_TRANSFER) continue; char text[64]; - snprintf(text, sizeof(text), - "%s #%u: ", out->change_chain ? "Change" : "Receive", - out->address_index); + if (out->sp_address) + snprintf(text, sizeof(text), "Output %zu: ", out->index); + else + snprintf(text, sizeof(text), + "%s #%u: ", out->change_chain ? "Change" : "Receive", + out->address_index); lv_obj_t *row = indented_amount_row(parent, text, out->value); if (out->policy[0]) append_policy_note(row, "to", out->policy); + if (out->sp_address) + scan_create_address_label(parent, out->sp_address, accent_color(), + ADDRESS_INDENT_PX); render_destination(parent, out->address, out->dest_kind, out->script_len, accent_color()); } @@ -829,6 +972,23 @@ static void render_change(lv_obj_t *parent, const review_data_t *d) { lv_obj_set_style_margin_top(row, 15, 0); } +/* The taproot address a silent payment lands on is derived for this + * transaction only, so the recipient can vouch for the sp1 address alone. */ +static void render_silent_payment_warning(lv_obj_t *parent, + const review_data_t *d) { + for (size_t i = 0; i < d->num_outputs; i++) { + if (d->outputs[i].type != OUTPUT_TYPE_SPEND || !d->outputs[i].sp_address) + continue; + lv_obj_t *title = section_title( + parent, + "Verify each sp1 address with its recipient. The taproot address " + "under it cannot be checked.", + error_color(), true); + lv_label_set_long_mode(title, LV_LABEL_LONG_WRAP); + return; + } +} + /* A titled list of every output of one kind: amount row plus address, with * the derivation path in the row label when the kind carries one. */ static void render_output_group(lv_obj_t *parent, const review_data_t *d, @@ -851,6 +1011,9 @@ static void render_output_group(lv_obj_t *parent, const review_data_t *d, else snprintf(text, sizeof(text), "Output %zu: ", out->index); indented_amount_row(parent, text, out->value); + if (out->sp_address) + scan_create_address_label(parent, out->sp_address, color, + ADDRESS_INDENT_PX); render_destination(parent, out->address, out->dest_kind, out->script_len, color); } @@ -962,7 +1125,15 @@ static void render_fee_and_notes(lv_obj_t *parent, const review_data_t *d) { } } -static bool create_psbt_info_display(const psbt_owners_t *owners) { +static void add_shares_button_cb(lv_event_t *e) { + (void)e; + scan_psbt_export_shares(); +} + +// The review screen, its action adding our silent payment shares instead of +// signing when shares_only +static bool create_psbt_info_display(const psbt_owners_t *owners, + bool shares_only) { if (!scan_ctx.screen || !scan_ctx.psbt || !wallet_is_initialized()) return false; if (scan_psbt_check_mismatch()) @@ -994,12 +1165,23 @@ static bool create_psbt_info_display(const psbt_owners_t *owners) { "Owned (non-standard path): ", true); render_output_group(c, &data, OUTPUT_TYPE_EXPECTED_OWNED, "Expected ownership (UNVERIFIED): ", true); + render_silent_payment_warning(c, &data); render_output_group(c, &data, OUTPUT_TYPE_SPEND, "Spending: ", false); render_fee_and_notes(c, &data); review_data_free(&data); - scan_create_sign_action_row(c, scan_psbt_sign_button_cb); + if (shares_only) { + scan_create_review_note( + c, + "Other signers still owe silent payment shares, so the outputs cannot " + "be derived yet and nothing is signed. Add the shares of the inputs " + "this wallet holds?", + highlight_color()); + scan_create_sign_action_row(c, "Add shares", add_shares_button_cb); + } else { + scan_create_sign_action_row(c, "Sign", scan_psbt_sign_button_cb); + } return true; } diff --git a/main/pages/scan/scan_psbt_sign.c b/main/pages/scan/scan_psbt_sign.c index 3f66b9e0..3e256b1b 100644 --- a/main/pages/scan/scan_psbt_sign.c +++ b/main/pages/scan/scan_psbt_sign.c @@ -5,6 +5,7 @@ #include "../../core/psbt.h" #include "../../core/secp_hardening.h" #include "../../core/settings.h" +#include "../../core/sp_psbt.h" #include "../../qr/parser.h" #include "../../qr/viewer.h" #include "../../ui/dialog.h" @@ -21,6 +22,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 +47,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 +55,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 +70,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 +95,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 +165,28 @@ static void deferred_sign_cb(lv_timer_t *timer) { return; } - show_export_choice(); + finish_signed_psbt(); +} + +void scan_psbt_export_shares(void) { + if (!scan_ctx.psbt_signed_cb) { + struct wally_psbt *trimmed = psbt_trim(scan_ctx.psbt); + if (scan_ctx.signed_psbt_base64) { + wally_free_string(scan_ctx.signed_psbt_base64); + scan_ctx.signed_psbt_base64 = NULL; + } + bool ok = sp_psbt_base64_alloc(trimmed ? trimmed : scan_ctx.psbt, + &scan_ctx.signed_psbt_base64); + wally_psbt_free(trimmed); + if (!ok) { + scan_psbt_fail(SCAN_PSBT_INTERNAL, "Failed to encode PSBT", + scan_ctx.return_cb, 0); + return; + } + scan_ctx.saved_return_cb = + scan_ctx.complete_cb ? scan_ctx.complete_cb : scan_ctx.return_cb; + } + finish_signed_psbt(); } // Tears down the chooser, then returns to the caller that opened the @@ -262,7 +302,7 @@ static void deferred_export_save_cb(lv_timer_t *timer) { esp_err_t wret; if (scan_ctx.source_base64) { char *full_b64 = NULL; - if (wally_psbt_to_base64(scan_ctx.psbt, 0, &full_b64) != WALLY_OK) { + if (!sp_psbt_base64_alloc(scan_ctx.psbt, &full_b64)) { dialog_show_error_timeout("Failed to encode PSBT", show_export_choice, 0); return; } @@ -270,20 +310,9 @@ static void deferred_export_save_cb(lv_timer_t *timer) { sd_card_write_file(path, (const uint8_t *)full_b64, strlen(full_b64)); wally_free_string(full_b64); } else { - size_t bin_len = 0; - if (wally_psbt_get_length(scan_ctx.psbt, 0, &bin_len) != WALLY_OK) { - dialog_show_error_timeout("Failed to encode PSBT", show_export_choice, 0); - return; - } - uint8_t *bin = malloc(bin_len); - if (!bin) { - dialog_show_error_timeout("Out of memory", show_export_choice, 0); - return; - } + uint8_t *bin = NULL; size_t written = 0; - if (wally_psbt_to_bytes(scan_ctx.psbt, 0, bin, bin_len, &written) != - WALLY_OK) { - free(bin); + if (!sp_psbt_serialize_alloc(scan_ctx.psbt, &bin, &written)) { dialog_show_error_timeout("Failed to encode PSBT", show_export_choice, 0); return; } diff --git a/main/pages/scan/scan_review_widgets.c b/main/pages/scan/scan_review_widgets.c index fb86ca3f..c634592e 100644 --- a/main/pages/scan/scan_review_widgets.c +++ b/main/pages/scan/scan_review_widgets.c @@ -14,7 +14,8 @@ static void back_button_cb(lv_event_t *e); -void scan_create_sign_action_row(lv_obj_t *parent, lv_event_cb_t sign_cb) { +void scan_create_sign_action_row(lv_obj_t *parent, const char *sign_label, + lv_event_cb_t sign_cb) { lv_obj_t *button_container = theme_create_button_row(parent, 10); if (!button_container) return; @@ -24,7 +25,8 @@ void scan_create_sign_action_row(lv_obj_t *parent, lv_event_cb_t sign_cb) { lv_obj_add_event_cb(back_button, back_button_cb, LV_EVENT_CLICKED, NULL); lv_obj_clear_flag(back_button, LV_OBJ_FLAG_EVENT_BUBBLE); - lv_obj_t *sign_button = theme_create_button(button_container, "Sign", false); + lv_obj_t *sign_button = + theme_create_button(button_container, sign_label, false); lv_obj_set_size(sign_button, LV_PCT(45), LV_SIZE_CONTENT); lv_obj_add_event_cb(sign_button, sign_cb, LV_EVENT_CLICKED, NULL); lv_obj_clear_flag(sign_button, LV_OBJ_FLAG_EVENT_BUBBLE); @@ -142,6 +144,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/settings/descriptor_manager.c b/main/pages/settings/descriptor_manager.c index cc32fad6..258a6594 100644 --- a/main/pages/settings/descriptor_manager.c +++ b/main/pages/settings/descriptor_manager.c @@ -493,6 +493,7 @@ static void build_main_menu(void) { return; bool has_desc = registry_count() > 0; + bool has_entries = has_desc || registry_sp_alias_count() > 0; ui_menu_add_entry(main_menu, "Session Descriptors", registered_desc_cb); idx_registered = 0; @@ -502,8 +503,8 @@ static void build_main_menu(void) { load_descriptor_cb); idx_load = 1; - /* Disable session descriptor entries when no descriptor is loaded */ - if (!has_desc) { + /* Disable session descriptor entries when nothing is registered */ + if (!has_entries) { ui_menu_set_entry_enabled(main_menu, idx_registered, false); } @@ -521,7 +522,8 @@ static void refresh_menu_visibility(void) { : "Load Descriptor"); /* Toggle session descriptor actions */ - ui_menu_set_entry_enabled(main_menu, idx_registered, has_desc); + ui_menu_set_entry_enabled(main_menu, idx_registered, + has_desc || registry_sp_alias_count() > 0); } } diff --git a/main/pages/settings/registered_descriptors.c b/main/pages/settings/registered_descriptors.c index abf2bf20..d9da7d95 100644 --- a/main/pages/settings/registered_descriptors.c +++ b/main/pages/settings/registered_descriptors.c @@ -18,6 +18,10 @@ #include #include +// One entry per descriptor and per silent payment alias, none hidden +_Static_assert(UI_MENU_MAX_ENTRIES >= 2 * REGISTRY_MAX_ENTRIES, + "Session Descriptors menu cannot list the whole registry"); + static lv_obj_t *rd_screen = NULL; static ui_menu_t *rd_menu = NULL; static ui_menu_t *action_menu = NULL; @@ -27,6 +31,8 @@ static registered_descriptor_action_cb_t action_callback = NULL; static int pending_remove_index = -1; static int pending_deregister_index = -1; static int selected_descriptor_index = -1; +// Index among the silent payment aliases, listed after the registry entries +static int selected_sp_alias_index = -1; static void build_rd_menu(void); @@ -224,10 +230,54 @@ static void deregister_action_cb(void) { DIALOG_STYLE_OVERLAY); } +static void sp_deregister_confirmed_cb(bool confirmed, void *user_data) { + (void)user_data; + int idx = selected_sp_alias_index; + if (!confirmed || idx < 0) + return; + if (!registry_sp_alias_deregister_at((size_t)idx)) { + dialog_show_error_timeout("Could not de-register the alias.\n" + "The registration has not changed.", + NULL, 0); + return; + } + selected_sp_alias_index = -1; + build_rd_menu(); +} + +static void sp_deregister_action_cb(void) { + dialog_show_danger_confirm("Delete this silent payment account alias " + "from flash?", + sp_deregister_confirmed_cb, NULL, + DIALOG_STYLE_OVERLAY); +} + +static void show_sp_action_menu(size_t sp_index) { + const char *alias = registry_sp_alias_get(sp_index); + if (!alias) + return; + selected_sp_alias_index = (int)sp_index; + ui_menu_hide(rd_menu); + if (action_menu) { + ui_menu_destroy(action_menu); + action_menu = NULL; + } + action_menu = ui_menu_create(rd_screen, alias, action_menu_back_cb); + if (!action_menu) + return; + ui_menu_add_entry(action_menu, "De-register and Delete", + sp_deregister_action_cb); + ui_menu_show(action_menu); +} + static void show_action_menu(void) { int idx = ui_menu_get_selected(rd_menu); if (idx < 0) return; + if ((size_t)idx >= registry_count()) { + show_sp_action_menu((size_t)idx - registry_count()); + return; + } const registry_entry_t *entry = registry_get((size_t)idx); if (!entry) @@ -280,7 +330,8 @@ static void build_rd_menu(void) { return; size_t count = registry_count(); - if (count == 0) { + size_t sp_count = registry_sp_alias_count(); + if (count == 0 && sp_count == 0) { ui_menu_add_entry(rd_menu, "(no session descriptors)", disabled_entry_cb); ui_menu_set_entry_enabled(rd_menu, 0, false); } else { @@ -291,6 +342,13 @@ static void build_rd_menu(void) { ui_menu_add_entry(rd_menu, entry->label[0] ? entry->label : entry->id, show_action_menu); } + for (size_t i = 0; i < sp_count; i++) { + const char *alias = registry_sp_alias_get(i); + char text[REGISTRY_ID_MAX_LEN + 48]; + snprintf(text, sizeof(text), "%s (Silent payment account%s)", alias, + registry_sp_alias_scan_key(alias) ? ", external scan key" : ""); + ui_menu_add_entry(rd_menu, text, show_action_menu); + } } ui_menu_show(rd_menu); } @@ -350,6 +408,7 @@ void registered_descriptors_page_destroy(void) { pending_remove_index = -1; pending_deregister_index = -1; selected_descriptor_index = -1; + selected_sp_alias_index = -1; return_callback = NULL; action_callback = NULL; } 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..bf6cd156 100644 --- a/main/qr/parser.c +++ b/main/qr/parser.c @@ -43,6 +43,20 @@ static bool sequence_exceeds_budget(int total, size_t part_len) { part_len > QR_PARSER_MAX_STORED_BYTES / (size_t)(total - 1); } +static void skip_leading_whitespace(const char **data, size_t *data_len) { + while (*data_len > 0 && isspace((unsigned char)(*data)[0])) { + (*data)++; + (*data_len)--; + } +} + +static size_t trailing_trimmed_len(const char *data, size_t data_len) { + while (data_len > 0 && isspace((unsigned char)data[data_len - 1])) { + data_len--; + } + return data_len; +} + QRPartParser *qr_parser_create(void) { QRPartParser *parser = (QRPartParser *)calloc(1, sizeof(QRPartParser)); if (!parser) @@ -161,8 +175,17 @@ int qr_parser_parse_with_len(QRPartParser *parser, const char *data, return -1; } + /* A camera frame can carry stray whitespace around the payload. Skipping it + * up front lets a header be recognized; only the formats whose payload is + * self-delimiting (BBQr) may also drop it at the end. A pMofN part keeps its + * trailing whitespace, which belongs to the reassembled payload. */ + const char *frame = data; + size_t frame_len = data_len; + skip_leading_whitespace(&frame, &frame_len); + size_t body_len = trailing_trimmed_len(frame, frame_len); + if (parser->format == -1) { - parser->format = detect_format(data, data_len, &parser->bbqr); + parser->format = detect_format(frame, body_len, &parser->bbqr); } if (parser->format == FORMAT_NONE) { @@ -174,7 +197,7 @@ int qr_parser_parse_with_len(QRPartParser *parser, const char *data, const char *part = NULL; size_t part_len = 0; int index, total; - if (!parse_pmofn_qr_part(data, data_len, &part, &part_len, &index, + if (!parse_pmofn_qr_part(frame, frame_len, &part, &part_len, &index, &total)) { return fail_parser(parser); } @@ -200,7 +223,7 @@ int qr_parser_parse_with_len(QRPartParser *parser, const char *data, } ur_decoder_t *decoder = (ur_decoder_t *)parser->ur_decoder; - ur_decoder_state_t state = ur_decoder_receive_part(decoder, data); + ur_decoder_state_t state = ur_decoder_receive_part(decoder, frame); if (state == UR_DECODER_OK) { return 0; // Single-part UR, complete immediately } @@ -210,7 +233,7 @@ int qr_parser_parse_with_len(QRPartParser *parser, const char *data, } } else if (parser->format == FORMAT_BBQR) { BBQrPart part; - if (!parser->bbqr || !bbqr_parse_part(data, data_len, &part)) { + if (!parser->bbqr || !bbqr_parse_part(frame, body_len, &part)) { return fail_parser(parser); } if ((parser->total != -1 && parser->total != part.total) || @@ -370,7 +393,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..bba92ba5 100644 --- a/main/qr/test/test_parser.c +++ b/main/qr/test/test_parser.c @@ -427,6 +427,53 @@ 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. Split out so the whitespace and lowercase variants + * assert against the same payload. */ +#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_trims_frame_whitespace(void) { + const char *frame = " \n\tB$HB0100" BIP_REQUEST_BODY " \r\n"; + 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); +} + +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 +496,8 @@ int main(void) { test_bbqr_result_failure_clears_length(); test_valid_bbqr_still_assembles(); test_valid_ur_still_processes(); + test_bbqr_trims_frame_whitespace(); + 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/main/ui/address_label.c b/main/ui/address_label.c new file mode 100644 index 00000000..1472e042 --- /dev/null +++ b/main/ui/address_label.c @@ -0,0 +1,91 @@ +#include "address_label.h" +#include "theme.h" +#include +#include +#include + +// Block sizes a tap cycles through, 0 shows the plain address +static const size_t BLOCK_SIZES[] = {4, 6, 0}; +#define BLOCK_SIZES_COUNT (sizeof(BLOCK_SIZES) / sizeof(BLOCK_SIZES[0])) + +// Recolor markup around each block: separator space, "#RRGGBB " and "#" +#define BLOCK_MARKUP_LEN 10 + +typedef struct { + size_t mode; + char address[]; +} address_label_t; + +static uint32_t color_hex(lv_color_t color) { + lv_color32_t c = lv_color_to_32(color, LV_OPA_COVER); + return (c.red << 16) | (c.green << 8) | c.blue; +} + +// Show `address` in `block_size`-char blocks with alternating primary and +// highlight colors, or plain when `block_size` is 0. Returns false when out of +// memory, the label then keeps its text. +static bool set_blocks_text(lv_obj_t *label, const char *address, + size_t block_size) { + if (block_size == 0) { + lv_label_set_text(label, address); + return true; + } + + size_t len = strlen(address); + size_t blocks = (len + block_size - 1) / block_size; + size_t size = len + blocks * BLOCK_MARKUP_LEN + 1; + char *text = malloc(size); + if (!text) + return false; + + uint32_t hex1 = color_hex(primary_color()); + uint32_t hex2 = color_hex(highlight_color()); + size_t written = 0; + text[0] = '\0'; + for (size_t pos = 0; pos < len; pos += block_size) { + uint32_t color = ((pos / block_size) % 2 == 0) ? hex1 : hex2; + size_t chunk = (len - pos < block_size) ? (len - pos) : block_size; + written += snprintf(text + written, size - written, "%s#%06X %.*s#", + (pos > 0) ? " " : "", (unsigned)color, (int)chunk, + address + pos); + } + + lv_label_set_text(label, text); + free(text); + return true; +} + +static void address_label_clicked_cb(lv_event_t *e) { + lv_obj_t *label = lv_event_get_target(e); + address_label_t *state = lv_event_get_user_data(e); + size_t next = (state->mode + 1) % BLOCK_SIZES_COUNT; + if (set_blocks_text(label, state->address, BLOCK_SIZES[next])) + state->mode = next; +} + +static void address_label_delete_cb(lv_event_t *e) { + free(lv_event_get_user_data(e)); +} + +lv_obj_t *address_label_create(lv_obj_t *parent, const char *address) { + lv_obj_t *label = lv_label_create(parent); + lv_label_set_recolor(label, true); + lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP); + lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_set_style_text_font(label, theme_font_medium(), 0); + lv_obj_set_style_text_color(label, primary_color(), 0); + lv_label_set_text(label, address); + + size_t len = strlen(address); + address_label_t *state = malloc(sizeof(*state) + len + 1); + if (!state) + return label; + state->mode = 0; + memcpy(state->address, address, len + 1); + set_blocks_text(label, state->address, BLOCK_SIZES[state->mode]); + + lv_obj_add_flag(label, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_event_cb(label, address_label_clicked_cb, LV_EVENT_CLICKED, state); + lv_obj_add_event_cb(label, address_label_delete_cb, LV_EVENT_DELETE, state); + return label; +} diff --git a/main/ui/address_label.h b/main/ui/address_label.h new file mode 100644 index 00000000..7cc8c30f --- /dev/null +++ b/main/ui/address_label.h @@ -0,0 +1,22 @@ +/** + * Address label shown next to an address QR code. + */ + +#ifndef ADDRESS_LABEL_H +#define ADDRESS_LABEL_H + +#include "lvgl.h" + +/** + * Create a wrapped, centered label showing `address` in 4-char blocks with + * alternating primary/highlight colors. Tapping it cycles the display through + * 4-char blocks, 6-char blocks and the plain address. The label keeps its own + * copy of `address`. The caller sets the width. + * + * @param parent Parent LVGL object + * @param address Address to display + * @return The label object + */ +lv_obj_t *address_label_create(lv_obj_t *parent, const char *address); + +#endif // ADDRESS_LABEL_H diff --git a/main/ui/menu.h b/main/ui/menu.h index 7926c321..0c4c3a2b 100644 --- a/main/ui/menu.h +++ b/main/ui/menu.h @@ -6,7 +6,9 @@ #include #include -#define UI_MENU_MAX_ENTRIES 20 +// Covers the Session Descriptors list: every registry entry and silent +// payment alias +#define UI_MENU_MAX_ENTRIES 32 typedef void (*ui_menu_callback_t)(void); typedef void (*ui_menu_action_callback_t)(int index); 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..6e557eb1 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -49,13 +49,14 @@ set(WALLY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../components/libwally-core) add_library(wally STATIC ${WALLY_DIR}/kern_wally.c ../components/secure_memory/secret_alloc.c - ${WALLY_DIR}/upstream/src/amalgamation/combined.c + ${WALLY_DIR}/kern_combined.c ) set_target_properties(wally PROPERTIES POSITION_INDEPENDENT_CODE ON) target_include_directories(wally PUBLIC ../components/secure_memory/include ${WALLY_DIR} ${WALLY_DIR}/upstream/include + ${WALLY_DIR}/upstream/src/secp256k1/include ) target_include_directories(wally PRIVATE @@ -68,8 +69,6 @@ target_include_directories(wally PRIVATE target_compile_definitions(wally PRIVATE BUILD_MINIMAL=1 - # Standard libsecp256k1: drops MuSig2 + ecdsa-s2c/anti-exfil (unused by Kern). - BUILD_STANDARD_SECP=1 ECMULT_WINDOW_SIZE=8 ) @@ -156,6 +155,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 @@ -168,6 +168,7 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/dice_mnemonic.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/base43.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/descriptor_validator.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/descriptor_keys.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/miniscript_policy.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/multisig_setup.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/key.c @@ -175,6 +176,8 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/bip322.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/psbt.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/psbt_gate.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/musig_psbt.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/nonce_cache.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/psbt_parse.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/ss_whitelist.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/registry.c @@ -182,6 +185,7 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/bip138_keys.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/bip138_backup.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/descriptor_checksum.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/musig_leaves.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/bip32_path.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/script_templates.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/address_match.c @@ -190,6 +194,9 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/secp_hardening.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/crypto_init.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/self_test.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/dleq.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/silent_payments.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/sp_psbt.c # Shared zlib adapter used by KEF and BBQr ${CMAKE_CURRENT_SOURCE_DIR}/../components/deflate_codec/src/deflate_codec.c # bbqr (multi-part QR encoding) @@ -199,6 +206,7 @@ set(APP_CORE_SOURCES # --- UI components --- set(APP_UI_SOURCES + ${APP_UI_DIR}/address_label.c ${APP_UI_DIR}/dialog.c ${APP_UI_DIR}/dropdown_page.c ${APP_UI_DIR}/input_helpers.c @@ -303,6 +311,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 +383,24 @@ target_link_libraries(lvgl PUBLIC ${SDL2_LIBRARIES} ) +# --- kern-bipqr: the firmware's Rust staticlib, built for the host. The +# MuSig2 signer reaches its nonce cache sessions 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 +437,9 @@ 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 and bip_nonces_cache submodules + ${CMAKE_CURRENT_SOURCE_DIR}/../components/bipqr/upstream/bipqr-ll/include + ${CMAKE_CURRENT_SOURCE_DIR}/../components/bip_nonces_cache/upstream/bip-nonces-cache-ll/include # LVGL ${LVGL_DIR} ${LVGL_DIR}/src @@ -432,6 +463,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 +504,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/platform/video_sim/video_sim.c b/simulator/platform/video_sim/video_sim.c index 7f5c6822..957ee776 100644 --- a/simulator/platform/video_sim/video_sim.c +++ b/simulator/platform/video_sim/video_sim.c @@ -27,6 +27,9 @@ static const char *TAG = "VIDEO_SIM"; +// Frames each --qr-dir image stays on, so a multi-part QR animates +#define QR_DIR_FRAMES_PER_IMAGE 12 + static app_video_frame_operation_cb_t s_frame_cb = NULL; static uint8_t *s_frame_buf = NULL; static uint32_t s_width = 800; @@ -85,6 +88,10 @@ static uint8_t *alloc_blank_rgb565(uint32_t w, uint32_t h, size_t *out_size) { return buf; } +static int compare_names(const void *a, const void *b) { + return strcmp(*(char *const *)a, *(char *const *)b); +} + static uint8_t *load_next_dir_rgb565(uint32_t *out_w, uint32_t *out_h, size_t *out_size) { if (!s_qr_image_dir) @@ -122,7 +129,9 @@ static uint8_t *load_next_dir_rgb565(uint32_t *out_w, uint32_t *out_h, } entries = tmp; } - entries[count++] = strdup(name); + char *copy = strdup(name); + if (copy) + entries[count++] = copy; } closedir(dir); @@ -131,6 +140,7 @@ static uint8_t *load_next_dir_rgb565(uint32_t *out_w, uint32_t *out_h, free(entries); return NULL; } + qsort(entries, count, sizeof(*entries), compare_names); size_t pick = s_qr_dir_index % count; s_qr_dir_index++; @@ -206,6 +216,7 @@ static esp_err_t load_configured_frame(bool rotate_dir) { static void *stream_thread_func(void *arg) { (void)arg; + unsigned frames = 0; while (s_streaming) { #ifdef SIM_WEBCAM if (s_webcam && s_frame_buf) { @@ -218,7 +229,11 @@ static void *stream_thread_func(void *arg) { #ifdef SIM_WEBCAM if (!s_webcam) #endif + { + if (s_qr_image_dir && ++frames % QR_DIR_FRAMES_PER_IMAGE == 0) + load_configured_frame(true); usleep(33333); + } } return NULL; } 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"); }