From e4dd4d1aae3ae42eef83438c7dc6f286faecc7d1 Mon Sep 17 00:00:00 2001 From: odudex Date: Sat, 17 Oct 2026 17:12:55 -0300 Subject: [PATCH 1/9] descriptor: document that the network is not inferred from keys The docs for wally_descriptor_parse and wally_descriptor_get_network said a descriptor parsed with WALLY_NETWORK_NONE infers its network from its keys. It doesn't: e.g. wpkh(xpub.../0/*) and wpkh(tpub.../0/*) both keep WALLY_NETWORK_NONE, so wally_descriptor_set_network must be called before generating addresses. --- include/wally_descriptor.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/include/wally_descriptor.h b/include/wally_descriptor.h index 552041d68..70ec92bb6 100644 --- a/include/wally_descriptor.h +++ b/include/wally_descriptor.h @@ -53,8 +53,9 @@ struct wally_descriptor; * :param descriptor: Output descriptor or miniscript expression to parse. * :param vars_in: Map of variable names to values, or NULL. * :param network: Network the descriptor belongs to. Pass `WALLY_NETWORK_NONE` - *| for miniscript-only expressions or to infer the network. Must - *| be one of the :ref:`address-networks`. Taproot expressions for + *| for miniscript-only expressions, or to set the network later with + *| `wally_descriptor_set_network`. The network is not inferred from the + *| keys in the expression. Must be one of the :ref:`address-networks`. Taproot expressions for *| Elements networks must use ``eltr()`` or `WALLY_MINISCRIPT_AS_ELEMENTS`. *| Elements expressions cannot be used with Bitcoin networks. * :param flags: :ref:`miniscript-flags`. The maximum depth of the descriptor @@ -117,12 +118,11 @@ WALLY_CORE_API int wally_descriptor_get_checksum( * :param value_out: Destination for the resulting network, returned as one *| of the :ref:`address-networks`. * - * A descriptor parsed with `WALLY_NETWORK_NONE` will infer its network from - * the contained key expressions. If the descriptor does not contain network - * information (e.g. its keys are raw keys), then this function will - * return `WALLY_NETWORK_NONE`, and `wally_descriptor_set_network` must be - * called to set a network for the descriptor before addresses can be - * generated from it. + * This is the network the descriptor was parsed with, or was later given with + * `wally_descriptor_set_network`. It is not inferred from the descriptor's + * keys: a descriptor parsed with `WALLY_NETWORK_NONE` returns + * `WALLY_NETWORK_NONE`, and `wally_descriptor_set_network` must be called + * before addresses can be generated from it. */ WALLY_CORE_API int wally_descriptor_get_network( const struct wally_descriptor *descriptor, From fe0a714aa761baec9fd156ecb3ee4c78acd88193 Mon Sep 17 00:00:00 2001 From: odudex Date: Wed, 7 Oct 2026 08:44:22 -0300 Subject: [PATCH 2/9] script: add a script iterator and pattern matcher Add an internal iterator over the opcodes of a script, which does not allocate memory or copy any script data, and a matcher which compares the opcodes from the iterator's position against a pattern of opcodes, pushes of a given size and numbers in a given range. Based on a draft by Jon Griffiths. Co-authored-by: Jon Griffiths --- src/Makefile.am | 9 ++ src/amalgamation/combined.c | 1 + src/ctest/_CMakeLists.txt | 5 + src/ctest/test_script_iter.c | 219 +++++++++++++++++++++++++++++++++++ src/script_iter.c | 144 +++++++++++++++++++++++ src/script_iter.h | 66 +++++++++++ 6 files changed, 444 insertions(+) create mode 100644 src/ctest/test_script_iter.c create mode 100644 src/script_iter.c create mode 100644 src/script_iter.h diff --git a/src/Makefile.am b/src/Makefile.am index 349401519..e9b9f6f1e 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -164,6 +164,7 @@ libwallycore_la_SOURCES = \ psbt.c \ pullpush.c \ script.c \ + script_iter.c \ scrypt.c \ sign.c \ symmetric.c \ @@ -278,6 +279,14 @@ test_script_LDADD = $(lib_LTLIBRARIES) @CTEST_EXTRA_STATIC@ if PYTHON_MANYLINUX test_script_LDADD += $(PYTHON_LIBS) endif +TESTS += test_script_iter +noinst_PROGRAMS += test_script_iter +test_script_iter_SOURCES = ctest/test_script_iter.c script_iter.c +test_script_iter_CFLAGS = $(TESTS_CFLAGS) +test_script_iter_LDADD = $(lib_LTLIBRARIES) @CTEST_EXTRA_STATIC@ +if PYTHON_MANYLINUX +test_script_iter_LDADD += $(PYTHON_LIBS) +endif TESTS += test_tx noinst_PROGRAMS += test_tx test_tx_SOURCES = ctest/test_tx.c diff --git a/src/amalgamation/combined.c b/src/amalgamation/combined.c index 7952e1652..11eeef242 100644 --- a/src/amalgamation/combined.c +++ b/src/amalgamation/combined.c @@ -73,6 +73,7 @@ #include "src/pullpush.c" #include "src/psbt.c" #include "src/script.c" +#include "src/script_iter.c" #include "src/scrypt.c" #include "src/sign.c" #include "src/symmetric.c" diff --git a/src/ctest/_CMakeLists.txt b/src/ctest/_CMakeLists.txt index 1b9cc5e71..c98ed6276 100644 --- a/src/ctest/_CMakeLists.txt +++ b/src/ctest/_CMakeLists.txt @@ -43,6 +43,11 @@ add_test(test_psbt_limits test_psbt_limits) #target_link_libraries(test_script PRIVATE wallycore) #add_test(test_script test_script) +add_executable(test_script_iter test_script_iter.c ../script_iter.c) +target_include_directories(test_script_iter PRIVATE ${CMAKE_BINARY_DIR} $) +target_link_libraries(test_script_iter PRIVATE wallycore) +add_test(test_script_iter test_script_iter) + add_executable(test_tx test_tx.c) target_include_directories(test_tx PRIVATE ${CMAKE_BINARY_DIR}) target_link_libraries(test_tx PRIVATE wallycore) diff --git a/src/ctest/test_script_iter.c b/src/ctest/test_script_iter.c new file mode 100644 index 000000000..3402563a2 --- /dev/null +++ b/src/ctest/test_script_iter.c @@ -0,0 +1,219 @@ +#include "config.h" + +#include +#include +#include +#include +#include "../script_iter.h" + +#define NUM_ELEMS(a) (sizeof(a) / sizeof(a[0])) + +static bool check(bool ok, const char *what) +{ + if (!ok) + printf("FAIL: %s\n", what); + return ok; +} + +/* Iterate a script, returning the number of opcodes or -1 if malformed */ +static int count_opcodes(const unsigned char *script, size_t script_len) +{ + script_iter si; + int n = 0; + + si_init(&si, script, script_len); + while (si_next(&si)) + ++n; + return si_is_error(&si) ? -1 : n; +} + +static bool test_iterate(void) +{ + static const unsigned char script[] = { + OP_DUP, OP_HASH160, 0x02, 0xaa, 0xbb, OP_EQUALVERIFY, + OP_PUSHDATA1, 0x01, 0xcc, OP_PUSHDATA2, 0x01, 0x00, 0xdd, + OP_PUSHDATA4, 0x01, 0x00, 0x00, 0x00, 0xee, OP_0, OP_16 + }; + static const struct { + unsigned char opcode; + size_t data_len; + unsigned char data; + } expected[] = { + { OP_DUP, 0, 0 }, { OP_HASH160, 0, 0 }, { 0x02, 2, 0xaa }, + { OP_EQUALVERIFY, 0, 0 }, { OP_PUSHDATA1, 1, 0xcc }, + { OP_PUSHDATA2, 1, 0xdd }, { OP_PUSHDATA4, 1, 0xee }, + { OP_0, 0, 0 }, { OP_16, 0, 0 } + }; + /* Truncated push lengths and push data */ + static const unsigned char bad[][3] = { + { 0x02, 0xaa, 0 }, { OP_PUSHDATA1, 0, 0 }, { OP_PUSHDATA2, 0x01, 0 }, + { OP_PUSHDATA1, 0x02, 0xaa } + }; + static const size_t bad_len[] = { 2, 1, 2, 3 }; + script_iter si; + size_t i; + bool ok = true; + + si_init(&si, script, sizeof(script)); + for (i = 0; i < NUM_ELEMS(expected); ++i) { + ok &= check(si_next(&si), "iterate: next"); + ok &= check(si.opcode == expected[i].opcode, "iterate: opcode"); + ok &= check(si.data_len == expected[i].data_len, "iterate: data_len"); + if (expected[i].data_len) + ok &= check(si.data[0] == expected[i].data, "iterate: data"); + } + ok &= check(!si_next(&si) && !si_is_error(&si), "iterate: end"); + + ok &= check(count_opcodes(NULL, 0) == 0, "iterate: empty"); + for (i = 0; i < NUM_ELEMS(bad); ++i) + ok &= check(count_opcodes(bad[i], bad_len[i]) == -1, "iterate: truncated"); + si_init(&si, NULL, 1); + ok &= check(!si_next(&si) && si_is_error(&si), "iterate: NULL script"); + return ok; +} + +static bool is_minimal(const unsigned char *script, size_t script_len) +{ + script_iter si; + si_init(&si, script, script_len); + return si_next(&si) && si_is_minimal_push(&si); +} + +static bool test_minimal_push(void) +{ + unsigned char buf[300]; + bool ok = true; + + memset(buf, 0x11, sizeof(buf)); + buf[0] = OP_0; + ok &= check(is_minimal(buf, 1), "minimal: OP_0"); + buf[0] = OP_PUSHDATA1; buf[1] = 0; + ok &= check(!is_minimal(buf, 2), "minimal: empty PUSHDATA1"); + buf[0] = 0x01; buf[1] = 0x05; + ok &= check(!is_minimal(buf, 2), "minimal: push of 5"); + buf[1] = 0x81; + ok &= check(!is_minimal(buf, 2), "minimal: push of -1"); + buf[1] = 0x11; + ok &= check(is_minimal(buf, 2), "minimal: push of 17"); + buf[0] = 0x20; + ok &= check(is_minimal(buf, 33), "minimal: 32 byte push"); + buf[0] = OP_PUSHDATA1; buf[1] = 0x20; + ok &= check(!is_minimal(buf, 34), "minimal: 32 byte PUSHDATA1"); + buf[1] = 0x4c; + ok &= check(is_minimal(buf, 2 + 0x4c), "minimal: 76 byte PUSHDATA1"); + buf[0] = OP_PUSHDATA2; buf[1] = 0x4c; buf[2] = 0; + ok &= check(!is_minimal(buf, 3 + 0x4c), "minimal: 76 byte PUSHDATA2"); + buf[1] = 0x00; buf[2] = 0x01; + ok &= check(is_minimal(buf, 3 + 0x100), "minimal: 256 byte PUSHDATA2"); + buf[0] = OP_DUP; + ok &= check(!is_minimal(buf, 1), "minimal: not a push"); + return ok; +} + +static bool get_number(const unsigned char *script, size_t script_len, int64_t *v) +{ + script_iter si; + si_init(&si, script, script_len); + return si_next(&si) && si_get_number(&si, v); +} + +static bool test_number(void) +{ + static const struct { + unsigned char script[6]; + size_t len; + bool valid; + int64_t value; + } cases[] = { + { { OP_0 }, 1, true, 0 }, + { { OP_1NEGATE }, 1, true, -1 }, + { { OP_1 }, 1, true, 1 }, + { { OP_16 }, 1, true, 16 }, + { { 0x01, 0x11 }, 2, true, 17 }, + { { 0x01, 0x91 }, 2, true, -17 }, + { { 0x02, 0x80, 0x00 }, 3, true, 128 }, + { { 0x02, 0x80, 0x80 }, 3, true, -128 }, + { { 0x04, 0xff, 0xff, 0xff, 0x7f }, 5, true, 0x7fffffff }, + { { 0x01, 0x10 }, 2, false, 0 }, /* Should be OP_16 */ + { { 0x01, 0x00 }, 2, false, 0 }, /* Should be OP_0 */ + { { 0x01, 0x80 }, 2, false, 0 }, /* Negative zero */ + { { 0x02, 0x11, 0x00 }, 3, false, 0 }, /* Non-minimal */ + { { 0x05, 1, 2, 3, 4, 5 }, 6, false, 0 }, /* Too long */ + { { OP_PUSHDATA1, 0x01, 0x11 }, 3, false, 0 }, /* Non-minimal push */ + { { OP_DUP }, 1, false, 0 } /* Not a number */ + }; + size_t i; + bool ok = true; + + for (i = 0; i < NUM_ELEMS(cases); ++i) { + int64_t v = 1234; + bool ret = get_number(cases[i].script, cases[i].len, &v); + ok &= check(ret == cases[i].valid, "number: validity"); + ok &= check(v == cases[i].value, "number: value"); + } + return ok; +} + +static bool si_equal(const script_iter *a, const script_iter *b) +{ + return a->script == b->script && a->script_len == b->script_len && + a->next == b->next && a->data == b->data && + a->data_len == b->data_len && a->opcode == b->opcode; +} + +static bool test_match(void) +{ + /* DUP HASH160 <20 bytes> EQUALVERIFY CHECKSIG 144 CSV */ + unsigned char script[29] = { OP_DUP, OP_HASH160, 0x14 }; + const uint32_t pkh[] = { + OP_DUP, OP_HASH160, SI_PUSH, 20, OP_EQUALVERIFY, OP_CHECKSIG + }; + const uint32_t older[] = { SI_NUMBER, 1, 0x7fffffff, OP_CHECKSEQUENCEVERIFY }; + const uint32_t older_range[] = { SI_NUMBER, 145, 200, OP_CHECKSEQUENCEVERIFY }; + const uint32_t wrong_len[] = { OP_DUP, OP_HASH160, SI_PUSH, 32 }; + const uint32_t too_long[] = { SI_NUMBER, 1, 1000, OP_CHECKSEQUENCEVERIFY, OP_DROP }; + const uint32_t bad_pattern[] = { OP_DUP, SI_PUSH }; + script_iter si, start, matched[6]; + int64_t v; + bool ok = true; + + memset(script + 3, 0xab, 20); + script[23] = OP_EQUALVERIFY; + script[24] = OP_CHECKSIG; + script[25] = 0x02; + script[26] = 0x90; + script[27] = 0x00; + script[28] = OP_CHECKSEQUENCEVERIFY; + + si_init(&si, script, sizeof(script)); + ok &= check(!si_match(&si, pkh, NUM_ELEMS(pkh), NULL), "match: before first opcode"); + si_next(&si); + start = si; + ok &= check(!si_match(&si, wrong_len, NUM_ELEMS(wrong_len), NULL) && + si_equal(&si, &start), "match: failure leaves iterator unchanged"); + ok &= check(!si_match(&si, bad_pattern, NUM_ELEMS(bad_pattern), NULL), + "match: truncated pattern"); + ok &= check(si_match(&si, pkh, NUM_ELEMS(pkh), matched), "match: pkh"); + ok &= check(si.opcode == OP_CHECKSIG, "match: left at last opcode"); + ok &= check(matched[2].data_len == 20 && matched[2].data == script + 3, + "match: matched push"); + ok &= check(si_next(&si), "match: next"); + start = si; + ok &= check(!si_match(&si, older_range, NUM_ELEMS(older_range), NULL), + "match: number out of range"); + ok &= check(!si_match(&si, too_long, NUM_ELEMS(too_long), NULL), + "match: script ends before pattern"); + ok &= check(si_match(&si, older, NUM_ELEMS(older), matched), "match: older"); + ok &= check(si_get_number(&matched[0], &v) && v == 144, "match: matched number"); + ok &= check(!si_next(&si) && !si_is_error(&si), "match: end"); + return ok; +} + +int main(void) +{ + bool ok = test_iterate(); + ok &= test_minimal_push(); + ok &= test_number(); + ok &= test_match(); + return ok ? 0 : 1; +} diff --git a/src/script_iter.c b/src/script_iter.c new file mode 100644 index 000000000..9c75df0bf --- /dev/null +++ b/src/script_iter.c @@ -0,0 +1,144 @@ +#include "script_iter.h" +#include +#include + +void si_init(script_iter *si, const unsigned char *script, size_t script_len) +{ + si->script = script || !script_len ? script : NULL; + si->script_len = script_len; + si->next = 0; + si->data = NULL; + si->data_len = 0; + si->opcode = 0; +} + +static bool si_set_error(script_iter *si) +{ + si->script = NULL; + si->data = NULL; + si->data_len = 0; + return false; +} + +bool si_next(script_iter *si) +{ + size_t len_bytes = 0, push_len = 0, i; + + if (si_is_error(si) || si->next >= si->script_len) + return false; + + si->opcode = si->script[si->next++]; + si->data = NULL; + si->data_len = 0; + if (!si_is_push(si)) + return true; + + if (si->opcode < OP_PUSHDATA1) + push_len = si->opcode; + else + len_bytes = si->opcode == OP_PUSHDATA1 ? 1 : si->opcode == OP_PUSHDATA2 ? 2 : 4; + + if (len_bytes > si->script_len - si->next) + return si_set_error(si); /* Truncated push length */ + for (i = 0; i < len_bytes; ++i) + push_len |= (size_t)si->script[si->next + i] << (i * 8); + si->next += len_bytes; + + if (push_len > si->script_len - si->next) + return si_set_error(si); /* Truncated push data */ + si->data = si->script + si->next; + si->data_len = push_len; + si->next += push_len; + return true; +} + +bool si_is_error(const script_iter *si) +{ + return !si->script && si->script_len; +} + +bool si_is_push(const script_iter *si) +{ + return si->opcode <= OP_PUSHDATA4; +} + +bool si_is_minimal_push(const script_iter *si) +{ + const size_t len = si->data_len; + + if (!si_is_push(si)) + return false; + if (!len) + return si->opcode == OP_0; + if (len == 1 && ((si->data[0] >= 1 && si->data[0] <= 16) || si->data[0] == 0x81)) + return false; /* Should be OP_1 to OP_16 or OP_1NEGATE */ + if (len < OP_PUSHDATA1) + return si->opcode == len; + if (len <= 0xff) + return si->opcode == OP_PUSHDATA1; + if (len <= 0xffff) + return si->opcode == OP_PUSHDATA2; + return si->opcode == OP_PUSHDATA4; +} + +bool si_get_number(const script_iter *si, int64_t *value_out) +{ + const size_t len = si->data_len; + int64_t v = 0; + size_t i; + + *value_out = 0; + if (si->opcode == OP_0) + return true; + if (si->opcode == OP_1NEGATE) { + *value_out = -1; + return true; + } + if (si->opcode >= OP_1 && si->opcode <= OP_16) { + *value_out = si->opcode - OP_1 + 1; + return true; + } + if (!si_is_minimal_push(si) || len > 4) + return false; /* Not a minimal push of a 4 byte number */ + if (!(si->data[len - 1] & 0x7f) && + (len == 1 || !(si->data[len - 2] & 0x80))) + return false; /* Not minimally encoded (the push is never empty here) */ + for (i = 0; i < len; ++i) + v |= (int64_t)si->data[i] << (i * 8); + if (si->data[len - 1] & 0x80) + v = -(v & ~((int64_t)0x80 << ((len - 1) * 8))); /* Negative */ + *value_out = v; + return true; +} + +bool si_match(script_iter *si, const uint32_t *pattern, size_t pattern_len, + script_iter *matched) +{ + script_iter s = *si; + size_t i = 0; + int64_t v; + + if (!pattern || !pattern_len || si_is_error(si) || !si->next) + return false; /* No pattern, or no current opcode */ + + while (i < pattern_len) { + const uint32_t elem = pattern[i++]; + if (elem == SI_PUSH) { + if (i >= pattern_len || !si_is_minimal_push(&s) || + s.data_len != pattern[i++]) + return false; + } else if (elem == SI_NUMBER) { + if (i + 1 >= pattern_len || !si_get_number(&s, &v) || + v < (int64_t)pattern[i] || v > (int64_t)pattern[i + 1]) + return false; + i += 2; + } else if (elem > 0xff || s.opcode != elem) + return false; + if (matched) + *matched++ = s; + if (i < pattern_len && !si_next(&s)) + return false; /* Script ended before the pattern */ + } + *si = s; + return true; +} diff --git a/src/script_iter.h b/src/script_iter.h new file mode 100644 index 000000000..2ec5ce615 --- /dev/null +++ b/src/script_iter.h @@ -0,0 +1,66 @@ +#ifndef LIBWALLY_CORE_SCRIPT_ITER_H +#define LIBWALLY_CORE_SCRIPT_ITER_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* An iterator over the opcodes of a script. + * Iterating does not allocate memory or copy any script data. + */ +typedef struct script_iter { + const unsigned char *script; /* The script, or NULL if it is malformed */ + size_t script_len; /* Length of 'script' */ + size_t next; /* Position of the next opcode in 'script' */ + const unsigned char *data; /* The data pushed by the current opcode */ + size_t data_len; /* Length of 'data' (0 for non-pushes) */ + unsigned char opcode; /* The current opcode */ +} script_iter; + +/* Pattern elements for si_match(). Each element of a pattern is an opcode, + * or one of the following followed by its arguments: + * SI_PUSH, len: A minimal push of exactly 'len' bytes. + * SI_NUMBER, min, max: A number from 'min' to 'max' inclusive (see si_get_number). + */ +#define SI_PUSH 0x100 +#define SI_NUMBER 0x200 + +/* Prepare to iterate a script. si_next() reads the first opcode. */ +void si_init(script_iter *si, const unsigned char *script, size_t script_len); + +/* Move to the next opcode. Returns false at the end of the script, or if the + * script is malformed (see si_is_error()). + */ +bool si_next(script_iter *si); + +/* Whether the script is malformed (a push overran the end of the script) */ +bool si_is_error(const script_iter *si); + +/* Whether the current opcode pushes data (OP_0 to OP_PUSHDATA4) */ +bool si_is_push(const script_iter *si); + +/* Whether the current opcode pushes its data using the minimal encoding */ +bool si_is_minimal_push(const script_iter *si); + +/* Get the number pushed by the current opcode: OP_0, OP_1NEGATE, OP_1 to OP_16, + * or a minimally encoded number push of up to 4 bytes. + */ +bool si_get_number(const script_iter *si, int64_t *value_out); + +/* Match the opcodes from the current opcode onwards against a pattern. + * On success, the iterator is left at the last matched opcode and if 'matched' + * is non-NULL, it receives the iterator state of each matched opcode. On + * failure the iterator is left unchanged. + */ +bool si_match(script_iter *si, const uint32_t *pattern, size_t pattern_len, + script_iter *matched); + +#ifdef __cplusplus +} +#endif + +#endif /* LIBWALLY_CORE_SCRIPT_ITER_H */ From 670c082be2df48fcac712c15092d44456a302801 Mon Sep 17 00:00:00 2001 From: odudex Date: Wed, 7 Oct 2026 09:24:45 -0300 Subject: [PATCH 3/9] miniscript: add a script to miniscript decoder Add ms_script_to_miniscript(), which decodes a segwit v0 or tapscript script into miniscript expression text by iterating it forwards, and ms_descriptor_from_script(), which parses the resulting text, checking that it is a valid top level expression which generates the script. Scripts are decoded as Bitcoin Core's DecodeScript() does, and printed as its ToString() prints them. The miniscript node and descriptor definitions are moved to descriptor_int.h to check the expression type. Co-authored-by: Jon Griffiths --- src/Makefile.am | 9 + src/amalgamation/combined.c | 1 + src/ctest/_CMakeLists.txt | 5 + src/ctest/test_miniscript_decode.c | 539 +++++++++++++++ src/descriptor.c | 60 +- src/descriptor_int.h | 72 ++ src/miniscript_decode.c | 1004 ++++++++++++++++++++++++++++ src/miniscript_decode.h | 78 +++ 8 files changed, 1709 insertions(+), 59 deletions(-) create mode 100644 src/ctest/test_miniscript_decode.c create mode 100644 src/descriptor_int.h create mode 100644 src/miniscript_decode.c create mode 100644 src/miniscript_decode.h diff --git a/src/Makefile.am b/src/Makefile.am index e9b9f6f1e..914a6ca36 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -159,6 +159,7 @@ libwallycore_la_SOURCES = \ hmac.c \ internal.c \ map.c \ + miniscript_decode.c \ mnemonic.c \ pbkdf2.c \ psbt.c \ @@ -303,6 +304,14 @@ test_descriptor_LDADD = $(lib_LTLIBRARIES) @CTEST_EXTRA_STATIC@ if PYTHON_MANYLINUX test_descriptor_LDADD += $(PYTHON_LIBS) endif +TESTS += test_miniscript_decode +noinst_PROGRAMS += test_miniscript_decode +test_miniscript_decode_SOURCES = ctest/test_miniscript_decode.c miniscript_decode.c script_iter.c +test_miniscript_decode_CFLAGS = $(TESTS_CFLAGS) +test_miniscript_decode_LDADD = $(lib_LTLIBRARIES) @CTEST_EXTRA_STATIC@ +if PYTHON_MANYLINUX +test_miniscript_decode_LDADD += $(PYTHON_LIBS) +endif if BUILD_ELEMENTS TESTS += test_elements_tx noinst_PROGRAMS += test_elements_tx diff --git a/src/amalgamation/combined.c b/src/amalgamation/combined.c index 11eeef242..8554c7449 100644 --- a/src/amalgamation/combined.c +++ b/src/amalgamation/combined.c @@ -68,6 +68,7 @@ #include "src/hex_.c" #include "src/hmac.c" #include "src/map.c" +#include "src/miniscript_decode.c" #include "src/mnemonic.c" #include "src/pbkdf2.c" #include "src/pullpush.c" diff --git a/src/ctest/_CMakeLists.txt b/src/ctest/_CMakeLists.txt index c98ed6276..c8b124006 100644 --- a/src/ctest/_CMakeLists.txt +++ b/src/ctest/_CMakeLists.txt @@ -22,6 +22,11 @@ target_include_directories(test_descriptor PRIVATE ${CMAKE_BINARY_DIR}) target_link_libraries(test_descriptor PRIVATE wallycore) add_test(test_descriptor test_descriptor) +add_executable(test_miniscript_decode test_miniscript_decode.c ../miniscript_decode.c ../script_iter.c) +target_include_directories(test_miniscript_decode PRIVATE ${CMAKE_BINARY_DIR} $ $) +target_link_libraries(test_miniscript_decode PRIVATE wallycore) +add_test(test_miniscript_decode test_miniscript_decode) + add_executable(test_elements_tx test_elements_tx.c) target_include_directories(test_elements_tx PRIVATE ${CMAKE_BINARY_DIR}) target_link_libraries(test_elements_tx PRIVATE wallycore) diff --git a/src/ctest/test_miniscript_decode.c b/src/ctest/test_miniscript_decode.c new file mode 100644 index 000000000..e13ebd56f --- /dev/null +++ b/src/ctest/test_miniscript_decode.c @@ -0,0 +1,539 @@ +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../miniscript_decode.h" + +#define NUM_ELEMS(a) (sizeof(a) / sizeof(a[0])) +#define TAP WALLY_MINISCRIPT_TAPSCRIPT + +/* Compressed keys, and their x-only equivalents */ +#define K1 "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" +#define K2 "03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a" +#define K3 "025601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc" +#define X1 "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" +#define X2 "d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a" +#define X3 "5601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc" +#define H32 "9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2" +#define H20 "d0721279e70d39fb4aa409b52839a0056454e3b5" + +static bool check(bool ok, const char *what, const char *detail) +{ + if (!ok) + printf("FAIL: %s: %s\n", what, detail); + return ok; +} + +/* Generate the script of a miniscript expression */ +static int to_script(const char *miniscript, uint32_t flags, + unsigned char *script, size_t script_len, size_t *written, + struct wally_map *keys) +{ + struct wally_descriptor *d; + uint32_t i, num_keys; + unsigned char key[EC_PUBLIC_KEY_LEN]; + size_t key_len; + char *key_hex; + /* Many test vectors are not sane, e.g. timelock-only scripts */ + int ret = wally_descriptor_parse(miniscript, NULL, WALLY_NETWORK_NONE, + WALLY_MINISCRIPT_ONLY | WALLY_MINISCRIPT_ALLOW_NON_SANE | flags, + &d); + if (ret != WALLY_OK) + return ret; + ret = wally_descriptor_to_script(d, 0, 0, 0, 0, 0, 0, + script, script_len, written); + if (ret == WALLY_OK && *written > script_len) + ret = WALLY_ERROR; + /* Collect the keys of the expression, to look up pk_h keys from */ + if (ret == WALLY_OK && keys) + ret = wally_descriptor_get_num_keys(d, &num_keys); + for (i = 0; ret == WALLY_OK && keys && i < num_keys; ++i) { + ret = wally_descriptor_get_key(d, i, &key_hex); + if (ret == WALLY_OK) { + ret = wally_hex_to_bytes(key_hex, key, sizeof(key), &key_len); + if (ret == WALLY_OK) + ret = wally_map_add(keys, key, key_len, NULL, 0); + wally_free_string(key_hex); + } + } + wally_descriptor_free(d); + return ret; +} + +/* Decode a script, returning WALLY_OK if both the decoded text matches + * 'expected' and the parsed expression generates the script */ +static int decode(const unsigned char *script, size_t script_len, + const struct wally_map *keys, uint32_t flags, + const char *expected) +{ + struct wally_descriptor *d; + char *text; + int ret = ms_script_to_miniscript(script, script_len, keys, flags, &text); + + if (ret == WALLY_OK) { + if (expected && strcmp(text, expected)) { + printf("decoded %s, expected %s\n", text, expected); + ret = WALLY_ERROR; + } + wally_free_string(text); + } + if (ret == WALLY_OK) { + ret = ms_descriptor_from_script(script, script_len, keys, flags, &d); + if (ret == WALLY_OK) + wally_descriptor_free(d); + } + return ret; +} + +static bool test_round_trip(void) +{ + static const struct { + const char *miniscript; + uint32_t flags; + const char *expected; /* Decoded expression, if not 'miniscript' */ + } cases[] = { + /* Fragments */ + { "pk(" K1 ")", 0, NULL }, + { "pk(" X1 ")", TAP, NULL }, + { "pkh(" K1 ")", 0, NULL }, + { "pkh(" X1 ")", TAP, NULL }, + { "and_v(vc:pk_h(" K1 "),older(1))", 0, "and_v(v:pkh(" K1 "),older(1))" }, + { "and_v(v:pk(" K1 "),older(4259839))", 0, NULL }, + { "and_v(v:pk(" K1 "),after(500000000))", 0, NULL }, + { "and_v(v:pk(" K1 "),sha256(" H32 "))", 0, NULL }, + { "and_v(v:pk(" K1 "),hash256(" H32 "))", 0, NULL }, + { "and_v(v:pk(" K1 "),ripemd160(" H20 "))", 0, NULL }, + { "and_v(v:pk(" K1 "),hash160(" H20 "))", 0, NULL }, + { "multi(1," K1 ")", 0, NULL }, + { "multi(2," K1 "," K2 "," K3 ")", 0, NULL }, + { "multi_a(1," X1 ")", TAP, NULL }, + { "multi_a(2," X1 "," X2 "," X3 ")", TAP, NULL }, + { "and_v(v:multi(2," K1 "," K2 "),pk(" K3 "))", 0, NULL }, + { "and_v(v:multi_a(2," X1 "," X2 "),pk(" X3 "))", TAP, NULL }, + { "and_b(pk(" K1 "),s:pk(" K2 "))", 0, NULL }, + { "and_b(pk(" K1 "),a:pk(" K2 "))", 0, NULL }, + { "or_b(pk(" K1 "),s:pk(" K2 "))", 0, NULL }, + { "or_b(pk(" K1 "),a:pk(" K2 "))", 0, NULL }, + { "t:or_c(pk(" K1 "),v:pk(" K2 "))", 0, NULL }, + { "or_d(pk(" K1 "),pk(" K2 "))", 0, NULL }, + { "or_i(pk(" K1 "),pk(" K2 "))", 0, NULL }, + { "andor(pk(" K1 "),pk(" K2 "),pk(" K3 "))", 0, NULL }, + { "and_n(pk(" K1 "),pk(" K2 "))", 0, NULL }, + { "andor(pk(" K1 "),pk(" K2 "),0)", 0, "and_n(pk(" K1 "),pk(" K2 "))" }, + { "thresh(1,pk(" K1 "))", 0, NULL }, + { "thresh(2,pk(" K1 "),s:pk(" K2 "),a:pk(" K3 "))", 0, NULL }, + { "thresh(2,pk(" X1 "),s:pk(" X2 "),sdv:older(10))", TAP, NULL }, + /* Wrappers */ + { "c:pk_k(" K1 ")", 0, "pk(" K1 ")" }, + { "c:pk_h(" K1 ")", 0, "pkh(" K1 ")" }, + { "and_v(vc:pk_k(" K1 "),pk(" K2 "))", 0, "and_v(v:pk(" K1 "),pk(" K2 "))" }, + { "and_b(pk(" K1 "),sc:pk_k(" K2 "))", 0, "and_b(pk(" K1 "),s:pk(" K2 "))" }, + { "or_d(pk(" K1 "),dv:older(1))", 0, NULL }, + { "or_d(pk(" K1 "),j:pk(" K2 "))", 0, NULL }, + { "and_b(pk(" K1 "),sn:pk(" K2 "))", 0, NULL }, + { "and_v(v:pk(" K1 "),1)", 0, "tv:pk(" K1 ")" }, + { "or_i(0,pk(" K1 "))", 0, "l:pk(" K1 ")" }, + { "or_i(pk(" K1 "),0)", 0, "u:pk(" K1 ")" }, + { "or_i(0,0)", 0, "l:0" }, + { "nnnnnnnnnnn:pk(" K1 ")", 0, NULL }, + { "c:or_i(pk_k(" K1 "),pk_h(" K2 "))", 0, NULL }, + { "and_v(vc:or_i(pk_k(" K1 "),pk_h(" K2 ")),pk(" K3 "))", 0, NULL }, + /* and_v is the outermost expression, nesting to the left */ + { "and_v(v:pk(" K1 "),and_v(v:pk(" K2 "),pk(" K3 ")))", 0, + "and_v(and_v(v:pk(" K1 "),v:pk(" K2 ")),pk(" K3 "))" }, + { "c:and_v(v:pk(" K1 "),pk_k(" K2 "))", 0, "and_v(v:pk(" K1 "),pk(" K2 "))" }, + { "and_b(pk(" K1 "),s:and_v(v:older(1),pk(" K2 ")))", 0, NULL }, + { "and_b(pk(" K1 "),a:and_v(v:pk(" K2 "),pk(" K3 ")))", 0, NULL }, + { "or_d(pk(" K1 "),and_v(v:pk(" K2 "),pk(" K3 ")))", 0, NULL }, + { "or_i(and_v(v:pk(" K1 "),pk(" K2 ")),and_v(v:pk(" K2 "),pk(" K3 ")))", 0, NULL }, + { "andor(pk(" K1 "),and_v(v:pk(" K2 "),pk(" K3 ")),and_v(v:pk(" K2 "),pk(" K1 ")))", 0, NULL }, + { "j:and_v(v:pk(" K1 "),pk(" K2 "))", 0, NULL }, + { "thresh(2,pk(" K1 "),a:andor(pk(" K2 "),pk(" K3 "),pk(" K1 ")),s:pk(" K3 "))", 0, NULL }, + { "and_b(pk(" K1 "),a:and_b(pk(" K2 "),a:pk(" K3 ")))", 0, NULL }, + { "thresh(1,pk(" K1 "),s:thresh(1,pk(" K2 ")))", 0, NULL }, + /* BIP-379 vectors */ + { "and_b(lltvln:after(1231488000),s:pk(03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a))", 0, NULL }, + { "uuj:and_v(v:multi(2,03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a,025601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc),after(1231488000))", 0, NULL }, + { "or_b(un:multi(2,03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729,024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),al:older(16))", 0, NULL }, + { "j:and_v(vdv:after(1567547623),older(16))", 0, NULL }, + { "t:and_v(vu:hash256(" H32 "),v:sha256(" H32 "))", 0, NULL }, + { "t:andor(multi(3,02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e,03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556,02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),v:older(4194305),v:sha256(" H32 "))", 0, NULL }, + { "or_d(multi(1,02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9),or_b(multi(3,022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01,032fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f,03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a),su:after(500000)))", 0, NULL }, + { "or_d(sha256(" H32 "),and_n(un:after(499999999),older(4194305)))", 0, NULL }, + { "and_v(or_i(v:multi(2,02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5,03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb),v:multi(2,03e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a,025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc)),sha256(" H32 "))", 0, NULL }, + { "j:and_b(multi(2,0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),s:or_i(older(1),older(4252898)))", 0, NULL }, + { "and_b(older(16),s:or_d(sha256(" H32 "),n:after(1567547623)))", 0, NULL }, + { "j:and_v(v:ripemd160(" H20 "),or_d(sha256(" H32 "),older(16)))", 0, NULL }, + { "and_b(hash256(" H32 "),a:and_b(hash256(" H32 "),a:older(1)))", 0, NULL }, + { "thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),ac:pk_k(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01))", 0, + "thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:pk(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01))" }, + { "and_n(sha256(" H32 "),t:or_i(v:older(4252898),v:older(16)))", 0, NULL }, + { "or_d(nd:and_v(v:older(4252898),v:older(4252898)),sha256(" H32 "))", 0, NULL }, + { "c:and_v(or_c(sha256(" H32 "),v:multi(1,02c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db)),pk_k(03acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe))", 0, + "and_v(or_c(sha256(" H32 "),v:multi(1,02c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db)),pk(03acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe))" }, + { "c:and_v(or_c(multi(2,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00,02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5),v:ripemd160(" H20 ")),pk_k(03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556))", 0, + "and_v(or_c(multi(2,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00,02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5),v:ripemd160(" H20 ")),pk(03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556))" }, + { "and_v(andor(hash256(" H32 "),v:hash256(" H32 "),v:older(50000)),after(1231488000))", 0, NULL }, + { "andor(hash256(" H32 "),j:and_v(v:ripemd160(" H20 "),older(4194305)),ripemd160(" H20 "))", 0, NULL }, + { "or_i(c:and_v(v:after(500000),pk_k(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),sha256(" H32 "))", 0, + "or_i(and_v(v:after(500000),pk(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),sha256(" H32 "))" }, + { "thresh(2,c:pk_h(025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc),s:sha256(" H32 "),a:ripemd160(" H20 "))", 0, + "thresh(2,pkh(025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc),s:sha256(" H32 "),a:ripemd160(" H20 "))" }, + { "and_n(sha256(" H32 "),uc:and_v(v:older(16),pk_k(03fe72c435413d33d48ac09c9161ba8b09683215439d62b7940502bda8b202e6ce)))", 0, + "and_n(sha256(" H32 "),u:and_v(v:older(16),pk(03fe72c435413d33d48ac09c9161ba8b09683215439d62b7940502bda8b202e6ce)))" }, + { "and_n(c:pk_k(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),and_b(l:older(15),a:older(16)))", 0, + "and_n(pk(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),and_b(l:older(15),a:older(16)))" }, + { "c:or_i(and_v(v:older(16),pk_h(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e)),pk_h(026a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4))", 0, NULL }, + { "or_d(c:pk_h(02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),andor(c:pk_k(024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),older(2016),after(1567547623)))", 0, + "or_d(pkh(02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),andor(pk(024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),older(2016),after(1567547623)))" }, + { "c:andor(ripemd160(" H20 "),pk_h(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e),and_v(v:hash256(" H32 "),pk_h(03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a)))", 0, NULL }, + { "c:andor(u:ripemd160(" H20 "),pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),or_i(pk_h(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01),pk_h(0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798)))", 0, NULL }, + { "c:or_i(andor(c:pk_h(03d30199d74fb5a22d47b6e054e2f378cedacffcb89904a61d75d0dbd407143e65),pk_h(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01),pk_h(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),pk_k(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e))", 0, + "c:or_i(andor(pkh(03d30199d74fb5a22d47b6e054e2f378cedacffcb89904a61d75d0dbd407143e65),pk_h(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01),pk_h(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),pk_k(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e))" }, + { "thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00))", 0, NULL }, + /* Tapscript */ + { "or_d(pk(" X1 "),and_v(v:pkh(" X2 "),after(500000)))", TAP, NULL }, + { "andor(pk(" X1 "),multi_a(1," X2 "),sha256(" H32 "))", TAP, NULL }, + { "or_b(pk(" X1 "),s:pk(" X2 "))", TAP, NULL }, + { "j:and_v(v:hash160(" H20 "),multi_a(1," X1 "," X2 "))", TAP, NULL }, + { "or_d(pk(" X1 "),dv:older(1))", TAP, NULL }, + }; + struct wally_map keys; + unsigned char script[1024]; + size_t i, written; + bool ok = true; + int ret; + + for (i = 0; i < NUM_ELEMS(cases); ++i) { + const char *ms = cases[i].miniscript; + const char *expected = cases[i].expected ? cases[i].expected : ms; + const uint32_t other = cases[i].flags ^ TAP; + + wally_map_init(0, NULL, &keys); + ret = to_script(ms, cases[i].flags, script, sizeof(script), &written, &keys); + if (!check(ret == WALLY_OK, "round trip: parse", ms)) + ok = false; + else { + ok &= check(decode(script, written, &keys, cases[i].flags, expected) == WALLY_OK, + "round trip: decode", ms); + /* Scripts with keys are only valid in one context */ + if (keys.num_items) + ok &= check(decode(script, written, &keys, other, NULL) != WALLY_OK, + "round trip: decode in the wrong context", ms); + } + wally_map_clear(&keys); + } + return ok; +} + +#define PUSH_K1 "21" K1 +#define PUSH_K2 "21" K2 +#define PUSH_K3 "21" K3 +#define PUSH_X1 "20" X1 +#define PUSH_X2 "20" X2 + +/* Decoding, without type checking */ +static bool test_decode(void) +{ + static const struct { + const char *script; + uint32_t flags; + const char *expected; + } cases[] = { + { "51", 0, "1" }, + { "00", 0, "0" }, + { PUSH_K1, 0, "pk_k(" K1 ")" }, + { PUSH_X1, TAP, "pk_k(" X1 ")" }, + { PUSH_K1 "ad", 0, "v:pk(" K1 ")" }, + { PUSH_K1 "ac" PUSH_K2 "ac" PUSH_K3 "ac", 0, + "and_v(and_v(pk(" K1 "),pk(" K2 ")),pk(" K3 "))" }, + /* The W operand is a:X if the operator follows OP_FROMALTSTACK, + * otherwise s:X, where X is everything after the OP_SWAP */ + { PUSH_K1 "ac7c" PUSH_K2 "ac" PUSH_K3 "ac9a", 0, + "and_b(pk(" K1 "),s:and_v(pk(" K2 "),pk(" K3 ")))" }, + { PUSH_K1 "ac7c" PUSH_K2 "ac6b" PUSH_K3 "ac6c9a9a", 0, + "and_b(pk(" K1 "),s:and_b(pk(" K2 "),a:pk(" K3 ")))" }, + { PUSH_K1 "ac7c" PUSH_K2 "ac6b" PUSH_K3 "ac6c9351879a", 0, + "and_b(pk(" K1 "),s:thresh(1,pk(" K2 "),a:pk(" K3 ")))" }, + /* Operands are single expressions */ + { PUSH_K1 "ac" PUSH_K2 "ac6b" PUSH_K3 "ac6c9b", 0, + "and_v(pk(" K1 "),or_b(pk(" K2 "),a:pk(" K3 ")))" }, + { PUSH_K1 "ac" PUSH_K2 "ac64" PUSH_K3 "ac68", 0, + "and_v(pk(" K1 "),or_c(pk(" K2 "),pk(" K3 ")))" }, + { PUSH_K1 "ac" PUSH_K2 "ac5187", 0, + "and_v(pk(" K1 "),thresh(1,pk(" K2 ")))" }, + { PUSH_X1 "ac" PUSH_X2 "ac519c", TAP, + "and_v(pk(" X1 "),multi_a(1," X2 "))" }, + }; + char *text; + size_t i; + bool ok = true; + unsigned char script[256]; + size_t written; + + for (i = 0; i < NUM_ELEMS(cases); ++i) { + if (wally_hex_to_bytes(cases[i].script, script, sizeof(script), &written) != WALLY_OK || + ms_script_to_miniscript(script, written, NULL, cases[i].flags, &text) != WALLY_OK) + ok &= check(false, "decode", cases[i].expected); + else { + ok &= check(!strcmp(text, cases[i].expected), "decode", text); + wally_free_string(text); + } + } + return ok; +} + +/* Decode a hex script, returning the result */ +static int decode_hex(const char *hex, uint32_t flags, bool parse, + const struct wally_map *keys) +{ + unsigned char script[MS_DECODE_MAX_SCRIPT_LEN_SEGWIT_V0 + 1]; + struct wally_descriptor *d; + char *text; + size_t written; + int ret = wally_hex_to_bytes(hex, script, sizeof(script), &written); + + if (ret == WALLY_OK && written > sizeof(script)) + ret = WALLY_ERROR; + if (ret == WALLY_OK) { + if (parse) { + ret = ms_descriptor_from_script(script, written, keys, flags, &d); + if (ret == WALLY_OK) + wally_descriptor_free(d); + } else { + ret = ms_script_to_miniscript(script, written, keys, flags, &text); + if (ret == WALLY_OK) + wally_free_string(text); + } + } + return ret; +} + +static bool test_invalid(void) +{ + static const struct { + const char *script; + uint32_t flags; + const char *comment; + } cases[] = { + { "", 0, "Empty script" }, + { "21" "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817", 0, "Truncated push" }, + { "4c21" K1 "ac", 0, "Non-minimal push" }, + { "0105b2", 0, "Non-minimal number push" }, + { "020500b2", 0, "Non-minimally encoded number" }, + { "4f", 0, "OP_1NEGATE" }, + { "52", 0, "A number that is not 0 or 1" }, + { PUSH_K1 "ac69", 0, "OP_CHECKSIG OP_VERIFY" }, + { "82012088a820" H32 "8769" PUSH_K1 "ac", 0, "OP_EQUAL OP_VERIFY" }, + { "82012087" "69a820" H32 "87", 0, "Hash with OP_EQUAL OP_VERIFY" }, + { "82012188a820" H32 "87", 0, "Hash size not 32" }, + { "82012088a814" H20 "87", 0, "SHA256 with a 20 byte hash" }, + { "82012088a820" H32 "ac", 0, "Hash without OP_EQUAL" }, + { PUSH_X1 "ac", 0, "x-only key in segwit v0" }, + { PUSH_K1 "ac", TAP, "Compressed key in tapscript" }, + { "4104" "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8ac", 0, "Uncompressed key" }, + { "1400112233445566778899aabbccddeeff00112233ac", 0, "20 byte push" }, + { "00b2", 0, "older(0)" }, + { "0500000080 00b2", 0, "older(2^31)" }, + { "0400000080b2", 0, "older(-0)" }, + { "04ffffff7fb2", 0, "older(2^31-1), beyond the 16 bit lock value" }, + { "00b1", 0, "after(0)" }, + { PUSH_K1 "ac0087", 0, "thresh(0,...)" }, + { PUSH_K1 "ac5287", 0, "thresh(2,X)" }, + { PUSH_K1 "ac7c" PUSH_K2 "ac935387", 0, "thresh(3,X,Y)" }, + { "5187", 0, "thresh without a sub-expression" }, + { PUSH_K1 "ac6b" PUSH_K2 "ac6c", 0, "a: without operator" }, + { PUSH_K1 "ac6b" PUSH_K2 "ac6c" PUSH_K1 "ac9a", 0, "a: not used immediately" }, + { "6b" PUSH_K2 "ac6c9a", 0, "a: without first operand" }, + { PUSH_K1 "ac7c" PUSH_K2 "ac", 0, "s: without operator" }, + { PUSH_K1 "ac" PUSH_K2 "ac9a", 0, "and_b without W operand" }, + { PUSH_K1 "ac" PUSH_K2 "ac93", 0, "thresh without W operand" }, + { PUSH_K1 "ac7c" PUSH_K2 "ac93", 0, "Incomplete thresh" }, + { PUSH_K1 "ac7c" PUSH_K2 "ac93" PUSH_K1 "ac5187", 0, "Interrupted thresh" }, + { PUSH_K1 "ac6c", 0, "OP_FROMALTSTACK without OP_TOALTSTACK" }, + { PUSH_K1 "ac6b" PUSH_K2 "ac", 0, "Unterminated a:" }, + { "63" PUSH_K1 "ac68", 0, "OP_IF X OP_ENDIF" }, + { "63" PUSH_K1 "ac67" PUSH_K2 "ac", 0, "Unterminated or_i" }, + { "63" PUSH_K1 "ac67" "68", 0, "Empty or_i branch" }, + { "6367" PUSH_K1 "ac68", 0, "Empty or_i branch" }, + { PUSH_K1 "ac68", 0, "OP_ENDIF without OP_IF" }, + { PUSH_K1 "ac67", 0, "OP_ELSE without OP_IF" }, + { "64" PUSH_K1 "ac68", 0, "OP_NOTIF without condition" }, + { PUSH_K1 "ac73" PUSH_K2 "ac68", 0, "OP_IFDUP without OP_NOTIF" }, + { PUSH_K1 "ac7364" PUSH_K2 "ac67" PUSH_K2 "ac68", 0, "or_d with OP_ELSE" }, + { PUSH_K1 "ac6467" PUSH_K2 "ac68", 0, "Empty or_c branch" }, + { "7663" PUSH_K1 "ac67" PUSH_K2 "ac68", 0, "d: with OP_ELSE" }, + { "829263" PUSH_K1 "ac67" PUSH_K2 "ac68", 0, "j: with OP_ELSE" }, + { "7663" PUSH_K1 "ac", 0, "Unterminated d:" }, + { "76", 0, "OP_DUP alone" }, + { "82", 0, "OP_SIZE alone" }, + { "ac", 0, "OP_CHECKSIG without operand" }, + { "69", 0, "OP_VERIFY without operand" }, + { "92", 0, "OP_0NOTEQUAL without operand" }, + { PUSH_K1 "ac9c", 0, "Unsupported opcode" }, + { "51" PUSH_K1 PUSH_K2 "51ae", 0, "multi with too few keys" }, + { "51" PUSH_K1 PUSH_K2 "53ae", 0, "multi with too many keys" }, + { "53" PUSH_K1 PUSH_K2 "52ae", 0, "multi(3) of 2 keys" }, + { "00" PUSH_K1 "51ae", 0, "multi(0)" }, + { "5100ae", 0, "multi with no keys" }, + { "51" PUSH_X1 PUSH_X2 "52ae", TAP, "multi in tapscript" }, + { PUSH_X1 "ac" PUSH_X2 "ba519c", 0, "multi_a in segwit v0" }, + { PUSH_X1 "ac" PUSH_X2 "ba539c", TAP, "multi_a(3) of 2 keys" }, + { PUSH_X1 "ac" PUSH_X2 "ba009c", TAP, "multi_a(0)" }, + { PUSH_X1 "ba" PUSH_X2 "ba519c", TAP, "multi_a without OP_CHECKSIG" }, + { PUSH_X1 "ac" PUSH_X2 "ba519c69", TAP, "OP_NUMEQUAL OP_VERIFY" }, + { PUSH_K1 "ac929292929292929292929292", 0, "12 wrappers" }, + { "76a914" H20 "88ac", 0, "pk_h with an unknown key" }, + }; + size_t i; + bool ok = true; + + for (i = 0; i < NUM_ELEMS(cases); ++i) { + char hex[1024]; + size_t j, n = 0; + /* Remove any spaces */ + for (j = 0; cases[i].script[j]; ++j) + if (cases[i].script[j] != ' ') + hex[n++] = cases[i].script[j]; + hex[n] = '\0'; + ok &= check(decode_hex(hex, cases[i].flags, false, NULL) == WALLY_EINVAL, + "invalid script", cases[i].comment); + } + return ok; +} + +/* Scripts that decode, but not to a valid miniscript */ +static bool test_invalid_type(void) +{ + static const struct { + const char *script; + uint32_t flags; + const char *comment; + } cases[] = { + { PUSH_K1, 0, "pk_k() alone is type K" }, + { PUSH_K1 "ad", 0, "v:pk() alone is type V" }, + { PUSH_K1 "ac" PUSH_K2 "ac", 0, "and_v(pk(),pk()) is not V,B" }, + { "51b27c52b29b", 0, "or_b(older(1),s:older(2))" }, + { PUSH_K1 "ac64" PUSH_K2 "ac68", 0, "or_c with B second operand" }, + { PUSH_X1 "ac" PUSH_X2 "ac519c", TAP, "and_v(pk(),multi_a()) is not V,B" }, + { "51", 0, "1 (unsupported by the parser)" }, + }; + size_t i; + bool ok = true; + + for (i = 0; i < NUM_ELEMS(cases); ++i) + ok &= check(decode_hex(cases[i].script, cases[i].flags, true, NULL) == WALLY_EINVAL, + "invalid type", cases[i].comment); + return ok; +} + +static bool test_limits(void) +{ + unsigned char script[MS_DECODE_MAX_SCRIPT_LEN_SEGWIT_V0 + 1]; + struct wally_descriptor *d; + size_t i, depth, len; + bool ok = true; + char *text; + + /* Nesting depth: or_i(or_i(...(1,1)...,1),1) */ + for (depth = MS_DECODE_MAX_DEPTH - 1; depth <= MS_DECODE_MAX_DEPTH; ++depth) { + len = 0; + for (i = 0; i < depth; ++i) + script[len++] = OP_IF; + script[len++] = OP_1; + for (i = 0; i < depth; ++i) { + script[len++] = OP_ELSE; + script[len++] = OP_1; + script[len++] = OP_ENDIF; + } + /* An expression of depth+1, as there are depth or_i's around 1 */ + if (depth + 1 <= MS_DECODE_MAX_DEPTH) { + ok &= check(ms_descriptor_from_script(script, len, NULL, 0, &d) == WALLY_OK, + "limits", "maximum depth"); + wally_descriptor_free(d); + } else + ok &= check(ms_script_to_miniscript(script, len, NULL, 0, &text) == WALLY_EINVAL, + "limits", "too deep"); + } + + /* Script length: thresh(1,1,s:1,...) */ + len = 0; + script[len++] = OP_1; + while (len < MS_DECODE_MAX_SCRIPT_LEN_SEGWIT_V0 - 2) { + script[len++] = OP_SWAP; + script[len++] = OP_1; + script[len++] = OP_ADD; + } + script[len++] = OP_1; + script[len++] = OP_EQUAL; + ok &= check(ms_script_to_miniscript(script, len, NULL, 0, &text) == WALLY_OK, + "limits", "maximum length"); + wally_free_string(text); + script[len - 1] = OP_EQUALVERIFY; + script[len++] = OP_1; + ok &= check(ms_script_to_miniscript(script, len, NULL, 0, &text) == WALLY_EINVAL, + "limits", "too long"); + ok &= check(ms_script_to_miniscript(script, len, NULL, TAP, &text) == WALLY_OK, + "limits", "tapscript length"); + wally_free_string(text); + + /* Scripts larger than 520 bytes: multi() with 20 keys, and + * and_v(...and_v(v:pk(K1),v:pk(K2))...,pk(K20)) */ + for (i = 0; i < 4; ++i) { + const bool is_multi = i % 2 == 0, is_tapscript = i >= 2; + const size_t key_len = is_tapscript ? EC_XONLY_PUBLIC_KEY_LEN : EC_PUBLIC_KEY_LEN; + unsigned char priv[EC_PRIVATE_KEY_LEN] = { 0 }, pub[EC_PUBLIC_KEY_LEN]; + size_t j; + + if (is_multi && is_tapscript) + continue; + len = 0; + if (is_multi) + script[len++] = OP_1; + for (j = 0; j < 20; ++j) { + priv[EC_PRIVATE_KEY_LEN - 1] = j + 1; + wally_ec_public_key_from_private_key(priv, sizeof(priv), pub, sizeof(pub)); + script[len++] = key_len; + memcpy(script + len, pub + EC_PUBLIC_KEY_LEN - key_len, key_len); + len += key_len; + if (!is_multi) + script[len++] = j == 19 ? OP_CHECKSIG : OP_CHECKSIGVERIFY; + } + if (is_multi) { + script[len++] = 1; + script[len++] = 20; + script[len++] = OP_CHECKMULTISIG; + } + ok &= check(ms_descriptor_from_script(script, len, NULL, + is_tapscript ? TAP : 0, &d) == WALLY_OK, + "limits", is_multi ? "multi() with 20 keys" : "large script"); + wally_descriptor_free(d); + } + + /* Invalid arguments */ + ok &= check(ms_script_to_miniscript(NULL, 1, NULL, 0, &text) == WALLY_EINVAL, "args", "NULL script"); + ok &= check(ms_script_to_miniscript(script, 0, NULL, 0, &text) == WALLY_EINVAL, "args", "empty script"); + ok &= check(ms_script_to_miniscript(script, 1, NULL, 0x2, &text) == WALLY_EINVAL, "args", "bad flags"); + ok &= check(ms_script_to_miniscript(script, 1, NULL, 0, NULL) == WALLY_EINVAL, "args", "NULL output"); + ok &= check(ms_descriptor_from_script(script, 1, NULL, 0, NULL) == WALLY_EINVAL, "args", "NULL output"); + return ok; +} + +int main(void) +{ + bool ok = test_round_trip(); + ok &= test_decode(); + ok &= test_invalid(); + ok &= test_invalid_type(); + ok &= test_limits(); + wally_cleanup(0); + return ok ? 0 : 1; +} diff --git a/src/descriptor.c b/src/descriptor.c index 6df46ebfd..f82475123 100644 --- a/src/descriptor.c +++ b/src/descriptor.c @@ -1,5 +1,6 @@ #include "internal.h" +#include "descriptor_int.h" #include "script.h" #include "script_int.h" #include "tx_io.h" @@ -28,30 +29,6 @@ #define MS_FLAGS_CANONICALIZE (WALLY_MINISCRIPT_REQUIRE_CHECKSUM | \ WALLY_MINISCRIPT_POLICY_TEMPLATE) -/* Properties and expressions definition */ -#define TYPE_NONE 0x00 -#define TYPE_B 0x01 /* Base expressions */ -#define TYPE_V 0x02 /* Verify expressions */ -#define TYPE_K 0x04 /* Key expressions */ -#define TYPE_W 0x08 /* Wrapped expressions */ -#define TYPE_MASK 0x0F /* expressions mask */ - -#define PROP_Z 0x00000100 /* Zero-arg property */ -#define PROP_O 0x00000200 /* One-arg property */ -#define PROP_N 0x00000400 /* Nonzero arg property */ -#define PROP_D 0x00000800 /* Dissatisfiable property */ -#define PROP_U 0x00001000 /* Unit property */ -#define PROP_E 0x00002000 /* Expression property */ -#define PROP_F 0x00004000 /* Forced property */ -#define PROP_S 0x00008000 /* Safe property */ -#define PROP_M 0x00010000 /* Nonmalleable property */ -#define PROP_X 0x00020000 /* Expensive verify */ -#define PROP_G 0x00040000 /* Relative time timelock */ -#define PROP_H 0x00080000 /* Relative height timelock */ -#define PROP_I 0x00100000 /* Absolute time timelock */ -#define PROP_J 0x00200000 /* Absolute time heightlock */ -#define PROP_K 0x00400000 /* No timelock mixing allowed */ - /* OP_0 properties: Bzudemsxk */ #define PROP_OP_0 (TYPE_B | PROP_Z | PROP_U | PROP_D | PROP_E | PROP_M | PROP_S | PROP_X | PROP_K) /* OP_1 properties: Bzufmxk */ @@ -192,41 +169,6 @@ static const struct addr_ver_t g_address_versions[] = { }, }; -/* A node in a parsed miniscript expression */ -typedef struct ms_node_t { - struct ms_node_t *next; - struct ms_node_t *child; - struct ms_node_t *parent; - uint32_t kind; - uint32_t type_properties; - int64_t number; - const char *child_path; - const char *data; - uint32_t data_len; - uint32_t child_path_len; - char wrapper_str[12]; - unsigned short flags; /* WALLY_MS_IS_ flags */ - unsigned char builtin; -} ms_node; - -typedef struct wally_descriptor { - char *src; /* The canonical source script */ - size_t src_len; /* Length of src */ - ms_node *top_node; /* The first node of the parse tree */ - const struct addr_ver_t *addr_ver; - uint32_t features; /* Features present in the parsed tree */ - uint32_t num_variants; /* Number of script variants in the expression */ - uint32_t num_multipaths; /* Number of multi-path items in the expression */ - size_t script_len; /* Max script length generatable from this expression */ - /* User modified for generation */ - uint32_t variant; /* Variant for derivation of multi-type expressions */ - uint32_t child_num; /* BIP32 child number for derivation */ - uint32_t multi_index; /* Multi-path index for derivation */ - uint32_t *path_buff; /* Path buffer for deriving keys */ - uint32_t max_path_elems; /* Max path length seen in the descriptor */ - struct wally_map keys; -} ms_ctx; - static int ctx_add_key_node(ms_ctx *ctx, ms_node *node) { const char *v = (char *)node; diff --git a/src/descriptor_int.h b/src/descriptor_int.h new file mode 100644 index 000000000..3c7513f15 --- /dev/null +++ b/src/descriptor_int.h @@ -0,0 +1,72 @@ +#ifndef LIBWALLY_CORE_DESCRIPTOR_INT_H +#define LIBWALLY_CORE_DESCRIPTOR_INT_H 1 + +#include +#include +#include +#include + +/* Properties and expressions definition */ +#define TYPE_NONE 0x00 +#define TYPE_B 0x01 /* Base expressions */ +#define TYPE_V 0x02 /* Verify expressions */ +#define TYPE_K 0x04 /* Key expressions */ +#define TYPE_W 0x08 /* Wrapped expressions */ +#define TYPE_MASK 0x0F /* expressions mask */ + +#define PROP_Z 0x00000100 /* Zero-arg property */ +#define PROP_O 0x00000200 /* One-arg property */ +#define PROP_N 0x00000400 /* Nonzero arg property */ +#define PROP_D 0x00000800 /* Dissatisfiable property */ +#define PROP_U 0x00001000 /* Unit property */ +#define PROP_E 0x00002000 /* Expression property */ +#define PROP_F 0x00004000 /* Forced property */ +#define PROP_S 0x00008000 /* Safe property */ +#define PROP_M 0x00010000 /* Nonmalleable property */ +#define PROP_X 0x00020000 /* Expensive verify */ +#define PROP_G 0x00040000 /* Relative time timelock */ +#define PROP_H 0x00080000 /* Relative height timelock */ +#define PROP_I 0x00100000 /* Absolute time timelock */ +#define PROP_J 0x00200000 /* Absolute time heightlock */ +#define PROP_K 0x00400000 /* No timelock mixing allowed */ + +/* A node in a parsed miniscript expression */ +typedef struct ms_node_t { + struct ms_node_t *next; + struct ms_node_t *child; + struct ms_node_t *parent; + uint32_t kind; + uint32_t type_properties; + int64_t number; + const char *child_path; + const char *data; + uint32_t data_len; + uint32_t child_path_len; + char wrapper_str[12]; + unsigned short flags; /* WALLY_MS_IS_ flags */ + unsigned char builtin; +} ms_node; + +struct addr_ver_t; + +struct wally_descriptor { + char *src; /* The canonical source script */ + size_t src_len; /* Length of src */ + ms_node *top_node; /* The first node of the parse tree */ + const struct addr_ver_t *addr_ver; + uint32_t features; /* Features present in the parsed tree */ + uint32_t num_variants; /* Number of script variants in the expression */ + uint32_t num_multipaths; /* Number of multi-path items in the expression */ + size_t script_len; /* Max script length generatable from this expression */ + /* User modified for generation */ + uint32_t variant; /* Variant for derivation of multi-type expressions */ + uint32_t child_num; /* BIP32 child number for derivation */ + uint32_t multi_index; /* Multi-path index for derivation */ + uint32_t *path_buff; /* Path buffer for deriving keys */ + uint32_t max_path_elems; /* Max path length seen in the descriptor */ + struct wally_map keys; +}; + +typedef struct wally_descriptor ms_ctx; + +#endif /* LIBWALLY_CORE_DESCRIPTOR_INT_H */ diff --git a/src/miniscript_decode.c b/src/miniscript_decode.c new file mode 100644 index 000000000..38bf0ff58 --- /dev/null +++ b/src/miniscript_decode.c @@ -0,0 +1,1004 @@ +#include "internal.h" + +#include "descriptor_int.h" +#include "miniscript_decode.h" +#include "script_iter.h" + +#include +#include +#include +#include +#include + +/* Script to miniscript decoding. + * + * The script is iterated forwards, building a tree of the expressions found, + * which is then printed as text. This decodes scripts as Bitcoin Core's + * DecodeScript() does (which iterates backwards): + * + * - Expressions, e.g. "" or " OP_CHECKSEQUENCEVERIFY", are added + * as items to the current scope. + * - Operators take their operands from the last items of the current scope, + * e.g. OP_CHECKSIG wraps the last item in c:, while OP_BOOLAND combines the + * last two. Each operand is a single item, so that and_v is always the + * outermost expression, e.g. and_v(X,c:Y) rather than c:and_v(X,Y). + * - OP_IF, OP_NOTIF, OP_ELSE, OP_TOALTSTACK and OP_SWAP begin a new scope, + * which is closed by the operator that ends the expression they begin + * (OP_ELSE, OP_ENDIF, OP_FROMALTSTACK, or for s:, the OP_BOOLAND, OP_BOOLOR + * or OP_ADD that uses it). The items of a closed scope are combined using + * and_v, nesting to the left, e.g. and_v(and_v(X,Y),Z). + * - The W expressions a:X and s:X are only valid as the last operand of + * and_b, or_b and thresh. + * + * Decoding only checks that the script is a miniscript; the resulting + * expression is type checked by parsing it. + */ + +#define NO_NODE 0xffffffff +#define MAX_WRAPPERS 11 /* Maximum wrappers on an expression (ms_node.wrapper_str) */ +#define MULTI_MAX_KEYS 20 +#define MULTI_A_MAX_KEYS 999 /* BIP-342: stack limited to 1000 elements, one used by the threshold */ +#define LOCKTIME_MAX 0x7fffffff +#define SEQ_LOCKTIME_TYPE_FLAG 0x00400000 /* BIP-68 time based relative lock */ +#define SEQ_LOCKTIME_MASK 0x0000ffff /* BIP-68 relative lock value */ + +/* Expression fragments */ +enum { + FRAG_JUST_0, FRAG_JUST_1, FRAG_PK_K, FRAG_PK_H, FRAG_PK, FRAG_PKH, + FRAG_OLDER, FRAG_AFTER, FRAG_SHA256, FRAG_HASH256, FRAG_RIPEMD160, + FRAG_HASH160, FRAG_MULTI, FRAG_MULTI_A, FRAG_AND_V, FRAG_AND_B, + FRAG_AND_N, FRAG_ANDOR, FRAG_OR_B, FRAG_OR_C, FRAG_OR_D, FRAG_OR_I, + FRAG_THRESH, + /* Wrappers */ + FRAG_A, FRAG_S, FRAG_C, FRAG_D, FRAG_V, FRAG_J, FRAG_N, FRAG_T, FRAG_L, + FRAG_U +}; +#define IS_WRAPPER(frag) ((frag) >= FRAG_A) + +/* Fragment names, in FRAG_ order */ +static const char *const g_frag_names[] = { + "0", "1", "pk_k", "pk_h", "pk", "pkh", + "older", "after", "sha256", "hash256", "ripemd160", + "hash160", "multi", "multi_a", "and_v", "and_b", + "and_n", "andor", "or_b", "or_c", "or_d", "or_i", + "thresh", + "a", "s", "c", "d", "v", "j", "n", "t", "l", + "u" +}; + +static const struct ms_hash_t { + unsigned char opcode; + unsigned char frag; + unsigned char len; +} g_hashes[] = { + { OP_SHA256, FRAG_SHA256, SHA256_LEN }, + { OP_HASH256, FRAG_HASH256, SHA256_LEN }, + { OP_RIPEMD160, FRAG_RIPEMD160, RIPEMD160_LEN }, + { OP_HASH160, FRAG_HASH160, HASH160_LEN } +}; + +/* A decoded expression */ +typedef struct ms_dnode { + uint32_t child; /* First sub-expression */ + uint32_t next; /* Next sibling sub-expression */ + uint32_t parent; /* Parent expression */ + uint32_t value; /* Number/threshold, key index (pk_h), or number of wrappers */ + uint32_t offset; /* Script offset of the key/hash, or first key push (multi/multi_a) */ + uint32_t depth; /* Nesting depth, as calculated by wally_descriptor_parse() */ + unsigned char frag; +} ms_dnode; + +/* Item kinds */ +#define ITEM_EXPR 0 /* An expression */ +#define ITEM_W 1 /* An a: expression, which must be used by the next operator */ +#define ITEM_THRESH 2 /* An incomplete thresh */ + +typedef struct ms_ditem { + uint32_t node; + uint32_t last; /* ITEM_THRESH: The last sub-expression */ + uint32_t count; /* ITEM_THRESH: The number of sub-expressions */ + unsigned char kind; +} ms_ditem; + +/* Scope kinds, with the script decoded when they are opened */ +enum { + SCOPE_TOP, /* The script */ + SCOPE_OR_I, /* OP_IF */ + SCOPE_OR_I_Z, /* OP_IF X OP_ELSE */ + SCOPE_NOTIF, /* X OP_NOTIF */ + SCOPE_OR_D, /* X OP_IFDUP OP_NOTIF */ + SCOPE_ANDOR, /* X OP_NOTIF Z OP_ELSE */ + SCOPE_D, /* OP_DUP OP_IF */ + SCOPE_J, /* OP_SIZE OP_0NOTEQUAL OP_IF */ + SCOPE_A, /* OP_TOALTSTACK */ + SCOPE_S /* OP_SWAP */ +}; + +typedef struct ms_dscope { + size_t base; /* Index of the first item in the scope */ + uint32_t x; /* Condition (or_c/or_d/andor) or first branch (or_i) */ + uint32_t z; /* Second branch (andor) */ + unsigned char kind; +} ms_dscope; + +typedef struct ms_decoder { + const unsigned char *script; + size_t script_len; + size_t key_len; /* Length of keys in the script */ + bool is_tapscript; + const struct wally_map *keys; /* Keys for pk_h */ + unsigned char *key_hashes; /* HASH160 of each key in 'keys' */ + ms_dnode *nodes; + size_t num_nodes, nodes_len; + ms_ditem *items; + size_t num_items, items_len; + ms_dscope *scopes; + size_t num_scopes, scopes_len; +} ms_decoder; + +/* Ensure there is space for another element in an array */ +static int array_reserve(void **p, size_t num_elems, size_t *allocation_len, + size_t elem_size) +{ + size_t n; + void *new_p; + + if (num_elems < *allocation_len) + return WALLY_OK; + n = *allocation_len ? *allocation_len * 2 : 16; + if (!(new_p = wally_malloc(n * elem_size))) + return WALLY_ENOMEM; + if (*p) { + memcpy(new_p, *p, num_elems * elem_size); + wally_free(*p); + } + *p = new_p; + *allocation_len = n; + return WALLY_OK; +} + +static int node_new(ms_decoder *d, unsigned char frag, uint32_t value, + size_t offset, uint32_t *output) +{ + ms_dnode *node; + int ret = array_reserve((void **)&d->nodes, d->num_nodes, + &d->nodes_len, sizeof(*d->nodes)); + if (ret == WALLY_OK) { + node = d->nodes + d->num_nodes; + node->child = node->next = node->parent = NO_NODE; + node->value = value; + node->offset = (uint32_t)offset; + node->depth = frag == FRAG_JUST_0 || frag == FRAG_JUST_1 ? 1 : 2; + node->frag = frag; + *output = (uint32_t)d->num_nodes++; + } + return ret; +} + +/* Create an expression from its sub-expressions */ +static int node_make(ms_decoder *d, unsigned char frag, + const uint32_t *subs, size_t num_subs, uint32_t *output) +{ + ms_dnode *node, *sub; + uint32_t depth = 0; + size_t i; + int ret = node_new(d, frag, 0, 0, output); + + if (ret != WALLY_OK) + return ret; + node = d->nodes + *output; + node->child = subs[0]; + for (i = 0; i < num_subs; ++i) { + sub = d->nodes + subs[i]; + sub->parent = *output; + sub->next = i + 1 < num_subs ? subs[i + 1] : NO_NODE; + if (sub->depth > depth) + depth = sub->depth; + } + if (IS_WRAPPER(frag)) { + sub = d->nodes + subs[0]; + node->value = IS_WRAPPER(sub->frag) ? sub->value + 1 : 1; + node->depth = depth; + if (node->value > MAX_WRAPPERS) + return WALLY_EINVAL; /* Too many wrappers */ + } else + node->depth = depth + 1; + return node->depth > MS_DECODE_MAX_DEPTH ? WALLY_EINVAL : WALLY_OK; +} + +/* Apply a wrapper to an expression */ +static int node_wrap(ms_decoder *d, unsigned char frag, uint32_t *node) +{ + const uint32_t sub = *node; + return node_make(d, frag, &sub, 1, node); +} + +static bool node_is(const ms_decoder *d, uint32_t node, unsigned char frag) +{ + return d->nodes[node].frag == frag; +} + +static ms_dscope *scope_current(ms_decoder *d) +{ + return d->scopes + d->num_scopes - 1; +} + +/* Get the last item in the current scope, or NULL if it has none */ +static ms_ditem *item_last(ms_decoder *d) +{ + if (d->num_items == scope_current(d)->base) + return NULL; + return d->items + d->num_items - 1; +} + +static int item_push(ms_decoder *d, uint32_t node, unsigned char kind) +{ + ms_ditem *item; + int ret = array_reserve((void **)&d->items, d->num_items, + &d->items_len, sizeof(*d->items)); + if (ret == WALLY_OK) { + item = d->items + d->num_items++; + item->node = node; + item->last = NO_NODE; + item->count = 0; + item->kind = kind; + } + return ret; +} + +/* Remove the last item in the current scope, which must be an expression */ +static int item_pop(ms_decoder *d, uint32_t *node) +{ + const ms_ditem *item = item_last(d); + + if (!item || item->kind != ITEM_EXPR) + return WALLY_EINVAL; + *node = item->node; + --d->num_items; + return WALLY_OK; +} + +static int item_push_new(ms_decoder *d, unsigned char frag, uint32_t value, + size_t offset) +{ + uint32_t node; + int ret = node_new(d, frag, value, offset, &node); + return ret == WALLY_OK ? item_push(d, node, ITEM_EXPR) : ret; +} + +/* Apply a wrapper to the last item in the current scope */ +static int item_wrap(ms_decoder *d, unsigned char frag) +{ + uint32_t node; + int ret = item_pop(d, &node); + + if (ret == WALLY_OK) { + if (frag == FRAG_C && node_is(d, node, FRAG_PK_K)) + d->nodes[node].frag = FRAG_PK; /* pk(K) is c:pk_k(K) */ + else if (frag == FRAG_C && node_is(d, node, FRAG_PK_H)) + d->nodes[node].frag = FRAG_PKH; /* pkh(K) is c:pk_h(K) */ + else + ret = node_wrap(d, frag, &node); + } + return ret == WALLY_OK ? item_push(d, node, ITEM_EXPR) : ret; +} + +static int scope_open(ms_decoder *d, unsigned char kind, uint32_t x, uint32_t z) +{ + ms_dscope *scope; + int ret = array_reserve((void **)&d->scopes, d->num_scopes, + &d->scopes_len, sizeof(*d->scopes)); + if (ret == WALLY_OK) { + scope = d->scopes + d->num_scopes++; + scope->base = d->num_items; + scope->x = x; + scope->z = z; + scope->kind = kind; + } + return ret; +} + +/* Close the current scope, combining its items into a single expression */ +static int scope_close(ms_decoder *d, uint32_t *output) +{ + const size_t base = scope_current(d)->base; + uint32_t subs[2]; + size_t i; + int ret = base < d->num_items ? WALLY_OK : WALLY_EINVAL; /* Empty scope */ + + for (i = base; ret == WALLY_OK && i < d->num_items; ++i) { + if (d->items[i].kind != ITEM_EXPR) + ret = WALLY_EINVAL; /* Incomplete thresh, or unused a: */ + else if (i == base) + *output = d->items[i].node; + else if (node_is(d, d->items[i].node, FRAG_JUST_1)) + ret = node_wrap(d, FRAG_T, output); /* t:X is and_v(X,1) */ + else { + subs[0] = *output; + subs[1] = d->items[i].node; + ret = node_make(d, FRAG_AND_V, subs, 2, output); + } + } + d->num_items = base; + --d->num_scopes; + return ret; +} + +/* Find the key with a given HASH160 */ +static int lookup_key(ms_decoder *d, const unsigned char *hash, uint32_t *index) +{ + const struct wally_map_item *item; + const size_t num_keys = d->keys ? d->keys->num_items : 0; + size_t i; + int ret = WALLY_OK; + + if (!d->key_hashes && num_keys) { + /* Calculate the key hashes the first time they are needed */ + if (!(d->key_hashes = wally_malloc(num_keys * HASH160_LEN))) + return WALLY_ENOMEM; + for (i = 0; ret == WALLY_OK && i < num_keys; ++i) { + item = d->keys->items + i; + if (item->key && item->key_len == d->key_len) + ret = wally_hash160(item->key, item->key_len, + d->key_hashes + i * HASH160_LEN, HASH160_LEN); + } + if (ret != WALLY_OK) + return ret; + } + for (i = 0; i < num_keys; ++i) { + item = d->keys->items + i; + if (item->key && item->key_len == d->key_len && + !memcmp(hash, d->key_hashes + i * HASH160_LEN, HASH160_LEN)) { + *index = (uint32_t)i; + return WALLY_OK; + } + } + return WALLY_EINVAL; /* Key not found */ +} + +/* multi(k,key1,...,keyn): ... OP_CHECKMULTISIG */ +static int decode_multi(ms_decoder *d, script_iter *si, int64_t k, bool *matched) +{ + script_iter s = *si; + size_t num_keys = 0; + int64_t n; + int ret; + + *matched = false; + for (;;) { + if (!si_next(&s)) + return WALLY_OK; /* Not a multi */ + if (s.opcode != d->key_len) + break; /* Not a key push */ + if (++num_keys > MULTI_MAX_KEYS) + return WALLY_OK; /* Not a multi */ + } + if (!si_get_number(&s, &n) || !si_next(&s) || + (s.opcode != OP_CHECKMULTISIG && s.opcode != OP_CHECKMULTISIGVERIFY)) + return WALLY_OK; /* Not a multi */ + + *matched = true; + if (n != (int64_t)num_keys || !num_keys || k < 1 || k > n) + return WALLY_EINVAL; + ret = item_push_new(d, FRAG_MULTI, (uint32_t)k, si->next); + if (ret == WALLY_OK && s.opcode == OP_CHECKMULTISIGVERIFY) + ret = item_wrap(d, FRAG_V); + *si = s; + return ret; +} + +/* multi_a(k,key1,...,keyn): + * OP_CHECKSIG OP_CHECKSIGADD ... OP_CHECKSIGADD OP_NUMEQUAL + */ +static int decode_multi_a(ms_decoder *d, script_iter *si, bool *matched) +{ + script_iter s = *si; + size_t num_keys = 1; + int64_t k; + int ret; + + *matched = false; + if (!si_next(&s) || s.opcode != OP_CHECKSIG) + return WALLY_OK; /* Not a multi_a */ + for (;;) { + if (!si_next(&s)) + return WALLY_OK; /* Not a multi_a */ + if (s.opcode != d->key_len) + break; /* Not a key push */ + if (!si_next(&s) || s.opcode != OP_CHECKSIGADD) + return WALLY_OK; /* Not a multi_a */ + ++num_keys; + } + if (!si_get_number(&s, &k) || !si_next(&s) || + (s.opcode != OP_NUMEQUAL && s.opcode != OP_NUMEQUALVERIFY)) + return WALLY_OK; /* Not a multi_a */ + + *matched = true; + if (num_keys > MULTI_A_MAX_KEYS || k < 1 || k > (int64_t)num_keys) + return WALLY_EINVAL; + ret = item_push_new(d, FRAG_MULTI_A, (uint32_t)k, si->next - 1 - d->key_len); + if (ret == WALLY_OK && s.opcode == OP_NUMEQUALVERIFY) + ret = item_wrap(d, FRAG_V); + *si = s; + return ret; +} + +/* Complete a thresh: X1 X2 OP_ADD ... Xn OP_ADD OP_EQUAL */ +static int decode_thresh(ms_decoder *d, int64_t k, bool verify) +{ + ms_ditem *item = item_last(d); + uint32_t sub, count = 1; + int ret = WALLY_OK; + + if (!item || item->kind == ITEM_W) + return WALLY_EINVAL; + if (item->kind == ITEM_THRESH) + count = item->count; + else { + /* A thresh with a single sub-expression */ + sub = item->node; + ret = node_make(d, FRAG_THRESH, &sub, 1, &item->node); + } + if (ret == WALLY_OK && (k < 1 || k > count)) + ret = WALLY_EINVAL; + if (ret == WALLY_OK) { + d->nodes[item->node].value = (uint32_t)k; + item->kind = ITEM_EXPR; + if (verify) + ret = item_wrap(d, FRAG_V); + } + return ret; +} + +/* A number: older, after, multi, the end of a thresh, or 0/1 */ +static int decode_number(ms_decoder *d, script_iter *si, int64_t v) +{ + script_iter next = *si; + bool matched; + int ret; + + if (si_next(&next)) { + switch (next.opcode) { + case OP_CHECKSEQUENCEVERIFY: + case OP_CHECKLOCKTIMEVERIFY: + /* older(n): OP_CHECKSEQUENCEVERIFY + * after(n): OP_CHECKLOCKTIMEVERIFY */ + if (v < 1 || v > LOCKTIME_MAX) + return WALLY_EINVAL; + if (next.opcode == OP_CHECKSEQUENCEVERIFY && + (v & ~SEQ_LOCKTIME_TYPE_FLAG) > SEQ_LOCKTIME_MASK) + return WALLY_EINVAL; /* Lock value beyond 16 bits */ + *si = next; + return item_push_new(d, next.opcode == OP_CHECKSEQUENCEVERIFY ? + FRAG_OLDER : FRAG_AFTER, (uint32_t)v, 0); + case OP_EQUAL: + case OP_EQUALVERIFY: + *si = next; + return decode_thresh(d, v, next.opcode == OP_EQUALVERIFY); + } + if (!d->is_tapscript) { + ret = decode_multi(d, si, v, &matched); + if (ret != WALLY_OK || matched) + return ret; + } + } + if (si->opcode == OP_0 || si->opcode == OP_1) + return item_push_new(d, si->opcode == OP_0 ? FRAG_JUST_0 : FRAG_JUST_1, 0, 0); + return WALLY_EINVAL; +} + +/* pk_k(key): , or multi_a */ +static int decode_key(ms_decoder *d, script_iter *si) +{ + bool matched; + int ret; + + if (d->is_tapscript) { + ret = decode_multi_a(d, si, &matched); + if (ret != WALLY_OK || matched) + return ret; + } + return item_push_new(d, FRAG_PK_K, 0, si->data - d->script); +} + +static int decode_dup(ms_decoder *d, script_iter *si) +{ + static const uint32_t pk_h[] = { + OP_DUP, OP_HASH160, SI_PUSH, HASH160_LEN, OP_EQUALVERIFY + }; + static const uint32_t dup_if[] = { OP_DUP, OP_IF }; + script_iter matched[4]; + uint32_t key_index; + int ret; + + if (si_match(si, pk_h, NUM_ELEMS(pk_h), matched)) { + /* pk_h(key): OP_DUP OP_HASH160 OP_EQUALVERIFY */ + ret = lookup_key(d, matched[2].data, &key_index); + return ret == WALLY_OK ? item_push_new(d, FRAG_PK_H, key_index, 0) : ret; + } + if (si_match(si, dup_if, NUM_ELEMS(dup_if), NULL)) + return scope_open(d, SCOPE_D, NO_NODE, NO_NODE); + return WALLY_EINVAL; +} + +static int decode_size(ms_decoder *d, script_iter *si) +{ + static const uint32_t size_if[] = { OP_SIZE, OP_0NOTEQUAL, OP_IF }; + uint32_t hash[] = { + OP_SIZE, SI_NUMBER, SHA256_LEN, SHA256_LEN, OP_EQUALVERIFY, 0, SI_PUSH, 0 + }; + script_iter matched[5], next; + size_t i; + int ret; + + if (si_match(si, size_if, NUM_ELEMS(size_if), NULL)) + return scope_open(d, SCOPE_J, NO_NODE, NO_NODE); + + /* sha256(h): OP_SIZE <32> OP_EQUALVERIFY OP_SHA256 OP_EQUAL + * (and similarly for hash256, ripemd160 and hash160) */ + for (i = 0; i < NUM_ELEMS(g_hashes); ++i) { + hash[5] = g_hashes[i].opcode; + hash[7] = g_hashes[i].len; + if (si_match(si, hash, NUM_ELEMS(hash), matched)) { + next = *si; + if (!si_next(&next) || + (next.opcode != OP_EQUAL && next.opcode != OP_EQUALVERIFY)) + return WALLY_EINVAL; + *si = next; + ret = item_push_new(d, g_hashes[i].frag, 0, matched[4].data - d->script); + if (ret == WALLY_OK && next.opcode == OP_EQUALVERIFY) + ret = item_wrap(d, FRAG_V); + return ret; + } + } + return WALLY_EINVAL; +} + +/* or_c(X,Z): X OP_NOTIF Z OP_ENDIF + * or_d(X,Z): X OP_IFDUP OP_NOTIF Z OP_ENDIF + * andor(X,Y,Z): X OP_NOTIF Z OP_ELSE Y OP_ENDIF + */ +static int decode_notif(ms_decoder *d, unsigned char kind) +{ + uint32_t x; + int ret = item_pop(d, &x); + return ret == WALLY_OK ? scope_open(d, kind, x, NO_NODE) : ret; +} + +static int decode_else(ms_decoder *d) +{ + const unsigned char kind = scope_current(d)->kind; + const uint32_t x = scope_current(d)->x; + uint32_t branch; + int ret; + + if (kind != SCOPE_OR_I && kind != SCOPE_NOTIF) + return WALLY_EINVAL; + ret = scope_close(d, &branch); + if (ret == WALLY_OK) { + if (kind == SCOPE_OR_I) + ret = scope_open(d, SCOPE_OR_I_Z, branch, NO_NODE); + else + ret = scope_open(d, SCOPE_ANDOR, x, branch); + } + return ret; +} + +static int decode_endif(ms_decoder *d) +{ + const unsigned char kind = scope_current(d)->kind; + uint32_t subs[3], node; + int ret; + + subs[0] = scope_current(d)->x; + subs[2] = scope_current(d)->z; + if (kind == SCOPE_TOP || kind == SCOPE_OR_I || + kind == SCOPE_A || kind == SCOPE_S) + return WALLY_EINVAL; + ret = scope_close(d, &subs[1]); + if (ret != WALLY_OK) + return ret; + + switch (kind) { + case SCOPE_OR_I_Z: + /* or_i(X,Z): OP_IF X OP_ELSE Z OP_ENDIF */ + if (node_is(d, subs[0], FRAG_JUST_0)) + ret = node_make(d, FRAG_L, subs + 1, 1, &node); /* l:X is or_i(0,X) */ + else if (node_is(d, subs[1], FRAG_JUST_0)) + ret = node_make(d, FRAG_U, subs, 1, &node); /* u:X is or_i(X,0) */ + else + ret = node_make(d, FRAG_OR_I, subs, 2, &node); + break; + case SCOPE_NOTIF: + ret = node_make(d, FRAG_OR_C, subs, 2, &node); + break; + case SCOPE_OR_D: + ret = node_make(d, FRAG_OR_D, subs, 2, &node); + break; + case SCOPE_ANDOR: + if (node_is(d, subs[2], FRAG_JUST_0)) + ret = node_make(d, FRAG_AND_N, subs, 2, &node); /* and_n(X,Y) is andor(X,Y,0) */ + else + ret = node_make(d, FRAG_ANDOR, subs, 3, &node); + break; + case SCOPE_D: + /* d:X: OP_DUP OP_IF X OP_ENDIF */ + ret = node_make(d, FRAG_D, subs + 1, 1, &node); + break; + default: + /* j:X: OP_SIZE OP_0NOTEQUAL OP_IF X OP_ENDIF */ + ret = node_make(d, FRAG_J, subs + 1, 1, &node); + break; + } + return ret == WALLY_OK ? item_push(d, node, ITEM_EXPR) : ret; +} + +/* a:X: OP_TOALTSTACK X OP_FROMALTSTACK */ +static int decode_fromaltstack(ms_decoder *d) +{ + uint32_t node; + int ret = WALLY_EINVAL; + + if (scope_current(d)->kind == SCOPE_A) + ret = scope_close(d, &node); + if (ret == WALLY_OK) + ret = node_wrap(d, FRAG_A, &node); + return ret == WALLY_OK ? item_push(d, node, ITEM_W) : ret; +} + +/* Add a W expression to an incomplete thresh */ +static int thresh_add(ms_decoder *d, ms_ditem *item, uint32_t w) +{ + ms_dnode *thresh = d->nodes + item->node, *sub = d->nodes + w; + + d->nodes[item->last].next = w; + sub->parent = item->node; + item->last = w; + ++item->count; + if (sub->depth + 1 > thresh->depth) + thresh->depth = sub->depth + 1; + return thresh->depth > MS_DECODE_MAX_DEPTH ? WALLY_EINVAL : WALLY_OK; +} + +/* and_b(X,Y): X Y OP_BOOLAND + * or_b(X,Z): X Z OP_BOOLOR + * thresh(k,X1,...,Xn): X1 X2 OP_ADD ... Xn OP_ADD OP_EQUAL + * Where Y, Z and X2 to Xn are W expressions. + */ +static int decode_combine(ms_decoder *d, unsigned char opcode) +{ + ms_ditem *item = item_last(d); + uint32_t subs[2]; + int ret = WALLY_OK; + + if (item && item->kind == ITEM_W) { + subs[1] = item->node; /* a:X */ + --d->num_items; + } else if (scope_current(d)->kind == SCOPE_S) { + ret = scope_close(d, &subs[1]); /* s:X */ + if (ret == WALLY_OK) + ret = node_wrap(d, FRAG_S, &subs[1]); + } else + ret = WALLY_EINVAL; /* No W expression */ + + if (ret == WALLY_OK && !(item = item_last(d))) + ret = WALLY_EINVAL; + if (ret != WALLY_OK) + return ret; + if (opcode == OP_ADD && item->kind == ITEM_THRESH) + return thresh_add(d, item, subs[1]); + if (item->kind != ITEM_EXPR) + return WALLY_EINVAL; + subs[0] = item->node; + if (opcode == OP_BOOLAND) + return node_make(d, FRAG_AND_B, subs, 2, &item->node); + if (opcode == OP_BOOLOR) + return node_make(d, FRAG_OR_B, subs, 2, &item->node); + ret = node_make(d, FRAG_THRESH, subs, 2, &item->node); + item->kind = ITEM_THRESH; + item->last = subs[1]; + item->count = 2; + return ret; +} + +static int decode_opcode(ms_decoder *d, script_iter *si) +{ + static const uint32_t ifdup_notif[] = { OP_IFDUP, OP_NOTIF }; + int64_t v; + int ret; + + if (si_is_push(si) && !si_is_minimal_push(si)) + return WALLY_EINVAL; + if (si_is_push(si) || (si->opcode >= OP_1 && si->opcode <= OP_16)) { + if (si_get_number(si, &v)) + return decode_number(d, si, v); + if (si->data_len == d->key_len) + return decode_key(d, si); + return WALLY_EINVAL; + } + + switch (si->opcode) { + case OP_DUP: + return decode_dup(d, si); + case OP_SIZE: + return decode_size(d, si); + case OP_IF: + return scope_open(d, SCOPE_OR_I, NO_NODE, NO_NODE); + case OP_NOTIF: + return decode_notif(d, SCOPE_NOTIF); + case OP_IFDUP: + if (!si_match(si, ifdup_notif, NUM_ELEMS(ifdup_notif), NULL)) + return WALLY_EINVAL; + return decode_notif(d, SCOPE_OR_D); + case OP_ELSE: + return decode_else(d); + case OP_ENDIF: + return decode_endif(d); + case OP_TOALTSTACK: + return scope_open(d, SCOPE_A, NO_NODE, NO_NODE); + case OP_FROMALTSTACK: + return decode_fromaltstack(d); + case OP_SWAP: + return scope_open(d, SCOPE_S, NO_NODE, NO_NODE); + case OP_CHECKSIG: + return item_wrap(d, FRAG_C); + case OP_CHECKSIGVERIFY: + ret = item_wrap(d, FRAG_C); + return ret == WALLY_OK ? item_wrap(d, FRAG_V) : ret; + case OP_VERIFY: + return item_wrap(d, FRAG_V); + case OP_0NOTEQUAL: + return item_wrap(d, FRAG_N); + case OP_BOOLAND: + case OP_BOOLOR: + case OP_ADD: + return decode_combine(d, si->opcode); + } + return WALLY_EINVAL; +} + +static int decode_script(ms_decoder *d, uint32_t *root) +{ + script_iter si; + unsigned char prev_opcode = OP_INVALIDOPCODE; + int ret = scope_open(d, SCOPE_TOP, NO_NODE, NO_NODE); + + si_init(&si, d->script, d->script_len); + while (ret == WALLY_OK && si_next(&si)) { + if (si.opcode == OP_VERIFY && + (prev_opcode == OP_CHECKSIG || prev_opcode == OP_CHECKMULTISIG || + prev_opcode == OP_EQUAL || prev_opcode == OP_NUMEQUAL)) + ret = WALLY_EINVAL; /* Should use OP_CHECKSIGVERIFY etc */ + else + ret = decode_opcode(d, &si); + prev_opcode = si.opcode; + } + if (ret == WALLY_OK && (si_is_error(&si) || d->num_scopes != 1)) + ret = WALLY_EINVAL; /* Malformed script, or unterminated expression */ + if (ret == WALLY_OK) + ret = scope_close(d, root); + return ret; +} + +typedef struct ms_writer { + char *buf; /* Output buffer, or NULL to calculate the output length */ + size_t len; + size_t written; +} ms_writer; + +static void put(ms_writer *w, const char *str, size_t len) +{ + if (w->buf && w->written <= w->len && len <= w->len - w->written) + memcpy(w->buf + w->written, str, len); + w->written += len; +} + +static void put_hex(ms_writer *w, const unsigned char *bytes, size_t len) +{ + static const char hex[] = "0123456789abcdef"; + char c[2]; + size_t i; + + for (i = 0; i < len; ++i) { + c[0] = hex[bytes[i] >> 4]; + c[1] = hex[bytes[i] & 0xf]; + put(w, c, 2); + } +} + +static void put_number(ms_writer *w, uint32_t v) +{ + char buf[10]; + size_t i = sizeof(buf); + + do { + buf[--i] = '0' + v % 10; + v /= 10; + } while (v); + put(w, buf + i, sizeof(buf) - i); +} + +/* Write an expression, up to its first sub-expression (if it has any) */ +static void put_node(const ms_decoder *d, ms_writer *w, uint32_t index) +{ + const ms_dnode *node = d->nodes + index; + const char *name = g_frag_names[node->frag]; + const struct wally_map_item *key; + script_iter si; + + if (node->parent != NO_NODE && !IS_WRAPPER(node->frag) && + IS_WRAPPER(d->nodes[node->parent].frag)) + put(w, ":", 1); /* End of the wrappers */ + put(w, name, strlen(name)); + + switch (node->frag) { + case FRAG_JUST_0: + case FRAG_JUST_1: + return; + case FRAG_PK_K: + case FRAG_PK: + put(w, "(", 1); + put_hex(w, d->script + node->offset, d->key_len); + break; + case FRAG_PK_H: + case FRAG_PKH: + key = d->keys->items + node->value; + put(w, "(", 1); + put_hex(w, key->key, key->key_len); + break; + case FRAG_OLDER: + case FRAG_AFTER: + put(w, "(", 1); + put_number(w, node->value); + break; + case FRAG_SHA256: + case FRAG_HASH256: + put(w, "(", 1); + put_hex(w, d->script + node->offset, SHA256_LEN); + break; + case FRAG_RIPEMD160: + case FRAG_HASH160: + put(w, "(", 1); + put_hex(w, d->script + node->offset, HASH160_LEN); + break; + case FRAG_MULTI: + case FRAG_MULTI_A: + put(w, "(", 1); + put_number(w, node->value); + si_init(&si, d->script + node->offset, d->script_len - node->offset); + while (si_next(&si) && si.opcode == d->key_len) { + put(w, ",", 1); + put_hex(w, si.data, si.data_len); + if (node->frag == FRAG_MULTI_A) + si_next(&si); /* Skip OP_CHECKSIG/OP_CHECKSIGADD */ + } + break; + case FRAG_THRESH: + put(w, "(", 1); + put_number(w, node->value); + put(w, ",", 1); + return; + default: + if (!IS_WRAPPER(node->frag)) + put(w, "(", 1); + return; + } + put(w, ")", 1); +} + +/* Write an expression tree, returning the length of its text */ +static size_t put_tree(const ms_decoder *d, uint32_t root, char *buf, size_t len) +{ + ms_writer w = { buf, len, 0 }; + uint32_t node = root; + + for (;;) { + put_node(d, &w, node); + if (d->nodes[node].child != NO_NODE) { + node = d->nodes[node].child; + continue; + } + /* Close the expressions that end here */ + while (node != root && d->nodes[node].next == NO_NODE) { + node = d->nodes[node].parent; + if (!IS_WRAPPER(d->nodes[node].frag)) + put(&w, ")", 1); + } + if (node == root) + break; + put(&w, ",", 1); + node = d->nodes[node].next; + } + return w.written; +} + +int ms_script_to_miniscript(const unsigned char *script, size_t script_len, + const struct wally_map *keys, uint32_t flags, + char **output) +{ + const bool is_tapscript = flags & WALLY_MINISCRIPT_TAPSCRIPT; + const size_t max_len = is_tapscript ? MS_DECODE_MAX_SCRIPT_LEN_TAPSCRIPT : + MS_DECODE_MAX_SCRIPT_LEN_SEGWIT_V0; + ms_decoder d; + uint32_t root; + size_t len; + int ret; + + if (output) + *output = NULL; + if (!script || !script_len || script_len > max_len || + (flags & ~WALLY_MINISCRIPT_TAPSCRIPT) || !output) + return WALLY_EINVAL; + + memset(&d, 0, sizeof(d)); + d.script = script; + d.script_len = script_len; + d.key_len = is_tapscript ? EC_XONLY_PUBLIC_KEY_LEN : EC_PUBLIC_KEY_LEN; + d.is_tapscript = is_tapscript; + d.keys = keys; + + ret = decode_script(&d, &root); + if (ret == WALLY_OK) { + len = put_tree(&d, root, NULL, 0); + if (!(*output = wally_malloc(len + 1))) + ret = WALLY_ENOMEM; + else if (put_tree(&d, root, *output, len) != len) { + wally_free(*output); + *output = NULL; + ret = WALLY_ERROR; /* Should not happen */ + } else + (*output)[len] = '\0'; + } + if (d.nodes) + wally_free(d.nodes); + if (d.items) + wally_free(d.items); + if (d.scopes) + wally_free(d.scopes); + if (d.key_hashes) + wally_free(d.key_hashes); + return ret; +} + +int ms_descriptor_from_script(const unsigned char *script, size_t script_len, + const struct wally_map *keys, uint32_t flags, + struct wally_descriptor **output) +{ + /* The script already exists, so decode it even if it is not sane */ + const uint32_t parse_flags = WALLY_MINISCRIPT_ONLY | WALLY_MINISCRIPT_ALLOW_NON_SANE | + flags | (MS_DECODE_MAX_DEPTH << WALLY_MINISCRIPT_DEPTH_SHIFT); + unsigned char *generated = NULL; + char *text = NULL; + size_t written; + int ret; + + if (output) + *output = NULL; + if (!output) + return WALLY_EINVAL; + + ret = ms_script_to_miniscript(script, script_len, keys, flags, &text); + if (ret == WALLY_OK) { + ret = wally_descriptor_parse(text, NULL, WALLY_NETWORK_NONE, + parse_flags, output); + wally_free_string(text); + } + if (ret == WALLY_OK && + ((*output)->top_node->type_properties & TYPE_MASK) != TYPE_B) + ret = WALLY_EINVAL; /* Not a valid top level expression */ + if (ret == WALLY_OK && !(generated = wally_malloc(script_len))) + ret = WALLY_ENOMEM; + if (ret == WALLY_OK) + ret = wally_descriptor_to_script(*output, 0, 0, 0, 0, 0, 0, + generated, script_len, &written); + if (ret == WALLY_OK && + (written != script_len || memcmp(generated, script, script_len))) + ret = WALLY_EINVAL; /* Does not generate the decoded script */ + if (generated) + wally_free(generated); + if (ret != WALLY_OK) { + wally_descriptor_free(*output); + *output = NULL; + } + return ret; +} diff --git a/src/miniscript_decode.h b/src/miniscript_decode.h new file mode 100644 index 000000000..a969fbc24 --- /dev/null +++ b/src/miniscript_decode.h @@ -0,0 +1,78 @@ +#ifndef LIBWALLY_CORE_MINISCRIPT_DECODE_H +#define LIBWALLY_CORE_MINISCRIPT_DECODE_H 1 + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct wally_descriptor; +struct wally_map; + +/* Maximum script lengths accepted by the decoder, matching Bitcoin Core's + * MaxScriptSize(). Callers pass attacker-controlled PSBT scripts here, so + * anything larger is rejected before decoding. + * + * Segwit v0: the P2WSH standardness limit (MAX_STANDARD_P2WSH_SCRIPT_SIZE). + * + * Tapscript: leaf scripts have no explicit limit, so Core bounds them by what + * a maximum-standard-weight transaction can still spend with a maximum-sized + * witness, i.e. MAX_STANDARD_TX_WEIGHT (400000) + * - TX_BODY_LEEWAY_WEIGHT (378: version, locktime, 1 input, 1 P2WSH output, + * compact sizes, segwit marker, all x4, plus 2) + * - MAX_TAPSCRIPT_SAT_SIZE (70135: 1000 stack elements of 65 bytes with + * their compact sizes, plus a maximum 4129-byte control block) + * = 329487, less the 5-byte compact size of that length. */ +#define MS_DECODE_MAX_SCRIPT_LEN_SEGWIT_V0 3600 +#define MS_DECODE_MAX_SCRIPT_LEN_TAPSCRIPT 329482 + +/* Maximum nesting depth of a decoded expression, as limited by passing + * it to wally_descriptor_parse() (see WALLY_MINISCRIPT_DEPTH_SHIFT) */ +#define MS_DECODE_MAX_DEPTH 128 + +/* + * Decode a script into miniscript expression text. + * + * :param script: The segwit v0 witness script or tapscript leaf script. + * :param script_len: Length of ``script`` in bytes. + * :param keys: Public keys to resolve the key hashes of ``pk_h`` fragments + *| from, as the keys of a map, or NULL. Only keys of the size used by + *| the script context (33 bytes for segwit v0, 32 for tapscript) are used. + * :param flags: WALLY_MINISCRIPT_TAPSCRIPT to decode a tapscript, or 0. + * :param output: Destination for the resulting expression text. + *| The string returned should be freed using `wally_free_string`. + * + * The script is decoded as Bitcoin Core's miniscript DecodeScript() does, + * and printed as its ToString() would print the result. The expression is + * not type checked: use `ms_descriptor_from_script` to obtain a validated + * expression. + */ +int ms_script_to_miniscript(const unsigned char *script, size_t script_len, + const struct wally_map *keys, uint32_t flags, + char **output); + +/* + * Decode a script into a parsed miniscript expression. + * + * :param script: The segwit v0 witness script or tapscript leaf script. + * :param script_len: Length of ``script`` in bytes. + * :param keys: As for `ms_script_to_miniscript`. + * :param flags: As for `ms_script_to_miniscript`. + * :param output: Destination for the resulting parsed expression. + *| The descriptor returned should be freed using `wally_descriptor_free`. + * + * In addition to decoding the script, checks that the expression is a valid + * top level miniscript expression (i.e. of type B) and that it generates + * the given script. + */ +int ms_descriptor_from_script(const unsigned char *script, size_t script_len, + const struct wally_map *keys, uint32_t flags, + struct wally_descriptor **output); + +#ifdef __cplusplus +} +#endif + +#endif /* LIBWALLY_CORE_MINISCRIPT_DECODE_H */ From 64204988e4470f1c36e830ab30b01b0287c71b49 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Wed, 7 Oct 2026 09:34:16 -0300 Subject: [PATCH 4/9] miniscript: add miniscript satisfier Adds the witness satisfier (miniscript_satisfy.c): per-fragment satisfaction/dissatisfaction with non-malleable minimum-weight selection (satisfaction_best, or_b/c/d/i, andor, thresh with a DP sort) and a satisfy_node dispatch over a parsed miniscript expression, plus the ms_witness / ms_satisfaction structures and lifecycle helpers. Includes witness_weight overflow saturation, iterative tree traversal to bound stack usage, and the geometric-growth / move-not-copy / precomputed-weight optimizations. The node kinds are moved to descriptor_int.h. Co-authored-by: odudex --- docs/source/index.rst | 1 + docs/source/satisfier.rst | 67 ++ src/Makefile.am | 9 + src/amalgamation/combined.c | 1 + src/ctest/_CMakeLists.txt | 5 + src/ctest/test_miniscript_satisfy.c | 300 +++++++ src/descriptor.c | 58 -- src/descriptor_int.h | 59 ++ src/miniscript_satisfy.c | 1242 +++++++++++++++++++++++++++ src/miniscript_satisfy.h | 74 ++ 10 files changed, 1758 insertions(+), 58 deletions(-) create mode 100644 docs/source/satisfier.rst create mode 100644 src/ctest/test_miniscript_satisfy.c create mode 100644 src/miniscript_satisfy.c create mode 100644 src/miniscript_satisfy.h diff --git a/docs/source/index.rst b/docs/source/index.rst index 2348eb154..6e4f5c6c2 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -29,6 +29,7 @@ libwally-core documentation Library Conventions Liquid Anti Exfil Protocol + Miniscript Satisfier Indices and tables ================== diff --git a/docs/source/satisfier.rst b/docs/source/satisfier.rst new file mode 100644 index 000000000..5528de708 --- /dev/null +++ b/docs/source/satisfier.rst @@ -0,0 +1,67 @@ +Miniscript Satisfier +==================== + +These functions produce non-malleable (or optionally malleable) witness +stacks for a parsed miniscript expression, such as one decoded from a +script by ``ms_descriptor_from_script``. + +The satisfier mirrors `rust-miniscript `__'s +``Satisfaction::sat_dissat`` at commit ``1834bc06``. + +Satisfier Context +----------------- + +.. c:type:: ms_satisfier + + Asset provider passed to :c:func:`ms_satisfy_node`. All function + pointers may be ``NULL`` if the corresponding asset type is not + available. + + .. c:member:: bool (*lookup_sig)(...) + + Look up a signature for a public key. Called for ``pk_k``, + ``pk_h``, ``multi``, and ``multi_a`` fragments. The output buffer + holds ``EC_SIGNATURE_DER_MAX_LEN`` + 1 bytes (max-DER signature plus + sighash byte); callbacks must not write more. + + .. c:member:: bool (*lookup_preimage)(...) + + Look up a 32-byte hash preimage. ``hash_type`` is one of + ``MS_HASH_SHA256``, ``MS_HASH_HASH256``, ``MS_HASH_RIPEMD160``, + ``MS_HASH_HASH160``. + + .. c:member:: bool (*check_older)(...) + + Return ``true`` if the relative locktime ``lock`` is currently + satisfied (i.e. the UTXO is old enough). + + .. c:member:: bool (*check_after)(...) + + Return ``true`` if the absolute locktime ``lock`` is currently + satisfied. + + .. c:member:: void *user_data + + Opaque pointer passed back to each callback. + +Functions +--------- + +.. c:function:: void ms_satisfy_node(const ms_node *node, const ms_satisfier *stfr, bool malleable, ms_satisfaction *sat_out, ms_satisfaction *dissat_out) + + Compute both satisfaction and dissatisfaction for the miniscript + expression *node*. The keys of the expression must be public keys: + keys of other kinds are treated as having no signature available. + + The traversal is iterative (post-order), mirroring + ``rust-miniscript::Satisfaction::sat_dissat``. + + When *malleable* is ``false`` the returned satisfaction is + non-malleable: a third party cannot replace it with a strictly + lighter witness. When *malleable* is ``true`` the cheapest witness + is returned regardless of malleability. + + If an allocation fails, every result computed from the failed + allocation (including either output) is set to ``MS_WITNESS_OOM``, + rather than treating the affected sub-expression as impossible and + returning a different satisfaction. diff --git a/src/Makefile.am b/src/Makefile.am index 914a6ca36..f676581cc 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -160,6 +160,7 @@ libwallycore_la_SOURCES = \ internal.c \ map.c \ miniscript_decode.c \ + miniscript_satisfy.c \ mnemonic.c \ pbkdf2.c \ psbt.c \ @@ -312,6 +313,14 @@ test_miniscript_decode_LDADD = $(lib_LTLIBRARIES) @CTEST_EXTRA_STATIC@ if PYTHON_MANYLINUX test_miniscript_decode_LDADD += $(PYTHON_LIBS) endif +TESTS += test_miniscript_satisfy +noinst_PROGRAMS += test_miniscript_satisfy +test_miniscript_satisfy_SOURCES = ctest/test_miniscript_satisfy.c miniscript_satisfy.c miniscript_decode.c script_iter.c +test_miniscript_satisfy_CFLAGS = $(TESTS_CFLAGS) +test_miniscript_satisfy_LDADD = $(lib_LTLIBRARIES) @CTEST_EXTRA_STATIC@ +if PYTHON_MANYLINUX +test_miniscript_satisfy_LDADD += $(PYTHON_LIBS) +endif if BUILD_ELEMENTS TESTS += test_elements_tx noinst_PROGRAMS += test_elements_tx diff --git a/src/amalgamation/combined.c b/src/amalgamation/combined.c index 8554c7449..e956bc6d5 100644 --- a/src/amalgamation/combined.c +++ b/src/amalgamation/combined.c @@ -69,6 +69,7 @@ #include "src/hmac.c" #include "src/map.c" #include "src/miniscript_decode.c" +#include "src/miniscript_satisfy.c" #include "src/mnemonic.c" #include "src/pbkdf2.c" #include "src/pullpush.c" diff --git a/src/ctest/_CMakeLists.txt b/src/ctest/_CMakeLists.txt index c8b124006..5c36da4c7 100644 --- a/src/ctest/_CMakeLists.txt +++ b/src/ctest/_CMakeLists.txt @@ -27,6 +27,11 @@ target_include_directories(test_miniscript_decode PRIVATE ${CMAKE_BINARY_DIR} $< target_link_libraries(test_miniscript_decode PRIVATE wallycore) add_test(test_miniscript_decode test_miniscript_decode) +add_executable(test_miniscript_satisfy test_miniscript_satisfy.c ../miniscript_satisfy.c ../miniscript_decode.c ../script_iter.c) +target_include_directories(test_miniscript_satisfy PRIVATE ${CMAKE_BINARY_DIR} $ $) +target_link_libraries(test_miniscript_satisfy PRIVATE wallycore) +add_test(test_miniscript_satisfy test_miniscript_satisfy) + add_executable(test_elements_tx test_elements_tx.c) target_include_directories(test_elements_tx PRIVATE ${CMAKE_BINARY_DIR}) target_link_libraries(test_elements_tx PRIVATE wallycore) diff --git a/src/ctest/test_miniscript_satisfy.c b/src/ctest/test_miniscript_satisfy.c new file mode 100644 index 000000000..2b8dc3bc1 --- /dev/null +++ b/src/ctest/test_miniscript_satisfy.c @@ -0,0 +1,300 @@ +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "../miniscript_decode.h" +#include "../miniscript_satisfy.h" + +#define NUM_ELEMS(a) (sizeof(a) / sizeof(a[0])) +#define TAP WALLY_MINISCRIPT_TAPSCRIPT + +/* Compressed keys, and their x-only equivalents */ +#define K1 "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" +#define K2 "03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a" +#define K3 "025601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc" +#define K4 "03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556" +#define X1 "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" +#define X2 "d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a" +#define X3 "5601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc" +#define H32 "9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2" + +static const char *const g_keys[] = { K1, K2, K3, K4 }; +static unsigned char g_key_bytes[NUM_ELEMS(g_keys)][EC_PUBLIC_KEY_LEN]; + +#define SIG(n) (1u << ((n) - 1)) /* A signature is available for key n */ +#define NO_SATISFIER 0x80000000 /* Pass a NULL satisfier */ + +/* The assets available to satisfy an expression */ +typedef struct { + uint32_t sigs; + bool preimage; + uint32_t older; + uint32_t after; +} assets_t; + +/* Find a key from g_keys, returning its 1-based index or 0 if not found */ +static size_t key_index(const unsigned char *pk, size_t pk_len) +{ + const size_t offset = EC_PUBLIC_KEY_LEN - pk_len; + size_t i; + + for (i = 0; i < NUM_ELEMS(g_keys); ++i) + if (!memcmp(pk, g_key_bytes[i] + offset, pk_len)) + return i + 1; + return 0; +} + +/* A fake ECDSA (with sighash byte) or schnorr signature for key n */ +static size_t make_sig(size_t n, bool is_schnorr, unsigned char *sig) +{ + if (is_schnorr) { + memset(sig, (int)n, 64); + return 64; + } + sig[0] = 0x30; sig[1] = 0x44; + sig[2] = 0x02; sig[3] = 0x20; + memset(sig + 4, (int)n, 32); + sig[36] = 0x02; sig[37] = 0x20; + memset(sig + 38, (int)n, 32); + sig[70] = 0x01; + return 71; +} + +static bool lookup_sig(const ms_satisfier *stfr, + const unsigned char *pk, size_t pk_len, + unsigned char *sig_out, size_t *sig_len_out) +{ + const assets_t *assets = (const assets_t *)stfr->user_data; + const size_t n = key_index(pk, pk_len); + + if (!n || !(assets->sigs & SIG(n))) + return false; + *sig_len_out = make_sig(n, pk_len == EC_XONLY_PUBLIC_KEY_LEN, sig_out); + return true; +} + +static bool lookup_preimage(const ms_satisfier *stfr, + const unsigned char *hash, size_t hash_len, + uint32_t hash_type, unsigned char preimage_out[32]) +{ + const assets_t *assets = (const assets_t *)stfr->user_data; + (void)hash; + (void)hash_len; + (void)hash_type; + if (assets->preimage) + memset(preimage_out, 0x42, 32); + return assets->preimage; +} + +static bool check_older(const ms_satisfier *stfr, uint32_t lock) +{ + return lock <= ((const assets_t *)stfr->user_data)->older; +} + +static bool check_after(const ms_satisfier *stfr, uint32_t lock) +{ + return lock <= ((const assets_t *)stfr->user_data)->after; +} + +/* Check a witness against a description: "IMPOSSIBLE", "UNAVAILABLE", or + * its items separated by spaces: "-" (empty), "S" (key n's signature), + * "P" (key n), "H" (preimage), "Z" (32 zero bytes), or hex */ +static bool witness_is(const ms_satisfaction *s, const char *expected, bool is_tapscript) +{ + unsigned char item[128]; + char token[16]; + size_t i = 0, item_len, token_len; + const char *p = expected; + + if (!strcmp(expected, "IMPOSSIBLE")) + return s->witness.kind == MS_WITNESS_IMPOSSIBLE; + if (!strcmp(expected, "UNAVAILABLE")) + return s->witness.kind == MS_WITNESS_UNAVAILABLE; + if (s->witness.kind != MS_WITNESS_STACK) + return false; + + while (*p) { + token_len = strcspn(p, " "); + memcpy(token, p, token_len); + token[token_len] = '\0'; + p += token_len + (p[token_len] == ' '); + + if (!strcmp(token, "-")) + item_len = 0; + else if (token[0] == 'S') + item_len = make_sig(token[1] - '0', is_tapscript, item); + else if (token[0] == 'P') { + item_len = is_tapscript ? EC_XONLY_PUBLIC_KEY_LEN : EC_PUBLIC_KEY_LEN; + memcpy(item, g_key_bytes[token[1] - '1'] + EC_PUBLIC_KEY_LEN - item_len, item_len); + } else if (!strcmp(token, "H") || !strcmp(token, "Z")) { + item_len = 32; + memset(item, token[0] == 'H' ? 0x42 : 0, item_len); + } else if (wally_hex_to_bytes(token, item, sizeof(item), &item_len) != WALLY_OK) + return false; + + if (i >= s->witness.num_items || s->witness.items[i].data_len != item_len || + (item_len && memcmp(s->witness.items[i].data, item, item_len))) + return false; + ++i; + } + return i == s->witness.num_items; +} + +static bool test_satisfy(void) +{ + static const struct { + const char *miniscript; + uint32_t flags; + uint32_t sigs; /* SIG(n) for each available signature, or NO_SATISFIER */ + bool preimage; + uint32_t older, after; + bool malleable; + const char *sat, *dissat; + uint32_t sat_older, sat_after; /* Timelocks of the satisfaction */ + } cases[] = { + /* multi: a dummy item, then the signatures */ + { "multi(2," K1 "," K2 "," K3 ")", 0, SIG(1) | SIG(2) | SIG(3), false, 0, 0, false, + "- S1 S2", "- - -", 0, 0 }, + { "multi(2," K1 "," K2 "," K3 ")", 0, SIG(1), false, 0, 0, false, + "IMPOSSIBLE", "- - -", 0, 0 }, + { "multi(2," K1 "," K2 "," K3 ")", 0, NO_SATISFIER, false, 0, 0, false, + "IMPOSSIBLE", "- - -", 0, 0 }, + { "multi(1," K1 ")", 0, SIG(1), false, 0, 0, false, "- S1", "- -", 0, 0 }, + /* multi_a: an item for each key, in reverse order */ + { "multi_a(2," X1 "," X2 "," X3 ")", TAP, SIG(1) | SIG(2) | SIG(3), false, 0, 0, false, + "- S2 S1", "- - -", 0, 0 }, + { "multi_a(2," X1 "," X2 "," X3 ")", TAP, SIG(2), false, 0, 0, false, + "IMPOSSIBLE", "- - -", 0, 0 }, + { "multi_a(2," X1 "," X2 "," X3 ")", TAP, NO_SATISFIER, false, 0, 0, false, + "IMPOSSIBLE", "- - -", 0, 0 }, + { "multi_a(1," X1 ")", TAP, SIG(1), false, 0, 0, false, "S1", "-", 0, 0 }, + /* Timelocks */ + { "older(100)", 0, 0, false, 100, 0, false, "", "IMPOSSIBLE", 100, 0 }, + { "older(100)", 0, 0, false, 0, 0, false, "UNAVAILABLE", "IMPOSSIBLE", 0, 0 }, + { "older(100)", 0, NO_SATISFIER, false, 0, 0, false, "UNAVAILABLE", "IMPOSSIBLE", 0, 0 }, + { "after(500)", 0, 0, false, 0, 500, false, "", "IMPOSSIBLE", 0, 500 }, + { "after(500)", 0, 0, false, 0, 0, false, "UNAVAILABLE", "IMPOSSIBLE", 0, 0 }, + { "and_v(v:older(100),older(200))", 0, 0, false, 200, 0, false, "", "IMPOSSIBLE", 200, 0 }, + { "and_v(v:older(100),after(500))", 0, 0, false, 100, 500, false, "", "IMPOSSIBLE", 100, 500 }, + /* Keys */ + { "pk(" K1 ")", 0, SIG(1), false, 0, 0, false, "S1", "-", 0, 0 }, + { "pk(" K1 ")", 0, 0, false, 0, 0, false, "IMPOSSIBLE", "-", 0, 0 }, + { "pk(" X1 ")", TAP, SIG(1), false, 0, 0, false, "S1", "-", 0, 0 }, + { "pkh(" K1 ")", 0, SIG(1), false, 0, 0, false, "S1 P1", "- P1", 0, 0 }, + { "pkh(" K1 ")", 0, 0, false, 0, 0, false, "IMPOSSIBLE", "- P1", 0, 0 }, + { "pkh(" X1 ")", TAP, SIG(1), false, 0, 0, false, "S1 P1", "- P1", 0, 0 }, + /* Hashes */ + { "sha256(" H32 ")", 0, 0, true, 0, 0, false, "H", "Z", 0, 0 }, + { "sha256(" H32 ")", 0, 0, false, 0, 0, false, "UNAVAILABLE", "Z", 0, 0 }, + /* or_b(X,Z): [X] [Z] BOOLOR */ + { "or_b(dv:older(100),s:pk(" K1 "))", 0, 0, false, 100, 0, false, "- 01", "- -", 100, 0 }, + { "or_b(dv:older(100),s:pk(" K1 "))", 0, 0, false, 0, 0, false, "UNAVAILABLE", "- -", 0, 0 }, + { "or_b(dv:older(100),s:pk(" K1 "))", 0, NO_SATISFIER, false, 0, 0, false, "UNAVAILABLE", "- -", 0, 0 }, + /* or_c(X,Z): [X] NOTIF [Z] ENDIF */ + { "t:or_c(ndv:older(100),v:pk(" K2 "))", 0, 0, false, 100, 0, false, "01", "IMPOSSIBLE", 100, 0 }, + { "t:or_c(ndv:older(100),v:pk(" K2 "))", 0, 0, false, 0, 0, false, "UNAVAILABLE", "IMPOSSIBLE", 0, 0 }, + { "t:or_c(ndv:older(100),v:pk(" K2 "))", 0, NO_SATISFIER, false, 0, 0, false, "UNAVAILABLE", "IMPOSSIBLE", 0, 0 }, + /* or_d(X,Z): [X] IFDUP NOTIF [Z] ENDIF */ + { "or_d(ndv:older(100),pk(" K3 "))", 0, 0, false, 100, 0, false, "01", "- -", 100, 0 }, + { "or_d(ndv:older(100),pk(" K3 "))", 0, 0, false, 0, 0, false, "UNAVAILABLE", "- -", 0, 0 }, + { "or_d(ndv:older(100),pk(" K3 "))", 0, NO_SATISFIER, false, 0, 0, false, "UNAVAILABLE", "- -", 0, 0 }, + { "or_d(pk(" K1 "),j:pk(" K2 "))", 0, SIG(2), false, 0, 0, false, "S2 -", "- -", 0, 0 }, + /* or_i(X,Z): IF [X] ELSE [Z] ENDIF */ + { "or_i(older(100),pk(" K4 "))", 0, 0, false, 100, 0, false, "01", "- -", 100, 0 }, + { "or_i(older(100),pk(" K4 "))", 0, 0, false, 0, 0, false, "UNAVAILABLE", "- -", 0, 0 }, + { "or_i(older(100),pk(" K4 "))", 0, NO_SATISFIER, false, 0, 0, false, "UNAVAILABLE", "- -", 0, 0 }, + { "u:pk(" K1 ")", 0, SIG(1), false, 0, 0, false, "S1 01", "-", 0, 0 }, + { "l:pk(" K1 ")", 0, SIG(1), false, 0, 0, false, "S1 -", NULL, 0, 0 }, + /* andor(X,Y,Z): [X] NOTIF [Z] ELSE [Y] ENDIF */ + { "andor(pk(" K1 "),pk(" K2 "),pk(" K3 "))", 0, SIG(1) | SIG(2), false, 0, 0, false, "S2 S1", "- -", 0, 0 }, + { "andor(pk(" K1 "),pk(" K2 "),pk(" K3 "))", 0, SIG(1), false, 0, 0, false, "IMPOSSIBLE", "- -", 0, 0 }, + { "andor(pk(" K1 "),pk(" K2 "),pk(" K3 "))", 0, SIG(3), false, 0, 0, false, "S3 -", "- -", 0, 0 }, + { "andor(pk(" K1 "),1,pk(" K2 "))", 0, SIG(1), false, 0, 0, false, "S1", "- -", 0, 0 }, + { "and_n(pk(" K1 "),pk(" K2 "))", 0, SIG(1) | SIG(2), false, 0, 0, false, "S2 S1", "-", 0, 0 }, + /* and_v(X,Y): [X] [Y], and_b(X,Y): [X] [Y] BOOLAND */ + { "and_v(v:pk(" K1 "),pk(" K2 "))", 0, SIG(1) | SIG(2), false, 0, 0, false, "S2 S1", "- S1", 0, 0 }, + { "tv:pk(" K1 ")", 0, SIG(1), false, 0, 0, false, "S1", "IMPOSSIBLE", 0, 0 }, + { "and_b(pk(" K1 "),a:pk(" K2 "))", 0, SIG(1) | SIG(2), false, 0, 0, false, "S2 S1", "- -", 0, 0 }, + /* thresh(k,X1,...,Xn): [X1] [X2] ADD ... [Xn] ADD EQUAL */ + { "thresh(2,ndv:older(100),s:pk(" K1 "))", 0, SIG(1), false, 100, 0, false, "S1 01", "- -", 100, 0 }, + { "thresh(2,ndv:older(100),s:pk(" K1 "))", 0, SIG(1), false, 0, 0, false, "UNAVAILABLE", NULL, 0, 0 }, + { "thresh(2,ndv:older(100),s:pk(" K1 "))", 0, 0, false, 100, 0, false, "IMPOSSIBLE", NULL, 0, 0 }, + { "thresh(2,ndv:older(100),s:pk(" K1 "))", 0, NO_SATISFIER, false, 0, 0, false, "IMPOSSIBLE", NULL, 0, 0 }, + { "thresh(3,ndv:older(100),s:pk(" K1 "),s:pk(" K2 "))", 0, SIG(1) | SIG(2), false, 100, 0, false, + "S2 S1 01", "- - -", 100, 0 }, + { "thresh(3,ndv:older(100),s:pk(" K1 "),s:pk(" K2 "))", 0, SIG(1), false, 100, 0, false, + "IMPOSSIBLE", NULL, 0, 0 }, + { "thresh(3,ndv:older(100),s:pk(" K1 "),s:pk(" K2 "))", 0, SIG(1) | SIG(2), false, 100, 0, true, + "S2 S1 01", "- - -", 100, 0 }, + }; + struct wally_map keys; + unsigned char script[1024]; + size_t i, written; + bool ok = true; + + wally_map_init(NUM_ELEMS(g_keys) * 2, NULL, &keys); + for (i = 0; i < NUM_ELEMS(g_keys); ++i) { + wally_hex_to_bytes(g_keys[i], g_key_bytes[i], EC_PUBLIC_KEY_LEN, &written); + wally_map_add(&keys, g_key_bytes[i], EC_PUBLIC_KEY_LEN, NULL, 0); + wally_map_add(&keys, g_key_bytes[i] + 1, EC_XONLY_PUBLIC_KEY_LEN, NULL, 0); + } + + for (i = 0; i < NUM_ELEMS(cases); ++i) { + const char *ms = cases[i].miniscript; + const bool is_tapscript = cases[i].flags & TAP; + assets_t assets = { cases[i].sigs, cases[i].preimage, cases[i].older, cases[i].after }; + ms_satisfier stfr = { lookup_sig, lookup_preimage, check_older, check_after, &assets }; + struct wally_descriptor *d; + ms_satisfaction sat, dissat; + int ret; + + /* Generate the script, then decode it. Many test vectors are + * not sane, e.g. timelock-only scripts */ + ret = wally_descriptor_parse(ms, NULL, WALLY_NETWORK_NONE, + WALLY_MINISCRIPT_ONLY | WALLY_MINISCRIPT_ALLOW_NON_SANE | + cases[i].flags, &d); + if (ret == WALLY_OK) { + ret = wally_descriptor_to_script(d, 0, 0, 0, 0, 0, 0, + script, sizeof(script), &written); + wally_descriptor_free(d); + } + if (ret == WALLY_OK) + ret = ms_descriptor_from_script(script, written, &keys, cases[i].flags, &d); + if (ret != WALLY_OK) { + printf("FAIL: decode %s\n", ms); + ok = false; + continue; + } + + ms_satisfy_node(d->top_node, cases[i].sigs == NO_SATISFIER ? NULL : &stfr, + cases[i].malleable, &sat, &dissat); + if (!witness_is(&sat, cases[i].sat, is_tapscript) || + (sat.witness.kind == MS_WITNESS_STACK && + (sat.has_sig != !!strchr(cases[i].sat, 'S') || + sat.relative_timelock != cases[i].sat_older || + sat.absolute_timelock != cases[i].sat_after))) { + printf("FAIL: satisfaction %s (sigs %x)\n", ms, cases[i].sigs); + ok = false; + } + if (cases[i].dissat && !witness_is(&dissat, cases[i].dissat, is_tapscript)) { + printf("FAIL: dissatisfaction %s (sigs %x)\n", ms, cases[i].sigs); + ok = false; + } + ms_satisfaction_free(&sat); + ms_satisfaction_free(&dissat); + wally_descriptor_free(d); + } + wally_map_clear(&keys); + return ok; +} + +int main(void) +{ + return test_satisfy() ? 0 : 1; +} diff --git a/src/descriptor.c b/src/descriptor.c index f82475123..610893be7 100644 --- a/src/descriptor.c +++ b/src/descriptor.c @@ -34,23 +34,6 @@ /* OP_1 properties: Bzufmxk */ #define PROP_OP_1 (TYPE_B | PROP_Z | PROP_U | PROP_F | PROP_M | PROP_X | PROP_K) -#define KIND_MINISCRIPT 0x01 -#define KIND_DESCRIPTOR 0x02 /* Output Descriptor */ -#define KIND_RAW 0x04 -#define KIND_NUMBER 0x08 -#define KIND_ADDRESS 0x10 -#define KIND_KEY 0x20 -#define KIND_BRANCH 0x40 /* Taptree branch */ - -#define KIND_BASE58 (0x0100 | KIND_ADDRESS) -#define KIND_BECH32 (0x0200 | KIND_ADDRESS) - -#define KIND_PUBLIC_KEY (0x001000 | KIND_KEY) -#define KIND_PRIVATE_KEY (0x002000 | KIND_KEY) -#define KIND_BIP32 (0x004000 | KIND_KEY) -#define KIND_BIP32_PRIVATE_KEY (0x010000 | KIND_BIP32) -#define KIND_BIP32_PUBLIC_KEY (0x020000 | KIND_BIP32) - #define DESCRIPTOR_MIN_SIZE 20 #define MINISCRIPT_MULTI_MAX 20 #define MULTI_A_NUM_KEYS_MAX 999 /* BIP-342: stack limited to 1000 elements, one used by the threshold */ @@ -61,47 +44,6 @@ #define DESCRIPTOR_LOCKTIME_THRESHOLD 500000000 #define DESCRIPTOR_CHECKSUM_LENGTH 8 -/* output descriptor */ -#define KIND_DESCRIPTOR_PK (0x00000100 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_PKH (0x00000200 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_MULTI (0x00000300 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_MULTI_S (0x00000400 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_SH (0x00000500 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_WPKH (0x00010000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_WSH (0x00020000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_COMBO (0x00030000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_ADDR (0x00040000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_RAW (0x00050000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_RAW_TR (0x00100000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_TR (0x00200000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_CT (0x00300000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_SLIP77 (0x00400000 | KIND_DESCRIPTOR) -#define KIND_DESCRIPTOR_ELIP151 (0x00500000 | KIND_DESCRIPTOR) - -/* miniscript */ -#define KIND_MINISCRIPT_PK (0x00000100 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_PKH (0x00000200 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_MULTI (0x00000300 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_PK_K (0x00001000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_PK_H (0x00002000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_OLDER (0x00010000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_AFTER (0x00020000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_SHA256 (0x00030000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_HASH256 (0x00040000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_RIPEMD160 (0x00050000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_HASH160 (0x00060000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_THRESH (0x00070000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_ANDOR (0x01000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_AND_V (0x02000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_AND_B (0x03000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_AND_N (0x04000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_OR_B (0x05000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_OR_C (0x06000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_OR_D (0x07000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_OR_I (0x08000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_MULTI_A (0x09000000 | KIND_MINISCRIPT) -#define KIND_MINISCRIPT_MULTI_A_S (0x0A000000 | KIND_MINISCRIPT) - struct addr_ver_t { const unsigned char network; const unsigned char version_p2pkh; diff --git a/src/descriptor_int.h b/src/descriptor_int.h index 3c7513f15..7d1014bf6 100644 --- a/src/descriptor_int.h +++ b/src/descriptor_int.h @@ -30,6 +30,65 @@ #define PROP_J 0x00200000 /* Absolute time heightlock */ #define PROP_K 0x00400000 /* No timelock mixing allowed */ +/* Node kinds */ +#define KIND_MINISCRIPT 0x01 +#define KIND_DESCRIPTOR 0x02 /* Output Descriptor */ +#define KIND_RAW 0x04 +#define KIND_NUMBER 0x08 +#define KIND_ADDRESS 0x10 +#define KIND_KEY 0x20 +#define KIND_BRANCH 0x40 /* Taptree branch */ + +#define KIND_BASE58 (0x0100 | KIND_ADDRESS) +#define KIND_BECH32 (0x0200 | KIND_ADDRESS) + +#define KIND_PUBLIC_KEY (0x001000 | KIND_KEY) +#define KIND_PRIVATE_KEY (0x002000 | KIND_KEY) +#define KIND_BIP32 (0x004000 | KIND_KEY) +#define KIND_BIP32_PRIVATE_KEY (0x010000 | KIND_BIP32) +#define KIND_BIP32_PUBLIC_KEY (0x020000 | KIND_BIP32) + +/* output descriptor */ +#define KIND_DESCRIPTOR_PK (0x00000100 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_PKH (0x00000200 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_MULTI (0x00000300 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_MULTI_S (0x00000400 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_SH (0x00000500 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_WPKH (0x00010000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_WSH (0x00020000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_COMBO (0x00030000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_ADDR (0x00040000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_RAW (0x00050000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_RAW_TR (0x00100000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_TR (0x00200000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_CT (0x00300000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_SLIP77 (0x00400000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_ELIP151 (0x00500000 | KIND_DESCRIPTOR) + +/* miniscript */ +#define KIND_MINISCRIPT_PK (0x00000100 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_PKH (0x00000200 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_MULTI (0x00000300 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_PK_K (0x00001000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_PK_H (0x00002000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_OLDER (0x00010000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_AFTER (0x00020000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_SHA256 (0x00030000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_HASH256 (0x00040000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_RIPEMD160 (0x00050000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_HASH160 (0x00060000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_THRESH (0x00070000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_ANDOR (0x01000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_AND_V (0x02000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_AND_B (0x03000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_AND_N (0x04000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_OR_B (0x05000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_OR_C (0x06000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_OR_D (0x07000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_OR_I (0x08000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_MULTI_A (0x09000000 | KIND_MINISCRIPT) +#define KIND_MINISCRIPT_MULTI_A_S (0x0A000000 | KIND_MINISCRIPT) + /* A node in a parsed miniscript expression */ typedef struct ms_node_t { struct ms_node_t *next; diff --git a/src/miniscript_satisfy.c b/src/miniscript_satisfy.c new file mode 100644 index 000000000..6183ad41d --- /dev/null +++ b/src/miniscript_satisfy.c @@ -0,0 +1,1242 @@ +#include "config.h" +#include "internal.h" +#include "miniscript_satisfy.h" +#include +#include + +/* Witness item constants: a single 0x01 byte (true/IF branch selector) + * and a 32-byte all-zero value (hash dissatisfaction). */ +static const unsigned char push_1[] = {0x01}; +static const unsigned char zero32[32] = {0}; + +/* Securely clear memory that may hold signatures, preimages or keys. + * Uses the public wally_bzero (a non-elidable clear) rather than the + * internal wally_clear so that this file can also be compiled into + * test binaries that only link the public API. */ +static void ms_clear(void *p, size_t len) +{ + if (p) + wally_bzero(p, len); +} + +static void ms_witness_init(ms_witness *w, uint32_t kind) +{ + memset(w, 0, sizeof(*w)); + w->kind = kind; +} + +static void ms_witness_free(ms_witness *w) +{ + if (w) { + for (size_t i = 0; i < w->num_items; i++) { + /* Witness data can hold signatures/preimages: clear before freeing */ + ms_clear(w->items[i].data, w->items[i].data_len); + wally_free(w->items[i].data); + } + wally_free(w->items); + ms_clear(w, sizeof(*w)); + } +} + +static void ms_satisfaction_init(ms_satisfaction *s, uint32_t witness_kind) +{ + ms_witness_init(&s->witness, witness_kind); + s->has_sig = false; + s->absolute_timelock = 0; + s->relative_timelock = 0; +} + +void ms_satisfaction_free(ms_satisfaction *s) +{ + if (s) { + ms_witness_free(&s->witness); + ms_clear(s, sizeof(*s)); + } +} + +/* Whether a satisfaction failed to allocate, and so has no result. Results + * computed from it must also fail, rather than e.g. treating it as impossible + * and choosing a different (valid, but not the best) satisfaction instead. */ +#define IS_OOM(s) ((s).witness.kind == MS_WITNESS_OOM) + +/* Free a and b, returning an allocation failure. Consumes a and b. */ +static ms_satisfaction satisfaction_oom(ms_satisfaction *a, ms_satisfaction *b) +{ + ms_satisfaction result; + ms_satisfaction_free(a); + ms_satisfaction_free(b); + ms_satisfaction_init(&result, MS_WITNESS_OOM); + return result; +} + +static size_t witness_weight(const ms_witness *w) +{ + if (w->kind != MS_WITNESS_STACK) + return SIZE_MAX; + size_t total = 0; + for (size_t i = 0; i < w->num_items; i++) { + size_t item = w->items[i].data_len; + /* Saturate at SIZE_MAX-1 so SIZE_MAX stays the non-stack sentinel. */ + if (item >= SIZE_MAX - 1 || total >= SIZE_MAX - 1 - item) + return SIZE_MAX - 1; + total += item + 1; + } + return total; +} + +/* Weight delta (sat - dissat) for sorting thresh candidates. + * Returns INT64_MAX when sat is unavailable/impossible (avoid choosing). + * Returns INT64_MIN when dissat is unavailable/impossible (prefer choosing). */ +static int64_t thresh_weight_delta(const ms_satisfaction *sat, const ms_satisfaction *dsat) +{ + if (sat->witness.kind == MS_WITNESS_IMPOSSIBLE || + sat->witness.kind == MS_WITNESS_UNAVAILABLE) + return INT64_MAX; + if (dsat->witness.kind == MS_WITNESS_IMPOSSIBLE || + dsat->witness.kind == MS_WITNESS_UNAVAILABLE) + return INT64_MIN; + return (int64_t)witness_weight(&sat->witness) - + (int64_t)witness_weight(&dsat->witness); +} + +/* Precomputed sort key for a single thresh element. The key depends only on + * the element, so it can be computed once instead of in the O(n^2) sort. */ +struct thresh_key { + int imp; /* sat is impossible (sorts last) */ + int has_sig; /* sat carries a signature (sorts after sig-less) */ + int64_t delta; /* weight(sat) - weight(dissat) */ +}; + +static struct thresh_key thresh_make_key(const ms_satisfaction *sat, + const ms_satisfaction *dissat) +{ + struct thresh_key k; + k.imp = sat->witness.kind == MS_WITNESS_IMPOSSIBLE ? 1 : 0; + k.has_sig = sat->has_sig ? 1 : 0; + k.delta = thresh_weight_delta(sat, dissat); + return k; +} + +/* Non-malleable order: (is_impossible, has_sig, weight_delta) ascending */ +static int thresh_cmp_full(const struct thresh_key *a, const struct thresh_key *b) +{ + if (a->imp != b->imp) return a->imp - b->imp; + if (a->has_sig != b->has_sig) return a->has_sig - b->has_sig; + return (a->delta > b->delta) - (a->delta < b->delta); +} + +/* Malleable order: weight_delta only */ +static int thresh_cmp_mall(const struct thresh_key *a, const struct thresh_key *b) +{ + return (a->delta > b->delta) - (a->delta < b->delta); +} + +/* Insertion sort on index array (ascending). + * + * Each element's sort key is computed once up front (O(n) weight passes) + * rather than re-derived for every comparison (O(n^2) weight passes). On OOM + * the key array is left NULL and the keys are computed on demand instead. */ +static void thresh_sort(size_t *indices, size_t n, + const ms_satisfaction *sats, + const ms_satisfaction *dissats, int mall) +{ + struct thresh_key *keys = n ? wally_malloc(n * sizeof(*keys)) : NULL; + + for (size_t i = 0; keys && i < n; i++) + keys[i] = thresh_make_key(&sats[i], &dissats[i]); + + for (size_t i = 1; i < n; i++) { + size_t key = indices[i]; + size_t j = i; + while (j > 0) { + struct thresh_key ka, kb; + const struct thresh_key *pa, *pb; + if (keys) { + pa = &keys[indices[j - 1]]; + pb = &keys[key]; + } else { + ka = thresh_make_key(&sats[indices[j - 1]], &dissats[indices[j - 1]]); + kb = thresh_make_key(&sats[key], &dissats[key]); + pa = &ka; + pb = &kb; + } + if ((mall ? thresh_cmp_mall(pa, pb) : thresh_cmp_full(pa, pb)) <= 0) + break; + indices[j] = indices[j - 1]; + j--; + } + indices[j] = key; + } + wally_free(keys); +} + +/* + * Select the non-malleable minimum-weight satisfaction between a and b. + * Both a and b are consumed by this call; the caller must not use them + * afterwards. The caller owns the returned ms_satisfaction and must free + * it with ms_satisfaction_free() when done. + */ +static ms_satisfaction satisfaction_best(ms_satisfaction a, ms_satisfaction b) +{ + ms_satisfaction result; + + if (IS_OOM(a) || IS_OOM(b)) + return satisfaction_oom(&a, &b); + + /* Impossible short-circuits: if one side is impossible, take the other */ + if (a.witness.kind == MS_WITNESS_IMPOSSIBLE) + return b; + if (b.witness.kind == MS_WITNESS_IMPOSSIBLE) + return a; + + /* Neither has a sig: malleability vector, return unavailable */ + if (!a.has_sig && !b.has_sig) { + ms_satisfaction_free(&a); + ms_satisfaction_free(&b); + ms_satisfaction_init(&result, MS_WITNESS_UNAVAILABLE); + return result; + } + + /* Only b has a sig: third party can't malleate a (no sig to remove) */ + if (!a.has_sig) { + ms_satisfaction_free(&b); + return a; + } + + /* Only a has a sig: take b */ + if (!b.has_sig) { + ms_satisfaction_free(&a); + return b; + } + + /* Both have sigs: choose the lighter witness */ + if (witness_weight(&a.witness) <= witness_weight(&b.witness)) { + ms_satisfaction_free(&b); + return a; + } + ms_satisfaction_free(&a); + return b; +} + +/* Clone a satisfaction, deep-copying witness item data. On OOM returns OOM. */ +static ms_satisfaction ms_satisfaction_clone(const ms_satisfaction *src) +{ + ms_satisfaction result; + ms_satisfaction_init(&result, src->witness.kind); + result.has_sig = src->has_sig; + result.absolute_timelock = src->absolute_timelock; + result.relative_timelock = src->relative_timelock; + + if (src->witness.kind != MS_WITNESS_STACK || !src->witness.num_items) + return result; + + result.witness.items = wally_malloc(src->witness.num_items * sizeof(ms_witness_item)); + if (!result.witness.items) { + result.witness.kind = MS_WITNESS_OOM; + return result; + } + result.witness.items_allocation_len = src->witness.num_items; + + for (size_t i = 0; i < src->witness.num_items; i++) { + const ms_witness_item *si = &src->witness.items[i]; + unsigned char *data = NULL; + if (si->data_len) { + data = wally_malloc(si->data_len); + if (!data) { + ms_satisfaction_free(&result); + ms_satisfaction_init(&result, MS_WITNESS_OOM); + return result; + } + memcpy(data, si->data, si->data_len); + } + result.witness.items[i].data = data; + result.witness.items[i].data_len = si->data_len; + result.witness.num_items++; + } + return result; +} + +/* + * Concatenate two satisfactions: result has a's items followed by b's items. + * Consumes a and b. On OOM returns OOM. + * + * Mirrors rust-miniscript Witness::combine(b.stack, a.stack) called as + * a.concatenate_rev(b) - the caller must pass args in (right, left) order + * when building a witness where right-fragment items precede left-fragment + * items (the common case for binary fragments). + */ +static ms_satisfaction satisfaction_concat(ms_satisfaction a, ms_satisfaction b) +{ + bool b_has_sig; + uint32_t b_abs, b_rel; + size_t new_count; + ms_witness_item *new_items; + + if (IS_OOM(a) || IS_OOM(b)) + return satisfaction_oom(&a, &b); + if (a.witness.kind == MS_WITNESS_IMPOSSIBLE) { + ms_satisfaction_free(&b); + return a; + } + if (b.witness.kind == MS_WITNESS_IMPOSSIBLE) { + ms_satisfaction_free(&a); + return b; + } + if (a.witness.kind == MS_WITNESS_UNAVAILABLE) { + ms_satisfaction_free(&b); + return a; + } + if (b.witness.kind == MS_WITNESS_UNAVAILABLE) { + ms_satisfaction_free(&a); + return b; + } + + /* Save b's scalar fields before it is freed */ + b_has_sig = b.has_sig; + b_abs = b.absolute_timelock; + b_rel = b.relative_timelock; + + new_count = a.witness.num_items + b.witness.num_items; + + if (new_count > a.witness.items_allocation_len) { + new_items = wally_malloc(new_count * sizeof(ms_witness_item)); + if (!new_items) + return satisfaction_oom(&a, &b); + if (a.witness.num_items) + memcpy(new_items, a.witness.items, a.witness.num_items * sizeof(ms_witness_item)); + wally_free(a.witness.items); + a.witness.items = new_items; + a.witness.items_allocation_len = new_count; + } + + /* Transfer ownership of b's item data pointers into a */ + for (size_t i = 0; i < b.witness.num_items; i++) + a.witness.items[a.witness.num_items + i] = b.witness.items[i]; + a.witness.num_items = new_count; + + /* Prevent double-free: item data is now owned by a */ + b.witness.num_items = 0; + ms_satisfaction_free(&b); + + a.has_sig |= b_has_sig; + if (b_abs > a.absolute_timelock) + a.absolute_timelock = b_abs; + if (b_rel > a.relative_timelock) + a.relative_timelock = b_rel; + + return a; +} + +/* + * Malleable minimum: pick the cheaper satisfaction without enforcing + * non-malleability. Consumes a and b. + * + * Mirrors rust-miniscript Satisfaction::minimum_mall. + */ +static ms_satisfaction satisfaction_minimum_mall(ms_satisfaction a, ms_satisfaction b) +{ + bool has_sig; + + if (IS_OOM(a) || IS_OOM(b)) + return satisfaction_oom(&a, &b); + if (a.witness.kind == MS_WITNESS_IMPOSSIBLE || a.witness.kind == MS_WITNESS_UNAVAILABLE) { + ms_satisfaction_free(&a); + return b; + } + if (b.witness.kind == MS_WITNESS_IMPOSSIBLE || b.witness.kind == MS_WITNESS_UNAVAILABLE) { + ms_satisfaction_free(&b); + return a; + } + + /* Both are stacks: take the lighter; has_sig only if both carry a sig */ + has_sig = a.has_sig && b.has_sig; + + if (witness_weight(&a.witness) <= witness_weight(&b.witness)) { + ms_satisfaction_free(&b); + a.has_sig = has_sig; + return a; + } + ms_satisfaction_free(&a); + b.has_sig = has_sig; + return b; +} + +/* + * Append a single push item to a satisfaction's witness stack, taking + * ownership of `data` (no copy). data == NULL / data_len == 0 pushes an + * empty item. Consumes s and `data`; on OOM frees `data` and returns OOM. + */ +static ms_satisfaction satisfaction_push_item_take(ms_satisfaction s, + unsigned char *data, + size_t data_len) +{ + size_t n; + ms_witness_item *new_items; + + if (s.witness.kind != MS_WITNESS_STACK) { + ms_clear(data, data_len); + wally_free(data); + return s; + } + + n = s.witness.num_items; + + if (n + 1 > s.witness.items_allocation_len) { + /* Grow geometrically: building a k-item stack via repeated pushes + * is then amortized O(k) rather than O(k^2) reallocations. */ + size_t new_cap = s.witness.items_allocation_len ? + s.witness.items_allocation_len * 2 : 4; + new_items = wally_malloc(new_cap * sizeof(ms_witness_item)); + if (!new_items) { + ms_clear(data, data_len); + wally_free(data); + ms_satisfaction_free(&s); + ms_satisfaction_init(&s, MS_WITNESS_OOM); + return s; + } + if (n) + memcpy(new_items, s.witness.items, n * sizeof(ms_witness_item)); + wally_free(s.witness.items); + s.witness.items = new_items; + s.witness.items_allocation_len = new_cap; + } + + s.witness.items[n].data = data; + s.witness.items[n].data_len = data_len; + s.witness.num_items = n + 1; + return s; +} + +/* + * Append a single push item to a satisfaction's witness stack, copying + * `data`. data == NULL / data_len == 0 pushes an empty item (OP_0 / false). + * Consumes s; on OOM returns OOM. + * + * Used by satisfaction_or_i to attach the IF/ELSE branch selector byte. + */ +static ms_satisfaction satisfaction_push_item(ms_satisfaction s, + const unsigned char *data, + size_t data_len) +{ + unsigned char *item_data = NULL; + + if (s.witness.kind != MS_WITNESS_STACK) + return s; + + if (data_len) { + item_data = wally_malloc(data_len); + if (!item_data) { + ms_satisfaction_free(&s); + ms_satisfaction_init(&s, MS_WITNESS_OOM); + return s; + } + memcpy(item_data, data, data_len); + } + return satisfaction_push_item_take(s, item_data, data_len); +} + +/* + * or_b(X, Y) satisfaction and dissatisfaction. + * + * Script: [X] [Y] BOOLOR + * Witnesses (right/inner items precede left/outer in array): + * sat = best( concat(r_sat, l_dis), concat(r_dis, l_sat) ) + * dsat = concat(r_dis, l_dis) + * + * Mirrors rust-miniscript Terminal::OrB arm in sat_dissat.rs. + */ +static void satisfaction_or_b(ms_satisfaction sat_l, ms_satisfaction dissat_l, + ms_satisfaction sat_r, ms_satisfaction dissat_r, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out, + bool malleable) +{ + ms_satisfaction dissat_l_clone = ms_satisfaction_clone(&dissat_l); + ms_satisfaction dissat_r_clone = ms_satisfaction_clone(&dissat_r); + + *dissat_out = satisfaction_concat(dissat_r_clone, dissat_l_clone); + + if (malleable) + *sat_out = satisfaction_minimum_mall( + satisfaction_concat(sat_r, dissat_l), + satisfaction_concat(dissat_r, sat_l)); + else + *sat_out = satisfaction_best( + satisfaction_concat(sat_r, dissat_l), + satisfaction_concat(dissat_r, sat_l)); +} + +/* + * or_c(X, Y) satisfaction and dissatisfaction. + * + * Script: [X] NOTIF [Y] ENDIF + * Witnesses: + * sat = best( sat_l, concat(r_sat, l_dis) ) + * dsat = IMPOSSIBLE (or_c has no valid dissatisfaction) + * + * Mirrors rust-miniscript Terminal::OrC arm in sat_dissat.rs. + */ +static void satisfaction_or_c(ms_satisfaction sat_l, ms_satisfaction dissat_l, + ms_satisfaction sat_r, ms_satisfaction dissat_r, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out, + bool malleable) +{ + ms_satisfaction_free(&dissat_r); + ms_satisfaction_init(dissat_out, MS_WITNESS_IMPOSSIBLE); + + if (malleable) + *sat_out = satisfaction_minimum_mall(sat_l, satisfaction_concat(sat_r, dissat_l)); + else + *sat_out = satisfaction_best(sat_l, satisfaction_concat(sat_r, dissat_l)); +} + +/* + * or_d(X, Y) satisfaction and dissatisfaction. + * + * Script: [X] IFDUP NOTIF [Y] ENDIF + * Witnesses: + * sat = best( sat_l, concat(r_sat, l_dis) ) + * dsat = concat(r_dis, l_dis) + * + * Mirrors rust-miniscript Terminal::OrD arm in sat_dissat.rs. + */ +static void satisfaction_or_d(ms_satisfaction sat_l, ms_satisfaction dissat_l, + ms_satisfaction sat_r, ms_satisfaction dissat_r, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out, + bool malleable) +{ + ms_satisfaction dissat_l_clone = ms_satisfaction_clone(&dissat_l); + + *dissat_out = satisfaction_concat(dissat_r, dissat_l_clone); + + if (malleable) + *sat_out = satisfaction_minimum_mall(sat_l, satisfaction_concat(sat_r, dissat_l)); + else + *sat_out = satisfaction_best(sat_l, satisfaction_concat(sat_r, dissat_l)); +} + +/* + * or_i(X, Y) satisfaction and dissatisfaction. + * + * Script: IF [X] ELSE [Y] ENDIF + * The branch selector byte (0x01 = left / empty = right) is appended to the + * sub-satisfaction and sits on top of the witness stack when the script runs. + * Witnesses: + * sat = best( sat_l ++ [0x01], sat_r ++ [] ) + * dsat = minimum_mall( dissat_l ++ [0x01], dissat_r ++ [] ) + * + * Mirrors rust-miniscript Terminal::OrI arm in sat_dissat.rs. + */ +static void satisfaction_or_i(ms_satisfaction sat_l, ms_satisfaction dissat_l, + ms_satisfaction sat_r, ms_satisfaction dissat_r, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out, + bool malleable) +{ + if (malleable) + *sat_out = satisfaction_minimum_mall( + satisfaction_push_item(sat_l, push_1, 1), + satisfaction_push_item(sat_r, NULL, 0)); + else + *sat_out = satisfaction_best( + satisfaction_push_item(sat_l, push_1, 1), + satisfaction_push_item(sat_r, NULL, 0)); + + *dissat_out = satisfaction_minimum_mall( + satisfaction_push_item(dissat_l, push_1, 1), + satisfaction_push_item(dissat_r, NULL, 0)); +} + +/* + * andor(X, Y, Z) satisfaction and dissatisfaction. + * + * Script: [X] NOTIF [Z] ELSE [Y] ENDIF + * Witnesses: + * sat = best( concat(sat_y, sat_x), concat(sat_z, dissat_x) ) + * dsat = concat(dissat_z, dissat_x) + * + * (inner/Y-Z items precede outer/X in array) + * + * dissat_y is unused: the Y branch is only reached when X is satisfied, + * so the overall dissatisfaction always takes the Z path (dissat_x + dissat_z). + * + * Mirrors rust-miniscript Terminal::AndOr arm in sat_dissat.rs. + */ +static void satisfaction_andor(ms_satisfaction sat_x, ms_satisfaction dissat_x, + ms_satisfaction sat_y, ms_satisfaction dissat_y, + ms_satisfaction sat_z, ms_satisfaction dissat_z, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out, + bool malleable) +{ + ms_satisfaction dissat_x_clone = ms_satisfaction_clone(&dissat_x); + + ms_satisfaction_free(&dissat_y); + + *dissat_out = satisfaction_concat(dissat_z, dissat_x_clone); + + if (malleable) + *sat_out = satisfaction_minimum_mall( + satisfaction_concat(sat_y, sat_x), + satisfaction_concat(sat_z, dissat_x)); + else + *sat_out = satisfaction_best( + satisfaction_concat(sat_y, sat_x), + satisfaction_concat(sat_z, dissat_x)); +} + +/* + * thresh(k, X1, ..., Xn) satisfaction and dissatisfaction. + * + * Consumes every element in sats[] and dissats[]. When malleable is false + * two extra checks reject choices a third party could malleate. + * Mirrors rust-miniscript Satisfaction::thresh / Satisfaction::thresh_mall. + */ +static void satisfaction_thresh(size_t k, size_t n, + ms_satisfaction *sats, + ms_satisfaction *dissats, + ms_satisfaction *sat_out, + ms_satisfaction *dissat_out, + bool malleable) +{ + size_t i; + + /* 1. Compute dissat_out from clones of original dissats */ + ms_satisfaction dsat_acc; + ms_satisfaction_init(&dsat_acc, MS_WITNESS_STACK); + for (i = 0; i < n; i++) { + ms_satisfaction cl = ms_satisfaction_clone(&dissats[i]); + dsat_acc = satisfaction_concat(cl, dsat_acc); + } + *dissat_out = dsat_acc; + + /* 2. Build and sort index array by weight delta */ + for (i = 0; i < n; i++) + if (IS_OOM(sats[i]) || IS_OOM(dissats[i])) + break; /* A sub-satisfaction failed to allocate */ + size_t *indices = i == n ? wally_malloc(n * sizeof(size_t)) : NULL; + if (!indices) { + for (i = 0; i < n; i++) { + ms_satisfaction_free(&sats[i]); + ms_satisfaction_free(&dissats[i]); + } + ms_satisfaction_init(sat_out, MS_WITNESS_OOM); + return; + } + for (i = 0; i < n; i++) indices[i] = i; + thresh_sort(indices, n, sats, dissats, malleable ? 1 : 0); + + /* 3. Swap first k: dissats[indices[i]] gets the chosen sat */ + for (i = 0; i < k; i++) { + ms_satisfaction tmp = dissats[indices[i]]; + dissats[indices[i]] = sats[indices[i]]; + sats[indices[i]] = tmp; + } + + if (!malleable) { + /* 4. Malleability check A: if k-th chosen's original dissat is Impossible, + * we could not find k non-impossible satisfactions - overall impossible. */ + if (sats[indices[k - 1]].witness.kind == MS_WITNESS_IMPOSSIBLE) { + for (i = 0; i < n; i++) { + ms_satisfaction_free(&sats[i]); + ms_satisfaction_free(&dissats[i]); + } + wally_free(indices); + ms_satisfaction_init(sat_out, MS_WITNESS_IMPOSSIBLE); + return; + } + + /* 5. Malleability check B: if the first unchosen element's original sat is + * not impossible and has no sig, a third party can malleate - unavailable. */ + if (k < n && + sats[indices[k]].witness.kind != MS_WITNESS_IMPOSSIBLE && + !sats[indices[k]].has_sig) { + for (i = 0; i < n; i++) { + ms_satisfaction_free(&sats[i]); + ms_satisfaction_free(&dissats[i]); + } + wally_free(indices); + ms_satisfaction_init(sat_out, MS_WITNESS_UNAVAILABLE); + return; + } + } + + /* 6. Free leftover sats[] entries (unchosen sats + swapped-out dissats), + * then fold dissats[] (now ret_stack) for sat_out */ + for (i = 0; i < n; i++) ms_satisfaction_free(&sats[i]); + ms_satisfaction sat_acc; + ms_satisfaction_init(&sat_acc, MS_WITNESS_STACK); + for (i = 0; i < n; i++) + sat_acc = satisfaction_concat(dissats[i], sat_acc); + *sat_out = sat_acc; + + wally_free(indices); +} + +typedef struct { + ms_satisfaction sat; + ms_satisfaction dissat; +} sat_dissat_t; + +/* Pop and free the top child_n child results from the result stack. + * Used when a case cannot proceed (e.g. OOM) and must discard its + * children's satisfactions. */ +static void drain_children(sat_dissat_t *result, size_t *rsp, size_t child_n) +{ + for (size_t i = 0; i < child_n; i++) { + (*rsp)--; + ms_satisfaction_free(&result[*rsp].sat); + ms_satisfaction_free(&result[*rsp].dissat); + } +} + +/* Select the k cheapest available signatures for a multi/multi_a fragment. + * + * On success returns MS_WITNESS_STACK with *avail_out set to an array (owned + * by the caller) whose first k entries are the chosen key indices in + * ascending key order; unchosen-but-available sats[] entries are freed and + * reset to IMPOSSIBLE. On failure returns MS_WITNESS_OOM (allocation failure) + * or MS_WITNESS_IMPOSSIBLE (fewer than k signatures available) with + * *avail_out NULL, freeing every sats[] entry. + */ +static uint32_t multisig_select_k(ms_satisfaction *sats, size_t child_n, size_t k, + size_t **avail_out) +{ + size_t *avail = wally_malloc(child_n * sizeof(size_t)); + size_t navail = 0; + uint32_t kind = avail ? MS_WITNESS_IMPOSSIBLE : MS_WITNESS_OOM; + + *avail_out = NULL; + + /* Collect indices of keys with available signatures */ + for (size_t i = 0; avail && i < child_n; i++) { + if (IS_OOM(sats[i])) { + kind = MS_WITNESS_OOM; + break; /* A signature failed to allocate */ + } + if (sats[i].witness.kind == MS_WITNESS_STACK) + avail[navail++] = i; + } + + if (kind == MS_WITNESS_OOM || navail < k) { + for (size_t i = 0; i < child_n; i++) + ms_satisfaction_free(&sats[i]); + wally_free(avail); + return kind; + } + + if (navail > k) { + /* Sort avail[] by witness weight ascending, keep k lightest */ + for (size_t i = 1; i < navail; i++) { + size_t tmp = avail[i], j = i; + size_t tmp_w = witness_weight(&sats[tmp].witness); + while (j > 0 && + witness_weight(&sats[avail[j - 1]].witness) > tmp_w) { + avail[j] = avail[j - 1]; + j--; + } + avail[j] = tmp; + } + /* Free the heaviest sigs and mark them freed */ + for (size_t i = k; i < navail; i++) { + ms_satisfaction_free(&sats[avail[i]]); + ms_satisfaction_init(&sats[avail[i]], MS_WITNESS_IMPOSSIBLE); + } + /* Re-sort chosen indices by key position (ascending) */ + for (size_t i = 1; i < k; i++) { + size_t tmp = avail[i], j = i; + while (j > 0 && avail[j - 1] > tmp) { + avail[j] = avail[j - 1]; + j--; + } + avail[j] = tmp; + } + } + /* avail[0..k-1] holds chosen key indices in ascending order */ + *avail_out = avail; + return MS_WITNESS_STACK; +} + + +static size_t ms_node_count(const ms_node *node) +{ + /* Count `node`, its ->next siblings and all descendants iteratively. An + * explicit heap stack (grown by hand, as there is no wally_realloc) avoids + * the unbounded recursion that would overflow the stack on deeply-nested + * attacker-supplied scripts. On allocation failure we return 0, which the + * caller (ms_satisfy_node) treats as an allocation failure. */ + size_t count = 0, cap = 0, sp = 0; + const ms_node **stack = NULL; + const ms_node *cur = node; + + while (cur || sp) { + if (cur) { + ++count; + if (cur->child) { + if (sp == cap) { + size_t new_cap = cap ? cap * 2 : 32; + const ms_node **grown = wally_malloc(new_cap * sizeof(*grown)); + if (!grown) { wally_free(stack); return 0; } + if (sp) + memcpy(grown, stack, sp * sizeof(*grown)); + wally_free(stack); + stack = grown; + cap = new_cap; + } + stack[sp++] = cur->child; + } + cur = cur->next; + } else + cur = stack[--sp]; + } + wally_free(stack); + return count; +} + +/* Get the first sub-expression of an expression, or NULL if it has none + * (the children of other expressions are keys, hashes or numbers) */ +static const ms_node *first_sub(const ms_node *node) +{ + switch (node->kind) { + case KIND_MINISCRIPT_THRESH: + return node->child->next; /* Skip the threshold */ + case KIND_MINISCRIPT_ANDOR: + case KIND_MINISCRIPT_AND_V: + case KIND_MINISCRIPT_AND_B: + case KIND_MINISCRIPT_AND_N: + case KIND_MINISCRIPT_OR_B: + case KIND_MINISCRIPT_OR_C: + case KIND_MINISCRIPT_OR_D: + case KIND_MINISCRIPT_OR_I: + return node->child; + } + return NULL; +} + +static size_t num_children(const ms_node *node) +{ + size_t n = 0; + for (node = node->child; node; node = node->next) + ++n; + return n; +} + +/* The satisfaction of 0 or 1 */ +static void satisfy_constant(sat_dissat_t *entry, bool value) +{ + ms_satisfaction_init(&entry->sat, value ? MS_WITNESS_STACK : MS_WITNESS_IMPOSSIBLE); + ms_satisfaction_init(&entry->dissat, value ? MS_WITNESS_IMPOSSIBLE : MS_WITNESS_STACK); +} + +/* The satisfaction of a key: its signature */ +static ms_satisfaction satisfy_key(const ms_node *key, const ms_satisfier *stfr) +{ + unsigned char sig_buf[EC_SIGNATURE_DER_MAX_LEN + 1]; + size_t sig_len = 0; + ms_satisfaction sat; + + ms_satisfaction_init(&sat, MS_WITNESS_IMPOSSIBLE); + if (key->kind == KIND_PUBLIC_KEY && stfr && stfr->lookup_sig && + stfr->lookup_sig(stfr, (const unsigned char *)key->data, + key->data_len, sig_buf, &sig_len)) { + ms_satisfaction_init(&sat, MS_WITNESS_STACK); + sat = satisfaction_push_item(sat, sig_buf, sig_len); + sat.has_sig = true; + } + ms_clear(sig_buf, sizeof(sig_buf)); + return sat; +} + +/* and_v(X,Y): [X] [Y] */ +static void satisfy_and_v(sat_dissat_t x, sat_dissat_t y, sat_dissat_t *entry) +{ + ms_satisfaction x_sat_clone = ms_satisfaction_clone(&x.sat); + ms_satisfaction_free(&x.dissat); + entry->sat = satisfaction_concat(y.sat, x.sat); + entry->dissat = satisfaction_concat(y.dissat, x_sat_clone); +} + +/* multi(k,key1,...,keyn) and multi_a(k,key1,...,keyn) */ +static void satisfy_multi(const ms_node *n, const ms_satisfier *stfr, + sat_dissat_t *entry) +{ + const bool is_multi_a = n->kind == KIND_MINISCRIPT_MULTI_A; + const size_t k = (size_t)n->child->number; + const size_t child_n = num_children(n) - 1; + ms_satisfaction *sats = wally_malloc(child_n * sizeof(ms_satisfaction)); + const ms_node *key; + size_t *avail, i; + uint32_t kind; + + if (!sats) { + ms_satisfaction_init(&entry->sat, MS_WITNESS_OOM); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_OOM); + return; + } + for (i = 0, key = n->child->next; key; ++i, key = key->next) + sats[i] = satisfy_key(key, stfr); + + /* dissat: multi: a dummy item and k empty items (signatures), + * multi_a: an empty item (signature) for each key */ + ms_satisfaction_init(&entry->dissat, MS_WITNESS_STACK); + for (i = 0; i < (is_multi_a ? child_n : k + 1); i++) + entry->dissat = satisfaction_push_item(entry->dissat, NULL, 0); + + kind = multisig_select_k(sats, child_n, k, &avail); + if (kind != MS_WITNESS_STACK) { + wally_free(sats); + ms_satisfaction_init(&entry->sat, kind); /* IMPOSSIBLE or OOM */ + return; + } + + ms_satisfaction_init(&entry->sat, MS_WITNESS_STACK); + if (!is_multi_a) { + /* sat: dummy item followed by k signatures in key order */ + size_t ai = 0; + for (i = 0; i < child_n; i++) { + if (ai < k && avail[ai] == i) + ai++; + else + ms_satisfaction_free(&sats[i]); /* Unchosen */ + } + entry->sat = satisfaction_push_item(entry->sat, NULL, 0); + for (i = 0; i < k; i++) { + const size_t idx = avail[i]; + if (sats[idx].witness.num_items > 0) { + /* Move the signature item into entry->sat (no copy) */ + entry->sat = satisfaction_push_item_take(entry->sat, + sats[idx].witness.items[0].data, + sats[idx].witness.items[0].data_len); + sats[idx].witness.items[0].data = NULL; + sats[idx].witness.items[0].data_len = 0; + } + ms_satisfaction_free(&sats[idx]); + } + } else { + /* + * sat: n witness items in reverse key order (Kn first at stack + * bottom, K1 last at stack top). Chosen keys contribute their sig; + * unchosen keys contribute an empty byte string. + * Use two-pointer scan since avail[] is sorted ascending. + */ + size_t ai = k; + for (i = child_n; i-- > 0; ) { + const bool chosen = (ai > 0 && avail[ai - 1] == i); + if (chosen) { + ai--; + if (sats[i].witness.num_items > 0) { + /* Move the signature item into entry->sat (no copy) */ + entry->sat = satisfaction_push_item_take(entry->sat, + sats[i].witness.items[0].data, + sats[i].witness.items[0].data_len); + sats[i].witness.items[0].data = NULL; + sats[i].witness.items[0].data_len = 0; + } + } else { + entry->sat = satisfaction_push_item(entry->sat, NULL, 0); + } + ms_satisfaction_free(&sats[i]); + } + } + entry->sat.has_sig = true; + + wally_free(sats); + wally_free(avail); +} + +/* Satisfy an expression, given the results for its sub-expressions */ +static void satisfy_expression(const ms_node *n, const ms_satisfier *stfr, + bool malleable, sat_dissat_t *result, + size_t *rsp, sat_dissat_t *entry) +{ + switch (n->kind) { + + case KIND_NUMBER: + satisfy_constant(entry, n->number != 0); + break; + + case KIND_MINISCRIPT_PK_K: + case KIND_DESCRIPTOR_PK | KIND_MINISCRIPT_PK: + /* pk_k(key): , pk(key) is c:pk_k(key) */ + entry->sat = satisfy_key(n->child, stfr); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_STACK); + entry->dissat = satisfaction_push_item(entry->dissat, NULL, 0); + break; + + case KIND_MINISCRIPT_PK_H: + case KIND_DESCRIPTOR_PKH | KIND_MINISCRIPT_PKH: { + /* pk_h(key): DUP HASH160 EQUALVERIFY, + * pkh(key) is c:pk_h(key) */ + const ms_node *key = n->child; + if (key->kind != KIND_PUBLIC_KEY) { + ms_satisfaction_init(&entry->dissat, MS_WITNESS_UNAVAILABLE); + break; + } + /* sat: [sig, pubkey], dissat: [0, pubkey] */ + entry->sat = satisfy_key(key, stfr); + entry->sat = satisfaction_push_item(entry->sat, + (const unsigned char *)key->data, + key->data_len); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_STACK); + entry->dissat = satisfaction_push_item(entry->dissat, NULL, 0); + entry->dissat = satisfaction_push_item(entry->dissat, + (const unsigned char *)key->data, + key->data_len); + break; + } + + case KIND_MINISCRIPT_SHA256: + case KIND_MINISCRIPT_HASH256: + case KIND_MINISCRIPT_RIPEMD160: + case KIND_MINISCRIPT_HASH160: { + const ms_node *hash = n->child; + unsigned char preimage[32]; + uint32_t hash_type; + if (n->kind == KIND_MINISCRIPT_SHA256) hash_type = MS_HASH_SHA256; + else if (n->kind == KIND_MINISCRIPT_HASH256) hash_type = MS_HASH_HASH256; + else if (n->kind == KIND_MINISCRIPT_RIPEMD160) hash_type = MS_HASH_RIPEMD160; + else hash_type = MS_HASH_HASH160; + if (stfr && stfr->lookup_preimage && + stfr->lookup_preimage(stfr, (const unsigned char *)hash->data, + hash->data_len, hash_type, preimage)) { + ms_satisfaction_init(&entry->sat, MS_WITNESS_STACK); + entry->sat = satisfaction_push_item(entry->sat, preimage, 32); + } else { + ms_satisfaction_init(&entry->sat, MS_WITNESS_UNAVAILABLE); + } + /* Dissatisfaction for hash fragments is always possible: + * any 32-byte non-matching value suffices. */ + ms_satisfaction_init(&entry->dissat, MS_WITNESS_STACK); + entry->dissat = satisfaction_push_item(entry->dissat, zero32, 32); + ms_clear(preimage, sizeof(preimage)); + break; + } + + case KIND_MINISCRIPT_OLDER: { + const uint32_t lock = (uint32_t)n->child->number; + if (stfr && stfr->check_older && stfr->check_older(stfr, lock)) { + ms_satisfaction_init(&entry->sat, MS_WITNESS_STACK); + entry->sat.relative_timelock = lock; + } else { + ms_satisfaction_init(&entry->sat, MS_WITNESS_UNAVAILABLE); + } + break; + } + + case KIND_MINISCRIPT_AFTER: { + const uint32_t lock = (uint32_t)n->child->number; + if (stfr && stfr->check_after && stfr->check_after(stfr, lock)) { + ms_satisfaction_init(&entry->sat, MS_WITNESS_STACK); + entry->sat.absolute_timelock = lock; + } else { + ms_satisfaction_init(&entry->sat, MS_WITNESS_UNAVAILABLE); + } + break; + } + + case KIND_DESCRIPTOR_MULTI | KIND_MINISCRIPT_MULTI: + case KIND_MINISCRIPT_MULTI_A: + satisfy_multi(n, stfr, entry); + break; + + case KIND_MINISCRIPT_AND_B: { + sat_dissat_t r = result[--*rsp]; + sat_dissat_t l = result[--*rsp]; + entry->sat = satisfaction_concat(r.sat, l.sat); + entry->dissat = satisfaction_concat(r.dissat, l.dissat); + break; + } + + case KIND_MINISCRIPT_AND_V: { + sat_dissat_t r = result[--*rsp]; + sat_dissat_t l = result[--*rsp]; + satisfy_and_v(l, r, entry); + break; + } + + case KIND_MINISCRIPT_AND_N: + case KIND_MINISCRIPT_ANDOR: { + /* and_n(X,Y) is andor(X,Y,0) */ + sat_dissat_t z, y, x; + if (n->kind == KIND_MINISCRIPT_AND_N) + satisfy_constant(&z, false); + else + z = result[--*rsp]; + y = result[--*rsp]; + x = result[--*rsp]; + satisfaction_andor(x.sat, x.dissat, y.sat, y.dissat, + z.sat, z.dissat, + &entry->sat, &entry->dissat, malleable); + break; + } + + case KIND_MINISCRIPT_OR_B: { + sat_dissat_t r = result[--*rsp]; + sat_dissat_t l = result[--*rsp]; + satisfaction_or_b(l.sat, l.dissat, r.sat, r.dissat, + &entry->sat, &entry->dissat, malleable); + break; + } + + case KIND_MINISCRIPT_OR_C: { + sat_dissat_t r = result[--*rsp]; + sat_dissat_t l = result[--*rsp]; + satisfaction_or_c(l.sat, l.dissat, r.sat, r.dissat, + &entry->sat, &entry->dissat, malleable); + break; + } + + case KIND_MINISCRIPT_OR_D: { + sat_dissat_t r = result[--*rsp]; + sat_dissat_t l = result[--*rsp]; + satisfaction_or_d(l.sat, l.dissat, r.sat, r.dissat, + &entry->sat, &entry->dissat, malleable); + break; + } + + case KIND_MINISCRIPT_OR_I: { + sat_dissat_t r = result[--*rsp]; + sat_dissat_t l = result[--*rsp]; + satisfaction_or_i(l.sat, l.dissat, r.sat, r.dissat, + &entry->sat, &entry->dissat, malleable); + break; + } + + case KIND_MINISCRIPT_THRESH: { + const size_t k = (size_t)n->child->number; + const size_t child_n = num_children(n) - 1; + ms_satisfaction *sats = wally_malloc(child_n * sizeof(ms_satisfaction)); + ms_satisfaction *dissats = wally_malloc(child_n * sizeof(ms_satisfaction)); + if (!sats || !dissats) { + wally_free(sats); wally_free(dissats); + drain_children(result, rsp, child_n); + ms_satisfaction_init(&entry->sat, MS_WITNESS_OOM); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_OOM); + break; + } + for (size_t i = child_n; i-- > 0; ) { + sat_dissat_t sd = result[--*rsp]; + sats[i] = sd.sat; + dissats[i] = sd.dissat; + } + satisfaction_thresh(k, child_n, sats, dissats, + &entry->sat, &entry->dissat, malleable); + wally_free(sats); + wally_free(dissats); + break; + } + + default: + break; /* Not a miniscript expression: impossible to satisfy */ + } +} + +/* Apply the wrappers of an expression to its satisfaction */ +static void satisfy_wrappers(const ms_node *n, bool malleable, sat_dissat_t *entry) +{ + size_t i = strlen(n->wrapper_str); + sat_dissat_t c; + + while (i--) { + /* Apply the innermost wrapper first */ + const char wrapper = n->wrapper_str[i]; + switch (wrapper) { + case 'd': + /* d:X: DUP IF [X] ENDIF */ + ms_satisfaction_free(&entry->dissat); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_STACK); + entry->dissat = satisfaction_push_item(entry->dissat, NULL, 0); + entry->sat = satisfaction_push_item(entry->sat, push_1, 1); + break; + case 'v': + /* v:X: [X] VERIFY */ + ms_satisfaction_free(&entry->dissat); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_IMPOSSIBLE); + break; + case 'j': + /* j:X: SIZE 0NOTEQUAL IF [X] ENDIF. Satisfied by X's satisfaction + * (whose top element is non-zero-length); dissatisfied by a single + * empty push (SIZE=0 -> false -> IF skipped). */ + ms_satisfaction_free(&entry->dissat); + ms_satisfaction_init(&entry->dissat, MS_WITNESS_STACK); + entry->dissat = satisfaction_push_item(entry->dissat, NULL, 0); + break; + case 't': + /* t:X is and_v(X,1) */ + satisfy_constant(&c, true); + satisfy_and_v(*entry, c, entry); + break; + case 'l': + case 'u': + /* l:X is or_i(0,X), u:X is or_i(X,0) */ + satisfy_constant(&c, false); + if (wrapper == 'l') + satisfaction_or_i(c.sat, c.dissat, entry->sat, entry->dissat, + &entry->sat, &entry->dissat, malleable); + else + satisfaction_or_i(entry->sat, entry->dissat, c.sat, c.dissat, + &entry->sat, &entry->dissat, malleable); + break; + default: + /* a:, s:, c: and n: are satisfied as the wrapped expression */ + break; + } + } +} + +typedef struct { + const ms_node *node; + const ms_node *cur_child; +} trav_frame_t; + +void ms_satisfy_node(const ms_node *node, const ms_satisfier *stfr, + bool malleable, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out) +{ + size_t cap = ms_node_count(node); /* Zero on allocation failure */ + trav_frame_t *trav = cap ? wally_malloc(cap * sizeof(trav_frame_t)) : NULL; + sat_dissat_t *result = cap ? wally_malloc(cap * sizeof(sat_dissat_t)) : NULL; + if (!trav || !result) { + wally_free(trav); wally_free(result); + ms_satisfaction_init(sat_out, MS_WITNESS_OOM); + ms_satisfaction_init(dissat_out, MS_WITNESS_OOM); + return; + } + + size_t tsp = 0; + size_t rsp = 0; + + trav[tsp++] = (trav_frame_t){ node, first_sub(node) }; + + while (tsp > 0) { + trav_frame_t *top = &trav[tsp - 1]; + + if (top->cur_child) { + const ms_node *child = top->cur_child; + top->cur_child = child->next; + trav[tsp++] = (trav_frame_t){ child, first_sub(child) }; + continue; + } + + const ms_node *n = top->node; + tsp--; + + sat_dissat_t entry; + ms_satisfaction_init(&entry.sat, MS_WITNESS_IMPOSSIBLE); + ms_satisfaction_init(&entry.dissat, MS_WITNESS_IMPOSSIBLE); + satisfy_expression(n, stfr, malleable, result, &rsp, &entry); + satisfy_wrappers(n, malleable, &entry); + result[rsp++] = entry; + } + + /* Each expression pops exactly its sub-expressions' results, so + * exactly one result remains. */ + if (rsp == 1) { + *sat_out = result[0].sat; + *dissat_out = result[0].dissat; + } else { + drain_children(result, &rsp, rsp); + ms_satisfaction_init(sat_out, MS_WITNESS_IMPOSSIBLE); + ms_satisfaction_init(dissat_out, MS_WITNESS_IMPOSSIBLE); + } + + wally_free(trav); + wally_free(result); +} diff --git a/src/miniscript_satisfy.h b/src/miniscript_satisfy.h new file mode 100644 index 000000000..047e1330c --- /dev/null +++ b/src/miniscript_satisfy.h @@ -0,0 +1,74 @@ +#ifndef LIBWALLY_CORE_MINISCRIPT_SATISFY_H +#define LIBWALLY_CORE_MINISCRIPT_SATISFY_H 1 + +#include "descriptor_int.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Witness state kinds (maps to Rust Witness enum variants) */ +#define MS_WITNESS_IMPOSSIBLE 0u /* No valid satisfaction exists */ +#define MS_WITNESS_UNAVAILABLE 1u /* Missing data; third party may satisfy */ +#define MS_WITNESS_STACK 2u /* Stack data available */ +#define MS_WITNESS_OOM 3u /* An allocation failed: no result */ + +typedef struct ms_witness_item_t { + unsigned char *data; + size_t data_len; +} ms_witness_item; + +typedef struct ms_witness_t { + uint32_t kind; /* MS_WITNESS_* constant */ + ms_witness_item *items; + size_t num_items; + size_t items_allocation_len; /* allocated capacity */ +} ms_witness; + +typedef struct ms_satisfaction_t { + ms_witness witness; + bool has_sig; /* true if satisfaction contains a signature */ + uint32_t absolute_timelock; /* 0 = absent */ + uint32_t relative_timelock; /* 0 = absent */ +} ms_satisfaction; + +void ms_satisfaction_free(ms_satisfaction *s); + +/* Hash type constants for lookup_preimage */ +#define MS_HASH_SHA256 0u +#define MS_HASH_HASH256 1u +#define MS_HASH_RIPEMD160 2u +#define MS_HASH_HASH160 3u + +/* Asset provider for ms_satisfy_node. Mirrors rust-miniscript AssetProvider. */ +typedef struct ms_satisfier_t { + /* Write a DER/Schnorr sig into sig_out; set *sig_len_out. Return true if + * available. sig_out has room for EC_SIGNATURE_DER_MAX_LEN + 1 bytes + * (max-DER signature plus sighash byte); callbacks MUST NOT write more. */ + bool (*lookup_sig)(const struct ms_satisfier_t *stfr, + const unsigned char *pk, size_t pk_len, + unsigned char *sig_out, size_t *sig_len_out); + /* Write the 32-byte preimage of hash into preimage_out. hash_type = MS_HASH_*. */ + bool (*lookup_preimage)(const struct ms_satisfier_t *stfr, + const unsigned char *hash, size_t hash_len, + uint32_t hash_type, + unsigned char preimage_out[32]); + /* Return true if relative locktime lock is satisfied. */ + bool (*check_older)(const struct ms_satisfier_t *stfr, uint32_t lock); + /* Return true if absolute locktime lock is satisfied. */ + bool (*check_after)(const struct ms_satisfier_t *stfr, uint32_t lock); + void *user_data; +} ms_satisfier; + +/* Satisfy and dissatisfy a parsed miniscript expression. The keys of the + * expression must be public keys (as decoded by ms_descriptor_from_script): + * keys of other kinds are treated as having no signature available. */ +void ms_satisfy_node(const ms_node *node, const ms_satisfier *stfr, + bool malleable, + ms_satisfaction *sat_out, ms_satisfaction *dissat_out); + +#ifdef __cplusplus +} +#endif + +#endif /* LIBWALLY_CORE_MINISCRIPT_SATISFY_H */ From 584824f6b262539df8abf3ceb39f3243628a4263 Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Tue, 30 Jun 2026 13:36:21 -0300 Subject: [PATCH 5/9] musig2: add MuSig2 (BIP-327) core API Adds the MuSig2 implementation (musig.c) over the secp256k1-zkp musig module: key aggregation, nonce generation and aggregation, the signing pipeline (nonce_process, partial_sign, verify, aggregate), and lifecycle helpers for the opaque keyagg-cache / nonce / session / partial-sig types, plus BIP-328 synthetic-xpub helpers and the language bindings. Enables the secp256k1 musig module in the build and routes a malformed parsed keyagg-cache/session through a non-aborting illegal-argument callback. Includes the BIP-327/328 vector and protocol test suites. The bindings are regenerated from the headers via tools/build_wrappers.py. The Python SWIG wrapper gains the opaque output-parameter typemaps that the Java wrapper already had, and a contrib test covering the full signing flow. Co-authored-by: odudex --- .gitignore | 1 + _CMakeLists.txt | 2 +- configure.ac | 3 +- docs/source/conf.py | 2 +- include/wally.hpp | 178 ++++ include/wally_musig.h | 544 ++++++++++ src/Makefile.am | 6 + src/amalgamation/combined.c | 8 + src/data/bip327/det_sign_vectors.json | 144 +++ src/data/bip327/key_agg_vectors.json | 88 ++ src/data/bip327/nonce_agg_vectors.json | 51 + src/data/bip327/nonce_gen_vectors.json | 44 + src/data/bip327/sig_agg_vectors.json | 152 +++ src/data/bip327/sign_verify_vectors.json | 212 ++++ src/data/bip327/tweak_vectors.json | 84 ++ src/internal.c | 16 +- src/musig.c | 939 +++++++++++++++++ src/swig_java/swig.i | 110 ++ src/swig_python/contrib/musig.py | 60 ++ src/swig_python/python_extra.py_in | 9 + src/swig_python/swig.i | 78 ++ src/test/test_musig.py | 1214 ++++++++++++++++++++++ src/test/test_musig_vectors.py | 799 ++++++++++++++ src/test/util.py | 30 + src/wasm_package/src/const.js | 6 + src/wasm_package/src/functions.js | 30 + src/wasm_package/src/index.d.ts | 30 + tools/build_wrappers.py | 5 +- tools/wasm_exports.sh | 30 + 29 files changed, 4870 insertions(+), 5 deletions(-) create mode 100644 include/wally_musig.h create mode 100644 src/data/bip327/det_sign_vectors.json create mode 100644 src/data/bip327/key_agg_vectors.json create mode 100644 src/data/bip327/nonce_agg_vectors.json create mode 100644 src/data/bip327/nonce_gen_vectors.json create mode 100644 src/data/bip327/sig_agg_vectors.json create mode 100644 src/data/bip327/sign_verify_vectors.json create mode 100644 src/data/bip327/tweak_vectors.json create mode 100644 src/musig.c create mode 100644 src/swig_python/contrib/musig.py create mode 100644 src/test/test_musig.py create mode 100644 src/test/test_musig_vectors.py diff --git a/.gitignore b/.gitignore index ba5fad562..365eb9f35 100644 --- a/.gitignore +++ b/.gitignore @@ -75,6 +75,7 @@ docs/source/core.rst docs/source/crypto.rst docs/source/map.rst docs/source/descriptor.rst +docs/source/musig.rst docs/source/psbt.rst docs/source/psbt_members.rst docs/source/script.rst diff --git a/_CMakeLists.txt b/_CMakeLists.txt index 6243ce24a..2add1aa7f 100644 --- a/_CMakeLists.txt +++ b/_CMakeLists.txt @@ -48,7 +48,7 @@ set(SECP256K1_ENABLE_MODULE_GENERATOR ON) set(SECP256K1_ENABLE_MODULE_RANGEPROOF ON) set(SECP256K1_ENABLE_MODULE_SURJECTIONPROOF ON) set(SECP256K1_ENABLE_MODULE_WHITELIST ON) -set(SECP256K1_ENABLE_MODULE_MUSIG OFF) +set(SECP256K1_ENABLE_MODULE_MUSIG ON) set(SECP256K1_ENABLE_MODULE_ECDSA_ADAPTOR OFF) set(SECP256K1_ENABLE_MODULE_ECDSA_S2C ON) set(SECP256K1_ENABLE_MODULE_BPPP OFF) diff --git a/configure.ac b/configure.ac index bdf17215f..016b10e52 100644 --- a/configure.ac +++ b/configure.ac @@ -349,6 +349,7 @@ AM_COND_IF([LINK_SYSTEM_SECP256K1], [ ]) AM_COND_IF([BUILD_STANDARD_SECP], [], [ CHECK_MODULE([ecdsa-s2c], [secp256k1_ecdsa_s2c_sign]) + CHECK_MODULE([musig], [secp256k1_musig_pubkey_agg]) ]) AS_IF([test -n "${missing_modules}"], [ AC_MSG_ERROR([system-installed $with_system_secp256k1 does not support these required modules:${missing_modules}]) @@ -511,7 +512,7 @@ export LD export LDFLAGS AM_COND_IF([LINK_SYSTEM_SECP256K1], [], [ - AX_SUBDIRS_CONFIGURE([src/secp256k1], [[--disable-shared], [--enable-static], [--with-pic], [--enable-experimental], [--enable-module-ecdh], [--enable-module-recovery], [--enable-module-extrakeys], [--enable-module-schnorrsig], [--enable-module-generator], [--enable-module-rangeproof], [--enable-module-surjectionproof], [--enable-module-whitelist], [--enable-module-ecdsa-s2c], [$secp256k1_test_opt], [--enable-exhaustive-tests=no], [--enable-benchmark=no], [--disable-dependency-tracking], [$secp_asm]]) + AX_SUBDIRS_CONFIGURE([src/secp256k1], [[--disable-shared], [--enable-static], [--with-pic], [--enable-experimental], [--enable-module-ecdh], [--enable-module-recovery], [--enable-module-extrakeys], [--enable-module-schnorrsig], [--enable-module-musig], [--enable-module-generator], [--enable-module-rangeproof], [--enable-module-surjectionproof], [--enable-module-whitelist], [--enable-module-ecdsa-s2c], [$secp256k1_test_opt], [--enable-exhaustive-tests=no], [--enable-benchmark=no], [--disable-dependency-tracking], [$secp_asm]]) ]) AC_OUTPUT diff --git a/docs/source/conf.py b/docs/source/conf.py index f15613028..afccf897c 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -128,7 +128,7 @@ def extract_docs(infile, outfile): for m in [ 'address', 'anti_exfil', 'bip32', 'bip38', 'bip39', 'bip85', 'coinselection', 'core', 'crypto', 'descriptor', 'elements', - 'map', 'psbt', 'script', 'symmetric', 'transaction' + 'map', 'musig', 'psbt', 'script', 'symmetric', 'transaction' ]: extract_docs('../../include/wally_%s.h' % m, '%s.rst' % m) diff --git a/include/wally.hpp b/include/wally.hpp index 49ddc1de4..5e717cd5a 100644 --- a/include/wally.hpp +++ b/include/wally.hpp @@ -20,6 +20,9 @@ #include #include #include +#ifndef BUILD_STANDARD_SECP +#include +#endif /* These wrappers allow passing containers such as std::vector, std::array, * std::string and custom classes as input/output buffers to wally functions. @@ -1246,6 +1249,180 @@ inline bool merkle_path_xonly_public_key_verify(const KEY& key, const VAL& val) return ret == WALLY_OK; } +inline int musig_aggnonce_free(struct wally_musig_aggnonce* nonce) { + int ret = ::wally_musig_aggnonce_free(nonce); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_aggnonce_parse(const BYTES& bytes, struct wally_musig_aggnonce** output) { + int ret = ::wally_musig_aggnonce_parse(bytes.data(), bytes.size(), output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_aggnonce_serialize(const NONCE& nonce, BYTES_OUT& bytes_out) { + int ret = ::wally_musig_aggnonce_serialize(detail::get_p(nonce), bytes_out.data(), bytes_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +inline int musig_keyagg_cache_free(struct wally_musig_keyagg_cache* cache) { + int ret = ::wally_musig_keyagg_cache_free(cache); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_keyagg_cache_parse(const BYTES& bytes, struct wally_musig_keyagg_cache** output) { + int ret = ::wally_musig_keyagg_cache_parse(bytes.data(), bytes.size(), output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_keyagg_cache_serialize(const CACHE& cache, BYTES_OUT& bytes_out) { + int ret = ::wally_musig_keyagg_cache_serialize(detail::get_p(cache), bytes_out.data(), bytes_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_nonce_agg(const PUBNONCES& pubnonces, size_t n_pubnonces, struct wally_musig_aggnonce** aggnonce_out) { + int ret = ::wally_musig_nonce_agg(pubnonces.data(), pubnonces.size(), n_pubnonces, aggnonce_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_nonce_gen(const SESSION_SECRAND32& session_secrand32, const SECKEY& seckey, const PUB_KEY& pub_key, const KEYAGG_CACHE& keyagg_cache, const MSG32& msg32, const EXTRA_INPUT32& extra_input32, struct wally_musig_secnonce** secnonce_out, struct wally_musig_pubnonce** pubnonce_out) { + int ret = ::wally_musig_nonce_gen(session_secrand32.data(), session_secrand32.size(), seckey.data(), seckey.size(), pub_key.data(), pub_key.size(), detail::get_p(keyagg_cache), msg32.data(), msg32.size(), extra_input32.data(), extra_input32.size(), secnonce_out, pubnonce_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_nonce_gen_counter(uint64_t counter, const SECKEY& seckey, const PUB_KEY& pub_key, const KEYAGG_CACHE& keyagg_cache, const MSG32& msg32, const EXTRA_INPUT32& extra_input32, struct wally_musig_secnonce** secnonce_out, struct wally_musig_pubnonce** pubnonce_out) { + int ret = ::wally_musig_nonce_gen_counter(counter, seckey.data(), seckey.size(), pub_key.data(), pub_key.size(), detail::get_p(keyagg_cache), msg32.data(), msg32.size(), extra_input32.data(), extra_input32.size(), secnonce_out, pubnonce_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_nonce_process(const AGGNONCE& aggnonce, const MSG32& msg32, const CACHE& cache, const ADAPTOR& adaptor, struct wally_musig_session** session_out) { + int ret = ::wally_musig_nonce_process(detail::get_p(aggnonce), msg32.data(), msg32.size(), detail::get_p(cache), adaptor.data(), adaptor.size(), session_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_partial_sig_agg(const PARTIAL_SIGS& partial_sigs, size_t n_sigs, const SESSION& session, SIG64_OUT& sig64_out) { + int ret = ::wally_musig_partial_sig_agg(partial_sigs.data(), partial_sigs.size(), n_sigs, detail::get_p(session), sig64_out.data(), sig64_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +inline int musig_partial_sig_free(struct wally_musig_partial_sig* sig) { + int ret = ::wally_musig_partial_sig_free(sig); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_partial_sig_parse(const BYTES& bytes, struct wally_musig_partial_sig** output) { + int ret = ::wally_musig_partial_sig_parse(bytes.data(), bytes.size(), output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_partial_sig_serialize(const SIG& sig, BYTES_OUT& bytes_out) { + int ret = ::wally_musig_partial_sig_serialize(detail::get_p(sig), bytes_out.data(), bytes_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline bool musig_partial_sig_verify(const SIG& sig, const PUBNONCE& pubnonce, const PUB_KEY& pub_key, const CACHE& cache, const struct wally_musig_session* session) { + int ret = ::wally_musig_partial_sig_verify(detail::get_p(sig), detail::get_p(pubnonce), pub_key.data(), pub_key.size(), detail::get_p(cache), session); + return ret == WALLY_OK; +} + +template +inline int musig_partial_sign(const SECNONCE& secnonce, const SECKEY& seckey, const CACHE& cache, const SESSION& session, struct wally_musig_partial_sig** partial_sig_out) { + int ret = ::wally_musig_partial_sign(detail::get_p(secnonce), seckey.data(), seckey.size(), detail::get_p(cache), detail::get_p(session), partial_sig_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkey_agg(const PUB_KEYS& pub_keys, AGG_PK_OUT& agg_pk_out, struct wally_musig_keyagg_cache** cache_out) { + int ret = ::wally_musig_pubkey_agg(pub_keys.data(), pub_keys.size(), agg_pk_out.data(), agg_pk_out.size(), cache_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkey_ec_tweak_add(const CACHE& cache, const TWEAK& tweak, PUB_KEY_OUT& pub_key_out) { + int ret = ::wally_musig_pubkey_ec_tweak_add(detail::get_p(cache), tweak.data(), tweak.size(), pub_key_out.data(), pub_key_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkey_get(const CACHE& cache, PUB_KEY_OUT& pub_key_out) { + int ret = ::wally_musig_pubkey_get(detail::get_p(cache), pub_key_out.data(), pub_key_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkey_to_xpub(const AGG_PK& agg_pk, uint32_t version, struct ext_key** output) { + int ret = ::wally_musig_pubkey_to_xpub(agg_pk.data(), agg_pk.size(), version, output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkey_xonly_tweak_add(const CACHE& cache, const TWEAK& tweak, PUB_KEY_OUT& pub_key_out) { + int ret = ::wally_musig_pubkey_xonly_tweak_add(detail::get_p(cache), tweak.data(), tweak.size(), pub_key_out.data(), pub_key_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkeys_agg_then_derive(const PUB_KEYS& pub_keys, uint32_t version, uint32_t child_num, PUB_KEY_OUT& pub_key_out, struct ext_key** child_out) { + int ret = ::wally_musig_pubkeys_agg_then_derive(pub_keys.data(), pub_keys.size(), version, child_num, pub_key_out.data(), pub_key_out.size(), child_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubkeys_derive_then_agg(const XPUBS& xpubs, uint32_t child_num, AGG_PK_OUT& agg_pk_out, struct wally_musig_keyagg_cache** cache_out) { + int ret = ::wally_musig_pubkeys_derive_then_agg(xpubs.data(), xpubs.size(), child_num, agg_pk_out.data(), agg_pk_out.size(), cache_out); + return detail::check_ret(__FUNCTION__, ret); +} + +inline int musig_pubnonce_free(struct wally_musig_pubnonce* nonce) { + int ret = ::wally_musig_pubnonce_free(nonce); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubnonce_parse(const BYTES& bytes, struct wally_musig_pubnonce** output) { + int ret = ::wally_musig_pubnonce_parse(bytes.data(), bytes.size(), output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_pubnonce_serialize(const NONCE& nonce, BYTES_OUT& bytes_out) { + int ret = ::wally_musig_pubnonce_serialize(detail::get_p(nonce), bytes_out.data(), bytes_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +inline int musig_secnonce_free(struct wally_musig_secnonce* nonce) { + int ret = ::wally_musig_secnonce_free(nonce); + return detail::check_ret(__FUNCTION__, ret); +} + +inline int musig_session_free(struct wally_musig_session* session) { + int ret = ::wally_musig_session_free(session); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_session_parse(const BYTES& bytes, struct wally_musig_session** output) { + int ret = ::wally_musig_session_parse(bytes.data(), bytes.size(), output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int musig_session_serialize(const SESSION& session, BYTES_OUT& bytes_out) { + int ret = ::wally_musig_session_serialize(detail::get_p(session), bytes_out.data(), bytes_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int pbkdf2_hmac_sha256(const PASS& pass, const SALT& salt, uint32_t flags, uint32_t cost, BYTES_OUT& bytes_out) { int ret = ::wally_pbkdf2_hmac_sha256(pass.data(), pass.size(), salt.data(), salt.size(), flags, cost, bytes_out.data(), bytes_out.size()); @@ -3376,6 +3553,7 @@ inline bool is_elements_build() return ret != 0; } + } /* namespace wally */ #endif /* LIBWALLY_CORE_WALLY_HPP */ diff --git a/include/wally_musig.h b/include/wally_musig.h new file mode 100644 index 000000000..070f24b51 --- /dev/null +++ b/include/wally_musig.h @@ -0,0 +1,544 @@ +#ifndef LIBWALLY_CORE_MUSIG_H +#define LIBWALLY_CORE_MUSIG_H + +#include "wally_core.h" +#include "wally_crypto.h" +#include "wally_bip32.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* MuSig2 object sizes stay available even under BUILD_STANDARD_SECP: the inert + * musig2 PSBT field plumbing (storage/serialization) references these lengths, + * while the secp-backed crypto below is compiled out. */ +/** Sizes of serialized MuSig2 objects */ +#define WALLY_MUSIG_PUBNONCE_LEN 66 +#define WALLY_MUSIG_AGGNONCE_LEN 66 +#define WALLY_MUSIG_PARTIAL_SIG_LEN 32 + +/** Sizes of serializable opaque MuSig2 objects */ +#define WALLY_MUSIG_KEYAGG_CACHE_LEN 197 +#define WALLY_MUSIG_SESSION_LEN 133 + +/** Length of the BIP-328 synthetic chain code (same as BIP-32 chain code) */ +#define WALLY_MUSIG2_CHAINCODE_LEN 32 + +#ifndef BUILD_STANDARD_SECP + +/* Opaque type wrapping secp256k1_musig_keyagg_cache. + * Holds the result of key aggregation; required for signing. */ +struct wally_musig_keyagg_cache; + +/* Opaque type wrapping secp256k1_musig_secnonce. + * WARNING: MUST NOT be copied or serialized. Zeroed on free and after use. */ +struct wally_musig_secnonce; + +/* Opaque type wrapping secp256k1_musig_pubnonce. Serializes to 66 bytes. */ +struct wally_musig_pubnonce; + +/* Opaque type wrapping secp256k1_musig_aggnonce. Serializes to 66 bytes. */ +struct wally_musig_aggnonce; + +/* Opaque type wrapping secp256k1_musig_session. Not required to be secret. */ +struct wally_musig_session; + +/* Opaque type wrapping secp256k1_musig_partial_sig. Serializes to 32 bytes. */ +struct wally_musig_partial_sig; + +/* --- Lifecycle functions --- */ + +/** + * Free a keyagg_cache. + * + * :param cache: The keyagg_cache to free. + */ +WALLY_CORE_API int wally_musig_keyagg_cache_free( + struct wally_musig_keyagg_cache *cache); + +/** + * Serialize a keyagg_cache to its raw 197-byte form. + * + * :param cache: The keyagg_cache to serialize. + * :param bytes_out: 197-byte output buffer. + * FIXED_SIZED_OUTPUT(len, bytes_out, WALLY_MUSIG_KEYAGG_CACHE_LEN) + */ +WALLY_CORE_API int wally_musig_keyagg_cache_serialize( + const struct wally_musig_keyagg_cache *cache, + unsigned char *bytes_out, + size_t len); + +/** + * Restore a keyagg_cache from its raw 197-byte form. + * + * The aggregate key is checked, which rejects a corrupted magic or aggregate-key + * field. This is NOT a full integrity check: tampering with the tweak or other + * fields is not detected, so do not treat a successful parse as authentication of + * data crossing a trust boundary. Only round-trip bytes produced by + * wally_musig_keyagg_cache_serialize(). + * + * :param bytes: The 197-byte serialized keyagg_cache. + * :param bytes_len: Length of bytes. Must be WALLY_MUSIG_KEYAGG_CACHE_LEN. + * :param output: Destination for the allocated keyagg_cache. + */ +WALLY_CORE_API int wally_musig_keyagg_cache_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_keyagg_cache **output); + +/** + * Free a secnonce, securely zeroing it first. + * + * :param nonce: The secnonce to free. + */ +WALLY_CORE_API int wally_musig_secnonce_free( + struct wally_musig_secnonce *nonce); + +/** + * Parse a public nonce from its 66-byte serialized form. + * + * :param bytes: The 66-byte serialized pubnonce. + * :param bytes_len: Length of bytes. Must be WALLY_MUSIG_PUBNONCE_LEN. + * :param output: Destination for the allocated pubnonce. + */ +WALLY_CORE_API int wally_musig_pubnonce_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_pubnonce **output); + +/** + * Serialize a public nonce to its 66-byte form. + * + * :param nonce: The pubnonce to serialize. + * :param bytes_out: 66-byte output buffer. + * FIXED_SIZED_OUTPUT(len, bytes_out, WALLY_MUSIG_PUBNONCE_LEN) + */ +WALLY_CORE_API int wally_musig_pubnonce_serialize( + const struct wally_musig_pubnonce *nonce, + unsigned char *bytes_out, + size_t len); + +/** + * Free a pubnonce. + * + * :param nonce: The pubnonce to free. + */ +WALLY_CORE_API int wally_musig_pubnonce_free( + struct wally_musig_pubnonce *nonce); + +/** + * Parse an aggregate nonce from its 66-byte serialized form. + * + * :param bytes: The 66-byte serialized aggnonce. + * :param bytes_len: Length of bytes. Must be WALLY_MUSIG_AGGNONCE_LEN. + * :param output: Destination for the allocated aggnonce. + */ +WALLY_CORE_API int wally_musig_aggnonce_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_aggnonce **output); + +/** + * Serialize an aggregate nonce to its 66-byte form. + * + * :param nonce: The aggnonce to serialize. + * :param bytes_out: 66-byte output buffer. + * FIXED_SIZED_OUTPUT(len, bytes_out, WALLY_MUSIG_AGGNONCE_LEN) + */ +WALLY_CORE_API int wally_musig_aggnonce_serialize( + const struct wally_musig_aggnonce *nonce, + unsigned char *bytes_out, + size_t len); + +/** + * Free an aggnonce. + * + * :param nonce: The aggnonce to free. + */ +WALLY_CORE_API int wally_musig_aggnonce_free( + struct wally_musig_aggnonce *nonce); + +/** + * Free a session. + * + * :param session: The session to free. + */ +WALLY_CORE_API int wally_musig_session_free( + struct wally_musig_session *session); + +/** + * Serialize a session to its raw 133-byte form. + * + * :param session: The session to serialize. + * :param bytes_out: 133-byte output buffer. + * FIXED_SIZED_OUTPUT(len, bytes_out, WALLY_MUSIG_SESSION_LEN) + */ +WALLY_CORE_API int wally_musig_session_serialize( + const struct wally_musig_session *session, + unsigned char *bytes_out, + size_t len); + +/** + * Restore a session from its raw 133-byte form. + * + * WARNING: Do NOT call this on bytes from untrusted sources. The struct is not + * cryptographically validated; malformed bytes produce undefined signing behaviour. + * Only round-trip bytes produced by wally_musig_session_serialize(). + * + * :param bytes: The 133-byte serialized session. + * :param bytes_len: Length of bytes. Must be WALLY_MUSIG_SESSION_LEN. + * :param output: Destination for the allocated session. + */ +WALLY_CORE_API int wally_musig_session_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_session **output); + +/** + * Parse a partial signature from its 32-byte serialized form. + * + * :param bytes: The 32-byte serialized partial signature. + * :param bytes_len: Length of bytes. Must be WALLY_MUSIG_PARTIAL_SIG_LEN. + * :param output: Destination for the allocated partial_sig. + */ +WALLY_CORE_API int wally_musig_partial_sig_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_partial_sig **output); + +/** + * Serialize a partial signature to its 32-byte form. + * + * :param sig: The partial_sig to serialize. + * :param bytes_out: 32-byte output buffer. + * FIXED_SIZED_OUTPUT(len, bytes_out, WALLY_MUSIG_PARTIAL_SIG_LEN) + */ +WALLY_CORE_API int wally_musig_partial_sig_serialize( + const struct wally_musig_partial_sig *sig, + unsigned char *bytes_out, + size_t len); + +/** + * Free a partial signature. + * + * :param sig: The partial_sig to free. + */ +WALLY_CORE_API int wally_musig_partial_sig_free( + struct wally_musig_partial_sig *sig); + +/* --- Key aggregation functions --- */ + +/** + * Compute the MuSig2 aggregate public key from N individual public keys. + * + * :param pub_keys: Concatenated array of compressed public keys (each EC_PUBLIC_KEY_LEN bytes). + * :param pub_keys_len: Length of pub_keys. Must be a non-zero multiple of EC_PUBLIC_KEY_LEN. + * :param agg_pk_out: 32-byte buffer to receive the x-only aggregate public key. May be NULL. + * FIXED_SIZED_OUTPUT(agg_pk_out_len, agg_pk_out, EC_XONLY_PUBLIC_KEY_LEN) + * :param cache_out: Destination for the allocated keyagg_cache (required for signing). May be NULL. + */ +WALLY_CORE_API int wally_musig_pubkey_agg( + const unsigned char *pub_keys, + size_t pub_keys_len, + unsigned char *agg_pk_out, + size_t agg_pk_out_len, + struct wally_musig_keyagg_cache **cache_out); + +/** + * Extract the non-xonly (compressed) aggregate public key from a keyagg_cache. + * + * :param cache: The keyagg_cache produced by wally_musig_pubkey_agg. + * :param pub_key_out: 33-byte buffer to receive the compressed aggregate public key. + * FIXED_SIZED_OUTPUT(pub_key_out_len, pub_key_out, EC_PUBLIC_KEY_LEN) + */ +WALLY_CORE_API int wally_musig_pubkey_get( + const struct wally_musig_keyagg_cache *cache, + unsigned char *pub_key_out, + size_t pub_key_out_len); + +/** + * Apply BIP-32 plain EC tweaking to an aggregate key via the keyagg_cache. + * + * :param cache: The keyagg_cache to tweak (modified in place). + * :param tweak: 32-byte tweak value. + * :param tweak_len: Length of tweak. Must be 32. + * :param pub_key_out: 33-byte buffer for the tweaked compressed public key. May be NULL. + * FIXED_SIZED_OUTPUT(pub_key_out_len, pub_key_out, EC_PUBLIC_KEY_LEN) + */ +WALLY_CORE_API int wally_musig_pubkey_ec_tweak_add( + struct wally_musig_keyagg_cache *cache, + const unsigned char *tweak, + size_t tweak_len, + unsigned char *pub_key_out, + size_t pub_key_out_len); + +/** + * Apply BIP-341 x-only tweaking to an aggregate key via the keyagg_cache. + * + * :param cache: The keyagg_cache to tweak (modified in place). + * :param tweak: 32-byte tweak value. + * :param tweak_len: Length of tweak. Must be 32. + * :param pub_key_out: 33-byte buffer for the tweaked compressed public key. May be NULL. + * FIXED_SIZED_OUTPUT(pub_key_out_len, pub_key_out, EC_PUBLIC_KEY_LEN) + */ +WALLY_CORE_API int wally_musig_pubkey_xonly_tweak_add( + struct wally_musig_keyagg_cache *cache, + const unsigned char *tweak, + size_t tweak_len, + unsigned char *pub_key_out, + size_t pub_key_out_len); + +/** + * Construct a BIP-32 synthetic extended public key from a MuSig2 aggregate + * public key, as specified by BIP-328. + * + * The chain code is the fixed constant SHA256("MuSig2MuSig2MuSig2"). The + * resulting ext_key has depth=0, child_num=0, and no parent fingerprint. + * Unhardened BIP-32 derivation (bip32_key_from_parent with + * BIP32_FLAG_KEY_PUBLIC) is supported on the output key. Hardened derivation + * is not possible (no private key). + * + * :param agg_pk: The 33-byte compressed aggregate public key from + *| `wally_musig_pubkey_get`. Note BIP-328 requires the full key: its + *| parity affects derivation, so x-only keys are not accepted. + * :param agg_pk_len: Must be ``EC_PUBLIC_KEY_LEN``. + * :param version: BIP-32 version code. Use BIP32_VER_MAIN_PUBLIC or + * BIP32_VER_TEST_PUBLIC. + * :param output: Destination for the allocated ext_key. + */ +WALLY_CORE_API int wally_musig_pubkey_to_xpub( + const unsigned char *agg_pk, + size_t agg_pk_len, + uint32_t version, + struct ext_key **output); + +/** + * Derive child key from each xpub at child_num, sort derived pubkeys + * lexicographically (BIP-390), then aggregate. + * + * :param xpubs: Concatenated 78-byte serialized BIP-32 extended public keys. + * :param xpubs_len: Length of xpubs in bytes. Must be a multiple of + *| BIP32_SERIALIZED_LEN and at least 2 * BIP32_SERIALIZED_LEN. + * :param child_num: Unhardened child index to derive (< BIP32_INITIAL_HARDENED_CHILD). + * :param agg_pk_out: Destination for the 32-byte x-only aggregate pubkey, or NULL. + * FIXED_SIZED_OUTPUT(agg_pk_out_len, agg_pk_out, EC_XONLY_PUBLIC_KEY_LEN) + * :param cache_out: Destination for the allocated keyagg_cache, or NULL. + */ +WALLY_CORE_API int wally_musig_pubkeys_derive_then_agg( + const unsigned char *xpubs, + size_t xpubs_len, + uint32_t child_num, + unsigned char *agg_pk_out, + size_t agg_pk_out_len, + struct wally_musig_keyagg_cache **cache_out); + +/** + * Aggregate N pubkeys, construct BIP-328 synthetic xpub, then derive child_num. + * + * :param pub_keys: Concatenated 33-byte compressed public keys. + * :param pub_keys_len: Length of pub_keys. Must be a multiple of EC_PUBLIC_KEY_LEN + *| and at least 2 * EC_PUBLIC_KEY_LEN. + * :param version: BIP32_VER_MAIN_PUBLIC or BIP32_VER_TEST_PUBLIC. + * :param child_num: Unhardened child index to derive. + * :param pub_key_out: Destination for the 33-byte compressed child pubkey, or NULL. + * FIXED_SIZED_OUTPUT(pub_key_out_len, pub_key_out, EC_PUBLIC_KEY_LEN) + * :param child_out: Destination for the allocated child ext_key, or NULL. + */ +WALLY_CORE_API int wally_musig_pubkeys_agg_then_derive( + const unsigned char *pub_keys, + size_t pub_keys_len, + uint32_t version, + uint32_t child_num, + unsigned char *pub_key_out, + size_t pub_key_out_len, + struct ext_key **child_out); + +/* --- Nonce generation and aggregation functions --- */ + +/** + * Generate a MuSig2 secret/public nonce pair. + * + * :param session_secrand32: 32-byte unique random session ID. MUST NOT be reused. + *| It is not modified, so the caller should wipe it once the nonce is generated. + * :param session_secrand32_len: Must be 32. + * :param seckey: Secret key of the signer (optional, can be NULL). + * :param seckey_len: Must be ``EC_PRIVATE_KEY_LEN`` if seckey is non-NULL, 0 otherwise. + * :param pub_key: 33-byte compressed public key of this signer (required). + * :param pub_key_len: Must be ``EC_PUBLIC_KEY_LEN``. + * :param keyagg_cache: keyagg_cache from wally_musig_pubkey_agg (optional, can be NULL). + * :param msg32: 32-byte message to be signed, if known (optional, can be NULL). + * :param msg32_len: Must be ``EC_MESSAGE_HASH_LEN`` if msg32 is non-NULL, 0 otherwise. + * :param extra_input32: 32-byte extra entropy input (optional, can be NULL). + * :param extra_input32_len: Must be 32 if extra_input32 is non-NULL, 0 otherwise. + * :param secnonce_out: Destination for the allocated secret nonce. Must be kept secret. + * :param pubnonce_out: Destination for the allocated public nonce to send to cosigners. + */ +WALLY_CORE_API int wally_musig_nonce_gen( + const unsigned char *session_secrand32, + size_t session_secrand32_len, + const unsigned char *seckey, + size_t seckey_len, + const unsigned char *pub_key, + size_t pub_key_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + const unsigned char *msg32, + size_t msg32_len, + const unsigned char *extra_input32, + size_t extra_input32_len, + struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out); + +/** + * Generate a MuSig2 secret/public nonce pair using a counter-based session ID. + * + * WARNING: Nonce reuse in MuSig2 is catastrophic. Calling this function with + * the same (counter, seckey) pair more than once - across calls, sessions, or + * process restarts - leaks the private key. The counter MUST be stored durably + * and incremented before each signing session. See BIP-327 "Nonce generation", + * "Synthetic nonces". Prefer wally_musig_nonce_gen() for non-hardware-wallet use. + * + * This variant is intended for hardware wallets or deterministic signers that + * cannot generate random session IDs. The uint64_t counter is serialized as an + * 8-byte little-endian value, zero-padded to 32 bytes, and used as the + * session_id32. Per BIP-327, seckey MUST be provided when using a counter. + * + * :param counter: Monotonically increasing counter. Reuse with the same seckey + * leaks the private key. Persist and increment in durable storage. + * :param seckey: Secret key of the signer (REQUIRED for counter mode). + * :param seckey_len: Must be ``EC_PRIVATE_KEY_LEN``. + * :param pub_key: 33-byte compressed public key of this signer (required). + *| Must match the public key of ``seckey`` or `WALLY_EINVAL` is returned. + * :param pub_key_len: Must be ``EC_PUBLIC_KEY_LEN``. + * :param keyagg_cache: keyagg_cache from wally_musig_pubkey_agg (optional, can be NULL). + * :param msg32: 32-byte message to be signed, if known (optional, can be NULL). + * :param msg32_len: Must be ``EC_MESSAGE_HASH_LEN`` if msg32 is non-NULL, 0 otherwise. + * :param extra_input32: 32-byte extra entropy input (optional, can be NULL). + * :param extra_input32_len: Must be 32 if extra_input32 is non-NULL, 0 otherwise. + * :param secnonce_out: Destination for the allocated secret nonce. Must be kept secret. + * :param pubnonce_out: Destination for the allocated public nonce to send to cosigners. + */ +WALLY_CORE_API int wally_musig_nonce_gen_counter( + uint64_t counter, + const unsigned char *seckey, + size_t seckey_len, + const unsigned char *pub_key, + size_t pub_key_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + const unsigned char *msg32, + size_t msg32_len, + const unsigned char *extra_input32, + size_t extra_input32_len, + struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out); + +/** + * Aggregate N serialized public nonces into a single aggregate nonce. + * + * :param pubnonces: Flat array of serialized pubnonces (each WALLY_MUSIG_PUBNONCE_LEN bytes). + * :param pubnonces_len: Total byte length. Must equal n_pubnonces * WALLY_MUSIG_PUBNONCE_LEN. + * :param n_pubnonces: Number of pubnonces. Must be >= 2. + * :param aggnonce_out: Destination for the allocated aggregate nonce. + */ +WALLY_CORE_API int wally_musig_nonce_agg( + const unsigned char *pubnonces, + size_t pubnonces_len, + size_t n_pubnonces, + struct wally_musig_aggnonce **aggnonce_out); + +/* --- Signing and verification functions --- */ + +/** + * Process the aggregate nonce and message to create a signing session. + * + * Must be called by every participant after nonce aggregation and before signing. + * + * :param aggnonce: The aggregate nonce from wally_musig_nonce_agg. + * :param msg32: The 32-byte message to sign. + * :param msg32_len: Must be 32. + * :param cache: The keyagg_cache from wally_musig_pubkey_agg (and optional tweaks). + * :param adaptor: Optional 33-byte compressed adaptor public key (can be NULL). + * :param adaptor_len: Must be EC_PUBLIC_KEY_LEN if adaptor is non-NULL, 0 otherwise. + * :param session_out: Destination for the allocated session. + */ +WALLY_CORE_API int wally_musig_nonce_process( + const struct wally_musig_aggnonce *aggnonce, + const unsigned char *msg32, + size_t msg32_len, + const struct wally_musig_keyagg_cache *cache, + const unsigned char *adaptor, + size_t adaptor_len, + struct wally_musig_session **session_out); + +/** + * Produce a partial signature for this participant. + * + * WARNING: The secnonce is irrevocably zeroed whenever secp256k1_musig_partial_sign + * is reached (i.e., when WALLY_OK or WALLY_ERROR is returned). Input validation + * failures (WALLY_EINVAL) do not consume the secnonce. Never attempt to sign + * twice with the same secnonce. WALLY_EINVAL is returned if ``seckey`` is not + * the key the secnonce was generated for, or if the secnonce has been used. + * The partial signature is verified after signing, and WALLY_ERROR is returned + * if it fails to verify. + * + * :param secnonce: The secret nonce from wally_musig_nonce_gen (zeroed after use). + * :param seckey: The 32-byte secret key of this signer. + * :param seckey_len: Must be 32. + * :param cache: The keyagg_cache from wally_musig_pubkey_agg. + * :param session: The session from wally_musig_nonce_process. + * :param partial_sig_out: Destination for the allocated partial signature. + */ +WALLY_CORE_API int wally_musig_partial_sign( + struct wally_musig_secnonce *secnonce, + const unsigned char *seckey, + size_t seckey_len, + const struct wally_musig_keyagg_cache *cache, + const struct wally_musig_session *session, + struct wally_musig_partial_sig **partial_sig_out); + +/** + * Verify a partial signature from one participant. + * + * Returns WALLY_OK if valid, WALLY_ERROR if the signature is invalid, + * WALLY_EINVAL for bad arguments. + * + * :param sig: The partial signature to verify. + * :param pubnonce: The signer's public nonce (from round 1). + * :param pub_key: The signer's 33-byte compressed public key. + * :param pub_key_len: Must be ``EC_PUBLIC_KEY_LEN``. + * :param cache: The keyagg_cache from wally_musig_pubkey_agg. + * :param session: The session from wally_musig_nonce_process. + */ +WALLY_CORE_API int wally_musig_partial_sig_verify( + const struct wally_musig_partial_sig *sig, + const struct wally_musig_pubnonce *pubnonce, + const unsigned char *pub_key, + size_t pub_key_len, + const struct wally_musig_keyagg_cache *cache, + const struct wally_musig_session *session); + +/** + * Aggregate N partial signatures into a final 64-byte BIP-340 Schnorr signature. + * + * :param partial_sigs: Flat array of serialized partial signatures + * (each WALLY_MUSIG_PARTIAL_SIG_LEN bytes). + * :param partial_sigs_len: Total byte length. Must equal n_sigs * WALLY_MUSIG_PARTIAL_SIG_LEN. + * :param n_sigs: Number of partial signatures. Must be >= 2. + * :param session: The session from wally_musig_nonce_process. + * :param sig64_out: 64-byte buffer to receive the final Schnorr signature. + * FIXED_SIZED_OUTPUT(sig64_out_len, sig64_out, EC_SIGNATURE_LEN) + */ +WALLY_CORE_API int wally_musig_partial_sig_agg( + const unsigned char *partial_sigs, + size_t partial_sigs_len, + size_t n_sigs, + const struct wally_musig_session *session, + unsigned char *sig64_out, + size_t sig64_out_len); + +#endif /* ndef BUILD_STANDARD_SECP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LIBWALLY_CORE_MUSIG_H */ diff --git a/src/Makefile.am b/src/Makefile.am index f676581cc..d617ceda7 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -19,6 +19,7 @@ include_HEADERS += $(top_srcdir)/include/wally_crypto.h include_HEADERS += $(top_srcdir)/include/wally_descriptor.h include_HEADERS += $(top_srcdir)/include/wally_elements.h include_HEADERS += $(top_srcdir)/include/wally_map.h +include_HEADERS += $(top_srcdir)/include/wally_musig.h include_HEADERS += $(top_srcdir)/include/wally_psbt.h include_HEADERS += $(top_srcdir)/include/wally_psbt_members.h include_HEADERS += $(top_srcdir)/include/wally_script.h @@ -162,6 +163,7 @@ libwallycore_la_SOURCES = \ miniscript_decode.c \ miniscript_satisfy.c \ mnemonic.c \ + musig.c \ pbkdf2.c \ psbt.c \ pullpush.c \ @@ -194,6 +196,7 @@ libwallycore_la_INCLUDES = \ include/wally_descriptor.h \ include/wally_elements.h \ include/wally_map.h \ + include/wally_musig.h \ include/wally_psbt.h \ include/wally_psbt_members.h \ include/wally_script.h \ @@ -375,6 +378,8 @@ check-libwallycore: $(PYTHON_TEST_DEPS) $(AM_V_at)$(PYTHON_TEST) test/test_internal.py $(AM_V_at)$(PYTHON_TEST) test/test_map.py $(AM_V_at)$(PYTHON_TEST) test/test_mnemonic.py + $(AM_V_at)$(PYTHON_TEST) test/test_musig.py + $(AM_V_at)$(PYTHON_TEST) test/test_musig_vectors.py $(AM_V_at)$(PYTHON_TEST) test/test_psbt.py $(AM_V_at)$(PYTHON_TEST) test/test_pbkdf2.py $(AM_V_at)$(PYTHON_TEST) test/test_script.py @@ -402,6 +407,7 @@ check-swig-python: check-libwallycore check-swig-java $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/coinselection.py $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/descriptor.py $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/mnemonic.py + $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/musig.py $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/psbt.py $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/sha.py $(AM_V_at)$(top_builddir)/venv/bin/python swig_python/contrib/signmessage.py diff --git a/src/amalgamation/combined.c b/src/amalgamation/combined.c index e956bc6d5..2a60195af 100644 --- a/src/amalgamation/combined.c +++ b/src/amalgamation/combined.c @@ -5,6 +5,13 @@ #define ENABLE_MODULE_ECDH 1 #define ENABLE_MODULE_EXTRAKEYS 1 #define ENABLE_MODULE_SCHNORRSIG 1 +/* MuSig2 follows the standard --enable-standard-secp / -DBUILD_STANDARD_SECP + * knob: enabled here by default, dropped when a consumer defines + * BUILD_STANDARD_SECP (which also compiles out wally's musig/s2c/anti-exfil + * layers). Taproot (schnorr/bip341) is unaffected either way. */ +#ifndef BUILD_STANDARD_SECP +#define ENABLE_MODULE_MUSIG 1 +#endif #define ENABLE_MODULE_GENERATOR 1 #define ENABLE_MODULE_ECDSA_S2C 1 #define ENABLE_MODULE_RECOVERY 1 @@ -71,6 +78,7 @@ #include "src/miniscript_decode.c" #include "src/miniscript_satisfy.c" #include "src/mnemonic.c" +#include "src/musig.c" #include "src/pbkdf2.c" #include "src/pullpush.c" #include "src/psbt.c" diff --git a/src/data/bip327/det_sign_vectors.json b/src/data/bip327/det_sign_vectors.json new file mode 100644 index 000000000..261669ccd --- /dev/null +++ b/src/data/bip327/det_sign_vectors.json @@ -0,0 +1,144 @@ +{ + "sk": "7FB9E0E687ADA1EEBF7ECFE2F21E73EBDB51A7D450948DFE8D76D7F2D1007671", + "pubkeys": [ + "03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", + "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659", + "020000000000000000000000000000000000000000000000000000000000000007" + ], + "msgs": [ + "F95466D086770E689964664219266FE5ED215C92AE20BAB5C9D79ADDDDF3C0CF", + "2626262626262626262626262626262626262626262626262626262626262626262626262626" + ], + "valid_test_cases": [ + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [0, 1, 2], + "tweaks": [], + "is_xonly": [], + "msg_index": 0, + "signer_index": 0, + "expected": [ + "03D96275257C2FCCBB6EEB77BDDF51D3C88C26EE1626C6CDA8999B9D34F4BA13A60309BE2BF883C6ABE907FA822D9CA166D51A3DCC28910C57528F6983FC378B7843", + "41EA65093F71D084785B20DC26A887CD941C9597860A21660CBDB9CC2113CAD3" + ] + }, + { + "rand": null, + "aggothernonce": "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [1, 0, 2], + "tweaks": [], + "is_xonly": [], + "msg_index": 0, + "signer_index": 1, + "expected": [ + "028FBCCF5BB73A7B61B270BAD15C0F9475D577DD85C2157C9D38BEF1EC922B48770253BE3638C87369BC287E446B7F2C8CA5BEB9FFBD1EA082C62913982A65FC214D", + "AEAA31262637BFA88D5606679018A0FEEEC341F3107D1199857F6C81DE61B8DD" + ] + }, + { + "rand": "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + "aggothernonce": "0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F817980279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "key_indices": [1, 2, 0], + "tweaks": [], + "is_xonly": [], + "msg_index": 1, + "signer_index": 2, + "expected": [ + "024FA8D774F0C8743FAA77AFB4D08EE5A013C2E8EEAD8A6F08A77DDD2D28266DB803050905E8C994477F3F2981861A2E3791EF558626E645FBF5AA131C5D6447C2C2", + "FEE28A56B8556B7632E42A84122C51A4861B1F2DEC7E81B632195E56A52E3E13" + ], + "comment": "Message longer than 32 bytes" + }, + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "032DE2662628C90B03F5E720284EB52FF7D71F4284F627B68A853D78C78E1FFE9303E4C5524E83FFE1493B9077CF1CA6BEB2090C93D930321071AD40B2F44E599046", + "key_indices": [0, 1, 2], + "tweaks": ["E8F791FF9225A2AF0102AFFF4A9A723D9612A682A25EBE79802B263CDFCD83BB"], + "is_xonly": [true], + "msg_index": 0, + "signer_index": 0, + "expected": [ + "031E07C0D11A0134E55DB1FC16095ADCBD564236194374AA882BFB3C78273BF673039D0336E8CA6288C00BFC1F8B594563529C98661172B9BC1BE85C23A4CE1F616B", + "7B1246C5889E59CB0375FA395CC86AC42D5D7D59FD8EAB4FDF1DCAB2B2F006EA" + ], + "comment": "Tweaked public key" + } + ], + "error_test_cases": [ + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [1, 0, 3], + "tweaks": [], + "is_xonly": [], + "msg_index": 0, + "signer_index": 1, + "error": { + "type": "invalid_contribution", + "signer": 2, + "contrib": "pubkey" + }, + "comment": "Signer 2 provided an invalid public key" + }, + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [1, 2], + "tweaks": [], + "is_xonly": [], + "msg_index": 0, + "signer_index": 1, + "error": { + "type": "value", + "message": "The signer's pubkey must be included in the list of pubkeys." + }, + "comment": "The signers pubkey is not in the list of pubkeys" + }, + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "0437C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [1, 2, 0], + "tweaks": [], + "is_xonly": [], + "msg_index": 0, + "signer_index": 2, + "error": { + "type": "invalid_contribution", + "signer": null, + "contrib": "aggothernonce" + }, + "comment": "aggothernonce is invalid due wrong tag, 0x04, in the first half" + }, + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "0000000000000000000000000000000000000000000000000000000000000000000287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [1, 2, 0], + "tweaks": [], + "is_xonly": [], + "msg_index": 0, + "signer_index": 2, + "error": { + "type": "invalid_contribution", + "signer": null, + "contrib": "aggothernonce" + }, + "comment": "aggothernonce is invalid because first half corresponds to point at infinity" + }, + { + "rand": "0000000000000000000000000000000000000000000000000000000000000000", + "aggothernonce": "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "key_indices": [1, 2, 0], + "tweaks": ["FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"], + "is_xonly": [false], + "msg_index": 0, + "signer_index": 2, + "error": { + "type": "value", + "message": "The tweak must be less than n." + }, + "comment": "Tweak is invalid because it exceeds group size" + } + ] +} diff --git a/src/data/bip327/key_agg_vectors.json b/src/data/bip327/key_agg_vectors.json new file mode 100644 index 000000000..b2e623de6 --- /dev/null +++ b/src/data/bip327/key_agg_vectors.json @@ -0,0 +1,88 @@ +{ + "pubkeys": [ + "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "03DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659", + "023590A94E768F8E1815C2F24B4D80A8E3149316C3518CE7B7AD338368D038CA66", + "020000000000000000000000000000000000000000000000000000000000000005", + "02FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30", + "04F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9" + ], + "tweaks": [ + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", + "252E4BD67410A76CDF933D30EAA1608214037F1B105A013ECCD3C5C184A6110B" + ], + "valid_test_cases": [ + { + "key_indices": [0, 1, 2], + "expected": "90539EEDE565F5D054F32CC0C220126889ED1E5D193BAF15AEF344FE59D4610C" + }, + { + "key_indices": [2, 1, 0], + "expected": "6204DE8B083426DC6EAF9502D27024D53FC826BF7D2012148A0575435DF54B2B" + }, + { + "key_indices": [0, 0, 0], + "expected": "B436E3BAD62B8CD409969A224731C193D051162D8C5AE8B109306127DA3AA935" + }, + { + "key_indices": [0, 0, 1, 1], + "expected": "69BC22BFA5D106306E48A20679DE1D7389386124D07571D0D872686028C26A3E" + } + ], + "error_test_cases": [ + { + "key_indices": [0, 3], + "tweak_indices": [], + "is_xonly": [], + "error": { + "type": "invalid_contribution", + "signer": 1, + "contrib": "pubkey" + }, + "comment": "Invalid public key" + }, + { + "key_indices": [0, 4], + "tweak_indices": [], + "is_xonly": [], + "error": { + "type": "invalid_contribution", + "signer": 1, + "contrib": "pubkey" + }, + "comment": "Public key exceeds field size" + }, + { + "key_indices": [5, 0], + "tweak_indices": [], + "is_xonly": [], + "error": { + "type": "invalid_contribution", + "signer": 0, + "contrib": "pubkey" + }, + "comment": "First byte of public key is not 2 or 3" + }, + { + "key_indices": [0, 1], + "tweak_indices": [0], + "is_xonly": [true], + "error": { + "type": "value", + "message": "The tweak must be less than n." + }, + "comment": "Tweak is out of range" + }, + { + "key_indices": [6], + "tweak_indices": [1], + "is_xonly": [false], + "error": { + "type": "value", + "message": "The result of tweaking cannot be infinity." + }, + "comment": "Intermediate tweaking result is point at infinity" + } + ] +} diff --git a/src/data/bip327/nonce_agg_vectors.json b/src/data/bip327/nonce_agg_vectors.json new file mode 100644 index 000000000..1c04b8818 --- /dev/null +++ b/src/data/bip327/nonce_agg_vectors.json @@ -0,0 +1,51 @@ +{ + "pnonces": [ + "020151C80F435648DF67A22B749CD798CE54E0321D034B92B709B567D60A42E66603BA47FBC1834437B3212E89A84D8425E7BF12E0245D98262268EBDCB385D50641", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60248C264CDD57D3C24D79990B0F865674EB62A0F9018277A95011B41BFC193B833", + "020151C80F435648DF67A22B749CD798CE54E0321D034B92B709B567D60A42E6660279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60379BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "04FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60248C264CDD57D3C24D79990B0F865674EB62A0F9018277A95011B41BFC193B833", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A60248C264CDD57D3C24D79990B0F865674EB62A0F9018277A95011B41BFC193B831", + "03FF406FFD8ADB9CD29877E4985014F66A59F6CD01C0E88CAA8E5F3166B1F676A602FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30" + ], + "valid_test_cases": [ + { + "pnonce_indices": [0, 1], + "expected": "035FE1873B4F2967F52FEA4A06AD5A8ECCBE9D0FD73068012C894E2E87CCB5804B024725377345BDE0E9C33AF3C43C0A29A9249F2F2956FA8CFEB55C8573D0262DC8" + }, + { + "pnonce_indices": [2, 3], + "expected": "035FE1873B4F2967F52FEA4A06AD5A8ECCBE9D0FD73068012C894E2E87CCB5804B000000000000000000000000000000000000000000000000000000000000000000", + "comment": "Sum of second points encoded in the nonces is point at infinity which is serialized as 33 zero bytes" + } + ], + "error_test_cases": [ + { + "pnonce_indices": [0, 4], + "error": { + "type": "invalid_contribution", + "signer": 1, + "contrib": "pubnonce" + }, + "comment": "Public nonce from signer 1 is invalid due wrong tag, 0x04, in the first half" + }, + { + "pnonce_indices": [5, 1], + "error": { + "type": "invalid_contribution", + "signer": 0, + "contrib": "pubnonce" + }, + "comment": "Public nonce from signer 0 is invalid because the second half does not correspond to an X coordinate" + }, + { + "pnonce_indices": [6, 1], + "error": { + "type": "invalid_contribution", + "signer": 0, + "contrib": "pubnonce" + }, + "comment": "Public nonce from signer 0 is invalid because second half exceeds field size" + } + ] +} diff --git a/src/data/bip327/nonce_gen_vectors.json b/src/data/bip327/nonce_gen_vectors.json new file mode 100644 index 000000000..ced946f3e --- /dev/null +++ b/src/data/bip327/nonce_gen_vectors.json @@ -0,0 +1,44 @@ +{ + "test_cases": [ + { + "rand_": "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "sk": "0202020202020202020202020202020202020202020202020202020202020202", + "pk": "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "aggpk": "0707070707070707070707070707070707070707070707070707070707070707", + "msg": "0101010101010101010101010101010101010101010101010101010101010101", + "extra_in": "0808080808080808080808080808080808080808080808080808080808080808", + "expected_secnonce": "B114E502BEAA4E301DD08A50264172C84E41650E6CB726B410C0694D59EFFB6495B5CAF28D045B973D63E3C99A44B807BDE375FD6CB39E46DC4A511708D0E9D2024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "expected_pubnonce": "02F7BE7089E8376EB355272368766B17E88E7DB72047D05E56AA881EA52B3B35DF02C29C8046FDD0DED4C7E55869137200FBDBFE2EB654267B6D7013602CAED3115A" + }, + { + "rand_": "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "sk": "0202020202020202020202020202020202020202020202020202020202020202", + "pk": "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "aggpk": "0707070707070707070707070707070707070707070707070707070707070707", + "msg": "", + "extra_in": "0808080808080808080808080808080808080808080808080808080808080808", + "expected_secnonce": "E862B068500320088138468D47E0E6F147E01B6024244AE45EAC40ACE5929B9F0789E051170B9E705D0B9EB49049A323BBBBB206D8E05C19F46C6228742AA7A9024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "expected_pubnonce": "023034FA5E2679F01EE66E12225882A7A48CC66719B1B9D3B6C4DBD743EFEDA2C503F3FD6F01EB3A8E9CB315D73F1F3D287CAFBB44AB321153C6287F407600205109" + }, + { + "rand_": "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "sk": "0202020202020202020202020202020202020202020202020202020202020202", + "pk": "024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "aggpk": "0707070707070707070707070707070707070707070707070707070707070707", + "msg": "2626262626262626262626262626262626262626262626262626262626262626262626262626", + "extra_in": "0808080808080808080808080808080808080808080808080808080808080808", + "expected_secnonce": "3221975ACBDEA6820EABF02A02B7F27D3A8EF68EE42787B88CBEFD9AA06AF3632EE85B1A61D8EF31126D4663A00DD96E9D1D4959E72D70FE5EBB6E7696EBA66F024D4B6CD1361032CA9BD2AEB9D900AA4D45D9EAD80AC9423374C451A7254D0766", + "expected_pubnonce": "02E5BBC21C69270F59BD634FCBFA281BE9D76601295345112C58954625BF23793A021307511C79F95D38ACACFF1B4DA98228B77E65AA216AD075E9673286EFB4EAF3" + }, + { + "rand_": "0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F", + "sk": null, + "pk": "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "aggpk": null, + "msg": null, + "extra_in": null, + "expected_secnonce": "89BDD787D0284E5E4D5FC572E49E316BAB7E21E3B1830DE37DFE80156FA41A6D0B17AE8D024C53679699A6FD7944D9C4A366B514BAF43088E0708B1023DD289702F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "expected_pubnonce": "02C96E7CB1E8AA5DAC64D872947914198F607D90ECDE5200DE52978AD5DED63C000299EC5117C2D29EDEE8A2092587C3909BE694D5CFF0667D6C02EA4059F7CD9786" + } + ] +} diff --git a/src/data/bip327/sig_agg_vectors.json b/src/data/bip327/sig_agg_vectors.json new file mode 100644 index 000000000..519562c34 --- /dev/null +++ b/src/data/bip327/sig_agg_vectors.json @@ -0,0 +1,152 @@ +{ + "pubkeys": [ + "03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", + "02D2DC6F5DF7C56ACF38C7FA0AE7A759AE30E19B37359DFDE015872324C7EF6E05", + "03C7FB101D97FF930ACD0C6760852EF64E69083DE0B06AC6335724754BB4B0522C", + "02352433B21E7E05D3B452B81CAE566E06D2E003ECE16D1074AABA4289E0E3D581" + ], + "pnonces": [ + "036E5EE6E28824029FEA3E8A9DDD2C8483F5AF98F7177C3AF3CB6F47CAF8D94AE902DBA67E4A1F3680826172DA15AFB1A8CA85C7C5CC88900905C8DC8C328511B53E", + "03E4F798DA48A76EEC1C9CC5AB7A880FFBA201A5F064E627EC9CB0031D1D58FC5103E06180315C5A522B7EC7C08B69DCD721C313C940819296D0A7AB8E8795AC1F00", + "02C0068FD25523A31578B8077F24F78F5BD5F2422AFF47C1FADA0F36B3CEB6C7D202098A55D1736AA5FCC21CF0729CCE852575C06C081125144763C2C4C4A05C09B6", + "031F5C87DCFBFCF330DEE4311D85E8F1DEA01D87A6F1C14CDFC7E4F1D8C441CFA40277BF176E9F747C34F81B0D9F072B1B404A86F402C2D86CF9EA9E9C69876EA3B9", + "023F7042046E0397822C4144A17F8B63D78748696A46C3B9F0A901D296EC3406C302022B0B464292CF9751D699F10980AC764E6F671EFCA15069BBE62B0D1C62522A", + "02D97DDA5988461DF58C5897444F116A7C74E5711BF77A9446E27806563F3B6C47020CBAD9C363A7737F99FA06B6BE093CEAFF5397316C5AC46915C43767AE867C00" + ], + "tweaks": [ + "B511DA492182A91B0FFB9A98020D55F260AE86D7ECBD0399C7383D59A5F2AF7C", + "A815FE049EE3C5AAB66310477FBC8BCCCAC2F3395F59F921C364ACD78A2F48DC", + "75448A87274B056468B977BE06EB1E9F657577B7320B0A3376EA51FD420D18A8" + ], + "psigs": [ + "B15D2CD3C3D22B04DAE438CE653F6B4ECF042F42CFDED7C41B64AAF9B4AF53FB", + "6193D6AC61B354E9105BBDC8937A3454A6D705B6D57322A5A472A02CE99FCB64", + "9A87D3B79EC67228CB97878B76049B15DBD05B8158D17B5B9114D3C226887505", + "66F82EA90923689B855D36C6B7E032FB9970301481B99E01CDB4D6AC7C347A15", + "4F5AEE41510848A6447DCD1BBC78457EF69024944C87F40250D3EF2C25D33EFE", + "DDEF427BBB847CC027BEFF4EDB01038148917832253EBC355FC33F4A8E2FCCE4", + "97B890A26C981DA8102D3BC294159D171D72810FDF7C6A691DEF02F0F7AF3FDC", + "53FA9E08BA5243CBCB0D797C5EE83BC6728E539EB76C2D0BF0F971EE4E909971", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141" + ], + "msg": "599C67EA410D005B9DA90817CF03ED3B1C868E4DA4EDF00A5880B0082C237869", + "valid_test_cases": [ + { + "aggnonce": "0341432722C5CD0268D829C702CF0D1CBCE57033EED201FD335191385227C3210C03D377F2D258B64AADC0E16F26462323D701D286046A2EA93365656AFD9875982B", + "nonce_indices": [ + 0, + 1 + ], + "key_indices": [ + 0, + 1 + ], + "tweak_indices": [], + "is_xonly": [], + "psig_indices": [ + 0, + 1 + ], + "expected": "041DA22223CE65C92C9A0D6C2CAC828AAF1EEE56304FEC371DDF91EBB2B9EF0912F1038025857FEDEB3FF696F8B99FA4BB2C5812F6095A2E0004EC99CE18DE1E" + }, + { + "aggnonce": "0224AFD36C902084058B51B5D36676BBA4DC97C775873768E58822F87FE437D792028CB15929099EEE2F5DAE404CD39357591BA32E9AF4E162B8D3E7CB5EFE31CB20", + "nonce_indices": [ + 0, + 2 + ], + "key_indices": [ + 0, + 2 + ], + "tweak_indices": [], + "is_xonly": [], + "psig_indices": [ + 2, + 3 + ], + "expected": "1069B67EC3D2F3C7C08291ACCB17A9C9B8F2819A52EB5DF8726E17E7D6B52E9F01800260A7E9DAC450F4BE522DE4CE12BA91AEAF2B4279219EF74BE1D286ADD9" + }, + { + "aggnonce": "0208C5C438C710F4F96A61E9FF3C37758814B8C3AE12BFEA0ED2C87FF6954FF186020B1816EA104B4FCA2D304D733E0E19CEAD51303FF6420BFD222335CAA402916D", + "nonce_indices": [ + 0, + 3 + ], + "key_indices": [ + 0, + 2 + ], + "tweak_indices": [ + 0 + ], + "is_xonly": [ + false + ], + "psig_indices": [ + 4, + 5 + ], + "expected": "5C558E1DCADE86DA0B2F02626A512E30A22CF5255CAEA7EE32C38E9A71A0E9148BA6C0E6EC7683B64220F0298696F1B878CD47B107B81F7188812D593971E0CC" + }, + { + "aggnonce": "02B5AD07AFCD99B6D92CB433FBD2A28FDEB98EAE2EB09B6014EF0F8197CD58403302E8616910F9293CF692C49F351DB86B25E352901F0E237BAFDA11F1C1CEF29FFD", + "nonce_indices": [ + 0, + 4 + ], + "key_indices": [ + 0, + 3 + ], + "tweak_indices": [ + 0, + 1, + 2 + ], + "is_xonly": [ + true, + false, + true + ], + "psig_indices": [ + 6, + 7 + ], + "expected": "839B08820B681DBA8DAF4CC7B104E8F2638F9388F8D7A555DC17B6E6971D7426CE07BF6AB01F1DB50E4E33719295F4094572B79868E440FB3DEFD3FAC1DB589E" + } + ], + "error_test_cases": [ + { + "aggnonce": "02B5AD07AFCD99B6D92CB433FBD2A28FDEB98EAE2EB09B6014EF0F8197CD58403302E8616910F9293CF692C49F351DB86B25E352901F0E237BAFDA11F1C1CEF29FFD", + "nonce_indices": [ + 0, + 4 + ], + "key_indices": [ + 0, + 3 + ], + "tweak_indices": [ + 0, + 1, + 2 + ], + "is_xonly": [ + true, + false, + true + ], + "psig_indices": [ + 7, + 8 + ], + "error": { + "type": "invalid_contribution", + "signer": 1, + "contrib": "psig" + }, + "comment": "Partial signature is invalid because it exceeds group size" + } + ] +} diff --git a/src/data/bip327/sign_verify_vectors.json b/src/data/bip327/sign_verify_vectors.json new file mode 100644 index 000000000..f71c8dd9d --- /dev/null +++ b/src/data/bip327/sign_verify_vectors.json @@ -0,0 +1,212 @@ +{ + "sk": "7FB9E0E687ADA1EEBF7ECFE2F21E73EBDB51A7D450948DFE8D76D7F2D1007671", + "pubkeys": [ + "03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", + "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA661", + "020000000000000000000000000000000000000000000000000000000000000007" + ], + "secnonces": [ + "508B81A611F100A6B2B6B29656590898AF488BCF2E1F55CF22E5CFB84421FE61FA27FD49B1D50085B481285E1CA205D55C82CC1B31FF5CD54A489829355901F703935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9" + ], + "pnonces": [ + "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F817980279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "032DE2662628C90B03F5E720284EB52FF7D71F4284F627B68A853D78C78E1FFE9303E4C5524E83FFE1493B9077CF1CA6BEB2090C93D930321071AD40B2F44E599046", + "0237C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0387BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "0200000000000000000000000000000000000000000000000000000000000000090287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480" + ], + "aggnonces": [ + "028465FCF0BBDBCF443AABCCE533D42B4B5A10966AC09A49655E8C42DAAB8FCD61037496A3CC86926D452CAFCFD55D25972CA1675D549310DE296BFF42F72EEEA8C9", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "048465FCF0BBDBCF443AABCCE533D42B4B5A10966AC09A49655E8C42DAAB8FCD61037496A3CC86926D452CAFCFD55D25972CA1675D549310DE296BFF42F72EEEA8C9", + "028465FCF0BBDBCF443AABCCE533D42B4B5A10966AC09A49655E8C42DAAB8FCD61020000000000000000000000000000000000000000000000000000000000000009", + "028465FCF0BBDBCF443AABCCE533D42B4B5A10966AC09A49655E8C42DAAB8FCD6102FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30" + ], + "msgs": [ + "F95466D086770E689964664219266FE5ED215C92AE20BAB5C9D79ADDDDF3C0CF", + "", + "2626262626262626262626262626262626262626262626262626262626262626262626262626" + ], + "valid_test_cases": [ + { + "key_indices": [0, 1, 2], + "nonce_indices": [0, 1, 2], + "aggnonce_index": 0, + "msg_index": 0, + "signer_index": 0, + "expected": "012ABBCB52B3016AC03AD82395A1A415C48B93DEF78718E62A7A90052FE224FB" + }, + { + "key_indices": [1, 0, 2], + "nonce_indices": [1, 0, 2], + "aggnonce_index": 0, + "msg_index": 0, + "signer_index": 1, + "expected": "9FF2F7AAA856150CC8819254218D3ADEEB0535269051897724F9DB3789513A52" + }, + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "aggnonce_index": 0, + "msg_index": 0, + "signer_index": 2, + "expected": "FA23C359F6FAC4E7796BB93BC9F0532A95468C539BA20FF86D7C76ED92227900" + }, + { + "key_indices": [0, 1], + "nonce_indices": [0, 3], + "aggnonce_index": 1, + "msg_index": 0, + "signer_index": 0, + "expected": "AE386064B26105404798F75DE2EB9AF5EDA5387B064B83D049CB7C5E08879531", + "comment": "Both halves of aggregate nonce correspond to point at infinity" + }, + { + "key_indices": [0, 1, 2], + "nonce_indices": [0, 1, 2], + "aggnonce_index": 0, + "msg_index": 1, + "signer_index": 0, + "expected": "D7D63FFD644CCDA4E62BC2BC0B1D02DD32A1DC3030E155195810231D1037D82D", + "comment": "Empty message" + }, + { + "key_indices": [0, 1, 2], + "nonce_indices": [0, 1, 2], + "aggnonce_index": 0, + "msg_index": 2, + "signer_index": 0, + "expected": "E184351828DA5094A97C79CABDAAA0BFB87608C32E8829A4DF5340A6F243B78C", + "comment": "38-byte message" + } + ], + "sign_error_test_cases": [ + { + "key_indices": [1, 2], + "aggnonce_index": 0, + "msg_index": 0, + "secnonce_index": 0, + "error": { + "type": "value", + "message": "The signer's pubkey must be included in the list of pubkeys." + }, + "comment": "The signers pubkey is not in the list of pubkeys. This test case is optional: it can be skipped by implementations that do not check that the signer's pubkey is included in the list of pubkeys." + }, + { + "key_indices": [1, 0, 3], + "aggnonce_index": 0, + "msg_index": 0, + "secnonce_index": 0, + "error": { + "type": "invalid_contribution", + "signer": 2, + "contrib": "pubkey" + }, + "comment": "Signer 2 provided an invalid public key" + }, + { + "key_indices": [1, 2, 0], + "aggnonce_index": 2, + "msg_index": 0, + "secnonce_index": 0, + "error": { + "type": "invalid_contribution", + "signer": null, + "contrib": "aggnonce" + }, + "comment": "Aggregate nonce is invalid due wrong tag, 0x04, in the first half" + }, + { + "key_indices": [1, 2, 0], + "aggnonce_index": 3, + "msg_index": 0, + "secnonce_index": 0, + "error": { + "type": "invalid_contribution", + "signer": null, + "contrib": "aggnonce" + }, + "comment": "Aggregate nonce is invalid because the second half does not correspond to an X coordinate" + }, + { + "key_indices": [1, 2, 0], + "aggnonce_index": 4, + "msg_index": 0, + "secnonce_index": 0, + "error": { + "type": "invalid_contribution", + "signer": null, + "contrib": "aggnonce" + }, + "comment": "Aggregate nonce is invalid because second half exceeds field size" + }, + { + "key_indices": [0, 1, 2], + "aggnonce_index": 0, + "msg_index": 0, + "signer_index": 0, + "secnonce_index": 1, + "error": { + "type": "value", + "message": "first secnonce value is out of range." + }, + "comment": "Secnonce is invalid which may indicate nonce reuse" + } + ], + "verify_fail_test_cases": [ + { + "sig": "FED54434AD4CFE953FC527DC6A5E5BE8F6234907B7C187559557CE87A0541C46", + "key_indices": [0, 1, 2], + "nonce_indices": [0, 1, 2], + "msg_index": 0, + "signer_index": 0, + "comment": "Wrong signature (which is equal to the negation of valid signature)" + }, + { + "sig": "012ABBCB52B3016AC03AD82395A1A415C48B93DEF78718E62A7A90052FE224FB", + "key_indices": [0, 1, 2], + "nonce_indices": [0, 1, 2], + "msg_index": 0, + "signer_index": 1, + "comment": "Wrong signer" + }, + { + "sig": "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", + "key_indices": [0, 1, 2], + "nonce_indices": [0, 1, 2], + "msg_index": 0, + "signer_index": 0, + "comment": "Signature exceeds group size" + } + ], + "verify_error_test_cases": [ + { + "sig": "012ABBCB52B3016AC03AD82395A1A415C48B93DEF78718E62A7A90052FE224FB", + "key_indices": [0, 1, 2], + "nonce_indices": [4, 1, 2], + "msg_index": 0, + "signer_index": 0, + "error": { + "type": "invalid_contribution", + "signer": 0, + "contrib": "pubnonce" + }, + "comment": "Invalid pubnonce" + }, + { + "sig": "012ABBCB52B3016AC03AD82395A1A415C48B93DEF78718E62A7A90052FE224FB", + "key_indices": [3, 1, 2], + "nonce_indices": [0, 1, 2], + "msg_index": 0, + "signer_index": 0, + "error": { + "type": "invalid_contribution", + "signer": 0, + "contrib": "pubkey" + }, + "comment": "Invalid pubkey" + } + ] +} diff --git a/src/data/bip327/tweak_vectors.json b/src/data/bip327/tweak_vectors.json new file mode 100644 index 000000000..d0a7cfe83 --- /dev/null +++ b/src/data/bip327/tweak_vectors.json @@ -0,0 +1,84 @@ +{ + "sk": "7FB9E0E687ADA1EEBF7ECFE2F21E73EBDB51A7D450948DFE8D76D7F2D1007671", + "pubkeys": [ + "03935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", + "02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9", + "02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659" + ], + "secnonce": "508B81A611F100A6B2B6B29656590898AF488BCF2E1F55CF22E5CFB84421FE61FA27FD49B1D50085B481285E1CA205D55C82CC1B31FF5CD54A489829355901F703935F972DA013F80AE011890FA89B67A27B7BE6CCB24D3274D18B2D4067F261A9", + "pnonces": [ + "0337C87821AFD50A8644D820A8F3E02E499C931865C2360FB43D0A0D20DAFE07EA0287BF891D2A6DEAEBADC909352AA9405D1428C15F4B75F04DAE642A95C2548480", + "0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F817980279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "032DE2662628C90B03F5E720284EB52FF7D71F4284F627B68A853D78C78E1FFE9303E4C5524E83FFE1493B9077CF1CA6BEB2090C93D930321071AD40B2F44E599046" + ], + "aggnonce": "028465FCF0BBDBCF443AABCCE533D42B4B5A10966AC09A49655E8C42DAAB8FCD61037496A3CC86926D452CAFCFD55D25972CA1675D549310DE296BFF42F72EEEA8C9", + "tweaks": [ + "E8F791FF9225A2AF0102AFFF4A9A723D9612A682A25EBE79802B263CDFCD83BB", + "AE2EA797CC0FE72AC5B97B97F3C6957D7E4199A167A58EB08BCAFFDA70AC0455", + "F52ECBC565B3D8BEA2DFD5B75A4F457E54369809322E4120831626F290FA87E0", + "1969AD73CC177FA0B4FCED6DF1F7BF9907E665FDE9BA196A74FED0A3CF5AEF9D", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141" + ], + "msg": "F95466D086770E689964664219266FE5ED215C92AE20BAB5C9D79ADDDDF3C0CF", + "valid_test_cases": [ + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "tweak_indices": [0], + "is_xonly": [true], + "signer_index": 2, + "expected": "E28A5C66E61E178C2BA19DB77B6CF9F7E2F0F56C17918CD13135E60CC848FE91", + "comment": "A single x-only tweak" + }, + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "tweak_indices": [0], + "is_xonly": [false], + "signer_index": 2, + "expected": "38B0767798252F21BF5702C48028B095428320F73A4B14DB1E25DE58543D2D2D", + "comment": "A single plain tweak" + }, + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "tweak_indices": [0, 1], + "is_xonly": [false, true], + "signer_index": 2, + "expected": "408A0A21C4A0F5DACAF9646AD6EB6FECD7F7A11F03ED1F48DFFF2185BC2C2408", + "comment": "A plain tweak followed by an x-only tweak" + }, + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "tweak_indices": [0, 1, 2, 3], + "is_xonly": [false, false, true, true], + "signer_index": 2, + "expected": "45ABD206E61E3DF2EC9E264A6FEC8292141A633C28586388235541F9ADE75435", + "comment": "Four tweaks: plain, plain, x-only, x-only." + }, + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "tweak_indices": [0, 1, 2, 3], + "is_xonly": [true, false, true, false], + "signer_index": 2, + "expected": "B255FDCAC27B40C7CE7848E2D3B7BF5EA0ED756DA81565AC804CCCA3E1D5D239", + "comment": "Four tweaks: x-only, plain, x-only, plain. If an implementation prohibits applying plain tweaks after x-only tweaks, it can skip this test vector or return an error." + } + ], + "error_test_cases": [ + { + "key_indices": [1, 2, 0], + "nonce_indices": [1, 2, 0], + "tweak_indices": [4], + "is_xonly": [false], + "signer_index": 2, + "error": { + "type": "value", + "message": "The tweak must be less than n." + }, + "comment": "Tweak is invalid because it exceeds group size" + } + ] +} diff --git a/src/internal.c b/src/internal.c index e64e1d267..3e9e03513 100644 --- a/src/internal.c +++ b/src/internal.c @@ -404,9 +404,23 @@ static int wally_internal_ec_nonce_fn(unsigned char *nonce32, return secp256k1_nonce_function_default(nonce32, msg32, key32, algo16, data, attempt); } +static void wally_secp_illegal_callback(const char *str, void *data) +{ + /* secp256k1's default illegal-argument callback calls abort(), which would + * crash the host process when an API precondition is violated - e.g. when a + * malformed keyagg_cache/session parsed from untrusted bytes is later loaded. + * Ignore it instead so the calling wally_ function returns WALLY_ERROR. */ + (void)str; + (void)data; +} + struct secp256k1_context_struct *wally_get_new_secp_context(void) { - return secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN); + struct secp256k1_context_struct *ctx; + ctx = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN); + if (ctx) + secp256k1_context_set_illegal_callback(ctx, wally_secp_illegal_callback, NULL); + return ctx; } struct secp256k1_context_struct *wally_internal_secp_context(void) diff --git a/src/musig.c b/src/musig.c new file mode 100644 index 000000000..adec7549b --- /dev/null +++ b/src/musig.c @@ -0,0 +1,939 @@ +#include "internal.h" +#include +#include +#include + +#ifndef BUILD_STANDARD_SECP +#include + +/* Struct bodies kept private to prevent inadvertent copying (nonce-reuse risk) */ +struct wally_musig_keyagg_cache { unsigned char data[197]; }; +struct wally_musig_secnonce { unsigned char data[132]; }; +struct wally_musig_pubnonce { unsigned char data[132]; }; +struct wally_musig_aggnonce { unsigned char data[132]; }; +struct wally_musig_session { unsigned char data[133]; }; +struct wally_musig_partial_sig { unsigned char data[36]; }; + +/* Comparison function for qsort: lexicographic order of 33-byte compressed pubkeys */ +static int musig2_keyagg_pubkey_cmp(const void *a, const void *b) +{ + return memcmp(a, b, EC_PUBLIC_KEY_LEN); +} + +/* BIP-328 synthetic xpub chain code: SHA256("MuSig2MuSig2MuSig2") */ +static const unsigned char MUSIG2_CHAINCODE[WALLY_MUSIG2_CHAINCODE_LEN] = { + 0x86, 0x80, 0x87, 0xca, 0x02, 0xa6, 0xf9, 0x74, + 0xc4, 0x59, 0x89, 0x24, 0xc3, 0x6b, 0x57, 0x76, + 0x2d, 0x32, 0xcb, 0x45, 0x71, 0x71, 0x67, 0xe3, + 0x00, 0x62, 0x2c, 0x71, 0x67, 0xe3, 0x89, 0x65 +}; + +/* Compile-time size assertions to catch upstream secp256k1-zkp ABI changes */ +typedef char assert_keyagg_cache_size[ + sizeof(secp256k1_musig_keyagg_cache) == sizeof(struct wally_musig_keyagg_cache) ? 1 : -1]; +typedef char assert_secnonce_size[ + sizeof(secp256k1_musig_secnonce) == sizeof(struct wally_musig_secnonce) ? 1 : -1]; +typedef char assert_pubnonce_size[ + sizeof(secp256k1_musig_pubnonce) == sizeof(struct wally_musig_pubnonce) ? 1 : -1]; +typedef char assert_aggnonce_size[ + sizeof(secp256k1_musig_aggnonce) == sizeof(struct wally_musig_aggnonce) ? 1 : -1]; +typedef char assert_session_size[ + sizeof(secp256k1_musig_session) == sizeof(struct wally_musig_session) ? 1 : -1]; +typedef char assert_partial_sig_size[ + sizeof(secp256k1_musig_partial_sig) == sizeof(struct wally_musig_partial_sig) ? 1 : -1]; + +/* --- Lifecycle functions (parse/serialize/free) --- */ + +/* Free an opaque MuSig2 object, zeroing its contents first */ +#define MUSIG_FREE(typ) \ + WALLY_CORE_API int wally_musig_ ## typ ## _free( \ + struct wally_musig_ ## typ *p) \ + { \ + if (p) \ + clear_and_free(p, sizeof(*p)); \ + return WALLY_OK; \ + } + +/* Serialize an opaque MuSig2 object by copying out its raw bytes */ +#define MUSIG_RAW_SERIALIZE(typ, LEN) \ + WALLY_CORE_API int wally_musig_ ## typ ## _serialize( \ + const struct wally_musig_ ## typ *p, \ + unsigned char *bytes_out, \ + size_t len) \ + { \ + if (!p || !bytes_out || len != LEN) \ + return WALLY_EINVAL; \ + memcpy(bytes_out, p->data, LEN); \ + return WALLY_OK; \ + } + +/* Parse an opaque MuSig2 object via its secp256k1 parse function */ +#define MUSIG_SECP_PARSE(typ, LEN) \ + WALLY_CORE_API int wally_musig_ ## typ ## _parse( \ + const unsigned char *bytes, \ + size_t bytes_len, \ + struct wally_musig_ ## typ **output) \ + { \ + const secp256k1_context *ctx = secp_ctx(); \ + secp256k1_musig_ ## typ *parsed; \ + OUTPUT_CHECK; \ + if (!bytes || bytes_len != LEN) \ + return WALLY_EINVAL; \ + if (!ctx) \ + return WALLY_ENOMEM; \ + if (!(parsed = wally_calloc(sizeof(*parsed)))) \ + return WALLY_ENOMEM; \ + if (!secp256k1_musig_ ## typ ## _parse(ctx, parsed, bytes)) { \ + clear_and_free(parsed, sizeof(*parsed)); \ + return WALLY_EINVAL; \ + } \ + *output = (struct wally_musig_ ## typ *)parsed; \ + return WALLY_OK; \ + } + +/* Serialize an opaque MuSig2 object via its secp256k1 serialize function */ +#define MUSIG_SECP_SERIALIZE(typ, LEN) \ + WALLY_CORE_API int wally_musig_ ## typ ## _serialize( \ + const struct wally_musig_ ## typ *p, \ + unsigned char *bytes_out, \ + size_t len) \ + { \ + const secp256k1_context *ctx = secp_ctx(); \ + if (!p || !bytes_out || len != LEN) \ + return WALLY_EINVAL; \ + if (!ctx) \ + return WALLY_ENOMEM; \ + if (!secp256k1_musig_ ## typ ## _serialize( \ + ctx, bytes_out, (const secp256k1_musig_ ## typ *)p)) \ + return WALLY_ERROR; \ + return WALLY_OK; \ + } + +MUSIG_FREE(keyagg_cache) +MUSIG_FREE(secnonce) +MUSIG_FREE(pubnonce) +MUSIG_FREE(aggnonce) +MUSIG_FREE(session) +MUSIG_FREE(partial_sig) + +MUSIG_RAW_SERIALIZE(keyagg_cache, WALLY_MUSIG_KEYAGG_CACHE_LEN) +MUSIG_RAW_SERIALIZE(session, WALLY_MUSIG_SESSION_LEN) + +MUSIG_SECP_PARSE(pubnonce, WALLY_MUSIG_PUBNONCE_LEN) +MUSIG_SECP_SERIALIZE(pubnonce, WALLY_MUSIG_PUBNONCE_LEN) +MUSIG_SECP_PARSE(aggnonce, WALLY_MUSIG_AGGNONCE_LEN) +MUSIG_SECP_SERIALIZE(aggnonce, WALLY_MUSIG_AGGNONCE_LEN) +MUSIG_SECP_PARSE(partial_sig, WALLY_MUSIG_PARTIAL_SIG_LEN) +MUSIG_SECP_SERIALIZE(partial_sig, WALLY_MUSIG_PARTIAL_SIG_LEN) + +WALLY_CORE_API int wally_musig_keyagg_cache_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_keyagg_cache **output) +{ + const secp256k1_context *ctx = secp_ctx(); + struct wally_musig_keyagg_cache *cache; + secp256k1_pubkey agg_pk; + + OUTPUT_CHECK; + if (!bytes || bytes_len != WALLY_MUSIG_KEYAGG_CACHE_LEN) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + cache = wally_calloc(sizeof(*cache)); + if (!cache) + return WALLY_ENOMEM; + memcpy(cache->data, bytes, WALLY_MUSIG_KEYAGG_CACHE_LEN); + /* Validate by extracting the aggregate key. secp256k1-zkp has no full + * validator for this struct, but this rejects a corrupted magic or + * aggregate-key field rather than deferring the failure to signing. */ + if (!secp256k1_musig_pubkey_get(ctx, &agg_pk, + (const secp256k1_musig_keyagg_cache *)cache)) { + clear_and_free(cache, sizeof(*cache)); + return WALLY_EINVAL; + } + *output = cache; + return WALLY_OK; +} + +WALLY_CORE_API int wally_musig_session_parse( + const unsigned char *bytes, + size_t bytes_len, + struct wally_musig_session **output) +{ + struct wally_musig_session *session; + + OUTPUT_CHECK; + if (!bytes || bytes_len != WALLY_MUSIG_SESSION_LEN) + return WALLY_EINVAL; + session = wally_calloc(sizeof(*session)); + if (!session) + return WALLY_ENOMEM; + memcpy(session->data, bytes, WALLY_MUSIG_SESSION_LEN); + *output = session; + return WALLY_OK; +} + +/* --- Key aggregation functions --- */ + +WALLY_CORE_API int wally_musig_pubkey_agg( + const unsigned char *pub_keys, + size_t pub_keys_len, + unsigned char *agg_pk_out, + size_t agg_pk_out_len, + struct wally_musig_keyagg_cache **cache_out) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_pubkey *pubkeys_parsed = NULL; + const secp256k1_pubkey **pubkey_ptrs = NULL; + secp256k1_musig_keyagg_cache *cache = NULL; + secp256k1_xonly_pubkey xonly; + size_t n_pubkeys, i; + int ret = WALLY_EINVAL; + + if (cache_out) + *cache_out = NULL; + if (!pub_keys || !pub_keys_len || pub_keys_len % EC_PUBLIC_KEY_LEN != 0) + return WALLY_EINVAL; + if (agg_pk_out && agg_pk_out_len != EC_XONLY_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!agg_pk_out && !cache_out) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + n_pubkeys = pub_keys_len / EC_PUBLIC_KEY_LEN; + if (n_pubkeys < 2) + return WALLY_EINVAL; + + /* Allocate the pointer and element arrays together */ + pubkey_ptrs = array_calloc(n_pubkeys, sizeof(*pubkey_ptrs) + sizeof(*pubkeys_parsed)); + if (!pubkey_ptrs) + return WALLY_ENOMEM; + pubkeys_parsed = (secp256k1_pubkey *)(pubkey_ptrs + n_pubkeys); + + for (i = 0; i < n_pubkeys; i++) { + if (!pubkey_parse(&pubkeys_parsed[i], + pub_keys + i * EC_PUBLIC_KEY_LEN, + EC_PUBLIC_KEY_LEN)) + goto cleanup; + pubkey_ptrs[i] = &pubkeys_parsed[i]; + } + + if (cache_out) { + cache = wally_calloc(sizeof(secp256k1_musig_keyagg_cache)); + if (!cache) { + ret = WALLY_ENOMEM; + goto cleanup; + } + } + + if (!secp256k1_musig_pubkey_agg(ctx, + agg_pk_out ? &xonly : NULL, + cache, pubkey_ptrs, n_pubkeys)) + goto cleanup; + + if (agg_pk_out) + xpubkey_serialize(agg_pk_out, &xonly); + + if (cache_out) { + *cache_out = (struct wally_musig_keyagg_cache *)cache; + cache = NULL; + } + ret = WALLY_OK; + +cleanup: + if (cache) + wally_free(cache); + wally_free(pubkey_ptrs); + return ret; +} + +WALLY_CORE_API int wally_musig_pubkey_get( + const struct wally_musig_keyagg_cache *cache, + unsigned char *pub_key_out, + size_t pub_key_out_len) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_pubkey agg_pk; + size_t len = EC_PUBLIC_KEY_LEN; + + if (!cache || !pub_key_out || pub_key_out_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + if (!secp256k1_musig_pubkey_get(ctx, &agg_pk, + (const secp256k1_musig_keyagg_cache *)cache)) + return WALLY_ERROR; + + pubkey_serialize(pub_key_out, &len, &agg_pk, PUBKEY_COMPRESSED); + return WALLY_OK; +} + +WALLY_CORE_API int wally_musig_pubkey_ec_tweak_add( + struct wally_musig_keyagg_cache *cache, + const unsigned char *tweak, + size_t tweak_len, + unsigned char *pub_key_out, + size_t pub_key_out_len) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_pubkey output_pk; + size_t len = EC_PUBLIC_KEY_LEN; + + if (!cache || !tweak || tweak_len != EC_SCALAR_LEN) + return WALLY_EINVAL; + if (pub_key_out && pub_key_out_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + if (!secp256k1_musig_pubkey_ec_tweak_add(ctx, + pub_key_out ? &output_pk : NULL, + (secp256k1_musig_keyagg_cache *)cache, + tweak)) + return WALLY_ERROR; + + if (pub_key_out) + pubkey_serialize(pub_key_out, &len, &output_pk, PUBKEY_COMPRESSED); + return WALLY_OK; +} + +WALLY_CORE_API int wally_musig_pubkey_xonly_tweak_add( + struct wally_musig_keyagg_cache *cache, + const unsigned char *tweak, + size_t tweak_len, + unsigned char *pub_key_out, + size_t pub_key_out_len) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_pubkey output_pk; + size_t len = EC_PUBLIC_KEY_LEN; + + if (!cache || !tweak || tweak_len != EC_SCALAR_LEN) + return WALLY_EINVAL; + if (pub_key_out && pub_key_out_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + if (!secp256k1_musig_pubkey_xonly_tweak_add(ctx, + pub_key_out ? &output_pk : NULL, + (secp256k1_musig_keyagg_cache *)cache, + tweak)) + return WALLY_ERROR; + + if (pub_key_out) + pubkey_serialize(pub_key_out, &len, &output_pk, PUBKEY_COMPRESSED); + return WALLY_OK; +} + +/* --- Nonce generation and aggregation functions --- */ + +WALLY_CORE_API int wally_musig_nonce_gen( + const unsigned char *session_secrand32, + size_t session_secrand32_len, + const unsigned char *seckey, + size_t seckey_len, + const unsigned char *pub_key, + size_t pub_key_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + const unsigned char *msg32, + size_t msg32_len, + const unsigned char *extra_input32, + size_t extra_input32_len, + struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_musig_secnonce *secnonce = NULL; + secp256k1_musig_pubnonce *pubnonce = NULL; + secp256k1_pubkey pubkey; + int ret; + + if (secnonce_out) + *secnonce_out = NULL; + if (pubnonce_out) + *pubnonce_out = NULL; + if (!session_secrand32 || session_secrand32_len != 32) + return WALLY_EINVAL; + if (mem_is_zero(session_secrand32, session_secrand32_len)) + return WALLY_EINVAL; /* All-zero session randomness is never valid: it must be + * unique and uniformly random. Reject the most common + * uninitialized/predictable input as defense-in-depth. + * The caller is still responsible for real entropy and + * never reusing a value across signing sessions. */ + if (BYTES_INVALID_N(seckey, seckey_len, EC_PRIVATE_KEY_LEN)) + return WALLY_EINVAL; + if (!pub_key || pub_key_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (BYTES_INVALID_N(msg32, msg32_len, EC_MESSAGE_HASH_LEN)) + return WALLY_EINVAL; + if (BYTES_INVALID_N(extra_input32, extra_input32_len, 32)) + return WALLY_EINVAL; + if (!secnonce_out || !pubnonce_out) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + if (seckey && (ret = wally_ec_private_key_verify(seckey, seckey_len)) != WALLY_OK) + return ret; + + if (!pubkey_parse(&pubkey, pub_key, pub_key_len)) + return WALLY_EINVAL; + + secnonce = wally_calloc(sizeof(secp256k1_musig_secnonce)); + if (!secnonce) + return WALLY_ENOMEM; + + pubnonce = wally_calloc(sizeof(secp256k1_musig_pubnonce)); + if (!pubnonce) { + wally_free(secnonce); + return WALLY_ENOMEM; + } + + { + /* secp256k1 zeroes the session randomness buffer in place to prevent + * reuse; copy our const input into a mutable local for the call. */ + unsigned char secrand[32]; + int ok; + wally_memcpy(secrand, session_secrand32, sizeof(secrand)); + ok = secp256k1_musig_nonce_gen(ctx, secnonce, pubnonce, + secrand, seckey, &pubkey, + msg32, + keyagg_cache ? (const secp256k1_musig_keyagg_cache *)keyagg_cache : NULL, + extra_input32); + wally_clear(secrand, sizeof(secrand)); + if (!ok) { + clear_and_free(secnonce, sizeof(*secnonce)); + wally_free(pubnonce); + return WALLY_ERROR; + } + } + + *secnonce_out = (struct wally_musig_secnonce *)secnonce; + *pubnonce_out = (struct wally_musig_pubnonce *)pubnonce; + return WALLY_OK; +} + +WALLY_CORE_API int wally_musig_nonce_gen_counter( + uint64_t counter, + const unsigned char *seckey, + size_t seckey_len, + const unsigned char *pub_key, + size_t pub_key_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + const unsigned char *msg32, + size_t msg32_len, + const unsigned char *extra_input32, + size_t extra_input32_len, + struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_musig_secnonce *secnonce = NULL; + secp256k1_musig_pubnonce *pubnonce = NULL; + unsigned char derived[EC_PUBLIC_KEY_LEN]; + secp256k1_keypair keypair; + int ret; + + if (secnonce_out) + *secnonce_out = NULL; + if (pubnonce_out) + *pubnonce_out = NULL; + /* seckey is REQUIRED for counter mode */ + if (!seckey || seckey_len != EC_PRIVATE_KEY_LEN) + return WALLY_EINVAL; + if (!pub_key || pub_key_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (BYTES_INVALID_N(msg32, msg32_len, EC_MESSAGE_HASH_LEN)) + return WALLY_EINVAL; + if (BYTES_INVALID_N(extra_input32, extra_input32_len, 32)) + return WALLY_EINVAL; + if (!secnonce_out || !pubnonce_out) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + /* Counter mode signs with the keypair derived from seckey; require that + * the callers public key matches it to catch mismatched arguments. */ + if (wally_ec_public_key_from_private_key(seckey, seckey_len, + derived, sizeof(derived)) != WALLY_OK) + return WALLY_EINVAL; + if (memcmp(derived, pub_key, sizeof(derived))) + return WALLY_EINVAL; + + /* secp256k1's dedicated counter API (a low-entropy session_id would be + * rejected by nonce_gen). */ + if (!keypair_create(&keypair, seckey)) + return WALLY_EINVAL; + + secnonce = wally_calloc(sizeof(secp256k1_musig_secnonce)); + if (!secnonce) { + wally_clear(&keypair, sizeof(keypair)); + return WALLY_ENOMEM; + } + + pubnonce = wally_calloc(sizeof(secp256k1_musig_pubnonce)); + if (!pubnonce) { + wally_free(secnonce); + wally_clear(&keypair, sizeof(keypair)); + return WALLY_ENOMEM; + } + + ret = secp256k1_musig_nonce_gen_counter(ctx, secnonce, pubnonce, + counter, &keypair, msg32, + keyagg_cache ? (const secp256k1_musig_keyagg_cache *)keyagg_cache : NULL, + extra_input32); + wally_clear(&keypair, sizeof(keypair)); + + if (!ret) { + clear_and_free(secnonce, sizeof(*secnonce)); + wally_free(pubnonce); + return WALLY_ERROR; + } + + *secnonce_out = (struct wally_musig_secnonce *)secnonce; + *pubnonce_out = (struct wally_musig_pubnonce *)pubnonce; + return WALLY_OK; +} + +WALLY_CORE_API int wally_musig_nonce_agg( + const unsigned char *pubnonces, + size_t pubnonces_len, + size_t n_pubnonces, + struct wally_musig_aggnonce **aggnonce_out) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_musig_pubnonce *parsed = NULL; + const secp256k1_musig_pubnonce **ptrs = NULL; + secp256k1_musig_aggnonce *aggnonce = NULL; + size_t i; + int ret = WALLY_EINVAL; + + if (aggnonce_out) + *aggnonce_out = NULL; + if (!pubnonces || n_pubnonces < 2 || !aggnonce_out || + pubnonces_len % WALLY_MUSIG_PUBNONCE_LEN || + pubnonces_len / WALLY_MUSIG_PUBNONCE_LEN != n_pubnonces) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + /* Allocate the pointer and element arrays together */ + ptrs = array_calloc(n_pubnonces, sizeof(*ptrs) + sizeof(*parsed)); + if (!ptrs) + return WALLY_ENOMEM; + parsed = (secp256k1_musig_pubnonce *)(ptrs + n_pubnonces); + + for (i = 0; i < n_pubnonces; i++) { + if (!secp256k1_musig_pubnonce_parse(ctx, &parsed[i], + pubnonces + i * WALLY_MUSIG_PUBNONCE_LEN)) + goto cleanup; + ptrs[i] = &parsed[i]; + } + + aggnonce = wally_calloc(sizeof(secp256k1_musig_aggnonce)); + if (!aggnonce) { + ret = WALLY_ENOMEM; + goto cleanup; + } + + if (!secp256k1_musig_nonce_agg(ctx, aggnonce, ptrs, n_pubnonces)) { + ret = WALLY_ERROR; + goto cleanup; + } + + *aggnonce_out = (struct wally_musig_aggnonce *)aggnonce; + aggnonce = NULL; + ret = WALLY_OK; + +cleanup: + if (aggnonce) + wally_free(aggnonce); + wally_free(ptrs); + return ret; +} + +WALLY_CORE_API int wally_musig_nonce_process( + const struct wally_musig_aggnonce *aggnonce, + const unsigned char *msg32, + size_t msg32_len, + const struct wally_musig_keyagg_cache *cache, + const unsigned char *adaptor, + size_t adaptor_len, + struct wally_musig_session **session_out) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_musig_session *session = NULL; + secp256k1_pubkey adaptor_pk; + int ret = WALLY_EINVAL; + + if (session_out) + *session_out = NULL; + if (!aggnonce || !msg32 || msg32_len != 32) + return WALLY_EINVAL; + if (!cache || !session_out) + return WALLY_EINVAL; + if (adaptor && adaptor_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!adaptor && adaptor_len) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + if (adaptor && !pubkey_parse(&adaptor_pk, adaptor, adaptor_len)) + return WALLY_EINVAL; + + session = wally_calloc(sizeof(secp256k1_musig_session)); + if (!session) + return WALLY_ENOMEM; + + if (!secp256k1_musig_nonce_process(ctx, session, + (const secp256k1_musig_aggnonce *)aggnonce, + msg32, + (const secp256k1_musig_keyagg_cache *)cache, + adaptor ? &adaptor_pk : NULL)) { + ret = WALLY_ERROR; + goto cleanup; + } + + *session_out = (struct wally_musig_session *)session; + session = NULL; + ret = WALLY_OK; + +cleanup: + if (session) + wally_free(session); + return ret; +} + +WALLY_CORE_API int wally_musig_partial_sign( + struct wally_musig_secnonce *secnonce, + const unsigned char *seckey, + size_t seckey_len, + const struct wally_musig_keyagg_cache *cache, + const struct wally_musig_session *session, + struct wally_musig_partial_sig **partial_sig_out) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_keypair keypair; + secp256k1_pubkey signer_pk, nonce_pt; + secp256k1_musig_pubnonce pubnonce; + unsigned char pubnonce_bytes[2 * EC_PUBLIC_KEY_LEN]; + secp256k1_musig_partial_sig *partial_sig = NULL; + size_t i, len; + int ret = WALLY_EINVAL; + + if (partial_sig_out) + *partial_sig_out = NULL; + if (!secnonce || !seckey || seckey_len != EC_PRIVATE_KEY_LEN) + return WALLY_EINVAL; + if (!cache || !session || !partial_sig_out) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + /* secp256k1 rejects a key that doesn't match the secnonce through its + * illegal argument callback, which wally ignores, leaving the secret + * key and nonce in its stack frame. Reject a mismatched key (or a used, + * zeroed secnonce) here instead. The secnonce holds the signer's public + * key after its 4 byte magic and two 32 byte nonce scalars. */ + if (!keypair_create(&keypair, seckey) || + !secp256k1_keypair_pub(ctx, &signer_pk, &keypair) || + memcmp(signer_pk.data, secnonce->data + 68, sizeof(signer_pk.data))) + goto cleanup; + + /* Compute our public nonce from the nonce scalars before signing zeroes + * them, to verify the partial signature against */ + for (i = 0; i < 2; ++i) { + len = EC_PUBLIC_KEY_LEN; + if (!secp256k1_ec_pubkey_create(ctx, &nonce_pt, secnonce->data + 4 + i * 32) || + !secp256k1_ec_pubkey_serialize(ctx, pubnonce_bytes + i * EC_PUBLIC_KEY_LEN, + &len, &nonce_pt, SECP256K1_EC_COMPRESSED)) + goto cleanup; + } + if (!secp256k1_musig_pubnonce_parse(ctx, &pubnonce, pubnonce_bytes)) + goto cleanup; + + partial_sig = wally_calloc(sizeof(secp256k1_musig_partial_sig)); + if (!partial_sig) { + ret = WALLY_ENOMEM; + goto cleanup; + } + + if (!secp256k1_musig_partial_sign(ctx, partial_sig, + (secp256k1_musig_secnonce *)secnonce, + &keypair, + (const secp256k1_musig_keyagg_cache *)cache, + (const secp256k1_musig_session *)session)) { + ret = WALLY_ERROR; + goto cleanup; + } + + /* Verify the partial signature, as secp256k1 recommends, so that a + * computation fault can never return a bad signature */ + if (!secp256k1_musig_partial_sig_verify(ctx, partial_sig, &pubnonce, &signer_pk, + (const secp256k1_musig_keyagg_cache *)cache, + (const secp256k1_musig_session *)session)) { + wally_clear(partial_sig, sizeof(*partial_sig)); + ret = WALLY_ERROR; + goto cleanup; + } + + *partial_sig_out = (struct wally_musig_partial_sig *)partial_sig; + partial_sig = NULL; + ret = WALLY_OK; + +cleanup: + wally_clear(&keypair, sizeof(keypair)); + if (partial_sig) + wally_free(partial_sig); + return ret; +} + +WALLY_CORE_API int wally_musig_partial_sig_verify( + const struct wally_musig_partial_sig *sig, + const struct wally_musig_pubnonce *pubnonce, + const unsigned char *pub_key, + size_t pub_key_len, + const struct wally_musig_keyagg_cache *cache, + const struct wally_musig_session *session) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_pubkey pk; + + if (!sig || !pubnonce || !pub_key || pub_key_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!cache || !session) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + if (!pubkey_parse(&pk, pub_key, pub_key_len)) + return WALLY_EINVAL; + + if (!secp256k1_musig_partial_sig_verify(ctx, + (const secp256k1_musig_partial_sig *)sig, + (const secp256k1_musig_pubnonce *)pubnonce, + &pk, + (const secp256k1_musig_keyagg_cache *)cache, + (const secp256k1_musig_session *)session)) + return WALLY_ERROR; + + return WALLY_OK; +} + +WALLY_CORE_API int wally_musig_partial_sig_agg( + const unsigned char *partial_sigs, + size_t partial_sigs_len, + size_t n_sigs, + const struct wally_musig_session *session, + unsigned char *sig64_out, + size_t sig64_out_len) +{ + const secp256k1_context *ctx = secp_ctx(); + secp256k1_musig_partial_sig *parsed = NULL; + const secp256k1_musig_partial_sig **ptrs = NULL; + size_t i; + int ret = WALLY_EINVAL; + + if (!partial_sigs || n_sigs < 2 || + partial_sigs_len % WALLY_MUSIG_PARTIAL_SIG_LEN || + partial_sigs_len / WALLY_MUSIG_PARTIAL_SIG_LEN != n_sigs) + return WALLY_EINVAL; + if (!session || !sig64_out || sig64_out_len != EC_SIGNATURE_LEN) + return WALLY_EINVAL; + if (!ctx) + return WALLY_ENOMEM; + + /* Allocate the pointer and element arrays together */ + ptrs = array_calloc(n_sigs, sizeof(*ptrs) + sizeof(*parsed)); + if (!ptrs) + return WALLY_ENOMEM; + parsed = (secp256k1_musig_partial_sig *)(ptrs + n_sigs); + + for (i = 0; i < n_sigs; i++) { + if (!secp256k1_musig_partial_sig_parse(ctx, &parsed[i], + partial_sigs + i * WALLY_MUSIG_PARTIAL_SIG_LEN)) { + ret = WALLY_EINVAL; + goto cleanup; + } + ptrs[i] = &parsed[i]; + } + + if (!secp256k1_musig_partial_sig_agg(ctx, sig64_out, + (const secp256k1_musig_session *)session, + ptrs, n_sigs)) { + ret = WALLY_ERROR; + goto cleanup; + } + + ret = WALLY_OK; + +cleanup: + wally_free(ptrs); + return ret; +} + +WALLY_CORE_API int wally_musig_pubkey_to_xpub( + const unsigned char *agg_pk, + size_t agg_pk_len, + uint32_t version, + struct ext_key **output) +{ + OUTPUT_CHECK; + if (!agg_pk || agg_pk_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (agg_pk[0] != 0x02 && agg_pk[0] != 0x03) + return WALLY_EINVAL; /* Not a compressed public key */ + if (version != BIP32_VER_MAIN_PUBLIC && version != BIP32_VER_TEST_PUBLIC) + return WALLY_EINVAL; + + /* Construct ext_key at depth 0 with no parent, using the fixed BIP-328 + * chain code. Note BIP-328 uses the full compressed aggregate key with + * its real parity byte, not an (implicitly even) x-only interpretation. */ + return bip32_key_init_alloc( + version, + 0, /* depth */ + 0, /* child_num */ + MUSIG2_CHAINCODE, WALLY_MUSIG2_CHAINCODE_LEN, + agg_pk, EC_PUBLIC_KEY_LEN, + NULL, 0, /* no private key */ + NULL, 0, /* hash160: computed from pub_key */ + NULL, 0, /* parent160: zeros for root key */ + output); +} + +WALLY_CORE_API int wally_musig_pubkeys_derive_then_agg( + const unsigned char *xpubs, + size_t xpubs_len, + uint32_t child_num, + unsigned char *agg_pk_out, + size_t agg_pk_out_len, + struct wally_musig_keyagg_cache **cache_out) +{ + unsigned char *sorted_pubkeys = NULL; + struct ext_key hdkey, child; + size_t n_xpubs, i; + int ret = WALLY_EINVAL; + + if (cache_out) + *cache_out = NULL; + if (!xpubs || xpubs_len < 2 * BIP32_SERIALIZED_LEN || + xpubs_len % BIP32_SERIALIZED_LEN != 0) + return WALLY_EINVAL; + if (child_num >= BIP32_INITIAL_HARDENED_CHILD) + return WALLY_EINVAL; + if (agg_pk_out && agg_pk_out_len != EC_XONLY_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + if (!agg_pk_out && !cache_out) + return WALLY_EINVAL; + + n_xpubs = xpubs_len / BIP32_SERIALIZED_LEN; + + sorted_pubkeys = wally_malloc(n_xpubs * EC_PUBLIC_KEY_LEN); + if (!sorted_pubkeys) + return WALLY_ENOMEM; + + for (i = 0; i < n_xpubs; i++) { + ret = bip32_key_unserialize(xpubs + i * BIP32_SERIALIZED_LEN, + BIP32_SERIALIZED_LEN, &hdkey); + if (ret != WALLY_OK) + goto cleanup; + + ret = bip32_key_from_parent(&hdkey, child_num, + BIP32_FLAG_KEY_PUBLIC, &child); + if (ret != WALLY_OK) + goto cleanup; + + memcpy(sorted_pubkeys + i * EC_PUBLIC_KEY_LEN, + child.pub_key, EC_PUBLIC_KEY_LEN); + } + + qsort(sorted_pubkeys, n_xpubs, EC_PUBLIC_KEY_LEN, musig2_keyagg_pubkey_cmp); + + ret = wally_musig_pubkey_agg(sorted_pubkeys, n_xpubs * EC_PUBLIC_KEY_LEN, + agg_pk_out, agg_pk_out_len, cache_out); + +cleanup: + wally_clear_2(&hdkey, sizeof(hdkey), &child, sizeof(child)); + wally_free(sorted_pubkeys); + return ret; +} + +WALLY_CORE_API int wally_musig_pubkeys_agg_then_derive( + const unsigned char *pub_keys, + size_t pub_keys_len, + uint32_t version, + uint32_t child_num, + unsigned char *pub_key_out, + size_t pub_key_out_len, + struct ext_key **child_out) +{ + unsigned char agg_pk[EC_PUBLIC_KEY_LEN]; + struct wally_musig_keyagg_cache *cache = NULL; + struct ext_key *synthetic_xpub = NULL; + struct ext_key *child = NULL; + unsigned char *sorted = NULL; + int ret; + + if (child_out) + *child_out = NULL; + if (!pub_keys || pub_keys_len < 2 * EC_PUBLIC_KEY_LEN || + pub_keys_len % EC_PUBLIC_KEY_LEN != 0) + return WALLY_EINVAL; + if (version != BIP32_VER_MAIN_PUBLIC && version != BIP32_VER_TEST_PUBLIC) + return WALLY_EINVAL; + if (child_num >= BIP32_INITIAL_HARDENED_CHILD) + return WALLY_EINVAL; + if (!pub_key_out && !child_out) + return WALLY_EINVAL; + if (pub_key_out && pub_key_out_len != EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + + sorted = wally_malloc(pub_keys_len); + if (!sorted) + return WALLY_ENOMEM; + memcpy(sorted, pub_keys, pub_keys_len); + qsort(sorted, pub_keys_len / EC_PUBLIC_KEY_LEN, EC_PUBLIC_KEY_LEN, musig2_keyagg_pubkey_cmp); + + ret = wally_musig_pubkey_agg(sorted, pub_keys_len, NULL, 0, &cache); + if (ret != WALLY_OK) + goto cleanup; + + /* Fetch the full compressed aggregate key; BIP-328 requires its parity */ + ret = wally_musig_pubkey_get(cache, agg_pk, sizeof(agg_pk)); + if (ret != WALLY_OK) + goto cleanup; + + ret = wally_musig_pubkey_to_xpub(agg_pk, sizeof(agg_pk), version, + &synthetic_xpub); + if (ret != WALLY_OK) + goto cleanup; + + ret = bip32_key_from_parent_alloc(synthetic_xpub, child_num, + BIP32_FLAG_KEY_PUBLIC, &child); + if (ret != WALLY_OK) + goto cleanup; + + if (pub_key_out) + memcpy(pub_key_out, child->pub_key, EC_PUBLIC_KEY_LEN); + + if (child_out) { + *child_out = child; + child = NULL; + } + +cleanup: + if (child) + bip32_key_free(child); + if (synthetic_xpub) + bip32_key_free(synthetic_xpub); + wally_musig_keyagg_cache_free(cache); + wally_free(sorted); + wally_clear(agg_pk, sizeof(agg_pk)); + return ret; +} + +#endif /* ndef BUILD_STANDARD_SECP */ diff --git a/src/swig_java/swig.i b/src/swig_java/swig.i index d0a901f3c..b78e18b63 100644 --- a/src/swig_java/swig.i +++ b/src/swig_java/swig.i @@ -19,6 +19,7 @@ #include "../include/wally_transaction.h" #include "../include/wally_transaction_members.h" #include "../include/wally_elements.h" +#include "../include/wally_musig.h" #include "../internal.h" #include @@ -259,6 +260,8 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { /* BEGIN AUTOGENERATED */ %apply(char *STRING, size_t LENGTH) { (const unsigned char* abf, size_t abf_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* adaptor, size_t adaptor_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* agg_pk, size_t agg_pk_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* annex, size_t annex_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* asset, size_t asset_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* aux_rand, size_t aux_rand_len) }; @@ -268,6 +271,7 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %apply(char *STRING, size_t LENGTH) { (const unsigned char* contract_hash, size_t contract_hash_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* entropy, size_t entropy_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* extra, size_t extra_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* extra_input32, size_t extra_input32_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* final_scriptsig, size_t final_scriptsig_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* fingerprint, size_t fingerprint_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* generator, size_t generator_len) }; @@ -285,6 +289,7 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %apply(char *STRING, size_t LENGTH) { (const unsigned char* mainchain_script, size_t mainchain_script_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* merkle_hashes, size_t merkle_hashes_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* merkle_root, size_t merkle_root_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* msg32, size_t msg32_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* nonce, size_t nonce_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* nonce_hash, size_t nonce_hash_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* offline_keys, size_t offline_keys_len) }; @@ -295,10 +300,13 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %apply(char *STRING, size_t LENGTH) { (const unsigned char* output_asset, size_t output_asset_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* output_generator, size_t output_generator_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* parent160, size_t parent160_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* partial_sigs, size_t partial_sigs_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* pass, size_t pass_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* priv_key, size_t priv_key_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* proof, size_t proof_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* pub_key, size_t pub_key_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* pub_keys, size_t pub_keys_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* pubnonces, size_t pubnonces_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* rangeproof, size_t rangeproof_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* redeem_script, size_t redeem_script_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* s2c_data, size_t s2c_data_len) }; @@ -307,6 +315,8 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %apply(char *STRING, size_t LENGTH) { (const unsigned char* scalar, size_t scalar_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* script, size_t script_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* scriptpubkey, size_t scriptpubkey_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* seckey, size_t seckey_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* session_secrand32, size_t session_secrand32_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* sig, size_t sig_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* sub_pubkey, size_t sub_pubkey_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* summed_key, size_t summed_key_len) }; @@ -323,11 +333,15 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %apply(char *STRING, size_t LENGTH) { (const unsigned char* vbf, size_t vbf_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* whitelistproof, size_t whitelistproof_len) }; %apply(char *STRING, size_t LENGTH) { (const unsigned char* witness, size_t witness_len) }; +%apply(char *STRING, size_t LENGTH) { (const unsigned char* xpubs, size_t xpubs_len) }; %apply(char *STRING, size_t LENGTH) { (unsigned char* abf_out, size_t abf_out_len) }; +%apply(char *STRING, size_t LENGTH) { (unsigned char* agg_pk_out, size_t agg_pk_out_len) }; %apply(char *STRING, size_t LENGTH) { (unsigned char* asset_out, size_t asset_out_len) }; %apply(char *STRING, size_t LENGTH) { (unsigned char* bytes_out, size_t len) }; +%apply(char *STRING, size_t LENGTH) { (unsigned char* pub_key_out, size_t pub_key_out_len) }; %apply(char *STRING, size_t LENGTH) { (unsigned char* s2c_opening_out, size_t s2c_opening_out_len) }; %apply(char *STRING, size_t LENGTH) { (unsigned char* scalar, size_t scalar_len) }; +%apply(char *STRING, size_t LENGTH) { (unsigned char* sig64_out, size_t sig64_out_len) }; %apply(char *STRING, size_t LENGTH) { (unsigned char* vbf_out, size_t vbf_out_len) }; %apply(char *STRING, size_t LENGTH) { (void* bytes, size_t bytes_len) }; %ignore bip32_key_from_base58; @@ -470,6 +484,14 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %java_opaque_struct(wally_map, 7); %java_opaque_struct(wally_psbt, 8); %java_opaque_struct(wally_descriptor, 9); +#ifndef BUILD_STANDARD_SECP +%java_opaque_struct(wally_musig_keyagg_cache, 10); +%java_opaque_struct(wally_musig_secnonce, 11); +%java_opaque_struct(wally_musig_pubnonce, 12); +%java_opaque_struct(wally_musig_aggnonce, 13); +%java_opaque_struct(wally_musig_session, 14); +%java_opaque_struct(wally_musig_partial_sig, 15); +#endif /* ndef BUILD_STANDARD_SECP */ /* Our wrapped functions return types */ %returns_void__(bip32_key_free); @@ -1247,6 +1269,93 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %returns_array_(wally_ae_sig_from_bytes, 8, 9, EC_SIGNATURE_LEN); %returns_void__(wally_ae_verify); +#ifndef BUILD_STANDARD_SECP +/* The musig/psbt headers use parameter names other than "output" for their + * opaque-output pointers (cache_out, aggnonce_out, partial_sig_out, + * session_out, secnonce_out, child_out). The %java_opaque_struct typemap + * only matches the literal name "output", so without the typemaps below + * SWIG falls back to a default that takes a `long` raw pointer-to-pointer + * from the Java caller - which crashes when dereferenced. Each typemap + * here suppresses the input slot, allocates a local, and feeds &local to + * the C call. The matching (argout) from %java_opaque_struct fires on + * type alone and wraps the result. */ +%typemap(in, numinputs=0) struct wally_musig_keyagg_cache **cache_out + (struct wally_musig_keyagg_cache *w) { w = 0; $1 = &w; } +%typemap(in, numinputs=0) struct wally_musig_aggnonce **aggnonce_out + (struct wally_musig_aggnonce *w) { w = 0; $1 = &w; } +%typemap(in, numinputs=0) struct wally_musig_partial_sig **partial_sig_out + (struct wally_musig_partial_sig *w) { w = 0; $1 = &w; } +%typemap(in, numinputs=0) struct wally_musig_session **session_out + (struct wally_musig_session *w) { w = 0; $1 = &w; } +%typemap(in, numinputs=0) struct wally_musig_secnonce **secnonce_out + (struct wally_musig_secnonce *w) { w = 0; $1 = &w; } +%typemap(in, numinputs=0) struct ext_key **child_out + (struct ext_key *w) { w = 0; $1 = &w; } + +/* MuSig2 nonce_gen / nonce_gen_counter return TWO opaque outputs at once + * (secnonce + pubnonce). The multi-arg typemap below matches the two + * parameters appearing consecutively (nonce_gen and nonce_gen_counter + * are the only two functions in the API where that pair appears, so the + * typemap is correctly scoped). The Java return type is Object[] of + * length 2: index 0 = secnonce holder, index 1 = pubnonce holder. */ +%typemap(in, numinputs=0) (struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out) + (struct wally_musig_secnonce *sn_local, + struct wally_musig_pubnonce *pn_local) { + sn_local = 0; pn_local = 0; + $1 = &sn_local; + $2 = &pn_local; +} +%typemap(argout) (struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out) { + jclass obj_cls = (*jenv)->FindClass(jenv, "java/lang/Object"); + jobjectArray arr = (*jenv)->NewObjectArray(jenv, 2, obj_cls, NULL); + if (*$1) + (*jenv)->SetObjectArrayElement(jenv, arr, 0, create_obj(jenv, *$1, 11)); + if (*$2) + (*jenv)->SetObjectArrayElement(jenv, arr, 1, create_obj(jenv, *$2, 12)); + $result = arr; +} +%return_decls(wally_musig_nonce_gen, Object[], jobjectArray) +%return_decls(wally_musig_nonce_gen_counter, Object[], jobjectArray) + +/* MuSig2 single-output opaque-returning functions */ +%returns_struct(wally_musig_aggnonce_parse, wally_musig_aggnonce); +%returns_struct(wally_musig_keyagg_cache_parse, wally_musig_keyagg_cache); +%returns_struct(wally_musig_pubnonce_parse, wally_musig_pubnonce); +%returns_struct(wally_musig_session_parse, wally_musig_session); +%returns_struct(wally_musig_partial_sig_parse, wally_musig_partial_sig); +%returns_struct(wally_musig_pubkey_agg, wally_musig_keyagg_cache); +%returns_struct(wally_musig_pubkeys_agg_then_derive, ext_key); +%returns_struct(wally_musig_pubkeys_derive_then_agg, wally_musig_keyagg_cache); +%returns_struct(wally_musig_pubkey_to_xpub, ext_key); +%returns_struct(wally_musig_nonce_agg, wally_musig_aggnonce); +%returns_struct(wally_musig_nonce_process, wally_musig_session); +%returns_struct(wally_musig_partial_sign, wally_musig_partial_sig); + +/* MuSig2 opaque type destructors */ +%returns_void__(wally_musig_keyagg_cache_free); +%returns_void__(wally_musig_secnonce_free); +%returns_void__(wally_musig_pubnonce_free); +%returns_void__(wally_musig_aggnonce_free); +%returns_void__(wally_musig_session_free); +%returns_void__(wally_musig_partial_sig_free); + +/* MuSig2 opaque type serializers */ +%returns_array_(wally_musig_keyagg_cache_serialize, 2, 3, WALLY_MUSIG_KEYAGG_CACHE_LEN); +%returns_array_(wally_musig_pubnonce_serialize, 2, 3, WALLY_MUSIG_PUBNONCE_LEN); +%returns_array_(wally_musig_aggnonce_serialize, 2, 3, WALLY_MUSIG_AGGNONCE_LEN); +%returns_array_(wally_musig_session_serialize, 2, 3, WALLY_MUSIG_SESSION_LEN); +%returns_array_(wally_musig_partial_sig_serialize, 2, 3, WALLY_MUSIG_PARTIAL_SIG_LEN); + +/* MuSig2 key/signature accessors */ +%returns_array_(wally_musig_pubkey_get, 2, 3, EC_PUBLIC_KEY_LEN); +%returns_array_(wally_musig_pubkey_ec_tweak_add, 4, 5, EC_PUBLIC_KEY_LEN); +%returns_array_(wally_musig_pubkey_xonly_tweak_add, 4, 5, EC_PUBLIC_KEY_LEN); +%returns_array_(wally_musig_partial_sig_agg, 5, 6, EC_SIGNATURE_LEN); +%returns_void__(wally_musig_partial_sig_verify); +#endif /* ndef BUILD_STANDARD_SECP */ + %rename("_cleanup") wally_cleanup; %returns_void__(_cleanup); @@ -1420,3 +1529,4 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %include "../include/wally_transaction.h" %include "../include/wally_transaction_members.h" %include "../include/wally_elements.h" +%include "../include/wally_musig.h" diff --git a/src/swig_python/contrib/musig.py b/src/swig_python/contrib/musig.py new file mode 100644 index 000000000..6a6ba4de6 --- /dev/null +++ b/src/swig_python/contrib/musig.py @@ -0,0 +1,60 @@ +"""Tests for the MuSig2 SWIG wrappers. + +Regression test for the opaque output-parameter typemaps: every MuSig2 +function must return its opaque result (keyagg cache, nonces, session, +partial sig) as a capsule, and nonce generation must return a +(secnonce, pubnonce) tuple. +""" +import os +import unittest + +import wallycore as wally + +if not hasattr(wally, 'musig_pubkey_agg'): + # Built against standard libsecp256k1 without the musig module + raise SystemExit(0) + + +class MuSigTests(unittest.TestCase): + + def test_musig_2of2(self): + """Aggregate, exchange nonces, sign and combine a 2-of-2 signature""" + seckeys = [os.urandom(32), os.urandom(32)] + pubkeys = [wally.ec_public_key_from_private_key(k) for k in seckeys] + msg = os.urandom(32) + + agg_pk = bytearray(32) + cache = wally.musig_pubkey_agg(b''.join(bytes(p) for p in pubkeys), agg_pk) + self.assertIsNotNone(cache) + + # Nonce generation returns a (secnonce, pubnonce) tuple + secnonces, pubnonces = [], [] + for seckey, pubkey in zip(seckeys, pubkeys): + secnonce, pubnonce = wally.musig_nonce_gen(os.urandom(32), seckey, + pubkey, cache, msg, None) + secnonces.append(secnonce) + pubnonces.append(pubnonce) + + # Pubnonces serialize/parse round-trip + serialized = [wally.musig_pubnonce_serialize(pn) for pn in pubnonces] + for ser in serialized: + self.assertIsNotNone(wally.musig_pubnonce_parse(ser)) + + aggnonce = wally.musig_nonce_agg(b''.join(bytes(s) for s in serialized), + len(serialized)) + session = wally.musig_nonce_process(aggnonce, msg, cache, None) + + partial_sigs = [] + for seckey, secnonce, pubnonce, pubkey in zip(seckeys, secnonces, + pubnonces, pubkeys): + psig = wally.musig_partial_sign(secnonce, seckey, cache, session) + wally.musig_partial_sig_verify(psig, pubnonce, pubkey, cache, session) + partial_sigs.append(wally.musig_partial_sig_serialize(psig)) + + sig = wally.musig_partial_sig_agg(b''.join(bytes(s) for s in partial_sigs), + len(partial_sigs), session) + self.assertEqual(len(sig), 64) + + +if __name__ == '__main__': + unittest.main() diff --git a/src/swig_python/python_extra.py_in b/src/swig_python/python_extra.py_in index b4fe37311..26e2efed1 100644 --- a/src/swig_python/python_extra.py_in +++ b/src/swig_python/python_extra.py_in @@ -193,6 +193,15 @@ map_keypath_get_item_fingerprint = _wrap_bin(map_keypath_get_item_fingerprint, B map_keypath_get_item_path = _wrap_int_array(map_keypath_get_item_path, map_keypath_get_item_path_len) map_keypath_public_key_init = map_keypath_public_key_init_alloc map_preimage_init = map_preimage_init_alloc +musig_aggnonce_serialize = _wrap_bin(musig_aggnonce_serialize, WALLY_MUSIG_AGGNONCE_LEN) +musig_keyagg_cache_serialize = _wrap_bin(musig_keyagg_cache_serialize, WALLY_MUSIG_KEYAGG_CACHE_LEN) +musig_partial_sig_agg = _wrap_bin(musig_partial_sig_agg, EC_SIGNATURE_LEN) +musig_partial_sig_serialize = _wrap_bin(musig_partial_sig_serialize, WALLY_MUSIG_PARTIAL_SIG_LEN) +musig_pubkey_ec_tweak_add = _wrap_bin(musig_pubkey_ec_tweak_add, EC_PUBLIC_KEY_LEN) +musig_pubkey_get = _wrap_bin(musig_pubkey_get, EC_PUBLIC_KEY_LEN) +musig_pubkey_xonly_tweak_add = _wrap_bin(musig_pubkey_xonly_tweak_add, EC_PUBLIC_KEY_LEN) +musig_pubnonce_serialize = _wrap_bin(musig_pubnonce_serialize, WALLY_MUSIG_PUBNONCE_LEN) +musig_session_serialize = _wrap_bin(musig_session_serialize, WALLY_MUSIG_SESSION_LEN) pbkdf2_hmac_sha256 = _wrap_bin(pbkdf2_hmac_sha256, PBKDF2_HMAC_SHA256_LEN) pbkdf2_hmac_sha512 = _wrap_bin(pbkdf2_hmac_sha512, PBKDF2_HMAC_SHA512_LEN) psbt_clone = psbt_clone_alloc diff --git a/src/swig_python/swig.i b/src/swig_python/swig.i index 77ced5827..a843d0032 100644 --- a/src/swig_python/swig.i +++ b/src/swig_python/swig.i @@ -40,6 +40,7 @@ del swig_import_helper #include "../include/wally_transaction.h" #include "../include/wally_transaction_members.h" #include "../include/wally_elements.h" +#include "../include/wally_musig.h" #include "../internal.h" #undef malloc @@ -101,6 +102,14 @@ capsule_dtor(wally_tx_input, wally_tx_input_free) capsule_dtor(wally_tx_output, wally_tx_output_free) capsule_dtor(wally_tx_witness_stack, wally_tx_witness_stack_free) capsule_dtor(wally_map, wally_map_free) +#ifndef BUILD_STANDARD_SECP +capsule_dtor(wally_musig_keyagg_cache, wally_musig_keyagg_cache_free) +capsule_dtor(wally_musig_secnonce, wally_musig_secnonce_free) +capsule_dtor(wally_musig_pubnonce, wally_musig_pubnonce_free) +capsule_dtor(wally_musig_aggnonce, wally_musig_aggnonce_free) +capsule_dtor(wally_musig_session, wally_musig_session_free) +capsule_dtor(wally_musig_partial_sig, wally_musig_partial_sig_free) +#endif /* ndef BUILD_STANDARD_SECP */ static void destroy_words(PyObject *obj) { (void)obj; } #define MAX_LOCAL_STACK 256u @@ -338,6 +347,8 @@ static void destroy_words(PyObject *obj) { (void)obj; } /* BEGIN AUTOGENERATED */ %pybuffer_nullable_binary(const unsigned char* abf, size_t abf_len); +%pybuffer_nullable_binary(const unsigned char* adaptor, size_t adaptor_len); +%pybuffer_nullable_binary(const unsigned char* agg_pk, size_t agg_pk_len); %pybuffer_nullable_binary(const unsigned char* annex, size_t annex_len); %pybuffer_nullable_binary(const unsigned char* asset, size_t asset_len); %pybuffer_nullable_binary(const unsigned char* aux_rand, size_t aux_rand_len); @@ -348,6 +359,7 @@ static void destroy_words(PyObject *obj) { (void)obj; } %pybuffer_nullable_binary(const unsigned char* contract_hash, size_t contract_hash_len); %pybuffer_nullable_binary(const unsigned char* entropy, size_t entropy_len); %pybuffer_nullable_binary(const unsigned char* extra, size_t extra_len); +%pybuffer_nullable_binary(const unsigned char* extra_input32, size_t extra_input32_len); %pybuffer_nullable_binary(const unsigned char* final_scriptsig, size_t final_scriptsig_len); %pybuffer_nullable_binary(const unsigned char* fingerprint, size_t fingerprint_len); %pybuffer_nullable_binary(const unsigned char* generator, size_t generator_len); @@ -365,6 +377,7 @@ static void destroy_words(PyObject *obj) { (void)obj; } %pybuffer_nullable_binary(const unsigned char* mainchain_script, size_t mainchain_script_len); %pybuffer_nullable_binary(const unsigned char* merkle_hashes, size_t merkle_hashes_len); %pybuffer_nullable_binary(const unsigned char* merkle_root, size_t merkle_root_len); +%pybuffer_nullable_binary(const unsigned char* msg32, size_t msg32_len); %pybuffer_nullable_binary(const unsigned char* nonce, size_t nonce_len); %pybuffer_nullable_binary(const unsigned char* nonce_hash, size_t nonce_hash_len); %pybuffer_nullable_binary(const unsigned char* offline_keys, size_t offline_keys_len); @@ -375,10 +388,13 @@ static void destroy_words(PyObject *obj) { (void)obj; } %pybuffer_nullable_binary(const unsigned char* output_asset, size_t output_asset_len); %pybuffer_nullable_binary(const unsigned char* output_generator, size_t output_generator_len); %pybuffer_nullable_binary(const unsigned char* parent160, size_t parent160_len); +%pybuffer_nullable_binary(const unsigned char* partial_sigs, size_t partial_sigs_len); %pybuffer_nullable_binary(const unsigned char* pass, size_t pass_len); %pybuffer_nullable_binary(const unsigned char* priv_key, size_t priv_key_len); %pybuffer_nullable_binary(const unsigned char* proof, size_t proof_len); %pybuffer_nullable_binary(const unsigned char* pub_key, size_t pub_key_len); +%pybuffer_nullable_binary(const unsigned char* pub_keys, size_t pub_keys_len); +%pybuffer_nullable_binary(const unsigned char* pubnonces, size_t pubnonces_len); %pybuffer_nullable_binary(const unsigned char* rangeproof, size_t rangeproof_len); %pybuffer_nullable_binary(const unsigned char* redeem_script, size_t redeem_script_len); %pybuffer_nullable_binary(const unsigned char* s2c_data, size_t s2c_data_len); @@ -387,6 +403,8 @@ static void destroy_words(PyObject *obj) { (void)obj; } %pybuffer_nullable_binary(const unsigned char* scalar, size_t scalar_len); %pybuffer_nullable_binary(const unsigned char* script, size_t script_len); %pybuffer_nullable_binary(const unsigned char* scriptpubkey, size_t scriptpubkey_len); +%pybuffer_nullable_binary(const unsigned char* seckey, size_t seckey_len); +%pybuffer_nullable_binary(const unsigned char* session_secrand32, size_t session_secrand32_len); %pybuffer_nullable_binary(const unsigned char* sig, size_t sig_len); %pybuffer_nullable_binary(const unsigned char* sub_pubkey, size_t sub_pubkey_len); %pybuffer_nullable_binary(const unsigned char* summed_key, size_t summed_key_len); @@ -403,12 +421,16 @@ static void destroy_words(PyObject *obj) { (void)obj; } %pybuffer_nullable_binary(const unsigned char* vbf, size_t vbf_len); %pybuffer_nullable_binary(const unsigned char* whitelistproof, size_t whitelistproof_len); %pybuffer_nullable_binary(const unsigned char* witness, size_t witness_len); +%pybuffer_nullable_binary(const unsigned char* xpubs, size_t xpubs_len); %pybuffer_nullable_binary(void* bytes, size_t bytes_len); %pybuffer_output_binary(unsigned char* abf_out, size_t abf_out_len); +%pybuffer_output_binary(unsigned char* agg_pk_out, size_t agg_pk_out_len); %pybuffer_output_binary(unsigned char* asset_out, size_t asset_out_len); %pybuffer_output_binary(unsigned char* bytes_out, size_t len); +%pybuffer_output_binary(unsigned char* pub_key_out, size_t pub_key_out_len); %pybuffer_output_binary(unsigned char* s2c_opening_out, size_t s2c_opening_out_len); %pybuffer_output_binary(unsigned char* scalar, size_t scalar_len); +%pybuffer_output_binary(unsigned char* sig64_out, size_t sig64_out_len); %pybuffer_output_binary(unsigned char* vbf_out, size_t vbf_out_len); %ignore bip32_key_from_base58; %ignore bip32_key_from_base58_n; @@ -441,6 +463,12 @@ static void destroy_words(PyObject *obj) { (void)obj; } %ignore wally_tx_output_free; %ignore wally_tx_witness_stack_free; %ignore wally_map_free; +%ignore wally_musig_keyagg_cache_free; +%ignore wally_musig_secnonce_free; +%ignore wally_musig_pubnonce_free; +%ignore wally_musig_aggnonce_free; +%ignore wally_musig_session_free; +%ignore wally_musig_partial_sig_free; %py_int_array(uint32_t, 0xffffffffull, child_path, child_path_len) %py_int_array(uint32_t, 0xffull, sighash, sighash_len) @@ -458,6 +486,55 @@ static void destroy_words(PyObject *obj) { (void)obj; } %py_opaque_struct(wally_tx_witness_stack); %py_opaque_struct(wally_map) %py_opaque_struct(words); +#ifndef BUILD_STANDARD_SECP +%py_opaque_struct(wally_musig_keyagg_cache); +%py_opaque_struct(wally_musig_secnonce); +%py_opaque_struct(wally_musig_pubnonce); +%py_opaque_struct(wally_musig_aggnonce); +%py_opaque_struct(wally_musig_session); +%py_opaque_struct(wally_musig_partial_sig); + +/* MuSig2 functions return their opaque types via output parameters that + * are not named "output" (cache_out, secnonce_out/pubnonce_out, + * aggnonce_out, session_out, partial_sig_out, child_out). The + * %py_opaque_struct in-typemap only matches the literal name "output", + * so without the typemaps below the raw pointer-to-pointer argument + * leaks into the Python signature and passing None crashes in the + * argout typemap. These mirror the Java typemaps for the same names. */ +%typemap(in, numinputs=0) struct wally_musig_keyagg_cache **cache_out + (struct wally_musig_keyagg_cache *w) { w = 0; $1 = ($1_ltype)&w; } +%typemap(in, numinputs=0) struct wally_musig_aggnonce **aggnonce_out + (struct wally_musig_aggnonce *w) { w = 0; $1 = ($1_ltype)&w; } +%typemap(in, numinputs=0) struct wally_musig_partial_sig **partial_sig_out + (struct wally_musig_partial_sig *w) { w = 0; $1 = ($1_ltype)&w; } +%typemap(in, numinputs=0) struct wally_musig_session **session_out + (struct wally_musig_session *w) { w = 0; $1 = ($1_ltype)&w; } +%typemap(in, numinputs=0) struct wally_musig_secnonce **secnonce_out + (struct wally_musig_secnonce *w) { w = 0; $1 = ($1_ltype)&w; } +%typemap(in, numinputs=0) struct ext_key **child_out + (struct ext_key *w) { w = 0; $1 = ($1_ltype)&w; } + +/* nonce_gen/nonce_gen_counter return a (secnonce, pubnonce) pair; wrap + * the two consecutive opaque outputs as a Python 2-tuple of capsules. */ +%typemap(in, numinputs=0) (struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out) + (struct wally_musig_secnonce *sn_local, + struct wally_musig_pubnonce *pn_local) { + sn_local = 0; pn_local = 0; + $1 = &sn_local; + $2 = &pn_local; +} +%typemap(argout) (struct wally_musig_secnonce **secnonce_out, + struct wally_musig_pubnonce **pubnonce_out) { + if (*$1 != NULL && *$2 != NULL) { + PyObject *tuple = PyTuple_New(2); + PyTuple_SetItem(tuple, 0, PyCapsule_New(*$1, "struct wally_musig_secnonce *", destroy_wally_musig_secnonce)); + PyTuple_SetItem(tuple, 1, PyCapsule_New(*$2, "struct wally_musig_pubnonce *", destroy_wally_musig_pubnonce)); + Py_DecRef($result); + $result = tuple; + } +} +#endif /* ndef BUILD_STANDARD_SECP */ %rename("%(regex:/^wally_(.+)/\\1/)s", %$isfunction) ""; @@ -480,3 +557,4 @@ static void destroy_words(PyObject *obj) { (void)obj; } %include "../include/wally_transaction.h" %include "../include/wally_transaction_members.h" %include "../include/wally_elements.h" +%include "../include/wally_musig.h" diff --git a/src/test/test_musig.py b/src/test/test_musig.py new file mode 100644 index 000000000..f2879bc1f --- /dev/null +++ b/src/test/test_musig.py @@ -0,0 +1,1214 @@ +import unittest +from ctypes import * +from util import * + +EC_PUBLIC_KEY_LEN = 33 +EC_XONLY_PUBLIC_KEY_LEN = 32 +EC_SIGNATURE_LEN = 64 +EC_FLAG_SCHNORR = 0x2 +WALLY_SIGHASH_DEFAULT = 0x00 + +BIP32_VER_MAIN_PUBLIC = 0x0488B21E +BIP32_VER_MAIN_PRIVATE = 0x0488ADE4 +BIP32_VER_TEST_PUBLIC = 0x043587CF +BIP32_INITIAL_HARDENED_CHILD = 0x80000000 +BIP32_FLAG_KEY_PUBLIC = 0x1 +BIP32_SERIALIZED_LEN = 78 + +MUSIG_PUBNONCE_LEN = 66 +MUSIG_AGGNONCE_LEN = 66 +MUSIG_PARTIAL_SIG_LEN = 32 +MUSIG_KEYAGG_CACHE_LEN = 197 +MUSIG_SESSION_LEN = 133 + +SECKEY1 = bytes([0x01] * 32) +SECKEY2 = bytes([0x02] * 32) +SECKEY3 = bytes([0x03] * 32) +TEST_MSG32 = bytes([0xde, 0xad, 0xbe, 0xef] * 8) +TEST_TWEAK = bytes([0xab, 0xcd] * 16) + + +def derive_pubkey(seckey): + pub, pub_len = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + ret = wally_ec_public_key_from_private_key(seckey, len(seckey), pub, pub_len) + assert ret == WALLY_OK, 'derive_pubkey failed' + return pub + + +def musig_full_flow(seckeys, msg32): + """ + Run a complete MuSig2 flow for n signers. + Returns (final_sig_bytes, agg_pk_xonly_bytes) or raises AssertionError. + """ + n = len(seckeys) + pubkeys = [derive_pubkey(sk) for sk in seckeys] + + # Key aggregation + pub_keys_flat = b''.join(pubkeys) + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + ret = wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), agg_pk, EC_XONLY_PUBLIC_KEY_LEN, cache) + assert ret == WALLY_OK, 'pubkey_agg failed' + assert cache.value is not None + + # Nonce generation + secnonces = [] + pubnonces = [] + pn_bytes_list = [] + for i, (sk, pk) in enumerate(zip(seckeys, pubkeys)): + session_id = bytes([i + 1]) * 32 + sn = c_void_p() + pn = c_void_p() + ret = wally_musig_nonce_gen(session_id, 32, sk, 32, pk, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn, pn) + assert ret == WALLY_OK, 'nonce_gen failed' + assert sn.value is not None + assert pn.value is not None + secnonces.append(sn) + pubnonces.append(pn) + + pn_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + ret = wally_musig_pubnonce_serialize(pn.value, pn_bytes, MUSIG_PUBNONCE_LEN) + assert ret == WALLY_OK, 'pubnonce_serialize failed' + pn_bytes_list.append(bytes(pn_bytes)) + + # Nonce aggregation + pubnonces_flat = b''.join(pn_bytes_list) + aggnonce = c_void_p() + ret = wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), n, aggnonce) + assert ret == WALLY_OK, 'nonce_agg failed' + assert aggnonce.value is not None + + # Nonce processing + session = c_void_p() + ret = wally_musig_nonce_process(aggnonce.value, msg32, 32, cache.value, None, 0, session) + assert ret == WALLY_OK, 'nonce_process failed' + assert session.value is not None + + # Partial signing + partial_sigs = [] + ps_bytes_list = [] + for i, (sn, sk) in enumerate(zip(secnonces, seckeys)): + psig = c_void_p() + ret = wally_musig_partial_sign(sn.value, sk, 32, cache.value, session.value, psig) + assert ret == WALLY_OK, f'partial_sign failed for signer {i}' + assert psig.value is not None + partial_sigs.append(psig) + + ps_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + ret = wally_musig_partial_sig_serialize(psig.value, ps_bytes, MUSIG_PARTIAL_SIG_LEN) + assert ret == WALLY_OK, 'partial_sig_serialize failed' + ps_bytes_list.append(bytes(ps_bytes)) + + # Partial sig verification + for i, (psig, pn, pk) in enumerate(zip(partial_sigs, pubnonces, pubkeys)): + ret = wally_musig_partial_sig_verify(psig.value, pn.value, pk, EC_PUBLIC_KEY_LEN, + cache.value, session.value) + assert ret == WALLY_OK, f'partial_sig_verify failed for signer {i}' + + # Sig aggregation + partial_sigs_flat = b''.join(ps_bytes_list) + final_sig, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + ret = wally_musig_partial_sig_agg(partial_sigs_flat, len(partial_sigs_flat), n, + session.value, final_sig, EC_SIGNATURE_LEN) + assert ret == WALLY_OK, 'partial_sig_agg failed' + + # Cleanup + for sn in secnonces: + if sn.value: + wally_musig_secnonce_free(sn.value) + for pn in pubnonces: + if pn.value: + wally_musig_pubnonce_free(pn.value) + for psig in partial_sigs: + if psig.value: + wally_musig_partial_sig_free(psig.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + return bytes(final_sig), bytes(agg_pk) + + +class MuSig2Tests(unittest.TestCase): + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_2of2_full_flow(self): + """2-of-2 full signing flow with BIP-340 signature verification""" + seckeys = [SECKEY1, SECKEY2] + pubkeys = [derive_pubkey(sk) for sk in seckeys] + + pub_keys_flat = b''.join(pubkeys) + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + agg_pk, EC_XONLY_PUBLIC_KEY_LEN, cache)) + self.assertIsNotNone(cache.value) + self.assertNotEqual(bytes(agg_pk), b'\x00' * EC_XONLY_PUBLIC_KEY_LEN) + + final_sig, agg_pk_bytes = musig_full_flow(seckeys, TEST_MSG32) + self.assertNotEqual(final_sig, b'\x00' * EC_SIGNATURE_LEN) + + # Verify the final signature is a valid BIP-340 Schnorr sig + ret = wally_ec_sig_verify(agg_pk_bytes, EC_XONLY_PUBLIC_KEY_LEN, + TEST_MSG32, 32, + EC_FLAG_SCHNORR, final_sig, EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, ret) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_3of3_full_flow(self): + """3-of-3 full signing flow with BIP-340 signature verification""" + seckeys = [SECKEY1, SECKEY2, SECKEY3] + final_sig, agg_pk_bytes = musig_full_flow(seckeys, TEST_MSG32) + self.assertNotEqual(final_sig, b'\x00' * EC_SIGNATURE_LEN) + ret = wally_ec_sig_verify(agg_pk_bytes, EC_XONLY_PUBLIC_KEY_LEN, + TEST_MSG32, 32, + EC_FLAG_SCHNORR, final_sig, EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, ret) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_keyagg(self): + """Key aggregation produces a consistent x-only key""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + + pub_keys_12 = pk1 + pk2 + pub_keys_21 = pk2 + pk1 + + agg_pk_12, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + agg_pk_21, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + + cache_12 = c_void_p() + cache_21 = c_void_p() + + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_12, len(pub_keys_12), + agg_pk_12, EC_XONLY_PUBLIC_KEY_LEN, cache_12)) + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_21, len(pub_keys_21), + agg_pk_21, EC_XONLY_PUBLIC_KEY_LEN, cache_21)) + + # Order of pubkeys changes the aggregate key + self.assertNotEqual(bytes(agg_pk_12), bytes(agg_pk_21)) + + # wally_musig_pubkey_get returns a compressed (33-byte) aggregate key + comp_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_get(cache_12.value, comp_pk, EC_PUBLIC_KEY_LEN)) + # First byte should be 0x02 or 0x03 (compressed) + self.assertIn(bytes(comp_pk)[0:1], [b'\x02', b'\x03']) + # The x-coordinate of the compressed key matches agg_pk_12 + self.assertEqual(bytes(comp_pk)[1:], bytes(agg_pk_12)) + + wally_musig_keyagg_cache_free(cache_12.value) + wally_musig_keyagg_cache_free(cache_21.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_malformed_cache_no_abort(self): + """A malformed keyagg_cache must be rejected at parse, not abort() the process.""" + # A wrong-magic but correctly sized buffer fails the secp256k1 precondition + # check inside parse; with the illegal-arg callback installed this must + # return an error (leaving output NULL) rather than abort() the process. + bad_bytes, _ = make_cbuffer('11' * MUSIG_KEYAGG_CACHE_LEN) + cache = c_void_p() + self.assertEqual(WALLY_EINVAL, + wally_musig_keyagg_cache_parse(bad_bytes, MUSIG_KEYAGG_CACHE_LEN, cache)) + self.assertEqual(None, cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_ec_tweak(self): + """EC tweak modifies the aggregate key and signing still works""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + tweaked_pub, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_ec_tweak_add(cache.value, TEST_TWEAK, 32, + tweaked_pub, EC_PUBLIC_KEY_LEN)) + self.assertNotEqual(bytes(tweaked_pub), b'\x00' * EC_PUBLIC_KEY_LEN) + self.assertIn(bytes(tweaked_pub)[0:1], [b'\x02', b'\x03']) + + wally_musig_keyagg_cache_free(cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_xonly_tweak(self): + """X-only tweak modifies the aggregate key and the result is a valid key""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + tweaked_pub, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_xonly_tweak_add(cache.value, TEST_TWEAK, 32, + tweaked_pub, EC_PUBLIC_KEY_LEN)) + self.assertNotEqual(bytes(tweaked_pub), b'\x00' * EC_PUBLIC_KEY_LEN) + self.assertIn(bytes(tweaked_pub)[0:1], [b'\x02', b'\x03']) + + wally_musig_keyagg_cache_free(cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_serialization_roundtrip(self): + """Serialize and parse each type, compare bytes""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + # keyagg_cache roundtrip + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + cache_bytes, _ = make_cbuffer('00' * MUSIG_KEYAGG_CACHE_LEN) + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_serialize(cache.value, cache_bytes, + MUSIG_KEYAGG_CACHE_LEN)) + cache2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_parse(cache_bytes, MUSIG_KEYAGG_CACHE_LEN, cache2)) + cache2_bytes, _ = make_cbuffer('00' * MUSIG_KEYAGG_CACHE_LEN) + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_serialize(cache2.value, cache2_bytes, + MUSIG_KEYAGG_CACHE_LEN)) + self.assertEqual(bytes(cache_bytes), bytes(cache2_bytes)) + + # pubnonce roundtrip + sn1 = c_void_p() + pn1 = c_void_p() + session_id1 = bytes([0x01] * 32) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id1, 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + pn1_parsed = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubnonce_parse(pn1_bytes, MUSIG_PUBNONCE_LEN, pn1_parsed)) + pn1_bytes2, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1_parsed.value, pn1_bytes2, MUSIG_PUBNONCE_LEN)) + self.assertEqual(bytes(pn1_bytes), bytes(pn1_bytes2)) + + sn2 = c_void_p() + pn2 = c_void_p() + session_id2 = bytes([0x02] * 32) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id2, 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + + # aggnonce roundtrip + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + an_bytes, _ = make_cbuffer('00' * MUSIG_AGGNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_aggnonce_serialize(aggnonce.value, an_bytes, MUSIG_AGGNONCE_LEN)) + aggnonce2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_aggnonce_parse(an_bytes, MUSIG_AGGNONCE_LEN, aggnonce2)) + an_bytes2, _ = make_cbuffer('00' * MUSIG_AGGNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_aggnonce_serialize(aggnonce2.value, an_bytes2, MUSIG_AGGNONCE_LEN)) + self.assertEqual(bytes(an_bytes), bytes(an_bytes2)) + + # session roundtrip + session = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_process(aggnonce.value, TEST_MSG32, 32, + cache.value, None, 0, session)) + sess_bytes, _ = make_cbuffer('00' * MUSIG_SESSION_LEN) + self.assertEqual(WALLY_OK, wally_musig_session_serialize(session.value, sess_bytes, MUSIG_SESSION_LEN)) + session2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_session_parse(sess_bytes, MUSIG_SESSION_LEN, session2)) + sess_bytes2, _ = make_cbuffer('00' * MUSIG_SESSION_LEN) + self.assertEqual(WALLY_OK, wally_musig_session_serialize(session2.value, sess_bytes2, MUSIG_SESSION_LEN)) + self.assertEqual(bytes(sess_bytes), bytes(sess_bytes2)) + + # partial_sig roundtrip + psig1 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_partial_sign(sn1.value, SECKEY1, 32, + cache.value, session.value, psig1)) + ps_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_serialize(psig1.value, ps_bytes, MUSIG_PARTIAL_SIG_LEN)) + psig_parsed = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_partial_sig_parse(ps_bytes, MUSIG_PARTIAL_SIG_LEN, psig_parsed)) + ps_bytes2, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_serialize(psig_parsed.value, ps_bytes2, MUSIG_PARTIAL_SIG_LEN)) + self.assertEqual(bytes(ps_bytes), bytes(ps_bytes2)) + + # Cleanup + wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1_parsed.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_partial_sig_free(psig1.value) + wally_musig_partial_sig_free(psig_parsed.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_aggnonce_free(aggnonce2.value) + wally_musig_session_free(session.value) + wally_musig_session_free(session2.value) + wally_musig_keyagg_cache_free(cache.value) + wally_musig_keyagg_cache_free(cache2.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_nonce_gen_counter(self): + """Counter-based nonce generation is deterministic""" + pk1 = derive_pubkey(SECKEY1) + + sn0a = c_void_p() + pn0a = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen_counter(0, SECKEY1, 32, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn0a, pn0a)) + self.assertIsNotNone(sn0a.value) + self.assertIsNotNone(pn0a.value) + + sn0b = c_void_p() + pn0b = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen_counter(0, SECKEY1, 32, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn0b, pn0b)) + + sn1 = c_void_p() + pn1 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen_counter(1, SECKEY1, 32, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + + # Serialize for comparison + pn0a_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn0b_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn0a.value, pn0a_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn0b.value, pn0b_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + + # Same counter -> same pubnonce (deterministic) + self.assertEqual(bytes(pn0a_bytes), bytes(pn0b_bytes)) + # Different counter -> different pubnonce + self.assertNotEqual(bytes(pn0a_bytes), bytes(pn1_bytes)) + + # seckey=NULL is WALLY_EINVAL for counter mode + sn_bad = c_void_p() + pn_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_gen_counter(0, None, 0, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn_bad, pn_bad)) + + # Cleanup + wally_musig_secnonce_free(sn0a.value) + wally_musig_secnonce_free(sn0b.value) + wally_musig_secnonce_free(sn1.value) + wally_musig_pubnonce_free(pn0a.value) + wally_musig_pubnonce_free(pn0b.value) + wally_musig_pubnonce_free(pn1.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_secnonce_consumed_after_sign(self): + """Verify the secnonce is consumed (zeroed) after partial_sign succeeds, + and is not consumed when signing with the wrong key.""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + session_id1 = bytes([0x10] * 32) + session_id2 = bytes([0x20] * 32) + sn1 = c_void_p() + pn1 = c_void_p() + sn2 = c_void_p() + pn2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id1, 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id2, 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + + session = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_process(aggnonce.value, TEST_MSG32, 32, + cache.value, None, 0, session)) + + # Signing with a key that doesn't match the secnonce fails + # without consuming the secnonce + psig1 = c_void_p() + ret = wally_musig_partial_sign(sn1.value, SECKEY2, 32, cache.value, session.value, psig1) + self.assertEqual(WALLY_EINVAL, ret) + self.assertIsNone(psig1.value) + + # Sign: should succeed and produce a non-NULL partial sig + ret = wally_musig_partial_sign(sn1.value, SECKEY1, 32, cache.value, session.value, psig1) + self.assertEqual(WALLY_OK, ret) + self.assertIsNotNone(psig1.value) + + # The secnonce is now zeroed, so it can't be used again + psig2 = c_void_p() + ret = wally_musig_partial_sign(sn1.value, SECKEY1, 32, cache.value, session.value, psig2) + self.assertEqual(WALLY_EINVAL, ret) + self.assertIsNone(psig2.value) + + # Cleanup + wally_musig_secnonce_free(sn1.value) + wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_partial_sig_free(psig1.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_partial_sig_verify_fails_on_bad_sig(self): + """Corrupting a partial sig bytes causes verify to return WALLY_ERROR""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + session_id1 = bytes([0x30] * 32) + session_id2 = bytes([0x40] * 32) + sn1 = c_void_p() + pn1 = c_void_p() + sn2 = c_void_p() + pn2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id1, 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id2, 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + + session = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_process(aggnonce.value, TEST_MSG32, 32, + cache.value, None, 0, session)) + + psig1 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_partial_sign(sn1.value, SECKEY1, 32, + cache.value, session.value, psig1)) + + # Serialize, corrupt, parse back + ps_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_serialize(psig1.value, ps_bytes, MUSIG_PARTIAL_SIG_LEN)) + + corrupted = bytearray(ps_bytes) + corrupted[0] ^= 0xff + corrupted_buf = bytes(corrupted) + + psig1_bad = c_void_p() + ret = wally_musig_partial_sig_parse(corrupted_buf, MUSIG_PARTIAL_SIG_LEN, psig1_bad) + if ret == WALLY_OK and psig1_bad.value is not None: + # If parsing succeeds, verify should fail + ret_v = wally_musig_partial_sig_verify(psig1_bad.value, pn1.value, pk1, EC_PUBLIC_KEY_LEN, + cache.value, session.value) + self.assertNotEqual(WALLY_OK, ret_v) + wally_musig_partial_sig_free(psig1_bad.value) + else: + # Parse itself rejected the corrupted sig + self.assertNotEqual(WALLY_OK, ret) + + # Cleanup + wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_partial_sig_free(psig1.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_invalid_args(self): + """Input validation returns WALLY_EINVAL""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + # wally_musig_pubkey_agg: NULL pubkeys + cache_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_pubkey_agg(None, 66, None, 0, cache_bad)) + # wrong length (not multiple of 33) + self.assertEqual(WALLY_EINVAL, wally_musig_pubkey_agg(pub_keys_flat, 32, None, 0, cache_bad)) + # only 1 key (min is 2) + self.assertEqual(WALLY_EINVAL, wally_musig_pubkey_agg(pk1, EC_PUBLIC_KEY_LEN, None, 0, cache_bad)) + + # wally_musig_nonce_gen: NULL session_secrand32 + sn_bad = c_void_p() + pn_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_gen(None, 0, SECKEY1, 32, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn_bad, pn_bad)) + # all-zero session_secrand32 must be rejected (defense-in-depth: it must be + # unique and uniformly random; all-zero is the common uninitialized mistake) + zero_secrand = bytes(32) + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_gen(zero_secrand, 32, SECKEY1, 32, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn_bad, pn_bad)) + # NULL pubkey + session_id = bytes([0xff] * 32) + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_gen(session_id, 32, SECKEY1, 32, None, 0, + None, None, 0, None, 0, sn_bad, pn_bad)) + # seckey non-NULL but seckey_len=0 + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_gen(session_id, 32, SECKEY1, 0, pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn_bad, pn_bad)) + + # wally_musig_nonce_agg: n_pubnonces=1 (min is 2) + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + sn1 = c_void_p() + pn1 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0x01] * 32), 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + an_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_agg(bytes(pn1_bytes), MUSIG_PUBNONCE_LEN, 1, an_bad)) + + # wally_musig_nonce_process: NULL msg32 + sn2 = c_void_p() + pn2 = c_void_p() + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0x02] * 32), 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + # Counts whose total length overflows to the given length are rejected + n_overflow = (1 << 63) + 2 if sizeof(c_size_t) == 8 else (1 << 31) + 2 + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), + n_overflow, an_bad)) + self.assertIsNone(an_bad.value) + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + + session_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_process(aggnonce.value, None, 0, cache.value, + None, 0, session_bad)) + # msg32 wrong length + self.assertEqual(WALLY_EINVAL, wally_musig_nonce_process(aggnonce.value, bytes(31), 31, cache.value, + None, 0, session_bad)) + + # wally_musig_partial_sig_agg: n_sigs=1 + session = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_process(aggnonce.value, TEST_MSG32, 32, + cache.value, None, 0, session)) + psig1 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_partial_sign(sn1.value, SECKEY1, 32, + cache.value, session.value, psig1)) + ps1_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_serialize(psig1.value, ps1_bytes, MUSIG_PARTIAL_SIG_LEN)) + final_sig, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + self.assertEqual(WALLY_EINVAL, wally_musig_partial_sig_agg(bytes(ps1_bytes), MUSIG_PARTIAL_SIG_LEN, 1, + session.value, final_sig, EC_SIGNATURE_LEN)) + n_overflow = (1 << 62) + 2 if sizeof(c_size_t) == 8 else (1 << 29) + 2 + self.assertEqual(WALLY_EINVAL, wally_musig_partial_sig_agg(bytes(ps1_bytes) * 2, MUSIG_PARTIAL_SIG_LEN * 2, + n_overflow, session.value, + final_sig, EC_SIGNATURE_LEN)) + + # tweak functions: wrong tweak_len + self.assertEqual(WALLY_EINVAL, wally_musig_pubkey_ec_tweak_add(cache.value, TEST_TWEAK, 31, + None, 0)) + self.assertEqual(WALLY_EINVAL, wally_musig_pubkey_xonly_tweak_add(cache.value, TEST_TWEAK, 31, + None, 0)) + + # Serialization with wrong output buffer length + cache_bytes_short, _ = make_cbuffer('00' * (MUSIG_KEYAGG_CACHE_LEN - 1)) + self.assertEqual(WALLY_EINVAL, wally_musig_keyagg_cache_serialize(cache.value, cache_bytes_short, + MUSIG_KEYAGG_CACHE_LEN - 1)) + + # Parse with wrong input byte length + cache_bytes_ok, _ = make_cbuffer('00' * MUSIG_KEYAGG_CACHE_LEN) + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_serialize(cache.value, cache_bytes_ok, + MUSIG_KEYAGG_CACHE_LEN)) + cache_parsed_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_keyagg_cache_parse(cache_bytes_ok, + MUSIG_KEYAGG_CACHE_LEN - 1, + cache_parsed_bad)) + pn_bytes_short, _ = make_cbuffer('00' * (MUSIG_PUBNONCE_LEN - 1)) + pn_parsed_bad = c_void_p() + self.assertEqual(WALLY_EINVAL, wally_musig_pubnonce_parse(pn_bytes_short, MUSIG_PUBNONCE_LEN - 1, + pn_parsed_bad)) + + # Cleanup + wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_partial_sig_free(psig1.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_tweaked_key_signing(self): + """Sign with a tweaked aggregate key and verify against tweaked key""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + # Apply xonly tweak (BIP-341 style) + tweaked_pub, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_xonly_tweak_add(cache.value, TEST_TWEAK, 32, + tweaked_pub, EC_PUBLIC_KEY_LEN)) + tweaked_xonly = bytes(tweaked_pub)[1:] # x-only from compressed + + # Run full signing with tweaked cache + session_id1 = bytes([0x51] * 32) + session_id2 = bytes([0x52] * 32) + sn1 = c_void_p() + pn1 = c_void_p() + sn2 = c_void_p() + pn2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id1, 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(session_id2, 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + + session = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_process(aggnonce.value, TEST_MSG32, 32, + cache.value, None, 0, session)) + + psig1 = c_void_p() + psig2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_partial_sign(sn1.value, SECKEY1, 32, + cache.value, session.value, psig1)) + self.assertEqual(WALLY_OK, wally_musig_partial_sign(sn2.value, SECKEY2, 32, + cache.value, session.value, psig2)) + + ps1_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + ps2_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_serialize(psig1.value, ps1_bytes, MUSIG_PARTIAL_SIG_LEN)) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_serialize(psig2.value, ps2_bytes, MUSIG_PARTIAL_SIG_LEN)) + + partial_sigs_flat = bytes(ps1_bytes) + bytes(ps2_bytes) + final_sig, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, wally_musig_partial_sig_agg(partial_sigs_flat, len(partial_sigs_flat), 2, + session.value, final_sig, EC_SIGNATURE_LEN)) + + # Verify against the tweaked aggregate key (x-only) + ret = wally_ec_sig_verify(tweaked_xonly, EC_XONLY_PUBLIC_KEY_LEN, + TEST_MSG32, 32, + EC_FLAG_SCHNORR, final_sig, EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, ret) + + # Cleanup + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_partial_sig_free(psig1.value) + wally_musig_partial_sig_free(psig2.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_synthetic_xpub_construction(self): + """BIP-328: synthetic xpub from 2-of-2 aggregate key""" + seckeys = [SECKEY1, SECKEY2] + pubkeys = [derive_pubkey(sk) for sk in seckeys] + pub_keys_flat = b''.join(pubkeys) + + cache = c_void_p() + ret = wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, byref(cache)) + self.assertEqual(WALLY_OK, ret) + agg_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubkey_get(cache, agg_pk, EC_PUBLIC_KEY_LEN)) + wally_musig_keyagg_cache_free(cache) + + xpub = POINTER(ext_key)() + ret = wally_musig_pubkey_to_xpub(agg_pk, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub)) + self.assertEqual(WALLY_OK, ret) + self.assertIsNotNone(xpub) + + # Verify depth=0, child_num=0, parent fingerprint=0 + self.assertEqual(0, xpub.contents.depth) + self.assertEqual(0, xpub.contents.child_num) + self.assertEqual(b'\x00' * 20, bytes(xpub.contents.parent160)) + + # Verify the chaincode matches BIP-328 constant + expected_cc = bytes([ + 0x86, 0x80, 0x87, 0xca, 0x02, 0xa6, 0xf9, 0x74, + 0xc4, 0x59, 0x89, 0x24, 0xc3, 0x6b, 0x57, 0x76, + 0x2d, 0x32, 0xcb, 0x45, 0x71, 0x71, 0x67, 0xe3, + 0x00, 0x62, 0x2c, 0x71, 0x67, 0xe3, 0x89, 0x65 + ]) + self.assertEqual(expected_cc, bytes(xpub.contents.chain_code)) + + # Serialize to base58 and verify it starts with 'xpub' + ret, b58_str = bip32_key_to_base58(xpub, BIP32_FLAG_KEY_PUBLIC) + self.assertEqual(WALLY_OK, ret) + b58_decoded = b58_str.decode('ascii') if isinstance(b58_str, bytes) else b58_str + self.assertTrue(b58_decoded.startswith('xpub'), + f'Expected xpub prefix, got: {b58_decoded[:4]}') + + bip32_key_free(xpub) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_synthetic_xpub_unhardened_derivation(self): + """BIP-328: unhardened child derivation from synthetic xpub succeeds""" + seckeys = [SECKEY1, SECKEY2] + pubkeys = [derive_pubkey(sk) for sk in seckeys] + pub_keys_flat = b''.join(pubkeys) + + cache = c_void_p() + wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, byref(cache)) + agg_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + wally_musig_pubkey_get(cache, agg_pk, EC_PUBLIC_KEY_LEN) + wally_musig_keyagg_cache_free(cache) + + xpub = POINTER(ext_key)() + wally_musig_pubkey_to_xpub(agg_pk, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub)) + + # Derive child 0 (unhardened) - should succeed + child0 = POINTER(ext_key)() + ret = bip32_key_from_parent_alloc(xpub, 0, BIP32_FLAG_KEY_PUBLIC, byref(child0)) + self.assertEqual(WALLY_OK, ret, 'Unhardened child 0 derivation should succeed') + self.assertIsNotNone(child0) + + # Derive child 1 (unhardened) - should succeed + child1 = POINTER(ext_key)() + ret = bip32_key_from_parent_alloc(xpub, 1, BIP32_FLAG_KEY_PUBLIC, byref(child1)) + self.assertEqual(WALLY_OK, ret, 'Unhardened child 1 derivation should succeed') + + # Children 0 and 1 produce different keys + ser0, _ = make_cbuffer('00' * BIP32_SERIALIZED_LEN) + ser1, _ = make_cbuffer('00' * BIP32_SERIALIZED_LEN) + bip32_key_serialize(child0, BIP32_FLAG_KEY_PUBLIC, ser0, BIP32_SERIALIZED_LEN) + bip32_key_serialize(child1, BIP32_FLAG_KEY_PUBLIC, ser1, BIP32_SERIALIZED_LEN) + self.assertNotEqual(bytes(ser0), bytes(ser1), + 'Different child indices must produce different keys') + + bip32_key_free(child0) + bip32_key_free(child1) + bip32_key_free(xpub) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_synthetic_xpub_hardened_derivation_rejected(self): + """BIP-328: hardened derivation from synthetic xpub must fail (no private key)""" + seckeys = [SECKEY1, SECKEY2] + pubkeys = [derive_pubkey(sk) for sk in seckeys] + pub_keys_flat = b''.join(pubkeys) + + cache = c_void_p() + wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, byref(cache)) + agg_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + wally_musig_pubkey_get(cache, agg_pk, EC_PUBLIC_KEY_LEN) + wally_musig_keyagg_cache_free(cache) + + xpub = POINTER(ext_key)() + wally_musig_pubkey_to_xpub(agg_pk, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub)) + + child_h = POINTER(ext_key)() + ret = bip32_key_from_parent_alloc(xpub, BIP32_INITIAL_HARDENED_CHILD, + BIP32_FLAG_KEY_PUBLIC, byref(child_h)) + self.assertNotEqual(WALLY_OK, ret, 'Hardened derivation must fail without private key') + + bip32_key_free(xpub) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_synthetic_xpub_invalid_args(self): + """wally_musig_pubkey_to_xpub validates its arguments""" + agg_pk_buf, _ = make_cbuffer('02' + '01' * EC_XONLY_PUBLIC_KEY_LEN) + xpub = POINTER(ext_key)() + + # NULL pubkey + self.assertEqual(WALLY_EINVAL, + wally_musig_pubkey_to_xpub(None, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub))) + # Wrong length (x-only keys are not accepted: the parity is required) + self.assertEqual(WALLY_EINVAL, + wally_musig_pubkey_to_xpub(agg_pk_buf, EC_XONLY_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub))) + # Not a compressed pubkey prefix + bad_prefix, _ = make_cbuffer('04' + '01' * EC_XONLY_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_EINVAL, + wally_musig_pubkey_to_xpub(bad_prefix, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub))) + # Invalid version (private key version) + self.assertEqual(WALLY_EINVAL, + wally_musig_pubkey_to_xpub(agg_pk_buf, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PRIVATE, byref(xpub))) + # NULL output + self.assertEqual(WALLY_EINVAL, + wally_musig_pubkey_to_xpub(agg_pk_buf, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, None)) + + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_derive_then_agg(self): + """BIP-390: derive child from each xpub then sort+aggregate""" + # Build two master xpubs from seeds + seed1 = bytes([0x01] * 32) + seed2 = bytes([0x02] * 32) + + xpub1 = POINTER(ext_key)() + xpub2 = POINTER(ext_key)() + ret = bip32_key_from_seed_alloc(seed1, len(seed1), BIP32_VER_MAIN_PRIVATE, 0, byref(xpub1)) + self.assertEqual(WALLY_OK, ret) + ret = bip32_key_from_seed_alloc(seed2, len(seed2), BIP32_VER_MAIN_PRIVATE, 0, byref(xpub2)) + self.assertEqual(WALLY_OK, ret) + + # Serialize both xpubs + xpub1_ser, _ = make_cbuffer('00' * BIP32_SERIALIZED_LEN) + xpub2_ser, _ = make_cbuffer('00' * BIP32_SERIALIZED_LEN) + self.assertEqual(WALLY_OK, bip32_key_serialize(xpub1, BIP32_FLAG_KEY_PUBLIC, xpub1_ser, BIP32_SERIALIZED_LEN)) + self.assertEqual(WALLY_OK, bip32_key_serialize(xpub2, BIP32_FLAG_KEY_PUBLIC, xpub2_ser, BIP32_SERIALIZED_LEN)) + + # Compute expected result manually: derive child 0, sort, aggregate + child1 = POINTER(ext_key)() + child2 = POINTER(ext_key)() + self.assertEqual(WALLY_OK, bip32_key_from_parent_alloc(xpub1, 0, BIP32_FLAG_KEY_PUBLIC, byref(child1))) + self.assertEqual(WALLY_OK, bip32_key_from_parent_alloc(xpub2, 0, BIP32_FLAG_KEY_PUBLIC, byref(child2))) + + pk1 = bytes(child1.contents.pub_key) + pk2 = bytes(child2.contents.pub_key) + sorted_pks = b''.join(sorted([pk1, pk2])) + + expected_agg, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(sorted_pks, len(sorted_pks), + expected_agg, EC_XONLY_PUBLIC_KEY_LEN, None)) + + # Call derive_then_agg with xpub1 first + xpubs_12 = bytes(xpub1_ser) + bytes(xpub2_ser) + agg_pk_12, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkeys_derive_then_agg( + xpubs_12, len(xpubs_12), 0, agg_pk_12, EC_XONLY_PUBLIC_KEY_LEN, None)) + self.assertEqual(bytes(expected_agg), bytes(agg_pk_12)) + + # Swapping xpub order must produce the same result (lexsort is canonical) + xpubs_21 = bytes(xpub2_ser) + bytes(xpub1_ser) + agg_pk_21, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkeys_derive_then_agg( + xpubs_21, len(xpubs_21), 0, agg_pk_21, EC_XONLY_PUBLIC_KEY_LEN, None)) + self.assertEqual(bytes(agg_pk_12), bytes(agg_pk_21)) + + # Verify child index 1 differs from index 0 + agg_pk_idx1, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkeys_derive_then_agg( + xpubs_12, len(xpubs_12), 1, agg_pk_idx1, EC_XONLY_PUBLIC_KEY_LEN, None)) + self.assertNotEqual(bytes(agg_pk_12), bytes(agg_pk_idx1)) + + # Invalid: hardened child + self.assertEqual(WALLY_EINVAL, wally_musig_pubkeys_derive_then_agg( + xpubs_12, len(xpubs_12), BIP32_INITIAL_HARDENED_CHILD, agg_pk_12, EC_XONLY_PUBLIC_KEY_LEN, None)) + + # Invalid: xpubs_len not multiple of 78 + self.assertEqual(WALLY_EINVAL, wally_musig_pubkeys_derive_then_agg( + xpubs_12, len(xpubs_12) - 1, 0, agg_pk_12, EC_XONLY_PUBLIC_KEY_LEN, None)) + + # Invalid: only 1 xpub + self.assertEqual(WALLY_EINVAL, wally_musig_pubkeys_derive_then_agg( + xpubs_12, BIP32_SERIALIZED_LEN, 0, agg_pk_12, EC_XONLY_PUBLIC_KEY_LEN, None)) + + bip32_key_free(child1) + bip32_key_free(child2) + bip32_key_free(xpub1) + bip32_key_free(xpub2) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_agg_then_derive(self): + """BIP-328: aggregate pubkeys, build synthetic xpub, then derive child""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + # Compute expected manually. wally_musig_pubkeys_agg_then_derive sorts + # the keys before aggregation, so sort here to mirror it. + sorted_keys_flat = b''.join(sorted([pk1, pk2])) + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(sorted_keys_flat, len(sorted_keys_flat), + None, 0, byref(cache))) + agg_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_get(cache, agg_pk, EC_PUBLIC_KEY_LEN)) + wally_musig_keyagg_cache_free(cache) + synthetic_xpub = POINTER(ext_key)() + self.assertEqual(WALLY_OK, wally_musig_pubkey_to_xpub(agg_pk, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(synthetic_xpub))) + expected_child = POINTER(ext_key)() + self.assertEqual(WALLY_OK, bip32_key_from_parent_alloc(synthetic_xpub, 0, + BIP32_FLAG_KEY_PUBLIC, byref(expected_child))) + expected_pk = bytes(expected_child.contents.pub_key) + + # Call agg_then_derive + result_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkeys_agg_then_derive( + pub_keys_flat, len(pub_keys_flat), BIP32_VER_MAIN_PUBLIC, 0, + result_pk, EC_PUBLIC_KEY_LEN, None)) + self.assertEqual(expected_pk, bytes(result_pk)) + + # Different child indices produce different pubkeys + result_pk1, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + result_pk2, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkeys_agg_then_derive( + pub_keys_flat, len(pub_keys_flat), BIP32_VER_MAIN_PUBLIC, 1, + result_pk1, EC_PUBLIC_KEY_LEN, None)) + self.assertEqual(WALLY_OK, wally_musig_pubkeys_agg_then_derive( + pub_keys_flat, len(pub_keys_flat), BIP32_VER_MAIN_PUBLIC, 2, + result_pk2, EC_PUBLIC_KEY_LEN, None)) + self.assertNotEqual(bytes(result_pk), bytes(result_pk1)) + self.assertNotEqual(bytes(result_pk1), bytes(result_pk2)) + + # child_out pointer variant + child_ptr = POINTER(ext_key)() + self.assertEqual(WALLY_OK, wally_musig_pubkeys_agg_then_derive( + pub_keys_flat, len(pub_keys_flat), BIP32_VER_MAIN_PUBLIC, 0, + None, 0, byref(child_ptr))) + self.assertIsNotNone(child_ptr) + self.assertEqual(expected_pk, bytes(child_ptr.contents.pub_key)) + + # Invalid: hardened child + self.assertEqual(WALLY_EINVAL, wally_musig_pubkeys_agg_then_derive( + pub_keys_flat, len(pub_keys_flat), BIP32_VER_MAIN_PUBLIC, + BIP32_INITIAL_HARDENED_CHILD, result_pk, EC_PUBLIC_KEY_LEN, None)) + + # Invalid: only 1 pubkey + self.assertEqual(WALLY_EINVAL, wally_musig_pubkeys_agg_then_derive( + pk1, EC_PUBLIC_KEY_LEN, BIP32_VER_MAIN_PUBLIC, 0, + result_pk, EC_PUBLIC_KEY_LEN, None)) + + bip32_key_free(expected_child) + bip32_key_free(synthetic_xpub) + bip32_key_free(child_ptr) + + def test_pubnonce_parse_invalid(self): + """wally_musig_pubnonce_parse rejects buffers of wrong length""" + invalid_lengths = [0, 1, 65, 67, 132] + for bad_len in invalid_lengths: + buf = bytes([0x00] * bad_len) + pn = c_void_p() + ret = wally_musig_pubnonce_parse(buf if bad_len > 0 else None, + bad_len, pn) + self.assertNotEqual(WALLY_OK, ret, + f'pubnonce_parse should fail for length {bad_len}') + + # All-zeros 66-byte buffer is an invalid (infinity) point and must fail + zero_buf = bytes([0x00] * MUSIG_PUBNONCE_LEN) + pn = c_void_p() + ret = wally_musig_pubnonce_parse(zero_buf, MUSIG_PUBNONCE_LEN, pn) + self.assertNotEqual(WALLY_OK, ret, + 'pubnonce_parse should reject all-zeros (infinity) input') + if pn.value: + wally_musig_pubnonce_free(pn.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_partial_sig_parse_invalid(self): + """wally_musig_partial_sig_parse rejects buffers of wrong length""" + invalid_lengths = [0, 31, 33] + for bad_len in invalid_lengths: + buf = bytes([0x01] * bad_len) + psig = c_void_p() + ret = wally_musig_partial_sig_parse(buf if bad_len > 0 else None, + bad_len, psig) + self.assertNotEqual(WALLY_OK, ret, + f'partial_sig_parse should fail for length {bad_len}') + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_aggnonce_mismatch_in_session(self): + """Corrupted aggnonce bytes produce a different session (or fail), preventing silent forgery""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + sn1 = c_void_p() + pn1 = c_void_p() + sn2 = c_void_p() + pn2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0xe1] * 32), 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0xe2] * 32), 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + + # Serialize aggnonce, corrupt one byte, parse back + an_bytes, _ = make_cbuffer('00' * MUSIG_AGGNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_aggnonce_serialize(aggnonce.value, an_bytes, MUSIG_AGGNONCE_LEN)) + + corrupted = bytearray(an_bytes) + corrupted[0] ^= 0xff + aggnonce_bad = c_void_p() + ret = wally_musig_aggnonce_parse(bytes(corrupted), MUSIG_AGGNONCE_LEN, aggnonce_bad) + + if ret == WALLY_OK and aggnonce_bad.value is not None: + # Corrupted aggnonce parsed: session will differ or partial sign will fail to verify + session_bad = c_void_p() + ret_proc = wally_musig_nonce_process(aggnonce_bad.value, TEST_MSG32, 32, + cache.value, None, 0, session_bad) + if ret_proc == WALLY_OK and session_bad.value is not None: + # Session formed with bad nonce: partial sig must fail verification + psig1_bad = c_void_p() + ret_sign = wally_musig_partial_sign(sn1.value, SECKEY1, 32, + cache.value, session_bad.value, psig1_bad) + if ret_sign == WALLY_OK and psig1_bad.value is not None: + ret_v = wally_musig_partial_sig_verify(psig1_bad.value, pn1.value, + pk1, EC_PUBLIC_KEY_LEN, + cache.value, session_bad.value) + # Verification should fail because the nonce was corrupted + self.assertNotEqual(WALLY_OK, ret_v, + 'partial sig must not verify against corrupted aggnonce') + wally_musig_partial_sig_free(psig1_bad.value) + wally_musig_session_free(session_bad.value) + wally_musig_aggnonce_free(aggnonce_bad.value) + else: + # Parse correctly rejected the corrupted aggnonce - that is also acceptable + pass + + # Cleanup (sn1 may have been consumed if partial_sign was called above) + try: + wally_musig_secnonce_free(sn1.value) + except Exception: + pass + wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_keyagg_cache_free(cache.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_keyagg_cache_roundtrip_3keys(self): + """Keyagg cache serialize/parse roundtrip is identical for 3 participants""" + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pk3 = derive_pubkey(SECKEY3) + pub_keys_flat = pk1 + pk2 + pk3 + + # Aggregate 3 keys + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + agg_pk, EC_XONLY_PUBLIC_KEY_LEN, cache)) + + # Serialize + cache_bytes, _ = make_cbuffer('00' * MUSIG_KEYAGG_CACHE_LEN) + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_serialize(cache.value, cache_bytes, + MUSIG_KEYAGG_CACHE_LEN)) + + # Parse back + cache2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_parse(cache_bytes, MUSIG_KEYAGG_CACHE_LEN, cache2)) + + # Re-serialize and compare bytes + cache2_bytes, _ = make_cbuffer('00' * MUSIG_KEYAGG_CACHE_LEN) + self.assertEqual(WALLY_OK, wally_musig_keyagg_cache_serialize(cache2.value, cache2_bytes, + MUSIG_KEYAGG_CACHE_LEN)) + self.assertEqual(bytes(cache_bytes), bytes(cache2_bytes)) + + # Verify the aggregate pubkey is consistent from both caches + agg_from_cache2, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_get(cache2.value, agg_from_cache2, EC_PUBLIC_KEY_LEN)) + self.assertIn(bytes(agg_from_cache2)[0:1], [b'\x02', b'\x03']) + self.assertEqual(bytes(agg_from_cache2)[1:], bytes(agg_pk)) + + wally_musig_keyagg_cache_free(cache.value) + wally_musig_keyagg_cache_free(cache2.value) + + def test_partial_sign_nonce_reuse(self): + """SECURITY: secp256k1 zeroes the secnonce after partial_sign to prevent nonce reuse. + + A second call with the same (now-zeroed) secnonce must fail. + """ + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 + + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, cache)) + + sn1 = c_void_p() + pn1 = c_void_p() + sn2 = c_void_p() + pn2 = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0xf1] * 32), 32, SECKEY1, 32, + pk1, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0xf2] * 32), 32, SECKEY2, 32, + pk2, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn2, pn2)) + + pn1_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn1.value, pn1_bytes, MUSIG_PUBNONCE_LEN)) + self.assertEqual(WALLY_OK, wally_musig_pubnonce_serialize(pn2.value, pn2_bytes, MUSIG_PUBNONCE_LEN)) + + pubnonces_flat = bytes(pn1_bytes) + bytes(pn2_bytes) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), 2, aggnonce)) + + session = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_process(aggnonce.value, TEST_MSG32, 32, + cache.value, None, 0, session)) + + # First call: MUST succeed - secnonce is valid and unused. + psig1 = c_void_p() + ret = wally_musig_partial_sign(sn1.value, SECKEY1, 32, cache.value, session.value, psig1) + self.assertEqual(WALLY_OK, ret, 'first partial_sign must succeed') + self.assertIsNotNone(psig1.value, 'partial sig must be non-NULL on success') + + # secp256k1 has now zeroed the secnonce memory inside sn1: + # a second call must fail rather than reuse the nonce + psig2 = c_void_p() + ret = wally_musig_partial_sign(sn1.value, SECKEY1, 32, cache.value, session.value, psig2) + self.assertEqual(WALLY_EINVAL, ret, 'secnonce reuse must be rejected') + self.assertIsNone(psig2.value) + + # Cleanup + wally_musig_secnonce_free(sn1.value) + wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + wally_musig_partial_sig_free(psig1.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + +if __name__ == '__main__': + unittest.main() diff --git a/src/test/test_musig_vectors.py b/src/test/test_musig_vectors.py new file mode 100644 index 000000000..24ea98544 --- /dev/null +++ b/src/test/test_musig_vectors.py @@ -0,0 +1,799 @@ +""" +BIP-327/328/390 test vector validation for the wally MuSig2 Python API. + +Loads the upstream BIP-327 JSON test vectors shipped under +src/data/bip327/ and drives them through the wally Python ctypes +binding layer end-to-end. +""" + +import json +import os +import unittest +from ctypes import * +from util import * + +_DATA_DIR = os.path.join(os.path.dirname(__file__), '..', 'data', 'bip327') + + +def _load_vectors(name): + with open(os.path.join(_DATA_DIR, name + '.json'), 'r') as f: + return json.load(f) + + +def _h(s): + """Hex -> bytes helper that tolerates None and empty strings.""" + if s is None: + return None + return bytes.fromhex(s) + + +# Map upstream BIP-327 error.type discriminators to wally error codes. +# Upstream uses "invalid_contribution" (a participant contributed bad data) +# and "value" (a scalar/field element is out of range). Both surface as +# WALLY_EINVAL through the wally API. +# Upstream 'value' errors map to different wally error codes depending on +# where validation rejects the input (EINVAL at the FFI boundary vs ERROR +# for scalar/field-element range checks inside secp256k1). Keep only the +# reliably one-to-one mapping; other types fall back to "any non-OK". +_ERROR_TYPE_MAP = { + 'invalid_contribution': WALLY_EINVAL, +} +_unknown_error_types = set() + + +def _assert_error(testcase, ret, err): + """Assert ret matches the upstream error descriptor's type (if known).""" + testcase.assertNotEqual(WALLY_OK, ret, 'expected error but got WALLY_OK') + etype = (err or {}).get('type') + if etype in _ERROR_TYPE_MAP: + testcase.assertEqual(_ERROR_TYPE_MAP[etype], ret, + f'error type {etype!r} expected {_ERROR_TYPE_MAP[etype]}, got {ret}') + elif etype is not None: + _unknown_error_types.add(etype) + +EC_PUBLIC_KEY_LEN = 33 +EC_XONLY_PUBLIC_KEY_LEN = 32 +EC_SIGNATURE_LEN = 64 +EC_FLAG_SCHNORR = 0x2 + +BIP32_VER_MAIN_PUBLIC = 0x0488B21E +BIP32_VER_MAIN_PRIVATE = 0x0488ADE4 +BIP32_INITIAL_HARDENED_CHILD = 0x80000000 +BIP32_FLAG_KEY_PUBLIC = 0x1 +BIP32_SERIALIZED_LEN = 78 + +MUSIG_PUBNONCE_LEN = 66 +MUSIG_AGGNONCE_LEN = 66 +MUSIG_PARTIAL_SIG_LEN = 32 +MUSIG_KEYAGG_CACHE_LEN = 197 +MUSIG_SESSION_LEN = 133 + +NETWORK_NONE = 0x00 +NETWORK_BTC_MAIN = 0x01 + +def derive_pubkey(seckey): + pub, pub_len = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + ret = wally_ec_public_key_from_private_key(seckey, len(seckey), pub, pub_len) + assert ret == WALLY_OK, 'derive_pubkey failed' + return pub + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class KeyAggVectorTests(unittest.TestCase): + """BIP-327 key aggregation test vectors (upstream key_agg_vectors.json).""" + + V = _load_vectors('key_agg_vectors') + PUBKEYS = [_h(p) for p in V['pubkeys']] + TWEAKS = [_h(t) for t in V['tweaks']] + + def _agg(self, key_indices): + pks = b''.join(self.PUBKEYS[i] for i in key_indices) + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + ret = wally_musig_pubkey_agg(pks, len(pks), agg_pk, + EC_XONLY_PUBLIC_KEY_LEN, cache) + return ret, bytes(agg_pk), cache + + def test_valid_cases(self): + """Each valid_test_case matches BIP-327 expected x-only output.""" + self.assertGreater(len(self.V['valid_test_cases']), 0, "valid_test_cases empty") + for i, tc in enumerate(self.V['valid_test_cases']): + with self.subTest(case=i): + ret, agg_pk, cache = self._agg(tc['key_indices']) + self.assertEqual(WALLY_OK, ret, f'case {i}: pubkey_agg failed') + self.assertEqual(_h(tc['expected']), agg_pk, + f'case {i}: x-only output mismatch') + if cache.value: + wally_musig_keyagg_cache_free(cache.value) + + def test_error_cases(self): + """Each error_test_case returns non-WALLY_OK with the expected type.""" + self.assertGreater(len(self.V['error_test_cases']), 0, "error_test_cases empty") + for i, tc in enumerate(self.V['error_test_cases']): + with self.subTest(case=i, comment=tc.get('comment', '')): + pks = b''.join(self.PUBKEYS[j] for j in tc['key_indices']) + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + ret = wally_musig_pubkey_agg(pks, len(pks), agg_pk, + EC_XONLY_PUBLIC_KEY_LEN, cache) + if ret == WALLY_OK and tc.get('tweak_indices') and cache.value: + for ti, xonly in zip(tc['tweak_indices'], tc['is_xonly']): + tweak = self.TWEAKS[ti] + out, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + fn = (wally_musig_pubkey_xonly_tweak_add if xonly + else wally_musig_pubkey_ec_tweak_add) + ret = fn(cache.value, tweak, len(tweak), + out, EC_PUBLIC_KEY_LEN) + if ret != WALLY_OK: + break + _assert_error(self, ret, tc.get('error')) + if cache.value: + wally_musig_keyagg_cache_free(cache.value) + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class NonceAggVectorTests(unittest.TestCase): + """BIP-327 nonce aggregation test vectors (upstream nonce_agg_vectors.json).""" + + V = _load_vectors('nonce_agg_vectors') + PNONCES = [_h(p) for p in V['pnonces']] + + def test_valid_cases(self): + self.assertGreater(len(self.V['valid_test_cases']), 0, "valid_test_cases empty") + for i, tc in enumerate(self.V['valid_test_cases']): + with self.subTest(case=i): + flat = b''.join(self.PNONCES[j] for j in tc['pnonce_indices']) + n = len(tc['pnonce_indices']) + aggnonce = c_void_p() + ret = wally_musig_nonce_agg(flat, len(flat), n, aggnonce) + self.assertEqual(WALLY_OK, ret, f'case {i}: nonce_agg failed') + an_bytes, _ = make_cbuffer('00' * MUSIG_AGGNONCE_LEN) + self.assertEqual(WALLY_OK, + wally_musig_aggnonce_serialize(aggnonce.value, an_bytes, + MUSIG_AGGNONCE_LEN)) + self.assertEqual(_h(tc['expected']), bytes(an_bytes), + f'case {i}: aggnonce output mismatch') + wally_musig_aggnonce_free(aggnonce.value) + + def test_error_cases(self): + self.assertGreater(len(self.V['error_test_cases']), 0, "error_test_cases empty") + for i, tc in enumerate(self.V['error_test_cases']): + with self.subTest(case=i, comment=tc.get('comment', '')): + flat = b''.join(self.PNONCES[j] for j in tc['pnonce_indices']) + n = len(tc['pnonce_indices']) + aggnonce = c_void_p() + ret = wally_musig_nonce_agg(flat, len(flat), n, aggnonce) + _assert_error(self, ret, tc.get('error')) + if aggnonce.value: + wally_musig_aggnonce_free(aggnonce.value) + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class NonceGenVectorTests(unittest.TestCase): + """BIP-327 nonce generation vectors (upstream nonce_gen_vectors.json). + + Cases 0..2 bind the nonce to an aggregate public key provided as raw + 32 bytes. wally's public API only accepts a keyagg_cache built from + the constituent individual pubkeys; there is no way to construct a + cache from a raw aggpk. Those cases are skipped. + Case 2 additionally uses a 38-byte msg which the wally API rejects + (msg must be 32 bytes). Case 3 has no aggpk/msg/extra_in and is + driven end-to-end against the expected pubnonce. + """ + + V = _load_vectors('nonce_gen_vectors') + + def test_cases(self): + checked = 0 + self.assertGreater(len(self.V['test_cases']), 0, "test_cases empty") + for i, tc in enumerate(self.V['test_cases']): + with self.subTest(case=i): + if tc.get('aggpk') is not None: + self.skipTest('aggpk injection unsupported by wally public API') + continue + msg = _h(tc.get('msg')) if tc.get('msg') is not None else None + if msg is not None and len(msg) != 32: + self.skipTest('non-32-byte msg unsupported by wally API') + continue + sk = _h(tc.get('sk')) if tc.get('sk') else None + pk = _h(tc['pk']) + extra = _h(tc.get('extra_in')) if tc.get('extra_in') else None + rand_ = _h(tc['rand_']) + sn, pn = c_void_p(), c_void_p() + ret = wally_musig_nonce_gen( + rand_, len(rand_), + sk, (32 if sk else 0), + pk, len(pk), + None, + msg, (32 if msg else 0), + extra, (32 if extra else 0), + sn, pn) + self.assertEqual(WALLY_OK, ret, f'case {i}: nonce_gen failed') + pn_bytes, _bl = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubnonce_serialize(pn.value, pn_bytes, + MUSIG_PUBNONCE_LEN)) + self.assertEqual(_h(tc['expected_pubnonce']), bytes(pn_bytes), + f'case {i}: pubnonce mismatch') + if sn.value: wally_musig_secnonce_free(sn.value) + wally_musig_pubnonce_free(pn.value) + checked += 1 + self.assertGreater(checked, 0, 'No nonce_gen cases exercised') + + def test_same_rand_same_result(self): + """Nonce gen is deterministic: same inputs produce identical pubnonces.""" + rand_ = bytes([0xAB] * 32) + pk = bytes.fromhex('02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9') + + sn1, pn1 = c_void_p(), c_void_p() + sn2, pn2 = c_void_p(), c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(rand_, 32, None, 0, pk, 33, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(rand_, 32, None, 0, pk, 33, + None, None, 0, None, 0, sn2, pn2)) + + pn1b, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2b, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + wally_musig_pubnonce_serialize(pn1.value, pn1b, MUSIG_PUBNONCE_LEN) + wally_musig_pubnonce_serialize(pn2.value, pn2b, MUSIG_PUBNONCE_LEN) + self.assertEqual(bytes(pn1b), bytes(pn2b), 'Same inputs must produce same pubnonce') + + if sn1.value: wally_musig_secnonce_free(sn1.value) + if sn2.value: wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + + def test_different_rand_different_result(self): + """Different rand values produce different pubnonces.""" + pk = bytes.fromhex('02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9') + + sn1, pn1 = c_void_p(), c_void_p() + sn2, pn2 = c_void_p(), c_void_p() + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0x01] * 32), 32, None, 0, pk, 33, + None, None, 0, None, 0, sn1, pn1)) + self.assertEqual(WALLY_OK, wally_musig_nonce_gen(bytes([0x02] * 32), 32, None, 0, pk, 33, + None, None, 0, None, 0, sn2, pn2)) + + pn1b, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + pn2b, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + wally_musig_pubnonce_serialize(pn1.value, pn1b, MUSIG_PUBNONCE_LEN) + wally_musig_pubnonce_serialize(pn2.value, pn2b, MUSIG_PUBNONCE_LEN) + self.assertNotEqual(bytes(pn1b), bytes(pn2b), + 'Different rand values must produce different pubnonces') + + if sn1.value: wally_musig_secnonce_free(sn1.value) + if sn2.value: wally_musig_secnonce_free(sn2.value) + wally_musig_pubnonce_free(pn1.value) + wally_musig_pubnonce_free(pn2.value) + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class SignVerifyVectorTests(unittest.TestCase): + """BIP-327 sign/verify: complete flow with verification. + + BIP-327 sign_verify vectors use secp256k1-internal secnonce format (194 bytes) + not accessible through the wally public API. We instead run complete + deterministic signing flows and verify final Schnorr signatures. + """ + + def _run_sign_flow(self, seckeys, msg32): + """Run full MuSig2 signing flow. Returns (final_sig, agg_pk_xonly).""" + n = len(seckeys) + pubkeys = [derive_pubkey(sk) for sk in seckeys] + + pub_keys_flat = b''.join(pubkeys) + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + self.assertEqual(WALLY_OK, + wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + agg_pk, EC_XONLY_PUBLIC_KEY_LEN, cache)) + + secnonces, pubnonces, pn_bytes_list = [], [], [] + for i, (sk, pk) in enumerate(zip(seckeys, pubkeys)): + sn, pn = c_void_p(), c_void_p() + session_id = bytes([0x10 + i]) * 32 + self.assertEqual(WALLY_OK, + wally_musig_nonce_gen(session_id, 32, sk, 32, pk, EC_PUBLIC_KEY_LEN, + None, None, 0, None, 0, sn, pn)) + secnonces.append(sn) + pubnonces.append(pn) + + pn_bytes, _ = make_cbuffer('00' * MUSIG_PUBNONCE_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubnonce_serialize(pn.value, pn_bytes, MUSIG_PUBNONCE_LEN)) + pn_bytes_list.append(bytes(pn_bytes)) + + pubnonces_flat = b''.join(pn_bytes_list) + aggnonce = c_void_p() + self.assertEqual(WALLY_OK, + wally_musig_nonce_agg(pubnonces_flat, len(pubnonces_flat), n, aggnonce)) + + session = c_void_p() + self.assertEqual(WALLY_OK, + wally_musig_nonce_process(aggnonce.value, msg32, 32, + cache.value, None, 0, session)) + + partial_sigs, ps_bytes_list = [], [] + for i, (sn, sk, pn, pk) in enumerate(zip(secnonces, seckeys, pubnonces, pubkeys)): + psig = c_void_p() + self.assertEqual(WALLY_OK, + wally_musig_partial_sign(sn.value, sk, 32, + cache.value, session.value, psig), + f'partial_sign failed for signer {i}') + partial_sigs.append(psig) + + ps_bytes, _ = make_cbuffer('00' * MUSIG_PARTIAL_SIG_LEN) + self.assertEqual(WALLY_OK, + wally_musig_partial_sig_serialize(psig.value, ps_bytes, + MUSIG_PARTIAL_SIG_LEN)) + ps_bytes_list.append(bytes(ps_bytes)) + + self.assertEqual(WALLY_OK, + wally_musig_partial_sig_verify(psig.value, pn.value, + pk, EC_PUBLIC_KEY_LEN, + cache.value, session.value), + f'partial_sig_verify failed for signer {i}') + + partial_sigs_flat = b''.join(ps_bytes_list) + final_sig, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, + wally_musig_partial_sig_agg(partial_sigs_flat, len(partial_sigs_flat), + n, session.value, final_sig, EC_SIGNATURE_LEN)) + + for sn in secnonces: + if sn.value: wally_musig_secnonce_free(sn.value) + for pn in pubnonces: + if pn.value: wally_musig_pubnonce_free(pn.value) + for psig in partial_sigs: + if psig.value: wally_musig_partial_sig_free(psig.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + return bytes(final_sig), bytes(agg_pk) + + def test_2of2_sign_verify(self): + """2-of-2: final Schnorr sig verifies against aggregate pubkey.""" + msg32 = bytes([0xDE, 0xAD, 0xBE, 0xEF] * 8) + final_sig, agg_pk = self._run_sign_flow([bytes([0x01]*32), bytes([0x02]*32)], msg32) + self.assertNotEqual(final_sig, b'\x00' * EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, + wally_ec_sig_verify(agg_pk, EC_XONLY_PUBLIC_KEY_LEN, + msg32, 32, EC_FLAG_SCHNORR, + final_sig, EC_SIGNATURE_LEN)) + + def test_3of3_sign_verify(self): + """3-of-3: final Schnorr sig verifies against aggregate pubkey.""" + msg32 = bytes([0xCA, 0xFE, 0xBA, 0xBE] * 8) + final_sig, agg_pk = self._run_sign_flow( + [bytes([0x01]*32), bytes([0x02]*32), bytes([0x03]*32)], msg32) + self.assertNotEqual(final_sig, b'\x00' * EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, + wally_ec_sig_verify(agg_pk, EC_XONLY_PUBLIC_KEY_LEN, + msg32, 32, EC_FLAG_SCHNORR, + final_sig, EC_SIGNATURE_LEN)) + + def test_deterministic_output(self): + """Deterministic inputs produce identical final signatures across two runs.""" + msg32 = bytes([0xAA] * 32) + sig1, _ = self._run_sign_flow([bytes([0x01]*32), bytes([0x02]*32)], msg32) + sig2, _ = self._run_sign_flow([bytes([0x01]*32), bytes([0x02]*32)], msg32) + self.assertEqual(sig1, sig2, 'Deterministic flow must produce same final sig') + + def test_wrong_message_fails_verify(self): + """Schnorr sig verifies only for the correct message, not a different one.""" + msg32_signed = bytes([0x01] * 32) + msg32_wrong = bytes([0x02] * 32) + final_sig, agg_pk = self._run_sign_flow([bytes([0x01]*32), bytes([0x02]*32)], msg32_signed) + self.assertNotEqual(WALLY_OK, + wally_ec_sig_verify(agg_pk, EC_XONLY_PUBLIC_KEY_LEN, + msg32_wrong, 32, EC_FLAG_SCHNORR, + final_sig, EC_SIGNATURE_LEN), + 'Verification against wrong message should fail') + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class Bip328VectorTests(unittest.TestCase): + """BIP-328 synthetic xpub construction and derivation test vectors.""" + + # BIP-328 chaincode = SHA256('MuSig2MuSig2MuSig2') + # Computed: hashlib.sha256(b'MuSig2MuSig2MuSig2').hexdigest() + EXPECTED_CHAINCODE = bytes.fromhex('868087ca02a6f974c4598924c36b57762d32cb45717167e300622c7167e38965') + + def _make_agg_pk(self, seckeys): + # Returns the full compressed aggregate key (BIP-328 needs its parity) + pubkeys = [derive_pubkey(sk) for sk in seckeys] + pub_keys_flat = b''.join(pubkeys) + cache = c_void_p() + self.assertEqual(WALLY_OK, + wally_musig_pubkey_agg(pub_keys_flat, len(pub_keys_flat), + None, 0, byref(cache))) + agg_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubkey_get(cache, agg_pk, EC_PUBLIC_KEY_LEN)) + wally_musig_keyagg_cache_free(cache) + return bytes(agg_pk) + + def _make_synthetic_xpub(self, seckeys): + agg_pk = self._make_agg_pk(seckeys) + agg_pk_buf, _ = make_cbuffer(agg_pk.hex()) + xpub = POINTER(ext_key)() + self.assertEqual(WALLY_OK, + wally_musig_pubkey_to_xpub(agg_pk_buf, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(xpub))) + return xpub + + def test_chaincode_is_bip328_constant(self): + """Synthetic xpub chain code must equal SHA256('MuSig2MuSig2MuSig2').""" + xpub = self._make_synthetic_xpub([bytes([0x01]*32), bytes([0x02]*32)]) + actual_cc = bytes(xpub.contents.chain_code) + self.assertEqual(self.EXPECTED_CHAINCODE, actual_cc, + f'Chain code mismatch:\n' + f' got: {actual_cc.hex()}\n' + f' expected: {self.EXPECTED_CHAINCODE.hex()}') + bip32_key_free(xpub) + + def test_xpub_root_metadata(self): + """Synthetic xpub has depth=0, child_num=0, all-zero parent fingerprint.""" + xpub = self._make_synthetic_xpub([bytes([0x01]*32), bytes([0x02]*32)]) + self.assertEqual(0, xpub.contents.depth, 'depth must be 0') + self.assertEqual(0, xpub.contents.child_num, 'child_num must be 0') + self.assertEqual(b'\x00' * 20, bytes(xpub.contents.parent160), + 'parent fingerprint must be all zeros') + bip32_key_free(xpub) + + def test_xpub_starts_with_xpub(self): + """Synthetic xpub serializes to a base58 string starting with 'xpub'.""" + xpub = self._make_synthetic_xpub([bytes([0x01]*32), bytes([0x02]*32)]) + ret, b58_str = bip32_key_to_base58(xpub, BIP32_FLAG_KEY_PUBLIC) + self.assertEqual(WALLY_OK, ret) + b58 = b58_str.decode('ascii') if isinstance(b58_str, bytes) else b58_str + self.assertTrue(b58.startswith('xpub'), f'Expected xpub prefix, got: {b58[:8]}') + bip32_key_free(xpub) + + def test_unhardened_child_derivation(self): + """Unhardened derivation from synthetic xpub succeeds; children differ.""" + xpub = self._make_synthetic_xpub([bytes([0x03]*32), bytes([0x04]*32)]) + c0, c1 = POINTER(ext_key)(), POINTER(ext_key)() + self.assertEqual(WALLY_OK, + bip32_key_from_parent_alloc(xpub, 0, BIP32_FLAG_KEY_PUBLIC, byref(c0))) + self.assertEqual(WALLY_OK, + bip32_key_from_parent_alloc(xpub, 1, BIP32_FLAG_KEY_PUBLIC, byref(c1))) + self.assertNotEqual(bytes(c0.contents.pub_key), bytes(c1.contents.pub_key), + 'Different indices must produce different pubkeys') + bip32_key_free(c0) + bip32_key_free(c1) + bip32_key_free(xpub) + + def test_hardened_derivation_rejected(self): + """Hardened derivation from synthetic xpub must fail (no private key).""" + xpub = self._make_synthetic_xpub([bytes([0x01]*32), bytes([0x02]*32)]) + child = POINTER(ext_key)() + ret = bip32_key_from_parent_alloc(xpub, BIP32_INITIAL_HARDENED_CHILD, + BIP32_FLAG_KEY_PUBLIC, byref(child)) + self.assertNotEqual(WALLY_OK, ret, 'Hardened derivation must fail') + bip32_key_free(xpub) + + def test_derive_then_agg_order_independent(self): + """BIP-390 derive_then_agg: swapping xpub order does not change output.""" + seed1, seed2 = bytes([0x01]*32), bytes([0x02]*32) + xpub1, xpub2 = POINTER(ext_key)(), POINTER(ext_key)() + self.assertEqual(WALLY_OK, + bip32_key_from_seed_alloc(seed1, len(seed1), + BIP32_VER_MAIN_PRIVATE, 0, byref(xpub1))) + self.assertEqual(WALLY_OK, + bip32_key_from_seed_alloc(seed2, len(seed2), + BIP32_VER_MAIN_PRIVATE, 0, byref(xpub2))) + + ser1, _ = make_cbuffer('00' * BIP32_SERIALIZED_LEN) + ser2, _ = make_cbuffer('00' * BIP32_SERIALIZED_LEN) + self.assertEqual(WALLY_OK, + bip32_key_serialize(xpub1, BIP32_FLAG_KEY_PUBLIC, ser1, BIP32_SERIALIZED_LEN)) + self.assertEqual(WALLY_OK, + bip32_key_serialize(xpub2, BIP32_FLAG_KEY_PUBLIC, ser2, BIP32_SERIALIZED_LEN)) + + agg_12, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + agg_21, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubkeys_derive_then_agg( + bytes(ser1) + bytes(ser2), 2 * BIP32_SERIALIZED_LEN, + 0, agg_12, EC_XONLY_PUBLIC_KEY_LEN, None)) + self.assertEqual(WALLY_OK, + wally_musig_pubkeys_derive_then_agg( + bytes(ser2) + bytes(ser1), 2 * BIP32_SERIALIZED_LEN, + 0, agg_21, EC_XONLY_PUBLIC_KEY_LEN, None)) + self.assertEqual(bytes(agg_12), bytes(agg_21), + 'derive_then_agg must be order-independent (BIP-390 lexsort)') + + bip32_key_free(xpub1) + bip32_key_free(xpub2) + + def test_agg_then_derive_consistent(self): + """BIP-328 agg_then_derive: matches manual aggregate+xpub+derive sequence.""" + sk1, sk2 = bytes([0x01]*32), bytes([0x02]*32) + pk1 = derive_pubkey(sk1) + pk2 = derive_pubkey(sk2) + pub_keys_flat = pk1 + pk2 + + # Manual computation. wally_musig_pubkeys_agg_then_derive sorts the keys + # before aggregation, so sort here to mirror it. + sorted_keys_flat = b''.join(sorted([pk1, pk2])) + cache = c_void_p() + self.assertEqual(WALLY_OK, + wally_musig_pubkey_agg(sorted_keys_flat, len(sorted_keys_flat), + None, 0, byref(cache))) + agg_pk_buf, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubkey_get(cache, agg_pk_buf, EC_PUBLIC_KEY_LEN)) + wally_musig_keyagg_cache_free(cache) + synthetic_xpub = POINTER(ext_key)() + self.assertEqual(WALLY_OK, + wally_musig_pubkey_to_xpub(agg_pk_buf, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, byref(synthetic_xpub))) + expected_child = POINTER(ext_key)() + self.assertEqual(WALLY_OK, + bip32_key_from_parent_alloc(synthetic_xpub, 0, + BIP32_FLAG_KEY_PUBLIC, byref(expected_child))) + expected_pk = bytes(expected_child.contents.pub_key) + + # agg_then_derive API + result_pk, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, + wally_musig_pubkeys_agg_then_derive( + pub_keys_flat, len(pub_keys_flat), + BIP32_VER_MAIN_PUBLIC, 0, + result_pk, EC_PUBLIC_KEY_LEN, None)) + self.assertEqual(expected_pk, bytes(result_pk), + 'agg_then_derive must match manual computation') + + bip32_key_free(expected_child) + bip32_key_free(synthetic_xpub) + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +def _build_cache(pubkeys_flat): + agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + ret = wally_musig_pubkey_agg(pubkeys_flat, len(pubkeys_flat), + agg_pk, EC_XONLY_PUBLIC_KEY_LEN, cache) + return ret, bytes(agg_pk), cache + + +def _apply_tweaks(cache, tweak_list, is_xonly): + for tweak, xonly in zip(tweak_list, is_xonly): + out, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + fn = (wally_musig_pubkey_xonly_tweak_add if xonly + else wally_musig_pubkey_ec_tweak_add) + ret = fn(cache, tweak, len(tweak), out, EC_PUBLIC_KEY_LEN) + if ret != WALLY_OK: + return ret + return WALLY_OK + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class SignVerifyVectorFileTests(unittest.TestCase): + """BIP-327 sign_verify_vectors.json partial signature verify cases. + + The valid_test_cases and sign_error_test_cases expect signing with a + preconstructed 194-byte secnonce; wally's public API has no way to + inject a raw secnonce, so those categories are not exercised here + (they are covered end-to-end by the flow tests in SignVerifyVectorTests + further down). verify_fail_test_cases and verify_error_test_cases + provide a complete partial signature and only need verification, which + is reachable through wally_musig_partial_sig_verify. + """ + + V = _load_vectors('sign_verify_vectors') + PUBKEYS = [_h(p) for p in V['pubkeys']] + PNONCES = [_h(p) for p in V['pnonces']] + MSGS = [_h(m) for m in V['msgs']] + + def _setup(self, tc): + pks = b''.join(self.PUBKEYS[j] for j in tc['key_indices']) + ret, _, cache = _build_cache(pks) + if ret != WALLY_OK: + return cache, c_void_p(), ret + pn_flat = b''.join(self.PNONCES[j] for j in tc['nonce_indices']) + n = len(tc['nonce_indices']) + aggnonce = c_void_p() + ret = wally_musig_nonce_agg(pn_flat, len(pn_flat), n, aggnonce) + return cache, aggnonce, ret + + def test_verify_fail_cases(self): + msg = self.MSGS[0] + self.assertEqual(32, len(msg)) + self.assertGreater(len(self.V['verify_fail_test_cases']), 0, "verify_fail_test_cases empty") + for i, tc in enumerate(self.V['verify_fail_test_cases']): + with self.subTest(case=i, comment=tc.get('comment', '')): + cache, aggnonce, ret = self._setup(tc) + if ret != WALLY_OK: + # Nonce aggregation failed; the expected verification + # failure has already occurred upstream. + if cache is not None and cache.value: + wally_musig_keyagg_cache_free(cache.value) + continue + session = c_void_p() + ret = wally_musig_nonce_process(aggnonce.value, msg, 32, + cache.value, None, 0, session) + self.assertEqual(WALLY_OK, ret, 'nonce_process setup failed') + psig = c_void_p() + r2 = wally_musig_partial_sig_parse(_h(tc['sig']), + MUSIG_PARTIAL_SIG_LEN, psig) + verify_ret = WALLY_ERROR + if r2 == WALLY_OK: + signer_pn = c_void_p() + r3 = wally_musig_pubnonce_parse( + self.PNONCES[tc['nonce_indices'][tc['signer_index']]], + MUSIG_PUBNONCE_LEN, signer_pn) + if r3 == WALLY_OK: + signer_pk = self.PUBKEYS[tc['key_indices'][tc['signer_index']]] + verify_ret = wally_musig_partial_sig_verify( + psig.value, signer_pn.value, + signer_pk, EC_PUBLIC_KEY_LEN, + cache.value, session.value) + wally_musig_pubnonce_free(signer_pn.value) + else: + verify_ret = r3 + wally_musig_partial_sig_free(psig.value) + else: + verify_ret = r2 + self.assertNotEqual(WALLY_OK, verify_ret, + f'case {i}: verify unexpectedly succeeded') + wally_musig_session_free(session.value) + wally_musig_aggnonce_free(aggnonce.value) + wally_musig_keyagg_cache_free(cache.value) + + def test_verify_error_cases(self): + msg = self.MSGS[0] + self.assertGreater(len(self.V['verify_error_test_cases']), 0, "verify_error_test_cases empty") + for i, tc in enumerate(self.V['verify_error_test_cases']): + with self.subTest(case=i, comment=tc.get('comment', '')): + cache, aggnonce, setup_ret = self._setup(tc) + final_ret = setup_ret + session = c_void_p() + if setup_ret == WALLY_OK: + final_ret = wally_musig_nonce_process( + aggnonce.value, msg, 32, cache.value, + None, 0, session) + if final_ret == WALLY_OK: + psig = c_void_p() + r2 = wally_musig_partial_sig_parse( + _h(tc['sig']), MUSIG_PARTIAL_SIG_LEN, psig) + if r2 != WALLY_OK: + final_ret = r2 + else: + signer_pn = c_void_p() + r3 = wally_musig_pubnonce_parse( + self.PNONCES[tc['nonce_indices'][tc['signer_index']]], + MUSIG_PUBNONCE_LEN, signer_pn) + if r3 != WALLY_OK: + final_ret = r3 + else: + signer_pk = self.PUBKEYS[tc['key_indices'][tc['signer_index']]] + final_ret = wally_musig_partial_sig_verify( + psig.value, signer_pn.value, + signer_pk, EC_PUBLIC_KEY_LEN, + cache.value, session.value) + wally_musig_pubnonce_free(signer_pn.value) + wally_musig_partial_sig_free(psig.value) + _assert_error(self, final_ret, tc.get('error')) + if session.value: + wally_musig_session_free(session.value) + if aggnonce.value: + wally_musig_aggnonce_free(aggnonce.value) + if cache.value: + wally_musig_keyagg_cache_free(cache.value) + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class TweakVectorTests(unittest.TestCase): + """BIP-327 tweak_vectors.json. + + valid_test_cases bind to a preconstructed 194-byte secnonce, which + wally's public API cannot accept. Only error_test_cases (which fail + before reaching signing) are exercised here. + """ + + V = _load_vectors('tweak_vectors') + PUBKEYS = [_h(p) for p in V['pubkeys']] + TWEAKS = [_h(t) for t in V['tweaks']] + + def test_error_cases(self): + self.assertGreater(len(self.V['error_test_cases']), 0, "error_test_cases empty") + for i, tc in enumerate(self.V['error_test_cases']): + with self.subTest(case=i, comment=tc.get('comment', '')): + pks = b''.join(self.PUBKEYS[j] for j in tc['key_indices']) + ret, _, cache = _build_cache(pks) + if ret == WALLY_OK: + tweaks = [self.TWEAKS[j] for j in tc['tweak_indices']] + ret = _apply_tweaks(cache.value, tweaks, tc['is_xonly']) + _assert_error(self, ret, tc.get('error')) + if cache.value: + wally_musig_keyagg_cache_free(cache.value) + + +@unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class SigAggVectorTests(unittest.TestCase): + """BIP-327 sig_agg_vectors.json.""" + + V = _load_vectors('sig_agg_vectors') + PUBKEYS = [_h(p) for p in V['pubkeys']] + PNONCES = [_h(p) for p in V['pnonces']] + TWEAKS = [_h(t) for t in V['tweaks']] + PSIGS = [_h(p) for p in V['psigs']] + MSG = _h(V['msg']) + + def _prepare(self, tc): + pks = b''.join(self.PUBKEYS[j] for j in tc['key_indices']) + ret, _, cache = _build_cache(pks) + if ret != WALLY_OK: + return ret, None, None + tweaks = [self.TWEAKS[j] for j in tc['tweak_indices']] + ret = _apply_tweaks(cache.value, tweaks, tc['is_xonly']) + if ret != WALLY_OK: + wally_musig_keyagg_cache_free(cache.value) + return ret, None, None + aggnonce = c_void_p() + ret = wally_musig_aggnonce_parse(_h(tc['aggnonce']), + MUSIG_AGGNONCE_LEN, aggnonce) + if ret != WALLY_OK: + wally_musig_keyagg_cache_free(cache.value) + return ret, None, None + session = c_void_p() + ret = wally_musig_nonce_process(aggnonce.value, self.MSG, 32, + cache.value, None, 0, session) + wally_musig_aggnonce_free(aggnonce.value) + if ret != WALLY_OK: + wally_musig_keyagg_cache_free(cache.value) + return ret, None, None + return WALLY_OK, cache, session + + def test_valid_cases(self): + self.assertGreater(len(self.V['valid_test_cases']), 0, "valid_test_cases empty") + for i, tc in enumerate(self.V['valid_test_cases']): + with self.subTest(case=i): + ret, cache, session = self._prepare(tc) + self.assertEqual(WALLY_OK, ret) + psigs_flat = b''.join(self.PSIGS[j] for j in tc['psig_indices']) + n = len(tc['psig_indices']) + out, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + ret = wally_musig_partial_sig_agg(psigs_flat, len(psigs_flat), + n, session.value, + out, EC_SIGNATURE_LEN) + self.assertEqual(WALLY_OK, ret, f'case {i}: partial_sig_agg failed') + self.assertEqual(_h(tc['expected']), bytes(out), + f'case {i}: aggregated sig mismatch') + wally_musig_session_free(session.value) + wally_musig_keyagg_cache_free(cache.value) + + def test_error_cases(self): + self.assertGreater(len(self.V['error_test_cases']), 0, "error_test_cases empty") + for i, tc in enumerate(self.V['error_test_cases']): + with self.subTest(case=i, comment=tc.get('comment', '')): + ret, cache, session = self._prepare(tc) + if ret == WALLY_OK: + psigs_flat = b''.join(self.PSIGS[j] for j in tc['psig_indices']) + n = len(tc['psig_indices']) + out, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + ret = wally_musig_partial_sig_agg(psigs_flat, len(psigs_flat), + n, session.value, + out, EC_SIGNATURE_LEN) + _assert_error(self, ret, tc.get('error')) + if session is not None and session.value: + wally_musig_session_free(session.value) + if cache is not None and cache.value: + wally_musig_keyagg_cache_free(cache.value) + + +@unittest.skipUnless(False, 'wally_musig_deterministic_sign is not exposed by ' + 'include/wally_musig.h; det_sign vectors cannot be ' + 'exercised through the public API') +class DetSignVectorTests(unittest.TestCase): + """BIP-327 det_sign_vectors.json (skipped: no public API).""" + + def test_placeholder(self): + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/src/test/util.py b/src/test/util.py index 0a35e3995..bca93969a 100755 --- a/src/test/util.py +++ b/src/test/util.py @@ -453,6 +453,36 @@ class wally_psbt(Structure): ('wally_map_replace_integer', c_int, [POINTER(wally_map), c_uint32, c_void_p, c_size_t]), ('wally_map_sort', c_int, [POINTER(wally_map), c_uint32]), ('wally_merkle_path_xonly_public_key_verify', c_int, [c_void_p, c_size_t, c_void_p, c_size_t]), + ('wally_musig_aggnonce_free', c_int, [c_void_p]), + ('wally_musig_aggnonce_parse', c_int, [c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_aggnonce_serialize', c_int, [c_void_p, c_void_p, c_size_t]), + ('wally_musig_keyagg_cache_free', c_int, [c_void_p]), + ('wally_musig_keyagg_cache_parse', c_int, [c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_keyagg_cache_serialize', c_int, [c_void_p, c_void_p, c_size_t]), + ('wally_musig_nonce_agg', c_int, [c_void_p, c_size_t, c_size_t, POINTER(c_void_p)]), + ('wally_musig_nonce_gen', c_int, [c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_void_p, c_size_t, c_void_p, c_size_t, POINTER(c_void_p), POINTER(c_void_p)]), + ('wally_musig_nonce_gen_counter', c_int, [c_uint64, c_void_p, c_size_t, c_void_p, c_size_t, c_void_p, c_void_p, c_size_t, c_void_p, c_size_t, POINTER(c_void_p), POINTER(c_void_p)]), + ('wally_musig_nonce_process', c_int, [c_void_p, c_void_p, c_size_t, c_void_p, c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_partial_sig_agg', c_int, [c_void_p, c_size_t, c_size_t, c_void_p, c_void_p, c_size_t]), + ('wally_musig_partial_sig_free', c_int, [c_void_p]), + ('wally_musig_partial_sig_parse', c_int, [c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_partial_sig_serialize', c_int, [c_void_p, c_void_p, c_size_t]), + ('wally_musig_partial_sig_verify', c_int, [c_void_p, c_void_p, c_void_p, c_size_t, c_void_p, c_void_p]), + ('wally_musig_partial_sign', c_int, [c_void_p, c_void_p, c_size_t, c_void_p, c_void_p, POINTER(c_void_p)]), + ('wally_musig_pubkey_agg', c_int, [c_void_p, c_size_t, c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_pubkey_ec_tweak_add', c_int, [c_void_p, c_void_p, c_size_t, c_void_p, c_size_t]), + ('wally_musig_pubkey_get', c_int, [c_void_p, c_void_p, c_size_t]), + ('wally_musig_pubkey_to_xpub', c_int, [c_void_p, c_size_t, c_uint32, POINTER(POINTER(ext_key))]), + ('wally_musig_pubkey_xonly_tweak_add', c_int, [c_void_p, c_void_p, c_size_t, c_void_p, c_size_t]), + ('wally_musig_pubkeys_agg_then_derive', c_int, [c_void_p, c_size_t, c_uint32, c_uint32, c_void_p, c_size_t, POINTER(POINTER(ext_key))]), + ('wally_musig_pubkeys_derive_then_agg', c_int, [c_void_p, c_size_t, c_uint32, c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_pubnonce_free', c_int, [c_void_p]), + ('wally_musig_pubnonce_parse', c_int, [c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_pubnonce_serialize', c_int, [c_void_p, c_void_p, c_size_t]), + ('wally_musig_secnonce_free', c_int, [c_void_p]), + ('wally_musig_session_free', c_int, [c_void_p]), + ('wally_musig_session_parse', c_int, [c_void_p, c_size_t, POINTER(c_void_p)]), + ('wally_musig_session_serialize', c_int, [c_void_p, c_void_p, c_size_t]), ('wally_pbkdf2_hmac_sha256', c_int, [c_void_p, c_size_t, c_void_p, c_size_t, c_uint32, c_uint32, c_void_p, c_size_t]), ('wally_pbkdf2_hmac_sha512', c_int, [c_void_p, c_size_t, c_void_p, c_size_t, c_uint32, c_uint32, c_void_p, c_size_t]), ('wally_psbt_add_global_scalar', c_int, [POINTER(wally_psbt), c_void_p, c_size_t]), diff --git a/src/wasm_package/src/const.js b/src/wasm_package/src/const.js index 444bf220d..29392525d 100755 --- a/src/wasm_package/src/const.js +++ b/src/wasm_package/src/const.js @@ -150,6 +150,12 @@ export const WALLY_MS_IS_TAPROOT = 0x1000; /** Contains a tr() taproot expressio export const WALLY_MS_IS_TAPSCRIPT = 0x2000; /** Contains a tr(key,{...}) tapscript tree, or is a tapscript miniscript expression */ export const WALLY_MS_IS_UNCOMPRESSED = 0x0008; /** Contains at least one uncompressed key */ export const WALLY_MS_IS_X_ONLY = 0x0040; /** Contains at least one x-only key */ +export const WALLY_MUSIG2_CHAINCODE_LEN = 32; +export const WALLY_MUSIG_AGGNONCE_LEN = 66; +export const WALLY_MUSIG_KEYAGG_CACHE_LEN = 197; +export const WALLY_MUSIG_PARTIAL_SIG_LEN = 32; +export const WALLY_MUSIG_PUBNONCE_LEN = 66; +export const WALLY_MUSIG_SESSION_LEN = 133; export const WALLY_NETWORK_BITCOIN_MAINNET = 0x01; /** Bitcoin mainnet */ export const WALLY_NETWORK_BITCOIN_REGTEST = 0xff ; /** Bitcoin regtest: Behaves as testnet except for segwit */ export const WALLY_NETWORK_BITCOIN_TESTNET = 0x02; /** Bitcoin testnet */ diff --git a/src/wasm_package/src/functions.js b/src/wasm_package/src/functions.js index 7b6436699..0c0b6e524 100644 --- a/src/wasm_package/src/functions.js +++ b/src/wasm_package/src/functions.js @@ -282,6 +282,36 @@ export const map_replace = wrap('wally_map_replace', [T.OpaqueRef, T.Bytes, T.By export const map_replace_integer = wrap('wally_map_replace_integer', [T.OpaqueRef, T.Int32, T.Bytes]); export const map_sort = wrap('wally_map_sort', [T.OpaqueRef, T.Int32]); export const merkle_path_xonly_public_key_verify = wrap('wally_merkle_path_xonly_public_key_verify', [T.Bytes, T.Bytes]); +export const musig_aggnonce_free = wrap('wally_musig_aggnonce_free', [T.OpaqueRef]); +export const musig_aggnonce_parse = wrap('wally_musig_aggnonce_parse', [T.Bytes, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_aggnonce_serialize = wrap('wally_musig_aggnonce_serialize', [T.OpaqueRef, T.DestPtrSized(T.Bytes, C.WALLY_MUSIG_AGGNONCE_LEN)]); +export const musig_keyagg_cache_free = wrap('wally_musig_keyagg_cache_free', [T.OpaqueRef]); +export const musig_keyagg_cache_parse = wrap('wally_musig_keyagg_cache_parse', [T.Bytes, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_keyagg_cache_serialize = wrap('wally_musig_keyagg_cache_serialize', [T.OpaqueRef, T.DestPtrSized(T.Bytes, C.WALLY_MUSIG_KEYAGG_CACHE_LEN)]); +export const musig_nonce_agg = wrap('wally_musig_nonce_agg', [T.Bytes, T.Int32, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_nonce_gen = wrap('wally_musig_nonce_gen', [T.Bytes, T.Bytes, T.Bytes, T.OpaqueRef, T.Bytes, T.Bytes, T.DestPtrPtr(T.OpaqueRef), T.DestPtrPtr(T.OpaqueRef)]); +export const musig_nonce_gen_counter = wrap('wally_musig_nonce_gen_counter', [T.Int64, T.Bytes, T.Bytes, T.OpaqueRef, T.Bytes, T.Bytes, T.DestPtrPtr(T.OpaqueRef), T.DestPtrPtr(T.OpaqueRef)]); +export const musig_nonce_process = wrap('wally_musig_nonce_process', [T.OpaqueRef, T.Bytes, T.OpaqueRef, T.Bytes, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_partial_sig_agg = wrap('wally_musig_partial_sig_agg', [T.Bytes, T.Int32, T.OpaqueRef, T.DestPtrSized(T.Bytes, C.EC_SIGNATURE_LEN)]); +export const musig_partial_sig_free = wrap('wally_musig_partial_sig_free', [T.OpaqueRef]); +export const musig_partial_sig_parse = wrap('wally_musig_partial_sig_parse', [T.Bytes, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_partial_sig_serialize = wrap('wally_musig_partial_sig_serialize', [T.OpaqueRef, T.DestPtrSized(T.Bytes, C.WALLY_MUSIG_PARTIAL_SIG_LEN)]); +export const musig_partial_sig_verify = wrap('wally_musig_partial_sig_verify', [T.OpaqueRef, T.OpaqueRef, T.Bytes, T.OpaqueRef, T.OpaqueRef]); +export const musig_partial_sign = wrap('wally_musig_partial_sign', [T.OpaqueRef, T.Bytes, T.OpaqueRef, T.OpaqueRef, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_pubkey_agg = wrap('wally_musig_pubkey_agg', [T.Bytes, T.DestPtrSized(T.Bytes, C.EC_XONLY_PUBLIC_KEY_LEN), T.DestPtrPtr(T.OpaqueRef)]); +export const musig_pubkey_ec_tweak_add = wrap('wally_musig_pubkey_ec_tweak_add', [T.OpaqueRef, T.Bytes, T.DestPtrSized(T.Bytes, C.EC_PUBLIC_KEY_LEN)]); +export const musig_pubkey_get = wrap('wally_musig_pubkey_get', [T.OpaqueRef, T.DestPtrSized(T.Bytes, C.EC_PUBLIC_KEY_LEN)]); +export const musig_pubkey_to_xpub = wrap('wally_musig_pubkey_to_xpub', [T.Bytes, T.Int32, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_pubkey_xonly_tweak_add = wrap('wally_musig_pubkey_xonly_tweak_add', [T.OpaqueRef, T.Bytes, T.DestPtrSized(T.Bytes, C.EC_PUBLIC_KEY_LEN)]); +export const musig_pubkeys_agg_then_derive = wrap('wally_musig_pubkeys_agg_then_derive', [T.Bytes, T.Int32, T.Int32, T.DestPtrSized(T.Bytes, C.EC_PUBLIC_KEY_LEN), T.DestPtrPtr(T.OpaqueRef)]); +export const musig_pubkeys_derive_then_agg = wrap('wally_musig_pubkeys_derive_then_agg', [T.Bytes, T.Int32, T.DestPtrSized(T.Bytes, C.EC_XONLY_PUBLIC_KEY_LEN), T.DestPtrPtr(T.OpaqueRef)]); +export const musig_pubnonce_free = wrap('wally_musig_pubnonce_free', [T.OpaqueRef]); +export const musig_pubnonce_parse = wrap('wally_musig_pubnonce_parse', [T.Bytes, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_pubnonce_serialize = wrap('wally_musig_pubnonce_serialize', [T.OpaqueRef, T.DestPtrSized(T.Bytes, C.WALLY_MUSIG_PUBNONCE_LEN)]); +export const musig_secnonce_free = wrap('wally_musig_secnonce_free', [T.OpaqueRef]); +export const musig_session_free = wrap('wally_musig_session_free', [T.OpaqueRef]); +export const musig_session_parse = wrap('wally_musig_session_parse', [T.Bytes, T.DestPtrPtr(T.OpaqueRef)]); +export const musig_session_serialize = wrap('wally_musig_session_serialize', [T.OpaqueRef, T.DestPtrSized(T.Bytes, C.WALLY_MUSIG_SESSION_LEN)]); export const pbkdf2_hmac_sha256 = wrap('wally_pbkdf2_hmac_sha256', [T.Bytes, T.Bytes, T.Int32, T.Int32, T.DestPtrSized(T.Bytes, C.PBKDF2_HMAC_SHA256_LEN)]); export const pbkdf2_hmac_sha512 = wrap('wally_pbkdf2_hmac_sha512', [T.Bytes, T.Bytes, T.Int32, T.Int32, T.DestPtrSized(T.Bytes, C.PBKDF2_HMAC_SHA512_LEN)]); export const psbt_add_global_scalar = wrap('wally_psbt_add_global_scalar', [T.OpaqueRef, T.Bytes]); diff --git a/src/wasm_package/src/index.d.ts b/src/wasm_package/src/index.d.ts index 9194455e5..17bb16b60 100644 --- a/src/wasm_package/src/index.d.ts +++ b/src/wasm_package/src/index.d.ts @@ -242,6 +242,36 @@ export function map_replace(map_in: Ref_wally_map, key: Buffer|Uint8Array|null, export function map_replace_integer(map_in: Ref_wally_map, key: number, value: Buffer|Uint8Array|null): void; export function map_sort(map_in: Ref_wally_map, flags: number): void; export function merkle_path_xonly_public_key_verify(key: Buffer|Uint8Array|null, val: Buffer|Uint8Array|null): void; +export function musig_aggnonce_free(nonce: Ref_wally_musig_aggnonce): void; +export function musig_aggnonce_parse(bytes: Buffer|Uint8Array|null): Ref_wally_musig_aggnonce; +export function musig_aggnonce_serialize(nonce: Ref_wally_musig_aggnonce): Buffer; +export function musig_keyagg_cache_free(cache: Ref_wally_musig_keyagg_cache): void; +export function musig_keyagg_cache_parse(bytes: Buffer|Uint8Array|null): Ref_wally_musig_keyagg_cache; +export function musig_keyagg_cache_serialize(cache: Ref_wally_musig_keyagg_cache): Buffer; +export function musig_nonce_agg(pubnonces: Buffer|Uint8Array|null, n_pubnonces: number): Ref_wally_musig_aggnonce; +export function musig_nonce_gen(session_secrand32: Buffer|Uint8Array|null, seckey: Buffer|Uint8Array|null, pub_key: Buffer|Uint8Array|null, keyagg_cache: Ref_wally_musig_keyagg_cache, msg32: Buffer|Uint8Array|null, extra_input32: Buffer|Uint8Array|null): [secnonce_out: Ref_wally_musig_secnonce, pubnonce_out: Ref_wally_musig_pubnonce]; +export function musig_nonce_gen_counter(counter: bigint, seckey: Buffer|Uint8Array|null, pub_key: Buffer|Uint8Array|null, keyagg_cache: Ref_wally_musig_keyagg_cache, msg32: Buffer|Uint8Array|null, extra_input32: Buffer|Uint8Array|null): [secnonce_out: Ref_wally_musig_secnonce, pubnonce_out: Ref_wally_musig_pubnonce]; +export function musig_nonce_process(aggnonce: Ref_wally_musig_aggnonce, msg32: Buffer|Uint8Array|null, cache: Ref_wally_musig_keyagg_cache, adaptor: Buffer|Uint8Array|null): Ref_wally_musig_session; +export function musig_partial_sig_agg(partial_sigs: Buffer|Uint8Array|null, n_sigs: number, session: Ref_wally_musig_session): Buffer; +export function musig_partial_sig_free(sig: Ref_wally_musig_partial_sig): void; +export function musig_partial_sig_parse(bytes: Buffer|Uint8Array|null): Ref_wally_musig_partial_sig; +export function musig_partial_sig_serialize(sig: Ref_wally_musig_partial_sig): Buffer; +export function musig_partial_sig_verify(sig: Ref_wally_musig_partial_sig, pubnonce: Ref_wally_musig_pubnonce, pub_key: Buffer|Uint8Array|null, cache: Ref_wally_musig_keyagg_cache, session: Ref_wally_musig_session): void; +export function musig_partial_sign(secnonce: Ref_wally_musig_secnonce, seckey: Buffer|Uint8Array|null, cache: Ref_wally_musig_keyagg_cache, session: Ref_wally_musig_session): Ref_wally_musig_partial_sig; +export function musig_pubkey_agg(pub_keys: Buffer|Uint8Array|null): [agg_pk_out: Buffer, cache_out: Ref_wally_musig_keyagg_cache]; +export function musig_pubkey_ec_tweak_add(cache: Ref_wally_musig_keyagg_cache, tweak: Buffer|Uint8Array|null): Buffer; +export function musig_pubkey_get(cache: Ref_wally_musig_keyagg_cache): Buffer; +export function musig_pubkey_to_xpub(agg_pk: Buffer|Uint8Array|null, version: number): Ref_ext_key; +export function musig_pubkey_xonly_tweak_add(cache: Ref_wally_musig_keyagg_cache, tweak: Buffer|Uint8Array|null): Buffer; +export function musig_pubkeys_agg_then_derive(pub_keys: Buffer|Uint8Array|null, version: number, child_num: number): [pub_key_out: Buffer, child_out: Ref_ext_key]; +export function musig_pubkeys_derive_then_agg(xpubs: Buffer|Uint8Array|null, child_num: number): [agg_pk_out: Buffer, cache_out: Ref_wally_musig_keyagg_cache]; +export function musig_pubnonce_free(nonce: Ref_wally_musig_pubnonce): void; +export function musig_pubnonce_parse(bytes: Buffer|Uint8Array|null): Ref_wally_musig_pubnonce; +export function musig_pubnonce_serialize(nonce: Ref_wally_musig_pubnonce): Buffer; +export function musig_secnonce_free(nonce: Ref_wally_musig_secnonce): void; +export function musig_session_free(session: Ref_wally_musig_session): void; +export function musig_session_parse(bytes: Buffer|Uint8Array|null): Ref_wally_musig_session; +export function musig_session_serialize(session: Ref_wally_musig_session): Buffer; export function pbkdf2_hmac_sha256(pass: Buffer|Uint8Array|null, salt: Buffer|Uint8Array|null, flags: number, cost: number): Buffer; export function pbkdf2_hmac_sha512(pass: Buffer|Uint8Array|null, salt: Buffer|Uint8Array|null, flags: number, cost: number): Buffer; export function psbt_add_global_scalar(psbt: Ref_wally_psbt, scalar: Buffer|Uint8Array|null): void; diff --git a/tools/build_wrappers.py b/tools/build_wrappers.py index 359d3dd3c..1f845d381 100755 --- a/tools/build_wrappers.py +++ b/tools/build_wrappers.py @@ -3,7 +3,10 @@ import subprocess # Structs with no definition in the public header files -OPAQUE_STRUCTS = [u'words', u'wally_descriptor'] +OPAQUE_STRUCTS = [u'words', u'wally_descriptor', + u'wally_musig_keyagg_cache', u'wally_musig_secnonce', + u'wally_musig_pubnonce', u'wally_musig_aggnonce', + u'wally_musig_session', u'wally_musig_partial_sig'] EXCLUDED_FUNCS = { # Callers should use the fixed length bip39_mnemonic_to_seed512 diff --git a/tools/wasm_exports.sh b/tools/wasm_exports.sh index f5e8af147..eeab76692 100644 --- a/tools/wasm_exports.sh +++ b/tools/wasm_exports.sh @@ -205,6 +205,36 @@ EXPORTED_FUNCTIONS="['_malloc','_free','_bip32_key_free' \ ,'_wally_map_replace_integer' \ ,'_wally_map_sort' \ ,'_wally_merkle_path_xonly_public_key_verify' \ +,'_wally_musig_aggnonce_free' \ +,'_wally_musig_aggnonce_parse' \ +,'_wally_musig_aggnonce_serialize' \ +,'_wally_musig_keyagg_cache_free' \ +,'_wally_musig_keyagg_cache_parse' \ +,'_wally_musig_keyagg_cache_serialize' \ +,'_wally_musig_nonce_agg' \ +,'_wally_musig_nonce_gen' \ +,'_wally_musig_nonce_gen_counter' \ +,'_wally_musig_nonce_process' \ +,'_wally_musig_partial_sig_agg' \ +,'_wally_musig_partial_sig_free' \ +,'_wally_musig_partial_sig_parse' \ +,'_wally_musig_partial_sig_serialize' \ +,'_wally_musig_partial_sig_verify' \ +,'_wally_musig_partial_sign' \ +,'_wally_musig_pubkey_agg' \ +,'_wally_musig_pubkey_ec_tweak_add' \ +,'_wally_musig_pubkey_get' \ +,'_wally_musig_pubkey_to_xpub' \ +,'_wally_musig_pubkey_xonly_tweak_add' \ +,'_wally_musig_pubkeys_agg_then_derive' \ +,'_wally_musig_pubkeys_derive_then_agg' \ +,'_wally_musig_pubnonce_free' \ +,'_wally_musig_pubnonce_parse' \ +,'_wally_musig_pubnonce_serialize' \ +,'_wally_musig_secnonce_free' \ +,'_wally_musig_session_free' \ +,'_wally_musig_session_parse' \ +,'_wally_musig_session_serialize' \ ,'_wally_pbkdf2_hmac_sha256' \ ,'_wally_pbkdf2_hmac_sha512' \ ,'_wally_psbt_add_input_keypath' \ From 92e6d571fc4c5758e7b2ce8aa231b8418ccea89e Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Tue, 30 Jun 2026 13:38:15 -0300 Subject: [PATCH 6/9] descriptor: add musig() key expressions (BIP-390) Adds the musig() key expression to the descriptor parser (valid only as a taproot internal key or tapscript leaf key), a format_key_node helper for serializing key nodes, and the musig() introspection API (participant count and per-participant keys). This enables parsing and address derivation for tr(musig(...)) descriptors. Includes the musig() descriptor parsing / address-generation tests and the BIP-390 vectors. --- include/wally.hpp | 36 ++ include/wally_descriptor.h | 103 ++++++ src/descriptor.c | 505 +++++++++++++++++++++++++++-- src/descriptor_int.h | 1 + src/swig_java/swig.i | 6 + src/swig_python/python_extra.py_in | 1 + src/test/test_descriptor.py | 349 ++++++++++++++++++++ src/test/test_musig.py | 59 ++++ src/test/test_musig_vectors.py | 122 +++++++ src/test/util.py | 6 + src/wasm_package/src/const.js | 1 + src/wasm_package/src/functions.js | 6 + src/wasm_package/src/index.d.ts | 6 + tools/wasm_exports.sh | 6 + 14 files changed, 1172 insertions(+), 35 deletions(-) diff --git a/include/wally.hpp b/include/wally.hpp index 5e717cd5a..bdea15ed1 100644 --- a/include/wally.hpp +++ b/include/wally.hpp @@ -614,6 +614,42 @@ inline int descriptor_get_key_origin_path_str_len(const DESCRIPTOR& descriptor, return detail::check_ret(__FUNCTION__, ret); } +template +inline int descriptor_get_musig_num_participants(const DESCRIPTOR& descriptor, size_t index, size_t* written) { + int ret = ::wally_descriptor_get_musig_num_participants(detail::get_p(descriptor), index, written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int descriptor_get_musig_participant_key(const DESCRIPTOR& descriptor, size_t index, size_t participant_index, char** output) { + int ret = ::wally_descriptor_get_musig_participant_key(detail::get_p(descriptor), index, participant_index, output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int descriptor_get_musig_participant_key_features(const DESCRIPTOR& descriptor, size_t index, size_t participant_index, uint32_t* value_out) { + int ret = ::wally_descriptor_get_musig_participant_key_features(detail::get_p(descriptor), index, participant_index, value_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int descriptor_get_musig_participant_key_origin_fingerprint(const DESCRIPTOR& descriptor, size_t index, size_t participant_index, BYTES_OUT& bytes_out) { + int ret = ::wally_descriptor_get_musig_participant_key_origin_fingerprint(detail::get_p(descriptor), index, participant_index, bytes_out.data(), bytes_out.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int descriptor_get_musig_participant_key_origin_path_str(const DESCRIPTOR& descriptor, size_t index, size_t participant_index, char** output) { + int ret = ::wally_descriptor_get_musig_participant_key_origin_path_str(detail::get_p(descriptor), index, participant_index, output); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int descriptor_get_musig_participant_key_origin_path_str_len(const DESCRIPTOR& descriptor, size_t index, size_t participant_index, size_t* written) { + int ret = ::wally_descriptor_get_musig_participant_key_origin_path_str_len(detail::get_p(descriptor), index, participant_index, written); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int descriptor_get_network(const DESCRIPTOR& descriptor, uint32_t* value_out) { int ret = ::wally_descriptor_get_network(detail::get_p(descriptor), value_out); diff --git a/include/wally_descriptor.h b/include/wally_descriptor.h index 70ec92bb6..aec567a30 100644 --- a/include/wally_descriptor.h +++ b/include/wally_descriptor.h @@ -38,6 +38,7 @@ struct wally_descriptor; #define WALLY_MS_IS_ELIP151 0x0800 /** A confidential ct() descriptor with ELIP-151 blinding */ #define WALLY_MS_IS_TAPROOT 0x1000 /** Contains a tr() taproot expression */ #define WALLY_MS_IS_TAPSCRIPT 0x2000 /** Contains a tr(key,{...}) tapscript tree, or is a tapscript miniscript expression */ +#define WALLY_MS_IS_MUSIG 0x4000 /** A musig() key aggregate (BIP-390) */ #define WALLY_MS_ANY_BLINDING_KEY 0x0E00 /** SLIP-77, ELIP-150 or ELIP-151 blinding key present */ /*** ms-canonicalization-flags Miniscript/Descriptor canonicalization flags */ @@ -229,6 +230,11 @@ WALLY_CORE_API int wally_descriptor_get_num_keys( *| determine the type of a given key. * * .. note:: Raw private blinding keys are returned as hex, not WIF. + * + * .. note:: A musig() key aggregate occupies a key index but has no single + *| string representation; `WALLY_EINVAL` is returned for it. Detect it + *| with `WALLY_MS_IS_MUSIG` from `wally_descriptor_get_key_features`, + *| then use the `wally_descriptor_get_musig_participant_key` family. */ WALLY_CORE_API int wally_descriptor_get_key( const struct wally_descriptor *descriptor, @@ -359,6 +365,103 @@ WALLY_CORE_API int wally_descriptor_derive_bip32_key_alloc( uint32_t flags, struct ext_key **output); +/** + * Get the number of participants in a musig() key aggregate. + * + * :param descriptor: The descriptor to get the participant count from. + * :param index: The index of the key in the descriptor. + * :param written: Destination for the number of participants. + * + * .. note:: Returns WALLY_EINVAL if the key at ``index`` is not a musig() aggregate. + */ +WALLY_CORE_API int wally_descriptor_get_musig_num_participants( + const struct wally_descriptor *descriptor, + size_t index, + size_t *written); + +/** + * Get a participant key from a musig() key aggregate. + * + * :param descriptor: The descriptor to get the participant key from. + * :param index: The index of the musig() key in the descriptor. + * :param participant_index: The index of the participant within musig(). + * :param output: Destination for the allocated participant key string. + *| The string returned should be freed using `wally_free_string`. + * + * .. note:: Returns WALLY_EINVAL if the key at ``index`` is not a musig() aggregate + *| or if ``participant_index`` is out of range. + */ +WALLY_CORE_API int wally_descriptor_get_musig_participant_key( + const struct wally_descriptor *descriptor, + size_t index, + size_t participant_index, + char **output); + +/** + * Get the features flags for a participant key in a musig() key aggregate. + * + * :param descriptor: The descriptor to get the participant key features from. + * :param index: The index of the musig() key in the descriptor. + * :param participant_index: The index of the participant within musig(). + * :param value_out: Destination for the resulting :ref:`miniscript-features`. + * + * .. note:: Returns WALLY_EINVAL if the key at ``index`` is not a musig() aggregate + *| or if ``participant_index`` is out of range. + */ +WALLY_CORE_API int wally_descriptor_get_musig_participant_key_features( + const struct wally_descriptor *descriptor, + size_t index, + size_t participant_index, + uint32_t *value_out); + +/** + * Get the key origin fingerprint for a participant key in a musig() key aggregate. + * + * :param descriptor: The descriptor to get the fingerprint from. + * :param index: The index of the musig() key in the descriptor. + * :param participant_index: The index of the participant within musig(). + * :param bytes_out: Destination for the 4-byte fingerprint. + * FIXED_SIZED_OUTPUT(len, bytes_out, BIP32_KEY_FINGERPRINT_LEN) + * + * .. note:: Returns WALLY_EINVAL if the participant key has no key origin. + */ +WALLY_CORE_API int wally_descriptor_get_musig_participant_key_origin_fingerprint( + const struct wally_descriptor *descriptor, + size_t index, + size_t participant_index, + unsigned char *bytes_out, + size_t len); + +/** + * Get the length of the key origin path string for a participant key in a musig() key aggregate. + * + * :param descriptor: The descriptor to get the origin path length from. + * :param index: The index of the musig() key in the descriptor. + * :param participant_index: The index of the participant within musig(). + * :param written: Destination for the length of the origin path string, + *| excluding the NUL terminator (zero if not present). + */ +WALLY_CORE_API int wally_descriptor_get_musig_participant_key_origin_path_str_len( + const struct wally_descriptor *descriptor, + size_t index, + size_t participant_index, + size_t *written); + +/** + * Get the key origin path string for a participant key in a musig() key aggregate. + * + * :param descriptor: The descriptor to get the origin path from. + * :param index: The index of the musig() key in the descriptor. + * :param participant_index: The index of the participant within musig(). + * :param output: Destination for the allocated origin path string (empty if not present). + *| The string returned should be freed using `wally_free_string`. + */ +WALLY_CORE_API int wally_descriptor_get_musig_participant_key_origin_path_str( + const struct wally_descriptor *descriptor, + size_t index, + size_t participant_index, + char **output); + /** * Get the maximum length of a script corresponding to an output descriptor. * diff --git a/src/descriptor.c b/src/descriptor.c index 610893be7..423047f6f 100644 --- a/src/descriptor.c +++ b/src/descriptor.c @@ -11,6 +11,9 @@ #include #include #include +#ifndef BUILD_STANDARD_SECP +#include +#endif #ifdef BUILD_ELEMENTS #include #endif @@ -243,6 +246,11 @@ static int generate_script(ms_ctx *ctx, ms_node *node, unsigned char *script, size_t script_len, size_t *written); static int node_generation_size(const ms_node *node, size_t *total); static int is_valid_policy_map(const struct wally_map *map_in, bool *is_elements); +static bool node_is_musig(const ms_node *node); +#ifndef BUILD_STANDARD_SECP +static int musig_derive_key(ms_ctx *ctx, const ms_node *node, + uint32_t flags, struct ext_key *output); +#endif static bool is_elements_policy_map(const struct wally_map *map_in) { @@ -648,7 +656,14 @@ static int node_derive_key(ms_ctx* ctx, const ms_node* node, /* SLIP77 blinding key is returned as a private key */ wally_memcpy(output->priv_key + 1, data, sizeof(output->priv_key) - 1); return WALLY_OK; - } else if ((node->kind & KIND_BIP32) == KIND_BIP32) { + } +#ifndef BUILD_STANDARD_SECP + else if (node_is_musig(node)) { + /* BIP-390 musig(): return the (possibly derived) aggregate key */ + return musig_derive_key(ctx, node, flags, output); + } +#endif + else if ((node->kind & KIND_BIP32) == KIND_BIP32) { int ret = bip32_key_from_base58_n(node->data, node->data_len, output); if (ret == WALLY_OK && node->child_path_len) { size_t path_len; @@ -845,10 +860,28 @@ static int verify_raw(ms_ctx *ctx, ms_node *node) return WALLY_OK; } +#ifndef BUILD_STANDARD_SECP +static int musig_pubkey_cmp(const void *a, const void *b) +{ + return memcmp(a, b, EC_PUBLIC_KEY_LEN); +} + +static bool node_is_musig(const ms_node *node) +{ + return node->builtin && builtin_get(node)->kind == KIND_DESCRIPTOR_MUSIG; +} +#else +static bool node_is_musig(const ms_node *node) { (void)node; return false; } +#endif /* ndef BUILD_STANDARD_SECP */ + static int verify_raw_tr(ms_ctx *ctx, ms_node *node) { - if (node->parent || node->child->builtin || !(node->child->kind & KIND_KEY) || - node_has_uncompressed_key(ctx, node)) + if (node->parent) + return WALLY_EINVAL; + if (!node_is_musig(node->child) && + (node->child->builtin || !(node->child->kind & KIND_KEY))) + return WALLY_EINVAL; + if (node_has_uncompressed_key(ctx, node)) return WALLY_EINVAL; node->type_properties = builtin_get(node)->type_properties; return WALLY_OK; @@ -860,13 +893,214 @@ static int verify_tr(ms_ctx *ctx, ms_node *node) /* only tr(key) and tr(key, tree) is valid */ if (child_count < 1u || child_count > 2u) return WALLY_EINVAL; - if (!node_is_top(node) || node->child->builtin || !(node->child->kind & KIND_KEY) || - node_has_uncompressed_key(ctx, node)) + if (!node_is_top(node)) + return WALLY_EINVAL; + if (!node_is_musig(node->child) && + (node->child->builtin || !(node->child->kind & KIND_KEY))) + return WALLY_EINVAL; + if (node_has_uncompressed_key(ctx, node)) return WALLY_EINVAL; node->type_properties = builtin_get(node)->type_properties; return WALLY_OK; } +#ifndef BUILD_STANDARD_SECP +static int verify_musig(ms_ctx *ctx, ms_node *node) +{ + const uint32_t count = node_get_child_count(node); + ms_node *key; + + /* Require at least 2 participants (wally_musig_pubkey_agg's minimum; + * BIP-390 itself sets no minimum) */ + if (count < 2) + return WALLY_EINVAL; + + /* BIP-390: musig() is only valid in taproot context */ + /* TODO: also allow miniscript pk/pkh parent kinds when tapscript path support is added (currently blocked by tr() FIXME) */ + if (!node->parent || !node->parent->builtin) + return WALLY_EINVAL; + { + const uint32_t parent_kind = builtin_get(node->parent)->kind; + if (parent_kind != KIND_DESCRIPTOR_TR && parent_kind != KIND_DESCRIPTOR_RAW_TR) + return WALLY_EINVAL; + } + + /* Each child must be a raw key expression; no nested musig(), no independent trailing paths */ + key = node->child; + while (key) { + if (key->builtin || !(key->kind & KIND_KEY)) + return WALLY_EINVAL; + /* BIP-390: participant keys must not use hardened derivation (no private key available) */ + if (key->child_path_len) { + uint32_t key_features; + if (bip32_path_str_n_get_features(key->child_path, key->child_path_len, + &key_features) != WALLY_OK) + return WALLY_EINVAL; + if (key_features & BIP32_PATH_IS_HARDENED) + return WALLY_EINVAL; + /* BIP-390: ranged or multi-path participant derivation is mutually + * exclusive with derivation steps after the musig() expression */ + if (node->child_path_len && + (key_features & (BIP32_PATH_IS_WILDCARD | BIP32_PATH_IS_MULTIPATH))) + return WALLY_EINVAL; + } + key = key->next; + } + + /* Validate trailing derivation path if present (set in analyze_miniscript) */ + if (node->child_path_len) { + uint32_t features, num_elems, num_multi, wildcard_pos; + if (bip32_path_str_n_get_features(node->child_path, + node->child_path_len, + &features) != WALLY_OK) + return WALLY_EINVAL; + /* BIP-390: no hardened derivation after musig() */ + if (features & BIP32_PATH_IS_HARDENED) + return WALLY_EINVAL; + if (!(features & BIP32_PATH_IS_BARE)) + return WALLY_EINVAL; + num_elems = (features & BIP32_PATH_LEN_MASK) >> BIP32_PATH_LEN_SHIFT; + num_multi = (features & BIP32_PATH_MULTI_MASK) >> BIP32_PATH_MULTI_SHIFT; + if (num_multi) { + if (ctx->num_multipaths != 1 && ctx->num_multipaths != num_multi) + return WALLY_EINVAL; /* Conflicting multi-path lengths */ + ctx->num_multipaths = num_multi; + ctx->features |= WALLY_MS_IS_MULTIPATH; + node->flags |= WALLY_MS_IS_MULTIPATH; + } + if (features & BIP32_PATH_IS_WILDCARD) { + wildcard_pos = (features & BIP32_PATH_WILDCARD_MASK) >> BIP32_PATH_WILDCARD_SHIFT; + if (wildcard_pos != num_elems - 1) + return WALLY_EINVAL; /* Wildcard must be last element */ + ctx->features |= WALLY_MS_IS_RANGED; + node->flags |= WALLY_MS_IS_RANGED; + } + if (num_elems > ctx->max_path_elems) + ctx->max_path_elems = num_elems; + } + + node->type_properties = builtin_get(node)->type_properties; + /* Register the musig() aggregate itself as a key for introspection */ + node->flags |= WALLY_MS_IS_MUSIG; + ctx->features |= WALLY_MS_IS_MUSIG; + return ctx_add_key_node(ctx, node); +} + +/* Derive the BIP-390 aggregate key of a musig() node. + * Without a trailing path the result is a bare key holding the compressed + * aggregate; otherwise it is the BIP-328 synthetic xpub derived to child_num. + */ +static int musig_derive_key(ms_ctx *ctx, const ms_node *node, + uint32_t flags, struct ext_key *output) +{ + const uint32_t n = node_get_child_count(node); + unsigned char *pubkeys = NULL; + unsigned char agg_xonly[EC_XONLY_PUBLIC_KEY_LEN]; + unsigned char agg_full[EC_PUBLIC_KEY_LEN]; + struct wally_musig_keyagg_cache *keyagg_cache = NULL; + struct ext_key *synthetic_xpub = NULL; + ms_node *key; + uint32_t i; + int ret; + + wally_clear(output, sizeof(*output)); + + if (!(pubkeys = wally_malloc(n * EC_PUBLIC_KEY_LEN))) + return WALLY_ENOMEM; + + /* Step 1: Resolve each participant key to a 33-byte compressed pubkey. + * BIP-390 requires musig() participants to be standard key expressions + * (xpub, WIF, compressed pubkey), which always produce 33-byte output. */ + key = node->child; + for (i = 0; i < n; i++, key = key->next) { + unsigned char buf[EC_PUBLIC_KEY_LEN]; + size_t key_written = 0; + ret = generate_script(ctx, key, buf, sizeof(buf), &key_written); + if (ret != WALLY_OK) + goto cleanup; + if (key_written != EC_PUBLIC_KEY_LEN) { + ret = WALLY_EINVAL; + goto cleanup; + } + memcpy(pubkeys + i * EC_PUBLIC_KEY_LEN, buf, EC_PUBLIC_KEY_LEN); + } + + /* Step 2: Sort pubkeys lexicographically per BIP-390 */ + qsort(pubkeys, n, EC_PUBLIC_KEY_LEN, musig_pubkey_cmp); + + /* Step 3: Aggregate the sorted keys. The full compressed aggregate is + * returned to the caller, and its real parity byte is required for + * BIP-328 derivation below, so the x-only form alone is insufficient. */ + ret = wally_musig_pubkey_agg(pubkeys, n * EC_PUBLIC_KEY_LEN, + agg_xonly, sizeof(agg_xonly), &keyagg_cache); + if (ret == WALLY_OK) + ret = wally_musig_pubkey_get(keyagg_cache, agg_full, sizeof(agg_full)); + if (ret != WALLY_OK) + goto cleanup; + + if (!node->child_path_len) { + /* No trailing path: the aggregate key is the result */ + memcpy(output->pub_key, agg_full, sizeof(agg_full)); + ret = bip32_key_strip_private_key(output); /* Mark as pubkey only */ + } else { + /* Aggregate-then-derive: musig(k1,k2)/path + * Per BIP-390: aggregate -> BIP-328 synthetic xpub -> derive child. */ + const bool is_mainnet = !ctx->addr_ver || + ctx->addr_ver->network == WALLY_NETWORK_BITCOIN_MAINNET || + ctx->addr_ver->network == WALLY_NETWORK_LIQUID; + const uint32_t bip32_ver = is_mainnet ? BIP32_VER_MAIN_PUBLIC : BIP32_VER_TEST_PUBLIC; + const uint32_t path_flags = BIP32_FLAG_STR_WILDCARD | + BIP32_FLAG_STR_BARE | + BIP32_FLAG_STR_MULTIPATH; + /* The synthetic xpub is public-only, so KEY_PUBLIC is implied */ + const uint32_t derive_flags = (flags & BIP32_FLAG_SKIP_HASH) | + BIP32_FLAG_KEY_PUBLIC; + size_t path_len = 0; + + ret = wally_musig_pubkey_to_xpub(agg_full, sizeof(agg_full), + bip32_ver, &synthetic_xpub); + if (ret != WALLY_OK) + goto cleanup; + + ret = bip32_path_from_str_n( + node->child_path, node->child_path_len, + (node->flags & WALLY_MS_IS_RANGED) ? ctx->child_num : 0, + (node->flags & WALLY_MS_IS_MULTIPATH) ? ctx->multi_index : 0, + path_flags, ctx->path_buff, ctx->max_path_elems, &path_len); + if (ret == WALLY_OK) + ret = bip32_key_from_parent_path(synthetic_xpub, ctx->path_buff, + path_len, derive_flags, output); + if (ret != WALLY_OK) + wally_clear(output, sizeof(*output)); + } + +cleanup: + bip32_key_free(synthetic_xpub); /* NULL-safe; defensive free */ + wally_musig_keyagg_cache_free(keyagg_cache); + wally_free(pubkeys); + return ret; +} + +static int generate_musig(ms_ctx *ctx, ms_node *node, + unsigned char *script, size_t script_len, size_t *written) +{ + struct ext_key key; + int ret; + + *written = 0; + + ret = musig_derive_key(ctx, node, BIP32_FLAG_SKIP_HASH, &key); + if (ret == WALLY_OK) { + /* Taproot keys are x-only: skip the aggregate keys parity byte */ + if (script_len >= EC_XONLY_PUBLIC_KEY_LEN) + memcpy(script, key.pub_key + 1, EC_XONLY_PUBLIC_KEY_LEN); + *written = EC_XONLY_PUBLIC_KEY_LEN; + } + wally_clear(&key, sizeof(key)); + return ret; +} +#endif /* ndef BUILD_STANDARD_SECP */ + static int verify_delay(ms_ctx *ctx, ms_node *node) { (void)ctx; @@ -2373,6 +2607,14 @@ static const struct ms_builtin_t g_builtins[] = { TYPE_NONE, 0xffffffff, verify_tr, generate_tr }, +#ifndef BUILD_STANDARD_SECP + { + I_NAME("musig"), + KIND_DESCRIPTOR_MUSIG, + TYPE_NONE, + 0xffffffff, verify_musig, generate_musig + }, +#endif /* ndef BUILD_STANDARD_SECP */ /* miniscript */ { I_NAME("pk_k"), @@ -2648,7 +2890,7 @@ static int analyze_address(ms_ctx *ctx, const char *str, size_t str_len, /* take the possible hex data in node->data, if it is a valid key then * convert it to an allocated binary buffer and make this node a key node */ -static int analyze_key_hex(ms_ctx *ctx, ms_node *node, +static int analyze_key_hex(ms_ctx *ctx, ms_node *node, ms_node *parent, uint32_t flags, bool is_ct_key, bool *is_hex) { unsigned char key[EC_PUBLIC_KEY_UNCOMPRESSED_LEN], *key_p = key; @@ -2731,6 +2973,8 @@ static int analyze_key_hex(ms_ctx *ctx, ms_node *node, } node->flags |= WALLY_MS_IS_RAW; ctx->features |= WALLY_MS_IS_RAW; + if (parent && node_is_musig(parent)) + goto cleanup; /* Participant keys are not registered directly */ ret = ctx_add_key_node(ctx, node); cleanup: wally_clear(key, sizeof(key)); @@ -2756,6 +3000,8 @@ static int analyze_miniscript_key(ms_ctx *ctx, uint32_t flags, if (!node || (parent && !parent->builtin)) return WALLY_EINVAL; + if (parent && node_is_musig(parent)) + flags &= ~WALLY_MINISCRIPT_TAPSCRIPT; /* Participants are aggregated as full keys */ /* * key origin identification @@ -2794,7 +3040,7 @@ static int analyze_miniscript_key(ms_ctx *ctx, uint32_t flags, } /* Check for a hex public key (hex private keys allowed for ct() only) */ - ret = analyze_key_hex(ctx, node, flags, is_ct_key, &is_hex); + ret = analyze_key_hex(ctx, node, parent, flags, is_ct_key, &is_hex); if (ret != WALLY_OK || is_hex) return ret; @@ -2831,7 +3077,10 @@ static int analyze_miniscript_key(ms_ctx *ctx, uint32_t flags, node->flags |= features; if (!is_ct_key) ctx->features |= features; - ret = ctx_add_key_node(ctx, node); + if (parent && node_is_musig(parent)) + ret = WALLY_OK; /* Participant keys are not registered directly */ + else + ret = ctx_add_key_node(ctx, node); } wally_clear(privkey, sizeof(privkey)); return ret; @@ -2917,7 +3166,10 @@ static int analyze_miniscript_key(ms_ctx *ctx, uint32_t flags, node->flags |= WALLY_MS_IS_X_ONLY; ctx->features |= WALLY_MS_IS_X_ONLY; } - ret = ctx_add_key_node(ctx, node); + if (parent && node_is_musig(parent)) + ret = WALLY_OK; /* Participant keys are not registered directly */ + else + ret = ctx_add_key_node(ctx, node); } } wally_clear(&extkey, sizeof(extkey)); @@ -3237,9 +3489,11 @@ static int analyze_miniscript(ms_ctx *ctx, const char *str, size_t str_len, } } - /* A nested expression must consume its entire input. The top - * level is delimited by its checksum instead. */ - if (ret == WALLY_OK && parent && node->builtin && offset != str_len) + /* A nested expression must consume its entire input. musig() is + * exempt as it may be followed by a derivation path, which is + * validated below. The top level is delimited by its checksum instead. */ + if (ret == WALLY_OK && parent && node->builtin && + builtin_get(node)->kind != KIND_DESCRIPTOR_MUSIG && offset != str_len) ret = WALLY_EINVAL; if (ret == WALLY_OK && (indent || brace_depth)) ret = WALLY_EINVAL; /* Unclosed '(' or '{' */ @@ -3251,6 +3505,22 @@ static int analyze_miniscript(ms_ctx *ctx, const char *str, size_t str_len, flags, node, parent); } +#ifndef BUILD_STANDARD_SECP + /* Capture trailing derivation path for musig() nodes: musig(k1,k2)/path */ + if (ret == WALLY_OK && node->builtin && + builtin_get(node)->kind == KIND_DESCRIPTOR_MUSIG && + offset < str_len && str[offset] != '#') { + if (str[offset] == '/') { + /* Note a bare trailing slash yields an empty path, matching the + * parser's leniency for trailing slashes on ordinary keys */ + node->child_path = str + offset + 1; /* skip leading '/' */ + node->child_path_len = str_len - offset - 1; + } else { + ret = WALLY_EINVAL; /* Unexpected trailing content after musig() */ + } + } +#endif /* ndef BUILD_STANDARD_SECP */ + if (ret == WALLY_OK && node->builtin) { const uint32_t expected_children = builtin_get(node)->child_count; if (expected_children != 0xffffffff && node_get_child_count(node) != expected_children) @@ -3348,6 +3618,12 @@ static int node_generation_size(const ms_node *node, size_t *total) * Plus threshold (up to 3 bytes) + OP_NUMEQUAL (1 byte) = 4. */ *total += (node_get_child_count(node) - 1) * 34 + 4; break; +#ifndef BUILD_STANDARD_SECP + case KIND_DESCRIPTOR_MUSIG: + /* The aggregate key generates as one x-only pubkey (32 bytes) */ + *total += EC_XONLY_PUBLIC_KEY_LEN; + break; +#endif /* ndef BUILD_STANDARD_SECP */ case KIND_MINISCRIPT_PK_K: *total += 1; break; @@ -4023,6 +4299,41 @@ static const ms_node *descriptor_get_key(const struct wally_descriptor *descript return (ms_node *)descriptor->keys.items[index].value; } +static int format_key_node(const struct wally_descriptor *descriptor, + const ms_node *node, char **output) +{ + if (node->kind == KIND_PUBLIC_KEY) + return wally_hex_from_bytes((const unsigned char *)node->data, + node->data_len, output); + if (node->kind == KIND_PRIVATE_KEY) { + uint32_t flags = node->flags & WALLY_MS_IS_UNCOMPRESSED ? WALLY_WIF_FLAG_UNCOMPRESSED : 0; + if (!descriptor->addr_ver) + return WALLY_EINVAL; + return wally_wif_from_bytes((const unsigned char *)node->data, node->data_len, + descriptor->addr_ver->version_wif, + flags, output); + } + if ((node->kind & KIND_BIP32) == KIND_BIP32) { + if (node->child_path_len) { + /* Include the derivation path: / */ + size_t total = node->data_len + 1 + node->child_path_len; + char *buf = (char *)wally_malloc(total + 1); + if (!buf) + return WALLY_ENOMEM; + memcpy(buf, node->data, node->data_len); + buf[node->data_len] = '/'; + memcpy(buf + node->data_len + 1, node->child_path, node->child_path_len); + buf[total] = '\0'; + *output = buf; + } else { + if (!(*output = wally_strdup_n(node->data, node->data_len))) + return WALLY_ENOMEM; + } + return WALLY_OK; + } + return WALLY_ERROR; /* Unknown key type */ +} + int wally_descriptor_get_key(const struct wally_descriptor *descriptor, size_t index, char **output) { @@ -4038,6 +4349,10 @@ int wally_descriptor_get_key(const struct wally_descriptor *descriptor, if (node->kind == KIND_PRIVATE_KEY || node->kind == KIND_RAW) goto return_hex; } +#endif +#ifndef BUILD_STANDARD_SECP + if (node->kind == KIND_DESCRIPTOR_MUSIG) + return WALLY_EINVAL; /* musig() aggregate: use wally_descriptor_get_musig_* */ #endif if (node->kind == KIND_PUBLIC_KEY) { #ifdef BUILD_ELEMENTS @@ -4074,6 +4389,142 @@ int wally_descriptor_get_key_features(const struct wally_descriptor *descriptor, return WALLY_OK; } +/* Get a key node's origin fingerprint, if any */ +static int key_node_origin_fingerprint(const struct wally_descriptor *descriptor, + const ms_node *node, + unsigned char *bytes_out, size_t len) +{ + const char *fingerprint; + size_t written; + int ret; + + if (!node || !bytes_out || len != BIP32_KEY_FINGERPRINT_LEN || + !(node->flags & WALLY_MS_IS_PARENTED)) + return WALLY_EINVAL; + fingerprint = descriptor->src + (((uint64_t)node->number) >> 32u) + 1; + ret = wally_hex_n_to_bytes(fingerprint, BIP32_KEY_FINGERPRINT_LEN * 2, + bytes_out, len, &written); + return ret == WALLY_OK && written != BIP32_KEY_FINGERPRINT_LEN ? WALLY_EINVAL : ret; +} + +/* Get the length of a key node's origin path string (0 if not present) */ +static size_t key_node_origin_path_str_len(const ms_node *node) +{ + const size_t len = node->flags & WALLY_MS_IS_PARENTED ? node->number & 0xffffffff : 0; + return len < 11u ? 0 : len - 11u; +} + +/* Copy a key node's origin path string ("" if not present) */ +static int key_node_origin_path_str(const struct wally_descriptor *descriptor, + const ms_node *node, char **output) +{ + const size_t path_len = key_node_origin_path_str_len(node); + const char *path = descriptor->src + (((uint64_t)node->number) >> 32u) + 10u; + + if (!(*output = wally_strdup_n(path, path_len))) + return WALLY_ENOMEM; + return WALLY_OK; +} + +/* Fetch the participant_index'th participant of a musig() key expression, + * or NULL if the key isn't a musig() aggregate/the index is out of range. + */ +static const ms_node *get_musig_participant( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index) +{ + const ms_node *node = descriptor_get_key(descriptor, index); + + if (!node || !node_is_musig(node)) + return NULL; /* Not a musig() key */ + node = node->child; + while (node && participant_index--) + node = node->next; + return node; +} + +int wally_descriptor_get_musig_num_participants( + const struct wally_descriptor *descriptor, + size_t index, size_t *written) +{ + const ms_node *node = descriptor_get_key(descriptor, index); + + if (written) + *written = 0; + if (!node || !written || !node_is_musig(node)) + return WALLY_EINVAL; /* Not a musig() key */ + *written = node_get_child_count(node); + return WALLY_OK; +} + +int wally_descriptor_get_musig_participant_key( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + char **output) +{ + const ms_node *k = get_musig_participant(descriptor, index, participant_index); + + if (output) + *output = NULL; + if (!k || !output) + return WALLY_EINVAL; + return format_key_node(descriptor, k, output); +} + +int wally_descriptor_get_musig_participant_key_features( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + uint32_t *value_out) +{ + const ms_node *k = get_musig_participant(descriptor, index, participant_index); + + if (value_out) + *value_out = 0; + if (!k || !value_out) + return WALLY_EINVAL; + *value_out = k->flags; + return WALLY_OK; +} + +int wally_descriptor_get_musig_participant_key_origin_fingerprint( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + unsigned char *bytes_out, size_t len) +{ + const ms_node *k = get_musig_participant(descriptor, index, participant_index); + + return key_node_origin_fingerprint(descriptor, k, bytes_out, len); +} + +int wally_descriptor_get_musig_participant_key_origin_path_str_len( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + size_t *written) +{ + const ms_node *k = get_musig_participant(descriptor, index, participant_index); + + if (written) + *written = 0; + if (!k || !written) + return WALLY_EINVAL; + *written = key_node_origin_path_str_len(k); + return WALLY_OK; +} + +int wally_descriptor_get_musig_participant_key_origin_path_str( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + char **output) +{ + const ms_node *k = get_musig_participant(descriptor, index, participant_index); + + if (output) + *output = NULL; + if (!k || !output) + return WALLY_EINVAL; + return key_node_origin_path_str(descriptor, k, output); +} + int wally_descriptor_get_key_child_path_str_len( const struct wally_descriptor *descriptor, size_t index, size_t *written) { @@ -4105,18 +4556,9 @@ int wally_descriptor_get_key_origin_fingerprint( const struct wally_descriptor *descriptor, size_t index, unsigned char *bytes_out, size_t len) { - const ms_node *node = descriptor_get_key(descriptor, index); - const char *fingerprint; - size_t written; - int ret; - - if (!node || !bytes_out || len != BIP32_KEY_FINGERPRINT_LEN || - !(node->flags & WALLY_MS_IS_PARENTED)) - return WALLY_EINVAL; - fingerprint = descriptor->src + (((uint64_t)node->number) >> 32u) + 1; - ret = wally_hex_n_to_bytes(fingerprint, BIP32_KEY_FINGERPRINT_LEN * 2, - bytes_out, len, &written); - return ret == WALLY_OK && written != BIP32_KEY_FINGERPRINT_LEN ? WALLY_EINVAL : ret; + return key_node_origin_fingerprint(descriptor, + descriptor_get_key(descriptor, index), + bytes_out, len); } int wally_descriptor_get_key_origin_path_str_len( @@ -4128,8 +4570,7 @@ int wally_descriptor_get_key_origin_path_str_len( *written = 0; if (!node || !written) return WALLY_EINVAL; - *written = node->flags & WALLY_MS_IS_PARENTED ? node->number & 0xffffffff : 0; - *written = *written < 11u ? 0 : *written - 11u; + *written = key_node_origin_path_str_len(node); return WALLY_OK; } @@ -4137,19 +4578,12 @@ int wally_descriptor_get_key_origin_path_str( const struct wally_descriptor *descriptor, size_t index, char **output) { const ms_node *node = descriptor_get_key(descriptor, index); - const char *path; - size_t path_len; if (output) *output = NULL; if (!node || !output) return WALLY_EINVAL; - path_len = node->flags & WALLY_MS_IS_PARENTED ? node->number & 0xffffffff : 0; - path_len = path_len < 11u ? 0 : path_len - 11u; - path = descriptor->src + (((uint64_t)node->number) >> 32u) + 10u; - if (!(*output = wally_strdup_n(path, path_len))) - return WALLY_ENOMEM; - return WALLY_OK; + return key_node_origin_path_str(descriptor, node, output); } int wally_descriptor_derive_bip32_key( @@ -4165,7 +4599,8 @@ int wally_descriptor_derive_bip32_key( if (!node || !index_args_valid(descriptor, variant, multi_index, child_num) || flags & ~(BIP32_FLAG_KEY_PUBLIC|BIP32_FLAG_SKIP_HASH) || !output) return WALLY_EINVAL; - if ((node->kind & KIND_BIP32) == KIND_BIP32 && node->child_path_len) { + if (node_is_musig(node) || + ((node->kind & KIND_BIP32) == KIND_BIP32 && node->child_path_len)) { /* Non-static key: create context required for deriving */ ret = ctx_clone(descriptor, variant, multi_index, child_num, &ctx); if (ret != WALLY_OK) diff --git a/src/descriptor_int.h b/src/descriptor_int.h index 7d1014bf6..32320508b 100644 --- a/src/descriptor_int.h +++ b/src/descriptor_int.h @@ -64,6 +64,7 @@ #define KIND_DESCRIPTOR_CT (0x00300000 | KIND_DESCRIPTOR) #define KIND_DESCRIPTOR_SLIP77 (0x00400000 | KIND_DESCRIPTOR) #define KIND_DESCRIPTOR_ELIP151 (0x00500000 | KIND_DESCRIPTOR) +#define KIND_DESCRIPTOR_MUSIG (0x00600000 | KIND_DESCRIPTOR) /* miniscript */ #define KIND_MINISCRIPT_PK (0x00000100 | KIND_MINISCRIPT) diff --git a/src/swig_java/swig.i b/src/swig_java/swig.i index b78e18b63..61b6e9905 100644 --- a/src/swig_java/swig.i +++ b/src/swig_java/swig.i @@ -613,6 +613,12 @@ static jobjectArray create_jstringArray(JNIEnv *jenv, char **p, size_t len) { %returns_array_(wally_descriptor_get_key_origin_fingerprint, 3, 4, BIP32_KEY_FINGERPRINT_LEN); %returns_string(wally_descriptor_get_key_origin_path_str); %returns_size_t(wally_descriptor_get_key_origin_path_str_len); +%returns_size_t(wally_descriptor_get_musig_num_participants); +%returns_string(wally_descriptor_get_musig_participant_key); +%returns_size_t(wally_descriptor_get_musig_participant_key_features); +%returns_array_(wally_descriptor_get_musig_participant_key_origin_fingerprint, 4, 5, BIP32_KEY_FINGERPRINT_LEN); +%returns_size_t(wally_descriptor_get_musig_participant_key_origin_path_str_len); +%returns_string(wally_descriptor_get_musig_participant_key_origin_path_str); %returns_size_t(wally_descriptor_get_num_keys); %returns_size_t(wally_descriptor_get_num_paths); %returns_size_t(wally_descriptor_get_num_variants); diff --git a/src/swig_python/python_extra.py_in b/src/swig_python/python_extra.py_in index 26e2efed1..6b2135a45 100644 --- a/src/swig_python/python_extra.py_in +++ b/src/swig_python/python_extra.py_in @@ -153,6 +153,7 @@ bip85_get_bip39_entropy = _wrap_bin(bip85_get_bip39_entropy, HMAC_SHA512_LEN, re bip85_get_rsa_entropy = _wrap_bin(bip85_get_rsa_entropy, HMAC_SHA512_LEN, resize=True) descriptor_derive_bip32_key = descriptor_derive_bip32_key_alloc descriptor_get_key_origin_fingerprint = _wrap_bin(descriptor_get_key_origin_fingerprint, BIP32_KEY_FINGERPRINT_LEN) +descriptor_get_musig_participant_key_origin_fingerprint = _wrap_bin(descriptor_get_musig_participant_key_origin_fingerprint, BIP32_KEY_FINGERPRINT_LEN) descriptor_get_taproot_control_block = _wrap_bin(descriptor_get_taproot_control_block, descriptor_get_taproot_control_block_len) descriptor_get_taproot_leaf_hash = _wrap_bin(descriptor_get_taproot_leaf_hash, SHA256_LEN) descriptor_get_taproot_leaf_script = _wrap_bin(descriptor_get_taproot_leaf_script, descriptor_get_taproot_leaf_script_len) diff --git a/src/test/test_descriptor.py b/src/test/test_descriptor.py index ff93e0bee..080fd95b9 100644 --- a/src/test/test_descriptor.py +++ b/src/test/test_descriptor.py @@ -33,6 +33,7 @@ MS_IS_ELIP151 = 0x800 MS_IS_TAPROOT = 0x1000 MS_IS_TAPSCRIPT = 0x2000 +MS_IS_MUSIG = 0x4000 NO_CHECKSUM = 0x1 # WALLY_MS_CANONICAL_NO_CHECKSUM @@ -887,5 +888,353 @@ def test_taproot_bad_args(self): ret = wally_descriptor_get_taproot_leaf_key_index(*args) self.assertEqual(ret, (WALLY_EINVAL, 0)) + def test_musig_parser(self): + """Test musig() descriptor parsing (BIP-390)""" + xpub1 = 'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB' + xpub2 = 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' + xpub3 = 'xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL' + + # Valid: tr(musig(xpub1, xpub2)) - two-participant musig in taproot + valid_cases = [ + f'tr(musig({xpub1},{xpub2}))', + # With trailing ranged wildcard path + f'tr(musig({xpub1},{xpub2})/<0;1>/*)', + # With plain trailing derivation path + f'tr(musig({xpub1},{xpub2})/0/*)', + # Participant keys may carry their own derivation path + f'tr(musig({xpub1}/0,{xpub2}/1))', + # Three-participant musig (3-of-3) + f'tr(musig({xpub1},{xpub2},{xpub3}))', + ] + for desc in valid_cases: + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK, f'Expected WALLY_OK for: {desc}') + + # MS_IS_MUSIG feature flag must be set (whole-descriptor) + ret, features = wally_descriptor_get_features(d) + self.assertEqual(ret, WALLY_OK) + self.assertTrue(features & MS_IS_MUSIG, f'MS_IS_MUSIG not set for: {desc}') + # MS_IS_TAPSCRIPT must NOT be set (musig is the internal key, not in a leaf) + self.assertFalse(features & MS_IS_TAPSCRIPT, f'MS_IS_TAPSCRIPT unexpectedly set for: {desc}') + + # MS_IS_MUSIG feature flag must also be set at the per-key level + ret, kf = wally_descriptor_get_key_features(d, 0) + self.assertEqual(ret, WALLY_OK) + self.assertTrue(kf & MS_IS_MUSIG, f'Per-key MS_IS_MUSIG not set for: {desc}') + + wally_descriptor_free(d) + + # Valid cases must also parse with the tapscript flag: it propagates + # to the internal key, whose trailing derivation path must not be + # rejected as unconsumed input. + for desc in valid_cases: + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_NONE, MS_TAP, d) + self.assertEqual(ret, WALLY_OK, f'{desc} (tapscript flag)') + wally_descriptor_free(d) + + # Participant count and key extraction for the basic two-participant case + two_participant_cases = [ + f'tr(musig({xpub1},{xpub2}))', + f'tr(musig({xpub1},{xpub2})/<0;1>/*)', + f'tr(musig({xpub1},{xpub2})/0/*)', + ] + for desc in two_participant_cases: + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + # Participant count at key index 0 + ret, count = wally_descriptor_get_musig_num_participants(d, 0) + self.assertEqual((ret, count), (WALLY_OK, 2), f'Count check failed for: {desc}') + # Participant key extraction + ret, key0 = wally_descriptor_get_musig_participant_key(d, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key0, xpub1) + ret, key1 = wally_descriptor_get_musig_participant_key(d, 0, 1) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key1, xpub2) + # Out-of-range participant index + ret, _ = wally_descriptor_get_musig_participant_key(d, 0, 2) + self.assertEqual(ret, WALLY_EINVAL) + wally_descriptor_free(d) + + # Participant keys with per-participant paths + d = c_void_p() + desc_pp = f'tr(musig({xpub1}/0,{xpub2}/1))' + ret = wally_descriptor_parse(desc_pp, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, count = wally_descriptor_get_musig_num_participants(d, 0) + self.assertEqual((ret, count), (WALLY_OK, 2)) + ret, key0 = wally_descriptor_get_musig_participant_key(d, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key0, f'{xpub1}/0') + ret, key1 = wally_descriptor_get_musig_participant_key(d, 0, 1) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key1, f'{xpub2}/1') + wally_descriptor_free(d) + + # Participant count and key extraction for the three-participant case + d = c_void_p() + desc3 = f'tr(musig({xpub1},{xpub2},{xpub3}))' + ret = wally_descriptor_parse(desc3, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, count = wally_descriptor_get_musig_num_participants(d, 0) + self.assertEqual((ret, count), (WALLY_OK, 3), f'Count check failed for: {desc3}') + ret, key0 = wally_descriptor_get_musig_participant_key(d, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key0, xpub1) + ret, key1 = wally_descriptor_get_musig_participant_key(d, 0, 1) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key1, xpub2) + ret, key2 = wally_descriptor_get_musig_participant_key(d, 0, 2) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(key2, xpub3) + # Out-of-range participant index for 3-participant case + ret, _ = wally_descriptor_get_musig_participant_key(d, 0, 3) + self.assertEqual(ret, WALLY_EINVAL) + wally_descriptor_free(d) + + # Error: non-musig descriptor key at index 0 + d2 = c_void_p() + ret = wally_descriptor_parse(f'tr({xpub1})', None, NETWORK_NONE, 0, d2) + self.assertEqual(ret, WALLY_OK) + ret, _ = wally_descriptor_get_musig_num_participants(d2, 0) + self.assertEqual(ret, WALLY_EINVAL) + ret, _ = wally_descriptor_get_musig_participant_key(d2, 0, 0) + self.assertEqual(ret, WALLY_EINVAL) + wally_descriptor_free(d2) + + # Error: NULL descriptor + ret, _ = wally_descriptor_get_musig_num_participants(None, 0) + self.assertEqual(ret, WALLY_EINVAL) + ret, _ = wally_descriptor_get_musig_participant_key(None, 0, 0) + self.assertEqual(ret, WALLY_EINVAL) + + # Invalid: musig() in non-taproot context or forbidden forms + invalid_cases = [ + # wpkh does not accept musig() + f'wpkh(musig({xpub1},{xpub2}))', + # pk does not accept musig() + f'pk(musig({xpub1},{xpub2}))', + # pkh does not accept musig() + f'pkh(musig({xpub1},{xpub2}))', + # nested musig() is forbidden + f'tr(musig(musig({xpub1},{xpub2}),{xpub2}))', + # single participant is forbidden (BIP-390 requires >=2) + f'tr(musig({xpub1}))', + # hardened trailing derivation step is forbidden + f'tr(musig({xpub1},{xpub2})/1h/*)', + f'tr(musig({xpub1},{xpub2})/*h)', + # hardened participant derivation is forbidden + f'tr(musig({xpub1}/*h,{xpub2}/*h))', + ] + for desc in invalid_cases: + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_EINVAL, f'Expected WALLY_EINVAL for: {desc}') + if ret == WALLY_OK: + wally_descriptor_free(d) + + def test_musig_derive_bip32_key(self): + """Test deriving the musig() aggregate key (BIP-390/BIP-328)""" + BIP32_VER_MAIN_PUBLIC = 0x0488B21E + EC_PUBLIC_KEY_LEN, EC_XONLY_PUBLIC_KEY_LEN = 33, 32 + xpub1 = 'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB' + xpub2 = 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' + + # Independently aggregate the participant keys, sorted as per BIP-390 + pubkeys = [] + for xpub in (xpub1, xpub2): + key = ext_key() + self.assertEqual(WALLY_OK, bip32_key_from_base58(xpub.encode(), key)) + pubkeys.append(bytes(key.pub_key)) + flat = b''.join(sorted(pubkeys)) + agg_xonly, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) + cache = c_void_p() + self.assertEqual(WALLY_OK, wally_musig_pubkey_agg(flat, len(flat), agg_xonly, + EC_XONLY_PUBLIC_KEY_LEN, cache)) + agg_full, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + self.assertEqual(WALLY_OK, wally_musig_pubkey_get(cache.value, agg_full, + EC_PUBLIC_KEY_LEN)) + wally_musig_keyagg_cache_free(cache.value) + + # A musig() aggregate is a key in its own right, at key index 0 + d = c_void_p() + ret = wally_descriptor_parse(f'tr(musig({xpub1},{xpub2}))', None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, features = wally_descriptor_get_key_features(d, 0) + self.assertEqual((ret, features & MS_IS_MUSIG), (WALLY_OK, MS_IS_MUSIG)) + + # With no trailing path, a bare key holding the aggregate is returned + key = ext_key() + ret = wally_descriptor_derive_bip32_key(d, 0, 0, 0, 0, 0, key) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(bytes(key.pub_key), bytes(agg_full)) + self.assertEqual(bytes(key.pub_key)[1:], bytes(agg_xonly)) + self.assertEqual(key.priv_key[0], FLAG_KEY_PUBLIC) + wally_descriptor_free(d) + + # With a trailing path, the BIP-328 synthetic xpub is derived from + synthetic = POINTER(ext_key)() + ret = wally_musig_pubkey_to_xpub(agg_full, EC_PUBLIC_KEY_LEN, + BIP32_VER_MAIN_PUBLIC, synthetic) + self.assertEqual(ret, WALLY_OK) + + d = c_void_p() + ret = wally_descriptor_parse(f'tr(musig({xpub1},{xpub2})/0/*)', None, + NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + derived_keys = [] + for child_num in (0, 1): + path = (c_uint32 * 2)(0, child_num) + expected = ext_key() + self.assertEqual(WALLY_OK, + bip32_key_from_parent_path(synthetic, path, 2, + FLAG_KEY_PUBLIC, expected)) + key = ext_key() + ret = wally_descriptor_derive_bip32_key(d, 0, 0, 0, child_num, 0, key) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(bytes(key.pub_key), bytes(expected.pub_key)) + self.assertEqual(bytes(key.chain_code), bytes(expected.chain_code)) + derived_keys.append(bytes(key.pub_key)) + self.assertNotEqual(derived_keys[0], derived_keys[1]) + + # musig() keys are only valid under tr(): no other key index exists + key = ext_key() + self.assertEqual(WALLY_EINVAL, + wally_descriptor_derive_bip32_key(d, 1, 0, 0, 0, 0, key)) + wally_descriptor_free(d) + bip32_key_free(synthetic) + + def test_musig_descriptor_address_generation(self): + """Test musig() descriptor address generation""" + xpub1 = 'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB' + xpub2 = 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' + + # 4a. Static musig() taproot address generation (mainnet) + desc = f'tr(musig({xpub1},{xpub2}))' + expected_addr_main = 'bc1p7y6m7r4u0035792q9dst9f32340nev5398dp9yvqw4mjkm3m4pdsqusq07' + expected_addr_test = 'tb1p7y6m7r4u0035792q9dst9f32340nev5398dp9yvqw4mjkm3m4pdsh5x043' + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_BTC_MAIN, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, addr_main = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(addr_main, expected_addr_main, + f'Expected known mainnet address, got: {addr_main}') + wally_descriptor_free(d) + + # Static musig() taproot address generation (testnet) + # Parse with NETWORK_NONE then set testnet (mainnet xpubs work with NONE) + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + ret = wally_descriptor_set_network(d, NETWORK_BTC_TEST) + self.assertEqual(ret, WALLY_OK) + ret, addr_test = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(addr_test, expected_addr_test, + f'Expected known testnet address, got: {addr_test}') + wally_descriptor_free(d) + + # Main and test addresses must differ + self.assertNotEqual(addr_main, addr_test) + + # Participants are full keys, even when parsing in tapscript context + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_BTC_MAIN, MS_TAP, d) + self.assertEqual(ret, WALLY_OK) + ret, addr = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual((ret, addr), (WALLY_OK, expected_addr_main)) + wally_descriptor_free(d) + + # 4b. Ranged musig() address derivation + desc_ranged = f'tr(musig({xpub1},{xpub2})/*)' + addrs = (c_char_p * 3)() + d = c_void_p() + ret = wally_descriptor_parse(desc_ranged, None, NETWORK_BTC_MAIN, 0, d) + self.assertEqual(ret, WALLY_OK) + ret = wally_descriptor_to_addresses(d, 0, 0, 0, 0, addrs, 3) + self.assertEqual(ret, WALLY_OK) + addr_strings = [a.decode() for a in addrs[:3]] + for a in addr_strings: + self.assertTrue(a.startswith('bc1p'), f'Expected bc1p prefix, got: {a}') + self.assertEqual(len(set(addr_strings)), 3, 'All ranged addresses must be distinct') + wally_descriptor_free(d) + + # 4c. Multipath ranged musig() descriptor + desc_mp = f'tr(musig({xpub1},{xpub2})/<0;1>/*)' + addrs_ext = (c_char_p * 1)() + addrs_int = (c_char_p * 1)() + d = c_void_p() + ret = wally_descriptor_parse(desc_mp, None, NETWORK_BTC_MAIN, 0, d) + self.assertEqual(ret, WALLY_OK) + # External path (multi_index=0) + ret = wally_descriptor_to_addresses(d, 0, 0, 0, 0, addrs_ext, 1) + self.assertEqual(ret, WALLY_OK) + self.assertTrue(addrs_ext[0].decode().startswith('bc1p')) + # Internal path (multi_index=1) + ret = wally_descriptor_to_addresses(d, 0, 1, 0, 0, addrs_int, 1) + self.assertEqual(ret, WALLY_OK) + self.assertTrue(addrs_int[0].decode().startswith('bc1p')) + self.assertNotEqual(addrs_ext[0], addrs_int[0]) + wally_descriptor_free(d) + + # 4d. Per-participant derivation paths + desc_pp = f'tr(musig({xpub1}/0,{xpub2}/1))' + d = c_void_p() + ret = wally_descriptor_parse(desc_pp, None, NETWORK_BTC_MAIN, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, addr = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertTrue(addr.startswith('bc1p'), f'Expected bc1p prefix, got: {addr}') + wally_descriptor_free(d) + + # 4e. Address generation requires network set + d = c_void_p() + ret = wally_descriptor_parse(desc, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, _ = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(ret, WALLY_EINVAL) + wally_descriptor_free(d) + + # Key order independence: swapping keys must produce the same address + desc_swapped = f'tr(musig({xpub2},{xpub1}))' + d = c_void_p() + ret = wally_descriptor_parse(desc_swapped, None, NETWORK_BTC_MAIN, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, addr_swapped = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(addr_swapped, addr_main, + 'Key order must not affect the aggregated taproot address') + wally_descriptor_free(d) + + # Canonicalization: wally_descriptor_canonicalize works for musig() descriptors + # and produces a deterministic output. + # NOTE: libwally's wally_descriptor_canonicalize normalises the textual descriptor + # (e.g. removes whitespace, normalises separators) but intentionally does NOT + # re-sort participant keys inside musig(). Sorting happens at the cryptographic + # aggregation stage (BIP-327 KeyAgg), not at the descriptor text level, which is + # why two descriptors with swapped keys still produce the same address (tested + # above). The canonical form therefore preserves the input key order. + d = c_void_p() + ret = wally_descriptor_parse(desc_swapped, None, NETWORK_NONE, 0, d) + self.assertEqual(ret, WALLY_OK) + ret, canonical = wally_descriptor_canonicalize(d, NO_CHECKSUM) + self.assertEqual(ret, WALLY_OK) + self.assertEqual(canonical, desc_swapped, + 'Canonical form preserves input key order (sorting is done at ' + 'key-aggregation time, not descriptor-text level)') + wally_descriptor_free(d) + + # musig() in a tapscript leaf is not yet supported (tr() FIXME for script paths). + # Verify that the parser correctly rejects this form until implemented. + desc_leaf = f'tr({xpub1},pk(musig({xpub1},{xpub2})))' + d = c_void_p() + ret = wally_descriptor_parse(desc_leaf, None, NETWORK_BTC_MAIN, 0, d) + self.assertNotEqual(ret, WALLY_OK, 'Script-leaf musig() should be rejected until implemented') + + if __name__ == '__main__': unittest.main() diff --git a/src/test/test_musig.py b/src/test/test_musig.py index f2879bc1f..39214200d 100644 --- a/src/test/test_musig.py +++ b/src/test/test_musig.py @@ -1149,6 +1149,34 @@ def test_keyagg_cache_roundtrip_3keys(self): wally_musig_keyagg_cache_free(cache.value) wally_musig_keyagg_cache_free(cache2.value) + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_descriptor_musig_outside_tr_rejected(self): + """musig() is only valid inside tr(); using it in wpkh() must fail""" + pk1 = '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798' + pk2 = '02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5' + bad_desc = f'wpkh(musig({pk1},{pk2}))' + d = c_void_p() + ret = wally_descriptor_parse(bad_desc, None, 0, 0, d) + self.assertNotEqual(WALLY_OK, ret, + 'musig() inside wpkh() must be rejected') + if d.value: + wally_descriptor_free(d.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_descriptor_nested_musig_rejected(self): + """Nested musig() must be rejected by the descriptor parser""" + pk1 = '0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798' + pk2 = '02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5' + pk3 = '02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9' + bad_desc = f'tr(musig(musig({pk1},{pk2}),{pk3}))' + d = c_void_p() + ret = wally_descriptor_parse(bad_desc, None, 0, 0, d) + self.assertNotEqual(WALLY_OK, ret, + 'nested musig() must be rejected') + if d.value: + wally_descriptor_free(d.value) + + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') def test_partial_sign_nonce_reuse(self): """SECURITY: secp256k1 zeroes the secnonce after partial_sign to prevent nonce reuse. @@ -1209,6 +1237,37 @@ def test_partial_sign_nonce_reuse(self): wally_musig_session_free(session.value) wally_musig_keyagg_cache_free(cache.value) + @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') + def test_descriptor_musig_hardened_rejected(self): + """wally_descriptor_parse must reject tr(musig()) with hardened child paths after xpub. + + BIP-32 public-key-only derivation cannot produce hardened children + (requires the private key). musig() keys are aggregated public keys, + so hardened derivation paths inside musig() must be rejected. + """ + xpub1 = 'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB' + xpub2 = 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' + fp1 = 'deadbeef' + fp2 = 'cafebabe' + + # Hardened child index after the xpub: /0h/* - must be rejected. + bad_desc = f'tr(musig([{fp1}/86h/0h/0h]{xpub1}/0h/*,[{fp2}/86h/0h/0h]{xpub2}/0h/*))' + d = c_void_p() + ret = wally_descriptor_parse(bad_desc, None, 0, 0, d) + self.assertNotEqual(WALLY_OK, ret, + 'musig() descriptor with hardened child path after xpub must be rejected') + if d.value: + wally_descriptor_free(d.value) + + # Sanity check: the same descriptor with unhardened /0/* must be accepted. + good_desc = f'tr(musig([{fp1}/86h/0h/0h]{xpub1}/0/*,[{fp2}/86h/0h/0h]{xpub2}/0/*))' + d2 = c_void_p() + ret2 = wally_descriptor_parse(good_desc, None, 0, 0, d2) + self.assertEqual(WALLY_OK, ret2, + 'musig() descriptor with unhardened /0/* must be accepted') + if d2.value: + wally_descriptor_free(d2.value) + if __name__ == '__main__': unittest.main() diff --git a/src/test/test_musig_vectors.py b/src/test/test_musig_vectors.py index 24ea98544..c5bbe8e0e 100644 --- a/src/test/test_musig_vectors.py +++ b/src/test/test_musig_vectors.py @@ -551,6 +551,128 @@ def test_agg_then_derive_consistent(self): @unittest.skipUnless(wally_musig_pubkey_agg, 'MuSig2 module not enabled') +class Bip390DescriptorVectorTests(unittest.TestCase): + """BIP-390 musig() descriptor parsing and address generation tests.""" + + PK1 = '02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9' + PK2 = '03DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659' + XPUB1 = 'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB' + XPUB2 = 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' + + def test_tr_musig_2of2_parse_and_participants(self): + """tr(musig(pk1,pk2)) parses with 2 participants.""" + desc_str = f'tr(musig({self.PK1},{self.PK2}))' + d = c_void_p() + ret = wally_descriptor_parse(desc_str, None, NETWORK_NONE, 0, d) + self.assertEqual(WALLY_OK, ret, f'Failed to parse: {desc_str}') + + ret, num_participants = wally_descriptor_get_musig_num_participants(d, 0) + self.assertEqual(WALLY_OK, ret) + self.assertEqual(2, num_participants, 'Expected 2 musig participants') + + wally_descriptor_free(d) + + def test_tr_musig_address_is_bech32m(self): + """tr(musig(pk1,pk2)) on mainnet generates a bc1p address.""" + desc_str = f'tr(musig({self.PK1},{self.PK2}))' + d = c_void_p() + self.assertEqual(WALLY_OK, + wally_descriptor_parse(desc_str, None, NETWORK_BTC_MAIN, 0, d)) + + ret, addr = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(WALLY_OK, ret, 'Address generation failed') + addr_str = addr.decode('ascii') if isinstance(addr, bytes) else addr + self.assertTrue(addr_str.startswith('bc1p'), + f'Expected bech32m (bc1p...) address, got: {addr_str}') + wally_descriptor_free(d) + + def test_tr_musig_with_xpub_derivation_paths(self): + """tr(musig([fp/path]xpub1/0/*, [fp/path]xpub2/0/*)) parses and has 2 participants.""" + desc_str = (f'tr(musig([deadbeef/86h/0h/0h]{self.XPUB1}/0/*,' + f'[cafebabe/86h/0h/0h]{self.XPUB2}/0/*))') + d = c_void_p() + ret = wally_descriptor_parse(desc_str, None, NETWORK_NONE, 0, d) + self.assertEqual(WALLY_OK, ret, f'Failed to parse: {desc_str}') + + ret, num_participants = wally_descriptor_get_musig_num_participants(d, 0) + self.assertEqual(WALLY_OK, ret) + self.assertEqual(2, num_participants) + wally_descriptor_free(d) + + def test_tr_musig_xpub_multiple_address_indices(self): + """Different child indices produce different tr(musig) addresses.""" + desc_str = f'tr(musig({self.XPUB1}/0/*,{self.XPUB2}/0/*))' + d = c_void_p() + ret = wally_descriptor_parse(desc_str, None, NETWORK_BTC_MAIN, 0, d) + self.assertEqual(WALLY_OK, ret) + + ret0, addr0 = wally_descriptor_to_address(d, 0, 0, 0, 0) + self.assertEqual(WALLY_OK, ret0) + ret1, addr1 = wally_descriptor_to_address(d, 0, 0, 1, 0) + self.assertEqual(WALLY_OK, ret1) + + a0 = addr0.decode('ascii') if isinstance(addr0, bytes) else addr0 + a1 = addr1.decode('ascii') if isinstance(addr1, bytes) else addr1 + self.assertNotEqual(a0, a1, 'Different indices must produce different addresses') + wally_descriptor_free(d) + + def _descriptor_script_hex(self, desc_str, child_num): + d = c_void_p() + ret = wally_descriptor_parse(desc_str, None, NETWORK_NONE, 0, d) + self.assertEqual(WALLY_OK, ret, f'Failed to parse: {desc_str}') + script, script_len = make_cbuffer('00' * 128) + ret, written = wally_descriptor_to_script(d, 0, 0, 0, 0, child_num, 0, + script, script_len) + self.assertEqual(WALLY_OK, ret, f'to_script failed: {desc_str}') + wally_descriptor_free(d) + return script[:written].hex() + + def test_bip390_valid_vectors(self): + """Pin the BIP-390 valid test vector scriptPubKeys.""" + pk3 = '023590A94E768F8E1815C2F24B4D80A8E3149316C3518CE7B7AD338368D038CA66' + # tr(musig(...)) with three static keys + script = self._descriptor_script_hex( + f'tr(musig({self.PK1},{self.PK2},{pk3}))', 0) + self.assertEqual( + '512079e6c3e628c9bfbce91de6b7fb28e2aec7713d377cf260ab599dcbc40e542312', + script) + # Ranged musig() over xpubs, first three indices + xpub_a = ('xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJ' + 'bZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL') + xpub_b = ('xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrAD' + 'WgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y') + expected = [ + '51209508c08832f3bb9d5e8baf8cb5cfa3669902e2f2da19acea63ff47b93faa9bfc', + '51205ca1102663025a83dd9b5dbc214762c5a6309af00d48167d2d6483808525a298', + '51207dbed1b89c338df6a1ae137f133a19cae6e03d481196ee6f1a5c7d1aeb56b166', + ] + for child_num, want in enumerate(expected): + script = self._descriptor_script_hex( + f'rawtr(musig({xpub_a},{xpub_b})/0/*)', child_num) + self.assertEqual(want, script, f'index {child_num}') + + def test_bip390_invalid_derivation_combos(self): + """BIP-390: ranged/multipath participants are invalid with a trailing path.""" + invalid = [ + # Ranged participants with ranged musig() + f'tr(musig({self.XPUB1}/*,{self.XPUB2})/0/*)', + # Ranged participants with a static trailing path + f'tr(musig({self.XPUB1}/*,{self.XPUB2}/*)/1/2)', + # Multipath participants with multipath musig() + f'tr(musig({self.XPUB1}/<0;1>,{self.XPUB2})/<2;3>)', + ] + for desc_str in invalid: + d = c_void_p() + ret = wally_descriptor_parse(desc_str, None, NETWORK_NONE, 0, d) + self.assertEqual(WALLY_EINVAL, ret, f'Must not parse: {desc_str}') + # Static participant paths plus a trailing path remain valid + valid = f'tr(musig({self.XPUB1}/1,{self.XPUB2}/1)/2)' + d = c_void_p() + ret = wally_descriptor_parse(valid, None, NETWORK_NONE, 0, d) + self.assertEqual(WALLY_OK, ret, f'Must parse: {valid}') + wally_descriptor_free(d) + + def _build_cache(pubkeys_flat): agg_pk, _ = make_cbuffer('00' * EC_XONLY_PUBLIC_KEY_LEN) cache = c_void_p() diff --git a/src/test/util.py b/src/test/util.py index bca93969a..8102cf21d 100755 --- a/src/test/util.py +++ b/src/test/util.py @@ -334,6 +334,12 @@ class wally_psbt(Structure): ('wally_descriptor_get_key_origin_fingerprint', c_int, [c_void_p, c_size_t, c_void_p, c_size_t]), ('wally_descriptor_get_key_origin_path_str', c_int, [c_void_p, c_size_t, c_char_p_p]), ('wally_descriptor_get_key_origin_path_str_len', c_int, [c_void_p, c_size_t, c_size_t_p]), + ('wally_descriptor_get_musig_num_participants', c_int, [c_void_p, c_size_t, c_size_t_p]), + ('wally_descriptor_get_musig_participant_key', c_int, [c_void_p, c_size_t, c_size_t, c_char_p_p]), + ('wally_descriptor_get_musig_participant_key_features', c_int, [c_void_p, c_size_t, c_size_t, c_uint32_p]), + ('wally_descriptor_get_musig_participant_key_origin_fingerprint', c_int, [c_void_p, c_size_t, c_size_t, c_void_p, c_size_t]), + ('wally_descriptor_get_musig_participant_key_origin_path_str', c_int, [c_void_p, c_size_t, c_size_t, c_char_p_p]), + ('wally_descriptor_get_musig_participant_key_origin_path_str_len', c_int, [c_void_p, c_size_t, c_size_t, c_size_t_p]), ('wally_descriptor_get_network', c_int, [c_void_p, c_uint32_p]), ('wally_descriptor_get_num_keys', c_int, [c_void_p, c_uint32_p]), ('wally_descriptor_get_num_paths', c_int, [c_void_p, c_uint32_p]), diff --git a/src/wasm_package/src/const.js b/src/wasm_package/src/const.js index 29392525d..33d55ae2a 100755 --- a/src/wasm_package/src/const.js +++ b/src/wasm_package/src/const.js @@ -141,6 +141,7 @@ export const WALLY_MS_IS_ELEMENTS = 0x0100; /** Contains Elements expressions or export const WALLY_MS_IS_ELIP150 = 0x0400; /** A confidential ct() descriptor with ELIP-150 blinding */ export const WALLY_MS_IS_ELIP151 = 0x0800; /** A confidential ct() descriptor with ELIP-151 blinding */ export const WALLY_MS_IS_MULTIPATH = 0x0002; /** Allows multiple paths via ```` */ +export const WALLY_MS_IS_MUSIG = 0x4000; /** A musig() key aggregate (BIP-390) */ export const WALLY_MS_IS_PARENTED = 0x0080; /** Contains at least one key with a parent key origin */ export const WALLY_MS_IS_PRIVATE = 0x0004; /** Contains at least one private key */ export const WALLY_MS_IS_RANGED = 0x0001; /** Allows key ranges via ``*`` */ diff --git a/src/wasm_package/src/functions.js b/src/wasm_package/src/functions.js index 0c0b6e524..0a9f26eaf 100644 --- a/src/wasm_package/src/functions.js +++ b/src/wasm_package/src/functions.js @@ -175,6 +175,11 @@ export const descriptor_get_key_child_path_str_len = wrap('wally_descriptor_get_ export const descriptor_get_key_features = wrap('wally_descriptor_get_key_features', [T.OpaqueRef, T.Int32, T.DestPtr(T.Int32)]); export const descriptor_get_key_origin_fingerprint = wrap('wally_descriptor_get_key_origin_fingerprint', [T.OpaqueRef, T.Int32, T.DestPtrSized(T.Bytes, C.BIP32_KEY_FINGERPRINT_LEN)]); export const descriptor_get_key_origin_path_str_len = wrap('wally_descriptor_get_key_origin_path_str_len', [T.OpaqueRef, T.Int32, T.DestPtr(T.Int32)]); +export const descriptor_get_musig_num_participants = wrap('wally_descriptor_get_musig_num_participants', [T.OpaqueRef, T.Int32, T.DestPtr(T.Int32)]); +export const descriptor_get_musig_participant_key = wrap('wally_descriptor_get_musig_participant_key', [T.OpaqueRef, T.Int32, T.Int32, T.DestPtrPtr(T.String)]); +export const descriptor_get_musig_participant_key_features = wrap('wally_descriptor_get_musig_participant_key_features', [T.OpaqueRef, T.Int32, T.Int32, T.DestPtr(T.Int32)]); +export const descriptor_get_musig_participant_key_origin_fingerprint = wrap('wally_descriptor_get_musig_participant_key_origin_fingerprint', [T.OpaqueRef, T.Int32, T.Int32, T.DestPtrSized(T.Bytes, C.BIP32_KEY_FINGERPRINT_LEN)]); +export const descriptor_get_musig_participant_key_origin_path_str_len = wrap('wally_descriptor_get_musig_participant_key_origin_path_str_len', [T.OpaqueRef, T.Int32, T.Int32, T.DestPtr(T.Int32)]); export const descriptor_get_network = wrap('wally_descriptor_get_network', [T.OpaqueRef, T.DestPtr(T.Int32)]); export const descriptor_get_num_keys = wrap('wally_descriptor_get_num_keys', [T.OpaqueRef, T.DestPtr(T.Int32)]); export const descriptor_get_num_paths = wrap('wally_descriptor_get_num_paths', [T.OpaqueRef, T.DestPtr(T.Int32)]); @@ -859,6 +864,7 @@ export const bip32_path_from_str = wrap('bip32_path_from_str', [T.String, T.Int3 export const bip32_path_from_str_n = wrap('bip32_path_from_str_n', [T.String, T.Int32, T.Int32, T.Int32, T.Int32, T.DestPtrVarLen(T.Uint32Array, bip32_path_from_str_n_len, false)]); export const descriptor_get_key_child_path_str = wrap('wally_descriptor_get_key_child_path_str', [T.OpaqueRef, T.Int32, T.DestPtrPtr(T.String)]); export const descriptor_get_key_origin_path_str = wrap('wally_descriptor_get_key_origin_path_str', [T.OpaqueRef, T.Int32, T.DestPtrPtr(T.String)]); +export const descriptor_get_musig_participant_key_origin_path_str = wrap('wally_descriptor_get_musig_participant_key_origin_path_str', [T.OpaqueRef, T.Int32, T.Int32, T.DestPtrPtr(T.String)]); export const descriptor_get_taproot_control_block = wrap('wally_descriptor_get_taproot_control_block', [T.OpaqueRef, T.Int32, T.Int32, T.Int32, T.Int32, T.DestPtrVarLen(T.Bytes, descriptor_get_taproot_control_block_len, false)]); export const descriptor_get_taproot_leaf_script = wrap('wally_descriptor_get_taproot_leaf_script', [T.OpaqueRef, T.Int32, T.Int32, T.Int32, T.Int32, T.DestPtrVarLen(T.Bytes, descriptor_get_taproot_leaf_script_len, false)]); export const descriptor_to_script = wrap('wally_descriptor_to_script', [T.OpaqueRef, T.Int32, T.Int32, T.Int32, T.Int32, T.Int32, T.Int32, T.DestPtrVarLen(T.Bytes, descriptor_to_script_get_maximum_length, true)]); diff --git a/src/wasm_package/src/index.d.ts b/src/wasm_package/src/index.d.ts index 17bb16b60..557b1a4bc 100644 --- a/src/wasm_package/src/index.d.ts +++ b/src/wasm_package/src/index.d.ts @@ -135,6 +135,11 @@ export function descriptor_get_key_child_path_str_len(descriptor: Ref_wally_desc export function descriptor_get_key_features(descriptor: Ref_wally_descriptor, index: number): number; export function descriptor_get_key_origin_fingerprint(descriptor: Ref_wally_descriptor, index: number): Buffer; export function descriptor_get_key_origin_path_str_len(descriptor: Ref_wally_descriptor, index: number): number; +export function descriptor_get_musig_num_participants(descriptor: Ref_wally_descriptor, index: number): number; +export function descriptor_get_musig_participant_key(descriptor: Ref_wally_descriptor, index: number, participant_index: number): string; +export function descriptor_get_musig_participant_key_features(descriptor: Ref_wally_descriptor, index: number, participant_index: number): number; +export function descriptor_get_musig_participant_key_origin_fingerprint(descriptor: Ref_wally_descriptor, index: number, participant_index: number): Buffer; +export function descriptor_get_musig_participant_key_origin_path_str_len(descriptor: Ref_wally_descriptor, index: number, participant_index: number): number; export function descriptor_get_network(descriptor: Ref_wally_descriptor): number; export function descriptor_get_num_keys(descriptor: Ref_wally_descriptor): number; export function descriptor_get_num_paths(descriptor: Ref_wally_descriptor): number; @@ -819,6 +824,7 @@ export function bip32_path_from_str(path_str: string, child_num: number, multi_i export function bip32_path_from_str_n(path_str: string, path_str_len: number, child_num: number, multi_index: number, flags: number): Uint32Array; export function descriptor_get_key_child_path_str(descriptor: Ref_wally_descriptor, index: number): string; export function descriptor_get_key_origin_path_str(descriptor: Ref_wally_descriptor, index: number): string; +export function descriptor_get_musig_participant_key_origin_path_str(descriptor: Ref_wally_descriptor, index: number, participant_index: number): string; export function descriptor_get_taproot_control_block(descriptor: Ref_wally_descriptor, leaf_index: number, multi_index: number, child_num: number, flags: number): Buffer; export function descriptor_get_taproot_leaf_script(descriptor: Ref_wally_descriptor, leaf_index: number, multi_index: number, child_num: number, flags: number): Buffer; export function descriptor_to_script(descriptor: Ref_wally_descriptor, depth: number, index: number, variant: number, multi_index: number, child_num: number, flags: number): Buffer; diff --git a/tools/wasm_exports.sh b/tools/wasm_exports.sh index eeab76692..9b959e444 100644 --- a/tools/wasm_exports.sh +++ b/tools/wasm_exports.sh @@ -100,6 +100,12 @@ EXPORTED_FUNCTIONS="['_malloc','_free','_bip32_key_free' \ ,'_wally_descriptor_get_key_origin_fingerprint' \ ,'_wally_descriptor_get_key_origin_path_str' \ ,'_wally_descriptor_get_key_origin_path_str_len' \ +,'_wally_descriptor_get_musig_num_participants' \ +,'_wally_descriptor_get_musig_participant_key' \ +,'_wally_descriptor_get_musig_participant_key_features' \ +,'_wally_descriptor_get_musig_participant_key_origin_fingerprint' \ +,'_wally_descriptor_get_musig_participant_key_origin_path_str' \ +,'_wally_descriptor_get_musig_participant_key_origin_path_str_len' \ ,'_wally_descriptor_get_network' \ ,'_wally_descriptor_get_num_keys' \ ,'_wally_descriptor_get_num_paths' \ From 2d1a62da23f7b57846be6921ec7c4703b6a3962d Mon Sep 17 00:00:00 2001 From: pythcoiner Date: Tue, 30 Jun 2026 13:47:43 -0300 Subject: [PATCH 7/9] psbt: add taproot (BIP-371) and MuSig2 (BIP-373) support Adds PSBT support for the new descriptor types. BIP-371 taproot: internal key, leaf scripts, merkle root and tap bip32 derivation fields; script-path sighash, signing and descriptor-based taproot population; and the finalizers (p2wsh, p2tr key/script path, multisig). BIP-373 MuSig2: participant pubkey, public-nonce and partial-sig fields with nonce generation, partial signing, aggregation and finalization, plus wally_psbt_populate_musig2_from_descriptor. Includes the PSBT, MuSig2-PSBT, BIP-373 interop and satisfier differential test suites. Co-authored-by: odudex --- include/wally.hpp | 138 ++ include/wally_psbt.h | 503 +++++ src/Makefile.am | 2 + src/ctest/test_descriptor.c | 126 ++ src/data/bip379/gen_golden/Cargo.lock | 250 +++ src/data/bip379/gen_golden/Cargo.toml | 14 + src/data/bip379/gen_golden/src/main.rs | 99 + src/data/bip379/miniscript_vectors.json | 41 + src/data/bip379/satisfier_golden.json | 41 + src/data/psbt.json | 16 + src/descriptor.c | 171 ++ src/descriptor_int.h | 25 + src/psbt.c | 2643 +++++++++++++++++++++-- src/psbt_io.h | 18 +- src/sign.c | 7 +- src/swig_java/swig.i | 39 + src/swig_python/swig.i | 10 + src/test/test_musig.py | 901 ++++++++ src/test/test_musig_interop.py | 553 +++++ src/test/test_psbt.py | 1707 +++++++++++++++ src/test/test_satisfier_diff.py | 263 +++ src/test/util.py | 27 + src/tx_io.h | 7 + src/wasm_package/src/functions.js | 23 + src/wasm_package/src/index.d.ts | 23 + tools/wasm_exports.sh | 23 + 26 files changed, 7540 insertions(+), 130 deletions(-) create mode 100644 src/data/bip379/gen_golden/Cargo.lock create mode 100644 src/data/bip379/gen_golden/Cargo.toml create mode 100644 src/data/bip379/gen_golden/src/main.rs create mode 100644 src/data/bip379/miniscript_vectors.json create mode 100644 src/data/bip379/satisfier_golden.json create mode 100644 src/test/test_musig_interop.py create mode 100644 src/test/test_satisfier_diff.py diff --git a/include/wally.hpp b/include/wally.hpp index bdea15ed1..1fa8db3fd 100644 --- a/include/wally.hpp +++ b/include/wally.hpp @@ -1648,12 +1648,42 @@ inline int psbt_init_alloc(uint32_t version, size_t inputs_allocation_len, size_ return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_input_add_musig2_partial_sig(const INPUT& input, const PARTICIPANT& participant, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, const PARTIAL_SIG& partial_sig) { + int ret = ::wally_psbt_input_add_musig2_partial_sig(detail::get_p(input), participant.data(), participant.size(), agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), partial_sig.data(), partial_sig.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_add_musig2_participant_pubkeys(const INPUT& input, const AGG_PUBKEY& agg_pubkey, const PARTICIPANTS& participants) { + int ret = ::wally_psbt_input_add_musig2_participant_pubkeys(detail::get_p(input), agg_pubkey.data(), agg_pubkey.size(), participants.data(), participants.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_add_musig2_pubnonce(const INPUT& input, const PARTICIPANT& participant, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, const PUBNONCE& pubnonce) { + int ret = ::wally_psbt_input_add_musig2_pubnonce(detail::get_p(input), participant.data(), participant.size(), agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), pubnonce.data(), pubnonce.size()); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_input_add_signature(const INPUT& input, const PUB_KEY& pub_key, const SIG& sig) { int ret = ::wally_psbt_input_add_signature(detail::get_p(input), pub_key.data(), pub_key.size(), sig.data(), sig.size()); return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_input_add_taproot_leaf_script(const INPUT& input, const CONTROL_BLOCK& control_block, const SCRIPT& script) { + int ret = ::wally_psbt_input_add_taproot_leaf_script(detail::get_p(input), control_block.data(), control_block.size(), script.data(), script.size()); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_add_taproot_leaf_signature(const INPUT& input, const PUBKEY_AND_HASH& pubkey_and_hash, const SIG& sig) { + int ret = ::wally_psbt_input_add_taproot_leaf_signature(detail::get_p(input), pubkey_and_hash.data(), pubkey_and_hash.size(), sig.data(), sig.size()); + return detail::check_ret(__FUNCTION__, ret); +} + inline int psbt_input_clear_required_lockheight(struct wally_psbt_input* input) { int ret = ::wally_psbt_input_clear_required_lockheight(input); return detail::check_ret(__FUNCTION__, ret); @@ -1675,6 +1705,24 @@ inline int psbt_input_find_keypath(const INPUT& input, const PUB_KEY& pub_key, s return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_input_find_musig2_partial_sig(const INPUT& input, const PARTICIPANT& participant, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, size_t* written) { + int ret = ::wally_psbt_input_find_musig2_partial_sig(detail::get_p(input), participant.data(), participant.size(), agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_find_musig2_pubkey(const INPUT& input, const AGG_PUBKEY& agg_pubkey, size_t* written) { + int ret = ::wally_psbt_input_find_musig2_pubkey(detail::get_p(input), agg_pubkey.data(), agg_pubkey.size(), written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_find_musig2_pubnonce(const INPUT& input, const PARTICIPANT& participant, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, size_t* written) { + int ret = ::wally_psbt_input_find_musig2_pubnonce(detail::get_p(input), participant.data(), participant.size(), agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), written); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_input_find_signature(const INPUT& input, const PUB_KEY& pub_key, size_t* written) { int ret = ::wally_psbt_input_find_signature(detail::get_p(input), pub_key.data(), pub_key.size(), written); @@ -1687,6 +1735,36 @@ inline int psbt_input_find_unknown(const INPUT& input, const KEY& key, size_t* w return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_input_get_musig2_partial_sig_size(const INPUT& input, size_t* written) { + int ret = ::wally_psbt_input_get_musig2_partial_sig_size(detail::get_p(input), written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_get_musig2_pubnonce_size(const INPUT& input, size_t* written) { + int ret = ::wally_psbt_input_get_musig2_pubnonce_size(detail::get_p(input), written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_get_taproot_keypaths_size(const INPUT& input, size_t* written) { + int ret = ::wally_psbt_input_get_taproot_keypaths_size(detail::get_p(input), written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_get_taproot_leaf_script_size(const INPUT& input, size_t* written) { + int ret = ::wally_psbt_input_get_taproot_leaf_script_size(detail::get_p(input), written); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_input_get_taproot_leaf_signature_size(const INPUT& input, size_t* written) { + int ret = ::wally_psbt_input_get_taproot_leaf_signature_size(detail::get_p(input), written); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_input_is_finalized(const INPUT& input, size_t* written) { int ret = ::wally_psbt_input_is_finalized(detail::get_p(input), written); @@ -1699,6 +1777,12 @@ inline int psbt_input_keypath_add(const INPUT& input, const PUB_KEY& pub_key, co return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_input_populate_taproot_from_descriptor(const PSBT& psbt, size_t index, const DESCRIPTOR& descriptor, uint32_t multi_index, uint32_t child_num, uint32_t flags) { + int ret = ::wally_psbt_input_populate_taproot_from_descriptor(detail::get_p(psbt), index, detail::get_p(descriptor), multi_index, child_num, flags); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_input_set_final_scriptsig(const INPUT& input, const FINAL_SCRIPTSIG& final_scriptsig) { int ret = ::wally_psbt_input_set_final_scriptsig(detail::get_p(input), final_scriptsig.data(), final_scriptsig.size()); @@ -1717,6 +1801,12 @@ inline int psbt_input_set_keypaths(const INPUT& input, const struct wally_map* m return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_input_set_musig2_pubkeys(const INPUT& input, const struct wally_map* map_in) { + int ret = ::wally_psbt_input_set_musig2_pubkeys(detail::get_p(input), map_in); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_input_set_output_index(const INPUT& input, uint32_t index) { int ret = ::wally_psbt_input_set_output_index(detail::get_p(input), index); @@ -1831,6 +1921,30 @@ inline int psbt_is_input_finalized(const PSBT& psbt, size_t index, size_t* writt return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_musig2_add_nonce(const PSBT& psbt, size_t index, const SESSION_SECRAND32& session_secrand32, const SECKEY& seckey, const PUBKEY33& pubkey33, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, const KEYAGG_CACHE& keyagg_cache, uint32_t flags, struct wally_musig_secnonce** secnonce_out) { + int ret = ::wally_psbt_musig2_add_nonce(detail::get_p(psbt), index, session_secrand32.data(), session_secrand32.size(), seckey.data(), seckey.size(), pubkey33.data(), pubkey33.size(), agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), detail::get_p(keyagg_cache), flags, secnonce_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_musig2_finalize_input(const PSBT& psbt, size_t index, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, const KEYAGG_CACHE& keyagg_cache, uint32_t flags) { + int ret = ::wally_psbt_musig2_finalize_input(detail::get_p(psbt), index, agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), detail::get_p(keyagg_cache), flags); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_musig2_sign(const PSBT& psbt, size_t index, const SECNONCE& secnonce, const SECKEY& seckey, const PUBKEY33& pubkey33, const AGG_PUBKEY& agg_pubkey, const LEAF_HASH& leaf_hash, const KEYAGG_CACHE& keyagg_cache, uint32_t flags, struct wally_musig_partial_sig** partial_sig_out) { + int ret = ::wally_psbt_musig2_sign(detail::get_p(psbt), index, detail::get_p(secnonce), seckey.data(), seckey.size(), pubkey33.data(), pubkey33.size(), agg_pubkey.data(), agg_pubkey.size(), leaf_hash.data(), leaf_hash.size(), detail::get_p(keyagg_cache), flags, partial_sig_out); + return detail::check_ret(__FUNCTION__, ret); +} + +template +inline int psbt_output_add_musig2_participant_pubkeys(const OUTPUT& output, const AGG_PUBKEY& agg_pubkey, const PARTICIPANTS& participants) { + int ret = ::wally_psbt_output_add_musig2_participant_pubkeys(detail::get_p(output), agg_pubkey.data(), agg_pubkey.size(), participants.data(), participants.size()); + return detail::check_ret(__FUNCTION__, ret); +} + inline int psbt_output_clear_amount(struct wally_psbt_output* output) { int ret = ::wally_psbt_output_clear_amount(output); return detail::check_ret(__FUNCTION__, ret); @@ -1842,6 +1956,12 @@ inline int psbt_output_find_keypath(const OUTPUT& output, const PUB_KEY& pub_key return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_output_find_musig2_pubkey(const OUTPUT& output, const AGG_PUBKEY& agg_pubkey, size_t* written) { + int ret = ::wally_psbt_output_find_musig2_pubkey(detail::get_p(output), agg_pubkey.data(), agg_pubkey.size(), written); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_output_find_unknown(const OUTPUT& output, const KEY& key, size_t* written) { int ret = ::wally_psbt_output_find_unknown(detail::get_p(output), key.data(), key.size(), written); @@ -1854,6 +1974,12 @@ inline int psbt_output_keypath_add(const OUTPUT& output, const PUB_KEY& pub_key, return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_output_populate_taproot_from_descriptor(const PSBT& psbt, size_t index, const DESCRIPTOR& descriptor, uint32_t multi_index, uint32_t child_num, uint32_t flags) { + int ret = ::wally_psbt_output_populate_taproot_from_descriptor(detail::get_p(psbt), index, detail::get_p(descriptor), multi_index, child_num, flags); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_output_set_amount(const OUTPUT& output, uint64_t amount) { int ret = ::wally_psbt_output_set_amount(detail::get_p(output), amount); @@ -1866,6 +1992,12 @@ inline int psbt_output_set_keypaths(const OUTPUT& output, const struct wally_map return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_output_set_musig2_pubkeys(const OUTPUT& output, const struct wally_map* map_in) { + int ret = ::wally_psbt_output_set_musig2_pubkeys(detail::get_p(output), map_in); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_output_set_redeem_script(const OUTPUT& output, const SCRIPT& script) { int ret = ::wally_psbt_output_set_redeem_script(detail::get_p(output), script.data(), script.size()); @@ -1902,6 +2034,12 @@ inline int psbt_output_taproot_keypath_add(const OUTPUT& output, const PUB_KEY& return detail::check_ret(__FUNCTION__, ret); } +template +inline int psbt_populate_musig2_from_descriptor(const PSBT& psbt, const DESCRIPTOR& descriptor, uint32_t multi_index, uint32_t child_num, uint32_t flags) { + int ret = ::wally_psbt_populate_musig2_from_descriptor(detail::get_p(psbt), detail::get_p(descriptor), multi_index, child_num, flags); + return detail::check_ret(__FUNCTION__, ret); +} + template inline int psbt_remove_input(const PSBT& psbt, uint32_t index) { int ret = ::wally_psbt_remove_input(detail::get_p(psbt), index); diff --git a/include/wally_psbt.h b/include/wally_psbt.h index d4e83281d..25f9e21d0 100644 --- a/include/wally_psbt.h +++ b/include/wally_psbt.h @@ -9,6 +9,15 @@ extern "C" { #endif +/** An opaque type holding a parsed minscript/descriptor expression */ +struct wally_descriptor; + +/* Forward declarations for MuSig2 opaque types used in PSBT functions */ +struct wally_musig_keyagg_cache; +struct wally_musig_secnonce; +struct wally_musig_partial_sig; + + /* PSBT Version number */ #define WALLY_PSBT_VERSION_0 0x0 #define WALLY_PSBT_VERSION_2 0x2 @@ -89,6 +98,9 @@ struct wally_psbt_input { /* Hashes and paths for taproot bip32 derivation path */ struct wally_map taproot_leaf_hashes; struct wally_map taproot_leaf_paths; + struct wally_map musig2_pubkeys; /* BIP-373: agg pubkey -> participant pubkeys */ + struct wally_map musig2_pubnonces; /* BIP-373: (participant||agg[||leaf]) -> pubnonce */ + struct wally_map musig2_partial_sigs; /* BIP-373: (participant||agg[||leaf]) -> partial_sig */ #ifndef WALLY_ABI_NO_ELEMENTS uint64_t issuance_amount; /* Issuance amount, or 0 if not given */ uint64_t inflation_keys; /* Number of reissuance tokens, or 0 if none given */ @@ -116,6 +128,7 @@ struct wally_psbt_output { /* Hashes and paths for taproot bip32 derivation path */ struct wally_map taproot_leaf_hashes; struct wally_map taproot_leaf_paths; + struct wally_map musig2_pubkeys; /* BIP-373: agg pubkey -> participant pubkeys */ #ifndef WALLY_ABI_NO_ELEMENTS uint32_t blinder_index; /* Index of the input whose owner should blind this output */ uint32_t has_blinder_index; @@ -372,6 +385,221 @@ WALLY_CORE_API int wally_psbt_input_set_taproot_internal_key( const unsigned char *pub_key, size_t pub_key_len); +/** + * Add a taproot leaf script (TAP_LEAF_SCRIPT) to a PSBT input. + * + * :param input: The input to update. + * :param control_block: The BIP-341 control block for the leaf. + * :param control_block_len: Length of ``control_block`` in bytes. + * :param script: The leaf script bytes, or NULL for an empty script. + * :param script_len: Length of ``script`` in bytes. + */ +WALLY_CORE_API int wally_psbt_input_add_taproot_leaf_script( + struct wally_psbt_input *input, + const unsigned char *control_block, + size_t control_block_len, + const unsigned char *script, + size_t script_len); + +/** + * Get the number of taproot leaf scripts in a PSBT input. + * + * :param input: The input to query. + * :param written: Destination for the count. + */ +WALLY_CORE_API int wally_psbt_input_get_taproot_leaf_script_size( + const struct wally_psbt_input *input, + size_t *written); + +/** + * Add a taproot script-path signature (TAP_SCRIPT_SIG) to a PSBT input. + * + * :param input: The input to update. + * :param pubkey_and_hash: Concatenation of x-only pubkey (32 bytes) and leaf hash (32 bytes). + * :param pubkey_and_hash_len: Must be 64. + * :param sig: The 64 or 65-byte Schnorr signature. + * :param sig_len: Length of ``sig``. + */ +WALLY_CORE_API int wally_psbt_input_add_taproot_leaf_signature( + struct wally_psbt_input *input, + const unsigned char *pubkey_and_hash, + size_t pubkey_and_hash_len, + const unsigned char *sig, + size_t sig_len); + +/** + * Get the number of taproot script-path signatures in a PSBT input. + * + * :param input: The input to query. + * :param written: Destination for the count. + */ +WALLY_CORE_API int wally_psbt_input_get_taproot_leaf_signature_size( + const struct wally_psbt_input *input, + size_t *written); + +/** + * Add or replace a musig2 participant pubkeys entry in an input. + * + * :param input: The input to update. + * :param agg_pubkey: The 33-byte compressed aggregate public key (map key). + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param participants: Concatenated 33-byte compressed participant public keys. + * :param participants_len: Length of ``participants``. Must be a multiple of + *| `EC_PUBLIC_KEY_LEN` and at least ``2 * EC_PUBLIC_KEY_LEN``. + */ +WALLY_CORE_API int wally_psbt_input_add_musig2_participant_pubkeys( + struct wally_psbt_input *input, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *participants, + size_t participants_len); + +/** + * Find a musig2 participant pubkeys entry in an input by aggregate pubkey. + * + * :param input: The input to search. + * :param agg_pubkey: The 33-byte compressed aggregate public key to look up. + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param written: On success, set to zero if not found, otherwise the 1-based index. + */ +WALLY_CORE_API int wally_psbt_input_find_musig2_pubkey( + const struct wally_psbt_input *input, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + size_t *written); + +/** + * Set the musig2 participant pubkeys map in an input. + * + * :param input: The input to update. + * :param map_in: Map of agg pubkey to participant pubkeys entries. + */ +WALLY_CORE_API int wally_psbt_input_set_musig2_pubkeys( + struct wally_psbt_input *input, + const struct wally_map *map_in); + +/** + * Add a MuSig2 pubnonce to an input. + * + * :param input: The input to update. + * :param participant: The participant's compressed public key (33 bytes). + * :param participant_len: Length of ``participant``. Must be `EC_PUBLIC_KEY_LEN`. + * :param agg_pubkey: The aggregate public key (33 bytes). + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param leaf_hash: The tapscript leaf hash (32 bytes) or NULL for key-path. + * :param leaf_hash_len: Length of ``leaf_hash``. Must be `SHA256_LEN` or 0. + * :param pubnonce: The 66-byte serialized pubnonce. + * :param pubnonce_len: Length of ``pubnonce``. Must be `WALLY_MUSIG_PUBNONCE_LEN`. + */ +WALLY_CORE_API int wally_psbt_input_add_musig2_pubnonce( + struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const unsigned char *pubnonce, + size_t pubnonce_len); + +/** + * Find a MuSig2 pubnonce in an input. + * + * :param input: The input to search in. + * :param participant: The participant's compressed public key (33 bytes). + * :param participant_len: Length of ``participant``. Must be `EC_PUBLIC_KEY_LEN`. + * :param agg_pubkey: The aggregate public key (33 bytes). + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param leaf_hash: The tapscript leaf hash (32 bytes) or NULL for key-path. + * :param leaf_hash_len: Length of ``leaf_hash``. Must be `SHA256_LEN` or 0. + * :param written: On success, set to zero if not found, otherwise the 1-based index. + */ +WALLY_CORE_API int wally_psbt_input_find_musig2_pubnonce( + const struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + size_t *written); + +/** + * Get the number of MuSig2 pubnonces in an input. + * + * :param input: The input to query. + * :param written: On success, set to the number of pubnonce entries. + */ +WALLY_CORE_API int wally_psbt_input_get_musig2_pubnonce_size( + const struct wally_psbt_input *input, + size_t *written); + +/** + * Get the number of TAP_BIP32_DERIVATION entries in a PSBT input. + * + * :param input: The input to query. + * :param written: Destination for the count. + */ +WALLY_CORE_API int wally_psbt_input_get_taproot_keypaths_size( + const struct wally_psbt_input *input, + size_t *written); + +/** + * Add a MuSig2 partial signature to an input. + * + * :param input: The input to update. + * :param participant: The participant's compressed public key (33 bytes). + * :param participant_len: Length of ``participant``. Must be `EC_PUBLIC_KEY_LEN`. + * :param agg_pubkey: The aggregate public key (33 bytes). + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param leaf_hash: The tapscript leaf hash (32 bytes) or NULL for key-path. + * :param leaf_hash_len: Length of ``leaf_hash``. Must be `SHA256_LEN` or 0. + * :param partial_sig: The 32-byte partial signature. + * :param partial_sig_len: Length of ``partial_sig``. Must be `WALLY_MUSIG_PARTIAL_SIG_LEN`. + */ +WALLY_CORE_API int wally_psbt_input_add_musig2_partial_sig( + struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const unsigned char *partial_sig, + size_t partial_sig_len); + +/** + * Find a MuSig2 partial signature in an input. + * + * :param input: The input to search in. + * :param participant: The participant's compressed public key (33 bytes). + * :param participant_len: Length of ``participant``. Must be `EC_PUBLIC_KEY_LEN`. + * :param agg_pubkey: The aggregate public key (33 bytes). + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param leaf_hash: The tapscript leaf hash (32 bytes) or NULL for key-path. + * :param leaf_hash_len: Length of ``leaf_hash``. Must be `SHA256_LEN` or 0. + * :param written: On success, set to zero if not found, otherwise the 1-based index. + */ +WALLY_CORE_API int wally_psbt_input_find_musig2_partial_sig( + const struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + size_t *written); + +/** + * Get the number of MuSig2 partial signatures in an input. + * + * :param input: The input to query. + * :param written: On success, set to the number of partial signature entries. + */ +WALLY_CORE_API int wally_psbt_input_get_musig2_partial_sig_size( + const struct wally_psbt_input *input, + size_t *written); + /** * Find a partial signature matching a pubkey in an input. * @@ -474,6 +702,51 @@ WALLY_CORE_API int wally_psbt_input_set_required_lockheight( WALLY_CORE_API int wally_psbt_input_clear_required_lockheight( struct wally_psbt_input *input); +/** + * Populate taproot PSBT input fields from a tr() descriptor. + * + * Sets TAP_INTERNAL_KEY, TAP_LEAF_SCRIPT entries, TAP_BIP32_DERIVATION + * entries (for the internal key and each taptree key), and TAP_MERKLE_ROOT + * on the given input. Does not sign. PSETs must be populated from Elements + * (``eltr()``) descriptors, and PSBTs from Bitcoin descriptors. + * + * :param psbt: The PSBT to update. + * :param index: The input index to populate. + * :param descriptor: A parsed tr() descriptor. + * :param multi_index: Multi-path index for descriptor derivation. + * :param child_num: BIP-32 child derivation index for variable keys. + * :param flags: Must be zero. + */ +WALLY_CORE_API int wally_psbt_input_populate_taproot_from_descriptor( + struct wally_psbt *psbt, + size_t index, + const struct wally_descriptor *descriptor, + uint32_t multi_index, + uint32_t child_num, + uint32_t flags); + +/** + * Populate taproot PSBT output fields from a tr() descriptor. + * + * Sets TAP_INTERNAL_KEY and TAP_BIP32_DERIVATION entries (for the internal + * key and each taptree key) on the given output. PSETs must be populated + * from Elements (``eltr()``) descriptors, and PSBTs from Bitcoin descriptors. + * + * :param psbt: The PSBT to update. + * :param index: The output index to populate. + * :param descriptor: A parsed tr() descriptor. + * :param multi_index: Multi-path index for descriptor derivation. + * :param child_num: BIP-32 child derivation index for variable keys. + * :param flags: Must be zero. + */ +WALLY_CORE_API int wally_psbt_output_populate_taproot_from_descriptor( + struct wally_psbt *psbt, + size_t index, + const struct wally_descriptor *descriptor, + uint32_t multi_index, + uint32_t child_num, + uint32_t flags); + #ifndef WALLY_ABI_NO_ELEMENTS /** * Set the unblinded amount in an input. @@ -1451,6 +1724,46 @@ WALLY_CORE_API int wally_psbt_output_set_taproot_internal_key( const unsigned char *pub_key, size_t pub_key_len); +/** + * Add or replace a musig2 participant pubkeys entry in an output. + * + * :param output: The output to update. + * :param agg_pubkey: The 33-byte compressed aggregate public key (map key). + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param participants: Concatenated 33-byte compressed participant public keys. + * :param participants_len: Length of ``participants``. Must be a multiple of + *| `EC_PUBLIC_KEY_LEN` and at least ``2 * EC_PUBLIC_KEY_LEN``. + */ +WALLY_CORE_API int wally_psbt_output_add_musig2_participant_pubkeys( + struct wally_psbt_output *output, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *participants, + size_t participants_len); + +/** + * Find a musig2 participant pubkeys entry in an output by aggregate pubkey. + * + * :param output: The output to search. + * :param agg_pubkey: The 33-byte compressed aggregate public key to look up. + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be `EC_PUBLIC_KEY_LEN`. + * :param written: On success, set to zero if not found, otherwise the 1-based index. + */ +WALLY_CORE_API int wally_psbt_output_find_musig2_pubkey( + const struct wally_psbt_output *output, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + size_t *written); + +/** + * Set the musig2 participant pubkeys map in an output. + * + * :param output: The output to update. + * :param map_in: Map of agg pubkey to participant pubkeys entries. + */ +WALLY_CORE_API int wally_psbt_output_set_musig2_pubkeys( + struct wally_psbt_output *output, + const struct wally_map *map_in); #ifndef WALLY_ABI_NO_ELEMENTS /** @@ -2675,6 +2988,11 @@ WALLY_CORE_API int wally_psbt_sign( * .. note:: Inputs are signed using the sighash stored for the input, *| or SIGHASH_ALL/SIGHASH_DEFAULT if not present. The caller should ensure *| that each input sighash is acceptable before signing. + * + * .. note:: Taproot inputs are signed for the script path with each key + *| derived from ``hdkey`` that is in a leaf whose script is present, and + *| for the key path if ``hdkey`` derives the internal key, which the + *| merkle root of the input (if any) tweaks to the output key being spent. */ WALLY_CORE_API int wally_psbt_sign_bip32( struct wally_psbt *psbt, @@ -2696,6 +3014,10 @@ WALLY_CORE_API int wally_psbt_sign_bip32( * .. note:: Inputs are signed using the sighash stored for the input, *| or SIGHASH_ALL/SIGHASH_DEFAULT if not present. The caller should ensure *| that the sighash is acceptable before signing. + * + * .. note:: Taproot inputs are signed for the key path. ``hdkey`` must be + *| the internal key, which the merkle root of the input (if any) tweaks + *| to the output key being spent. */ WALLY_CORE_API int wally_psbt_sign_input_bip32( struct wally_psbt *psbt, @@ -2758,6 +3080,187 @@ WALLY_CORE_API int wally_psbt_is_elements( const struct wally_psbt *psbt, size_t *written); +/** + * Populate MuSig2 PSBT fields from a musig() descriptor. + * + * For each musig() key expression in the descriptor, this function populates: + * + * - `PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS`: aggregate pubkey to participant pubkeys map + * - `PSBT_IN_TAP_BIP32_DERIVATION`: for each participant (x-only pubkey + derivation path) + * - `PSBT_IN_TAP_INTERNAL_KEY`: x-only aggregate pubkey (untweaked) + * - `PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS`: for each matching output + * + * Only inputs whose witness UTXO scriptPubKey matches the descriptor's + * scriptPubKey for ``multi_index`` and ``child_num``, and outputs whose script + * matches it, are populated. Other inputs and outputs, including inputs with no witness + * UTXO, are left untouched. + * + * .. note:: BIP-390 aggregate-then-derive expressions, i.e. a ``musig()`` + *| key with a trailing derivation path, are rejected with `WALLY_EINVAL`: + *| signing them requires BIP-328 tweaks that are not yet implemented. + *| Give the derivation paths to the participant keys instead, so that the + *| aggregate key is itself the taproot internal key. + * + * :param psbt: The PSBT to populate. + * :param descriptor: The parsed descriptor containing musig() expressions. + * :param multi_index: Multi-path index for descriptor derivation. + * :param child_num: The BIP32 child number for ranged descriptors. + * :param flags: For future use, pass 0. + */ +WALLY_CORE_API int wally_psbt_populate_musig2_from_descriptor( + struct wally_psbt *psbt, + const struct wally_descriptor *descriptor, + uint32_t multi_index, + uint32_t child_num, + uint32_t flags); + +/** + * Generate a MuSig2 nonce for a PSBT input and store it in the PSBT. + * + * Computes the input sighash (when available) and uses it as the message in + * nonce generation (per BIP-327). The resulting public nonce is stored in the + * PSBT under the composite key ``participant || agg_pubkey``. + * The secret nonce is returned to the caller, who MUST store it securely and + * supply it during Round 2 partial signing. The secret nonce MUST NOT be used + * more than once. + * + * ``pubkey33`` must be present in the input's + * `PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS` entry for ``agg_pubkey``. + * + * Returns WALLY_ERROR if a pubnonce already exists for this participant/key + * combination (nonce reuse prevention). + * + * :param psbt: The PSBT to generate a nonce for. + * :param index: The zero-based index of the input to generate a nonce for. + * :param session_secrand32: 32 bytes of cryptographically secure random data. + *| This value MUST NOT be reused across signing sessions. + * :param session_secrand_len: Length of ``session_secrand32``. Must be 32. + * :param seckey: The signer's 32-byte private key (optional, improves security). + * :param seckey_len: Length of ``seckey``. Must be ``EC_PRIVATE_KEY_LEN`` or 0. + * :param pubkey33: The signer's 33-byte compressed public key (participant key). + * :param pubkey33_len: Length of ``pubkey33``. Must be ``EC_PUBLIC_KEY_LEN``. + * :param agg_pubkey: The 33-byte aggregate public key for this musig() group. + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be ``EC_PUBLIC_KEY_LEN``. + * :param leaf_hash: Must be NULL: only key-path spends are currently supported + *| (script-path MuSig2 signing is not yet implemented). + * :param leaf_hash_len: Length of ``leaf_hash``. Must be 0. + * :param keyagg_cache: Optional untweaked keyagg cache of the participant keys, + *| from `wally_musig_pubkey_agg` or `wally_musig_pubkeys_derive_then_agg`. + * :param flags: For future use, pass 0. + * :param secnonce_out: Destination for the secret nonce. The caller owns this + *| and must free it with `wally_musig_secnonce_free`. MUST NOT be reused. + */ +WALLY_CORE_API int wally_psbt_musig2_add_nonce( + struct wally_psbt *psbt, + size_t index, + const unsigned char *session_secrand32, + size_t session_secrand_len, + const unsigned char *seckey, + size_t seckey_len, + const unsigned char *pubkey33, + size_t pubkey33_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + uint32_t flags, + struct wally_musig_secnonce **secnonce_out); + +/** + * Produce a MuSig2 partial signature for a PSBT input (Round 2). + * + * Collects all public nonces for the given musig() group from the PSBT, + * aggregates them, processes the signing session with the input sighash, + * and produces a partial signature. The partial signature is stored in the + * PSBT under the composite key ``participant || agg_pubkey``. + * The secret nonce is zeroed after use (nonce reuse prevention). It is only + * used once all other checks and allocations have succeeded, so signing can + * be retried with it after any error except a failure to sign. + * + * ``pubkey33`` must be present in the input's + * `PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS` entry for ``agg_pubkey``, and the + * keys listed there must aggregate to ``agg_pubkey``. The BIP-341 + * taproot output tweak is applied internally to a copy of ``keyagg_cache`` + * during signing. + * + * Returns ``WALLY_EINVAL`` if the tweaked key is not the output key being + * spent, i.e. unless ``agg_pubkey`` is the internal key of the input and + * the merkle root of the input (if any) is present and correct. + * Returns ``WALLY_ERROR`` if any participant's pubnonce is missing. + * + * :param psbt: The PSBT to sign. + * :param index: The zero-based index of the input to sign. + * :param secnonce: The secret nonce from Round 1. Zeroed after use. + * :param seckey: The signer's 32-byte private key. + * :param seckey_len: Length of ``seckey``. Must be ``EC_PRIVATE_KEY_LEN``. + * :param pubkey33: The signer's 33-byte compressed public key (participant key). + * :param pubkey33_len: Length of ``pubkey33``. Must be ``EC_PUBLIC_KEY_LEN``. + * :param agg_pubkey: The 33-byte aggregate public key for this musig() group. + * :param agg_pubkey_len: Length of ``agg_pubkey``. Must be ``EC_PUBLIC_KEY_LEN``. + * :param leaf_hash: Must be NULL: only key-path spends are currently supported + *| (script-path MuSig2 signing is not yet implemented). + * :param leaf_hash_len: Length of ``leaf_hash``. Must be 0. + * :param keyagg_cache: The untweaked keyagg cache of the participant keys, + *| from `wally_musig_pubkey_agg` or `wally_musig_pubkeys_derive_then_agg`. + *| Do not apply any tweak to it: the BIP-341 taproot tweak is applied + *| internally, and a pre-tweaked cache produces invalid signatures. + * :param flags: For future use, pass 0. + * :param partial_sig_out: Optional destination for the partial signature. The caller + *| owns this and must free it with `wally_musig_partial_sig_free`. Pass NULL + *| if not needed (the sig is always stored in the PSBT). + */ +WALLY_CORE_API int wally_psbt_musig2_sign( + struct wally_psbt *psbt, + size_t index, + struct wally_musig_secnonce *secnonce, + const unsigned char *seckey, + size_t seckey_len, + const unsigned char *pubkey33, + size_t pubkey33_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + uint32_t flags, + struct wally_musig_partial_sig **partial_sig_out); + +/** + * Aggregate MuSig2 partial signatures for one input and store the result + * as PSBT_IN_TAP_KEY_SIG. + * + * MUST be called before wally_psbt_finalize_input(), and only after all + * participants have added their partial signatures via wally_psbt_musig2_sign(). + * + * Each partial signature is verified before aggregation; if any fails to + * verify, an error is returned and the input's pubnonces and partial + * signatures are left in place. The aggregate key and its participants + * are checked as for `wally_psbt_musig2_sign`. + * + * :param psbt: The PSBT containing the input. + * :param index: The input index. + * :param agg_pubkey: 33-byte compressed aggregate public key. + * :param agg_pubkey_len: Must be EC_PUBLIC_KEY_LEN (33). + * :param leaf_hash: Must be NULL: only key-path spends are currently supported + *| (script-path MuSig2 signing is not yet implemented). + * :param leaf_hash_len: Length of ``leaf_hash``. Must be 0. + * :param keyagg_cache: The untweaked keyagg cache of the participant keys, + *| from `wally_musig_pubkey_agg` or `wally_musig_pubkeys_derive_then_agg`. + *| Do not apply any tweak to it: the BIP-341 taproot tweak is applied + *| internally, and a pre-tweaked cache produces invalid signatures. + * :param flags: Must be 0. + */ +WALLY_CORE_API int wally_psbt_musig2_finalize_input( + struct wally_psbt *psbt, + size_t index, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const struct wally_musig_keyagg_cache *keyagg_cache, + uint32_t flags); + #ifdef __cplusplus } #endif diff --git a/src/Makefile.am b/src/Makefile.am index d617ceda7..1faece57b 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -380,8 +380,10 @@ check-libwallycore: $(PYTHON_TEST_DEPS) $(AM_V_at)$(PYTHON_TEST) test/test_mnemonic.py $(AM_V_at)$(PYTHON_TEST) test/test_musig.py $(AM_V_at)$(PYTHON_TEST) test/test_musig_vectors.py + $(AM_V_at)$(PYTHON_TEST) test/test_musig_interop.py $(AM_V_at)$(PYTHON_TEST) test/test_psbt.py $(AM_V_at)$(PYTHON_TEST) test/test_pbkdf2.py + $(AM_V_at)$(PYTHON_TEST) test/test_satisfier_diff.py $(AM_V_at)$(PYTHON_TEST) test/test_script.py $(AM_V_at)$(PYTHON_TEST) test/test_scrypt.py $(AM_V_at)$(PYTHON_TEST) test/test_sign.py diff --git a/src/ctest/test_descriptor.c b/src/ctest/test_descriptor.c index 4a2da51c8..154b70eb3 100644 --- a/src/ctest/test_descriptor.c +++ b/src/ctest/test_descriptor.c @@ -4463,6 +4463,127 @@ static bool check_sanity(void) return tests_ok; } +static bool test_psbt_taproot_scriptpath(void) +{ + static const unsigned char prev_txid[WALLY_TXHASH_LEN] = { + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa + }; + static const unsigned char op_return[] = { 0x6a }; /* OP_RETURN for dummy spend output */ + struct wally_descriptor *desc = NULL; + struct wally_tx *tx = NULL; + struct wally_tx_input *txin = NULL; + struct wally_tx_output *utxo_out = NULL, *spend_out = NULL; + struct wally_psbt *psbt = NULL, *psbt_v2 = NULL; + unsigned char script[64], priv_key[EC_PRIVATE_KEY_LEN]; + size_t script_len = 0; + int ret; + bool ok = true; + + /* Parse tr(x_only,pk(key_1)) descriptor */ + ret = wally_descriptor_parse("tr(x_only,pk(key_1))", &g_vars[VARS_STD], + WALLY_NETWORK_BITCOIN_MAINNET, 0, &desc); + if (!check_ret("psbt: parse", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Get P2TR output script (OP_1 + push32 + tweaked_output_key = 34 bytes) */ + ret = wally_descriptor_to_script(desc, 0, 0, 0, 0, 0, 0, script, sizeof(script), &script_len); + if (!check_ret("psbt: to_script", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Build spending transaction with one taproot input and a dummy output */ + ret = wally_tx_input_init_alloc(prev_txid, WALLY_TXHASH_LEN, 0, 0xffffffff, + NULL, 0, NULL, &txin); + if (!check_ret("psbt: tx_input_init", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + ret = wally_tx_output_init_alloc(0, op_return, sizeof(op_return), &spend_out); + if (!check_ret("psbt: tx_output_init", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + ret = wally_tx_init_alloc(2, 0, 1, 1, &tx); + if (!check_ret("psbt: tx_init", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + ret = wally_tx_add_input(tx, txin); + if (!check_ret("psbt: tx_add_input", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + ret = wally_tx_add_output(tx, spend_out); + if (!check_ret("psbt: tx_add_output", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Create PSBT v0 with properly initialized inputs via init_alloc + set_global_tx */ + ret = wally_psbt_init_alloc(WALLY_PSBT_VERSION_0, 0, 0, 0, 0, &psbt); + if (!check_ret("psbt: init_alloc", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + ret = wally_psbt_set_global_tx(psbt, tx); + if (!check_ret("psbt: set_global_tx", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Set witness_utxo: the previous output being spent */ + ret = wally_tx_output_init_alloc(100000000, script, script_len, &utxo_out); + if (!check_ret("psbt: utxo_out init", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + ret = wally_psbt_input_set_witness_utxo(&psbt->inputs[0], utxo_out); + if (!check_ret("psbt: set_witness_utxo", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Populate taproot PSBT input fields (internal key, leaf scripts, keypaths) */ + ret = wally_psbt_input_populate_taproot_from_descriptor(psbt, 0, desc, 0, 0, 0); + if (!check_ret("psbt: set_taproot_from_descriptor", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Decode raw private key for key_1 from testnet WIF */ + ret = wally_wif_to_bytes("cNha6ams8o6qokphL3XfcUTRs7ggweD3SWn7YXLtB3Rrm3QDNxD4", + WALLY_ADDRESS_VERSION_WIF_TESTNET, WALLY_WIF_FLAG_COMPRESSED, + priv_key, sizeof(priv_key)); + if (!check_ret("psbt: wif_to_bytes", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Script-path signing a v2 PSBT updates its modifiable flags, with + * SIGHASH_DEFAULT covering the same as SIGHASH_ALL (BIP-370) */ + ret = wally_psbt_clone_alloc(psbt, 0, &psbt_v2); + if (ret == WALLY_OK) + ret = wally_psbt_set_version(psbt_v2, 0, WALLY_PSBT_VERSION_2); + if (ret == WALLY_OK) + ret = wally_psbt_sign(psbt_v2, priv_key, sizeof(priv_key), 0); + if (!check_ret("psbt: sign v2", ret, WALLY_OK)) { ok = false; goto done_psbt; } + if (!psbt_v2->inputs[0].taproot_leaf_signatures.num_items || + psbt_v2->tx_modifiable_flags) { + printf("[psbt] v2 script-path signing left flags 0x%x\n", psbt_v2->tx_modifiable_flags); + ok = false; + goto done_psbt; + } + + /* Sign the script-path spend */ + ret = wally_psbt_sign(psbt, priv_key, sizeof(priv_key), 0); + if (!check_ret("psbt: sign", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Assert TAP_SCRIPT_SIG is present and non-empty */ + if (psbt->inputs[0].taproot_leaf_signatures.num_items == 0) { + printf("[psbt] no TAP_SCRIPT_SIG after signing\n"); + ok = false; + goto done_psbt; + } + + /* Finalize the PSBT input */ + ret = wally_psbt_finalize(psbt, 0); + if (!check_ret("psbt: finalize", ret, WALLY_OK)) { ok = false; goto done_psbt; } + + /* Assert final witness contains [sig, leaf_script, control_block] (3 items) */ + if (!psbt->inputs[0].final_witness) { + printf("[psbt] no final_witness after finalization\n"); + ok = false; + } else if (psbt->inputs[0].final_witness->num_items != 3) { + printf("[psbt] expected 3 witness items, got %zu\n", + psbt->inputs[0].final_witness->num_items); + ok = false; + } + +done_psbt: + wally_descriptor_free(desc); + wally_tx_free(tx); + wally_tx_input_free(txin); + wally_tx_output_free(utxo_out); + wally_tx_output_free(spend_out); + wally_psbt_free(psbt); + wally_psbt_free(psbt_v2); + memset(priv_key, 0, sizeof(priv_key)); + return ok; +} + int main(void) { bool tests_ok = true; @@ -4509,6 +4630,11 @@ int main(void) tests_ok = false; } + if (!test_psbt_taproot_scriptpath()) { + printf("[test_psbt_taproot_scriptpath] failed!\n"); + tests_ok = false; + } + wally_cleanup(0); return tests_ok ? 0 : 1; } diff --git a/src/data/bip379/gen_golden/Cargo.lock b/src/data/bip379/gen_golden/Cargo.lock new file mode 100644 index 000000000..d7fc9c02f --- /dev/null +++ b/src/data/bip379/gen_golden/Cargo.lock @@ -0,0 +1,250 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "base58ck" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c8d66485a3a2ea485c1913c4572ce0256067a5377ac8c75c4960e1cda98605f" +dependencies = [ + "bitcoin-internals", + "bitcoin_hashes", +] + +[[package]] +name = "bech32" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" + +[[package]] +name = "bitcoin" +version = "0.32.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e499f9fc0407f50fe98af744ab44fa67d409f76b6772e1689ec8485eb0c0f66" +dependencies = [ + "base58ck", + "bech32", + "bitcoin-internals", + "bitcoin-io", + "bitcoin-units", + "bitcoin_hashes", + "hex-conservative 0.2.2", + "hex_lit", + "secp256k1", +] + +[[package]] +name = "bitcoin-internals" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30bdbe14aa07b06e6cfeffc529a1f099e5fbe249524f8125358604df99a4bed2" + +[[package]] +name = "bitcoin-io" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dee39a0ee5b4095224a0cfc6bf4cc1baf0f9624b96b367e53b66d974e51d953" + +[[package]] +name = "bitcoin-units" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346568ebaab2918487cea76dd55dae13c27bb618cdb737c952e69eb2017c4118" +dependencies = [ + "bitcoin-internals", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b" +dependencies = [ + "bitcoin-io", + "hex-conservative 0.2.2", +] + +[[package]] +name = "cc" +version = "1.2.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "gen_golden" +version = "0.1.0" +dependencies = [ + "bitcoin", + "miniscript", + "serde", + "serde_json", +] + +[[package]] +name = "hex-conservative" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "hex-conservative" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366fa3443ac84474447710ec17bb00b05dfbd096137817981e86f992f21a2793" + +[[package]] +name = "hex_lit" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3011d1213f159867b13cfd6ac92d2cd5f1345762c63be3554e84092d85a50bbd" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "miniscript" +version = "13.0.0" +dependencies = [ + "bech32", + "bitcoin", + "hex-conservative 1.0.1", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "secp256k1" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" +dependencies = [ + "bitcoin_hashes", + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/src/data/bip379/gen_golden/Cargo.toml b/src/data/bip379/gen_golden/Cargo.toml new file mode 100644 index 000000000..108ab2df4 --- /dev/null +++ b/src/data/bip379/gen_golden/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "gen_golden" +version = "0.1.0" +edition = "2021" + +[[bin]] +name = "gen_golden" +path = "src/main.rs" + +[dependencies] +miniscript = { path = "../../../../../rust-miniscript", features = ["std"] } +bitcoin = { version = "0.32.6", default-features = false, features = ["std"] } +serde_json = "1.0" +serde = { version = "1.0", features = ["derive"] } diff --git a/src/data/bip379/gen_golden/src/main.rs b/src/data/bip379/gen_golden/src/main.rs new file mode 100644 index 000000000..028560aa5 --- /dev/null +++ b/src/data/bip379/gen_golden/src/main.rs @@ -0,0 +1,99 @@ +use std::collections::BTreeMap; + +use bitcoin::hashes::{ripemd160, sha256, Hash}; +use bitcoin::hex::DisplayHex; +use miniscript::miniscript::satisfy::{Preimage32, Satisfier}; +use miniscript::{Miniscript, Segwitv0}; + +// SHA256([0x12;32]) and RIPEMD160([0x78;32]) - must match test_satisfier_diff.py +const SHA256_PRE: [u8; 32] = [0x12u8; 32]; +const RIPEMD160_PRE: [u8; 32] = [0x78u8; 32]; +const SHA256_H: &str = "b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94"; +const RIPEMD_H: &str = "6646adac9fb158a6df66130746d48a0e7f9db390"; + +struct CorpusSatisfier { + expected_sha256: sha256::Hash, + expected_ripemd160: ripemd160::Hash, +} + +impl CorpusSatisfier { + fn new() -> Self { + Self { + expected_sha256: sha256::Hash::hash(&SHA256_PRE), + expected_ripemd160: ripemd160::Hash::hash(&RIPEMD160_PRE), + } + } +} + +impl Satisfier for CorpusSatisfier { + fn lookup_sha256(&self, h: &sha256::Hash) -> Option { + if h == &self.expected_sha256 { + Some(SHA256_PRE) + } else { + None + } + } + + fn lookup_ripemd160(&self, h: &ripemd160::Hash) -> Option { + if h == &self.expected_ripemd160 { + Some(RIPEMD160_PRE) + } else { + None + } + } + // lookup_hash256, lookup_hash160, check_after, check_older all return None/false + // (defaults) - hash256/hash160 can't be satisfied with our preimages; we don't + // model timelocks so golden data stays stable regardless of tx fields. +} + +fn sub_h(ms: &str) -> String { + let ms = ms.replace("hash256(H)", &format!("hash256({})", SHA256_H)); + let ms = ms.replace("sha256(H)", &format!("sha256({})", SHA256_H)); + let ms = ms.replace("hash160(H)", &format!("hash160({})", RIPEMD_H)); + ms.replace("ripemd160(H)", &format!("ripemd160({})", RIPEMD_H)) +} + +fn main() { + let manifest_dir = env!("CARGO_MANIFEST_DIR"); + let vectors_path = format!("{}/../miniscript_vectors.json", manifest_dir); + let golden_path = format!("{}/../satisfier_golden.json", manifest_dir); + + let vectors_data = std::fs::read_to_string(&vectors_path) + .unwrap_or_else(|e| panic!("failed to read {}: {}", vectors_path, e)); + let vectors: serde_json::Value = + serde_json::from_str(&vectors_data).expect("failed to parse miniscript_vectors.json"); + + let satisfier = CorpusSatisfier::new(); + let mut golden = BTreeMap::>::new(); + + let valid_cases = vectors["valid_cases"] + .as_array() + .expect("valid_cases not array"); + + for tc in valid_cases { + let ms_raw = tc["miniscript"].as_str().expect("miniscript not string"); + let substituted = sub_h(ms_raw); + + let ms = match Miniscript::::from_str_insane(&substituted) { + Ok(m) => m, + Err(_) => continue, + }; + + let stack = match ms.satisfy_malleable(&satisfier) { + Ok(s) => s, + Err(_) => continue, + }; + + let script_hex = format!("{:x}", ms.encode()); + let mut witness: Vec = stack.iter().map(|item| item.to_lower_hex_string()).collect(); + witness.push(script_hex); + + golden.insert(substituted, witness); + } + + let out = serde_json::to_string_pretty(&golden).expect("failed to serialize golden"); + std::fs::write(&golden_path, out) + .unwrap_or_else(|e| panic!("failed to write {}: {}", golden_path, e)); + + println!("wrote {} golden entries to {}", golden.len(), golden_path); +} diff --git a/src/data/bip379/miniscript_vectors.json b/src/data/bip379/miniscript_vectors.json new file mode 100644 index 000000000..e7449d43c --- /dev/null +++ b/src/data/bip379/miniscript_vectors.json @@ -0,0 +1,41 @@ +{ + "source": "rust-miniscript bitcoind-tests/tests/data/random_ms.txt", + "commit": "1834bc0635278b0fcdb6b6b2ebe3a7fef2b8154e", + "note": "H is a placeholder substituted by the test: sha256(H)/hash256(H) use a 32-byte hash; ripemd160(H)/hash160(H) use a 20-byte hash", + "valid_cases": [ + {"miniscript": "and_b(lltvln:after(1231488000),s:pk(03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a))", "comment": "random_ms.txt line 1"}, + {"miniscript": "uuj:and_v(v:multi(2,03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a,025601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc),after(1231488000))", "comment": "random_ms.txt line 2"}, + {"miniscript": "or_b(un:multi(2,03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729,024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),al:older(16))", "comment": "random_ms.txt line 3"}, + {"miniscript": "j:and_v(vdv:after(1567547623),older(16))", "comment": "random_ms.txt line 4"}, + {"miniscript": "t:and_v(vu:hash256(H),v:sha256(H))", "comment": "random_ms.txt line 5"}, + {"miniscript": "t:andor(multi(3,02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e,03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556,02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),v:older(4194305),v:sha256(H))", "comment": "random_ms.txt line 6"}, + {"miniscript": "or_d(multi(1,02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9),or_b(multi(3,022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01,032fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f,03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a),su:after(500000)))", "comment": "random_ms.txt line 7"}, + {"miniscript": "or_d(sha256(H),and_n(un:after(499999999),older(4194305)))", "comment": "random_ms.txt line 8"}, + {"miniscript": "and_v(or_i(v:multi(2,02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5,03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb),v:multi(2,03e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a,025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc)),sha256(H))", "comment": "random_ms.txt line 9"}, + {"miniscript": "j:and_b(multi(2,0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),s:or_i(older(1),older(4252898)))", "comment": "random_ms.txt line 10"}, + {"miniscript": "and_b(older(16),s:or_d(sha256(H),n:after(1567547623)))", "comment": "random_ms.txt line 11"}, + {"miniscript": "j:and_v(v:ripemd160(H),or_d(sha256(H),older(16)))", "comment": "random_ms.txt line 12"}, + {"miniscript": "and_b(hash256(H),a:and_b(hash256(H),a:older(1)))", "comment": "random_ms.txt line 13"}, + {"miniscript": "thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),ac:pk_k(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01))", "comment": "random_ms.txt line 14"}, + {"miniscript": "and_n(sha256(H),t:or_i(v:older(4252898),v:older(16)))", "comment": "random_ms.txt line 15"}, + {"miniscript": "or_d(nd:and_v(v:older(4252898),v:older(4252898)),sha256(H))", "comment": "random_ms.txt line 16"}, + {"miniscript": "c:and_v(or_c(sha256(H),v:multi(1,02c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db)),pk_k(03acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe))", "comment": "random_ms.txt line 17"}, + {"miniscript": "c:and_v(or_c(multi(2,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00,02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5),v:ripemd160(H)),pk_k(03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556))", "comment": "random_ms.txt line 18"}, + {"miniscript": "and_v(andor(hash256(H),v:hash256(H),v:older(50000)),after(1231488000))", "comment": "random_ms.txt line 19"}, + {"miniscript": "andor(hash256(H),j:and_v(v:ripemd160(H),older(4194305)),ripemd160(H))", "comment": "random_ms.txt line 20"}, + {"miniscript": "or_i(c:and_v(v:after(500000),pk_k(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),sha256(H))", "comment": "random_ms.txt line 21"}, + {"miniscript": "thresh(2,c:pk_h(025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc),s:sha256(H),a:ripemd160(H))", "comment": "random_ms.txt line 22"}, + {"miniscript": "and_n(sha256(H),uc:and_v(v:older(16),pk_k(03fe72c435413d33d48ac09c9161ba8b09683215439d62b7940502bda8b202e6ce)))", "comment": "random_ms.txt line 23"}, + {"miniscript": "and_n(c:pk_k(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),and_b(l:older(15),a:older(16)))", "comment": "random_ms.txt line 24"}, + {"miniscript": "c:or_i(and_v(v:older(16),pk_h(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e)),pk_h(026a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4))", "comment": "random_ms.txt line 25"}, + {"miniscript": "or_d(c:pk_h(02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),andor(c:pk_k(024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),older(2016),after(1567547623)))", "comment": "random_ms.txt line 26"}, + {"miniscript": "c:andor(ripemd160(H),pk_h(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e),and_v(v:hash256(H),pk_h(03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a)))", "comment": "random_ms.txt line 27"}, + {"miniscript": "c:andor(u:ripemd160(H),pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),or_i(pk_h(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01),pk_h(0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798)))", "comment": "random_ms.txt line 28"}, + {"miniscript": "c:or_i(andor(c:pk_h(03d30199d74fb5a22d47b6e054e2f378cedacffcb89904a61d75d0dbd407143e65),pk_h(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01),pk_h(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),pk_k(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e))", "comment": "random_ms.txt line 29"}, + {"miniscript": "multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00)", "comment": "random_ms.txt line 30"}, + {"miniscript": "multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00)", "comment": "random_ms.txt line 31"}, + {"miniscript": "thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00))", "comment": "random_ms.txt line 32"}, + {"miniscript": "thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),ac:pk_k(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01))", "comment": "random_ms.txt line 33"}, + {"miniscript": "c:pk_k(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01)", "comment": "random_ms.txt line 34"} + ] +} diff --git a/src/data/bip379/satisfier_golden.json b/src/data/bip379/satisfier_golden.json new file mode 100644 index 000000000..fce5e30cb --- /dev/null +++ b/src/data/bip379/satisfier_golden.json @@ -0,0 +1,41 @@ +{ + "andor(hash256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94),j:and_v(v:ripemd160(6646adac9fb158a6df66130746d48a0e7f9db390),older(4194305)),ripemd160(6646adac9fb158a6df66130746d48a0e7f9db390))": [ + "7878787878787878787878787878787878787878787878787878787878787878", + "0000000000000000000000000000000000000000000000000000000000000000", + "82012088aa20b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94876482012088a6146646adac9fb158a6df66130746d48a0e7f9db390876782926382012088a6146646adac9fb158a6df66130746d48a0e7f9db3908803010040b26868" + ], + "j:and_v(v:ripemd160(6646adac9fb158a6df66130746d48a0e7f9db390),or_d(sha256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94),older(16)))": [ + "1212121212121212121212121212121212121212121212121212121212121212", + "7878787878787878787878787878787878787878787878787878787878787878", + "82926382012088a6146646adac9fb158a6df66130746d48a0e7f9db3908882012088a820b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc9487736460b26868" + ], + "or_d(nd:and_v(v:older(4252898),v:older(4252898)),sha256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94))": [ + "1212121212121212121212121212121212121212121212121212121212121212", + "", + "766303e2e440b26903e2e440b2696892736482012088a820b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc948768" + ], + "or_d(sha256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94),and_n(un:after(499999999),older(4194305)))": [ + "1212121212121212121212121212121212121212121212121212121212121212", + "82012088a820b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc948773646304ff64cd1db19267006864006703010040b26868" + ], + "or_i(c:and_v(v:after(500000),pk_k(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),sha256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94))": [ + "1212121212121212121212121212121212121212121212121212121212121212", + "", + "630320a107b1692102c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5ac6782012088a820b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc948768" + ], + "t:andor(multi(3,02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e,03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556,02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),v:older(4194305),v:sha256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94))": [ + "1212121212121212121212121212121212121212121212121212121212121212", + "", + "", + "", + "", + "532102d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e2103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a14602975562102e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd1353ae6482012088a820b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94886703010040b2696851" + ], + "thresh(2,c:pk_h(025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc),s:sha256(b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc94),a:ripemd160(6646adac9fb158a6df66130746d48a0e7f9db390))": [ + "7878787878787878787878787878787878787878787878787878787878787878", + "1212121212121212121212121212121212121212121212121212121212121212", + "", + "025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", + "76a9145dedfbf9ea599dd4e3ca6a80b333c472fd0b3f6988ac7c82012088a820b6acca81a0939a856c35e4c4188e95b91731aab1d4629a4cee79dd09ded4fc9487936b82012088a6146646adac9fb158a6df66130746d48a0e7f9db390876c935287" + ] +} \ No newline at end of file diff --git a/src/data/psbt.json b/src/data/psbt.json index 4bf83db8e..e9608eb69 100644 --- a/src/data/psbt.json +++ b/src/data/psbt.json @@ -1,5 +1,21 @@ { "invalid": [ + { + "comment": "PSBT_OUT_TAP_TREE leaf with odd (parity-bit) leaf version", + "psbt": "cHNidP8BAF4CAAAAASd0Srq/MCf+DWzyOpbu4u+xiO9SMBlUWFiD5ptmJLJCAAAAAAD/////AUjmBSoBAAAAIlEgCoy9yG3hzhwPnK6yLW33ztNoP+Qj4F0eQCqHk0HW9vUAAAAAAAEBKwDyBSoBAAAAIlEgWiws9bUs8x+DrS6Npj/wMYPs2PYJx1EK6KSOA5EKB1chFv40kGTJjW4qhT+jybEr2LMEoZwZXGDvp+4jkwRtP6IyGQB3Ky2nVgAAgAEAAIAAAACAAQAAAAAAAAABFyD+NJBkyY1uKoU/o8mxK9izBKGcGVxg76fuI5MEbT+iMgABBSBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAEGbwLBIiBzblcpAP4SUliaIUPI88efcaBBLSNTr3VelwHHgmlKAqwCwCIgYxxfO1gyuPvev7GXBM7rMjwh9A96JPQ9aO8MwmsSWWmsAcAiIET6pJoDON5IjI3//s37bzKfOAvVZu8gyN9tgT6rHEJzrCEHRPqkmgM43kiMjf/+zftvMp84C9Vm7yDI322BPqscQnM5AfBreYuSoQ7ZqdC7/Trxc6U7FhfaOkFZygCCFs2Fay4Odystp1YAAIABAACAAQAAgAAAAAADAAAAIQdQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEHYxxfO1gyuPvev7GXBM7rMjwh9A96JPQ9aO8MwmsSWWk5ARis5AmIl4Xg6nDO67jhyokqenjq7eDy4pbPQ1lhqPTKdystp1YAAIABAACAAgAAgAAAAAADAAAAIQdzblcpAP4SUliaIUPI88efcaBBLSNTr3VelwHHgmlKAjkBKaW0kVCQFi11mv0/4Pk/ozJgVtC0CIy5M8rngmy42Cx3Ky2nVgAAgAEAAIADAACAAAAAAAMAAAAA" + }, + { + "comment": "PSBT_OUT_TAP_TREE leaf depth exceeds the BIP-341 maximum", + "psbt": "cHNidP8BAF4CAAAAASd0Srq/MCf+DWzyOpbu4u+xiO9SMBlUWFiD5ptmJLJCAAAAAAD/////AUjmBSoBAAAAIlEgCoy9yG3hzhwPnK6yLW33ztNoP+Qj4F0eQCqHk0HW9vUAAAAAAAEBKwDyBSoBAAAAIlEgWiws9bUs8x+DrS6Npj/wMYPs2PYJx1EK6KSOA5EKB1chFv40kGTJjW4qhT+jybEr2LMEoZwZXGDvp+4jkwRtP6IyGQB3Ky2nVgAAgAEAAIAAAACAAQAAAAAAAAABFyD+NJBkyY1uKoU/o8mxK9izBKGcGVxg76fuI5MEbT+iMgABBSBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAEGb4HAIiBzblcpAP4SUliaIUPI88efcaBBLSNTr3VelwHHgmlKAqwCwCIgYxxfO1gyuPvev7GXBM7rMjwh9A96JPQ9aO8MwmsSWWmsAcAiIET6pJoDON5IjI3//s37bzKfOAvVZu8gyN9tgT6rHEJzrCEHRPqkmgM43kiMjf/+zftvMp84C9Vm7yDI322BPqscQnM5AfBreYuSoQ7ZqdC7/Trxc6U7FhfaOkFZygCCFs2Fay4Odystp1YAAIABAACAAQAAgAAAAAADAAAAIQdQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEHYxxfO1gyuPvev7GXBM7rMjwh9A96JPQ9aO8MwmsSWWk5ARis5AmIl4Xg6nDO67jhyokqenjq7eDy4pbPQ1lhqPTKdystp1YAAIABAACAAgAAgAAAAAADAAAAIQdzblcpAP4SUliaIUPI88efcaBBLSNTr3VelwHHgmlKAjkBKaW0kVCQFi11mv0/4Pk/ozJgVtC0CIy5M8rngmy42Cx3Ky2nVgAAgAEAAIADAACAAAAAAAMAAAAA" + }, + { + "comment": "PSBT_OUT_TAP_TREE leaf script length overruns the value buffer", + "psbt": "cHNidP8BAF4CAAAAASd0Srq/MCf+DWzyOpbu4u+xiO9SMBlUWFiD5ptmJLJCAAAAAAD/////AUjmBSoBAAAAIlEgCoy9yG3hzhwPnK6yLW33ztNoP+Qj4F0eQCqHk0HW9vUAAAAAAAEBKwDyBSoBAAAAIlEgWiws9bUs8x+DrS6Npj/wMYPs2PYJx1EK6KSOA5EKB1chFv40kGTJjW4qhT+jybEr2LMEoZwZXGDvp+4jkwRtP6IyGQB3Ky2nVgAAgAEAAIAAAACAAQAAAAAAAAABFyD+NJBkyY1uKoU/o8mxK9izBKGcGVxg76fuI5MEbT+iMgABBSBQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAEGbwLAIiBzblcpAP4SUliaIUPI88efcaBBLSNTr3VelwHHgmlKAqwCwCIgYxxfO1gyuPvev7GXBM7rMjwh9A96JPQ9aO8MwmsSWWmsAcB/IET6pJoDON5IjI3//s37bzKfOAvVZu8gyN9tgT6rHEJzrCEHRPqkmgM43kiMjf/+zftvMp84C9Vm7yDI322BPqscQnM5AfBreYuSoQ7ZqdC7/Trxc6U7FhfaOkFZygCCFs2Fay4Odystp1YAAIABAACAAQAAgAAAAAADAAAAIQdQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wAUAfEYeXSEHYxxfO1gyuPvev7GXBM7rMjwh9A96JPQ9aO8MwmsSWWk5ARis5AmIl4Xg6nDO67jhyokqenjq7eDy4pbPQ1lhqPTKdystp1YAAIABAACAAgAAgAAAAAADAAAAIQdzblcpAP4SUliaIUPI88efcaBBLSNTr3VelwHHgmlKAjkBKaW0kVCQFi11mv0/4Pk/ozJgVtC0CIy5M8rngmy42Cx3Ky2nVgAAgAEAAIADAACAAAAAAAMAAAAA" + }, + { + "comment": "PSBT_IN_TAP_LEAF_SCRIPT trailing leaf version does not match the control block", + "psbt": "cHNidP8BAF4CAAAAAZvUh2UjC/mnLmYgAflyVW5U8Mb5f+tWvLVgDYF/aZUmAQAAAAD/////AUjmBSoBAAAAIlEgg2mORYxmZOFZXXXaJZfeHiLul9eY5wbEwKS1qYI810MAAAAAAAEBKwDyBSoBAAAAIlEgwiR++/2SrEf29AuNQtFpF1oZ+p+hDkol1/NetN2FtpJiFcFQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wG99YgWelJehpKJnVp2YdtpgEBr/OONSm5uTnOf5GulwEV8uSQr3zEXE94UR82BXzlxaXFYyWin7RN/CA/NW4fgjICyxOsaCSN6AaqajZZzzwD62gh0JyBFKToaP696GW7bSrMJCFcFQkpt0waBJVLeLS2A16XpeB4paDyjsltVHv+6azoA6wJfG5v6l/3FP9XJEmZkIEOQG6YqhD1v35fZ4S8HQqabOIyBDILC/FvARtT6nvmFZJKp/J+XSmtIOoRVdhIZ2w7rRsqzAYhXBUJKbdMGgSVS3i0tgNel6XgeKWg8o7JbVR7/ums6AOsDNlw4V9T/AyC+VD9Vg/6kZt2FyvgFzaKiZE68HT0ALCRFfLkkK98xFxPeFEfNgV85cWlxWMlop+0TfwgPzVuH4IyD6D3o87zsdDAps59JuF62gsuXJLRnvrUi0GFnLikUcqazAIRYssTrGgkjegGqmo2Wc88A+toIdCcgRSk6Gj+vehlu20jkBzZcOFfU/wMgvlQ/VYP+pGbdhcr4Bc2iomROvB09ACwl3Ky2nVgAAgAEAAIACAACAAAAAAAAAAAAhFkMgsL8W8BG1Pqe+YVkkqn8n5dKa0g6hFV2EhnbDutGyOQERXy5JCvfMRcT3hRHzYFfOXFpcVjJaKftE38ID81bh+HcrLadWAACAAQAAgAEAAIAAAAAAAAAAACEWUJKbdMGgSVS3i0tgNel6XgeKWg8o7JbVR7/ums6AOsAFAHxGHl0hFvoPejzvOx0MCmzn0m4XraCy5cktGe+tSLQYWcuKRRypOQFvfWIFnpSXoaSiZ1admHbaYBAa/zjjUpubk5zn+RrpcHcrLadWAACAAQAAgAMAAIAAAAAAAAAAAAEXIFCSm3TBoElUt4tLYDXpel4HiloPKOyW1Ue/7prOgDrAARgg8DYuL3Wm9CClvePrIh2WrmcgzyX4GJDJWx13WstRXmUAAQUgESTaeuySzNBslUViZH9DexOLlXIahL4r8idrvdqz5nEhBxEk2nrskszQbJVFYmR/Q3sTi5VyGoS+K/Ina73as+ZxGQB3Ky2nVgAAgAEAAIAAAACAAAAAAAUAAAAA" + }, { "comment": "Network transaction, not PSBT format", "psbt": "AgAAAAEmgXE3Ht/yhek3re6ks3t4AAwFZsuzrWRkFxPKQhcb9gAAAABqRzBEAiBwsiRRI+a/R01gxbUMBD1MaRpdJDXwmjSnZiqdwlF5CgIgATKcqdrPKAvfMHQOwDkEIkIsgctFg5RXrrdvwS7dlbMBIQJlfRGNM1e44PTCzUbbezn22cONmnCry5st5dyNv+TOMf7///8C09/1BQAAAAAZdqkU0MWZA8W6woaHYOkP1SGkZlqnZSCIrADh9QUAAAAAF6kUNUXm4zuDLEcFDyTT7rk8nAOUi8eHsy4TAA==" diff --git a/src/descriptor.c b/src/descriptor.c index 423047f6f..17cd4c4ac 100644 --- a/src/descriptor.c +++ b/src/descriptor.c @@ -4981,6 +4981,177 @@ int wally_descriptor_get_taproot_leaf_key_index( return leaf_num_keys_impl(descriptor, leaf_index, key_index, value_out, false); } +static int leaf_key_indices_impl(const struct wally_descriptor *descriptor, + const ms_node *node, + uint32_t *indices_out, size_t num_indices, + size_t *written, size_t *hint) +{ + const ms_node *child; + int ret; + + if (node->kind & KIND_KEY) { + /* Keys are registered in parse order, so a leaf's keys are normally + * contiguous: search forward from the last match, wrapping around, + * to make collecting a leaf's keys linear rather than quadratic */ + const size_t num_keys = descriptor->keys.num_items; + size_t i, n; + for (n = 0; n < num_keys; ++n) { + i = (*hint + n) % num_keys; + if ((const ms_node *)descriptor->keys.items[i].value == node) + break; + } + if (n == num_keys) + return WALLY_EINVAL; /* Key not found in map (should not happen) */ + if (*written < num_indices) + indices_out[*written] = (uint32_t)i; + ++*written; + *hint = i + 1; + return WALLY_OK; + } + if (node->builtin) + for (child = node->child; child; child = child->next) { + ret = leaf_key_indices_impl(descriptor, child, indices_out, + num_indices, written, hint); + if (ret != WALLY_OK) + return ret; + } + return WALLY_OK; +} + +int descriptor_get_taproot_leaf_key_indices( + const struct wally_descriptor *descriptor, + uint32_t leaf_index, + uint32_t *indices_out, size_t num_indices, size_t *written) +{ + ms_node *leaf; + size_t hint = 0; + int ret; + + if (written) + *written = 0; + if (!written || (!indices_out && num_indices)) + return WALLY_EINVAL; + if ((ret = tr_get_leaf(descriptor, leaf_index, &leaf)) != WALLY_OK) + return ret; + return leaf_key_indices_impl(descriptor, leaf, indices_out, num_indices, + written, &hint); +} + +/* Internal: derive the x-only pubkey for a descriptor key (used by psbt.c). + * FIXME: replace with a public get_bip32_key() returning a populated ext_key */ +int descriptor_get_key_xonly_public_key( + const struct wally_descriptor *descriptor, + size_t index, uint32_t multi_index, uint32_t child_num, + unsigned char *bytes_out, size_t len) +{ + const ms_node *key_node; + ms_ctx ctx; + unsigned char pubkey[EC_PUBLIC_KEY_LEN]; + size_t written = 0; + int ret; + + if (!descriptor || !bytes_out || len != EC_XONLY_PUBLIC_KEY_LEN || + !index_args_valid(descriptor, 0, multi_index, child_num)) + return WALLY_EINVAL; + if (!(key_node = descriptor_get_key(descriptor, index))) + return WALLY_EINVAL; + + if ((ret = ctx_clone(descriptor, 0, multi_index, child_num, &ctx)) != WALLY_OK) + return ret; + + /* Generate the pubkey for this key node */ + ret = generate_script(&ctx, (ms_node *)key_node, pubkey, sizeof(pubkey), &written); + wally_free(ctx.path_buff); + + if (ret == WALLY_OK) { + if (written == EC_XONLY_PUBLIC_KEY_LEN) { + memcpy(bytes_out, pubkey, EC_XONLY_PUBLIC_KEY_LEN); + } else if (written == EC_PUBLIC_KEY_LEN) { + /* Compressed key: strip the parity byte */ + memcpy(bytes_out, pubkey + 1, EC_XONLY_PUBLIC_KEY_LEN); + } else { + ret = WALLY_EINVAL; + } + } + return ret; +} + +int descriptor_get_musig_participant_keypath( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + uint32_t multi_index, uint32_t child_num, + unsigned char *pub_key_out, size_t pub_key_len, + unsigned char *fingerprint_out, size_t fingerprint_len, + uint32_t **path_out, size_t *path_len_out) +{ + const ms_node *k = get_musig_participant(descriptor, index, participant_index); + const uint32_t child_flags = BIP32_FLAG_STR_WILDCARD | BIP32_FLAG_STR_BARE | + BIP32_FLAG_STR_MULTIPATH; + const char *origin_str = NULL; + size_t origin_str_len = 0, origin_len = 0, child_len = 0, written; + uint32_t child_index = 0, path_index = 0; + ms_ctx ctx; + int ret; + + if (path_out) + *path_out = NULL; + if (path_len_out) + *path_len_out = 0; + if (!k || !pub_key_out || pub_key_len != EC_PUBLIC_KEY_LEN || + !fingerprint_out || fingerprint_len != BIP32_KEY_FINGERPRINT_LEN || + !path_out || !path_len_out || + !index_args_valid(descriptor, 0, multi_index, child_num)) + return WALLY_EINVAL; + + /* Derive the participant's public key, as for aggregation */ + if ((ret = ctx_clone(descriptor, 0, multi_index, child_num, &ctx)) != WALLY_OK) + return ret; + ret = generate_script(&ctx, (ms_node *)k, pub_key_out, pub_key_len, &written); + ctx_clear(&ctx); + if (ret == WALLY_OK && written != EC_PUBLIC_KEY_LEN) + ret = WALLY_EINVAL; /* musig() participants are compressed keys */ + + memset(fingerprint_out, 0, fingerprint_len); + if (ret == WALLY_OK && k->flags & WALLY_MS_IS_PARENTED) { + ret = key_node_origin_fingerprint(descriptor, k, fingerprint_out, fingerprint_len); + origin_str = descriptor->src + (((uint64_t)k->number) >> 32u) + 10u; + origin_str_len = key_node_origin_path_str_len(k); + } + + /* Compute the path length, then fetch the origin and child paths */ + if (ret == WALLY_OK && origin_str_len) + ret = bip32_path_from_str_n_len(origin_str, origin_str_len, + 0, 0, BIP32_FLAG_STR_BARE, &origin_len); + if (ret == WALLY_OK && k->child_path_len) { + if (k->flags & WALLY_MS_IS_RANGED) + child_index = child_num; + if (k->flags & WALLY_MS_IS_MULTIPATH) + path_index = multi_index; + ret = bip32_path_from_str_n_len(k->child_path, k->child_path_len, + child_index, path_index, child_flags, + &child_len); + } + if (ret != WALLY_OK || !(origin_len + child_len)) + return ret; + if (!(*path_out = wally_malloc((origin_len + child_len) * sizeof(uint32_t)))) + return WALLY_ENOMEM; + if (origin_len) + ret = bip32_path_from_str_n(origin_str, origin_str_len, 0, 0, + BIP32_FLAG_STR_BARE, *path_out, + origin_len, &written); + if (ret == WALLY_OK && child_len) + ret = bip32_path_from_str_n(k->child_path, k->child_path_len, + child_index, path_index, child_flags, + *path_out + origin_len, child_len, &written); + if (ret == WALLY_OK) + *path_len_out = origin_len + child_len; + else { + wally_free(*path_out); + *path_out = NULL; + } + return ret; +} + int wally_descriptor_get_taproot_merkle_root( const struct wally_descriptor *descriptor, uint32_t multi_index, uint32_t child_num, uint32_t flags, diff --git a/src/descriptor_int.h b/src/descriptor_int.h index 32320508b..ac8dff0a5 100644 --- a/src/descriptor_int.h +++ b/src/descriptor_int.h @@ -129,4 +129,29 @@ struct wally_descriptor { typedef struct wally_descriptor ms_ctx; +/* Write the descriptor key index of each key in taproot leaf ``leaf_index``, + * in leaf order. ``written`` is set to the number of keys in the leaf; + * the indices are only written if ``num_indices`` is large enough. */ +int descriptor_get_taproot_leaf_key_indices( + const struct wally_descriptor *descriptor, + uint32_t leaf_index, + uint32_t *indices_out, size_t num_indices, size_t *written); + +/* Derive the x-only pubkey for the descriptor key at ``index`` */ +int descriptor_get_key_xonly_public_key( + const struct wally_descriptor *descriptor, + size_t index, uint32_t multi_index, uint32_t child_num, + unsigned char *bytes_out, size_t len); + +/* Derive the compressed pubkey of a musig() participant, and get its origin + * fingerprint (zero if none) and full derivation path (origin path followed + * by its child path). The caller must wally_free(*path_out) */ +int descriptor_get_musig_participant_keypath( + const struct wally_descriptor *descriptor, + size_t index, size_t participant_index, + uint32_t multi_index, uint32_t child_num, + unsigned char *pub_key_out, size_t pub_key_len, + unsigned char *fingerprint_out, size_t fingerprint_len, + uint32_t **path_out, size_t *path_len_out); + #endif /* LIBWALLY_CORE_DESCRIPTOR_INT_H */ diff --git a/src/psbt.c b/src/psbt.c index a297206fd..bc4bd21cf 100644 --- a/src/psbt.c +++ b/src/psbt.c @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -12,6 +13,9 @@ #include "script.h" #include "pullpush.h" #include "tx_io.h" +#include "descriptor_int.h" +#include "miniscript_decode.h" +#include "miniscript_satisfy.h" /* TODO: * - When setting utxo in an input via the psbt (in the SWIG @@ -422,6 +426,163 @@ SET_STRUCT(wally_psbt_input, final_witness, wally_tx_witness_stack, SET_MAP(wally_psbt_input, keypath,) ADD_KEYPATH(wally_psbt_input) ADD_TAP_KEYPATH(wally_psbt_input) +SET_MAP(wally_psbt_input, musig2_pubkey,) +int wally_psbt_input_add_musig2_participant_pubkeys(struct wally_psbt_input *input, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *participants, + size_t participants_len) +{ + if (!input || !agg_pubkey || agg_pubkey_len != EC_PUBLIC_KEY_LEN || + !participants || participants_len < EC_PUBLIC_KEY_LEN * 2 || + participants_len % EC_PUBLIC_KEY_LEN) + return WALLY_EINVAL; + return wally_map_replace(&input->musig2_pubkeys, + agg_pubkey, agg_pubkey_len, + participants, participants_len); +} +static void musig2_composite_key_build(const unsigned char *participant, + const unsigned char *agg_pubkey, + const unsigned char *leaf_hash, + unsigned char *key_out, size_t *key_len_out) +{ + size_t key_len = EC_PUBLIC_KEY_LEN * 2 + (leaf_hash ? SHA256_LEN : 0); + memcpy(key_out, participant, EC_PUBLIC_KEY_LEN); + memcpy(key_out + EC_PUBLIC_KEY_LEN, agg_pubkey, EC_PUBLIC_KEY_LEN); + if (leaf_hash) + memcpy(key_out + EC_PUBLIC_KEY_LEN * 2, leaf_hash, SHA256_LEN); + *key_len_out = key_len; +} + +/* Add/replace (value non-NULL) or find (written non-NULL) an entry in a + * MuSig2 map keyed by participant + aggregate key (+ optional leaf hash) */ +static int musig2_map_add_or_find(const struct wally_map *map_in, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const unsigned char *value, size_t value_len, + size_t *written) +{ + unsigned char key[EC_PUBLIC_KEY_LEN * 2 + SHA256_LEN]; + size_t key_len; + + if (written) + *written = 0; + if (!participant || participant_len != EC_PUBLIC_KEY_LEN || + !agg_pubkey || agg_pubkey_len != EC_PUBLIC_KEY_LEN || + (leaf_hash && leaf_hash_len != SHA256_LEN) || + (!leaf_hash && leaf_hash_len != 0)) + return WALLY_EINVAL; + + musig2_composite_key_build(participant, agg_pubkey, leaf_hash, key, &key_len); + if (written) + return wally_map_find(map_in, key, key_len, written); + return wally_map_replace((struct wally_map *)map_in, key, key_len, value, value_len); +} + +int wally_psbt_input_add_musig2_pubnonce(struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const unsigned char *pubnonce, + size_t pubnonce_len) +{ + if (!input || !pubnonce || pubnonce_len != WALLY_MUSIG_PUBNONCE_LEN) + return WALLY_EINVAL; + return musig2_map_add_or_find(&input->musig2_pubnonces, + participant, participant_len, + agg_pubkey, agg_pubkey_len, + leaf_hash, leaf_hash_len, + pubnonce, pubnonce_len, NULL); +} + +int wally_psbt_input_find_musig2_pubnonce(const struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + size_t *written) +{ + if (written) + *written = 0; + if (!input || !written) + return WALLY_EINVAL; + return musig2_map_add_or_find(&input->musig2_pubnonces, + participant, participant_len, + agg_pubkey, agg_pubkey_len, + leaf_hash, leaf_hash_len, + NULL, 0, written); +} + +int wally_psbt_input_get_musig2_pubnonce_size(const struct wally_psbt_input *input, + size_t *written) +{ + if (written) + *written = 0; + if (!input || !written) + return WALLY_EINVAL; + *written = input->musig2_pubnonces.num_items; + return WALLY_OK; +} + +int wally_psbt_input_add_musig2_partial_sig(struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + const unsigned char *partial_sig, + size_t partial_sig_len) +{ + if (!input || !partial_sig || partial_sig_len != WALLY_MUSIG_PARTIAL_SIG_LEN) + return WALLY_EINVAL; + return musig2_map_add_or_find(&input->musig2_partial_sigs, + participant, participant_len, + agg_pubkey, agg_pubkey_len, + leaf_hash, leaf_hash_len, + partial_sig, partial_sig_len, NULL); +} + +int wally_psbt_input_find_musig2_partial_sig(const struct wally_psbt_input *input, + const unsigned char *participant, + size_t participant_len, + const unsigned char *agg_pubkey, + size_t agg_pubkey_len, + const unsigned char *leaf_hash, + size_t leaf_hash_len, + size_t *written) +{ + if (written) + *written = 0; + if (!input || !written) + return WALLY_EINVAL; + return musig2_map_add_or_find(&input->musig2_partial_sigs, + participant, participant_len, + agg_pubkey, agg_pubkey_len, + leaf_hash, leaf_hash_len, + NULL, 0, written); +} + +int wally_psbt_input_get_musig2_partial_sig_size(const struct wally_psbt_input *input, + size_t *written) +{ + if (written) + *written = 0; + if (!input || !written) + return WALLY_EINVAL; + *written = input->musig2_partial_sigs.num_items; + return WALLY_OK; +} + SET_MAP(wally_psbt_input, signature, _internal) int wally_psbt_input_add_signature(struct wally_psbt_input *input, const unsigned char *pub_key, size_t pub_key_len, @@ -557,6 +718,33 @@ static int map_leaf_hashes_verify(const unsigned char *key, size_t key_len, return ret; } +/* BIP-371 PSBT_IN_TAP_SCRIPT_SIG: key = x-only pubkey(32) + leaf hash(32), + * value = 64 or 65 byte BIP-340 Schnorr signature. */ +static int taproot_leaf_signature_verify(const unsigned char *key, size_t key_len, + const unsigned char *val, size_t val_len) +{ + if (!key || key_len != EC_XONLY_PUBLIC_KEY_LEN + SHA256_LEN) + return WALLY_EINVAL; + if (wally_ec_xonly_public_key_verify(key, EC_XONLY_PUBLIC_KEY_LEN) != WALLY_OK) + return WALLY_EINVAL; + if (!val || (val_len != EC_SIGNATURE_LEN && val_len != EC_SIGNATURE_LEN + 1)) + return WALLY_EINVAL; + return WALLY_OK; +} + +/* BIP-371 PSBT_IN_TAP_LEAF_SCRIPT: key = BIP-341 control block, value = the + * tapscript (the leaf version is taken from the control block, see BIP-341). + * The tapscript may be empty. */ +static int taproot_leaf_script_verify(const unsigned char *key, size_t key_len, + const unsigned char *val, size_t val_len) +{ + if (wally_bip341_control_block_verify(key, key_len) != WALLY_OK) + return WALLY_EINVAL; + if (BYTES_INVALID(val, val_len)) + return WALLY_EINVAL; + return WALLY_OK; +} + /* BIP-371 PSBT_OUT_TAP_TREE value: a depth-first sequence of * <8-bit depth> <8-bit leaf version>