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/contrib/musig2_psbt_2of2.py b/contrib/musig2_psbt_2of2.py new file mode 100644 index 000000000..9ff8c4bbd --- /dev/null +++ b/contrib/musig2_psbt_2of2.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +""" +2-of-2 MuSig2 PSBT signing example (BIP-327/373) + +Demonstrates the full two-round MuSig2 signing workflow: + 1. Key aggregation (signer 1 and signer 2 combine pubkeys) + 2. PSBT creation with P2TR output locked to the aggregate key + 3. Round 1: nonce generation and injection into the PSBT + 4. Round 2: partial signing by each participant + 5. Finalization: partial sigs aggregated into a 64-byte Schnorr sig + 6. Final PSBT verification + +Run with: + LD_LIBRARY_PATH=src/.libs PYTHONPATH=src/swig_python python3 contrib/musig2_psbt_2of2.py +""" +import sys +import os + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src', 'swig_python')) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src', 'test')) + +from ctypes import * +from util import * + +# -- Constants ---------------------------------------------------------------- + +EC_PUBLIC_KEY_LEN = 33 +EC_XONLY_PUBLIC_KEY_LEN = 32 +EC_SIGNATURE_LEN = 64 +EC_FLAG_SCHNORR = 0x2 +WALLY_SIGHASH_DEFAULT = 0x00 +WALLY_PSBT_EXTRACT_NON_FINAL = 0x1 +BIP32_VER_MAIN_PUBLIC = 0x0488B21E + +# Two participant secret keys (for example use only - never hardcode in production!) +SECKEY1 = bytes([0x01] * 32) +SECKEY2 = bytes([0x02] * 32) + + +def derive_pubkey(seckey): + """Derive the compressed 33-byte pubkey from a 32-byte secret key.""" + 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 bytes(pub) + + +def main(): + # -- Step 1: Key Aggregation ----------------------------------------------- + pk1 = derive_pubkey(SECKEY1) + pk2 = derive_pubkey(SECKEY2) + pub_keys_flat = pk1 + pk2 # concatenated compressed pubkeys + + agg_pk_xonly, _ = 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_xonly, EC_XONLY_PUBLIC_KEY_LEN, cache) + assert ret == WALLY_OK, 'key aggregation failed' + assert cache.value is not None + print(f'Aggregate x-only pubkey: {bytes(agg_pk_xonly).hex()}') + + # The PSBT stores participant keys under the compressed (33-byte) aggregate + # pubkey. Fetch it from the cache: the parity byte is the real one computed + # during aggregation (do not assume even/0x02 parity). + agg_pubkey_buf, _ = make_cbuffer('00' * EC_PUBLIC_KEY_LEN) + ret = wally_musig_pubkey_get(cache.value, agg_pubkey_buf, EC_PUBLIC_KEY_LEN) + assert ret == WALLY_OK, 'aggregate pubkey fetch failed' + agg_pubkey = bytes(agg_pubkey_buf) + + # -- Step 2: Build PSBT with a P2TR input --------------------------------- + # Build the P2TR scriptpubkey. Passing the 33-byte COMPRESSED aggregate + # (internal) key makes wally apply the BIP-341 key-path output tweak, so the + # coin is locked to the standard taproot output key Q = P + H_TapTweak(P)*G + # (NOT the raw aggregate key P). The PSBT musig signing flow re-applies the + # same tweak internally so the aggregated signature is valid under Q. + p2tr_buf, _ = make_cbuffer('00' * 34) + ret, p2tr_written = wally_scriptpubkey_p2tr_from_bytes( + agg_pubkey, EC_PUBLIC_KEY_LEN, 0, p2tr_buf, 34) + assert ret == WALLY_OK, 'P2TR scriptpubkey creation failed' + p2tr_bytes = bytes(p2tr_buf[:p2tr_written]) + + # Create PSBT v2 with 1 input and 1 output + psbt = pointer(wally_psbt()) + assert wally_psbt_init_alloc(2, 1, 1, 0, 0, psbt) == WALLY_OK + + # Add a dummy input (txid=0..0, vout=0) + tx_in = pointer(wally_tx_input()) + assert wally_psbt_add_tx_input_at(psbt, 0, 0, tx_in) == WALLY_OK + + # Add a dummy P2WPKH output (recipient) + tx_output = pointer(wally_tx_output()) + assert wally_tx_output_init_alloc( + 1000, b'\x00\x14' + b'\xab' * 20, 22, tx_output) == WALLY_OK + assert wally_psbt_add_tx_output_at(psbt, 0, 0, tx_output) == WALLY_OK + + # Set the UTXO being spent (P2TR output, 200,000 sat) + utxo = pointer(wally_tx_output()) + assert wally_tx_output_init_alloc( + 200000, p2tr_bytes, len(p2tr_bytes), utxo) == WALLY_OK + assert wally_psbt_set_input_witness_utxo(psbt, 0, utxo) == WALLY_OK + assert wally_psbt_set_input_amount(psbt, 0, 200000) == WALLY_OK + + # Record the taproot internal key (x-only) so sighash knows the script tree + assert wally_psbt_set_input_taproot_internal_key( + psbt, 0, agg_pk_xonly, EC_XONLY_PUBLIC_KEY_LEN) == WALLY_OK + + # Register both participant pubkeys in the PSBT under the aggregate key. + # This is the BIP-373 MUSIG2_PARTICIPANT_PUBKEYS field. + participants_flat = pk1 + pk2 + ret = wally_psbt_input_add_musig2_participant_pubkeys( + psbt.contents.inputs, + agg_pubkey_buf, EC_PUBLIC_KEY_LEN, + participants_flat, len(participants_flat)) + assert ret == WALLY_OK, 'registering participant pubkeys failed' + + print('PSBT created with P2TR input') + + # -- Step 3: Round 1 - Nonce Generation ----------------------------------- + # Each signer independently generates a (secnonce, pubnonce) pair using a + # unique session random value. wally_psbt_musig2_add_nonce stores the + # pubnonce in the PSBT and returns the secnonce to the caller. + # Each signer MUST use unique, cryptographically secure randomness here and + # MUST NOT reuse it across signing sessions (MuSig2 nonce reuse leaks the key). + secrand1, _ = make_cbuffer(os.urandom(32).hex()) + secrand2, _ = make_cbuffer(os.urandom(32).hex()) + sn1 = c_void_p() + sn2 = c_void_p() + + # Passing the signer's seckey binds the nonce to it, improving + # nonce-misuse resistance (BIP-327 recommends providing it). + seckey1, _ = make_cbuffer(SECKEY1.hex()) + seckey2, _ = make_cbuffer(SECKEY2.hex()) + + ret = wally_psbt_musig2_add_nonce( + psbt, 0, + secrand1, 32, # unique session random (32 bytes) + seckey1, 32, # signer seckey, for nonce-misuse resistance + pk1, EC_PUBLIC_KEY_LEN, + agg_pubkey_buf, EC_PUBLIC_KEY_LEN, + None, 0, # no tapscript leaf hash (key-path spend) + None, 0, # no external keyagg_cache + byref(sn1)) + assert ret == WALLY_OK, 'participant 1 nonce generation failed' + + ret = wally_psbt_musig2_add_nonce( + psbt, 0, + secrand2, 32, + seckey2, 32, + pk2, EC_PUBLIC_KEY_LEN, + agg_pubkey_buf, EC_PUBLIC_KEY_LEN, + None, 0, None, 0, + byref(sn2)) + assert ret == WALLY_OK, 'participant 2 nonce generation failed' + + print('Round 1 complete: both pubnonces stored in PSBT') + + # -- Step 4: Round 2 - Partial Signing ------------------------------------ + # Each signer produces a partial signature using their secnonce + seckey. + # The keyagg_cache (from step 1) must be the same object for both signers. + ret = wally_psbt_musig2_sign( + psbt, 0, + sn1.value, # secnonce is consumed (zeroed) after this call + seckey1, 32, + pk1, EC_PUBLIC_KEY_LEN, + agg_pubkey_buf, EC_PUBLIC_KEY_LEN, + None, 0, # no tapscript leaf hash + cache.value, 0, # keyagg_cache from step 1 + None) # partial_sig_out (stored in PSBT internally) + assert ret == WALLY_OK, 'participant 1 partial sign failed' + + ret = wally_psbt_musig2_sign( + psbt, 0, + sn2.value, + seckey2, 32, + pk2, EC_PUBLIC_KEY_LEN, + agg_pubkey_buf, EC_PUBLIC_KEY_LEN, + None, 0, + cache.value, 0, + None) + assert ret == WALLY_OK, 'participant 2 partial sign failed' + + print('Round 2 complete: both partial signatures stored in PSBT') + + # -- Step 5: Finalization -------------------------------------------------- + # wally_psbt_musig2_finalize_input aggregates the two partial signatures + # into a single 64-byte BIP-340 Schnorr signature and writes it as the + # PSBT TAP_KEY_SIG field. The pubnonce and partial sig entries are then + # cleared from the PSBT. + ret = wally_psbt_musig2_finalize_input( + psbt, 0, + agg_pubkey_buf, EC_PUBLIC_KEY_LEN, + None, 0, # no tapscript leaf hash + cache.value, 0) + assert ret == WALLY_OK, 'finalization failed' + + # Read back the aggregated Schnorr signature + sig_buf, _ = make_cbuffer('00' * EC_SIGNATURE_LEN) + ret, sig_written = wally_psbt_get_input_taproot_signature( + psbt, 0, sig_buf, EC_SIGNATURE_LEN) + assert ret == WALLY_OK and sig_written == EC_SIGNATURE_LEN + print(f'Final Schnorr signature ({sig_written} bytes): {bytes(sig_buf).hex()}') + + # -- Step 6: Cryptographic Verification ----------------------------------- + # Verify the signature against the P2TR output key. + # The P2TR scriptpubkey is OP_1 <32-byte-tweaked-output-key>; + # bytes [2:34] are the x-only output key the signature must verify against. + output_xonly_key = p2tr_bytes[2:34] + output_key_buf, _ = make_cbuffer(output_xonly_key.hex()) + + # Extract the (unsigned) transaction from the PSBT to compute the sighash + tx_pp = POINTER(wally_tx)() + assert wally_psbt_extract(psbt, WALLY_PSBT_EXTRACT_NON_FINAL, byref(tx_pp)) == WALLY_OK + + sighash_buf, _ = make_cbuffer('00' * 32) + ret = wally_psbt_get_input_signature_hash( + psbt, 0, tx_pp, None, 0, WALLY_SIGHASH_DEFAULT, sighash_buf, 32) + assert ret == WALLY_OK, 'sighash computation failed' + + ret = wally_ec_sig_verify( + output_key_buf, EC_XONLY_PUBLIC_KEY_LEN, + sighash_buf, 32, + EC_FLAG_SCHNORR, + sig_buf, EC_SIGNATURE_LEN) + assert ret == WALLY_OK, 'BIP-340 signature verification FAILED' + print('BIP-340 Schnorr signature verified successfully') + + # -- Cleanup --------------------------------------------------------------- + wally_musig_secnonce_free(sn1.value) + wally_musig_secnonce_free(sn2.value) + wally_musig_keyagg_cache_free(cache.value) + wally_tx_free(tx_pp) + wally_psbt_free(psbt) + + print('MuSig2 2-of-2 example complete') + + +if __name__ == '__main__': + main() 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/docs/source/index.rst b/docs/source/index.rst index 2348eb154..873a6d83d 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -14,6 +14,7 @@ libwally-core documentation bip85 coinselection map + musig psbt script descriptor @@ -29,6 +30,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/fuzz/Makefile.am b/fuzz/Makefile.am index 78de1631c..beee823ee 100644 --- a/fuzz/Makefile.am +++ b/fuzz/Makefile.am @@ -1,4 +1,4 @@ -noinst_PROGRAMS = fuzz_psbt_from_bytes fuzz_tx_from_bytes +noinst_PROGRAMS = fuzz_psbt_from_bytes fuzz_tx_from_bytes fuzz_descriptor fuzz_psbt_musig2 fuzz_psbt_from_bytes_SOURCES = fuzz_psbt_from_bytes.c fuzz_psbt_from_bytes_CFLAGS = -I$(top_srcdir)/include $(AM_CFLAGS) @@ -9,3 +9,13 @@ fuzz_tx_from_bytes_SOURCES = fuzz_tx_from_bytes.c fuzz_tx_from_bytes_CFLAGS = -I$(top_srcdir)/include $(AM_CFLAGS) fuzz_tx_from_bytes_LDFLAGS = -fsanitize=fuzzer fuzz_tx_from_bytes_LDADD = $(top_builddir)/src/libwallycore.la + +fuzz_descriptor_SOURCES = fuzz_descriptor.c +fuzz_descriptor_CFLAGS = -I$(top_srcdir)/include $(AM_CFLAGS) +fuzz_descriptor_LDFLAGS = -fsanitize=fuzzer +fuzz_descriptor_LDADD = $(top_builddir)/src/libwallycore.la + +fuzz_psbt_musig2_SOURCES = fuzz_psbt_musig2.c +fuzz_psbt_musig2_CFLAGS = -I$(top_srcdir)/include $(AM_CFLAGS) +fuzz_psbt_musig2_LDFLAGS = -fsanitize=fuzzer +fuzz_psbt_musig2_LDADD = $(top_builddir)/src/libwallycore.la diff --git a/fuzz/corpus/fuzz_descriptor/malformed_missing_paren b/fuzz/corpus/fuzz_descriptor/malformed_missing_paren new file mode 100644 index 000000000..612e23e84 --- /dev/null +++ b/fuzz/corpus/fuzz_descriptor/malformed_missing_paren @@ -0,0 +1 @@ +tr(musig(0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5) \ No newline at end of file diff --git a/fuzz/corpus/fuzz_descriptor/valid_compressed_keys b/fuzz/corpus/fuzz_descriptor/valid_compressed_keys new file mode 100644 index 000000000..ee32fd7a6 --- /dev/null +++ b/fuzz/corpus/fuzz_descriptor/valid_compressed_keys @@ -0,0 +1 @@ +tr(musig(0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)) \ No newline at end of file diff --git a/fuzz/corpus/fuzz_descriptor/valid_xpub_derivation b/fuzz/corpus/fuzz_descriptor/valid_xpub_derivation new file mode 100644 index 000000000..ae6342577 --- /dev/null +++ b/fuzz/corpus/fuzz_descriptor/valid_xpub_derivation @@ -0,0 +1 @@ +tr(musig([deadbeef/86h/0h/0h]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/0/*,[cafebabe/86h/0h/0h]xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/0/*)) \ No newline at end of file diff --git a/fuzz/corpus/fuzz_psbt_musig2/partial_sig_keypath b/fuzz/corpus/fuzz_psbt_musig2/partial_sig_keypath new file mode 100644 index 000000000..a536acb34 --- /dev/null +++ b/fuzz/corpus/fuzz_psbt_musig2/partial_sig_keypath @@ -0,0 +1,2 @@ +O5[Ü·Ì +÷(ï<ιa]�hKµ²Ê_…š°ð·Xqªvê¦Çz.K‰ç3¾(‹I‘ŽwˆM˜?$4‹S*Ó33333333333333333333333333333333 \ No newline at end of file diff --git a/fuzz/corpus/fuzz_psbt_musig2/participants_2of2 b/fuzz/corpus/fuzz_psbt_musig2/participants_2of2 new file mode 100644 index 000000000..9a10568bf --- /dev/null +++ b/fuzz/corpus/fuzz_psbt_musig2/participants_2of2 @@ -0,0 +1,2 @@ +vê¦Çz.K‰ç3¾(‹I‘ŽwˆM˜?$4‹S*ÓO5[Ü·Ì +÷(ï<ιa]�hKµ²Ê_…š°ð·XqªFmÊåcåË  Ñ‡ µ€4Haxy¡IIÏ"(_®?' \ No newline at end of file diff --git a/fuzz/corpus/fuzz_psbt_musig2/pubnonce_keypath b/fuzz/corpus/fuzz_psbt_musig2/pubnonce_keypath new file mode 100644 index 000000000..d6f6f1d45 --- /dev/null +++ b/fuzz/corpus/fuzz_psbt_musig2/pubnonce_keypath @@ -0,0 +1,2 @@ +O5[Ü·Ì +÷(ï<ιa]�hKµ²Ê_…š°ð·Xqªvê¦Çz.K‰ç3¾(‹I‘ŽwˆM˜?$4‹S*ÓõÃ*×Ì”~{cªí䆥º}«tñzßÓ`·ßápaI¬‚åÓ"ç$Ù�Ñ�3—õö�ùYè¬\7ÃûBA \ No newline at end of file diff --git a/fuzz/corpus/fuzz_psbt_musig2/pubnonce_scriptpath b/fuzz/corpus/fuzz_psbt_musig2/pubnonce_scriptpath new file mode 100644 index 000000000..3809d0635 --- /dev/null +++ b/fuzz/corpus/fuzz_psbt_musig2/pubnonce_scriptpath @@ -0,0 +1,2 @@ +O5[Ü·Ì +÷(ï<ιa]�hKµ²Ê_…š°ð·Xqªvê¦Çz.K‰ç3¾(‹I‘ŽwˆM˜?$4‹S*ÓwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwõÃ*×Ì”~{cªí䆥º}«tñzßÓ`·ßápaI¬‚åÓ"ç$Ù�Ñ�3—õö�ùYè¬\7ÃûBA \ No newline at end of file diff --git a/fuzz/fuzz_descriptor.c b/fuzz/fuzz_descriptor.c new file mode 100644 index 000000000..9be22f414 --- /dev/null +++ b/fuzz/fuzz_descriptor.c @@ -0,0 +1,82 @@ +#include +#include +#include +#include +#include + +static void test_fuzz_descriptor(const char *str, uint32_t network) +{ + struct wally_descriptor *desc = NULL; + int ret; + + ret = wally_descriptor_parse(str, NULL, network, 0, &desc); + if (desc) { + uint32_t features = 0; + wally_descriptor_get_features(desc, &features); + + /* Canonicalize - must not crash */ + char *canon = NULL; + wally_descriptor_canonicalize(desc, 0, &canon); + wally_free_string(canon); + + /* Checksum - must not crash */ + char *chk = NULL; + wally_descriptor_get_checksum(desc, 0, &chk); + wally_free_string(chk); + + /* Address derivation for indices 0 and 1 */ + if (ret == WALLY_OK) { + char *addr = NULL; + wally_descriptor_to_address(desc, 0, 0, 0, 0, &addr); + wally_free_string(addr); + addr = NULL; + wally_descriptor_to_address(desc, 0, 0, 1, 0, &addr); + wally_free_string(addr); + } + + /* If musig() is present, walk participant keys */ + if (features & WALLY_MS_IS_MUSIG) { + uint32_t num_keys = 0; + wally_descriptor_get_num_keys(desc, &num_keys); + if (num_keys > 16) + num_keys = 16; + for (size_t k = 0; k < num_keys; k++) { + size_t np = 0; + if (wally_descriptor_get_musig_num_participants(desc, k, &np) == WALLY_OK) { + if (np > 16) + np = 16; + for (size_t p = 0; p < np; p++) { + char *pkey = NULL; + wally_descriptor_get_musig_participant_key(desc, k, p, &pkey); + wally_free_string(pkey); + } + } + } + } + + wally_descriptor_free(desc); + } +} + +int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Treat input bytes as a NUL-terminated descriptor string */ + char *str = malloc(size + 1); + if (!str) + return 0; + memcpy(str, data, size); + str[size] = '\0'; + + /* Derive the network from the input so all variants are reachable + * without running the whole pipeline four times per input */ + static const uint32_t networks[] = { + WALLY_NETWORK_NONE, + WALLY_NETWORK_BITCOIN_MAINNET, + WALLY_NETWORK_BITCOIN_TESTNET, + WALLY_NETWORK_BITCOIN_REGTEST, + }; + test_fuzz_descriptor(str, networks[size ? data[0] & 3 : 0]); + + free(str); + return 0; +} diff --git a/fuzz/fuzz_psbt_from_bytes.c b/fuzz/fuzz_psbt_from_bytes.c index d08420425..307882251 100644 --- a/fuzz/fuzz_psbt_from_bytes.c +++ b/fuzz/fuzz_psbt_from_bytes.c @@ -7,6 +7,10 @@ static void test_fuzz_psbt_from_bytes(const uint8_t *data, size_t size, uint32_t ret = wally_psbt_from_bytes(data, size, flags, &psbt); if (psbt) { + /* Finalization decodes any witness/leaf scripts through the + * script-to-miniscript decoder and satisfier; exercise it on + * whatever inputs the parsed PSBT carries */ + wally_psbt_finalize(psbt, 0); if (ret == WALLY_OK && flags == WALLY_PSBT_PARSE_FLAG_STRICT) { /* Parsing succeeded: try to serialize it back to bytes */ size_t len = 0, written = 0; diff --git a/fuzz/fuzz_psbt_musig2.c b/fuzz/fuzz_psbt_musig2.c new file mode 100644 index 000000000..1db53d11e --- /dev/null +++ b/fuzz/fuzz_psbt_musig2.c @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include + +/* + * MuSig2 per-input PSBT field types (BIP-373): + * 0x1a = PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS key: type(1) + agg_pubkey(33) + * 0x1b = PSBT_IN_MUSIG2_PUB_NONCE key: type(1) + part_pubkey(33) + agg_pubkey(33) [+ leaf_hash(32)] + * 0x1c = PSBT_IN_MUSIG2_PARTIAL_SIG key: type(1) + part_pubkey(33) + agg_pubkey(33) [+ leaf_hash(32)] + * + * This fuzzer builds a minimal but structurally valid PSBT v0 frame and splices + * fuzz bytes into key-value pairs with each MuSig2 field type, specifically + * exercising the deserialization paths for types 0x1a, 0x1b, and 0x1c, with + * both the key-path (66-byte) and script-path (98-byte) compound key forms. + */ + +/* Minimal serialized tx: version=2, 1 input (all-zero txid), 1 output (0-val) */ +static const uint8_t s_minimal_tx[] = { + 0x02, 0x00, 0x00, 0x00, /* version=2 */ + 0x01, /* 1 input */ + /* txid (32 zero bytes) */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0x00, 0x00, 0x00, 0x00, /* vout=0 */ + 0x00, /* scriptSig len=0 */ + 0xff, 0xff, 0xff, 0xff, /* sequence=0xffffffff */ + 0x01, /* 1 output */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0 satoshis */ + 0x00, /* scriptPubKey len=0 */ + 0x00, 0x00, 0x00, 0x00 /* locktime=0 */ +}; + +/* PSBT magic: 0x70736274ff */ +static const uint8_t s_psbt_magic[] = {0x70, 0x73, 0x62, 0x74, 0xff}; + +/* Write a compact-size (varint) integer, return bytes written */ +static size_t write_varint(uint8_t *buf, uint64_t v) +{ + if (v < 0xfd) { + buf[0] = (uint8_t)v; + return 1; + } else if (v <= 0xffff) { + buf[0] = 0xfd; + buf[1] = (uint8_t)(v & 0xff); + buf[2] = (uint8_t)((v >> 8) & 0xff); + return 3; + } else { + buf[0] = 0xfe; + buf[1] = (uint8_t)(v & 0xff); + buf[2] = (uint8_t)((v >> 8) & 0xff); + buf[3] = (uint8_t)((v >> 16) & 0xff); + buf[4] = (uint8_t)((v >> 24) & 0xff); + return 5; + } +} + +/* Append a key-value pair to the output buffer, return new offset */ +static size_t append_kv(uint8_t *out, size_t off, + const uint8_t *key, size_t key_len, + const uint8_t *val, size_t val_len) +{ + off += write_varint(out + off, key_len); + memcpy(out + off, key, key_len); + off += key_len; + off += write_varint(out + off, val_len); + if (val_len && val) + memcpy(out + off, val, val_len); + off += val_len; + return off; +} + +/* + * Build a minimal PSBT frame and inject fuzz bytes as the value of a + * per-input key-value pair with the given MuSig2 field type. + * The key suffix (after the type byte) is filled from fuzz data or zeros. + */ +static void fuzz_musig2_field(const uint8_t *fuzz, size_t fuzz_size, + uint8_t field_type, size_t key_suffix_len) +{ + /* Build the key: type byte + key_suffix (from fuzz or zero-padded) */ + uint8_t key[100]; + key[0] = field_type; + size_t from_fuzz = fuzz_size < key_suffix_len ? fuzz_size : key_suffix_len; + if (from_fuzz) + memcpy(key + 1, fuzz, from_fuzz); + if (from_fuzz < key_suffix_len) + memset(key + 1 + from_fuzz, 0, key_suffix_len - from_fuzz); + + /* Value: fuzz bytes beyond the key suffix (may be empty) */ + const uint8_t *val = fuzz_size > key_suffix_len ? fuzz + key_suffix_len : NULL; + size_t val_len = fuzz_size > key_suffix_len ? fuzz_size - key_suffix_len : 0; + + /* Allocate output buffer: magic + global(~80) + input(keysize + valsize) + output + extra */ + size_t buf_cap = 5 + 5 + sizeof(s_minimal_tx) + 10 + + 5 + (1 + key_suffix_len) + 5 + val_len + 16; + uint8_t *buf = malloc(buf_cap); + if (!buf) + return; + + size_t off = 0; + + /* 1. Magic */ + memcpy(buf + off, s_psbt_magic, 5); + off += 5; + + /* 2. Global map: UNSIGNED_TX (key type = 0x00) */ + static const uint8_t unsigned_tx_key[] = {0x00}; + off = append_kv(buf, off, unsigned_tx_key, 1, + s_minimal_tx, sizeof(s_minimal_tx)); + buf[off++] = 0x00; /* end of global map */ + + /* 3. Input 0 map: inject MuSig2-typed key-value pair */ + off = append_kv(buf, off, key, 1 + key_suffix_len, val, val_len); + buf[off++] = 0x00; /* end of input 0 map */ + + /* 4. Output 0 map: empty */ + buf[off++] = 0x00; + + /* Feed to the parser */ + struct wally_psbt *psbt = NULL; + wally_psbt_from_bytes(buf, off, 0, &psbt); + if (psbt) + wally_psbt_free(psbt); + + psbt = NULL; + wally_psbt_from_bytes(buf, off, WALLY_PSBT_PARSE_FLAG_STRICT, &psbt); + if (psbt) + wally_psbt_free(psbt); + + free(buf); +} + +int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Exercise all MuSig2 per-input field type code paths, in both the + * key-path (participant+aggregate) and script-path (+leaf hash) forms */ + fuzz_musig2_field(data, size, 0x1a, 33); /* PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS */ + fuzz_musig2_field(data, size, 0x1b, 66); /* PSBT_IN_MUSIG2_PUB_NONCE */ + fuzz_musig2_field(data, size, 0x1b, 98); /* PSBT_IN_MUSIG2_PUB_NONCE + leaf hash */ + fuzz_musig2_field(data, size, 0x1c, 66); /* PSBT_IN_MUSIG2_PARTIAL_SIG */ + fuzz_musig2_field(data, size, 0x1c, 98); /* PSBT_IN_MUSIG2_PARTIAL_SIG + leaf hash */ + + return 0; +} diff --git a/include/wally.hpp b/include/wally.hpp index 49ddc1de4..1fa8db3fd 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. @@ -611,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); @@ -1246,6 +1285,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()); @@ -1435,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); @@ -1462,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); @@ -1474,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); @@ -1486,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()); @@ -1504,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); @@ -1618,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); @@ -1629,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); @@ -1641,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); @@ -1653,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()); @@ -1689,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); @@ -3376,6 +3727,7 @@ inline bool is_elements_build() return ret != 0; } + } /* namespace wally */ #endif /* LIBWALLY_CORE_WALLY_HPP */ diff --git a/include/wally_descriptor.h b/include/wally_descriptor.h index 552041d68..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 */ @@ -53,8 +54,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 +119,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, @@ -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/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/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 349401519..1faece57b 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 @@ -159,11 +160,15 @@ libwallycore_la_SOURCES = \ hmac.c \ internal.c \ map.c \ + miniscript_decode.c \ + miniscript_satisfy.c \ mnemonic.c \ + musig.c \ pbkdf2.c \ psbt.c \ pullpush.c \ script.c \ + script_iter.c \ scrypt.c \ sign.c \ symmetric.c \ @@ -191,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 \ @@ -278,6 +284,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 @@ -294,6 +308,22 @@ 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 +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 @@ -348,8 +378,12 @@ 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_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 @@ -375,6 +409,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 7952e1652..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 @@ -68,11 +75,15 @@ #include "src/hex_.c" #include "src/hmac.c" #include "src/map.c" +#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" #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..5c36da4c7 100644 --- a/src/ctest/_CMakeLists.txt +++ b/src/ctest/_CMakeLists.txt @@ -22,6 +22,16 @@ 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_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) @@ -43,6 +53,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_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/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/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/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/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/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 6df46ebfd..17cd4c4ac 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" @@ -10,6 +11,9 @@ #include #include #include +#ifndef BUILD_STANDARD_SECP +#include +#endif #ifdef BUILD_ELEMENTS #include #endif @@ -28,52 +32,11 @@ #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 */ #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 */ @@ -84,47 +47,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; @@ -192,41 +114,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; @@ -359,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) { @@ -764,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; @@ -961,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; @@ -976,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; @@ -2489,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"), @@ -2764,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; @@ -2847,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)); @@ -2872,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 @@ -2910,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; @@ -2947,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; @@ -3033,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)); @@ -3353,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 '{' */ @@ -3367,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) @@ -3464,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; @@ -4139,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) { @@ -4154,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 @@ -4190,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) { @@ -4221,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( @@ -4244,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; } @@ -4253,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( @@ -4281,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) @@ -4662,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 new file mode 100644 index 000000000..ac8dff0a5 --- /dev/null +++ b/src/descriptor_int.h @@ -0,0 +1,157 @@ +#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 */ + +/* 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) +#define KIND_DESCRIPTOR_MUSIG (0x00600000 | 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; + 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; + +/* 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/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/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 */ 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 */ 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/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>