From c4d17bbade6d53d4771004a36530b8606b4a73aa Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 6 Sep 2026 16:19:49 +0000 Subject: [PATCH 01/13] feat(psbt): sign a taptree input with every key the coordinator lists --- components/libwally-core/upstream | 2 +- main/core/psbt.c | 147 ++++++++++++--- main/core/test/test_psbt_classify.c | 279 ++++++++++++++++++++++++++++ 3 files changed, 397 insertions(+), 31 deletions(-) diff --git a/components/libwally-core/upstream b/components/libwally-core/upstream index a39fc8cd..b1a55a7c 160000 --- a/components/libwally-core/upstream +++ b/components/libwally-core/upstream @@ -1 +1 @@ -Subproject commit a39fc8cde1447a7ba9394e39532e518146e89484 +Subproject commit b1a55a7cb575093c30d24052ee138095a665b769 diff --git a/main/core/psbt.c b/main/core/psbt.c index 0d1dc1e8..959b3501 100644 --- a/main/core/psbt.c +++ b/main/core/psbt.c @@ -956,6 +956,66 @@ static void apply_signer_modifiable_rules(struct wally_psbt *psbt) { ESP_LOGW(TAG, "Failed to clear tx-modifiable flags after signing"); } +/* One derivation this wallet is asked to sign an input with. */ +typedef struct { + uint32_t path[MAX_KEYPATH_TOTAL_DEPTH]; + size_t path_len; +} signing_path_t; + +/* The internal key plus the leaves one wallet realistically sits in. */ +#define MAX_SIGNING_PATHS_PER_INPUT 8 + +/* Collect every distinct derivation the coordinator asked this wallet to sign + * input `i` with. A taproot input names our keys in + * PSBT_IN_TAP_BIP32_DERIVATION, one entry per key: the internal key, and the + * key in each leaf we sit in. All of them are wanted, so the caller signs with + * each rather than picking one. + * + * A key in several leaves is still one entry, and libwally signs every leaf it + * lists in one pass, so one derivation covers it. + * + * Returns false when the input is malformed, in which case nothing may be + * signed. Writes no paths for a non-taproot input, leaving the caller to fall + * back to the path its classification produced. */ +static bool collect_taproot_signing_paths(const struct wally_psbt *psbt, + size_t i, const unsigned char *our_fp, + signing_path_t *out, size_t cap, + size_t *out_count) { + const struct wally_map *tp_paths = &psbt->inputs[i].taproot_leaf_paths; + + *out_count = 0; + for (size_t j = 0; j < tp_paths->num_items; j++) { + const struct wally_map_item *item = &tp_paths->items[j]; + signing_path_t candidate = {0}; + + if (!keypath_matches_fingerprint(item->value, item->value_len, our_fp)) + continue; + if (!bip32_path_from_keypath(item->value, item->value_len, candidate.path, + &candidate.path_len, MAX_KEYPATH_TOTAL_DEPTH)) + continue; + + for (size_t k = 0; k < *out_count; k++) { + if (out[k].path_len != candidate.path_len || + memcmp(out[k].path, candidate.path, + candidate.path_len * sizeof(candidate.path[0])) != 0) + continue; + /* A path derives exactly one key, so two entries claiming it name two + * different keys for one private key. Signing either would be picking + * for an attacker, so refuse the whole PSBT. */ + ESP_LOGE(TAG, "Input %zu names two keys on one derivation path", i); + return false; + } + + if (*out_count == cap) { + ESP_LOGE(TAG, "Input %zu asks for more than %zu signing keys", i, cap); + return false; + } + out[(*out_count)++] = candidate; + } + + return true; +} + size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, psbt_sign_policy_t policy, psbt_sign_result_t *result) { if (result) @@ -980,12 +1040,26 @@ size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, size_t signatures_added = 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)) { + signing_path_t probe[MAX_SIGNING_PATHS_PER_INPUT]; + size_t probe_count = 0; + /* Reject a malformed input here rather than in the signing loop, so a + * refusal hands the PSBT back with nothing signed. */ + if (!collect_taproot_signing_paths(psbt, i, our_fp, probe, + MAX_SIGNING_PATHS_PER_INPUT, + &probe_count)) + goto cleanup; signable_any = true; plan[i].sig_baseline = input_signature_count(psbt, i); continue; @@ -1009,44 +1083,57 @@ size_t psbt_sign(struct wally_psbt *psbt, bool is_testnet, if (plan[i].denied) continue; - const uint32_t *path = NULL; - size_t path_len = 0; - uint32_t raw_comps[MAX_KEYPATH_TOTAL_DEPTH]; + signing_path_t paths[MAX_SIGNING_PATHS_PER_INPUT]; + size_t num_paths = 0; - if (ownership.ownership == PSBT_OWNERSHIP_OWNED_SAFE) { - path = ownership.claim.derived_path; - path_len = ownership.claim.derived_path_len; - } else { - /* OWNED_UNSAFE / EXPECTED_OWNED — policy already vetted above; derive - * from the raw path supplied in the PSBT. */ - if (!bip32_path_from_keypath(ownership.raw_keypath, - ownership.raw_keypath_len, raw_comps, - &path_len, MAX_KEYPATH_TOTAL_DEPTH)) + /* Already validated in the classify pass, so this cannot fail here. */ + if (!collect_taproot_signing_paths(psbt, i, our_fp, paths, + MAX_SIGNING_PATHS_PER_INPUT, &num_paths)) + continue; + + if (num_paths == 0) { + /* Not a taproot input: the single path its classification produced. + * OWNED_UNSAFE / EXPECTED_OWNED were vetted by the policy above, so + * derive from the raw path the PSBT supplied. */ + if (ownership.ownership == PSBT_OWNERSHIP_OWNED_SAFE) { + memcpy(paths[0].path, ownership.claim.derived_path, + sizeof(paths[0].path)); + paths[0].path_len = ownership.claim.derived_path_len; + } else if (!bip32_path_from_keypath(ownership.raw_keypath, + ownership.raw_keypath_len, + paths[0].path, &paths[0].path_len, + MAX_KEYPATH_TOTAL_DEPTH)) { continue; - path = raw_comps; - } + } - if (!path || path_len > MAX_KEYPATH_TOTAL_DEPTH) { - ESP_LOGE(TAG, "Invalid signing path for input %zu", i); - continue; + /* An empty path derives the master key itself, which signs nothing we + * classified. */ + if (!paths[0].path_len || paths[0].path_len > MAX_KEYPATH_TOTAL_DEPTH) { + ESP_LOGE(TAG, "Invalid signing path for input %zu", i); + continue; + } + num_paths = 1; } - struct ext_key *derived_key = NULL; - if (!key_get_derived_key_components(path, path_len, &derived_key)) { - ESP_LOGE(TAG, "Failed to derive key for input %zu", i); - continue; - } + for (size_t p = 0; p < num_paths; p++) { + struct ext_key *derived_key = NULL; + if (!key_get_derived_key_components(paths[p].path, paths[p].path_len, + &derived_key)) { + ESP_LOGE(TAG, "Failed to derive key for input %zu", i); + continue; + } - plan[i].attempted = true; + plan[i].attempted = true; - int ret = wally_psbt_sign(psbt, derived_key->priv_key + 1, - EC_PRIVATE_KEY_LEN, EC_FLAG_GRIND_R); - bip32_key_free(derived_key); + int ret = wally_psbt_sign(psbt, derived_key->priv_key + 1, + EC_PRIVATE_KEY_LEN, EC_FLAG_GRIND_R); + bip32_key_free(derived_key); - if (ret == WALLY_OK) { - signatures_added++; - } else { - ESP_LOGE(TAG, "Failed to sign input %zu: %d", i, ret); + if (ret == WALLY_OK) { + signatures_added++; + } else { + ESP_LOGE(TAG, "Failed to sign input %zu: %d", i, ret); + } } } diff --git a/main/core/test/test_psbt_classify.c b/main/core/test/test_psbt_classify.c index 4ad54a44..3c3d1601 100644 --- a/main/core/test/test_psbt_classify.c +++ b/main/core/test/test_psbt_classify.c @@ -5,6 +5,7 @@ #include /* Wally types needed by stubs */ +#include #include #include #include @@ -2466,6 +2467,281 @@ static void test_psbt_classify_multi_input_mixed(void) { * 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 * names the key input 0 signs with, so wally_psbt_sign() reaches it. */ +/* ================================================================ + * 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/*))" + +/* 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. */ +/* 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; +} + +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(); +} + static void test_psbt_sign_denied_input_keeps_no_signature(void) { TEST("psbt_sign: denied input naming our key keeps no signature"); @@ -2795,6 +3071,9 @@ int main(void) { test_psbt_sign_gate_expected_blocked(); test_psbt_sign_gate_external_always_skipped(); test_psbt_classify_multi_input_mixed(); + 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(); From 53be6d56a9c3f03ec1453c40c8d175428571669e Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Mon, 24 Aug 2026 17:07:00 +0000 Subject: [PATCH 02/13] feat(bwk): add airgap QR protocol --- .gitignore | 2 + .gitmodules | 5 +- .justfile | 12 + components/bbqr/src/bbqr.c | 176 ++- components/bbqr/src/bbqr.h | 17 + components/bbqr/test/test_bbqr.c | 79 ++ components/bwk | 1 + components/bwk_codecs/CMakeLists.txt | 35 + components/bwk_codecs/Cargo.lock | 14 + components/bwk_codecs/Cargo.toml | 16 + components/bwk_codecs/dummy.c | 1 + components/bwk_codecs/src/lib.rs | 41 + components/bwk_codecs/strip_c_builtins.cmake | 13 + main/CMakeLists.txt | 7 +- main/core/debug_log.c | 97 ++ main/core/debug_log.h | 18 + main/core/descriptor_validator.c | 51 +- main/core/descriptor_validator.h | 6 + main/core/key.c | 58 +- main/core/key.h | 3 + main/core/registry.c | 32 + main/core/registry.h | 3 + main/core/test/Makefile | 6 +- main/core/test/stubs/debug_log_stub.c | 4 + main/core/test/test_descriptor_validator.c | 29 + main/core/test/test_ss_whitelist_regen.c | 33 + main/main.c | 2 + main/pages/bip_flow/bip_flow.c | 1011 +++++++++++++++++ main/pages/bip_flow/bip_flow.h | 19 + main/pages/bip_flow/test/Makefile | 19 + main/pages/bip_flow/test/stubs/lvgl.h | 4 + .../bip_flow/test/test_bip_flow_register.c | 44 + main/pages/home/home.c | 19 +- main/pages/login/login_scan.c | 30 + main/pages/scan/scan.c | 43 + main/pages/scan/scan.h | 16 + main/pages/scan/scan_internal.h | 6 + main/pages/scan/scan_psbt_sign.c | 24 +- main/pages/shared/descriptor_loader.c | 111 ++ main/pages/shared/descriptor_loader.h | 8 + main/qr/export.c | 15 + main/qr/export.h | 3 + main/qr/parser.c | 34 +- main/qr/test/test_parser.c | 49 + main/qr/viewer.c | 31 +- main/qr/viewer.h | 11 + scripts/test.sh | 3 + 47 files changed, 2175 insertions(+), 86 deletions(-) create mode 160000 components/bwk create mode 100644 components/bwk_codecs/CMakeLists.txt create mode 100644 components/bwk_codecs/Cargo.lock create mode 100644 components/bwk_codecs/Cargo.toml create mode 100644 components/bwk_codecs/dummy.c create mode 100644 components/bwk_codecs/src/lib.rs create mode 100644 components/bwk_codecs/strip_c_builtins.cmake create mode 100644 main/core/debug_log.c create mode 100644 main/core/debug_log.h create mode 100644 main/core/test/stubs/debug_log_stub.c create mode 100644 main/pages/bip_flow/bip_flow.c create mode 100644 main/pages/bip_flow/bip_flow.h create mode 100644 main/pages/bip_flow/test/Makefile create mode 100644 main/pages/bip_flow/test/stubs/lvgl.h create mode 100644 main/pages/bip_flow/test/test_bip_flow_register.c diff --git a/.gitignore b/.gitignore index 734f2b2f..bbf1e4e7 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ sdkconfig sdkconfig.old managed_components/ compile_commands.json +**/target/ # Release release/ @@ -58,6 +59,7 @@ 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 # IDE / tools .vscode/ diff --git a/.gitmodules b/.gitmodules index 14d21d6c..03bb41d3 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "components/libwally-core/upstream"] path = components/libwally-core/upstream - url = https://github.com/odudex/libwally-core.git + url = https://github.com/ws-plaude/libwally-core.git [submodule "components/cUR"] path = components/cUR url = https://github.com/odudex/cUR.git @@ -10,3 +10,6 @@ [submodule "components/bip138"] path = components/bip138 url = https://github.com/odudex/bip138.git +[submodule "components/bwk"] + path = components/bwk + url = https://github.com/ws-plaude/bwk.git diff --git a/.justfile b/.justfile index c141d188..ef770b6f 100644 --- a/.justfile +++ b/.justfile @@ -49,12 +49,23 @@ 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 test: ./scripts/test.sh +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 rm -fRd build_*_v3 @@ -68,6 +79,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..7ca3d059 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 bwk-qr-protocol 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/bwk b/components/bwk new file mode 160000 index 00000000..dd803aea --- /dev/null +++ b/components/bwk @@ -0,0 +1 @@ +Subproject commit dd803aeabdb77e150c236f8cb255cc0ce4dcc6d6 diff --git a/components/bwk_codecs/CMakeLists.txt b/components/bwk_codecs/CMakeLists.txt new file mode 100644 index 00000000..87f58956 --- /dev/null +++ b/components/bwk_codecs/CMakeLists.txt @@ -0,0 +1,35 @@ +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_bwk_codecs.a) + +idf_component_register( + SRCS "dummy.c" + INCLUDE_DIRS + "../bwk/qr-protocol/include" +) + +find_program(CARGO_EXECUTABLE cargo REQUIRED) + +add_custom_command( + OUTPUT ${RUST_LIB} + 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 + DEPENDS + ${CMAKE_CURRENT_LIST_DIR}/Cargo.toml + ${CMAKE_CURRENT_LIST_DIR}/src/lib.rs + ${CMAKE_CURRENT_LIST_DIR}/strip_c_builtins.cmake + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMENT "Building bwk codec Rust staticlib" + VERBATIM +) + +add_custom_target(bwk_codecs_rust DEPENDS ${RUST_LIB}) +add_library(bwk_codecs_static STATIC IMPORTED GLOBAL) +set_target_properties(bwk_codecs_static PROPERTIES IMPORTED_LOCATION ${RUST_LIB}) +add_dependencies(bwk_codecs_static bwk_codecs_rust) +add_dependencies(${COMPONENT_LIB} bwk_codecs_static) +target_link_libraries(${COMPONENT_LIB} INTERFACE bwk_codecs_static) diff --git a/components/bwk_codecs/Cargo.lock b/components/bwk_codecs/Cargo.lock new file mode 100644 index 00000000..0e65af9b --- /dev/null +++ b/components/bwk_codecs/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bwk-qr-protocol" +version = "0.0.1" + +[[package]] +name = "kern-bwk-codecs" +version = "0.1.0" +dependencies = [ + "bwk-qr-protocol", +] diff --git a/components/bwk_codecs/Cargo.toml b/components/bwk_codecs/Cargo.toml new file mode 100644 index 00000000..fd62b928 --- /dev/null +++ b/components/bwk_codecs/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "kern-bwk-codecs" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["staticlib"] + +[dependencies] +bwk-qr-protocol = { path = "../bwk/qr-protocol", features = ["ffi"] } + +[profile.dev] +panic = "abort" + +[profile.release] +panic = "abort" diff --git a/components/bwk_codecs/dummy.c b/components/bwk_codecs/dummy.c new file mode 100644 index 00000000..4f990009 --- /dev/null +++ b/components/bwk_codecs/dummy.c @@ -0,0 +1 @@ +/* ESP-IDF requires a component source file; the symbols come from Rust. */ diff --git a/components/bwk_codecs/src/lib.rs b/components/bwk_codecs/src/lib.rs new file mode 100644 index 00000000..6d88bac2 --- /dev/null +++ b/components/bwk_codecs/src/lib.rs @@ -0,0 +1,41 @@ +#![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 bwk_qr_protocol::ffi::*; + +#[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/bwk_codecs/strip_c_builtins.cmake b/components/bwk_codecs/strip_c_builtins.cmake new file mode 100644 index 00000000..6b5395b2 --- /dev/null +++ b/components/bwk_codecs/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/main/CMakeLists.txt b/main/CMakeLists.txt index 21e22090..7e86f121 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,6 +1,7 @@ file(GLOB_RECURSE SOURCES "*.c") -list(FILTER SOURCES EXCLUDE REGEX ".*/core/test/.*") -list(FILTER SOURCES EXCLUDE REGEX ".*/qr/test/.*") +list(APPEND SOURCES "${CMAKE_CURRENT_LIST_DIR}/core/debug_log.c") +list(REMOVE_DUPLICATES SOURCES) +list(FILTER SOURCES EXCLUDE REGEX ".*/test/.*") # Select touch driver based on board if(CONFIG_KERN_BOARD_WAVE_4B) @@ -34,7 +35,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 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 bwk_codecs esp_driver_ppa app_update bootloader_support secure_memory bsp_common bus_timeout ) diff --git a/main/core/debug_log.c b/main/core/debug_log.c new file mode 100644 index 00000000..e1d858e0 --- /dev/null +++ b/main/core/debug_log.c @@ -0,0 +1,97 @@ +#include "debug_log.h" + +#include "storage.h" + +#include +#include +#include +#include +#include +#include +#include + +static const char *TAG = "debug_log"; +static const size_t DEBUG_LOG_MAX_BYTES = 8192; + +static esp_err_t trim_if_needed(void) { + struct stat st; + if (stat(DEBUG_LOG_FLASH_PATH, &st) != 0 || st.st_size < 0 || + (size_t)st.st_size <= DEBUG_LOG_MAX_BYTES) + return ESP_OK; + + FILE *f = fopen(DEBUG_LOG_FLASH_PATH, "rb"); + if (!f) + return ESP_FAIL; + + size_t keep = DEBUG_LOG_MAX_BYTES / 2; + if (fseek(f, st.st_size - (long)keep, SEEK_SET) != 0) { + fclose(f); + return ESP_FAIL; + } + + char buf[4096]; + size_t nread = fread(buf, 1, sizeof(buf), f); + fclose(f); + + f = fopen(DEBUG_LOG_FLASH_PATH, "wb"); + if (!f) + return ESP_FAIL; + + const char *prefix = "--- debug log trimmed ---\n"; + size_t expected = strlen(prefix) + nread; + size_t written = fwrite(prefix, 1, strlen(prefix), f); + written += fwrite(buf, 1, nread, f); + fclose(f); + return written == expected ? ESP_OK : ESP_FAIL; +} + +esp_err_t debug_log_init(void) { return storage_init(); } + +esp_err_t debug_log_clear(void) { + esp_err_t ret = storage_init(); + if (ret != ESP_OK) + return ret; + unlink(DEBUG_LOG_FLASH_PATH); + return ESP_OK; +} + +void debug_logf(const char *fmt, ...) { + if (!fmt || storage_init() != ESP_OK) + return; + + if (trim_if_needed() != ESP_OK) + ESP_LOGW(TAG, "failed to trim debug log"); + + FILE *f = fopen(DEBUG_LOG_FLASH_PATH, "ab"); + if (!f) + return; + + fprintf(f, "%lld ", (long long)esp_timer_get_time()); + + va_list ap; + va_start(ap, fmt); + vfprintf(f, fmt, ap); + va_end(ap); + fputc('\n', f); + fclose(f); +} + +void debug_log_event(const char *event) { debug_logf("%s", event); } + +void debug_log_hex_preview(const char *label, const uint8_t *data, size_t len, + size_t preview_len) { + if (!label) + return; + + char hex[65]; + size_t n = len < preview_len ? len : preview_len; + if (n > sizeof(hex) / 2) + n = sizeof(hex) / 2; + + for (size_t i = 0; i < n; i++) + snprintf(hex + i * 2, sizeof(hex) - i * 2, "%02X", data ? data[i] : 0); + hex[n * 2] = '\0'; + + debug_logf("%s len=%u preview=%s%s", label, (unsigned)len, hex, + len > n ? "..." : ""); +} diff --git a/main/core/debug_log.h b/main/core/debug_log.h new file mode 100644 index 00000000..236e7ec8 --- /dev/null +++ b/main/core/debug_log.h @@ -0,0 +1,18 @@ +#ifndef DEBUG_LOG_H +#define DEBUG_LOG_H + +#include "esp_err.h" + +#include +#include + +#define DEBUG_LOG_FLASH_PATH "/spiffs/debug.log" + +esp_err_t debug_log_init(void); +esp_err_t debug_log_clear(void); +void debug_log_event(const char *event); +void debug_logf(const char *fmt, ...); +void debug_log_hex_preview(const char *label, const uint8_t *data, size_t len, + size_t preview_len); + +#endif /* DEBUG_LOG_H */ diff --git a/main/core/descriptor_validator.c b/main/core/descriptor_validator.c index 7d4635fc..0cee9cef 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 @@ -36,7 +37,8 @@ typedef struct { void *user_data; descriptor_info_t info; 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) */ @@ -458,6 +460,8 @@ static bool extract_descriptor_info(struct wally_descriptor *descriptor, 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; @@ -465,7 +469,8 @@ static void id_loc_proceed(const char *id, storage_location_t loc, complete_validation(VALIDATION_USER_DECLINED); return; } - if (!registry_add_from_string(id, current_ctx->descriptor_str, loc, true)) { + if (!registry_persist_or_add_from_string(id, current_ctx->descriptor_str, + loc)) { ESP_LOGE(TAG, "Failed to register descriptor '%s'", id); complete_validation(VALIDATION_INTERNAL_ERROR); return; @@ -542,6 +547,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; @@ -554,9 +560,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(); } @@ -870,6 +878,41 @@ void descriptor_validate_and_load(const char *descriptor_str, verify_xpub_and_show_info(descriptor, key_index); } +void descriptor_validate_and_load_persistent( + const char *descriptor_str, validation_complete_cb callback, + validation_confirm_cb confirm_cb, + validation_info_confirm_cb info_confirm_cb, validation_id_loc_cb id_loc_cb, + void *user_data) { + if (descriptor_str && callback && + (!key_is_loaded() || !wallet_is_initialized())) { + cleanup_context(); + callback(VALIDATION_INTERNAL_ERROR, user_data); + return; + } + + struct wally_descriptor *descriptor = NULL; + if (validation_begin(descriptor_str, callback, info_confirm_cb, user_data, + &descriptor) != VALIDATION_SUCCESS) + return; + + current_ctx->confirm_cb = confirm_cb; + current_ctx->id_loc_cb = id_loc_cb; + current_ctx->force_persistent = true; + + int key_index = find_matching_key_index(descriptor); + if (key_index < 0) { + ESP_LOGE(TAG, "Wallet fingerprint not found in descriptor"); + wally_descriptor_free(descriptor); + complete_validation(VALIDATION_FINGERPRINT_NOT_FOUND); + return; + } + + if (!checksum_and_dedup(descriptor)) + return; + + verify_xpub_and_show_info(descriptor, key_index); +} + // Watch-only: extract info and show the "Load?" dialog, skipping the xpub // verification and PSB warning that the keyed path performs. static void watch_only_show_info(struct wally_descriptor *descriptor) { diff --git a/main/core/descriptor_validator.h b/main/core/descriptor_validator.h index 130f61b0..67388886 100644 --- a/main/core/descriptor_validator.h +++ b/main/core/descriptor_validator.h @@ -119,6 +119,12 @@ void descriptor_validate_and_load(const char *descriptor_str, validation_id_loc_cb id_loc_cb, void *user_data); +void descriptor_validate_and_load_persistent( + const char *descriptor_str, validation_complete_cb callback, + validation_confirm_cb confirm_cb, + validation_info_confirm_cb info_confirm_cb, validation_id_loc_cb id_loc_cb, + void *user_data); + /* Infer a descriptor's network by trying to parse it as mainnet, then testnet. * Writes the network to *network_out and returns true on success; returns false * if the descriptor parses on neither (xpub keys parse only on mainnet, tpub diff --git a/main/core/key.c b/main/core/key.c index b681fbea..4932a712 100644 --- a/main/core/key.c +++ b/main/core/key.c @@ -121,6 +121,38 @@ bool key_get_fingerprint_hex(char *hex_out) { return true; } +static uint32_t xpub_version_for_path(const uint32_t *path, size_t path_depth) { + if (path && path_depth >= 2) { + 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) { @@ -182,10 +214,32 @@ 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 > KEY_MAX_DERIVATION_DEPTH || + !xpub_out) { + return false; + } + + 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 55f37126..517b2eab 100644 --- a/main/core/key.h +++ b/main/core/key.h @@ -32,6 +32,9 @@ key_mnemonic_passphrase_fingerprint_hex(const char *mnemonic, /* On success, *xpub_out is heap-allocated and must be freed by the caller * with wally_free_string(). Public-only -- safe to log. */ KERN_WARN_UNUSED_RESULT bool key_get_xpub(const char *path, char **xpub_out); +KERN_WARN_UNUSED_RESULT bool key_get_xpub_components(const uint32_t *path, + size_t path_depth, + char **xpub_out); KERN_WARN_UNUSED_RESULT bool key_get_master_xpub(char **xpub_out); /* On success, *mnemonic_out is a heap-allocated copy of the active mnemonic. diff --git a/main/core/registry.c b/main/core/registry.c index 0b9c6df0..912fb9fb 100644 --- a/main/core/registry.c +++ b/main/core/registry.c @@ -419,6 +419,38 @@ bool registry_persist(const char *id, const char *name) { return true; } +bool registry_persist_or_add_from_string(const char *id, + const char *descriptor_str, + storage_location_t loc) { + if (!id || !descriptor_str) + return false; + + for (size_t i = 0; i < registry_len; i++) { + if (strncmp(registry_entries[i].id, id, REGISTRY_ID_MAX_LEN) != 0) + continue; + struct wally_descriptor *desc = NULL; + uint32_t wally_network = (wallet_get_network() == WALLET_NETWORK_MAINNET) + ? WALLY_NETWORK_BITCOIN_MAINNET + : WALLY_NETWORK_BITCOIN_TESTNET; + if (wallet_descriptor_parse(descriptor_str, NULL, wally_network, &desc) != + WALLY_OK) + return false; + char existing_checksum[9]; + char new_checksum[9]; + bool same = registry_entries[i].desc && + descriptor_checksum_from_descriptor(registry_entries[i].desc, + existing_checksum) && + descriptor_checksum_from_descriptor(desc, new_checksum) && + strcmp(existing_checksum, new_checksum) == 0; + wally_descriptor_free(desc); + if (!same) + return false; + return registry_entries[i].persisted || registry_persist(id, id); + } + + return registry_add_from_string(id, descriptor_str, loc, true); +} + 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 140c6c29..3ed16208 100644 --- a/main/core/registry.h +++ b/main/core/registry.h @@ -42,6 +42,9 @@ KERN_WARN_UNUSED_RESULT bool registry_deregister_at(size_t index); KERN_WARN_UNUSED_RESULT bool registry_add_from_string(const char *id, const char *descriptor_str, storage_location_t loc, bool persist); +KERN_WARN_UNUSED_RESULT bool +registry_persist_or_add_from_string(const char *id, const char *descriptor_str, + storage_location_t loc); /* Register a session entry: writes its BIP138 backup to flash under `name`, * then renames and labels the entry. Registered descriptors load automatically diff --git a/main/core/test/Makefile b/main/core/test/Makefile index 8736fa78..da46d0df 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -77,6 +77,8 @@ SCRIPT_TEMPLATE_SRC = ../script_templates.c ../script_templates.h REGISTRY_STUB_SRC = stubs/registry_stub.c REGISTRY_PERSIST_STUB_SRC = stubs/registry_persist_stub.c VALIDATOR_KEYED_STUB_SRC = stubs/validator_keyed_stub.c +# debug_logf writes to device storage, never host-linkable +DEBUG_LOG_STUB_SRC = stubs/debug_log_stub.c SRCS_REG_PARSE = test_registry_parse.c TARGET_REG_PARSE = test_registry_parse @@ -221,11 +223,11 @@ $(TARGET_FW_UPDATE): $(SRCS_FW_UPDATE) $(FW_UPDATE_SRC) $(wildcard stubs/*.h) # The host compiler flags the %zu session-id suffix as truncatable; the # firmware build carries -Wno-format for the same reason. -$(TARGET_DESC_VALIDATOR): $(SRCS_DESC_VALIDATOR) $(DESC_VALIDATOR_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SS_SRC) $(LIBWALLY) +$(TARGET_DESC_VALIDATOR): $(SRCS_DESC_VALIDATOR) $(DESC_VALIDATOR_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SS_SRC) $(DEBUG_LOG_STUB_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -Wno-format-truncation -o $@ $(SRCS_DESC_VALIDATOR) \ ../descriptor_validator.c ../wallet.c ../key.c ../registry.c $(REGISTRY_PERSIST_STUB_SRC) \ ../descriptor_checksum.c ../bip32_path.c ../script_templates.c \ - ../ss_whitelist.c ../miniscript_policy.c $(LIBWALLY) + ../ss_whitelist.c ../miniscript_policy.c $(DEBUG_LOG_STUB_SRC) $(LIBWALLY) # 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. 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/test_descriptor_validator.c b/main/core/test/test_descriptor_validator.c index 27feb71f..cd673c11 100644 --- a/main/core/test/test_descriptor_validator.c +++ b/main/core/test/test_descriptor_validator.c @@ -152,6 +152,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) { @@ -579,6 +588,25 @@ static void test_dedup(void) { registry_clear(); } +/* descriptor_validate_and_load_persistent() forces the registration path that + * DESCRIPTOR_PERSISTENT_REGISTRATION_ENABLED gates off, so a duplicate must + * still be caught before that path is entered. */ +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 duplicate completes without descriptor review", + done_result == VALIDATION_DUPLICATE && info_calls == 0); + check("persistent duplicate does not request storage id", id_loc_calls == 0); + check("persistent duplicate does not append registry entry", + registry_count() == 1); + registry_clear(); +} + static void test_generation_guard(void) { registry_clear(); capture_reset(); @@ -712,6 +740,7 @@ int main(void) { test_taproot_keypath(); test_network(); test_dedup(); + test_persistent_registration(); test_generation_guard(); test_watch_only(); diff --git a/main/core/test/test_ss_whitelist_regen.c b/main/core/test/test_ss_whitelist_regen.c index b9729ce0..73170d3d 100644 --- a/main/core/test/test_ss_whitelist_regen.c +++ b/main/core/test/test_ss_whitelist_regen.c @@ -4,6 +4,7 @@ #include "core/key.h" #include "core/ss_whitelist.h" +#include static int tests_passed = 0; static int tests_failed = 0; @@ -90,6 +91,23 @@ static void test_address(const char *name, ss_script_type_t script, PASS(); } +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) { printf("=== ss_whitelist regen tests ===\n\n"); @@ -135,6 +153,21 @@ int main(void) { key_unload(); + printf("\n--- Group 4: xpub version follows requested coin type ---\n"); + { + TEST("key_load_from_mnemonic testnet"); + if (!key_load_from_mnemonic(TEST_MNEMONIC, "", true)) { + FAIL("failed to load testnet mnemonic"); + } else { + PASS(); + test_xpub_prefix("testnet seed exports xpub for coin 0'", + "m/48'/0'/0'/2'", "xpub"); + test_xpub_prefix("testnet seed exports tpub for coin 1'", + "m/48'/1'/0'/2'", "tpub"); + key_unload(); + } + } + printf("\n=== Results: %d passed, %d failed ===\n", tests_passed, tests_failed); return tests_failed > 0 ? 1 : 0; diff --git a/main/main.c b/main/main.c index 77f42e4f..50e10dc8 100644 --- a/main/main.c +++ b/main/main.c @@ -1,4 +1,5 @@ #include "bus_timeout.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/bip_flow.c b/main/pages/bip_flow/bip_flow.c new file mode 100644 index 00000000..b4bb0004 --- /dev/null +++ b/main/pages/bip_flow/bip_flow.c @@ -0,0 +1,1011 @@ +#include "bip_flow.h" + +#include "../../components/bbqr/src/bbqr.h" +#include "../../core/bip32_path.h" +#include "../../core/debug_log.h" +#include "../../core/key.h" +#include "../../core/psbt.h" +#include "../../core/registry.h" +#include "../../core/settings.h" +#include "../../core/wallet.h" +#include "../../qr/encoder.h" +#include "../../qr/viewer.h" +#include "../../ui/dialog.h" +#include "../../ui/theme.h" +#include "../../ui/theme_widgets.h" +#include "../scan/scan.h" +#include "../shared/address_checker.h" +#include "../shared/descriptor_loader.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + lv_obj_t *parent; + void (*return_cb)(void); + const bwk_qr_request *request; +} bip_flow_ctx_t; + +static bip_flow_ctx_t ctx; +static char *pending_verified_address = NULL; +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; +} + +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) { + if (ctx.request) { + bwk_qr_request_free(ctx.request); + ctx.request = NULL; + } +} + +static void return_from_response(void) { + qr_viewer_page_destroy(); + destroy_verify_address_detail(); + 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_with_done(bwk_qr_response *response, + void (*done_cb)(void)) { + debug_logf("bip_flow show_response is_error=%d", response->is_error); + bwk_qr_buf encoded = {0}; + const char *err = NULL; + int32_t rc = bwk_qr_response_encode(response, &encoded, &err); + if (rc != BWK_QR_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, + settings_get_qr_density()); + bwk_qr_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(bwk_qr_response *response) { + show_response_with_done(response, return_from_response); +} + +static void fill_response_header(bwk_qr_response *response) { + memset(response, 0, sizeof(*response)); + memcpy(response->id, ctx.request->id, BWK_QR_REQUEST_ID_LEN); + response->message_type = ctx.request->message_type; +} + +static void show_error_response(uint8_t error, const char *message) { + debug_logf("bip_flow show_error_response code=%u msg=%s", (unsigned)error, + message ? message : ""); + bwk_qr_response response; + fill_response_header(&response); + response.is_error = true; + response.body.error.error = error; + snprintf(response.body.error.message, sizeof(response.body.error.message), + "%s", message ? message : "Error"); + show_response(&response); +} + +static bool xpub_base58_to_wire(const char *xpub, bwk_qr_xpub *out) { + struct ext_key *key = NULL; + bool ok = false; + if (bip32_key_from_base58_alloc(xpub, &key) == WALLY_OK && key) { + uint8_t serialized[BWK_QR_XPUB_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 void get_xpubs_confirm_cb(bool confirmed, void *user_data) { + (void)user_data; + if (!confirmed) { + show_error_response(BWK_QR_RESPONSE_ERROR_USER_DECLINED, "Declined"); + return; + } + + const bwk_qr_get_xpubs *req = &ctx.request->body.get_xpubs; + size_t n = req->derivation_paths.len; + bwk_qr_xpub *xpubs = calloc(n, sizeof(*xpubs)); + if (!xpubs) { + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "Out of memory"); + return; + } + + for (size_t i = 0; i < n; i++) { + const bwk_qr_path *path = &req->derivation_paths.ptr[i]; + char *xpub = NULL; + if (!key_get_xpub_components(path->ptr, path->len, &xpub) || !xpub || + !xpub_base58_to_wire(xpub, &xpubs[i])) { + if (xpub) + wally_free_string(xpub); + free(xpubs); + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "Xpub failed"); + return; + } + wally_free_string(xpub); + } + + bwk_qr_response response; + fill_response_header(&response); + response.body.xpubs.xpubs.ptr = xpubs; + response.body.xpubs.xpubs.len = n; + if (!key_get_fingerprint(response.body.xpubs.fingerprint)) { + free(xpubs); + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "Fingerprint failed"); + return; + } + snprintf(response.body.xpubs.model, sizeof(response.body.xpubs.model), + "Kern"); + 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); + response.body.xpubs.version.major = (uint16_t)major; + response.body.xpubs.version.minor = (uint16_t)minor; + response.body.xpubs.version.patch = patch; + response.body.xpubs.version.flag = BWK_QR_RELEASE_STABLE; + response.body.xpubs.capabilities = 0x03; + show_response(&response); + free(xpubs); +} + +static bool path_requested_network(const bwk_qr_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_xpubs_network_matches_wallet(const bwk_qr_path_list *paths, + char *message, + size_t message_size) { + if (!paths || !paths->ptr) + return true; + + bool have_network = false; + wallet_network_t requested = WALLET_NETWORK_MAINNET; + for (size_t i = 0; i < paths->len; i++) { + wallet_network_t path_network; + if (!path_requested_network(&paths->ptr[i], &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_xpub_path_range(const bwk_qr_path_list *paths, char *buf, + size_t buf_size) { + if (!paths || paths->len < 2 || !paths->ptr || !buf || buf_size == 0) + return false; + + uint8_t depth = paths->ptr[0].len; + if (depth == 0) + return false; + + int varying_index = -1; + for (uint8_t i = 0; i < depth; i++) { + uint32_t first = paths->ptr[0].ptr[i]; + bool varies = false; + for (size_t j = 1; j < paths->len; j++) { + if (!paths->ptr[j].ptr || paths->ptr[j].len != depth) + return false; + if (paths->ptr[j].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 = paths->ptr[0].ptr[varying_index]; + bool hardened = bip32_path_is_hardened(first); + uint32_t first_child = bip32_path_unharden(first); + for (size_t i = 1; i < paths->len; i++) { + uint32_t component = paths->ptr[i].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)paths->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, paths->ptr[0].ptr[i]); + } + } + + return off < buf_size; +} + +static size_t append_xpub_request_paths(char *msg, size_t msg_size, size_t off, + const bwk_qr_path_list *paths) { + char range_path[128]; + if (format_xpub_path_range(paths, range_path, sizeof(range_path))) + return appendf(msg, msg_size, off, "\n\n%s", range_path); + + size_t shown = paths->len < 6 ? paths->len : 6; + for (size_t i = 0; i < shown && off < msg_size; i++) { + char path[96]; + if (!bip32_path_format(paths->ptr[i].ptr, paths->ptr[i].len, path, + sizeof(path))) { + snprintf(path, sizeof(path), ""); + } + off = appendf(msg, msg_size, off, "\n%s", path); + } + if (paths->len > shown) + off = appendf(msg, msg_size, off, "\n...and %zu more", paths->len - shown); + return off; +} + +static void handle_get_xpubs(void) { + const bwk_qr_get_xpubs *req = &ctx.request->body.get_xpubs; + char mismatch[80]; + if (!get_xpubs_network_matches_wallet(&req->derivation_paths, mismatch, + sizeof(mismatch))) { + debug_logf("bip_flow xpub_network_mismatch msg=%s", mismatch); + show_error_response(BWK_QR_RESPONSE_ERROR_MALFORMED_REQUEST, mismatch); + return; + } + + char msg[512]; + size_t off = snprintf(msg, sizeof(msg), "Export %zu xpub(s)?\n", + req->derivation_paths.len); + append_xpub_request_paths(msg, sizeof(msg), off, &req->derivation_paths); + dialog_show_confirm(msg, get_xpubs_confirm_cb, NULL, DIALOG_STYLE_OVERLAY); +} + +static bool append_bip388_key(char *out, size_t out_size, size_t *off, + const bwk_qr_bip388 *bip388, + unsigned long index) { + if (!bip388 || index >= bip388->keys.len || !bip388->keys.ptr[index]) + return false; + + size_t key_len = strlen(bip388->keys.ptr[index]); + if (*off > out_size || key_len >= out_size - *off) + return false; + + memcpy(out + *off, bip388->keys.ptr[index], key_len); + *off += key_len; + out[*off] = '\0'; + return true; +} + +static char *bip388_to_descriptor(const bwk_qr_bip388 *bip388) { + if (!bip388 || !bip388->policy) + return NULL; + + size_t out_size = strlen(bip388->policy) + 1; + for (size_t i = 0; i < bip388->keys.len; i++) { + if (!bip388->keys.ptr[i]) + return NULL; + out_size += strlen(bip388->keys.ptr[i]); + } + + char *out = malloc(out_size); + if (!out) + return NULL; + + size_t off = 0; + for (const char *p = bip388->policy; *p; p++) { + if (*p != '@') { + if (off + 1 >= out_size) { + free(out); + return NULL; + } + out[off++] = *p; + continue; + } + + p++; + if (*p < '0' || *p > '9') { + free(out); + return NULL; + } + + unsigned long index = 0; + do { + index = index * 10 + (unsigned long)(*p - '0'); + p++; + } while (*p >= '0' && *p <= '9'); + p--; + + if (!append_bip388_key(out, out_size, &off, bip388, index)) { + free(out); + return NULL; + } + } + out[off] = '\0'; + return out; +} + +static char *request_descriptor_alloc(const bwk_qr_descriptor_body *body) { + if (!body) + return NULL; + if (body->tag == BWK_QR_DESCRIPTOR_BIP380) + return body->value.bip380 ? strdup(body->value.bip380) : NULL; + if (body->tag == BWK_QR_DESCRIPTOR_BIP388) + return bip388_to_descriptor(&body->value.bip388); + return NULL; +} + +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 "XPub mismatch - check passphrase"; + 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_SCRIPT: + return "Script too large (max 15 multisig keys)"; + 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"; + } +} + +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); + const bwk_qr_register_descriptor *req = + &ctx.request->body.register_descriptor; + if (result == VALIDATION_USER_DECLINED) { + show_error_response(BWK_QR_RESPONSE_ERROR_USER_DECLINED, "Declined"); + return; + } + + if (!bip_flow_register_validation_result_allows_response(result)) { + debug_logf("bip_flow register local_error result=%d", result); + cleanup_request(); + dialog_show_error_timeout(register_error_message(result), ctx.return_cb, 0); + return; + } + + bwk_qr_response response; + fill_response_header(&response); + response.body.registration.descriptor_alias = req->descriptor_alias; + response.body.registration.registered = 1; + response.body.registration.stored = 1; + response.body.registration.proof.ptr = NULL; + response.body.registration.proof.len = 0; + show_response(&response); +} + +static void handle_register(void) { + debug_log_event("bip_flow handle_register"); + const bwk_qr_register_descriptor *req = + &ctx.request->body.register_descriptor; + if (!req->descriptor) { + debug_log_event("bip_flow register missing_descriptor"); + cleanup_request(); + dialog_show_error_timeout("Descriptor required for registration", + ctx.return_cb, 0); + return; + } + char *descriptor = request_descriptor_alloc(req->descriptor); + if (!descriptor) { + debug_log_event("bip_flow register unsupported_descriptor"); + cleanup_request(); + dialog_show_error_timeout("Unsupported descriptor", ctx.return_cb, 0); + return; + } + debug_logf("bip_flow register descriptor_ok alias=%s", + req->descriptor_alias ? req->descriptor_alias : ""); + descriptor_loader_process_string_with_id(descriptor, req->descriptor_alias, + STORAGE_FLASH, + register_validation_cb, NULL); + free(descriptor); +} + +static bool resolve_descriptor(const char *alias, + const bwk_qr_descriptor_body *body, + const registry_entry_t **entry_out) { + if (entry_out) + *entry_out = NULL; + if (body) { + char *descriptor = request_descriptor_alloc(body); + if (!descriptor) + return false; + if (alias && !registry_find_by_id(alias) && + !registry_add_from_string(alias, descriptor, STORAGE_FLASH, false)) { + free(descriptor); + return false; + } + const registry_entry_t *entry = alias ? registry_find_by_id(alias) : NULL; + if (entry_out) + *entry_out = entry; + free(descriptor); + return true; + } + const registry_entry_t *entry = registry_find_by_id(alias); + if (!entry) + return false; + if (entry_out) + *entry_out = entry; + return true; +} + +static bool address_from_entry_path(const registry_entry_t *entry, + const bwk_qr_path *path, char **out) { + if (!entry || !path || !out) + return false; + + size_t suffix_start = 0; + if (path->len == entry->origin_path_len + 2) { + for (size_t i = 0; i < entry->origin_path_len; i++) { + if (path->ptr[i] != entry->origin_path[i]) + return false; + } + suffix_start = entry->origin_path_len; + } else if (path->len != 2) { + return false; + } + + uint32_t multi_index = path->ptr[suffix_start]; + uint32_t child_num = path->ptr[suffix_start + 1]; + if (bip32_path_is_hardened(multi_index) || bip32_path_is_hardened(child_num)) + 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, unsigned char *script, + size_t script_len, size_t *written) { + if (!address || !script || !written) + return false; + return wally_addr_segwit_to_bytes(address, "bc", 0, script, script_len, + written) == WALLY_OK || + wally_addr_segwit_to_bytes(address, "tb", 0, script, script_len, + written) == WALLY_OK || + wally_addr_segwit_to_bytes(address, "bcrt", 0, script, script_len, + written) == WALLY_OK || + wally_address_to_scriptpubkey(address, WALLY_NETWORK_BITCOIN_MAINNET, + script, script_len, + written) == WALLY_OK || + wally_address_to_scriptpubkey(address, WALLY_NETWORK_BITCOIN_TESTNET, + script, script_len, written) == WALLY_OK; +} + +static bool addresses_have_same_spk(const char *a, const char *b) { + unsigned char a_script[128]; + unsigned char b_script[128]; + size_t a_len = 0; + size_t b_len = 0; + return address_to_spk(a, a_script, sizeof(a_script), &a_len) && + address_to_spk(b, b_script, sizeof(b_script), &b_len) && + a_len == b_len && memcmp(a_script, b_script, a_len) == 0; +} + +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(); + if (pending_verified_address) { + wally_free_string(pending_verified_address); + pending_verified_address = NULL; + } + cleanup_request(); + if (ctx.return_cb) + ctx.return_cb(); +} + +static void verify_local_error(const char *message) { + debug_logf("bip_flow verify local_error msg=%s", message ? message : ""); + if (pending_verified_address) { + wally_free_string(pending_verified_address); + pending_verified_address = NULL; + } + cleanup_request(); + dialog_show_error_timeout(message ? message : "Address verification failed", + ctx.return_cb, 0); +} + +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 *content = lv_obj_create(verify_address_detail); + lv_obj_remove_style_all(content); + lv_obj_set_size(content, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(content, + landscape ? LV_FLEX_FLOW_ROW : LV_FLEX_FLOW_COLUMN); + lv_obj_set_flex_align(content, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, + LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_pad_gap(content, pad, 0); + lv_obj_clear_flag(content, LV_OBJ_FLAG_SCROLLABLE); + + char *upper = qr_bech32_to_upper(pending_verified_address); + const char *qr_payload = upper ? upper : pending_verified_address; + lv_obj_t *qr_container = theme_create_qr_container(content, square_size, 15); + qr_create_optimal(qr_container, square_size - 30, qr_payload); + qr_viewer_attach_fullscreen(qr_container, qr_payload, "Verify Address"); + free(upper); + + lv_obj_t *addr_label = + theme_create_label(content, pending_verified_address, false); + if (landscape) + lv_obj_set_width(addr_label, scr_w - 2 * pad - square_size - pad); + else + lv_obj_set_width(addr_label, LV_PCT(95)); + lv_label_set_long_mode(addr_label, LV_LABEL_LONG_WRAP); + lv_obj_set_style_text_align(addr_label, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_set_style_text_font(addr_label, theme_font_medium(), 0); + + verify_address_approve_btn = lv_btn_create(verify_address_detail); + lv_obj_set_size(verify_address_approve_btn, LV_PCT(60), LV_SIZE_CONTENT); + theme_apply_touch_button(verify_address_approve_btn, true); + lv_obj_add_state(verify_address_approve_btn, LV_STATE_DISABLED); + lv_obj_t *approve_lbl = lv_label_create(verify_address_approve_btn); + lv_label_set_text(approve_lbl, "Done"); + lv_obj_center(approve_lbl); + theme_apply_button_label(approve_lbl, true); + lv_obj_add_event_cb(verify_address_approve_btn, verify_address_done_cb, + LV_EVENT_CLICKED, NULL); + lv_timer_t *enable_timer = + lv_timer_create(verify_address_approve_enable_cb, 500, NULL); + lv_timer_set_repeat_count(enable_timer, 1); +} + +static void handle_verify(void) { + debug_log_event("bip_flow handle_verify"); + const bwk_qr_verify_address *req = &ctx.request->body.verify_address; + const registry_entry_t *entry = NULL; + if (!resolve_descriptor(req->descriptor_alias, req->descriptor, &entry) || + !entry) { + verify_local_error("Unknown descriptor"); + return; + } + char *address = NULL; + if (!address_from_entry_path(entry, &req->derivation_path, &address) || + !address) { + verify_local_error("Failed to derive address"); + return; + } + if (req->address && !addresses_have_same_spk(req->address, address)) { + wally_free_string(address); + verify_local_error("Address mismatch"); + return; + } + if (pending_verified_address) + wally_free_string(pending_verified_address); + if (req->address) { + pending_verified_address = strdup(req->address); + wally_free_string(address); + if (!pending_verified_address) { + verify_local_error("Out of memory"); + return; + } + } else { + pending_verified_address = address; + } + debug_log_event("bip_flow verify show_detail"); + cleanup_request(); + show_verify_address_detail(); +} + +static uint8_t *serialize_psbt(const struct wally_psbt *psbt, size_t *len_out) { + size_t len = 0, written = 0; + if (wally_psbt_get_length(psbt, 0, &len) != WALLY_OK || len == 0) + return NULL; + uint8_t *buf = malloc(len); + if (!buf) + return NULL; + if (wally_psbt_to_bytes(psbt, 0, buf, len, &written) != WALLY_OK || + written != len) { + free(buf); + return NULL; + } + *len_out = len; + return buf; +} + +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(bwk_qr_signature *signatures, size_t len) { + if (!signatures) + return; + for (size_t i = 0; i < len; i++) { + switch (signatures[i].kind) { + case BWK_QR_SIGNATURE_ECDSA: + free((void *)signatures[i].value.ecdsa.signature.ptr); + break; + case BWK_QR_SIGNATURE_TAP_KEY: + free((void *)signatures[i].value.tap_key.signature.ptr); + break; + case BWK_QR_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, + bwk_qr_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(bwk_qr_signature **signatures, size_t *len, + size_t *cap, const bwk_qr_signature *sig) { + if (*len == *cap) { + size_t new_cap = *cap ? *cap * 2 : 4; + bwk_qr_signature *new_signatures = + realloc(*signatures, new_cap * sizeof(*new_signatures)); + if (!new_signatures) + return false; + *signatures = new_signatures; + *cap = new_cap; + } + (*signatures)[(*len)++] = *sig; + return true; +} + +static bool collect_signatures(const struct wally_psbt *psbt, + bwk_qr_signature **signatures_out, + size_t *len_out) { + bwk_qr_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 != BWK_QR_PUBLIC_KEY_LEN || !item->key || !item->value) + continue; + bwk_qr_signature sig = {.input_index = (uint32_t)input_index, + .kind = BWK_QR_SIGNATURE_ECDSA}; + memcpy(sig.value.ecdsa.public_key, item->key, BWK_QR_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; + } + bwk_qr_signature sig = {.input_index = (uint32_t)input_index, + .kind = BWK_QR_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; + bwk_qr_signature sig = {.input_index = (uint32_t)input_index, + .kind = BWK_QR_SIGNATURE_TAP_SCRIPT}; + memcpy(sig.value.tap_script.xonly_public_key, item->key, 32); + memcpy(sig.value.tap_script.tap_leaf_hash, item->key + 32, 32); + if (!copy_signature_bytes(item->value, item->value_len, + &sig.value.tap_script.signature) || + !append_signature(&signatures, &len, &cap, &sig)) { + free((void *)sig.value.tap_script.signature.ptr); + free_signature_list(signatures, len); + return false; + } + } + } + + *signatures_out = signatures; + *len_out = len; + return true; +} + +static void signed_psbt_cb(struct wally_psbt *psbt, void *user_data) { + (void)user_data; + bwk_qr_response response; + fill_response_header(&response); + if (ctx.request->body.sign.want_kind == BWK_QR_SIGN_RESPONSE_SIGNATURES) { + bwk_qr_signature *signatures = NULL; + size_t signatures_len = 0; + if (!collect_signatures(psbt, &signatures, &signatures_len)) { + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, + "Signature extraction failed"); + return; + } + if (signatures_len == 0) { + free_signature_list(signatures, signatures_len); + show_error_response(BWK_QR_RESPONSE_ERROR_NOTHING_TO_SIGN, + "Nothing to sign"); + return; + } + response.body.signed_body.kind = BWK_QR_SIGN_RESPONSE_SIGNATURES; + response.body.signed_body.value.signatures.ptr = signatures; + response.body.signed_body.value.signatures.len = signatures_len; + show_response_with_done(&response, return_from_signing_response); + free_signature_list(signatures, signatures_len); + } else { + struct wally_psbt *trimmed = psbt_trim(psbt); + 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 = serialize_psbt(export_psbt, &signed_len); + if (trimmed) + wally_psbt_free(trimmed); + if (!signed_bytes) { + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "PSBT encode failed"); + return; + } + response.body.signed_body.kind = BWK_QR_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); + } +} + +static void handle_sign(void) { + const bwk_qr_sign *req = &ctx.request->body.sign; + for (size_t i = 0; i < req->descriptors.len; i++) { + const bwk_qr_descriptor *descriptor = &req->descriptors.ptr[i]; + char *descriptor_str = request_descriptor_alloc(&descriptor->body); + if (!descriptor_str) { + show_error_response(BWK_QR_RESPONSE_ERROR_UNSUPPORTED_DESCRIPTOR_FORM, + "Unsupported descriptor"); + return; + } + if (descriptor->alias && !registry_find_by_id(descriptor->alias) && + !registry_add_from_string(descriptor->alias, descriptor_str, + STORAGE_FLASH, false)) { + free(descriptor_str); + show_error_response(BWK_QR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED, + "Descriptor failed"); + return; + } + free(descriptor_str); + } + scan_review_psbt(ctx.parent, req->psbt.ptr, req->psbt.len, ctx.return_cb, + return_from_signing_response, signed_psbt_cb, NULL); +} + +static void dispatch_request(void) { + debug_logf("bip_flow dispatch message_type=%d", ctx.request->message_type); + switch (ctx.request->message_type) { + case BWK_QR_MESSAGE_GET_XPUBS: + handle_get_xpubs(); + break; + case BWK_QR_MESSAGE_REGISTER_DESCRIPTOR: + handle_register(); + break; + case BWK_QR_MESSAGE_ADDRESS_VERIFICATION: + handle_verify(); + break; + case BWK_QR_MESSAGE_SIGNING: + handle_sign(); + break; + default: + show_error_response(BWK_QR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Unknown 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(); + if (pending_verified_address) { + wally_free_string(pending_verified_address); + pending_verified_address = NULL; + } + const char *err = NULL; + int32_t rc = bwk_qr_request_decode(data, len, &ctx.request, &err); + if (rc != BWK_QR_OK || !ctx.request) { + debug_logf("bip_flow decode_error rc=%d err=%s", (int)rc, err ? err : ""); + dialog_show_error_timeout(err ? err : "Invalid request", return_cb, 0); + 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..a4e512e8 --- /dev/null +++ b/main/pages/bip_flow/bip_flow.h @@ -0,0 +1,19 @@ +#ifndef BIP_FLOW_H +#define BIP_FLOW_H + +#include +#include +#include +#include + +#include "../../core/descriptor_validator.h" + +bool bip_flow_can_handle(const uint8_t *data, size_t len); +static inline bool bip_flow_register_validation_result_allows_response( + descriptor_validation_result_t result) { + return result == VALIDATION_SUCCESS || result == VALIDATION_USER_DECLINED; +} +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..3296304a --- /dev/null +++ b/main/pages/bip_flow/test/Makefile @@ -0,0 +1,19 @@ +CC = gcc +CFLAGS = -Wall -Wextra -g + +ROOT = ../../../.. +TARGET = test_bip_flow_register +TEST_INCS = -Istubs -I$(ROOT)/main -I$(ROOT)/main/core/test/stubs + +all: $(TARGET) + +$(TARGET): test_bip_flow_register.c ../bip_flow.h + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ test_bip_flow_register.c + +run: $(TARGET) + ./$(TARGET) + +clean: + rm -f $(TARGET) + +.PHONY: all run clean 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_bip_flow_register.c b/main/pages/bip_flow/test/test_bip_flow_register.c new file mode 100644 index 00000000..bf645266 --- /dev/null +++ b/main/pages/bip_flow/test/test_bip_flow_register.c @@ -0,0 +1,44 @@ +#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_response_allowed(descriptor_validation_result_t result, + bool expected, const char *name) { + TEST(name); + if (bip_flow_register_validation_result_allows_response(result) == expected) { + PASS(); + } else { + FAIL("unexpected response policy"); + } +} + +int main(void) { + printf("BIP flow register response policy tests\n"); + printf("=======================================\n\n"); + + expect_response_allowed(VALIDATION_SUCCESS, true, + "approved registration may show response"); + expect_response_allowed(VALIDATION_USER_DECLINED, true, + "declined registration may show response"); + expect_response_allowed(VALIDATION_PARSE_ERROR, false, + "parse error must stay local"); + expect_response_allowed(VALIDATION_FINGERPRINT_NOT_FOUND, false, + "fingerprint error must stay local"); + expect_response_allowed(VALIDATION_DUPLICATE, false, + "duplicate shortcut must stay local"); + expect_response_allowed(VALIDATION_XPUB_MISMATCH, false, + "xpub mismatch must stay local"); + + printf("\nResults: %d failed\n", tests_failed); + return tests_failed == 0 ? 0 : 1; +} diff --git a/main/pages/home/home.c b/main/pages/home/home.c index 4f480693..3cfd72d7 100644 --- a/main/pages/home/home.c +++ b/main/pages/home/home.c @@ -1,4 +1,5 @@ #include "home.h" +#include "../../core/debug_log.h" #include "../../core/key.h" #include "../../core/wallet.h" #include "../../ui/assets/icons.h" @@ -127,21 +128,23 @@ static void return_from_addresses_cb(void) { } static void return_from_scan_cb(void) { + debug_log_event("home return_from_scan_cb enter"); scan_page_destroy(); - if (key_snapshot_changed() || wallet_settings_were_applied()) { - home_page_destroy(); - home_page_create(lv_screen_active()); - } + debug_log_event("home return_from_scan_cb recreate_home"); + home_page_destroy(); + home_page_create(lv_screen_active()); home_page_show(); + debug_log_event("home return_from_scan_cb show_home"); } static void return_from_load_cb(void) { + debug_log_event("home return_from_load_cb enter"); load_page_destroy(); - if (key_snapshot_changed() || wallet_settings_were_applied()) { - home_page_destroy(); - home_page_create(lv_screen_active()); - } + debug_log_event("home return_from_load_cb recreate_home"); + home_page_destroy(); + home_page_create(lv_screen_active()); home_page_show(); + debug_log_event("home return_from_load_cb show_home"); } static void return_from_advanced_tools_cb(void) { diff --git a/main/pages/login/login_scan.c b/main/pages/login/login_scan.c index 582b92a9..657da789 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,27 @@ static void show_psbt_needs_key(void) { unidentified_dismissed_cb, NULL, DIALOG_STYLE_OVERLAY); } +static const char *bip_request_title(const uint8_t *content, size_t len) { + const bwk_qr_request *request = NULL; + const char *err = NULL; + const char *title = "Wallet request detected"; + if (bwk_qr_request_decode(content, len, &request, &err) == BWK_QR_OK && + request) { + if (request->message_type == BWK_QR_MESSAGE_GET_XPUBS) + title = "Xpub request detected"; + } + if (request) + bwk_qr_request_free(request); + return title; +} + +static void show_bip_request_needs_key(const uint8_t *content, size_t len) { + dialog_show_info(bip_request_title(content, len), + "Load a seed first to export xpubs or respond to wallet " + "requests.", + unidentified_dismissed_cb, NULL, DIALOG_STYLE_OVERLAY); +} + static bool is_psbt_content(const char *content, size_t len) { if (!content) return false; @@ -165,6 +188,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(); @@ -179,6 +203,12 @@ static void on_scan_done(void) { return; } + if (bip_request_scanned) { + free(desc_candidate); + show_bip_request_needs_key((const uint8_t *)content, len); + return; + } + if (!content && !desc_candidate) { finish_to_login(); return; diff --git a/main/pages/scan/scan.c b/main/pages/scan/scan.c index 340eefdd..f5d0d1ff 100644 --- a/main/pages/scan/scan.c +++ b/main/pages/scan/scan.c @@ -23,6 +23,7 @@ #include "../../ui/theme_widgets.h" #include "../../utils/secure_mem.h" #include "../../utils/session_cleanup.h" +#include "../bip_flow/bip_flow.h" #include "../load_descriptor_storage.h" #include "../shared/address_checker.h" #include "../shared/descriptor_loader.h" @@ -126,6 +127,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 @@ -302,6 +311,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); @@ -463,6 +481,8 @@ 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_signed_user_data = NULL; scan_ctx.screen = theme_create_page_container(parent); // A file may hold a serialized binary PSBT — try that first (mirroring the @@ -484,6 +504,25 @@ 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, void *signed_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_signed_user_data = signed_user_data; + scan_ctx.screen = theme_create_page_container(parent); + + scan_psbt_cleanup(); + bool parse_success = psbt_parse_payload(data, len, &scan_ctx.psbt); + finish_dispatch(NULL, len, parse_success, 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()) { @@ -492,6 +531,8 @@ 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_signed_user_data = NULL; reset_export_context(NULL, NULL); scan_ctx.screen = theme_create_page_container(parent); @@ -539,4 +580,6 @@ void scan_page_destroy(void) { scan_ctx.return_cb = NULL; scan_ctx.complete_cb = NULL; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_signed_user_data = NULL; } diff --git a/main/pages/scan/scan.h b/main/pages/scan/scan.h index 7580c098..b6895f4c 100644 --- a/main/pages/scan/scan.h +++ b/main/pages/scan/scan.h @@ -2,6 +2,13 @@ #define SCAN_H #include +#include +#include + +struct wally_psbt; + +typedef void (*scan_psbt_signed_cb_t)(struct wally_psbt *signed_psbt, + void *user_data); /** * Create the scan page — universal QR content detection @@ -36,6 +43,15 @@ 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. + */ +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, void *signed_user_data); + /** * Show the scan page */ diff --git a/main/pages/scan/scan_internal.h b/main/pages/scan/scan_internal.h index 15802d3d..b0b50bbe 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 @@ -50,6 +51,11 @@ typedef struct { bool is_bip322; char *scanned_mnemonic; + + /* Set by scan_review_psbt(): the signed PSBT goes back to the caller + * instead of the export menu. */ + scan_psbt_signed_cb_t psbt_signed_cb; + void *psbt_signed_user_data; } scan_ctx_t; extern scan_ctx_t scan_ctx; diff --git a/main/pages/scan/scan_psbt_sign.c b/main/pages/scan/scan_psbt_sign.c index e145f06f..73cdebc7 100644 --- a/main/pages/scan/scan_psbt_sign.c +++ b/main/pages/scan/scan_psbt_sign.c @@ -20,6 +20,21 @@ 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_signed_user_data; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_signed_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); @@ -29,7 +44,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) { @@ -79,8 +94,9 @@ static void deferred_sign_cb(lv_timer_t *timer) { 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 @@ -117,7 +133,7 @@ static void deferred_sign_cb(lv_timer_t *timer) { return; } - show_export_choice(); + finish_signed_psbt(); } // Tears down the chooser, then returns to the caller that opened the diff --git a/main/pages/shared/descriptor_loader.c b/main/pages/shared/descriptor_loader.c index 6f5d0364..1520dd4b 100644 --- a/main/pages/shared/descriptor_loader.c +++ b/main/pages/shared/descriptor_loader.c @@ -1,6 +1,7 @@ #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/key.h" #include "../../core/miniscript_policy.h" #include "../../core/registry.h" @@ -22,6 +23,9 @@ #include #include +static void debug_log_descriptor_shape(const char *label, + const char *descriptor); + // Convert extended pubkey with non-standard version bytes to xpub/tpub. // Handles Zpub, Ypub (mainnet) and Vpub, Upub (testnet). static char *convert_xpub_version(const char *key) { @@ -277,6 +281,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) @@ -428,6 +452,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); @@ -839,6 +875,44 @@ 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; + + char *converted = bluewallet_to_descriptor(descriptor_str); + const char *to_process = converted ? converted : descriptor_str; + char *unambiguous = descriptor_to_unambiguous(to_process); + debug_logf("descriptor_loader fixed_id converted=%d unambiguous=%d", + converted != NULL, unambiguous != NULL); + debug_log_descriptor_shape("descriptor_loader raw", descriptor_str); + debug_log_descriptor_shape("descriptor_loader final", + unambiguous ? unambiguous : to_process); + session_cleanup_register(descriptor_validation_cancel); + descriptor_validate_and_load_persistent( + unambiguous ? unambiguous : to_process, fixed_id_validation_cb, + descriptor_confirm_wrapper, descriptor_info_confirm_wrapper, + fixed_id_loc_wrapper, fixed); + free(unambiguous); + free(converted); +} + void descriptor_loader_process_string_watch_only( const char *descriptor_str, validation_complete_cb validation_cb, void *user_data) { @@ -942,6 +1016,43 @@ static bool is_base58_char(char c) { (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 ? "..." : ""); +} + char *descriptor_to_unambiguous(const char *descriptor) { if (!descriptor) return NULL; diff --git a/main/pages/shared/descriptor_loader.h b/main/pages/shared/descriptor_loader.h index 317e7f7a..6180bb3f 100644 --- a/main/pages/shared/descriptor_loader.h +++ b/main/pages/shared/descriptor_loader.h @@ -32,6 +32,14 @@ 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. + */ +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. 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/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 From 8bf3ab1f0c14fb40632034294268317e861490a2 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 05:45:40 +0000 Subject: [PATCH 03/13] fix(bwk): show the xpub response QR with modules twice as big --- main/pages/bip_flow/bip_flow.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c index b4bb0004..d60f6d9f 100644 --- a/main/pages/bip_flow/bip_flow.c +++ b/main/pages/bip_flow/bip_flow.c @@ -94,8 +94,8 @@ static void return_from_signing_response(void) { } } -static void show_response_with_done(bwk_qr_response *response, - void (*done_cb)(void)) { +static void show_response_sized(bwk_qr_response *response, + void (*done_cb)(void), int max_chars) { debug_logf("bip_flow show_response is_error=%d", response->is_error); bwk_qr_buf encoded = {0}; const char *err = NULL; @@ -107,8 +107,8 @@ static void show_response_with_done(bwk_qr_response *response, return; } - BBQrParts *parts = bbqr_encode_hex(encoded.ptr, encoded.len, BBQR_TYPE_BINARY, - settings_get_qr_density()); + BBQrParts *parts = + bbqr_encode_hex(encoded.ptr, encoded.len, BBQR_TYPE_BINARY, max_chars); bwk_qr_buf_free(encoded); if (!parts) { cleanup_request(); @@ -125,6 +125,11 @@ static void show_response_with_done(bwk_qr_response *response, qr_viewer_page_show(); } +static void show_response_with_done(bwk_qr_response *response, + void (*done_cb)(void)) { + show_response_sized(response, done_cb, settings_get_qr_density()); +} + static void show_response(bwk_qr_response *response) { show_response_with_done(response, return_from_response); } @@ -212,7 +217,10 @@ static void get_xpubs_confirm_cb(bool confirmed, void *user_data) { response.body.xpubs.version.patch = patch; response.body.xpubs.version.flag = BWK_QR_RELEASE_STABLE; response.body.xpubs.capabilities = 0x03; - show_response(&response); + // 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(xpubs); } From 8048557107ae183945f4d3677ad200f22c147a93 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 08:17:54 +0000 Subject: [PATCH 04/13] fix(bwk): bump bwk to the 2-byte request id protocol The coordinator now sends 2-byte request ids, which the pinned codec read as a truncated 16-byte id and rejected. A sign request's descriptor body is now optional and refers to an already registered alias when absent. --- components/bwk | 2 +- main/pages/bip_flow/bip_flow.c | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/components/bwk b/components/bwk index dd803aea..8ff3f712 160000 --- a/components/bwk +++ b/components/bwk @@ -1 +1 @@ -Subproject commit dd803aeabdb77e150c236f8cb255cc0ce4dcc6d6 +Subproject commit 8ff3f712f23948e659a103d69c9d084caa068e63 diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c index d60f6d9f..a6cf482a 100644 --- a/main/pages/bip_flow/bip_flow.c +++ b/main/pages/bip_flow/bip_flow.c @@ -955,7 +955,14 @@ static void handle_sign(void) { const bwk_qr_sign *req = &ctx.request->body.sign; for (size_t i = 0; i < req->descriptors.len; i++) { const bwk_qr_descriptor *descriptor = &req->descriptors.ptr[i]; - char *descriptor_str = request_descriptor_alloc(&descriptor->body); + if (!descriptor->body) { + if (descriptor->alias && registry_find_by_id(descriptor->alias)) + continue; + show_error_response(BWK_QR_RESPONSE_ERROR_UNKNOWN_DESCRIPTOR_ALIAS, + "Unknown descriptor"); + return; + } + char *descriptor_str = request_descriptor_alloc(descriptor->body); if (!descriptor_str) { show_error_response(BWK_QR_RESPONSE_ERROR_UNSUPPORTED_DESCRIPTOR_FORM, "Unsupported descriptor"); From c3ae652f54dbce12cd05df570020606758ec7d6d Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 08:20:28 +0000 Subject: [PATCH 05/13] fix(bwk): rebuild the codec staticlib when the bwk sources change --- components/bwk_codecs/CMakeLists.txt | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/components/bwk_codecs/CMakeLists.txt b/components/bwk_codecs/CMakeLists.txt index 87f58956..4448a45c 100644 --- a/components/bwk_codecs/CMakeLists.txt +++ b/components/bwk_codecs/CMakeLists.txt @@ -10,24 +10,19 @@ idf_component_register( find_program(CARGO_EXECUTABLE cargo REQUIRED) -add_custom_command( - OUTPUT ${RUST_LIB} +# Always runs: cargo tracks the bwk sources and only relinks on a change +add_custom_target(bwk_codecs_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 - DEPENDS - ${CMAKE_CURRENT_LIST_DIR}/Cargo.toml - ${CMAKE_CURRENT_LIST_DIR}/src/lib.rs - ${CMAKE_CURRENT_LIST_DIR}/strip_c_builtins.cmake + BYPRODUCTS ${RUST_LIB} WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} COMMENT "Building bwk codec Rust staticlib" VERBATIM ) - -add_custom_target(bwk_codecs_rust DEPENDS ${RUST_LIB}) add_library(bwk_codecs_static STATIC IMPORTED GLOBAL) set_target_properties(bwk_codecs_static PROPERTIES IMPORTED_LOCATION ${RUST_LIB}) add_dependencies(bwk_codecs_static bwk_codecs_rust) From 84311a0d304056d0184158911ab8a7b0b3746b8e Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 10:30:01 +0000 Subject: [PATCH 06/13] fix(bwk): bump bwk to the protocol carrying the device vendor --- components/bwk | 2 +- main/pages/bip_flow/bip_flow.c | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/components/bwk b/components/bwk index 8ff3f712..24bfd420 160000 --- a/components/bwk +++ b/components/bwk @@ -1 +1 @@ -Subproject commit 8ff3f712f23948e659a103d69c9d084caa068e63 +Subproject commit 24bfd42042d1905c580c4d7d3312a885126ccbaf diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c index a6cf482a..c56b0ca8 100644 --- a/main/pages/bip_flow/bip_flow.c +++ b/main/pages/bip_flow/bip_flow.c @@ -206,6 +206,8 @@ static void get_xpubs_confirm_cb(bool confirmed, void *user_data) { show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "Fingerprint failed"); return; } + snprintf(response.body.xpubs.vendor, sizeof(response.body.xpubs.vendor), + "Kern"); snprintf(response.body.xpubs.model, sizeof(response.body.xpubs.model), "Kern"); const esp_app_desc_t *desc = esp_app_get_description(); From a12dc7e2324f8e50897a8532f3a34b439e4f84b1 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 10:35:58 +0000 Subject: [PATCH 07/13] fix(bwk): report the board as the model in the xpub response --- main/Kconfig.projbuild | 9 +++++++++ main/pages/bip_flow/bip_flow.c | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/main/Kconfig.projbuild b/main/Kconfig.projbuild index 1dbbba9f..bccb586b 100644 --- a/main/Kconfig.projbuild +++ b/main/Kconfig.projbuild @@ -25,6 +25,15 @@ menu "Kern Configuration" bool "Waveshare ESP32-P4-WiFi6-Touch-LCD-7B (1024x600 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 + config KERN_PBKDF2_HW_SHA bool "Drive PBKDF2-HMAC-SHA256 on the P4 SHA accelerator" default y diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c index c56b0ca8..35cc18fb 100644 --- a/main/pages/bip_flow/bip_flow.c +++ b/main/pages/bip_flow/bip_flow.c @@ -18,6 +18,7 @@ #include "../shared/descriptor_loader.h" #include #include +#include #include #include #include @@ -209,7 +210,7 @@ static void get_xpubs_confirm_cb(bool confirmed, void *user_data) { snprintf(response.body.xpubs.vendor, sizeof(response.body.xpubs.vendor), "Kern"); snprintf(response.body.xpubs.model, sizeof(response.body.xpubs.model), - "Kern"); + "%s", CONFIG_KERN_BOARD_NAME); const esp_app_desc_t *desc = esp_app_get_description(); unsigned major = 0, minor = 0, patch = 0; if (desc) From 0330b2c430cb43999479be2560dbba64169bc213 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 12:14:02 +0000 Subject: [PATCH 08/13] build(secp): compile the BIP352 silentpayments module from secp256k1 PR #1765 --- components/libwally-core/CMakeLists.txt | 6 +- components/libwally-core/kern_bech32.h | 12 + components/libwally-core/kern_combined.c | 43 + .../libwally-core/silentpayments/README.md | 7 + .../include/secp256k1_silentpayments.h | 399 +++++++++ .../src/modules/silentpayments/main_impl.h | 800 ++++++++++++++++++ main/core/test/.gitignore | 1 + main/core/test/Makefile | 20 +- main/core/test/test_silentpayments.c | 226 +++++ simulator/CMakeLists.txt | 4 +- 10 files changed, 1509 insertions(+), 9 deletions(-) create mode 100644 components/libwally-core/kern_bech32.h create mode 100644 components/libwally-core/kern_combined.c create mode 100644 components/libwally-core/silentpayments/README.md create mode 100644 components/libwally-core/silentpayments/include/secp256k1_silentpayments.h create mode 100644 components/libwally-core/silentpayments/src/modules/silentpayments/main_impl.h create mode 100644 main/core/test/test_silentpayments.c diff --git a/components/libwally-core/CMakeLists.txt b/components/libwally-core/CMakeLists.txt index 2f9c6aed..775e3164 100644 --- a/components/libwally-core/CMakeLists.txt +++ b/components/libwally-core/CMakeLists.txt @@ -1,9 +1,11 @@ idf_component_register(SRCS "kern_wally.c" - "upstream/src/amalgamation/combined.c" + "kern_combined.c" INCLUDE_DIRS "." "upstream/include" + "upstream/src/secp256k1/include" + "silentpayments/include" PRIV_INCLUDE_DIRS "." "upstream" @@ -26,7 +28,7 @@ idf_component_register(SRCS PRIV_REQUIRES mbedtls mbedtls_compat secure_memory) set_source_files_properties( - upstream/src/amalgamation/combined.c + kern_combined.c PROPERTIES COMPILE_FLAGS "-Wno-nonnull-compare -Wno-unused-function -Wno-error=maybe-uninitialized -Wno-type-limits -Wno-error=array-parameter -Wno-unterminated-string-initialization" ) 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..ef922cce --- /dev/null +++ b/components/libwally-core/kern_combined.c @@ -0,0 +1,43 @@ +/* libwally amalgamation plus the BIP352 silentpayments module of secp256k1 + * PR #1765 (see silentpayments/README.md), which needs the secp256k1 + * internals of the same translation unit. */ +#include "upstream/src/amalgamation/combined.c" + +#ifndef WALLY_NO_AMALGAMATION +#include "kern_bech32.h" + +/* secp256k1-zkp predates this upstream helper the module calls. */ +static void secp256k1_ecmult_gen_ge(const secp256k1_ecmult_gen_context *ctx, + secp256k1_ge *r, const secp256k1_scalar *a) { + secp256k1_gej rj; + secp256k1_ecmult_gen(ctx, &rj, a); + secp256k1_ge_set_gej(r, &rj); + secp256k1_gej_clear(&rj); +} + +#include "silentpayments/src/modules/silentpayments/main_impl.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/silentpayments/README.md b/components/libwally-core/silentpayments/README.md new file mode 100644 index 00000000..b5fa0b12 --- /dev/null +++ b/components/libwally-core/silentpayments/README.md @@ -0,0 +1,7 @@ +# secp256k1 silentpayments module + +`include/secp256k1_silentpayments.h` and `src/modules/silentpayments/main_impl.h` are copied +unchanged from [bitcoin-core/secp256k1#1765](https://github.com/bitcoin-core/secp256k1/pull/1765) +at commit `cea6d114109aff49ce26a9d4e2f8c1106e36f2bc`. The tree layout mirrors secp256k1 so the +module's relative includes resolve against libwally's bundled secp256k1-zkp, and +`../kern_combined.c` compiles it in the same translation unit. diff --git a/components/libwally-core/silentpayments/include/secp256k1_silentpayments.h b/components/libwally-core/silentpayments/include/secp256k1_silentpayments.h new file mode 100644 index 00000000..256e95ac --- /dev/null +++ b/components/libwally-core/silentpayments/include/secp256k1_silentpayments.h @@ -0,0 +1,399 @@ +#ifndef SECP256K1_SILENTPAYMENTS_H +#define SECP256K1_SILENTPAYMENTS_H + +#include +#include "secp256k1.h" +#include "secp256k1_extrakeys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** This module provides an implementation for Silent Payments, as specified in + * BIP352. This particularly involves the creation of input tweak data by + * summing up secret or public keys and the derivation of a shared secret using + * Elliptic Curve Diffie-Hellman. Combined are either: + * - spender's secret keys and recipient's public key (a * B, sender side) + * - spender's public keys and recipient's secret key (A * b, recipient side) + * With this result, the necessary key material for ultimately creating/scanning + * or spending Silent Payments outputs can be determined. + * + * Note that this module is _not_ a full implementation of BIP352, as it + * inherently doesn't deal with higher-level concepts like addresses, output + * script types or transactions. The intent is to provide a module for + * abstracting away the elliptic-curve operations required for the protocol. For + * any wallet software already using libsecp256k1, this API should provide all + * the functions needed for a Silent Payments implementation without requiring + * any further elliptic-curve operations from the wallet. + */ + +/* Maximum number of Silent Payments recipients per group (i.e. + * recipients sharing the same scan public key) as per BIP-352 */ +#define SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT 2323 + +/** The data from a single recipient address + * + * This struct serves as an input argument to `silentpayments_sender_create_outputs`. + * + * `index` must be set to the position (starting with 0) of this recipient in the + * `recipients` array passed to `silentpayments_sender_create_outputs`. It is + * used to map the returned generated outputs back to the original recipient. + * + * Note: + * The spend public key named `spend_pubkey` may have been optionally tweaked with + * a label by the recipient. Whether `spend_pubkey` has actually been tagged with + * a label is irrelevant for the sender. As a documentation convention in this API, + * `unlabeled_spend_pubkey` is used to indicate when the unlabeled spend public key + * must be used. + */ +typedef struct secp256k1_silentpayments_recipient { + secp256k1_pubkey scan_pubkey; + secp256k1_pubkey spend_pubkey; + size_t index; +} secp256k1_silentpayments_recipient; + +/** Create Silent Payments outputs for recipient(s). + * + * Given a list of n secret keys a_1...a_n (one for each Silent Payments + * eligible input to spend), a serialized outpoint, and a list of recipients, + * create the taproot outputs. Inputs with conditional branches or multiple + * public keys are excluded from Silent Payments eligible inputs; see BIP352 + * for more information. + * + * `outpoint_smallest36` refers to the smallest outpoint lexicographically + * from the transaction inputs (both Silent Payments eligible and non-eligible + * inputs). This value MUST be the smallest outpoint out of all of the + * transaction inputs, otherwise the recipient will be unable to find the + * payment. Determining the smallest outpoint from the list of transaction + * inputs is the responsibility of the caller. It is strongly recommended + * that implementations ensure they are doing this correctly by using the + * test vectors from BIP352. + * + * When creating more than one generated output, all of the generated outputs + * MUST be included in the final transaction. Dropping any of the generated + * outputs from the final transaction may make all or some of the outputs + * unfindable by the recipient. + * + * Returns: 1 if creation of outputs was successful. + * 0 on failure. This is expected only with an adversarially chosen + * recipient spend key. Specifically, failure occurs when: + * - Input secret keys sum to 0 + * (negligible probability if at least one of the input secret + * keys is uniformly random and independent of all other keys) + * - A hash output is not a valid scalar (negligible probability + * per hash evaluation) + * - Any group (i.e. recipients sharing the same scan public key) exceeds + * the protocol limit SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT + * + * Args: ctx: pointer to a context object + * (not secp256k1_context_static). + * Out: generated_outputs: pointer to an array of pointers to xonly public keys, + * one per recipient. + * The outputs are ordered to match the original + * ordering of the recipient objects, i.e., + * `generated_outputs[0]` is the generated output + * for the `secp256k1_silentpayments_recipient` object + * with index = 0. + * In: recipients: pointer to an array of pointers to Silent Payments + * recipients, where each recipient is a scan public + * key, a spend public key, and an index indicating + * its position in the original ordering. The + * recipient array will be grouped by scan public key + * in place (as specified in BIP0352), but generated + * outputs are saved in the `generated_outputs` array + * to match the original ordering (using the index + * field). This ensures the caller is able to match + * the generated outputs to the correct Silent + * Payments addresses. The same recipient can be + * passed multiple times to create multiple outputs + * for the same recipient. + * n_recipients: the size of the recipients array. + * outpoint_smallest36: serialized (36-byte) smallest outpoint + * (lexicographically) from the transaction inputs + * keypairs: pointer to an array of pointers to taproot + * keypair inputs (can be NULL if no secret keys + * of taproot inputs are used) + * n_keypairs: the size of the keypairs array. + * seckeys: pointer to an array of pointers to 32-byte + * secret keys of non-taproot inputs (can be NULL + * if no secret keys of non-taproot inputs are + * used) + * n_seckeys: the size of the seckeys array. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_sender_create_outputs( + const secp256k1_context *ctx, + secp256k1_xonly_pubkey **generated_outputs, + const secp256k1_silentpayments_recipient **recipients, + size_t n_recipients, + const unsigned char *outpoint_smallest36, + const secp256k1_keypair * const *keypairs, + size_t n_keypairs, + const unsigned char * const *seckeys, + size_t n_seckeys +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5); + +/** Opaque data structure that holds a Silent Payments label. + * + * Guaranteed to be 68 bytes in size. Serialized and parsed with + * `secp256k1_silentpayments_recipient_label_serialize` and + * `secp256k1_silentpayments_recipient_label_parse`. + */ +typedef struct secp256k1_silentpayments_label { + unsigned char data[68]; +} secp256k1_silentpayments_label; + +/** Parse a Silent Payments label. + * + * Returns: 1 when the label could be parsed, 0 otherwise. + * Args: ctx: pointer to a context object + * Out: label: pointer to a label object + * In: in33: pointer to the 33-byte label to be parsed + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_recipient_label_parse( + const secp256k1_context *ctx, + secp256k1_silentpayments_label *label, + const unsigned char *in33 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize a Silent Payments label + * + * Returns: 1 always + * Args: ctx: pointer to a context object + * Out: out33: pointer to a 33-byte array to store the serialized label + * In: label: pointer to the label + */ +SECP256K1_API int secp256k1_silentpayments_recipient_label_serialize( + const secp256k1_context *ctx, + unsigned char *out33, + const secp256k1_silentpayments_label *label +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Create Silent Payments label tweak and label. + * + * Given a recipient's 32 byte scan key and a label integer m, calculate the + * corresponding label tweak and label: + * + * label_tweak = hash(scan_key || m) + * label = label_tweak * G + * + * Returns: 1 if label tweak and label creation was successful. + * 0 if scan_key32 is invalid or the hash output label_tweak32 is + * not a valid scalar (negligible probability per hash evaluation). + * + * WARNING: Creating a large number of labels may significantly degrade + * scanning performance in certain Silent Payments wallet implementations, + * such as light clients. The scanning function provided in this module, + * which is designed for full nodes, performs consistently even with hundreds + * of thousands of labels. Other implementations may not share this property + * or may be unable to use it due to lacking full transaction data. + * + * To maximize wallet interoperability, it is recommended to create only + * the change label (m = 0) and avoid distributing labeled addresses. + * + * Args: ctx: pointer to a context object + * (not secp256k1_context_static) + * Out: label: pointer to the resulting label + * label_tweak32: pointer to the 32 byte label tweak + * In: scan_key32: pointer to the recipient's 32 byte scan key + * m: integer for the m-th label (0 is used for change outputs) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_recipient_label_create( + const secp256k1_context *ctx, + secp256k1_silentpayments_label *label, + unsigned char *label_tweak32, + const unsigned char *scan_key32, + uint32_t m +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Create Silent Payments labeled spend public key. + * + * Given a recipient's spend public key and a label, calculate the + * corresponding labeled spend public key: + * + * labeled_spend_pubkey = unlabeled_spend_pubkey + label + * + * The result is used by the recipient to create a Silent Payments address, + * consisting of the serialized and concatenated scan public key and + * (labeled) spend public key. + * + * Returns: 1 if labeled spend public key creation was successful. + * 0 if spend pubkey and label sum to zero (negligible probability for + * labels created according to BIP352). + * + * Args: ctx: pointer to a context object + * Out: labeled_spend_pubkey: pointer to the resulting labeled spend public key + * In: unlabeled_spend_pubkey: pointer to the recipient's unlabeled spend public key + * label: pointer to the recipient's label + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_recipient_create_labeled_spend_pubkey( + const secp256k1_context *ctx, + secp256k1_pubkey *labeled_spend_pubkey, + const secp256k1_pubkey *unlabeled_spend_pubkey, + const secp256k1_silentpayments_label *label +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Opaque data structure that holds Silent Payments prevouts summary data. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 101 bytes in size, and can be safely copied/moved. + * This structure does not contain secret data. It can be created with + * `secp256k1_silentpayments_recipient_prevouts_summary_create`. + */ +typedef struct secp256k1_silentpayments_prevouts_summary { + unsigned char data[101]; +} secp256k1_silentpayments_prevouts_summary; + +/** Compute Silent Payments prevouts summary from prevout public keys and transaction + * inputs. + * + * Given a list of n public keys A_1...A_n (one for each Silent Payments + * eligible input to spend) and a serialized outpoint_smallest36, create a + * `prevouts_summary` object. This object summarizes the prevout data from the + * transaction inputs needed for scanning. + * + * `outpoint_smallest36` refers to the smallest outpoint lexicographically + * from the transaction inputs (both Silent Payments eligible and non-eligible + * inputs). This value MUST be the smallest outpoint out of all of the + * transaction inputs, otherwise the recipient will be unable to find the + * payment. + * + * The public keys have to be passed in via two different parameter pairs, one + * for regular and one for x-only public keys, in order to avoid the need of + * users converting to a common public key format before calling this function. + * The resulting data can be used for scanning on the recipient side. + * + * Returns: 1 if prevouts summary creation was successful. + * 0 if the transaction is not a Silent Payments transaction. + * + * Args: ctx: pointer to a context object + * Out: prevouts_summary: pointer to prevouts_summary object containing the + * summed public key and input_hash. + * In: outpoint_smallest36: serialized smallest outpoint (lexicographically) + * from the transaction inputs + * xonly_pubkeys: pointer to an array of pointers to taproot + * x-only public keys (can be NULL if no taproot + * inputs are used) + * n_xonly_pubkeys: the size of the xonly_pubkeys array. + * pubkeys: pointer to an array of pointers to non-taproot + * public keys (can be NULL if no non-taproot + * inputs are used) + * n_pubkeys: the size of the pubkeys array. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_recipient_prevouts_summary_create( + const secp256k1_context *ctx, + secp256k1_silentpayments_prevouts_summary *prevouts_summary, + const unsigned char *outpoint_smallest36, + const secp256k1_xonly_pubkey * const *xonly_pubkeys, + size_t n_xonly_pubkeys, + const secp256k1_pubkey * const *pubkeys, + size_t n_pubkeys +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Type of callback function for label lookups + * + * A function of this type will be used to retrieve the label tweak for a given + * label during scanning. A typical implementation will perform a lookup in a + * key-value store called the "label cache". + * + * For creating the label cache data, + * `secp256k1_silentpayments_recipient_label_create` and + * `secp256k1_silentpayments_recipient_label_serialize` can be used. + * + * Returns: pointer to the 32-byte label tweak if there is a match. + * NULL pointer if there is no match. + * + * In: label: pointer to the serialized 33-byte label to check + * (computed during scanning) + * label_context: pointer to the recipient's label cache. + */ +typedef const unsigned char* (*secp256k1_silentpayments_label_lookup)(const unsigned char* label33, const void* label_context); + +/** Found outputs struct + * + * Struct for holding a found output along with data needed to spend it later. + * + * output: the x-only public key for the taproot output + * tweak: the 32-byte tweak needed to spend the output + * found_with_label: boolean value to indicate if the output was sent to a + * labeled address. If true, label will be set to a valid value. + * label: the label used. If found_with_label = false, this is set to + * an invalid value. + */ +typedef struct secp256k1_silentpayments_found_output { + secp256k1_xonly_pubkey output; + unsigned char tweak[32]; + int found_with_label; + secp256k1_silentpayments_label label; +} secp256k1_silentpayments_found_output; + +/** Scan for Silent Payments transaction outputs. + * + * Given a prevouts_summary object, a recipient's 32 byte scan key and spend public key, + * and the relevant transaction outputs, scan for outputs belonging to + * the recipient and return the tweak(s) needed for spending the output(s). An + * optional label_lookup callback function and label_context can be passed if + * the recipient uses labels. This allows for checking if a label exists in + * the recipients label cache and retrieving the label tweak during scanning. + * + * If used, the `label_lookup` function must return a pointer to a 32-byte label + * tweak if the label is found, or NULL otherwise. The returned pointer must remain + * valid until the next call to `label_lookup` or until the function returns, + * whichever comes first. It is not retained beyond that. + * + * For creating the label cache, `secp256k1_silentpayments_recipient_label_create` + * and `secp256k1_silentpayments_recipient_label_serialize` can be used. + * + * Note: + * Scanning is bounded by SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT and may + * miss outputs if a transaction contains more outputs for a single scan public + * key group than this limit. + * + * Returns: 1 if output scanning was successful. + * 0 if the transaction is not a Silent Payments transaction, + * or if the arguments are invalid. + * + * Args: ctx: pointer to a context object + * Out: found_outputs: pointer to an array of pointers to found + * output objects. The found outputs array MUST + * have the same length as the tx_outputs array. + * n_found_outputs: pointer to an integer indicating the final + * size of the found outputs array. This number + * represents the number of outputs found while + * scanning (0 if none are found). Can't be larger than + * SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT. + * In: tx_outputs: pointer to the transaction's x-only public key outputs, + * in their original transaction (vout) order + * n_tx_outputs: the size of the tx_outputs array. + * scan_key32: pointer to the recipient's 32 byte scan key. The scan + * key is valid if it passes secp256k1_ec_seckey_verify + * prevouts_summary: pointer to the transaction prevouts summary data (see + * `secp256k1_silentpayments_recipient_prevouts_summary_create`). + * unlabeled_spend_pubkey: pointer to the recipient's unlabeled spend public key + * label_lookup: pointer to a callback function for looking up + * a label value. This function takes a serialized 33-byte + * label as an argument and returns a pointer to the + * 32-byte label tweak if the label exists, otherwise + * returns a NULL pointer (NULL if labels are not + * used) + * label_context: pointer to a label context object (NULL if + * labels are not used or context is not needed) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_recipient_scan_outputs( + const secp256k1_context *ctx, + secp256k1_silentpayments_found_output **found_outputs, + uint32_t *n_found_outputs, + const secp256k1_xonly_pubkey * const *tx_outputs, + size_t n_tx_outputs, + const unsigned char *scan_key32, + const secp256k1_silentpayments_prevouts_summary *prevouts_summary, + const secp256k1_pubkey *unlabeled_spend_pubkey, + secp256k1_silentpayments_label_lookup label_lookup, + const void *label_context +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(6) SECP256K1_ARG_NONNULL(7) SECP256K1_ARG_NONNULL(8); + +#ifdef __cplusplus +} +#endif + +#endif /* SECP256K1_SILENTPAYMENTS_H */ diff --git a/components/libwally-core/silentpayments/src/modules/silentpayments/main_impl.h b/components/libwally-core/silentpayments/src/modules/silentpayments/main_impl.h new file mode 100644 index 00000000..d2a910e3 --- /dev/null +++ b/components/libwally-core/silentpayments/src/modules/silentpayments/main_impl.h @@ -0,0 +1,800 @@ +/*********************************************************************** + * Distributed under the MIT software license, see the accompanying * + * file COPYING or https://www.opensource.org/licenses/mit-license.php.* + ***********************************************************************/ + +#ifndef SECP256K1_MODULE_SILENTPAYMENTS_MAIN_H +#define SECP256K1_MODULE_SILENTPAYMENTS_MAIN_H + +#include "../../../include/secp256k1.h" +#include "../../../include/secp256k1_extrakeys.h" +#include "../../../include/secp256k1_silentpayments.h" + +#include "../../eckey.h" +#include "../../ecmult.h" +#include "../../ecmult_const.h" +#include "../../ecmult_gen.h" +#include "../../group.h" +#include "../../hash.h" +#include "../../hsort.h" + +/** magic bytes for ensuring prevouts_summary objects were initialized correctly. */ +static const unsigned char secp256k1_silentpayments_prevouts_summary_magic[4] = { 0xa7, 0x1c, 0xd3, 0x5e }; + +/** Sort an array of Silent Payments recipients. This is used to group recipients by scan pubkey to + * ensure the correct values of k are used when creating multiple outputs for a recipient. + * Since heap sort is unstable, we use the recipient's index as tie-breaker to have a well-defined + * order, i.e. within scan pubkey groups, the spend pubkeys appear in the same order as they were + * passed in. + */ +static int secp256k1_silentpayments_recipient_sort_cmp(const void* pk1, const void* pk2, void *ctx) { + const secp256k1_silentpayments_recipient *r1 = *(const secp256k1_silentpayments_recipient **)pk1; + const secp256k1_silentpayments_recipient *r2 = *(const secp256k1_silentpayments_recipient **)pk2; + + const int ret = secp256k1_ec_pubkey_cmp((secp256k1_context *)ctx, &r1->scan_pubkey, &r2->scan_pubkey); + if (ret != 0) { + return ret; + } else { + return (r1->index > r2->index) - (r1->index < r2->index); + } +} + +static void secp256k1_silentpayments_recipient_sort(const secp256k1_context* ctx, const secp256k1_silentpayments_recipient **recipients, size_t n_recipients) { + /* Suppress wrong warning (fixed in MSVC 19.33) */ + #if defined(_MSC_VER) && (_MSC_VER < 1933) + #pragma warning(push) + #pragma warning(disable: 4090) + #endif + + secp256k1_hsort(recipients, n_recipients, sizeof(*recipients), secp256k1_silentpayments_recipient_sort_cmp, (void *)ctx); + + #if defined(_MSC_VER) && (_MSC_VER < 1933) + #pragma warning(pop) + #endif +} + +/** Set hash state to the BIP340 tagged hash midstate for "BIP0352/Inputs". */ +static void secp256k1_silentpayments_sha256_init_inputs(secp256k1_sha256* hash) { + static const uint32_t midstate[8] = { + 0xd4143ffcul, 0x012ea4b5ul, 0x36e21c8ful, 0xf7ec7b54ul, + 0x4dd4e2acul, 0x9bcaa0a4ul, 0xe244899bul, 0xcd06903eul + }; + secp256k1_sha256_initialize_midstate(hash, 64, midstate); +} + +/** Callers must ensure that pubkey_sum is not the point at infinity before calling this function. */ +static int secp256k1_silentpayments_calculate_input_hash_scalar(const secp256k1_hash_ctx *hash_ctx, secp256k1_scalar *input_hash_scalar, const unsigned char *outpoint_smallest36, secp256k1_ge *pubkey_sum) { + secp256k1_sha256 hash; + unsigned char pubkey_sum_ser[33]; + unsigned char input_hash[32]; + int overflow; + + secp256k1_silentpayments_sha256_init_inputs(&hash); + secp256k1_sha256_write(hash_ctx, &hash, outpoint_smallest36, 36); + secp256k1_eckey_pubkey_serialize33(pubkey_sum, pubkey_sum_ser); + secp256k1_sha256_write(hash_ctx, &hash, pubkey_sum_ser, sizeof(pubkey_sum_ser)); + secp256k1_sha256_finalize(hash_ctx, &hash, input_hash); + /* Convert input_hash to a scalar. + * + * This can only fail if the output of the hash function is zero or greater than or equal to the curve order, which + * happens with negligible probability. Normally, we would use VERIFY_CHECK as opposed to returning an error + * since returning an error here would result in an untestable branch in the code. But in this case, we return + * an error to ensure strict compliance with BIP0352. + */ + secp256k1_scalar_set_b32(input_hash_scalar, input_hash, &overflow); + return (!secp256k1_scalar_is_zero(input_hash_scalar)) & (!overflow); +} + +static void secp256k1_silentpayments_create_shared_secret(unsigned char *shared_secret33, const secp256k1_ge *public_component, const secp256k1_scalar *secret_component) { + secp256k1_gej ss_j; + secp256k1_ge ss; + + VERIFY_CHECK(!secp256k1_ge_is_infinity(public_component)); + VERIFY_CHECK(!secp256k1_scalar_is_zero(secret_component)); + + secp256k1_ecmult_const(&ss_j, public_component, secret_component); + secp256k1_ge_set_gej(&ss, &ss_j); + + /* serialize shared secret in constant-time */ + secp256k1_fe_normalize(&ss.x); + secp256k1_fe_normalize(&ss.y); + shared_secret33[0] = SECP256K1_TAG_PUBKEY_EVEN | secp256k1_fe_is_odd(&ss.y); + secp256k1_fe_get_b32(&shared_secret33[1], &ss.x); + + /* Leaking these values would break indistinguishability of the transaction, so clear them. */ + secp256k1_ge_clear(&ss); + secp256k1_gej_clear(&ss_j); +} + +/** Set hash state to the BIP340 tagged hash midstate for "BIP0352/SharedSecret". */ +static void secp256k1_silentpayments_sha256_init_sharedsecret(secp256k1_sha256* hash) { + static const uint32_t midstate[8] = { + 0x88831537ul, 0x5127079bul, 0x69c2137bul, 0xab0303e6ul, + 0x98fa21faul, 0x4a888523ul, 0xbd99daabul, 0xf25e5e0aul + }; + secp256k1_sha256_initialize_midstate(hash, 64, midstate); +} + +static int secp256k1_silentpayments_create_output_tweak(const secp256k1_context *ctx, secp256k1_scalar *t_k_scalar, const unsigned char *shared_secret33, uint32_t k) { + const secp256k1_hash_ctx *hash_ctx = secp256k1_get_hash_context(ctx); + secp256k1_sha256 hash; + unsigned char hash_ser[32]; + unsigned char k_serialized[4]; + int overflow; + + /* Compute hash(shared_secret || ser_32(k)) [sha256 with tag "BIP0352/SharedSecret"] */ + secp256k1_silentpayments_sha256_init_sharedsecret(&hash); + secp256k1_sha256_write(hash_ctx, &hash, shared_secret33, 33); + secp256k1_write_be32(k_serialized, k); + secp256k1_sha256_write(hash_ctx, &hash, k_serialized, sizeof(k_serialized)); + secp256k1_sha256_finalize(hash_ctx, &hash, hash_ser); + + /* The only thing that the attacker can do with the hashed secret is derive the final pubkeys. + * On the side of the sender, we assume that will reveal those on the blockchain anyway. + * On the side of the scanner, we assume that the caller wants to branch when a payment is found. */ + secp256k1_declassify(ctx, hash_ser, sizeof(hash_ser)); + + /* Convert output tweak t_k to a scalar. + * + * This can only fail if the output of the hash function is zero or greater than or equal to the curve order, which + * happens with negligible probability. Normally, we would use VERIFY_CHECK as opposed to returning an error + * since returning an error here would result in an untestable branch in the code. But in this case, we return + * an error to ensure strict compliance with BIP0352. + */ + secp256k1_scalar_set_b32(t_k_scalar, hash_ser, &overflow); + /* Leaking this value would break indistinguishability of the transaction, so clear it. */ + secp256k1_memclear_explicit(hash_ser, sizeof(hash_ser)); + secp256k1_sha256_clear(&hash); + return (!secp256k1_scalar_is_zero(t_k_scalar)) & (!overflow); +} + +static int secp256k1_silentpayments_create_output_pubkey(const secp256k1_context *ctx, secp256k1_xonly_pubkey *output_xonly, const unsigned char *shared_secret33, const secp256k1_pubkey *spend_pubkey, uint32_t k) { + secp256k1_ge output_ge; + secp256k1_scalar t_k_scalar; + /* Calculate the output tweak t_k and convert it to a scalar. + * + * Note: _create_output_tweak can only fail if the output of the hash function is zero or greater than or equal to + * the curve order, which is statistically improbable. Returning an error here results in an untestable branch in + * the code, but we do this anyways to ensure strict compliance with BIP0352. + */ + if (!secp256k1_silentpayments_create_output_tweak(ctx, &t_k_scalar, shared_secret33, k)) { + secp256k1_scalar_clear(&t_k_scalar); + return 0; + } + + if (!secp256k1_pubkey_load(ctx, &output_ge, spend_pubkey)) { + secp256k1_scalar_clear(&t_k_scalar); + return 0; + } + /* `tweak_add` only fails if t_k_scalar * G = -spend_pubkey. Considering t_k is the output of a hash function, this + * will happen only with negligible probability for honestly created spend_pubkey, but we handle this error anyway + * to protect against this function being called with malicious inputs, i.e., + * spend_pubkey = -(_create_output_tweak(shared_secret33, k))*G + */ + if (!secp256k1_eckey_pubkey_tweak_add(&output_ge, &t_k_scalar)) { + secp256k1_scalar_clear(&t_k_scalar); + return 0; + } + secp256k1_fe_normalize_var(&output_ge.y); + secp256k1_extrakeys_ge_even_y(&output_ge); + secp256k1_xonly_pubkey_save(output_xonly, &output_ge); + + /* Leaking this value would break indistinguishability of the transaction, so clear it. */ + secp256k1_scalar_clear(&t_k_scalar); + return 1; +} + +int secp256k1_silentpayments_sender_create_outputs( + const secp256k1_context *ctx, + secp256k1_xonly_pubkey **generated_outputs, + const secp256k1_silentpayments_recipient **recipients, + size_t n_recipients, + const unsigned char *outpoint_smallest36, + const secp256k1_keypair * const *keypairs, + size_t n_keypairs, + const unsigned char * const *seckeys, + size_t n_seckeys +) { + size_t i; + uint32_t k; + secp256k1_scalar seckey_sum_scalar, addend, input_hash_scalar; + secp256k1_ge prevouts_pubkey_sum_ge; + unsigned char shared_secret[33]; + secp256k1_pubkey current_scan_pubkey; + int ret, sum_is_zero; + + /* Sanity check inputs. */ + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(generated_outputs != NULL); + ARG_CHECK(recipients != NULL); + ARG_CHECK(n_recipients > 0); + ARG_CHECK(outpoint_smallest36 != NULL); + ARG_CHECK((seckeys != NULL) || (keypairs != NULL)); + if (keypairs != NULL) { + ARG_CHECK(n_keypairs > 0); + for (i = 0; i < n_keypairs; i++) { + ARG_CHECK(keypairs[i] != NULL); + } + } else { + ARG_CHECK(n_keypairs == 0); + } + if (seckeys != NULL) { + ARG_CHECK(n_seckeys > 0); + for (i = 0; i < n_seckeys; i++) { + ARG_CHECK(seckeys[i] != NULL); + } + } else { + ARG_CHECK(n_seckeys == 0); + } + for (i = 0; i < n_recipients; i++) { + ARG_CHECK(generated_outputs[i] != NULL); + ARG_CHECK(recipients[i] != NULL); + ARG_CHECK(recipients[i]->index == i); + } + + seckey_sum_scalar = secp256k1_scalar_zero; + for (i = 0; i < n_seckeys; i++) { + ret = secp256k1_scalar_set_b32_seckey(&addend, seckeys[i]); + secp256k1_declassify(ctx, &ret, sizeof(ret)); + if (!ret) { + secp256k1_scalar_clear(&addend); + secp256k1_scalar_clear(&seckey_sum_scalar); + return 0; + } + secp256k1_scalar_add(&seckey_sum_scalar, &seckey_sum_scalar, &addend); + } + /* Secret keys used for taproot outputs have to be negated if they result in an odd point. This is to ensure + * the sender and recipient can arrive at the same shared secret when using x-only public keys. */ + for (i = 0; i < n_keypairs; i++) { + secp256k1_ge addend_point; + ret = secp256k1_keypair_load(ctx, &addend, &addend_point, keypairs[i]); + secp256k1_declassify(ctx, &ret, sizeof(ret)); + if (!ret) { + secp256k1_scalar_clear(&addend); + secp256k1_scalar_clear(&seckey_sum_scalar); + return 0; + } + if (secp256k1_fe_is_odd(&addend_point.y)) { + secp256k1_scalar_negate(&addend, &addend); + } + secp256k1_scalar_add(&seckey_sum_scalar, &seckey_sum_scalar, &addend); + } + /* If there are any failures in loading/summing up the secret keys, fail early. */ + sum_is_zero = secp256k1_scalar_is_zero(&seckey_sum_scalar); + secp256k1_declassify(ctx, &sum_is_zero, sizeof(sum_is_zero)); + secp256k1_scalar_clear(&addend); + if (sum_is_zero) { + secp256k1_scalar_clear(&seckey_sum_scalar); + return 0; + } + secp256k1_ecmult_gen_ge(&ctx->ecmult_gen_ctx, &prevouts_pubkey_sum_ge, &seckey_sum_scalar); + /* We declassify the pubkey sum because serializing a group element (done in the + * `_calculate_input_hash_scalar` call following) is not a constant-time operation. + */ + secp256k1_declassify(ctx, &prevouts_pubkey_sum_ge, sizeof(prevouts_pubkey_sum_ge)); + + /* Calculate the input_hash and convert it to a scalar so that it can be multiplied with the summed up private keys, i.e., a_sum = a_sum * input_hash. + * By multiplying the scalars together first, we can save an elliptic curve multiplication. + * + * Note: _input_hash_scalar can only fail if the output of the hash function is zero or greater than or equal to the + * curve order, which is statistically improbable. Returning an error here results in an untestable branch in the + * code, but we do this anyways to ensure strict compliance with BIP0352. + */ + if (!secp256k1_silentpayments_calculate_input_hash_scalar(secp256k1_get_hash_context(ctx), &input_hash_scalar, outpoint_smallest36, &prevouts_pubkey_sum_ge)) { + secp256k1_scalar_clear(&seckey_sum_scalar); + return 0; + } + secp256k1_scalar_mul(&seckey_sum_scalar, &seckey_sum_scalar, &input_hash_scalar); + /* _recipient_sort sorts the array of recipients in place by their scan public keys (lexicographically). + * This ensures that all recipients with the same scan public key are grouped together, as specified in BIP0352. + * + * More specifically, this ensures `k` is incremented from 0 to the number of requested outputs for each recipient group, + * where a recipient group is all addresses with the same scan public key. + */ + secp256k1_silentpayments_recipient_sort(ctx, recipients, n_recipients); + current_scan_pubkey = recipients[0]->scan_pubkey; + k = 0; /* This is a dead store but clang will emit a false positive warning if we omit it. */ + for (i = 0; i < n_recipients; i++) { + if ((i == 0) || (secp256k1_ec_pubkey_cmp(ctx, ¤t_scan_pubkey, &recipients[i]->scan_pubkey) != 0)) { + /* If we are on a different scan pubkey, its time to recreate the shared secret and reset k to 0. + * It's very unlikely the scan public key is invalid by this point, since this means the caller would + * have created the _silentpayments_recipient object incorrectly, but just to be sure we still check that + * the public key is valid. + */ + secp256k1_ge pk; + if (!secp256k1_pubkey_load(ctx, &pk, &recipients[i]->scan_pubkey)) { + secp256k1_scalar_clear(&seckey_sum_scalar); + /* Leaking this value would break indistinguishability of the transaction, so clear it. */ + secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret)); + return 0; + } + /* Creating the shared secret requires that the public and secret components are + * non-infinity and non-zero, respectively. Note that the involved parts (input hash, + * secret key sum, and scan public key) have all been verified at this point. */ + secp256k1_silentpayments_create_shared_secret(shared_secret, &pk, &seckey_sum_scalar); + k = 0; + } + /* If creating another output for the current recipient group exceeded the + * protocol limit, fail, as the recipient wouldn't be guaranteed to find it. */ + if (k >= SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT) { + secp256k1_scalar_clear(&seckey_sum_scalar); + secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret)); + return 0; + } + if (!secp256k1_silentpayments_create_output_pubkey(ctx, generated_outputs[recipients[i]->index], shared_secret, &recipients[i]->spend_pubkey, k)) { + secp256k1_scalar_clear(&seckey_sum_scalar); + secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret)); + return 0; + } + current_scan_pubkey = recipients[i]->scan_pubkey; + k++; + } + secp256k1_scalar_clear(&seckey_sum_scalar); + secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret)); + return 1; +} + +/** Set hash state to the BIP340 tagged hash midstate for "BIP0352/Label". */ +static void secp256k1_silentpayments_sha256_init_label(secp256k1_sha256* hash) { + static const uint32_t midstate[8] = { + 0x26b95d63ul, 0x8bf1b740ul, 0x10a5986ful, 0x06a387a5ul, + 0x2d1c1c30ul, 0xd035951aul, 0x2d7f0f96ul, 0x29e3e0dbul + }; + secp256k1_sha256_initialize_midstate(hash, 64, midstate); +} + +static const unsigned char secp256k1_silentpayments_label_magic[4] = { 0x27, 0x9d, 0x44, 0xba }; + +/* Saves a group element into a label. Requires that the provided group element is not infinity. */ +static void secp256k1_silentpayments_label_save(secp256k1_silentpayments_label* label, const secp256k1_ge* ge) { + memcpy(&label->data[0], secp256k1_silentpayments_label_magic, 4); + secp256k1_ge_to_bytes(label->data + 4, ge); +} + +/* Loads a group element from a label. Returns 1 unless the label wasn't properly initialized. */ +static int secp256k1_silentpayments_label_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_silentpayments_label* label) { + ARG_CHECK(secp256k1_memcmp_var(&label->data[0], secp256k1_silentpayments_label_magic, 4) == 0); + secp256k1_ge_from_bytes(ge, label->data + 4); + return 1; +} + +int secp256k1_silentpayments_recipient_label_parse(const secp256k1_context* ctx, secp256k1_silentpayments_label* label, const unsigned char *in33) { + secp256k1_ge ge; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(label != NULL); + memset(label, 0, sizeof(*label)); + ARG_CHECK(in33 != NULL); + + if (!secp256k1_eckey_pubkey_parse(&ge, in33, 33)) { + return 0; + } + + secp256k1_silentpayments_label_save(label, &ge); + return 1; +} + +int secp256k1_silentpayments_recipient_label_serialize(const secp256k1_context* ctx, unsigned char *out33, const secp256k1_silentpayments_label* label) { + secp256k1_ge ge; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(out33 != NULL); + memset(out33, 0, 33); + ARG_CHECK(label != NULL); + + if (!secp256k1_silentpayments_label_load(ctx, &ge, label)) { + return 0; + } + secp256k1_eckey_pubkey_serialize33(&ge, out33); + return 1; +} + +int secp256k1_silentpayments_recipient_label_create(const secp256k1_context *ctx, secp256k1_silentpayments_label *label, unsigned char *label_tweak32, const unsigned char *scan_key32, uint32_t m) { + secp256k1_sha256 hash; + unsigned char m_serialized[4]; + secp256k1_ge label_ge; + secp256k1_scalar label_tweak_scalar; + int ret; + + /* Sanity check inputs. */ + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(label != NULL); + memset(label, 0, sizeof(*label)); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(label_tweak32 != NULL); + ARG_CHECK(scan_key32 != NULL); + + /* ensure that the passed scan key is valid, in order to avoid creating unspendable labels */ + ret = secp256k1_ec_seckey_verify(ctx, scan_key32); + + /* Compute hash(ser_256(b_scan) || ser_32(m)) [sha256 with tag "BIP0352/Label"] */ + secp256k1_silentpayments_sha256_init_label(&hash); + secp256k1_sha256_write(secp256k1_get_hash_context(ctx), &hash, scan_key32, 32); + secp256k1_write_be32(m_serialized, m); + secp256k1_sha256_write(secp256k1_get_hash_context(ctx), &hash, m_serialized, sizeof(m_serialized)); + secp256k1_sha256_finalize(secp256k1_get_hash_context(ctx), &hash, label_tweak32); + + ret &= secp256k1_ec_pubkey_create_helper(&ctx->ecmult_gen_ctx, &label_tweak_scalar, &label_ge, label_tweak32); + secp256k1_silentpayments_label_save(label, &label_ge); + secp256k1_memczero(label, sizeof(*label), !ret); + secp256k1_memczero(label_tweak32, 32, !ret); + + secp256k1_scalar_clear(&label_tweak_scalar); + secp256k1_memclear_explicit(m_serialized, sizeof(m_serialized)); + secp256k1_sha256_clear(&hash); + + return ret; +} + +int secp256k1_silentpayments_recipient_create_labeled_spend_pubkey(const secp256k1_context *ctx, secp256k1_pubkey *labeled_spend_pubkey, const secp256k1_pubkey *unlabeled_spend_pubkey, const secp256k1_silentpayments_label *label) { + secp256k1_ge labeled_spend_pubkey_ge, label_addend; + secp256k1_gej result_gej; + secp256k1_ge result_ge; + int ret; + + /* Sanity check inputs. */ + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(labeled_spend_pubkey != NULL); + memset(labeled_spend_pubkey, 0, sizeof(*labeled_spend_pubkey)); + ARG_CHECK(unlabeled_spend_pubkey != NULL); + ARG_CHECK(label != NULL); + + /* Calculate labeled_spend_pubkey = unlabeled_spend_pubkey + label. + * If either the label or spend public key is invalid, return early. + */ + ret = secp256k1_pubkey_load(ctx, &labeled_spend_pubkey_ge, unlabeled_spend_pubkey); + ret &= secp256k1_silentpayments_label_load(ctx, &label_addend, label); + if (!ret) { + return 0; + } + secp256k1_gej_set_ge(&result_gej, &labeled_spend_pubkey_ge); + secp256k1_gej_add_ge_var(&result_gej, &result_gej, &label_addend, NULL); + if (secp256k1_gej_is_infinity(&result_gej)) { + return 0; + } + + secp256k1_ge_set_gej_var(&result_ge, &result_gej); + secp256k1_pubkey_save(labeled_spend_pubkey, &result_ge); + + return 1; +} + +/** An explanation of the prevouts_summary object and its usage: + * + * The prevouts_summary object contains: + * + * [magic: 4 bytes][boolean: 1 byte][prevouts_pubkey_sum: 64 bytes][input_hash: 32 bytes] + * + * The magic bytes are checked by functions using the prevouts_summary object to + * check that the prevouts_summary object was initialized correctly. + * + * The boolean (combined) indicates whether or not the summed prevout public keys and the + * input_hash scalar have already been combined or are both included. The reason + * for keeping input_hash and the summed prevout public keys separate is so that an elliptic + * curve multiplication can be avoided when creating the shared secret, i.e., + * (recipient_scan_key * input_hash) * prevouts_pubkey_sum. + * + * But when storing the prevouts_summary object (not supported yet), either to send to + * light clients or for wallet rescans, we can save 32-bytes by combining the input_hash + * and prevouts_pubkey_sum and saving the resulting point serialized as a compressed + * public key, i.e., input_hash * prevouts_pubkey_sum. + * + * For each function: + * + * - `_recipient_prevouts_summary_create` always creates a prevouts_summary object with combined = false + */ + +int secp256k1_silentpayments_recipient_prevouts_summary_create( + const secp256k1_context *ctx, + secp256k1_silentpayments_prevouts_summary *prevouts_summary, + const unsigned char *outpoint_smallest36, + const secp256k1_xonly_pubkey * const *xonly_pubkeys, + size_t n_xonly_pubkeys, + const secp256k1_pubkey * const *pubkeys, + size_t n_pubkeys +) { + size_t i; + secp256k1_ge prevouts_pubkey_sum_ge, addend; + secp256k1_gej prevouts_pubkey_sum_gej; + secp256k1_scalar input_hash_scalar; + + /* Sanity check inputs */ + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(prevouts_summary != NULL); + memset(prevouts_summary, 0, sizeof(*prevouts_summary)); + ARG_CHECK(outpoint_smallest36 != NULL); + ARG_CHECK((pubkeys != NULL) || (xonly_pubkeys != NULL)); + if (xonly_pubkeys != NULL) { + ARG_CHECK(n_xonly_pubkeys > 0); + for (i = 0; i < n_xonly_pubkeys; i++) { + ARG_CHECK(xonly_pubkeys[i] != NULL); + } + } else { + ARG_CHECK(n_xonly_pubkeys == 0); + } + if (pubkeys != NULL) { + ARG_CHECK(n_pubkeys > 0); + for (i = 0; i < n_pubkeys; i++) { + ARG_CHECK(pubkeys[i] != NULL); + } + } else { + ARG_CHECK(n_pubkeys == 0); + } + + /* Compute prevouts_pubkey_sum = A_1 + A_2 + ... + A_n. + * + * Since an attacker can maliciously craft transactions where the public keys sum to zero, fail early here + * to avoid making the caller do extra work, e.g., when building an index or scanning a malicious transaction. + * + * This will also fail if any of the provided prevout public keys are malformed. + */ + secp256k1_gej_set_infinity(&prevouts_pubkey_sum_gej); + for (i = 0; i < n_pubkeys; i++) { + if (!secp256k1_pubkey_load(ctx, &addend, pubkeys[i])) { + return 0; + } + secp256k1_gej_add_ge_var(&prevouts_pubkey_sum_gej, &prevouts_pubkey_sum_gej, &addend, NULL); + } + for (i = 0; i < n_xonly_pubkeys; i++) { + if (!secp256k1_xonly_pubkey_load(ctx, &addend, xonly_pubkeys[i])) { + return 0; + } + secp256k1_gej_add_ge_var(&prevouts_pubkey_sum_gej, &prevouts_pubkey_sum_gej, &addend, NULL); + } + if (secp256k1_gej_is_infinity(&prevouts_pubkey_sum_gej)) { + return 0; + } + secp256k1_ge_set_gej_var(&prevouts_pubkey_sum_ge, &prevouts_pubkey_sum_gej); + /* Calculate the input_hash and convert it to a scalar. + * + * Note: _input_hash_scalar can only fail if the output of the hash function is zero or greater than or equal to the + * curve order, which is statistically improbable. Returning an error here results in an untestable branch in the + * code, but we do this anyways to ensure strict compliance with BIP0352. + */ + if (!secp256k1_silentpayments_calculate_input_hash_scalar(secp256k1_get_hash_context(ctx), &input_hash_scalar, outpoint_smallest36, &prevouts_pubkey_sum_ge)) { + return 0; + } + memcpy(&prevouts_summary->data[0], secp256k1_silentpayments_prevouts_summary_magic, 4); + prevouts_summary->data[4] = 0; + secp256k1_ge_to_bytes(&prevouts_summary->data[5], &prevouts_pubkey_sum_ge); + secp256k1_scalar_get_b32(&prevouts_summary->data[5 + 64], &input_hash_scalar); + return 1; +} + +/* Label scanning involves the transformation from Jacobian (gej) to affine (ge) coordinates + * for serializing label candidates. As this is an expensive operation involving modular + * inversion, we don't do this one by one for each tx output, but collect multiple label + * candidates in Jacobian in order to apply Montgomery's trick for batch inversion (using + * the function `secp256k1_ge_set_all_gej_var`). For transactions with a large number of + * outputs, this speeds up scanning significantly (~2.5x). */ +enum { LABEL_BATCH_SIZE = 8 }; /* batch size expressed in number of tx outputs */ + +/* Check the label cache for each pair of candidates in a batch. + * Returns the first matching tx output index, or -1 if none has a matching label. */ +static int secp256k1_silentpayments_check_label_batch( + secp256k1_ge *label_ge, + const unsigned char **label_tweak, + const secp256k1_gej *label_candidates_gej, + size_t n_batch, + size_t j_start, + secp256k1_silentpayments_label_lookup label_lookup, + const void *label_context +) { + secp256k1_ge label_candidates_ge[2 * LABEL_BATCH_SIZE]; + unsigned char label33[33]; + size_t i; + + *label_tweak = NULL; + secp256k1_ge_set_all_gej_var(label_candidates_ge, label_candidates_gej, 2 * n_batch); + for (i = 0; i < 2 * n_batch; i++) { + /* Serialize only non-infinity points because candidates are collected only when + * tx_output != unlabeled_output_xonly. */ + secp256k1_eckey_pubkey_serialize33(&label_candidates_ge[i], label33); + *label_tweak = label_lookup(label33, label_context); + if (*label_tweak != NULL) { + *label_ge = label_candidates_ge[i]; + return (int)(j_start + i / 2); + } + } + return -1; +} + +int secp256k1_silentpayments_recipient_scan_outputs( + const secp256k1_context *ctx, + secp256k1_silentpayments_found_output **found_outputs, uint32_t *n_found_outputs, + const secp256k1_xonly_pubkey * const *tx_outputs, size_t n_tx_outputs, + const unsigned char *scan_key32, + const secp256k1_silentpayments_prevouts_summary *prevouts_summary, + const secp256k1_pubkey *unlabeled_spend_pubkey, + secp256k1_silentpayments_label_lookup label_lookup, + const void *label_context +) { + secp256k1_scalar scan_key_scalar; + secp256k1_ge unlabeled_spend_pubkey_ge, prevouts_pubkey_sum_ge, tx_output_ge; + unsigned char shared_secret[33]; + uint32_t k, k_max; + size_t i; + int found_idx, combined, valid_scan_key, ret; + + /* Sanity check inputs */ + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(found_outputs != NULL); + ARG_CHECK(n_found_outputs != NULL); + *n_found_outputs = 0; + ARG_CHECK(tx_outputs != NULL); + ARG_CHECK(n_tx_outputs > 0); + for (i = 0; i < n_tx_outputs; i++) { + ARG_CHECK(found_outputs[i] != NULL); + ARG_CHECK(tx_outputs[i] != NULL); + /* Validate each tx output object early so malformed pubkeys are always rejected. */ + if (!secp256k1_xonly_pubkey_load(ctx, &tx_output_ge, tx_outputs[i])) { + return 0; + } + } + ARG_CHECK(scan_key32 != NULL); + ARG_CHECK(prevouts_summary != NULL); + ARG_CHECK(secp256k1_memcmp_var(&prevouts_summary->data[0], secp256k1_silentpayments_prevouts_summary_magic, 4) == 0); + ARG_CHECK(unlabeled_spend_pubkey != NULL); + /* Passing a context without a lookup function is non-sensical */ + if (label_context != NULL) { + ARG_CHECK(label_lookup != NULL); + } + valid_scan_key = secp256k1_scalar_set_b32_seckey(&scan_key_scalar, scan_key32); + secp256k1_declassify(ctx, &valid_scan_key, sizeof(valid_scan_key)); + if (!valid_scan_key) { + secp256k1_scalar_clear(&scan_key_scalar); + return 0; + } + secp256k1_ge_from_bytes(&prevouts_pubkey_sum_ge, &prevouts_summary->data[5]); + combined = (int)prevouts_summary->data[4]; + if (!combined) { + secp256k1_scalar input_hash_scalar; + secp256k1_scalar_set_b32(&input_hash_scalar, &prevouts_summary->data[5 + 64], NULL); + secp256k1_scalar_mul(&scan_key_scalar, &scan_key_scalar, &input_hash_scalar); + } + ret = secp256k1_pubkey_load(ctx, &unlabeled_spend_pubkey_ge, unlabeled_spend_pubkey); + if (!ret) { + secp256k1_scalar_clear(&scan_key_scalar); + return 0; + } + /* Creating the shared secret requires that the public and secret components are + * non-infinity and non-zero, respectively. Note that the involved parts (input hash, + * scan secret key, and prevouts public key sum) have all been verified at this point, + * assuming that the user hasn't tampered the `prevouts_summary` object manually. */ + secp256k1_silentpayments_create_shared_secret(shared_secret, &prevouts_pubkey_sum_ge, &scan_key_scalar); + /* Clear the scan_key_scalar since we no longer need it and leaking this value would break indistinguishability of the transaction. */ + secp256k1_scalar_clear(&scan_key_scalar); + + found_idx = -1; + /* Don't look further than the per-group recipient limit, in order to avoid quadratic scaling issues. */ + k_max = (n_tx_outputs < SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT) ? + n_tx_outputs : SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT; + for (k = 0; k < k_max; k++) { + secp256k1_scalar t_k_scalar; + secp256k1_xonly_pubkey unlabeled_output_xonly; + secp256k1_ge unlabeled_output_ge = unlabeled_spend_pubkey_ge; + secp256k1_ge unlabeled_output_negated_ge; + secp256k1_gej label_candidates_gej[2 * LABEL_BATCH_SIZE]; /* two candidates per tx output (one per y-parity) */ + size_t label_batch_idx = 0; /* current index within a batch */ + const unsigned char *label_tweak = NULL; + secp256k1_ge label_ge; + size_t j; + + /* Calculate the output tweak t_k and convert it to a scalar. + * + * Note: _create_output_tweak can only fail if the output of the hash function is zero or greater than or equal + * to the curve order, which is statistically improbable. Returning an error here results in an untestable + * branch in the code, but we do this anyways to ensure strict compliance with BIP0352. + */ + if (!secp256k1_silentpayments_create_output_tweak(ctx, &t_k_scalar, shared_secret, k)) { + secp256k1_scalar_clear(&t_k_scalar); + secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret)); + return 0; + } + + /* Calculate unlabeled_output = unlabeled_spend_pubkey + t_k * G. + * This can fail if t_k * G is the negation of unlabeled_spend_pubkey, but this happens only with negligible + * probability for honestly created unlabeled_spend_pubkey as t_k is the output of a hash function. */ + if (!secp256k1_eckey_pubkey_tweak_add(&unlabeled_output_ge, &t_k_scalar)) { + /* Leaking these values would break indistinguishability of the transaction, so clear them. */ + secp256k1_scalar_clear(&t_k_scalar); + secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret)); + return 0; + } + /* Calculate unlabeled_output_negated = -unlabeled_output */ + secp256k1_ge_neg(&unlabeled_output_negated_ge, &unlabeled_output_ge); + + found_idx = -1; + secp256k1_fe_normalize_var(&unlabeled_output_ge.y); + secp256k1_extrakeys_ge_even_y(&unlabeled_output_ge); + secp256k1_xonly_pubkey_save(&unlabeled_output_xonly, &unlabeled_output_ge); + for (j = 0; j < n_tx_outputs; j++) { + if (secp256k1_xonly_pubkey_cmp(ctx, &unlabeled_output_xonly, tx_outputs[j]) == 0) { + label_tweak = NULL; + found_idx = j; + /* An earlier label match takes precedence over this direct match. */ + if (label_batch_idx > 0) { + int label_found_idx = secp256k1_silentpayments_check_label_batch( + &label_ge, &label_tweak, label_candidates_gej, label_batch_idx, + j - label_batch_idx, label_lookup, label_context); + if (label_found_idx != -1) { + found_idx = label_found_idx; + } + } + break; + } + + /* If not found, proceed to check for labels (if a label lookup function is provided). */ + if (label_lookup != NULL) { + secp256k1_gej tx_output_gej; + secp256k1_gej *label_candidate1 = &label_candidates_gej[2 * label_batch_idx]; + secp256k1_gej *label_candidate2 = &label_candidates_gej[2 * label_batch_idx + 1]; + + /* Calculate scan label candidates: + * label_candidate1 = tx_output - unlabeled_output + * label_candidate2 = -tx_output - unlabeled_output + * and store them in the batch */ + secp256k1_xonly_pubkey_load(ctx, &tx_output_ge, tx_outputs[j]); + secp256k1_gej_set_ge(&tx_output_gej, &tx_output_ge); + secp256k1_gej_add_ge_var(label_candidate1, &tx_output_gej, &unlabeled_output_negated_ge, NULL); + secp256k1_gej_neg(&tx_output_gej, &tx_output_gej); + secp256k1_gej_add_ge_var(label_candidate2, &tx_output_gej, &unlabeled_output_negated_ge, NULL); + label_batch_idx++; + /* If the batch is filled or we have reached the last transaction output, perform batch + * inversion and check the label cache for each label candidate entry in the batch */ + if (label_batch_idx == LABEL_BATCH_SIZE || j == (n_tx_outputs-1)) { + found_idx = secp256k1_silentpayments_check_label_batch( + &label_ge, &label_tweak, label_candidates_gej, label_batch_idx, + j + 1 - label_batch_idx, label_lookup, label_context); + label_batch_idx = 0; + } + if (found_idx != -1) { + break; + } + } + } + if (found_idx != -1) { + found_outputs[k]->output = *tx_outputs[found_idx]; + secp256k1_scalar_get_b32(found_outputs[k]->tweak, &t_k_scalar); + /* Clear the t_k_scalar since we no longer need it and leaking this value would + * break indistinguishability of the transaction. */ + secp256k1_scalar_clear(&t_k_scalar); + if (label_tweak != NULL) { + found_outputs[k]->found_with_label = 1; + /* This is extremely unlikely to fail in that it can only really happen if label_tweak + * is the negation of the shared secret tweak. But since both tweak and label_tweak are + * created by hashing data, practically speaking this would only happen if an attacker + * tricked us into using a particular label_tweak (deviating from the protocol). + * Note that this call could also fail due to a malformed label_tweak data from the + * label cache, but we generally assume the passed in data is created using the API + * functions and thus have already been checked for correctness. + * + * Furthermore, although technically a failure for ec_seckey_tweak_add, this is not treated + * as a failure for Silent Payments because the output is still spendable with just the + * spend secret key. We set `tweak = 0` for this case. + */ + if (!secp256k1_ec_seckey_tweak_add(ctx, found_outputs[k]->tweak, label_tweak)) { + memset(found_outputs[k]->tweak, 0, 32); + } + secp256k1_silentpayments_label_save(&found_outputs[k]->label, &label_ge); + } else { + found_outputs[k]->found_with_label = 0; + /* Set the label to an invalid value. */ + memset(&found_outputs[k]->label, 0, sizeof(found_outputs[k]->label)); + } + /* Reset everything for the next round of scanning. */ + label_tweak = NULL; + } else { + secp256k1_scalar_clear(&t_k_scalar); + break; + } + } + *n_found_outputs = k; + + /* Leaking the shared_secret would break indistinguishability of the transaction, so clear it. */ + secp256k1_memclear_explicit(shared_secret, sizeof(shared_secret)); + return 1; +} + +#endif diff --git a/main/core/test/.gitignore b/main/core/test/.gitignore index 1c27d1bc..ec1ad634 100644 --- a/main/core/test/.gitignore +++ b/main/core/test/.gitignore @@ -25,3 +25,4 @@ test_key test_crypto_utils test_pbkdf2 test_pbkdf2_core.o +test_silentpayments diff --git a/main/core/test/Makefile b/main/core/test/Makefile index da46d0df..4fe7b4c2 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -3,8 +3,9 @@ CFLAGS = -Wall -Wextra -g 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 +SECP_INCS = -I$(WALLY_DIR)/upstream/src/secp256k1/include -I$(WALLY_DIR)/silentpayments/include WALLY_PRIV_INCS = \ -I$(WALLY_DIR) \ @@ -35,7 +36,7 @@ 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) $(SECP_INCS) -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; @@ -158,9 +159,12 @@ SRCS_BIP138_BACKUP = test_bip138_backup.c TARGET_BIP138_BACKUP = test_bip138_backup KEY_STUB_SRC = stubs/key_stub.c -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) +SRCS_SILENTPAYMENTS = test_silentpayments.c +TARGET_SILENTPAYMENTS = test_silentpayments -$(LIBWALLY): $(WALLY_SRC) $(wildcard $(WALLY_DIR)/upstream/src/*.c) $(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 +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_SILENTPAYMENTS) + +$(LIBWALLY): $(WALLY_SRC) $(wildcard $(WALLY_DIR)/upstream/src/*.c) $(WALLY_DIR)/kern_bech32.h $(wildcard $(WALLY_DIR)/silentpayments/src/modules/silentpayments/*.h) $(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 $< $(CC) $(CFLAGS) -I$(WALLY_INC) -I$(ROOT)/components/secure_memory/include -c -o kern_wally.o $(WALLY_DIR)/kern_wally.c $(CC) $(CFLAGS) -I$(ROOT)/components/secure_memory/include -c -o secret_alloc.o $(ROOT)/components/secure_memory/secret_alloc.c @@ -267,7 +271,10 @@ $(TARGET_BIP138_BACKUP): $(SRCS_BIP138_BACKUP) ../bip138_backup.c ../bip138_keys ../script_templates.c ../ss_whitelist.c ../miniscript_policy.c \ $(BIP138_SRCS) $(LIBWALLY) $(KEF_LIBS) -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_SILENTPAYMENTS): $(SRCS_SILENTPAYMENTS) $(LIBWALLY) + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_SILENTPAYMENTS) $(LIBWALLY) + +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_SILENTPAYMENTS) ./$(TARGET_DERIV) ./$(TARGET_SS_PARSE) ./$(TARGET_SS_WHITELISTED) @@ -291,8 +298,9 @@ run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REG ./$(TARGET_PBKDF2) ./$(TARGET_BIP138_KEYS) ./$(TARGET_BIP138_BACKUP) + ./$(TARGET_SILENTPAYMENTS) 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) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) + 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_SILENTPAYMENTS) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) .PHONY: all run clean 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/simulator/CMakeLists.txt b/simulator/CMakeLists.txt index 7847a208..48d04852 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -56,13 +56,15 @@ 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 + ${WALLY_DIR}/silentpayments/include ) target_include_directories(wally PRIVATE From 42e754642d96586a440ea159a2e61315a2175d2e Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 12:16:13 +0000 Subject: [PATCH 09/13] feat(sp): add BIP374 DLEQ proofs --- main/core/dleq.c | 195 +++++++++++++++++++++++++++++++++++++ main/core/dleq.h | 27 +++++ main/core/test/.gitignore | 1 + main/core/test/Makefile | 14 ++- main/core/test/test_dleq.c | 167 +++++++++++++++++++++++++++++++ simulator/CMakeLists.txt | 1 + 6 files changed, 402 insertions(+), 3 deletions(-) create mode 100644 main/core/dleq.c create mode 100644 main/core/dleq.h create mode 100644 main/core/test/test_dleq.c 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/test/.gitignore b/main/core/test/.gitignore index ec1ad634..6ce942e8 100644 --- a/main/core/test/.gitignore +++ b/main/core/test/.gitignore @@ -26,3 +26,4 @@ test_crypto_utils test_pbkdf2 test_pbkdf2_core.o test_silentpayments +test_dleq diff --git a/main/core/test/Makefile b/main/core/test/Makefile index 4fe7b4c2..ff232d1e 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -162,7 +162,11 @@ KEY_STUB_SRC = stubs/key_stub.c SRCS_SILENTPAYMENTS = test_silentpayments.c TARGET_SILENTPAYMENTS = test_silentpayments -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_SILENTPAYMENTS) +SRCS_DLEQ = test_dleq.c +TARGET_DLEQ = test_dleq +DLEQ_SRC = ../dleq.c ../dleq.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_SILENTPAYMENTS) $(TARGET_DLEQ) $(LIBWALLY): $(WALLY_SRC) $(wildcard $(WALLY_DIR)/upstream/src/*.c) $(WALLY_DIR)/kern_bech32.h $(wildcard $(WALLY_DIR)/silentpayments/src/modules/silentpayments/*.h) $(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 $< @@ -274,7 +278,10 @@ $(TARGET_BIP138_BACKUP): $(SRCS_BIP138_BACKUP) ../bip138_backup.c ../bip138_keys $(TARGET_SILENTPAYMENTS): $(SRCS_SILENTPAYMENTS) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_SILENTPAYMENTS) $(LIBWALLY) -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_SILENTPAYMENTS) +$(TARGET_DLEQ): $(SRCS_DLEQ) $(DLEQ_SRC) $(LIBWALLY) + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DLEQ) ../dleq.c $(LIBWALLY) + +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_SILENTPAYMENTS) $(TARGET_DLEQ) ./$(TARGET_DERIV) ./$(TARGET_SS_PARSE) ./$(TARGET_SS_WHITELISTED) @@ -299,8 +306,9 @@ run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REG ./$(TARGET_BIP138_KEYS) ./$(TARGET_BIP138_BACKUP) ./$(TARGET_SILENTPAYMENTS) + ./$(TARGET_DLEQ) 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_SILENTPAYMENTS) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) + 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_SILENTPAYMENTS) $(TARGET_DLEQ) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) .PHONY: all run clean 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/simulator/CMakeLists.txt b/simulator/CMakeLists.txt index 48d04852..cd2cd4fb 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -204,6 +204,7 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/descriptor_checksum.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/dleq.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) From 6df9f21aa398da86205acccec3328b37d4969e8d Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 12:20:03 +0000 Subject: [PATCH 10/13] feat(sp): export the silent payment descriptor over the bwk QR protocol --- main/core/descriptor_checksum.c | 4 + main/core/descriptor_checksum.h | 4 + main/core/silent_payments.c | 133 ++++++++++++++++++++++++++++++++ main/core/silent_payments.h | 37 +++++++++ main/core/test/.gitignore | 1 + main/core/test/Makefile | 14 +++- main/core/test/test_sp_keys.c | 125 ++++++++++++++++++++++++++++++ main/pages/bip_flow/bip_flow.c | 51 +++++++++++- simulator/CMakeLists.txt | 1 + 9 files changed, 366 insertions(+), 4 deletions(-) create mode 100644 main/core/silent_payments.c create mode 100644 main/core/silent_payments.h create mode 100644 main/core/test/test_sp_keys.c diff --git a/main/core/descriptor_checksum.c b/main/core/descriptor_checksum.c index 2f3e5f87..06b501ff 100644 --- a/main/core/descriptor_checksum.c +++ b/main/core/descriptor_checksum.c @@ -94,6 +94,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) diff --git a/main/core/descriptor_checksum.h b/main/core/descriptor_checksum.h index 23eb2d80..32639139 100644 --- a/main/core/descriptor_checksum.h +++ b/main/core/descriptor_checksum.h @@ -8,6 +8,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/silent_payments.c b/main/core/silent_payments.c new file mode 100644 index 00000000..874ab050 --- /dev/null +++ b/main/core/silent_payments.c @@ -0,0 +1,133 @@ +#include "silent_payments.h" +#include "../utils/secure_mem.h" +#include "descriptor_checksum.h" +#include "key.h" +#include +#include +#include +#include +#include +#include + +#define SP_PURPOSE 352 +#define SP_ACCOUNT 0 +#define SP_SCAN_BRANCH 1 +#define SP_SPEND_BRANCH 0 +#define SP_PATH_DEPTH 5 +#define SP_VERSION 0 + +#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; } + +// m/352'/coin'/0'/branch'/0 +static bool derive_sp_key(bool is_testnet, uint32_t branch, + unsigned char *secret_out, + unsigned char *pubkey_out) { + const uint32_t path[SP_PATH_DEPTH] = { + BIP32_INITIAL_HARDENED_CHILD | SP_PURPOSE, + BIP32_INITIAL_HARDENED_CHILD | sp_coin(is_testnet), + BIP32_INITIAL_HARDENED_CHILD | SP_ACCOUNT, + BIP32_INITIAL_HARDENED_CHILD | branch, 0}; + struct ext_key *key = NULL; + + 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)); } + +// 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_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; +} diff --git a/main/core/silent_payments.h b/main/core/silent_payments.h new file mode 100644 index 00000000..9918762e --- /dev/null +++ b/main/core/silent_payments.h @@ -0,0 +1,37 @@ +#ifndef SILENT_PAYMENTS_H +#define SILENT_PAYMENTS_H + +#include "../utils/attributes.h" +#include + +#define SP_SECRET_LEN 32 +#define SP_PUBKEY_LEN 33 + +// 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); + +// 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); + +// 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); + +#endif // SILENT_PAYMENTS_H diff --git a/main/core/test/.gitignore b/main/core/test/.gitignore index 6ce942e8..3066572c 100644 --- a/main/core/test/.gitignore +++ b/main/core/test/.gitignore @@ -27,3 +27,4 @@ test_pbkdf2 test_pbkdf2_core.o test_silentpayments test_dleq +test_sp_keys diff --git a/main/core/test/Makefile b/main/core/test/Makefile index ff232d1e..1f4c1142 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -166,7 +166,11 @@ SRCS_DLEQ = test_dleq.c TARGET_DLEQ = test_dleq DLEQ_SRC = ../dleq.c ../dleq.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_SILENTPAYMENTS) $(TARGET_DLEQ) +SRCS_SP_KEYS = test_sp_keys.c +TARGET_SP_KEYS = test_sp_keys +SP_SRC = ../silent_payments.c ../silent_payments.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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(LIBWALLY): $(WALLY_SRC) $(wildcard $(WALLY_DIR)/upstream/src/*.c) $(WALLY_DIR)/kern_bech32.h $(wildcard $(WALLY_DIR)/silentpayments/src/modules/silentpayments/*.h) $(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 $< @@ -281,7 +285,10 @@ $(TARGET_SILENTPAYMENTS): $(SRCS_SILENTPAYMENTS) $(LIBWALLY) $(TARGET_DLEQ): $(SRCS_DLEQ) $(DLEQ_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_DLEQ) ../dleq.c $(LIBWALLY) -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_SILENTPAYMENTS) $(TARGET_DLEQ) +$(TARGET_SP_KEYS): $(SRCS_SP_KEYS) $(SP_SRC) $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(LIBWALLY) + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_SP_KEYS) ../silent_payments.c ../key.c ../bip32_path.c ../descriptor_checksum.c $(LIBWALLY) + +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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) ./$(TARGET_DERIV) ./$(TARGET_SS_PARSE) ./$(TARGET_SS_WHITELISTED) @@ -307,8 +314,9 @@ run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REG ./$(TARGET_BIP138_BACKUP) ./$(TARGET_SILENTPAYMENTS) ./$(TARGET_DLEQ) + ./$(TARGET_SP_KEYS) 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_SILENTPAYMENTS) $(TARGET_DLEQ) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) + 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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) .PHONY: all run clean diff --git a/main/core/test/test_sp_keys.c b/main/core/test/test_sp_keys.c new file mode 100644 index 00000000..0ea3f6bf --- /dev/null +++ b/main/core/test/test_sp_keys.c @@ -0,0 +1,125 @@ +#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"; + +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); +} + +int main(void) { + 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(); + key_unload(); + + printf("\n%d passed, %d failed\n", tests_passed, tests_failed); + return tests_failed ? 1 : 0; +} diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c index 35cc18fb..ac9027cb 100644 --- a/main/pages/bip_flow/bip_flow.c +++ b/main/pages/bip_flow/bip_flow.c @@ -7,12 +7,14 @@ #include "../../core/psbt.h" #include "../../core/registry.h" #include "../../core/settings.h" +#include "../../core/silent_payments.h" #include "../../core/wallet.h" #include "../../qr/encoder.h" #include "../../qr/viewer.h" #include "../../ui/dialog.h" #include "../../ui/theme.h" #include "../../ui/theme_widgets.h" +#include "../../utils/secure_mem.h" #include "../scan/scan.h" #include "../shared/address_checker.h" #include "../shared/descriptor_loader.h" @@ -31,6 +33,10 @@ #include #include +// Xpubs capability bits: miniscript segwit v0, miniscript taproot, silent +// payments v0 +#define XPUBS_CAPABILITIES (0x01 | 0x02 | 0x04) + typedef struct { lv_obj_t *parent; void (*return_cb)(void); @@ -219,7 +225,7 @@ static void get_xpubs_confirm_cb(bool confirmed, void *user_data) { response.body.xpubs.version.minor = (uint16_t)minor; response.body.xpubs.version.patch = patch; response.body.xpubs.version.flag = BWK_QR_RELEASE_STABLE; - response.body.xpubs.capabilities = 0x03; + response.body.xpubs.capabilities = XPUBS_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, @@ -390,6 +396,46 @@ static void handle_get_xpubs(void) { dialog_show_confirm(msg, get_xpubs_confirm_cb, NULL, DIALOG_STYLE_OVERLAY); } +static bool wallet_is_testnet(void) { + return wallet_get_network() == WALLET_NETWORK_TESTNET; +} + +static void get_sp_descriptor_confirm_cb(bool confirmed, void *user_data) { + (void)user_data; + if (!confirmed) { + show_error_response(BWK_QR_RESPONSE_ERROR_USER_DECLINED, "Declined"); + return; + } + + char *descriptor = NULL; + if (!sp_descriptor_alloc(wallet_is_testnet(), &descriptor)) { + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "Descriptor failed"); + return; + } + bwk_qr_response response; + fill_response_header(&response); + response.body.sp_descriptor.descriptor = descriptor; + show_response(&response); + SECURE_FREE_STRING(descriptor); +} + +static void handle_get_sp_descriptor(void) { + char fingerprint[BIP32_KEY_FINGERPRINT_LEN * 2 + 1]; + if (!key_get_fingerprint_hex(fingerprint)) { + show_error_response(BWK_QR_RESPONSE_ERROR_INTERNAL, "Fingerprint failed"); + return; + } + + char msg[256]; + snprintf(msg, sizeof(msg), + "Export the %s Silent Payments account of %s?\n\n" + "It carries the scan private key: whoever holds it sees every " + "payment this account receives, but cannot spend them.", + wallet_is_testnet() ? "Testnet" : "Mainnet", fingerprint); + dialog_show_confirm(msg, get_sp_descriptor_confirm_cb, NULL, + DIALOG_STYLE_OVERLAY); +} + static bool append_bip388_key(char *out, size_t out_size, size_t *off, const bwk_qr_bip388 *bip388, unsigned long index) { @@ -1000,6 +1046,9 @@ static void dispatch_request(void) { case BWK_QR_MESSAGE_SIGNING: handle_sign(); break; + case BWK_QR_MESSAGE_GET_SP_DESCRIPTOR: + handle_get_sp_descriptor(); + break; default: show_error_response(BWK_QR_RESPONSE_ERROR_MALFORMED_REQUEST, "Unknown request"); diff --git a/simulator/CMakeLists.txt b/simulator/CMakeLists.txt index cd2cd4fb..3f87ec93 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -205,6 +205,7 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/bip32_path.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/script_templates.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/dleq.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/silent_payments.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) From 4fb37a01ab8b0a21d87de25a081ed6518a4edad1 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 12:34:20 +0000 Subject: [PATCH 11/13] feat(psbt): fill BIP375 ECDH shares and silent payment output scripts --- main/core/psbt.c | 5 + main/core/psbt.h | 4 +- main/core/psbt_parse.c | 21 +- main/core/sp_psbt.c | 1024 ++++++++++++++++++++++++++++ main/core/sp_psbt.h | 65 ++ main/core/test/.gitignore | 1 + main/core/test/Makefile | 25 +- main/core/test/sp_fixture.h | 148 ++++ main/core/test/test_sp_psbt.c | 427 ++++++++++++ main/pages/scan/scan.c | 2 +- main/pages/scan/scan_internal.h | 3 + main/pages/scan/scan_psbt_review.c | 20 +- simulator/CMakeLists.txt | 1 + 13 files changed, 1732 insertions(+), 14 deletions(-) create mode 100644 main/core/sp_psbt.c create mode 100644 main/core/sp_psbt.h create mode 100644 main/core/test/sp_fixture.h create mode 100644 main/core/test/test_sp_psbt.c diff --git a/main/core/psbt.c b/main/core/psbt.c index 959b3501..20514ec6 100644 --- a/main/core/psbt.c +++ b/main/core/psbt.c @@ -3,6 +3,7 @@ #include "key.h" #include "psbt_internal.h" #include "script_templates.h" +#include "sp_psbt.h" #include "wallet.h" #include #include @@ -1205,6 +1206,10 @@ static struct wally_psbt *psbt_trim_v2(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 763e05c4..86afe20a 100644 --- a/main/core/psbt.h +++ b/main/core/psbt.h @@ -13,7 +13,9 @@ /* 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. */ KERN_WARN_UNUSED_RESULT bool psbt_parse_payload(const uint8_t *data, size_t len, struct wally_psbt **psbt_out); diff --git a/main/core/psbt_parse.c b/main/core/psbt_parse.c index be4a0b9b..33e01222 100644 --- a/main/core/psbt_parse.c +++ b/main/core/psbt_parse.c @@ -1,4 +1,5 @@ #include "psbt.h" +#include "sp_psbt.h" #include @@ -11,8 +12,22 @@ bool psbt_parse_payload(const uint8_t *data, size_t len, while (len > 0 && (data[len - 1] == '\n' || data[len - 1] == '\r' || data[len - 1] == ' ' || data[len - 1] == '\t')) len--; + if (len == 0) + return false; + + if (wally_psbt_from_bytes(data, len, WALLY_PSBT_PARSE_FLAG_COMPLETE, + psbt_out) == WALLY_OK) + return true; - return len > 0 && - wally_psbt_from_bytes(data, len, WALLY_PSBT_PARSE_FLAG_COMPLETE, - psbt_out) == WALLY_OK; + // A BIP375 PSBT leaves silent payment output scripts to the signer + if (wally_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; } diff --git a/main/core/sp_psbt.c b/main/core/sp_psbt.c new file mode 100644 index 00000000..43f0930c --- /dev/null +++ b/main/core/sp_psbt.c @@ -0,0 +1,1024 @@ +/* + * 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 "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 +// 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 +// 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" + +// 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; + +// Parity-adjusted signing keys of the inputs we own +typedef struct { + unsigned char (*keys)[SP_SECRET_LEN]; + size_t count; +} owned_inputs_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; + } +} + +// Input rules checked before deriving the outputs (bip375.rs +// validate_input_eligibility), then the owned key of an eligible input +static sp_psbt_result_t check_input(const struct wally_psbt *psbt, size_t i, + const signer_t *signer, + owned_inputs_t *owned) { + const struct wally_psbt_input *in = &psbt->inputs[i]; + const struct wally_tx_output *prevout = NULL; + bool eligible = false, is_ours = 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, &eligible); + if (result != SP_PSBT_OK || !eligible) + return result; + result = input_signing_key(psbt, i, prevout, signer, &is_ours, + owned->keys[owned->count]); + if (result != SP_PSBT_OK) + return result; + if (!is_ours) + return SP_PSBT_ERR_FOREIGN; + owned->count++; + return SP_PSBT_OK; +} + +static void owned_inputs_free(owned_inputs_t *owned) { + if (owned->keys) { + secure_memzero(owned->keys, owned->count * sizeof(*owned->keys)); + free(owned->keys); + } + owned->keys = NULL; + owned->count = 0; +} + +// The global share needs every eligible input's key, so all must be ours +static sp_psbt_result_t collect_owned_inputs(const struct wally_psbt *psbt, + const signer_t *signer, + owned_inputs_t *owned) { + owned->count = 0; + owned->keys = kern_secret_alloc(psbt->num_inputs * sizeof(*owned->keys)); + if (!owned->keys) + return SP_PSBT_ERR_CRYPTO; + for (size_t i = 0; i < psbt->num_inputs; i++) { + sp_psbt_result_t result = check_input(psbt, i, signer, owned); + if (result != SP_PSBT_OK) { + owned_inputs_free(owned); + return result; + } + } + if (owned->count) + return SP_PSBT_OK; + owned_inputs_free(owned); + return SP_PSBT_ERR_INPUT; +} + +static bool sum_owned_keys(const owned_inputs_t *owned, unsigned char *sum) { + memcpy(sum, owned->keys[0], SP_SECRET_LEN); + for (size_t i = 1; i < owned->count; i++) + if (!secp256k1_ec_seckey_tweak_add(secp_ctx(), sum, owned->keys[i])) + return false; + return true; +} + +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)); +} + +// H(rng || a_sum || 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 *sum, 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, sum, 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; +} + +// A share and proof the PSBT already holds must be ours: the same share, and +// a proof that verifies against A_sum = a_sum*G +static sp_psbt_result_t +check_declared_share(const struct wally_psbt *psbt, const unsigned char *scan, + const secp256k1_pubkey *scan_point, + const secp256k1_pubkey *share, + const unsigned char *share_bytes, const unsigned char *sum, + const secp256k1_pubkey *generator, bool *declared) { + const struct wally_map_item *declared_share = + find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, scan); + const struct wally_map_item *declared_proof = + find_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_DLEQ, scan); + secp256k1_pubkey public; + + *declared = declared_share || declared_proof; + if (!*declared) + return SP_PSBT_OK; + if (!declared_share || !declared_proof || + declared_share->value_len != SP_PUBKEY_LEN || + memcmp(declared_share->value, share_bytes, SP_PUBKEY_LEN) != 0 || + declared_proof->value_len != DLEQ_PROOF_LEN) + return SP_PSBT_ERR_FIELD; + if (!secp256k1_ec_pubkey_create(secp_ctx(), &public, sum)) + return SP_PSBT_ERR_CRYPTO; + return dleq_verify(&public, scan_point, share, declared_proof->value, + generator, NULL) + ? SP_PSBT_OK + : SP_PSBT_ERR_FIELD; +} + +// share = a_sum*B_scan, with its proof over A_sum = a_sum*G +static sp_psbt_result_t write_scan_share(struct wally_psbt *psbt, + const unsigned char *scan, + const unsigned char *sum, + const secp256k1_pubkey *generator) { + secp256k1_pubkey scan_point, share; + 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; + + if (!parse_point(scan, &scan_point)) + return SP_PSBT_ERR_FIELD; + share = scan_point; + if (!secp256k1_ec_pubkey_tweak_mul(secp_ctx(), &share, sum) || + !serialize_point(&share, share_bytes)) + return SP_PSBT_ERR_CRYPTO; + result = check_declared_share(psbt, scan, &scan_point, &share, share_bytes, + sum, generator, &declared); + if (result != SP_PSBT_OK || declared) + return result; + ok = hedged_aux(sum, scan, aux) && + dleq_prove(sum, &scan_point, aux, generator, NULL, proof) && + set_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_ECDH_SHARE, scan, + share_bytes, sizeof(share_bytes)) && + set_scan_field(&psbt->unknowns, PSBT_GLOBAL_SP_DLEQ, scan, proof, + sizeof(proof)); + secure_memzero(aux, sizeof(aux)); + return ok ? SP_PSBT_OK : SP_PSBT_ERR_CRYPTO; +} + +// One global share and DLEQ proof per distinct scan key (signer.rs +// write_shares) +static sp_psbt_result_t write_shares(struct wally_psbt *psbt, + const owned_inputs_t *owned, + const sp_recipient_t *recipients, + size_t count) { + unsigned char sum[SP_SECRET_LEN]; + secp256k1_pubkey generator; + sp_psbt_result_t result = + sum_owned_keys(owned, sum) && + secp256k1_ec_pubkey_create(secp_ctx(), &generator, SCALAR_ONE) + ? SP_PSBT_OK + : SP_PSBT_ERR_CRYPTO; + + for (size_t i = 0; result == SP_PSBT_OK && i < count; i++) { + if (i && !memcmp(recipients[i].scan, recipients[i - 1].scan, SP_PUBKEY_LEN)) + continue; + result = write_scan_share(psbt, recipients[i].scan, sum, &generator); + } + secure_memzero(sum, sizeof(sum)); + 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); + } +} + +// 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; +} + +typedef struct { + const unsigned char **seckey_ptrs; + secp256k1_silentpayments_recipient *recipients; + const secp256k1_silentpayments_recipient **recipient_ptrs; + secp256k1_xonly_pubkey *outputs; + secp256k1_xonly_pubkey **output_ptrs; +} sender_buffers_t; + +static void sender_buffers_free(sender_buffers_t *b) { + free(b->seckey_ptrs); + free(b->recipients); + free(b->recipient_ptrs); + free(b->outputs); + free(b->output_ptrs); +} + +static bool sender_buffers_alloc(sender_buffers_t *b, size_t seckey_count, + size_t recipient_count) { + memset(b, 0, sizeof(*b)); + b->seckey_ptrs = calloc(seckey_count, sizeof(*b->seckey_ptrs)); + b->recipients = calloc(recipient_count, sizeof(*b->recipients)); + b->recipient_ptrs = calloc(recipient_count, sizeof(*b->recipient_ptrs)); + b->outputs = calloc(recipient_count, sizeof(*b->outputs)); + b->output_ptrs = calloc(recipient_count, sizeof(*b->output_ptrs)); + return b->seckey_ptrs && b->recipients && b->recipient_ptrs && b->outputs && + b->output_ptrs; +} + +// libsecp256k1 keeps the given order within a scan key group, so recipients +// already sorted the bwk way give bwk's k for every output. The owned keys go +// in as plain secret keys: the taproot ones are already even-Y, and passing +// them as keypairs would negate an odd-Y P2WPKH or P2PKH key. +static bool fill_sender_buffers(sender_buffers_t *b, + const owned_inputs_t *owned, + const sp_recipient_t *recipients, + size_t count) { + for (size_t i = 0; i < owned->count; i++) + b->seckey_ptrs[i] = owned->keys[i]; + for (size_t i = 0; i < count; i++) { + if (!parse_point(recipients[i].scan, &b->recipients[i].scan_pubkey) || + !parse_point(recipients[i].spend, &b->recipients[i].spend_pubkey)) + return false; + b->recipients[i].index = i; + b->recipient_ptrs[i] = &b->recipients[i]; + b->output_ptrs[i] = &b->outputs[i]; + } + return true; +} + +static sp_psbt_result_t fill_output_scripts(struct wally_psbt *psbt, + const owned_inputs_t *owned, + const sp_recipient_t *recipients, + size_t count) { + unsigned char outpoint[OUTPOINT_LEN]; + sender_buffers_t b; + sp_psbt_result_t result = SP_PSBT_ERR_CRYPTO; + + smallest_outpoint(psbt, outpoint); + if (sender_buffers_alloc(&b, owned->count, count) && + fill_sender_buffers(&b, owned, recipients, count) && + secp256k1_silentpayments_sender_create_outputs( + secp_ctx(), b.output_ptrs, b.recipient_ptrs, count, outpoint, NULL, 0, + b.seckey_ptrs, owned->count)) { + result = SP_PSBT_OK; + for (size_t i = 0; result == SP_PSBT_OK && i < count; i++) + result = + set_output_script(psbt, recipients[i].output_index, &b.outputs[i]); + } + sender_buffers_free(&b); + 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 && + wally_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; +} + +static sp_psbt_result_t complete_with_keys(struct wally_psbt *psbt, + const struct sp_keys *keys) { + sp_recipient_t *recipients = NULL; + size_t count = 0; + owned_inputs_t owned = {0}; + signer_t signer = {.keys = keys}; + sp_psbt_result_t result = collect_recipients(psbt, &recipients, &count); + + if (result == SP_PSBT_OK && !key_get_fingerprint(signer.fingerprint)) + result = SP_PSBT_ERR_KEYS; + if (result == SP_PSBT_OK) + result = collect_owned_inputs(psbt, &signer, &owned); + if (result == SP_PSBT_OK) + result = write_shares(psbt, &owned, recipients, count); + if (result == SP_PSBT_OK) + result = fill_output_scripts(psbt, &owned, recipients, count); + // The scripts depend on the exact input and output sets, so freeze both + if (result == SP_PSBT_OK && + wally_psbt_set_tx_modifiable_flags(psbt, 0) != WALLY_OK) + result = SP_PSBT_ERR_PSBT; + owned_inputs_free(&owned); + free(recipients); + return result; +} + +sp_psbt_result_t sp_psbt_complete(struct wally_psbt **psbt, bool is_testnet) { + struct wally_psbt *completed = NULL; + struct sp_keys keys; + 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 SP_PSBT_OK; + 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 = wally_psbt_clone_alloc(*psbt, 0, &completed) == WALLY_OK + ? complete_with_keys(completed, &keys) + : SP_PSBT_ERR_PSBT; + sp_keys_wipe(&keys); + if (result == SP_PSBT_OK) + result = reparse_strict(&completed); + if (result != SP_PSBT_OK) { + wally_psbt_free(completed); + return result; + } + wally_psbt_free(*psbt); + *psbt = completed; + return SP_PSBT_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_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_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; +} + +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_ERR_FOREIGN: + return "Silent payment outputs need every input to be ours"; + 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..efc0c98a --- /dev/null +++ b/main/core/sp_psbt.h @@ -0,0 +1,65 @@ +#ifndef SP_PSBT_H +#define SP_PSBT_H + +#include "../utils/attributes.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_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_FOREIGN, // an eligible input is not ours + 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 silent payment keys: writes the +// global ECDH share and DLEQ proof of every scan key, derives every silent +// payment output script and freezes the transaction. Every eligible input +// must be ours, its key proven against the script it spends. A share or proof +// already present must match ours. On success *psbt is replaced by its +// strictly re-parsed copy; on failure it 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); + +// Copies the BIP375 global 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); + +const char *sp_psbt_result_message(sp_psbt_result_t result); + +#endif // SP_PSBT_H diff --git a/main/core/test/.gitignore b/main/core/test/.gitignore index 3066572c..836d5d7a 100644 --- a/main/core/test/.gitignore +++ b/main/core/test/.gitignore @@ -28,3 +28,4 @@ test_pbkdf2_core.o test_silentpayments test_dleq test_sp_keys +test_sp_psbt diff --git a/main/core/test/Makefile b/main/core/test/Makefile index 1f4c1142..30de3c72 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -170,7 +170,14 @@ SRCS_SP_KEYS = test_sp_keys.c TARGET_SP_KEYS = test_sp_keys SP_SRC = ../silent_payments.c ../silent_payments.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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) +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 + +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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) $(LIBWALLY): $(WALLY_SRC) $(wildcard $(WALLY_DIR)/upstream/src/*.c) $(WALLY_DIR)/kern_bech32.h $(wildcard $(WALLY_DIR)/silentpayments/src/modules/silentpayments/*.h) $(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 $< @@ -202,11 +209,11 @@ $(TARGET_REG_PARSE): $(SRCS_REG_PARSE) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC $(PSBT_KEY_OBJ): $(KEY_SRC) $(CC) $(CFLAGS) $(TEST_INCS) -Dkey_get_fingerprint=key_get_fingerprint_raw -c -o $@ ../key.c -$(TARGET_PSBT_CLASSIFY): $(SRCS_PSBT_CLASSIFY) $(PSBT_SRC) $(SS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(LIBWALLY) $(PSBT_KEY_OBJ) - $(CC) $(CFLAGS) $(TEST_INCS) -DPSBT_TESTING -o $@ $(SRCS_PSBT_CLASSIFY) $(PSBT_KEY_OBJ) ../ss_whitelist.c ../registry.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../psbt.c ../bip32_path.c ../script_templates.c ../descriptor_checksum.c $(LIBWALLY) +$(TARGET_PSBT_CLASSIFY): $(SRCS_PSBT_CLASSIFY) $(PSBT_SRC) $(SS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SP_PSBT_SRC) $(LIBWALLY) $(PSBT_KEY_OBJ) + $(CC) $(CFLAGS) $(KEF_INCS) -DPSBT_TESTING -o $@ $(SRCS_PSBT_CLASSIFY) $(PSBT_KEY_OBJ) ../ss_whitelist.c ../registry.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../psbt.c ../bip32_path.c ../script_templates.c ../descriptor_checksum.c $(SP_PSBT_LINK) $(LIBWALLY) -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) +$(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 $(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) @@ -288,7 +295,10 @@ $(TARGET_DLEQ): $(SRCS_DLEQ) $(DLEQ_SRC) $(LIBWALLY) $(TARGET_SP_KEYS): $(SRCS_SP_KEYS) $(SP_SRC) $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(SRCS_SP_KEYS) ../silent_payments.c ../key.c ../bip32_path.c ../descriptor_checksum.c $(LIBWALLY) -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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) +$(TARGET_SP_PSBT): $(SRCS_SP_PSBT) sp_fixture.h $(SP_PSBT_SRC) ../psbt_parse.c $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(LIBWALLY) + $(CC) $(CFLAGS) $(KEF_INCS) -o $@ $(SRCS_SP_PSBT) ../psbt_parse.c ../key.c ../bip32_path.c ../descriptor_checksum.c $(SP_PSBT_LINK) $(LIBWALLY) -lmbedcrypto + +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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) ./$(TARGET_DERIV) ./$(TARGET_SS_PARSE) ./$(TARGET_SS_WHITELISTED) @@ -315,8 +325,9 @@ run: $(TARGET_DERIV) $(TARGET_SS_PARSE) $(TARGET_SS_WHITELISTED) $(TARGET_SS_REG ./$(TARGET_SILENTPAYMENTS) ./$(TARGET_DLEQ) ./$(TARGET_SP_KEYS) + ./$(TARGET_SP_PSBT) 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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) + 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_SILENTPAYMENTS) $(TARGET_DLEQ) $(TARGET_SP_KEYS) $(TARGET_SP_PSBT) $(LIBWALLY) combined.o kern_wally.o secret_alloc.o $(PSBT_KEY_OBJ) $(STORAGE_OBJ) $(PBKDF2_OBJ) .PHONY: all run clean diff --git a/main/core/test/sp_fixture.h b/main/core/test/sp_fixture.h new file mode 100644 index 00000000..28f71409 --- /dev/null +++ b/main/core/test/sp_fixture.h @@ -0,0 +1,148 @@ +#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"; + +#endif // SP_FIXTURE_H diff --git a/main/core/test/test_sp_psbt.c b/main/core/test/test_sp_psbt.c new file mode 100644 index 00000000..b2c53a25 --- /dev/null +++ b/main/core/test/test_sp_psbt.c @@ -0,0 +1,427 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#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"; + +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) { + unsigned char bytes[2048]; + size_t written = 0; + struct wally_psbt *psbt = NULL; + if (wally_hex_to_bytes(hex, bytes, sizeof(bytes), &written) != WALLY_OK || + !psbt_parse_payload(bytes, written, &psbt)) + return NULL; + 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); +} + +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); +} + +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 eligible input is refused", parse_hex(FOREIGN_PSBT), + SP_PSBT_ERR_FOREIGN); + + 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_refusal("an input with a wrong tweak is not ours", psbt, + SP_PSBT_ERR_FOREIGN); + + 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 foreign", + psbt, SP_PSBT_ERR_FOREIGN); + + psbt = parse_hex(ALL_TYPES_PSBT); + expect_refusal( + "a P2TR key not reaching the output key is foreign", + checked(psbt, psbt && flip_input_field(psbt, 2, PSBT_IN_TAP_MERKLE_ROOT)), + SP_PSBT_ERR_FOREIGN); + + 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_refusal( + "an unproven NUMS input stays eligible, and is foreign", + checked(psbt, psbt && flip_input_field(psbt, 1, PSBT_IN_TAP_MERKLE_ROOT)), + SP_PSBT_ERR_FOREIGN); +} + +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); +} + +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_refusals(); + test_bip352_inputs(); + test_input_refusals(); + test_field_checks(); + key_unload(); + + printf("\n%d passed, %d failed\n", tests_passed, tests_failed); + return tests_failed ? 1 : 0; +} diff --git a/main/pages/scan/scan.c b/main/pages/scan/scan.c index f5d0d1ff..677dc58e 100644 --- a/main/pages/scan/scan.c +++ b/main/pages/scan/scan.c @@ -220,7 +220,7 @@ 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; } diff --git a/main/pages/scan/scan_internal.h b/main/pages/scan/scan_internal.h index b0b50bbe..917c6c22 100644 --- a/main/pages/scan/scan_internal.h +++ b/main/pages/scan/scan_internal.h @@ -77,6 +77,9 @@ 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); diff --git a/main/pages/scan/scan_psbt_review.c b/main/pages/scan/scan_psbt_review.c index 0e52f9ba..0de10f7a 100644 --- a/main/pages/scan/scan_psbt_review.c +++ b/main/pages/scan/scan_psbt_review.c @@ -5,6 +5,7 @@ #include "../../core/psbt.h" #include "../../core/registry.h" +#include "../../core/sp_psbt.h" #include "../../core/wallet.h" #include "../../qr/parser.h" #include "../../qr/scanner.h" @@ -255,16 +256,31 @@ static void mismatch_dialog_cb(void *user_data) { } } +bool scan_psbt_complete_silent_payments(void) { + if (!scan_ctx.psbt || !sp_psbt_has_fields(scan_ctx.psbt)) + return false; + sp_psbt_result_t result = sp_psbt_complete( + &scan_ctx.psbt, wallet_get_network() == WALLET_NETWORK_TESTNET); + if (result == SP_PSBT_OK) + return false; + dialog_show_error_timeout(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) { diff --git a/simulator/CMakeLists.txt b/simulator/CMakeLists.txt index 3f87ec93..ef7fe7ae 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -206,6 +206,7 @@ set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/script_templates.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) From cd0b3cfa6579e8ea0b0e30ddcec7f756858ea73d Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 12:38:48 +0000 Subject: [PATCH 12/13] feat(psbt): classify, review and sign silent payment inputs and outputs --- main/core/psbt.c | 24 +++++ main/core/psbt.h | 6 ++ main/core/sp_psbt.c | 130 +++++++++++++++++++++++++++ main/core/sp_psbt.h | 22 +++++ main/core/test/Makefile | 2 +- main/core/test/sp_fixture.h | 9 ++ main/core/test/test_psbt_classify.c | 84 ++++++++++++++++++ main/core/test/test_sp_psbt.c | 131 ++++++++++++++++++++++++++++ main/pages/scan/scan_psbt_review.c | 96 ++++++++++++++++---- 9 files changed, 485 insertions(+), 19 deletions(-) diff --git a/main/core/psbt.c b/main/core/psbt.c index 20514ec6..3b04eaa0 100644 --- a/main/core/psbt.c +++ b/main/core/psbt.c @@ -558,6 +558,12 @@ 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), @@ -638,6 +644,15 @@ 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_psbt_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; + } + struct wally_tx *global_tx = psbt_tx_alloc(psbt); if (!global_tx) return result; @@ -1084,6 +1099,15 @@ 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[MAX_SIGNING_PATHS_PER_INPUT]; size_t num_paths = 0; diff --git a/main/core/psbt.h b/main/core/psbt.h index 86afe20a..4ae45a3b 100644 --- a/main/core/psbt.h +++ b/main/core/psbt.h @@ -22,6 +22,9 @@ KERN_WARN_UNUSED_RESULT bool psbt_parse_payload(const uint8_t *data, size_t len, typedef enum { CLAIM_WHITELIST, CLAIM_REGISTRY, + /* our silent payment input, or our silent payment change or self-transfer + * output */ + CLAIM_SILENT_PAYMENT, } claim_kind_t; typedef struct { @@ -40,6 +43,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; diff --git a/main/core/sp_psbt.c b/main/core/sp_psbt.c index 43f0930c..6bb57330 100644 --- a/main/core/sp_psbt.c +++ b/main/core/sp_psbt.c @@ -43,6 +43,9 @@ #define OP_1 0x51 #define OP_16 0x60 #define PUSH_32 0x20 +// BIP352 reserves label m = 0 for change +#define SP_CHANGE_LABEL 0 +#define SCHNORR_SIG_LEN 64 // Smallest and largest witness program, BIP141 #define WITNESS_PROGRAM_MIN 2 #define WITNESS_PROGRAM_MAX 40 @@ -967,6 +970,133 @@ sp_psbt_result_t sp_psbt_complete(struct wally_psbt **psbt, bool is_testnet) { return 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; +} + +// Our spend key labeled with m (BIP352 labels) +static bool labeled_spend_key(const struct sp_keys *keys, uint32_t m, + unsigned char *out) { + secp256k1_silentpayments_label label; + secp256k1_pubkey spend, labeled; + unsigned char label_tweak[SP_SECRET_LEN]; + bool ok = secp256k1_silentpayments_recipient_label_create( + secp_ctx(), &label, label_tweak, keys->scan_secret, m) && + parse_point(keys->spend_pubkey, &spend) && + secp256k1_silentpayments_recipient_create_labeled_spend_pubkey( + secp_ctx(), &labeled, &spend, &label) && + serialize_point(&labeled, out); + secure_memzero(label_tweak, sizeof(label_tweak)); + return ok; +} + +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 labeled_spend_key(keys, 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, 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_keys_derive(is_testnet, &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++) { diff --git a/main/core/sp_psbt.h b/main/core/sp_psbt.h index efc0c98a..6aaa16ae 100644 --- a/main/core/sp_psbt.h +++ b/main/core/sp_psbt.h @@ -54,6 +54,28 @@ sp_output_keys(const struct wally_psbt_output *output, unsigned char *scan_out, 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, // our scan key, our spend key labeled m = 0 + SP_OUTPUT_SELF, // our scan key, our spend key unlabeled or labeled m > 0 +} sp_output_ownership_t; + +// Whose silent payment output `i` is. 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, 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 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. diff --git a/main/core/test/Makefile b/main/core/test/Makefile index 30de3c72..810b2fd3 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -209,7 +209,7 @@ $(TARGET_REG_PARSE): $(SRCS_REG_PARSE) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC $(PSBT_KEY_OBJ): $(KEY_SRC) $(CC) $(CFLAGS) $(TEST_INCS) -Dkey_get_fingerprint=key_get_fingerprint_raw -c -o $@ ../key.c -$(TARGET_PSBT_CLASSIFY): $(SRCS_PSBT_CLASSIFY) $(PSBT_SRC) $(SS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SP_PSBT_SRC) $(LIBWALLY) $(PSBT_KEY_OBJ) +$(TARGET_PSBT_CLASSIFY): $(SRCS_PSBT_CLASSIFY) sp_fixture.h $(PSBT_SRC) $(SS_SRC) $(KEY_SRC) $(REGISTRY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SP_PSBT_SRC) $(LIBWALLY) $(PSBT_KEY_OBJ) $(CC) $(CFLAGS) $(KEF_INCS) -DPSBT_TESTING -o $@ $(SRCS_PSBT_CLASSIFY) $(PSBT_KEY_OBJ) ../ss_whitelist.c ../registry.c $(REGISTRY_PERSIST_STUB_SRC) $(VALIDATOR_KEYED_STUB_SRC) ../psbt.c ../bip32_path.c ../script_templates.c ../descriptor_checksum.c $(SP_PSBT_LINK) $(LIBWALLY) -lmbedcrypto $(TARGET_PSBT_PARSE): $(SRCS_PSBT_PARSE) ../psbt_parse.c ../psbt.h $(KEY_SRC) $(DESCRIPTOR_CHECKSUM_SRC) $(SP_PSBT_SRC) $(LIBWALLY) diff --git a/main/core/test/sp_fixture.h b/main/core/test/sp_fixture.h index 28f71409..7a1716e0 100644 --- a/main/core/test/sp_fixture.h +++ b/main/core/test/sp_fixture.h @@ -145,4 +145,13 @@ static const char V0_SP_PSBT[] = "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"; + #endif // SP_FIXTURE_H diff --git a/main/core/test/test_psbt_classify.c b/main/core/test/test_psbt_classify.c index 3c3d1601..87b5ee64 100644 --- a/main/core/test/test_psbt_classify.c +++ b/main/core/test/test_psbt_classify.c @@ -17,8 +17,10 @@ #include "core/psbt.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, @@ -1898,6 +1900,83 @@ static void test_trim_leaves_out_previous_transactions(void) { * place. It must stay v2, keep the flags the signer set and every signature, * and still describe the same transaction, or the coordinator cannot merge it. */ +/* The bwk-built silent payment PSBT, with its output scripts derived */ +static struct wally_psbt *make_silent_payment_psbt(void) { + unsigned char bytes[1024]; + size_t written = 0; + struct wally_psbt *psbt = NULL; + if (wally_hex_to_bytes(UNSIGNED_PSBT, 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; + 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); +} + +static void test_sign_silent_payment_input(void) { + struct wally_psbt *psbt = make_silent_payment_psbt(); + psbt_sign_policy_t policy = {0}; + size_t sig_len = 0; + + TEST("psbt_sign: signs our silent payment input with SIGHASH_DEFAULT"); + if (psbt && psbt_sign(psbt, false, policy, NULL) == 1 && + wally_psbt_get_input_taproot_signature_len(psbt, 0, &sig_len) == + WALLY_OK && + sig_len == 64) + PASS(); + else + FAIL("silent payment input not signed"); + + 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_trim_psbt_v2_in_place(void) { TEST("psbt_trim: a v2 PSBT is trimmed in place"); @@ -3089,6 +3168,11 @@ int main(void) { test_trim_leaves_out_previous_transactions(); test_trim_psbt_v2_in_place(); + printf("\n=== silent payment tests ===\n\n"); + + test_silent_payment_classify(); + test_sign_silent_payment_input(); + key_unload(); printf("\n=== Results: %d passed, %d failed ===\n", tests_passed, diff --git a/main/core/test/test_sp_psbt.c b/main/core/test/test_sp_psbt.c index b2c53a25..e579ab19 100644 --- a/main/core/test/test_sp_psbt.c +++ b/main/core/test/test_sp_psbt.c @@ -5,10 +5,13 @@ #include #include +#include +#include #include #include #include #include +#include #include "core/dleq.h" #include "core/key.h" @@ -409,6 +412,131 @@ static void test_field_checks(void) { SP_PSBT_ERR_FIELD); } +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, false) == SP_OUTPUT_CHANGE && + sp_psbt_output_ownership(psbt, 0, false) == SP_OUTPUT_FOREIGN && + sp_psbt_output_ownership(psbt, 1, 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 +static sp_output_ownership_t ownership_of(const char *scan_hex, + const char *spend_hex, + const uint32_t *label) { + 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) + ownership = sp_psbt_output_ownership(psbt, 1, 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, + sp_output_ownership_t expected) { + TEST(name); + if (ownership_of(scan_hex, spend_hex, label) == 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, SP_OUTPUT_CHANGE); + expect_ownership("label 3 on the m=3 key is a self-transfer", OUR_SCAN, + OUR_SPEND_LABEL_3, &three, SP_OUTPUT_SELF); + expect_ownership("no label on the unlabeled key is a self-transfer", OUR_SCAN, + OUR_SPEND, NULL, SP_OUTPUT_SELF); + expect_ownership("no label on the m=0 key is change", OUR_SCAN, + OUR_SPEND_LABEL_0, NULL, SP_OUTPUT_CHANGE); + expect_ownership("label 3 on the m=0 key is not ours", OUR_SCAN, + OUR_SPEND_LABEL_0, &three, SP_OUTPUT_FOREIGN); + expect_ownership("a foreign scan key with our m=0 key is not ours", + RECIPIENT_SCAN, OUR_SPEND_LABEL_0, &change, + 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"); @@ -420,6 +548,9 @@ int main(void) { test_bip352_inputs(); test_input_refusals(); test_field_checks(); + test_ownership(); + test_labels(); + test_sign(); key_unload(); printf("\n%d passed, %d failed\n", tests_passed, tests_failed); diff --git a/main/pages/scan/scan_psbt_review.c b/main/pages/scan/scan_psbt_review.c index 0de10f7a..7dfba439 100644 --- a/main/pages/scan/scan_psbt_review.c +++ b/main/pages/scan/scan_psbt_review.c @@ -5,6 +5,7 @@ #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" @@ -55,6 +56,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 is_dust; /* below the relay dust threshold for its script type */ char path[80]; /* populated for OWNED_UNSAFE / EXPECTED_OWNED */ @@ -98,14 +100,41 @@ static void format_input_policy(const input_ownership_t *own, char *out, out[0] = '\0'; if (own->ownership != PSBT_OWNERSHIP_OWNED_SAFE) return; - if (own->claim.kind == CLAIM_WHITELIST) { + switch (own->claim.kind) { + case CLAIM_WHITELIST: snprintf(out, out_size, "%s @ account %u", ss_script_label(own->claim.whitelist.script), (unsigned)own->claim.whitelist.account); - } else if (own->claim.kind == CLAIM_REGISTRY && own->claim.registry.entry) { - const registry_entry_t *entry = own->claim.registry.entry; - snprintf(out, out_size, "%s", entry->label[0] ? entry->label : entry->id); + break; + case CLAIM_REGISTRY: + if (own->claim.registry.entry) { + const registry_entry_t *entry = own->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; + } +} + +// Change or self-transfer, from the claim that proved the output ours +static output_type_t owned_output_type(const claim_t *source, + uint32_t *address_index_out) { + switch (source->kind) { + case CLAIM_WHITELIST: + *address_index_out = source->whitelist.index; + return source->whitelist.chain == 1 ? OUTPUT_TYPE_CHANGE + : OUTPUT_TYPE_SELF_TRANSFER; + case CLAIM_REGISTRY: + *address_index_out = source->registry.child_num; + return source->registry.multi_index == 1 ? OUTPUT_TYPE_CHANGE + : OUTPUT_TYPE_SELF_TRANSFER; + case CLAIM_SILENT_PAYMENT: + return source->silent_payment.is_change ? OUTPUT_TYPE_CHANGE + : OUTPUT_TYPE_SELF_TRANSFER; } + return OUTPUT_TYPE_SPEND; } // Classify output as self-transfer, change, owned-unsafe, expected-owned, @@ -114,23 +143,12 @@ static void format_input_policy(const input_ownership_t *own, char *out, static output_type_t classify_output(size_t output_index, uint32_t *address_index_out, char *path_out, size_t path_out_size) { - bool is_change = false; - uint32_t address_index = 0; - output_ownership_t ownership = psbt_classify_output(scan_ctx.psbt, output_index, scan_ctx.is_testnet); switch (ownership.ownership) { case PSBT_OWNERSHIP_OWNED_SAFE: - if (ownership.source.kind == CLAIM_WHITELIST) { - is_change = (ownership.source.whitelist.chain == 1); - address_index = ownership.source.whitelist.index; - } else { - is_change = (ownership.source.registry.multi_index == 1); - address_index = ownership.source.registry.child_num; - } - *address_index_out = address_index; - return is_change ? OUTPUT_TYPE_CHANGE : OUTPUT_TYPE_SELF_TRANSFER; + return owned_output_type(&ownership.source, address_index_out); case PSBT_OWNERSHIP_OWNED_UNSAFE: case PSBT_OWNERSHIP_EXPECTED_OWNED: @@ -344,12 +362,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) { memset(d, 0, sizeof(*d)); if (wally_psbt_get_num_inputs(scan_ctx.psbt, &d->num_inputs) != WALLY_OK || @@ -410,6 +439,10 @@ static bool review_data_collect(review_data_t *d) { d->total_output += out->value; out->address = psbt_scriptpubkey_to_address(txo->script, txo->script_len, scan_ctx.is_testnet); + if (!output_sp_address(i, &out->sp_address)) { + wally_tx_free(tx); + goto fail; + } out->type = classify_output(i, &out->address_index, out->path, sizeof(out->path)); out->is_dust = @@ -724,8 +757,14 @@ 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), "Receive #%u: ", out->address_index); + if (out->sp_address) + snprintf(text, sizeof(text), "Output %zu: ", out->index); + else + snprintf(text, sizeof(text), "Receive #%u: ", out->address_index); indented_amount_row(parent, text, out->value); + if (out->sp_address) + scan_create_address_label(parent, out->sp_address, accent_color(), + ADDRESS_INDENT_PX); if (out->address) scan_create_address_label(parent, out->address, accent_color(), ADDRESS_INDENT_PX); @@ -753,6 +792,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, @@ -775,6 +831,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); if (out->address) scan_create_address_label(parent, out->address, color, ADDRESS_INDENT_PX); } @@ -916,6 +975,7 @@ static bool create_psbt_info_display(void) { "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); From 07905b54580da5f842cc7815bdfb6e4bd0f09465 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Sun, 11 Oct 2026 12:40:26 +0000 Subject: [PATCH 13/13] feat(bwk): sign silent payment PSBTs requested over the bwk QR protocol --- main/core/silent_payments.c | 24 ++++++++++++++++++++++++ main/core/silent_payments.h | 7 +++++++ main/core/test/test_sp_keys.c | 33 +++++++++++++++++++++++++++++++++ main/pages/bip_flow/bip_flow.c | 16 +++++++++++++++- 4 files changed, 79 insertions(+), 1 deletion(-) diff --git a/main/core/silent_payments.c b/main/core/silent_payments.c index 874ab050..43f49cfa 100644 --- a/main/core/silent_payments.c +++ b/main/core/silent_payments.c @@ -15,6 +15,7 @@ #define SP_SPEND_BRANCH 0 #define SP_PATH_DEPTH 5 #define SP_VERSION 0 +#define SP_DESCRIPTOR_PREFIX "sp(" #define FINGERPRINT_HEX_LEN 9 #define CHECKSUM_LEN 9 @@ -114,6 +115,29 @@ bool sp_descriptor_alloc(bool is_testnet, char **out) { 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) { diff --git a/main/core/silent_payments.h b/main/core/silent_payments.h index 9918762e..732f6a2f 100644 --- a/main/core/silent_payments.h +++ b/main/core/silent_payments.h @@ -28,6 +28,13 @@ void sp_keys_wipe(struct sp_keys *keys); // 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, diff --git a/main/core/test/test_sp_keys.c b/main/core/test/test_sp_keys.c index 0ea3f6bf..f20e47ab 100644 --- a/main/core/test/test_sp_keys.c +++ b/main/core/test/test_sp_keys.c @@ -100,6 +100,38 @@ static void test_address(void) { free(address); } +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"); +} + int main(void) { TEST("sp_descriptor_alloc fails without a loaded key"); char *descriptor = NULL; @@ -118,6 +150,7 @@ int main(void) { test_descriptor("sp_descriptor_alloc matches bwk on testnet", true, TESTNET_DESCRIPTOR); test_address(); + test_descriptor_ownership(); key_unload(); printf("\n%d passed, %d failed\n", tests_passed, tests_failed); diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c index ac9027cb..52200c29 100644 --- a/main/pages/bip_flow/bip_flow.c +++ b/main/pages/bip_flow/bip_flow.c @@ -8,6 +8,7 @@ #include "../../core/registry.h" #include "../../core/settings.h" #include "../../core/silent_payments.h" +#include "../../core/sp_psbt.h" #include "../../core/wallet.h" #include "../../qr/encoder.h" #include "../../qr/viewer.h" @@ -959,7 +960,9 @@ static void signed_psbt_cb(struct wally_psbt *psbt, void *user_data) { (void)user_data; bwk_qr_response response; fill_response_header(&response); - if (ctx.request->body.sign.want_kind == BWK_QR_SIGN_RESPONSE_SIGNATURES) { + // Silent payment scripts, shares and proofs only travel inside the PSBT + if (ctx.request->body.sign.want_kind == BWK_QR_SIGN_RESPONSE_SIGNATURES && + !sp_psbt_has_outputs(psbt)) { bwk_qr_signature *signatures = NULL; size_t signatures_len = 0; if (!collect_signatures(psbt, &signatures, &signatures_len)) { @@ -1017,6 +1020,17 @@ static void handle_sign(void) { "Unsupported descriptor"); return; } + // An sp() descriptor carries our scan secret and is never registered + if (sp_descriptor_is_sp(descriptor_str)) { + bool ours = sp_descriptor_is_ours(descriptor_str, wallet_is_testnet()); + SECURE_FREE_STRING(descriptor_str); + if (!ours) { + show_error_response(BWK_QR_RESPONSE_ERROR_UNKNOWN_DESCRIPTOR_ALIAS, + "Not this device's silent payment account"); + return; + } + continue; + } if (descriptor->alias && !registry_find_by_id(descriptor->alias) && !registry_add_from_string(descriptor->alias, descriptor_str, STORAGE_FLASH, false)) {