Merge pull request #576 from LedgerHQ/musig2_improvements
What changed, and why it matters
This commit improves the Ledger Bitcoin app's MuSig2 multi-signature feature. It lets wallet software pre-generate public nonces before a transaction is known, adds an optional MUSIG2_SESSION_ID field so multiple signing sessions can be in flight for the same wallet, and increases the stored session limit from 8 to 32. It also adds early checks so the device fails fast if a Round 2 session is missing, and rejects malformed session IDs. The changes are defensive and do not appear to introduce a vulnerability.
No immediate security action required. This is a feature and hardening patch. Reviewers may want to confirm that the 28-byte stored id prefix does not meaningfully increase collision risk in practice, and that LRU eviction cannot be abused to force deletion of another wallet's session.
Security signals we found
New PSBT proprietary field parsing with length validation (1-32 bytes, empty rejected)
Session ID now commits to wallet policy plus optional MUSIG2_SESSION_ID
Session storage limit raised from 8 to 32 with LRU eviction
Early missing-session check before transaction review/user approval
New explicit error codes for invalid session ID and missing session
Extensive unit and integration tests added for new behavior
Evidence from the diff
The merge commit refactors MuSig2 session handling. The psbt_session_id now hashes in an optional global proprietary PSBT field MUSIG2_SESSION_ID (1-32 bytes), enabling parallel sessions per wallet policy. Session storage was restructured to a 64-byte slot holding a 28-byte id prefix, a counter for LRU eviction, and the 32-byte rand_root, raising MAX_N_MUSIG_SESSIONS from 8 to 32. New error codes EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID and EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND are introduced, and sign_psbt.c now calls musig_check_round2_session before user review to fail early on missing sessions. The Python client and tests are updated to parse and round-trip the new field.
Changed components
src/handler/sign_psbt.csrc/handler/sign_psbt.hsrc/handler/sign_psbt/init_global_state.csrc/handler/sign_psbt/musig_signing.csrc/handler/sign_psbt/musig_signing.hsrc/handler/sign_psbt/psbt_fields.csrc/handler/sign_psbt/psbt_fields.hsrc/musig/musig_sessions.csrc/musig/musig_sessions.hsrc/error_codes.hbitcoin_client/ledger_bitcoin/psbt.pydoc/musig.mdInspect captured patch +710 / −72
### CHANGELOG.md
@@ -16,7 +16,8 @@ Dates are in `dd-mm-yyyy` format.
### Changed
- MuSig2: the pubnonces no longer depend on the transaction, so they can be pre-generated before the transaction is known. See [doc/musig.md](doc/musig.md).
-- MuSig2 (breaking): as a consequence, at most one signing session can be pending for a given wallet policy; executing round 1 again for the same wallet policy discards the previous session, and round 2 with the old pubnonces fails.
+- MuSig2 (breaking): as a consequence, at most one signing session can be pending for a given wallet policy; executing round 1 again for the same wallet policy discards the previous session, and round 2 with the old pubnonces fails. In order to allow software wallets to manage multiple simultaneous sessions for the same wallet policy, this version adds support for a `MUSIG2_SESSION_ID` proprietary PSBT field. See [doc/musig.md](doc/musig.md) for more info.
+- MuSig2: up to 32 signing sessions can be pending (previously 8); when the storage is full, the oldest one is evicted.
### Fixed
### bitcoin_client/ledger_bitcoin/psbt.py
@@ -775,6 +775,9 @@ class PSBT(object):
PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE = 0x09
PSBT_GLOBAL_VERSION = 0xFB
+ # Proprietary key (BIP-174) with identifier "MUSIG2_SESSION_ID", subtype 0 and no keydata
+ PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY = b"\xfc" + ser_compact_size(17) + b"MUSIG2_SESSION_ID" + ser_compact_size(0)
+
def __init__(self, tx: Optional[CTransaction] = None) -> None:
"""
:param tx: A Bitcoin transaction that specifies the inputs and outputs to use
@@ -792,6 +795,11 @@ def __init__(self, tx: Optional[CTransaction] = None) -> None:
self.tx_modifiable: Optional[int] = None
# BIP-322: the message of a generic signed message request (allowed in any PSBT version)
self.generic_signed_message: Optional[bytes] = None
+ # MuSig2: the session id chosen by the software wallet (allowed in any PSBT version).
+ # A signer identifies its pending MuSig2 session by it, so the PSBT given to a signer in
+ # round 2 must have the value used for that signer in round 1. It is not part of the
+ # transaction: each signer can use its own value, in its own copy of the PSBT.
+ self.musig2_session_id: Optional[bytes] = None
# Assume version 0 PSBT
self.version = 0
@@ -907,6 +915,10 @@ def deserialize(self, psbt: str) -> None:
raise PSBTSerializationError("Global PSBT version is not 1 bytes")
self.version = struct.unpack("<I", v)[0]
self.explicit_version = True
+ elif key == PSBT.PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY:
+ if key in key_lookup:
+ raise PSBTSerializationError("Duplicate key, global MuSig2 session id is already provided")
+ self.musig2_session_id = deser_string(f)
else:
if key in self.unknown:
raise PSBTSerializationError("Duplicate key, key for unknown value already provided")
@@ -1035,6 +1047,10 @@ def serialize(self) -> str:
r += ser_string(ser_compact_size(PSBT.PSBT_GLOBAL_VERSION))
r += ser_string(struct.pack("<I", self.version))
+ if self.musig2_session_id is not None:
+ r += ser_string(PSBT.PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY)
+ r += ser_string(self.musig2_session_id)
+
# unknowns
for key, value in sorted(self.unknown.items()):
r += ser_string(key)
### bitcoin_client/tests/test_psbt_musig2_session_id.py
@@ -0,0 +1,82 @@
+import pytest
+
+from bitcoin_client.ledger_bitcoin.errors import PSBTSerializationError
+from bitcoin_client.ledger_bitcoin.psbt import PSBT, PartiallySignedInput, PartiallySignedOutput
+from bitcoin_client.ledger_bitcoin.tx import CTransaction, CTxIn, CTxOut, COutPoint
+
+
+MUSIG2_SESSION_ID_KEY = bytes.fromhex("fc11") + b"MUSIG2_SESSION_ID" + b"\x00"
+
+
+def make_psbt(session_id=None) -> PSBT:
+ """A PSBTv0 with one input and one output."""
+ tx = CTransaction()
+ tx.vin = [CTxIn(COutPoint(1, 0), b"", 0)]
+ tx.vout = [CTxOut(0, b"\x6a")]
+
+ psbt = PSBT(tx)
+ psbt.inputs = [PartiallySignedInput(0)]
+ psbt.outputs = [PartiallySignedOutput(0)]
+ psbt.musig2_session_id = session_id
+ return psbt
+
+
+def roundtrip(psbt: PSBT) -> PSBT:
+ result = PSBT()
+ result.deserialize(psbt.serialize())
+ return result
+
+
+def test_musig2_session_id_key():
+ assert PSBT.PSBT_GLOBAL_MUSIG2_SESSION_ID_KEY == MUSIG2_SESSION_ID_KEY
+ assert len(MUSIG2_SESSION_ID_KEY) == 20
+
+
+@pytest.mark.parametrize("session_id", [bytes(range(32)), b"\x01"])
+def test_musig2_session_id_roundtrip(session_id: bytes):
+ """The MUSIG2_SESSION_ID proprietary field is kept in both PSBT versions."""
+ psbt = make_psbt(session_id)
+
+ psbt_v0 = roundtrip(psbt)
+ assert psbt_v0.version == 0
+ assert psbt_v0.musig2_session_id == session_id
+ assert psbt_v0.unknown == {}
+
+ psbt_v0.convert_to_v2()
+ psbt_v2 = roundtrip(psbt_v0)
+ assert psbt_v2.version == 2
+ assert psbt_v2.musig2_session_id == session_id
+
+ psbt_v2.convert_to_v0()
+ assert roundtrip(psbt_v2).musig2_session_id == session_id
+
+
+def test_musig2_session_id_absent():
+ psbt = roundtrip(make_psbt())
+ assert psbt.musig2_session_id is None
+
+
+def test_musig2_session_id_set_as_unknown():
+ # a field set by a tool that does not know about it is parsed as well
+ psbt = make_psbt()
+ psbt.unknown[MUSIG2_SESSION_ID_KEY] = b"\x42" * 32
+ psbt = roundtrip(psbt)
+ assert psbt.musig2_session_id == b"\x42" * 32
+ assert psbt.unknown == {}
+
+
+def test_musig2_session_id_other_proprietary_keys():
+ # different subtype or keydata: not the MUSIG2_SESSION_ID field
+ psbt = make_psbt()
+ psbt.unknown[MUSIG2_SESSION_ID_KEY[:-1] + b"\x01"] = b"\x42"
+ psbt.unknown[MUSIG2_SESSION_ID_KEY + b"\x00"] = b"\x43"
+ psbt = roundtrip(psbt)
+ assert psbt.musig2_session_id is None
+ assert len(psbt.unknown) == 2
+
+
+def test_musig2_session_id_duplicate_key():
+ psbt = make_psbt(b"\x42" * 32)
+ psbt.unknown[MUSIG2_SESSION_ID_KEY] = b"\x43" * 32
+ with pytest.raises(PSBTSerializationError):
+ roundtrip(psbt)
### doc/musig.md
@@ -10,7 +10,8 @@ MuSig2 is a 2-round multi-signature scheme compatible with the public keys and s
- At most 5 keys are allowed in the musig expression; performance limitations, however, might apply in practice.
- `musig(...)` is allowed among the key expressions of `multi_a`, but not of `sortedmulti_a`.
-- At most 8 MuSig2 signing sessions can be pending at the same time, due to the need to persist state in the device's memory; moreover, at most one session can be pending for each wallet policy (see [below](#generalization-to-multiple-psbt-signing-sessions)).
+- At most 32 MuSig2 signing sessions can be pending at the same time, due to the need to persist state in the device's memory; when the storage is full, starting a new session evicts the oldest one.
+- By default, at most one session can be pending for each wallet policy. Software wallets that need multiple transactions in flight for the same wallet policy can identify each session with the [`MUSIG2_SESSION_ID`](#the-musig2_session_id-psbt-field) PSBT field (see [below](#generalization-to-multiple-psbt-signing-sessions)).
- The pubnonces can be generated before the transaction is known, and then used for a different transaction than the one given to the device in round 1 (see [below](#pre-generating-the-pubnonces)).
- Only `musig(...)/**` or `musig(...)/<M;N>/*` key expressions are supported; the public keys must be xpubs aggregated without any further derivation. Schemes where each pubkey is derived prior to aggregation (for example descriptors similar to `musig(xpub1/<0;1>/*,xpub2/<0;1>/*,...)`) are not supported.
@@ -95,18 +96,39 @@ The approach described above assumes that no attempt to sign a PSBT for a wallet
In order to generalize this to multiple parallel signing sessions, each signing session is identified by a `psbt_session_id`, which must be identical between Round 1 and Round 2 of the protocol. The device computes it as:
-$\qquad psbt\_session\_id = H_{PsbtSessionId}(descriptor\_template\_hash \| keys\_info\_merkle\_root)$
+$\qquad psbt\_session\_id = H_{PsbtSessionId}(descriptor\_template\_hash \| keys\_info\_merkle\_root \| len(session\_id) \| session\_id)$
-where $H_{tag}$ is the BIP-0340 tagged hash, and the two arguments are the hash of the descriptor template and the root of the Merkle tree of the keys information of the wallet policy. The name of the wallet policy is not committed to, as it plays no role in signing.
+where $H_{tag}$ is the BIP-0340 tagged hash, the first two arguments are the hash of the descriptor template and the root of the Merkle tree of the keys information of the wallet policy, $session\_id$ is the value of the [`MUSIG2_SESSION_ID`](#the-musig2_session_id-psbt-field) field (empty if the PSBT does not contain the field), and $len(session\_id)$ is its length as a single byte (`0x00` if the field is absent). The name of the wallet policy is not committed to, as it plays no role in signing.
-The `psbt_session_id` deliberately depends only on the wallet policy, and not on the transaction; together with the transaction-independent arguments of _NonceGen_, this is what allows [pre-generating the pubnonces](#pre-generating-the-pubnonces). The tradeoff is that at most one session can be pending for each wallet policy; the device can store up to 8 sessions, each for a different wallet policy.
+The `psbt_session_id` deliberately depends only on the wallet policy and on the `MUSIG2_SESSION_ID`, and not on the transaction; together with the transaction-independent arguments of _NonceGen_, this is what allows [pre-generating the pubnonces](#pre-generating-the-pubnonces). The tradeoff is that, without a `MUSIG2_SESSION_ID`, at most one session can be pending for each wallet policy.
+
+The device can store up to 32 sessions.
Collisions of the `psbt_session_id` do not constitute a security risk: they only cause the previous session to be deleted, and the following Phase 2 to fail.
+### The `MUSIG2_SESSION_ID` PSBT field
+
+`MUSIG2_SESSION_ID` is an optional global PSBT field that lets a software wallet keep multiple MuSig2 signing sessions in flight for the same wallet policy. It is a [BIP-0174](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki) proprietary field.
+
+| Key | Value |
+|-----|-------|
+| `0xFC` | `0x11` | `"MUSIG2_SESSION_ID"` | `0x00` (proprietary type, identifier length, identifier, subtype 0; no keydata) | The session id: between 1 and 32 bytes |
+
+- The field is optional. If it is absent, the behavior is the same as in the versions of the app that do not support it: wallets that do not need multiple sessions for the same wallet policy can ignore it.
+- The `psbt_session_id` commits to its value, so that sessions with different values are independent. The value must be the same in Phase 1 and Phase 2; otherwise, the device does not find the session in Phase 2.
+- Executing Phase 1 again with the same value replaces the pending session for that value.
+- A present but empty value, or a value longer than 32 bytes, is rejected (error code `EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID`).
+- Wallets should use a unique value for each session. The value is not secret.
+- The value is only meaningful to the device that receives the PSBT, and it is not part of the transaction: each signer's software wallet sets it, in its own copy of the PSBT, to the value it used in its own Phase 1. Different signers do not need to agree on a value, and the value does not need to be shared with the other signers.
+
### Pre-generating the pubnonces
Since neither the pubnonces nor the `psbt_session_id` depend on the transaction, a software wallet can execute Phase 1 before the transaction is known, for example while the device happens to be connected. It can then use the pubnonces returned by the device for a different transaction, provided that:
-- the transaction is for the same wallet policy, and no other Phase 1 or Phase 2 for that wallet policy was executed in the meantime;
+- the transaction is for the same wallet policy and has the same `MUSIG2_SESSION_ID` (or none), no other Phase 1 or Phase 2 for that wallet policy and `MUSIG2_SESSION_ID` was executed in the meantime, and the session was not evicted because the storage was full (see [above](#specs));
- all inputs are internal, and the PSBT used in Phase 1 has at least as many inputs as the PSBT used in Phase 2, and each pubnonce is put in the Phase 2 PSBT under the key (of the `PSBT_IN_MUSIG2_PUB_NONCE` field) computed for the new transaction. This key contains the aggregate public key _after_ the tweaks, and, for script path spends, the tapleaf hash; therefore, it depends on the transaction, not merely on the input's position.
More generally, this can also work when some inputs are not internal, as long as for each internal input of the PSBT used in Phase 2, there is a corresponding internal input in the PSBT used in Phase 1.
+
+Phase 1 does not require any user interaction, while Phase 2 requires the user to review the transaction. Therefore, with pubnonces generated in advance, signing a transaction only takes a single interaction per signer, like for a non-MuSig2 multisig.
+
+If the wallet policy also contains keys of the device outside of `musig()` key expressions (for example, in `tr(musig(@0,@1)/**,pk(@2/**))`, where `@0` and `@2` are keys of the device), the device also signs for those keys, and therefore asks the user to review the transaction, whenever the PSBT contains their key derivations (`PSBT_IN_BIP32_DERIVATION` or `PSBT_IN_TAP_BIP32_DERIVATION`). The PSBT used to pre-generate the pubnonces should therefore only contain the key derivations of the `musig()` key expressions.
### src/error_codes.h
@@ -109,6 +109,12 @@
// 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
+
+// The PSBT contains MuSig2 pubnonces, but the device has no corresponding MuSig2 session for it
+#define EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND 0x0017
+
/**
* Swap
*/
### src/handler/sign_psbt.c
@@ -21,6 +21,7 @@
#include "sign_psbt.h"
#include "sign_psbt/bip322_validation.h"
#include "sign_psbt/init_global_state.h"
+#include "sign_psbt/musig_signing.h"
#include "sign_psbt/preprocess_inputs.h"
#include "sign_psbt/preprocess_outputs.h"
#include "sign_psbt/sign_input.h"
@@ -96,11 +97,18 @@ static void sign_psbt(dispatcher_context_t *dc,
if (st->bip322.is_message_signing && !validate_bip322_request(dc, st)) return;
// check if we're only executing the MuSig2 Round 1
+ // true at the end of the loop if all key expressions we're signing for are MuSig2
bool only_signing_for_musig = true;
+ // true if any of the key expressions we're signing for is MuSig2
+ bool signing_for_musig = false;
for (size_t i = 0; i < st->account.n_internal_key_expressions; i++) {
- if (st->account.internal_key_expressions[i].to_sign &&
- st->account.internal_key_expressions[i].key_expression_ptr->type !=
- KEY_EXPRESSION_MUSIG) {
+ if (!st->account.internal_key_expressions[i].to_sign) {
+ continue;
+ }
+ if (st->account.internal_key_expressions[i].key_expression_ptr->type ==
+ KEY_EXPRESSION_MUSIG) {
+ signing_for_musig = true;
+ } else {
// at least one of the key expressions we're signing for is not a MuSig
only_signing_for_musig = false;
}
@@ -124,6 +132,12 @@ static void sign_psbt(dispatcher_context_t *dc,
// we execute the signing flow only if we're expected to produce any signature
// (including, possibly, any MuSig2 partial signature from Round 2 of MuSig2)
if (!only_signing_for_musig || st->has_musig2_pub_nonces) {
+ // If MuSig2 Round 2 is going to be executed, make sure that the session exists before
+ // proceeding, so we can fail early if missing.
+ if (signing_for_musig && st->has_musig2_pub_nonces && !musig_check_round2_session(dc, st)) {
+ return;
+ }
+
#ifdef HAVE_SWAP
if (G_called_from_swap) {
/** SWAP CHECKS
### 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
@@ -25,6 +25,7 @@
/* Local headers */
#include "client_commands.h"
#include "commands.h"
+#include "error_codes.h"
#include "get_merkleized_map_value.h"
#include "policy.h"
#include "psbt.h"
@@ -36,15 +37,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 +58,32 @@ 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 musig_check_round2_session(dispatcher_context_t *dc, const sign_psbt_state_t *st) {
+ uint8_t psbt_session_id[32];
+ musig_compute_session_id(st, psbt_session_id);
+
+ if (!musigsession_exists(psbt_session_id)) {
+ PRINTF("Missing MuSig2 session\n");
+ SEND_SW_EC(dc, SW_BAD_STATE, EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND);
+ return false;
+ }
+ return true;
}
bool compute_musig_per_input_info(dispatcher_context_t *dc,
@@ -434,7 +456,7 @@ bool __attribute__((noinline)) sign_sighash_musig_and_yield(dispatcher_context_t
// session in storage. Either it was deleted, or the pubnonces were not real. Either
// way, we cannot continue.
PRINTF("Missing MuSig2 session\n");
- SEND_SW(dc, SW_BAD_STATE);
+ SEND_SW_EC(dc, SW_BAD_STATE, EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND);
return false;
}
### src/handler/sign_psbt/musig_signing.h
@@ -34,6 +34,15 @@ typedef struct {
bool is_xonly[3]; // 2 or 3 elements
} musig_per_input_info_t;
+/**
+ * Checks that the MuSig2 session needed for Round 2 is in the persistent storage, without deleting
+ * it and without accessing its content.
+ *
+ * Returns true if the session exists, false otherwise. In case of failure, it already sends an
+ * error status word.
+ */
+bool musig_check_round2_session(dispatcher_context_t *dc, const sign_psbt_state_t *st);
+
/**
* Computes the MuSig2 per-input, per-key-expression information.
*
### 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 */
/* -------------------------------------------------------------------------- */
### src/musig/musig_sessions.c
@@ -8,33 +8,73 @@
/* Local headers */
#include "crypto.h"
+// A session in the persistent storage.
+// Only a prefix of the psbt_session_id is stored, so that each session fits in 64 bytes. This is
+// harmless: collisions remain nearly impossible, and anyway a collision on the ID only causes a
+// session to be deleted, and the following round 2 to fail.
+#define STORED_ID_PREFIX_LEN 28
+
+typedef struct {
+ uint8_t id_prefix[STORED_ID_PREFIX_LEN];
+ // Incremented for each stored session, in order to evict the oldest session when the storage is
+ // full. It is never 0 for a stored session; it would take 2^32 sessions to overflow.
+ uint32_t counter;
+ uint8_t rand_root[32];
+} musig_stored_session_t;
+
+_Static_assert(sizeof(musig_stored_session_t) == 64, "A stored session must take 64 bytes");
+
typedef struct {
// Aligning by 4 is necessary due to platform limitations.
// Aligning by 64 further guarantees that each session occupies exactly
// a single NVRAM page, minimizing the number of writes.
- __attribute__((aligned(64))) musig_psbt_session_t sessions[MAX_N_MUSIG_SESSIONS];
+ __attribute__((aligned(64))) musig_stored_session_t sessions[MAX_N_MUSIG_SESSIONS];
} musig_persistent_storage_t;
const musig_persistent_storage_t N_musig_storage_real;
#define N_musig_storage (*(const volatile musig_persistent_storage_t *) PIC(&N_musig_storage_real))
-static bool musigsession_pop(const uint8_t psbt_session_id[static 32], musig_psbt_session_t *out) {
- for (int i = 0; i < MAX_N_MUSIG_SESSIONS; i++) {
- if (memcmp(psbt_session_id, (const void *) N_musig_storage.sessions[i]._id, 32) == 0) {
- if (out != NULL) {
- memcpy(out,
- (const void *) &N_musig_storage.sessions[i],
- sizeof(musig_psbt_session_t));
- }
- uint8_t zeros[sizeof(musig_psbt_session_t)] = {0};
- nvm_write((void *) &N_musig_storage.sessions[i],
- (void *) zeros,
- sizeof(musig_psbt_session_t));
+static bool is_slot_free(int i) {
+ return is_array_all_zeros((uint8_t *) &N_musig_storage.sessions[i],
+ sizeof(musig_stored_session_t));
+}
- return true;
+// Returns the index of the slot storing the session with the given id, or -1 if there is none.
+static int find_slot(const uint8_t psbt_session_id[static 32]) {
+ for (int i = 0; i < MAX_N_MUSIG_SESSIONS; i++) {
+ if (is_slot_free(i)) {
+ continue;
+ }
+ if (memcmp(psbt_session_id,
+ (const void *) N_musig_storage.sessions[i].id_prefix,
+ STORED_ID_PREFIX_LEN) == 0) {
+ return i;
}
}
- return false;
+ return -1;
+}
+
+static bool musigsession_pop(const uint8_t psbt_session_id[static 32], musig_psbt_session_t *out) {
+ int i = find_slot(psbt_session_id);
+ if (i < 0) {
+ return false;
+ }
+ if (out != NULL) {
+ memcpy(out->_id, psbt_session_id, sizeof(out->_id));
+ memcpy(out->_rand_root,
+ (const void *) N_musig_storage.sessions[i].rand_root,
+ sizeof(out->_rand_root));
+ }
+ uint8_t zeros[sizeof(musig_stored_session_t)] = {0};
+ nvm_write((void *) &N_musig_storage.sessions[i],
+ (void *) zeros,
+ sizeof(musig_stored_session_t));
+
+ return true;
+}
+
+bool musigsession_exists(const uint8_t psbt_session_id[static 32]) {
+ return find_slot(psbt_session_id) >= 0;
}
__attribute__((warn_unused_result)) static bool musigsession_init_randomness(
@@ -53,22 +93,39 @@ static void musigsession_store(const uint8_t psbt_session_id[static 32],
// make sure that no session with the same id exists; delete it otherwise
musigsession_pop(psbt_session_id, NULL);
- int i;
- for (i = 0; i < MAX_N_MUSIG_SESSIONS; i++) {
- if (is_array_all_zeros((uint8_t *) &N_musig_storage.sessions[i],
- sizeof(musig_psbt_session_t))) {
- break;
+ // Use a free slot if any; otherwise, evict the oldest session (the one with the smallest
+ // counter). The new session gets a counter larger than all the stored ones.
+ int free_slot = -1;
+ int oldest_slot = -1;
+ uint32_t max_counter = 0;
+ for (int i = 0; i < MAX_N_MUSIG_SESSIONS; i++) {
+ if (is_slot_free(i)) {
+ if (free_slot < 0) {
+ free_slot = i;
+ }
+ continue;
+ }
+ uint32_t counter = N_musig_storage.sessions[i].counter;
+ if (oldest_slot < 0 || counter < N_musig_storage.sessions[oldest_slot].counter) {
+ oldest_slot = i;
+ }
+ if (counter > max_counter) {
+ max_counter = counter;
}
}
- if (i >= MAX_N_MUSIG_SESSIONS) {
- // no free slot found, delete the first by default
- // TODO: should we use a LIFO structure? Could add a counter to musig_psbt_session_t
- i = 0;
- }
+ int chosen = free_slot >= 0 ? free_slot : oldest_slot;
+
+ musig_stored_session_t stored_session;
+ memcpy(stored_session.id_prefix, psbt_session_id, sizeof(stored_session.id_prefix));
+ stored_session.counter = max_counter + 1;
+ memcpy(stored_session.rand_root, session->_rand_root, sizeof(stored_session.rand_root));
+
// replace the chosen slot
- nvm_write((void *) &N_musig_storage.sessions[i],
- (void *) session,
- sizeof(musig_psbt_session_t));
+ nvm_write((void *) &N_musig_storage.sessions[chosen],
+ (void *) &stored_session,
+ sizeof(musig_stored_session_t));
+
+ explicit_bzero(&stored_session, sizeof(stored_session));
}
void compute_rand_i_j(const musig_psbt_session_t *psbt_session,
### src/musig/musig_sessions.h
@@ -10,8 +10,9 @@
* documentation in docs/musig.md for more information.
*/
-// the maximum number of musig sessions that are stored in permanent memory
-#define MAX_N_MUSIG_SESSIONS 8
+// the maximum number of musig sessions that are stored in permanent memory; when the storage is
+// full, storing a new session evicts the oldest one
+#define MAX_N_MUSIG_SESSIONS 32
// state of a musig_psbt_session. Members are private and must not be accessed directly by any
// code outside of musig_sessions.c.
@@ -98,6 +99,17 @@ __attribute__((warn_unused_result)) const musig_psbt_session_t *musigsession_rou
uint8_t psbt_session_id[static 32],
musig_signing_state_t *musig_signing_state);
+/**
+ * Checks whether a session with the given id is in the persistent memory, without deleting it and
+ * without accessing its content.
+ *
+ * @param[in] psbt_session_id
+ * Pointer to the musig psbt session id.
+ *
+ * @return true if the session exists, false otherwise.
+ */
+bool musigsession_exists(const uint8_t psbt_session_id[static 32]);
+
/**
* If a session produced in round 1 is active in volatile memory, it is stored in the persistent
* memory. The signing state is then zeroed out, as the signing flow is over.
### 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,10 @@
tests_root: Path = Path(__file__).parent
+# error codes, see src/error_codes.h
+EC_SIGN_PSBT_INVALID_MUSIG2_SESSION_ID = 0x0016
+EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND = 0x0017
+
# for now, we assume that there's a single internal musig placeholder, with a single internal key
class LedgerMusig2Cosigner(PsbtMusig2Cosigner):
@@ -313,10 +317,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 +330,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)
@@ -492,6 +499,7 @@ def copy_psbt(psbt: PSBT) -> PSBT:
with pytest.raises(ExceptionRAPDU) as e:
signer_1.generate_partial_signatures(replayed_psbt)
assert DeviceException.exc.get(e.value.status) == BadStateError
+ assert int.from_bytes(e.value.data, byteorder='big') == EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND
assert len(replayed_psbt.inputs[0].musig2_partial_sigs) == 0
# 2) A failed round 2 consumes the session as well: after a round 2 that is rejected because of
@@ -511,4 +519,196 @@ def copy_psbt(psbt: PSBT) -> PSBT:
with pytest.raises(ExceptionRAPDU) as e:
signer_1.generate_partial_signatures(psbt)
assert DeviceException.exc.get(e.value.status) == BadStateError
+ assert int.from_bytes(e.value.data, byteorder='big') == EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND
+ 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 int.from_bytes(e.value.data, byteorder='big') == EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND
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
+
+
+def test_sign_psbt_musig2_missing_session_fails_before_review(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+ # If the session for round 2 is missing, the device fails before asking the user to review the
+ # transaction, rather than after the approval.
+ wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
+
+ # No navigator: round 1 has no UI, and round 2 must fail without showing any screen
+ signer_1 = LedgerMusig2Cosigner(client, wallet_policy, wallet_hmac)
+ 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)
+
+ # round 2 with a MUSIG2_SESSION_ID for which round 1 was never executed
+ other_psbt = PSBT()
+ other_psbt.deserialize(psbt.serialize())
+ other_psbt.musig2_session_id = b"\x02" * 32
+ with pytest.raises(ExceptionRAPDU) as e:
+ signer_1.generate_partial_signatures(other_psbt)
+ assert DeviceException.exc.get(e.value.status) == BadStateError
+ assert int.from_bytes(e.value.data, byteorder='big') == EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND
+ assert len(other_psbt.inputs[0].musig2_partial_sigs) == 0
+
+ # the session of the first psbt is unaffected, and round 2 completes after the review
+ signer_1_with_review = 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)
+ run_musig2_test(wallet_policy, psbt,
+ [Round2OnlyCosigner(signer_1_with_review), Round2OnlyCosigner(signer_2)], KEYPATH_SIGHASHES)
+
+
+MAX_N_MUSIG_SESSIONS = 32
+
+
+def test_sign_psbt_musig2_evicts_oldest_session(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals, enable_slow_tests: int):
+ # The device stores at most MAX_N_MUSIG_SESSIONS sessions; when the storage is full, round 1
+ # evicts the oldest session, regardless of the slot it occupies.
+
+ # slow test (it fills the whole storage), only run it if --enable_slow_tests is set to a value
+ # greater than 0
+ if enable_slow_tests < 1:
+ pytest.skip()
+
+ 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)
+
+ # Execute round 1 for MAX_N_MUSIG_SESSIONS + 2 sessions, that only differ in the
+ # MUSIG2_SESSION_ID. Any session left in storage by previous tests is older, hence evicted first.
+ n_sessions = MAX_N_MUSIG_SESSIONS + 2
+ psbts: List[PSBT] = []
+ hot_signers: List[HotMusig2Cosigner] = []
+ for i in range(n_sessions):
+ psbt = PSBT()
+ psbt.deserialize(KEYPATH_PSBT_B64)
+ psbt.musig2_session_id = bytes([i + 1])
+ # the hot cosigner identifies its sessions by the transaction, so each psbt needs its own
+ hot_signer = HotMusig2Cosigner(wallet_policy, KEYPATH_COSIGNER_2_XPRIV)
+ signer_1.generate_public_nonces(psbt)
+ hot_signer.generate_public_nonces(psbt)
+ psbts.append(psbt)
+ hot_signers.append(hot_signer)
+
+ # The two oldest sessions were evicted
+ for psbt in psbts[:2]:
+ with pytest.raises(ExceptionRAPDU) as e:
+ signer_1.generate_partial_signatures(psbt)
+ assert DeviceException.exc.get(e.value.status) == BadStateError
+ assert int.from_bytes(e.value.data, byteorder='big') == EC_SIGN_PSBT_MUSIG2_SESSION_NOT_FOUND
+
+ # The others are still there. Storing the second to last session must not have evicted the one
+ # stored right before it, nor the last one the second to last.
+ for i in [2, n_sessions - 3, n_sessions - 2, n_sessions - 1]:
+ run_musig2_test(wallet_policy, psbts[i],
+ [Round2OnlyCosigner(signer_1), Round2OnlyCosigner(hot_signers[i])], KEYPATH_SIGHASHES)
### 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 26/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.