sign_psbt: commit to the optional MUSIG2_SESSION_ID in psbt_session_id
What changed, and why it matters
This commit adds an optional 'session ID' field to MuSig2 multi-signature signing sessions in Ledger's Bitcoin app. Previously, the device could only track one unfinished signing session per wallet policy; starting a second one would overwrite the first. The change lets wallet software label each session with a unique ID so multiple signing rounds can run in parallel. It also rejects malformed IDs (empty or too long). This is a feature enhancement that reduces the chance of a wallet accidentally mixing up or losing in-flight signing sessions.
Review the new MUSIG2_SESSION_ID parsing for off-by-one and key-comparison issues; confirm that the proprietary key cannot be confused with other 0xFC keys; verify that hashing the user-controlled session ID into psbt_session_id does not introduce collision or malleability issues in the MuSig2 nonce/session state; and ensure documentation (doc/musig.md) is updated to describe the new field and its security assumptions.
Security signals we found
New PSBT global proprietary field parsing with explicit length bounds
Session identifier now commits to an externally-supplied value, expanding the collision domain
Malformed field values are rejected rather than ignored
Existing behavior preserved when the field is absent
Test coverage added for parallel sessions, session-id mismatch, and invalid lengths
Evidence from the diff
The patch introduces a new proprietary PSBT global field MUSIG2_SESSION_ID (key 0xFC || 0x11 || ‘MUSIG2_SESSION_ID’ || 0x00). When present, its value (1-32 bytes) is hashed into the deterministic psbt_session_id alongside the wallet policy descriptor template and keys merkle root. The session id derivation is changed from a single tagged hash to an incremental SHA256 update that includes the session ID length and value. A new error code EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID (0x0016) is returned if the field is empty or longer than 32 bytes. Tests are added/updated to verify parallel sessions, session ID consistency between round 1 and round 2, and rejection of invalid lengths.
Changed components
src/handler/sign_psbt/init_global_state.csrc/handler/sign_psbt/musig_signing.csrc/handler/sign_psbt/psbt_fields.csrc/handler/sign_psbt/psbt_fields.hsrc/handler/sign_psbt.hsrc/error_codes.htests/test_sign_psbt_musig.pyunit-tests/test_psbt_fields.cInspect captured patch +358 / −32
### src/error_codes.h
@@ -109,6 +109,9 @@
// proven amount shown to the user must be trustworthy, and external inputs cannot be signed.
#define EC_SIGN_PSBT_BIP322_EXTERNAL_INPUTS 0x0015
+// The MUSIG2_SESSION_ID global field is present, but its value is empty or longer than 32 bytes.
+#define EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID 0x0016
+
/**
* Swap
*/
### src/handler/sign_psbt.h
@@ -21,6 +21,7 @@
#include "display.h"
#include "merkle.h"
#include "musig_sessions.h"
+#include "psbt_fields.h"
// common info that applies to either the current input or the current output
typedef struct {
@@ -210,6 +211,14 @@ typedef struct {
// set to true if at least a PSBT_IN_MUSIG2_PUB_NONCE field is present in the PSBT
bool has_musig2_pub_nonces;
+ // set to true if the MUSIG2_SESSION_ID global field is present in the PSBT
+ bool has_musig2_session_id;
+
+ // The value of the MUSIG2_SESSION_ID global field in the PSBT
+ // musig2_session_id_len is 0 if absent.
+ uint8_t musig2_session_id[MAX_MUSIG2_SESSION_ID_LEN];
+ size_t musig2_session_id_len;
+
// aggregate info on outputs
struct {
uint64_t total_amount; // amount of all the outputs (external + change)
### src/handler/sign_psbt/init_global_state.c
@@ -130,13 +130,16 @@ static void global_map_keys_callback(dispatcher_context_t *dc,
if (data->size - data->offset == 1 &&
data->ptr[data->offset] == PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE) {
st->bip322.is_message_signing = true;
+ } else if (psbt_is_global_musig2_session_id_key(data->ptr + data->offset,
+ data->size - data->offset)) {
+ st->has_musig2_session_id = true;
}
}
/**
* Verifies the integrity of the PSBT global map (already committed to by
* st->global_map) and extracts the transaction-wide fields from it
- * (tx_version, fallback_locktime).
+ * (tx_version, fallback_locktime, musig2_session_id).
*
* Returns true on success; on failure, an error status word has already been
* sent.
@@ -146,8 +149,9 @@ static bool __attribute__((noinline)) process_global_map(dispatcher_context_t *d
// Check integrity of the global map (this also marks it as validated, so that its values may
// be read by key below).
// This also walks over all keys in the global map, keeping track of any fields
- // we care about tracking (currently, only the presence of a BIP-322 signature request)
+ // we care about tracking (the presence of a BIP-322 signature request, and a MuSig2 session id)
st->bip322.is_message_signing = false;
+ st->has_musig2_session_id = false;
if (call_check_merkleized_map_sorted_with_callback(dc,
&st->global_map,
st,
@@ -178,6 +182,19 @@ static bool __attribute__((noinline)) process_global_map(dispatcher_context_t *d
return false;
}
+ // Read the MuSig2 session id, if present.
+ // A malformed value is an error rather than being ignored.
+ st->musig2_session_id_len = 0;
+ if (st->has_musig2_session_id &&
+ PSBT_FIELD_PRESENT != psbt_get_global_musig2_session_id(dc,
+ &st->global_map,
+ st->musig2_session_id,
+ &st->musig2_session_id_len)) {
+ PRINTF("Invalid MUSIG2_SESSION_ID field\n");
+ SEND_SW_EC(dc, SW_INCORRECT_DATA, EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID);
+ return false;
+ }
+
return true;
}
### src/handler/sign_psbt/musig_signing.c
@@ -36,15 +36,18 @@
* The id identifies the session during both rounds of the protocol; it is the same for all the
* musig key expressions of the policy (if more than one), and for all the inputs of the psbt.
*
- * It deliberately depends only on the wallet policy, and _not_ on the transaction being signed.
- * That, together with the transaction-independent nonce derivation of musig_derive_nonce(), allows
- * a client to execute round 1 before knowing the transaction, storing the pubnonces for later use.
+ * It deliberately depends only on the wallet policy and on the optional MUSIG2_SESSION_ID field
+ * chosen by the software wallet, and _not_ on the transaction being signed. That, together with
+ * the transaction-independent nonce derivation of musig_derive_nonce(), allows a client to execute
+ * round 1 before knowing the transaction, storing the pubnonces for later use.
*
* The id commits to both the descriptor template and the keys of the policy, making sure that
* collisions are not possible for different wallet accounts.
- * However, this implies that at most one session can be pending for a wallet policy:
- * starting a new round 1 deletes the previous session, attempting to complete round 2 for a
- * deleted session results in failure, as the generated pubnonces do not match.
+ * Without a MUSIG2_SESSION_ID field, this implies that at most one session can be pending for a
+ * wallet policy: starting a new round 1 deletes the previous session, attempting to complete
+ * round 2 for a deleted session results in failure, as the generated pubnonces do not match.
+ * Software wallets that need multiple sessions in flight for the same wallet policy use a
+ * different MUSIG2_SESSION_ID for each of them.
*
* Software wallets are responsible for managing the state correctly.
*/
@@ -54,14 +57,20 @@ static void musig_compute_session_id(const sign_psbt_state_t *st, uint8_t out[st
LEDGER_ASSERT(st->account.wallet_header.version == WALLET_POLICY_VERSION_V2,
"MuSig2 requires a V2 wallet policy");
- crypto_tr_tagged_hash(
+ cx_sha256_t hash_context;
+ crypto_tr_tagged_hash_init(
+ &hash_context,
(uint8_t[]) {'P', 's', 'b', 't', 'S', 'e', 's', 's', 'i', 'o', 'n', 'I', 'd'},
- 13,
- st->account.wallet_header.descriptor_template_sha256,
- 32,
- st->account.wallet_header.keys_info_merkle_root,
- 32,
- out);
+ 13);
+ crypto_hash_update(&hash_context.header,
+ st->account.wallet_header.descriptor_template_sha256,
+ 32);
+ crypto_hash_update(&hash_context.header, st->account.wallet_header.keys_info_merkle_root, 32);
+ crypto_hash_update_u8(&hash_context.header, (uint8_t) st->musig2_session_id_len);
+ if (st->musig2_session_id_len > 0) {
+ crypto_hash_update(&hash_context.header, st->musig2_session_id, st->musig2_session_id_len);
+ }
+ crypto_hash_digest(&hash_context.header, out, 32);
}
bool compute_musig_per_input_info(dispatcher_context_t *dc,
### src/handler/sign_psbt/psbt_fields.c
@@ -32,28 +32,30 @@
/* -------------------------------------------------------------------------- */
/*
- * Every PSBT key handled here is a single key-type byte, and every field has a length policy (an
- * exact size, or a maximum). These helpers apply that policy on top of the raw map reader and
- * translate its outcome into a psbt_field_status_t, so the accessors below only have to name the
- * key type and the expected shape.
+ * Every PSBT key handled here is a single key-type byte (except proprietary keys, which are read
+ * with read_var_key), and every field has a length policy (an exact size, or a maximum). These
+ * helpers apply that policy on top of the raw map reader and translate its outcome into a
+ * psbt_field_status_t, so the accessors below only have to name the key type and the expected
+ * shape.
*
* The length policy is a PSBT-level concern, which is why these live here rather than alongside
* call_get_merkleized_map_value: the map layer has no opinion on how long a value ought to be.
*/
/**
- * Reads a value of variable length (up to `out_cap` bytes) into `out`, writing its length to
- * `*out_len`. A value longer than `out_cap` is reported as PSBT_FIELD_ERROR.
+ * Reads the value of the (possibly multi-byte) key `key` into `out`, up to `out_cap` bytes, writing
+ * its length to `*out_len`. A value longer than `out_cap` is reported as PSBT_FIELD_ERROR.
*
* On any non-PRESENT outcome `out` is left zeroed and `*out_len` is 0.
*/
-static psbt_field_status_t read_var(dispatcher_context_t *dc,
- const merkleized_map_commitment_t *map,
- uint8_t key_type,
- uint8_t *out,
- size_t out_cap,
- size_t *out_len) {
- int res = call_get_merkleized_map_value(dc, map, &key_type, 1, out, out_cap);
+static psbt_field_status_t read_var_key(dispatcher_context_t *dc,
+ const merkleized_map_commitment_t *map,
+ const uint8_t *key,
+ size_t key_len,
+ uint8_t *out,
+ size_t out_cap,
+ size_t *out_len) {
+ int res = call_get_merkleized_map_value(dc, map, key, key_len, out, out_cap);
if (res < 0) {
// on absent or error, zero out the output buffer and length,
// preventing the caller from possibly using uninitialized data
@@ -65,6 +67,21 @@ static psbt_field_status_t read_var(dispatcher_context_t *dc,
return PSBT_FIELD_PRESENT;
}
+/**
+ * Reads a value of variable length (up to `out_cap` bytes) into `out`, writing its length to
+ * `*out_len`. A value longer than `out_cap` is reported as PSBT_FIELD_ERROR.
+ *
+ * On any non-PRESENT outcome `out` is left zeroed and `*out_len` is 0.
+ */
+static psbt_field_status_t read_var(dispatcher_context_t *dc,
+ const merkleized_map_commitment_t *map,
+ uint8_t key_type,
+ uint8_t *out,
+ size_t out_cap,
+ size_t *out_len) {
+ return read_var_key(dc, map, &key_type, 1, out, out_cap, out_len);
+}
+
/**
* Reads a value that must be exactly `len` bytes into `out`. A present value of any other length
* is malformed, hence PSBT_FIELD_ERROR.
@@ -132,6 +149,38 @@ psbt_field_status_t psbt_get_global_fallback_locktime(dispatcher_context_t *dc,
return read_u32_le_field(dc, global_map, PSBT_GLOBAL_FALLBACK_LOCKTIME, out);
}
+// Proprietary key with identifier "MUSIG2_SESSION_ID", subtype 0 and no keydata
+// clang-format off
+static const uint8_t PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY[] = {
+ PSBT_GLOBAL_PROPRIETARY,
+ 17, // length of the identifier
+ 'M', 'U', 'S', 'I', 'G', '2', '_', 'S', 'E', 'S', 'S', 'I', 'O', 'N', '_', 'I', 'D',
+ 0x00 // subtype
+};
+// clang-format on
+
+bool psbt_is_global_musig2_session_id_key(const uint8_t *key, size_t key_len) {
+ return key_len == sizeof(PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY) &&
+ memcmp(key, PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY, key_len) == 0;
+}
+
+psbt_field_status_t psbt_get_global_musig2_session_id(dispatcher_context_t *dc,
+ const merkleized_map_commitment_t *global_map,
+ uint8_t out[static MAX_MUSIG2_SESSION_ID_LEN],
+ size_t *out_len) {
+ psbt_field_status_t status = read_var_key(dc,
+ global_map,
+ PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY,
+ sizeof(PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY),
+ out,
+ MAX_MUSIG2_SESSION_ID_LEN,
+ out_len);
+ if (status == PSBT_FIELD_PRESENT && *out_len == 0) {
+ return PSBT_FIELD_ERROR;
+ }
+ return status;
+}
+
/* -------------------------------------------------------------------------- */
/* Input map */
/* -------------------------------------------------------------------------- */
### src/handler/sign_psbt/psbt_fields.h
@@ -70,6 +70,25 @@ psbt_field_status_t psbt_get_global_fallback_locktime(dispatcher_context_t *dc,
const merkleized_map_commitment_t *global_map,
uint32_t *out);
+// Maximum length of the value of the MUSIG2_SESSION_ID field
+#define MAX_MUSIG2_SESSION_ID_LEN 32
+
+/**
+ * Returns true if `key` is the key of the MUSIG2_SESSION_ID field: the proprietary key with
+ * identifier "MUSIG2_SESSION_ID", subtype 0 and no keydata.
+ */
+bool psbt_is_global_musig2_session_id_key(const uint8_t *key, size_t key_len);
+
+/**
+ * MUSIG2_SESSION_ID: optional proprietary field, between 1 and MAX_MUSIG2_SESSION_ID_LEN bytes,
+ * chosen by the software wallet to identify the MuSig2 signing session. See doc/musig.md.
+ * An empty or too long value is reported as PSBT_FIELD_ERROR.
+ */
+psbt_field_status_t psbt_get_global_musig2_session_id(dispatcher_context_t *dc,
+ const merkleized_map_commitment_t *global_map,
+ uint8_t out[static MAX_MUSIG2_SESSION_ID_LEN],
+ size_t *out_len);
+
/* -------------------------------------------------------------------------- */
/* Input map */
/* -------------------------------------------------------------------------- */
### tests/test_sign_psbt_musig.py
@@ -3,7 +3,7 @@
from hashlib import sha256
import hmac
-from typing import Dict, Optional, Tuple
+from typing import Dict, List, Optional, Tuple
import pytest
@@ -26,6 +26,9 @@
tests_root: Path = Path(__file__).parent
+# error codes, see src/error_codes.h
+EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID = 0x0016
+
# for now, we assume that there's a single internal musig placeholder, with a single internal key
class LedgerMusig2Cosigner(PsbtMusig2Cosigner):
@@ -313,10 +316,11 @@ def test_sign_psbt_musig2_scriptpath_round1_on_another_transaction(navigator: Na
run_musig2_test(wallet_policy, psbt, [signer_1, signer_2], SCRIPTPATH_SIGHASHES)
-def test_sign_psbt_musig2_round1_twice_replaces_session(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+@pytest.mark.parametrize("musig2_session_id", [None, b"\x42" * 32])
+def test_sign_psbt_musig2_round1_twice_replaces_session(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals, musig2_session_id: Optional[bytes]):
# Since the psbt_session_id does not depend on the transaction, a second round 1 for the same
- # wallet policy (on any transaction) replaces the pending session: round 2 with the pubnonces
- # of the first round 1 must then fail.
+ # wallet policy (on any transaction) and the same MUSIG2_SESSION_ID (or none) replaces the
+ # pending session: round 2 with the pubnonces of the first round 1 must then fail.
wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
signer_1 = LedgerMusig2Cosigner(client, wallet_policy, wallet_hmac,
@@ -325,11 +329,13 @@ def test_sign_psbt_musig2_round1_twice_replaces_session(navigator: Navigator, fi
psbt = PSBT()
psbt.deserialize(KEYPATH_PSBT_B64)
+ psbt.musig2_session_id = musig2_session_id
signer_1.generate_public_nonces(psbt)
signer_2.generate_public_nonces(psbt)
other_psbt = PSBT()
other_psbt.deserialize(KEYPATH_PSBT_B64)
+ other_psbt.musig2_session_id = musig2_session_id
other_psbt.tx.vout[0].nValue += 1000
other_psbt.tx.rehash()
signer_1.generate_public_nonces(other_psbt)
@@ -512,3 +518,114 @@ def copy_psbt(psbt: PSBT) -> PSBT:
signer_1.generate_partial_signatures(psbt)
assert DeviceException.exc.get(e.value.status) == BadStateError
assert len(psbt.inputs[0].musig2_partial_sigs) == 0
+
+
+class Round2OnlyCosigner(PsbtMusig2Cosigner):
+ """
+ Wraps a cosigner that already added its pubnonces to the psbt: only round 2 is executed.
+ """
+
+ def __init__(self, cosigner: PsbtMusig2Cosigner) -> None:
+ super().__init__()
+ self.cosigner = cosigner
+
+ def get_participant_pubkey(self) -> bip0327.Point:
+ return self.cosigner.get_participant_pubkey()
+
+ def generate_public_nonces(self, psbt: PSBT) -> None:
+ pass
+
+ def generate_partial_signatures(self, psbt: PSBT) -> None:
+ self.cosigner.generate_partial_signatures(psbt)
+
+
+class Round1OnOtherPsbtCosigner(PsbtMusig2Cosigner):
+ """
+ Not a real cosigner: when asked for its pubnonces, it makes the given cosigners execute round 1
+ on a different psbt instead. Used to interleave the rounds of different signing sessions.
+ """
+
+ def __init__(self, other_psbt: PSBT, cosigners: List[PsbtMusig2Cosigner]) -> None:
+ super().__init__()
+ self.other_psbt = other_psbt
+ self.cosigners = cosigners
+
+ def get_participant_pubkey(self) -> bip0327.Point:
+ return self.cosigners[0].get_participant_pubkey()
+
+ def generate_public_nonces(self, psbt: PSBT) -> None:
+ for cosigner in self.cosigners:
+ cosigner.generate_public_nonces(self.other_psbt)
+
+ def generate_partial_signatures(self, psbt: PSBT) -> None:
+ pass
+
+
+def test_sign_psbt_musig2_parallel_sessions(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+ # With different MUSIG2_SESSION_IDs, multiple sessions can be pending for the same wallet
+ # policy: round 1 for one of them does not replace the other, and each of them completes.
+ wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
+
+ signer_1 = LedgerMusig2Cosigner(client, wallet_policy, wallet_hmac,
+ navigator=navigator, instructions=sign_psbt_instruction_approve(firmware, save_screenshot=False, has_spend_from_wallet=True, has_feewarning=True), testname=test_name)
+
+ # The two psbts only differ in the MUSIG2_SESSION_ID, therefore they have the same sighashes.
+ # The hot cosigner identifies its sessions by the transaction, so each psbt needs its own.
+ psbt_a = PSBT()
+ psbt_a.deserialize(KEYPATH_PSBT_B64)
+ psbt_a.musig2_session_id = b"\x01" * 32
+ signer_2_a = HotMusig2Cosigner(wallet_policy, KEYPATH_COSIGNER_2_XPRIV)
+
+ psbt_b = PSBT()
+ psbt_b.deserialize(KEYPATH_PSBT_B64)
+ psbt_b.musig2_session_id = b"\x02"
+ signer_2_b = HotMusig2Cosigner(wallet_policy, KEYPATH_COSIGNER_2_XPRIV)
+
+ # Round 1 for psbt_a, then round 1 for psbt_b, then round 2 for psbt_a
+ interloper = Round1OnOtherPsbtCosigner(psbt_b, [signer_1, signer_2_b])
+ run_musig2_test(wallet_policy, psbt_a, [signer_1, interloper, signer_2_a], KEYPATH_SIGHASHES)
+
+ # Round 2 for psbt_b
+ assert psbt_b.inputs[0].musig2_pub_nonces != psbt_a.inputs[0].musig2_pub_nonces
+ run_musig2_test(wallet_policy, psbt_b,
+ [Round2OnlyCosigner(signer_1), Round2OnlyCosigner(signer_2_b)], KEYPATH_SIGHASHES)
+
+
+@pytest.mark.parametrize("round2_session_id", [None, b"\x01" * 31, b"\x02" * 32])
+def test_sign_psbt_musig2_session_id_must_not_change(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals, round2_session_id: Optional[bytes]):
+ # The MUSIG2_SESSION_ID identifies the session: if it changes between round 1 and round 2
+ # (including if it is removed), the device finds no pending session for round 2.
+ wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
+
+ signer_1 = LedgerMusig2Cosigner(client, wallet_policy, wallet_hmac,
+ navigator=navigator, instructions=sign_psbt_instruction_approve(firmware, save_screenshot=False, has_spend_from_wallet=True, has_feewarning=True), testname=test_name)
+ signer_2 = HotMusig2Cosigner(wallet_policy, KEYPATH_COSIGNER_2_XPRIV)
+
+ psbt = PSBT()
+ psbt.deserialize(KEYPATH_PSBT_B64)
+ psbt.musig2_session_id = b"\x01" * 32
+ signer_1.generate_public_nonces(psbt)
+ signer_2.generate_public_nonces(psbt)
+
+ psbt.musig2_session_id = round2_session_id
+ with pytest.raises(ExceptionRAPDU) as e:
+ signer_1.generate_partial_signatures(psbt)
+ assert DeviceException.exc.get(e.value.status) == BadStateError
+ assert len(psbt.inputs[0].musig2_partial_sigs) == 0
+
+
+@pytest.mark.parametrize("musig2_session_id", [b"", b"\x01" * 33])
+def test_sign_psbt_musig2_invalid_session_id(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals, musig2_session_id: bytes):
+ # An empty or too long MUSIG2_SESSION_ID is rejected, rather than ignored
+ wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
+
+ psbt = PSBT()
+ psbt.deserialize(KEYPATH_PSBT_B64)
+ psbt.musig2_session_id = musig2_session_id
+
+ with pytest.raises(ExceptionRAPDU) as e:
+ client.sign_psbt(psbt, wallet_policy, wallet_hmac, navigator,
+ instructions=sign_psbt_instruction_approve(firmware, save_screenshot=False, has_spend_from_wallet=True, has_feewarning=True),
+ testname=test_name)
+ assert DeviceException.exc.get(e.value.status) == IncorrectDataError
+ assert int.from_bytes(e.value.data, byteorder='big') == EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID
### unit-tests/test_psbt_fields.c
@@ -633,6 +633,104 @@ static void test_witness_utxo_amount_too_short_is_error(void **state) {
assert_int_equal(got, 0xCAFEBABEu);
}
+/* ---------- MUSIG2_SESSION_ID (optional, proprietary key) ---------- */
+
+static const uint8_t MUSIG2_SESSION_ID_KEY[] = {0xFC, 0x11, 'M', 'U', 'S', 'I', 'G',
+ '2', '_', 'S', 'E', 'S', 'S', 'I',
+ 'O', 'N', '_', 'I', 'D', 0x00};
+
+/** Registers a map holding a single MUSIG2_SESSION_ID field and returns its commitment. */
+static void map_with_musig2_session_id(mock_dispatcher_t *mock,
+ const uint8_t *value,
+ size_t value_len,
+ merkleized_map_commitment_t *out) {
+ const uint8_t *keys[] = {MUSIG2_SESSION_ID_KEY};
+ const size_t key_lens[] = {sizeof(MUSIG2_SESSION_ID_KEY)};
+ const uint8_t *values[] = {value};
+ const size_t value_lens[] = {value_len};
+
+ mock_dispatcher_add_map(mock, keys, key_lens, values, value_lens, 1, out);
+}
+
+static void test_musig2_session_id_key(void **state) {
+ (void) state;
+
+ assert_true(
+ psbt_is_global_musig2_session_id_key(MUSIG2_SESSION_ID_KEY, sizeof(MUSIG2_SESSION_ID_KEY)));
+
+ /* keydata, a different subtype, or a truncated key are not the MUSIG2_SESSION_ID key */
+ uint8_t key[sizeof(MUSIG2_SESSION_ID_KEY) + 1];
+ memcpy(key, MUSIG2_SESSION_ID_KEY, sizeof(MUSIG2_SESSION_ID_KEY));
+ key[sizeof(MUSIG2_SESSION_ID_KEY)] = 0x00;
+ assert_false(psbt_is_global_musig2_session_id_key(key, sizeof(key)));
+ key[sizeof(MUSIG2_SESSION_ID_KEY) - 1] = 0x01;
+ assert_false(psbt_is_global_musig2_session_id_key(key, sizeof(MUSIG2_SESSION_ID_KEY)));
+ assert_false(psbt_is_global_musig2_session_id_key(MUSIG2_SESSION_ID_KEY,
+ sizeof(MUSIG2_SESSION_ID_KEY) - 1));
+}
+
+static void test_musig2_session_id_present(void **state) {
+ mock_dispatcher_t *mock = *state;
+
+ for (size_t len = 1; len <= MAX_MUSIG2_SESSION_ID_LEN; len += MAX_MUSIG2_SESSION_ID_LEN - 1) {
+ merkleized_map_commitment_t map;
+ uint8_t value[MAX_MUSIG2_SESSION_ID_LEN];
+ memset(value, 0x42, sizeof(value));
+ map_with_musig2_session_id(mock, value, len, &map);
+
+ uint8_t got[MAX_MUSIG2_SESSION_ID_LEN];
+ size_t got_len = 0;
+ psbt_field_status_t status =
+ psbt_get_global_musig2_session_id(mock_dispatcher_get_dc(mock), &map, got, &got_len);
+ assert_int_equal(status, PSBT_FIELD_PRESENT);
+ assert_int_equal(got_len, len);
+ assert_memory_equal(got, value, len);
+ }
+}
+
+static void test_musig2_session_id_absent(void **state) {
+ mock_dispatcher_t *mock = *state;
+ merkleized_map_commitment_t map;
+ map_without_field(mock, &map);
+
+ uint8_t got[MAX_MUSIG2_SESSION_ID_LEN];
+ size_t got_len = 0;
+ psbt_field_status_t status =
+ psbt_get_global_musig2_session_id(mock_dispatcher_get_dc(mock), &map, got, &got_len);
+ assert_int_equal(status, PSBT_FIELD_ABSENT);
+ assert_int_equal(got_len, 0);
+}
+
+static void test_musig2_session_id_empty_is_error(void **state) {
+ mock_dispatcher_t *mock = *state;
+ merkleized_map_commitment_t map;
+ map_with_musig2_session_id(mock, (const uint8_t *) "", 0, &map);
+
+ uint8_t got[MAX_MUSIG2_SESSION_ID_LEN];
+ size_t got_len = 0;
+ psbt_field_status_t status =
+ psbt_get_global_musig2_session_id(mock_dispatcher_get_dc(mock), &map, got, &got_len);
+ assert_int_equal(status, PSBT_FIELD_ERROR);
+ assert_int_equal(got_len, 0);
+}
+
+static void test_musig2_session_id_too_long_is_error(void **state) {
+ mock_dispatcher_t *mock = *state;
+ merkleized_map_commitment_t map;
+ uint8_t too_long[MAX_MUSIG2_SESSION_ID_LEN + 1];
+ memset(too_long, 0x42, sizeof(too_long));
+ map_with_musig2_session_id(mock, too_long, sizeof(too_long), &map);
+
+ uint8_t got[MAX_MUSIG2_SESSION_ID_LEN];
+ memset(got, 0xAA, sizeof(got));
+ size_t got_len = 0;
+ psbt_field_status_t status =
+ psbt_get_global_musig2_session_id(mock_dispatcher_get_dc(mock), &map, got, &got_len);
+ assert_int_equal(status, PSBT_FIELD_ERROR);
+ assert_int_equal(got_len, 0);
+ assert_cleared(got, sizeof(got));
+}
+
/* ---------- Main ---------- */
int main(void) {
@@ -670,6 +768,11 @@ int main(void) {
T(test_witness_utxo_amount_present),
T(test_witness_utxo_amount_absent),
T(test_witness_utxo_amount_too_short_is_error),
+ T(test_musig2_session_id_key),
+ T(test_musig2_session_id_present),
+ T(test_musig2_session_id_absent),
+ T(test_musig2_session_id_empty_is_error),
+ T(test_musig2_session_id_too_long_is_error),
};
#undef T
Why this scored 34/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.