Make the MuSig2 psbt_session_id independent of the transaction
What changed, and why it matters
This commit changes how the Ledger Bitcoin app identifies an in-progress MuSig2 multi-signature session. Previously, the session ID was tied to the specific transaction, so you could only start the signing process after the transaction was known. Now the session ID depends only on the wallet policy (the spending rules), allowing users to generate public nonces ahead of time for a later transaction. This is a deliberate feature change, not a fix for an active exploit. The trade-off is that only one pending session is allowed per wallet policy, and starting a new session overwrites the old one.
Review the security implications of allowing transaction-independent MuSig2 pubnonces, particularly the risk of a user generating nonces for one planned transaction and then inadvertently signing a different transaction. Ensure wallet software correctly manages session state and pubnonce placement. No urgent patch is indicated from the diff alone.
Security signals we found
Change in cryptographic session binding from (wallet policy + transaction) to wallet policy only
Removal of transaction hash commitment from MuSig2 session identifier
Addition of assertions and comments explaining the security trade-off (one session per wallet policy, session replacement)
New tests verifying cross-transaction nonce reuse and session replacement behavior
No evidence of memory corruption, buffer overflow, or secret leakage in the diff
Evidence from the diff
The commit removes transaction hashes (tx_hashes_t) from the MuSig2 psbt_session_id computation in src/handler/sign_psbt/musig_signing.c. A new static function musig_compute_session_id() derives the ID solely from the wallet policy’s descriptor template hash and the Merkle root of its key information, using a BIP-0340 tagged hash. The psbt_session_id field is removed from musig_per_input_info_t. Round 1 and round 2 now compute the session ID independently of the transaction. Documentation and tests are updated to reflect that pubnonces can be pre-generated for any future transaction sharing the same wallet policy, as long as internal inputs remain at the same indexes and pubnonces are placed under the correct PSBT keys (which depend on tweaked aggregate keys and tapleaf hashes).
Changed components
src/handler/sign_psbt/musig_signing.csrc/handler/sign_psbt/musig_signing.hdoc/musig.mdtests/test_sign_psbt_musig.pyInspect captured patch +295 / −58
### 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 parallel MuSig signing sessions are supported, due to the need to persist state in the device's memory.
+- 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)).
+- 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.
## State minimization
@@ -92,4 +93,20 @@ BIP-0327 suggests using the tweaked aggregate key as *aggpk*. Using the untweake
The approach described above assumes that no attempt to sign a PSBT for a wallet policy containing `musig()` keys is initiated while a session is already in progress.
-In order to generalize this to an arbitrary number of parallel signing sessions, one can identify each signing session with a `psbt_session_id`. Such `psbt_session_id` should deterministically depend on the transaction being signed (ignoring all the other PSBT fields), and the wallet policy being signed. In praticular, the computed `psbt_session_id` should be identical between Round 1 and Round 2 of the protocol. Note that malicious collisions of the `psbt_session_id` (for example by tampering with some details of the PSBT, like the SIGHASH flags) _are_ possible, but they do not constitute a security risk.
+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)$
+
+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.
+
+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.
+
+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.
+
+### 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;
+- 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.
### src/handler/sign_psbt/musig_signing.c
@@ -30,9 +30,42 @@
#include "psbt.h"
#include "sw.h"
+/**
+ * Computes the id of the psbt-level MuSig2 signing session.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * Software wallets are responsible for managing the state correctly.
+ */
+static void musig_compute_session_id(const sign_psbt_state_t *st, uint8_t out[static 32]) {
+ // musig() key expressions are only allowed in V2 wallet policies, where the header contains the
+ // hash of the descriptor template rather than the descriptor template itself
+ LEDGER_ASSERT(st->account.wallet_header.version == WALLET_POLICY_VERSION_V2,
+ "MuSig2 requires a V2 wallet policy");
+
+ crypto_tr_tagged_hash(
+ (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);
+}
+
bool compute_musig_per_input_info(dispatcher_context_t *dc,
sign_psbt_state_t *st,
- signing_state_t *signing_state,
const input_info_t *input,
const keyexpr_info_t *keyexpr_info,
musig_per_input_info_t *out) {
@@ -49,7 +82,6 @@ bool compute_musig_per_input_info(dispatcher_context_t *dc,
// 1) compute aggregate pubkey
// 2) compute musig2 tweaks
// 3) compute taproot tweak (if keypath spend)
- // 4) compute the psbt_session_id that identifies the psbt-level signing session
wallet_derivation_info_t wdi = {
.n_keys = st->account.wallet_header.n_keys,
@@ -144,24 +176,6 @@ bool compute_musig_per_input_info(dispatcher_context_t *dc,
sizeof(out->agg_key_tweaked.parent_fingerprint));
memset(out->agg_key_tweaked.version, 0, sizeof(out->agg_key_tweaked.version));
- // The psbt_session_id identifies the musig signing session for the entire (psbt, wallet_policy)
- // pair, in both rounds 1 and 2 of the protocol; it is the same for all the musig placeholders
- // in the policy (if more than one), and it is the same for all the inputs in the psbt. By
- // making the hash depend on both the wallet policy and the transaction hashes, we make sure
- // that an accidental collision is impossible, allowing for independent, parallel MuSig2 signing
- // sessions for different transactions or wallet policies.
- // Malicious collisions are not a concern, as they would only result in a signing failure (since
- // the nonces would be incorrectly regenerated during round 2 of MuSig2).
- crypto_tr_tagged_hash(
- (uint8_t[]) {'P', 's', 'b', 't', 'S', 'e', 's', 's', 'i', 'o', 'n', 'I', 'd'},
- 13,
- st->account.wallet_header
- .keys_info_merkle_root, // TODO: wallet policy id would be more precise
- 32,
- (uint8_t *) &signing_state->tx_hashes,
- sizeof(tx_hashes_t),
- out->psbt_session_id);
-
return true;
}
@@ -311,21 +325,19 @@ bool produce_and_yield_pubnonce(dispatcher_context_t *dc,
LOG_PROCESSOR(__FILE__, __LINE__, __func__);
musig_per_input_info_t musig_per_input_info;
- if (!compute_musig_per_input_info(dc,
- st,
- signing_state,
- input,
- keyexpr_info,
- &musig_per_input_info)) {
+ if (!compute_musig_per_input_info(dc, st, input, keyexpr_info, &musig_per_input_info)) {
return false;
}
/**
* Round 1 of the MuSig2 protocol: generate and yield pubnonce
**/
+ uint8_t psbt_session_id[32];
+ musig_compute_session_id(st, psbt_session_id);
+
const musig_psbt_session_t *psbt_session =
- musigsession_round1_initialize(musig_per_input_info.psbt_session_id, &signing_state->musig);
+ musigsession_round1_initialize(psbt_session_id, &signing_state->musig);
if (psbt_session == NULL) {
// This should never happen
PRINTF("Unexpected: failed to initialize MuSig2 round 1\n");
@@ -371,12 +383,7 @@ bool __attribute__((noinline)) sign_sighash_musig_and_yield(dispatcher_context_t
LOG_PROCESSOR(__FILE__, __LINE__, __func__);
musig_per_input_info_t musig_per_input_info;
- if (!compute_musig_per_input_info(dc,
- st,
- signing_state,
- input,
- keyexpr_info,
- &musig_per_input_info)) {
+ if (!compute_musig_per_input_info(dc, st, input, keyexpr_info, &musig_per_input_info)) {
return false;
}
@@ -416,8 +423,11 @@ bool __attribute__((noinline)) sign_sighash_musig_and_yield(dispatcher_context_t
* Round 2 of the MuSig2 protocol
**/
+ uint8_t psbt_session_id[32];
+ musig_compute_session_id(st, psbt_session_id);
+
const musig_psbt_session_t *psbt_session =
- musigsession_round2_initialize(musig_per_input_info.psbt_session_id, &signing_state->musig);
+ musigsession_round2_initialize(psbt_session_id, &signing_state->musig);
if (psbt_session == NULL) {
// The PSBT contains a partial nonce, but we do not have the corresponding psbt
### src/handler/sign_psbt/musig_signing.h
@@ -29,7 +29,6 @@
typedef struct {
plain_pk_t keys[MAX_PUBKEYS_PER_MUSIG];
serialized_extended_pubkey_t agg_key_tweaked;
- uint8_t psbt_session_id[32];
uint8_t tweaks[3][32]; // 2 or three tweaks
size_t n_tweaks; // always 2 or 3 for supported BIP-388 wallet policies
bool is_xonly[3]; // 2 or 3 elements
@@ -46,7 +45,6 @@ typedef struct {
*/
bool compute_musig_per_input_info(dispatcher_context_t *dc,
sign_psbt_state_t *st,
- signing_state_t *signing_state,
const input_info_t *input,
const keyexpr_info_t *keyexpr_info,
musig_per_input_info_t *out);
### tests/test_sign_psbt_musig.py
@@ -3,7 +3,7 @@
from hashlib import sha256
import hmac
-from typing import Optional, Tuple
+from typing import Dict, Optional, Tuple
import pytest
@@ -12,15 +12,16 @@
from ledger_bitcoin.exception.errors import IncorrectDataError
from ledger_bitcoin.exception.device_exception import DeviceException
from ledger_bitcoin.client_base import Client, MusigPartialSignature, MusigPubNonce
-from ledger_bitcoin.key import ExtendedKey
+from ledger_bitcoin.key import ExtendedKey, KeyOriginInfo
from ledger_bitcoin.psbt import PSBT
from ragger.navigator import Navigator
from ragger.firmware import Firmware
from ledger_bitcoin.wallet import WalletPolicy
from ragger_bitcoin import RaggerClient
from test_utils import SpeculosGlobals, bip0327
-from test_utils.musig2 import HotMusig2Cosigner, MuSig2KeyPlaceholder, PsbtMusig2Cosigner, TrDescriptorTemplate, run_musig2_test
+from test_utils.musig2 import HotMusig2Cosigner, MuSig2KeyPlaceholder, PsbtMusig2Cosigner, TrDescriptorTemplate, aggregate_musig_pubkey, process_placeholder, run_musig2_test, tapleaf_hash
+from test_utils.taproot import taproot_output_script
from .instructions import *
tests_root: Path = Path(__file__).parent
@@ -152,39 +153,250 @@ def test_sign_psbt_musig2_keypath(navigator: Navigator, firmware: Firmware, clie
run_musig2_test(wallet_policy, psbt, [signer_1, signer_2], sighashes)
-def test_sign_psbt_musig2_scriptpath(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
- cosigner_1_xpub = "[f5acc2fd/44'/1'/0']tpubDCwYjpDhUdPGP5rS3wgNg13mTrrjBuG8V9VpWbyptX6TRPbNoZVXsoVUSkCjmQ8jJycjuDKBb9eataSymXakTTaGifxR6kmVsfFehH1ZgJT"
+SCRIPTPATH_INTERNAL_XPUB = "tpubD6NzVbkrYhZ4WLczPJWReQycCJdd6YVWXubbVUFnJ5KgU5MDQrD998ZJLSmaB7GVcCnJSDWprxmrGkJ6SvgQC6QAffVpqSvonXmeizXcrkN"
+SCRIPTPATH_COSIGNER_1_XPUB = "[f5acc2fd/44'/1'/0']tpubDCwYjpDhUdPGP5rS3wgNg13mTrrjBuG8V9VpWbyptX6TRPbNoZVXsoVUSkCjmQ8jJycjuDKBb9eataSymXakTTaGifxR6kmVsfFehH1ZgJT"
+SCRIPTPATH_COSIGNER_2_XPRIV = "tprv8gFWbQBTLFhbX3EK3cS7LmenwE3JjXbD9kN9yXfq7LcBm81RSf8vPGPqGPjZSeX41LX9ZN14St3z8YxW48aq5Yhr9pQZVAyuBthfi6quTCf"
+SCRIPTPATH_COSIGNER_2_XPUB = ExtendedKey.deserialize(
+ SCRIPTPATH_COSIGNER_2_XPRIV).neutered().to_string()
+
+SCRIPTPATH_PSBT_B64 = "cHNidP8BAFoCAAAAAdOnEESfpXpBe9X59Q4jxz1u9E4Wovn2bkAuuyqUUY0mAAAAAAD9////AQAAAAAAAAAAHmocTXVzaWcyLiBOb3cgZXZlbiBpbiBTY3JpcHRzLgAAAAAAAQErOTAAAAAAAAAiUSDtVR7h2JYPJC463zrCcmfKriiugHBXAcXDP1O2ptF2LyIVwethFsEeXf/x51pIczoAIsj9RoVePIBTyk/rOMW8B6uIIyCQZkYWUCCfi7xZsFr10WFcUPX3nBiNe+dC/ZMiUvaPDKzAIRaQZkYWUCCfi7xZsFr10WFcUPX3nBiNe+dC/ZMiUvaPDC0BuYMCXh1wIlpyBMdMaCFPSwOeOyvhqg+FJ+fOMoWlJsRbj7yTAAAAAAMAAAABFyDrYRbBHl3/8edaSHM6ACLI/UaFXjyAU8pP6zjFvAeriAEYILmDAl4dcCJacgTHTGghT0sDnjsr4aoPhSfnzjKFpSbEAAA="
+
+SCRIPTPATH_SIGHASHES = [
+ bytes.fromhex(
+ "28f86cd95c144ed4a877701ae7166867e8805b654c43d9f44da45d7b0070c313")
+]
- cosigner_2_xpriv = "tprv8gFWbQBTLFhbX3EK3cS7LmenwE3JjXbD9kN9yXfq7LcBm81RSf8vPGPqGPjZSeX41LX9ZN14St3z8YxW48aq5Yhr9pQZVAyuBthfi6quTCf"
- cosigner_2_xpub = ExtendedKey.deserialize(
- cosigner_2_xpriv).neutered().to_string()
+def scriptpath_wallet_policy(speculos_globals: SpeculosGlobals) -> Tuple[WalletPolicy, bytes]:
wallet_policy = WalletPolicy(
name="Musig2 in the scriptpath",
descriptor_template="tr(@0/**,pk(musig(@1,@2)/**))",
keys_info=[
- "tpubD6NzVbkrYhZ4WLczPJWReQycCJdd6YVWXubbVUFnJ5KgU5MDQrD998ZJLSmaB7GVcCnJSDWprxmrGkJ6SvgQC6QAffVpqSvonXmeizXcrkN",
- cosigner_1_xpub,
- cosigner_2_xpub
+ SCRIPTPATH_INTERNAL_XPUB,
+ SCRIPTPATH_COSIGNER_1_XPUB,
+ SCRIPTPATH_COSIGNER_2_XPUB
]
)
wallet_hmac = hmac.new(
speculos_globals.wallet_registration_key, wallet_policy.id, sha256).digest()
+ return wallet_policy, wallet_hmac
- psbt_b64 = "cHNidP8BAFoCAAAAAdOnEESfpXpBe9X59Q4jxz1u9E4Wovn2bkAuuyqUUY0mAAAAAAD9////AQAAAAAAAAAAHmocTXVzaWcyLiBOb3cgZXZlbiBpbiBTY3JpcHRzLgAAAAAAAQErOTAAAAAAAAAiUSDtVR7h2JYPJC463zrCcmfKriiugHBXAcXDP1O2ptF2LyIVwethFsEeXf/x51pIczoAIsj9RoVePIBTyk/rOMW8B6uIIyCQZkYWUCCfi7xZsFr10WFcUPX3nBiNe+dC/ZMiUvaPDKzAIRaQZkYWUCCfi7xZsFr10WFcUPX3nBiNe+dC/ZMiUvaPDC0BuYMCXh1wIlpyBMdMaCFPSwOeOyvhqg+FJ+fOMoWlJsRbj7yTAAAAAAMAAAABFyDrYRbBHl3/8edaSHM6ACLI/UaFXjyAU8pP6zjFvAeriAEYILmDAl4dcCJacgTHTGghT0sDnjsr4aoPhSfnzjKFpSbEAAA="
- psbt = PSBT()
- psbt.deserialize(psbt_b64)
- sighashes = [
- bytes.fromhex(
- "28f86cd95c144ed4a877701ae7166867e8805b654c43d9f44da45d7b0070c313")
- ]
+def test_sign_psbt_musig2_scriptpath(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+ wallet_policy, wallet_hmac = scriptpath_wallet_policy(speculos_globals)
+
+ psbt = PSBT()
+ psbt.deserialize(SCRIPTPATH_PSBT_B64)
signer_1 = LedgerMusig2Cosigner(client, wallet_policy, wallet_hmac,
navigator=navigator, instructions=sign_psbt_instruction_approve(firmware, save_screenshot=False, has_spend_from_wallet=True), testname=test_name)
- signer_2 = HotMusig2Cosigner(wallet_policy, cosigner_2_xpriv)
+ signer_2 = HotMusig2Cosigner(wallet_policy, SCRIPTPATH_COSIGNER_2_XPRIV)
- run_musig2_test(wallet_policy, psbt, [signer_1, signer_2], sighashes)
+ run_musig2_test(wallet_policy, psbt, [signer_1, signer_2], SCRIPTPATH_SIGHASHES)
+
+
+def musig_pubnonce_ids(wallet_policy: WalletPolicy, psbt: PSBT) -> Dict[Tuple[int, int], Tuple[bytes, Optional[bytes]]]:
+ """
+ For each (input index, musig() key placeholder index) pair of the psbt, returns the
+ (aggregate pubkey after the tweaks, tapleaf hash) pair that, together with the participant's
+ pubkey, identifies the pubnonces and partial signatures in the psbt.
+ """
+ desc_tmpl = TrDescriptorTemplate.from_string(wallet_policy.descriptor_template)
+ result = {}
+ for placeholder_index, (placeholder, tapleaf_desc) in enumerate(desc_tmpl.placeholders()):
+ if not isinstance(placeholder, MuSig2KeyPlaceholder):
+ continue
+
+ agg_xpub_str, keyagg_ctx = aggregate_musig_pubkey(
+ wallet_policy.keys_info[i] for i in placeholder.key_indexes)
+ agg_xpub = ExtendedKey.deserialize(agg_xpub_str)
+
+ for input_index, input in enumerate(psbt.inputs):
+ res = process_placeholder(
+ wallet_policy, input, placeholder, keyagg_ctx, agg_xpub, tapleaf_desc, desc_tmpl)
+ if res is not None:
+ (_, _, leaf_script, aggpk_tweaked) = res
+ result[(input_index, placeholder_index)] = (
+ aggpk_tweaked, tapleaf_hash(leaf_script))
+ return result
+
+
+class Round1OnOtherTxCosigner(LedgerMusig2Cosigner):
+ """
+ A LedgerMusig2Cosigner that executes round 1 on a completely different transaction than the one
+ that is going to be signed, and then reuses the resulting pubnonces. This is what a software
+ wallet does when it pre-generates the pubnonces before the transaction is known.
+ """
+
+ def __init__(self, other_psbt: PSBT, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ self.other_psbt = other_psbt
+
+ def generate_public_nonces(self, psbt: PSBT) -> None:
+ # the device only ever sees the unrelated transaction during round 1
+ super().generate_public_nonces(self.other_psbt)
+
+ # Transplant the pubnonces into the transaction that will actually be signed.
+ src_ids = musig_pubnonce_ids(self.wallet_policy, self.other_psbt)
+ dst_ids = musig_pubnonce_ids(self.wallet_policy, psbt)
+ n_transplanted = 0
+ for (input_index, placeholder_index), (src_aggpk, src_leaf_hash) in src_ids.items():
+ dst_aggpk, dst_leaf_hash = dst_ids[(input_index, placeholder_index)]
+ src_key = (self.pubkey.pubkey, src_aggpk, src_leaf_hash)
+ if src_key in self.other_psbt.inputs[input_index].musig2_pub_nonces:
+ psbt.inputs[input_index].musig2_pub_nonces[(self.pubkey.pubkey, dst_aggpk, dst_leaf_hash)] = \
+ self.other_psbt.inputs[input_index].musig2_pub_nonces[src_key]
+ n_transplanted += 1
+ assert n_transplanted > 0
+
+
+def test_sign_psbt_musig2_round1_on_another_transaction(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+ # Neither the pubnonces nor the psbt_session_id depend on the transaction, therefore pubnonces
+ # obtained in round 1 for one transaction are valid for any other transaction of the same wallet
+ # policy, as long as the inputs are at the same indexes.
+ # This is needed by software wallets that want to pre-generate the pubnonces before the
+ # transaction is known, keeping the UX of musig similar to a regular multisig.
+ #
+ # This test would have failed on versions of the app until 2.5.1, since the psbt_session_id
+ # used to depend on the transaction.
+ wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
+
+ psbt = PSBT()
+ psbt.deserialize(KEYPATH_PSBT_B64)
+
+ other_psbt = PSBT()
+ other_psbt.deserialize(KEYPATH_PSBT_B64)
+ other_psbt.tx.vin[0].prevout.hash ^= 1
+ other_psbt.tx.vout[0].nValue += 1000
+ other_psbt.tx.rehash()
+
+ other_input = other_psbt.inputs[0]
+ ((_, (_, key_origin)),) = other_input.tap_bip32_paths.items()
+ assert key_origin.path == [0, 3]
+ other_steps = [1, 7] # change address with index 7, instead of receive address with index 3
+ agg_xpub = ExtendedKey.deserialize(aggregate_musig_pubkey(wallet_policy.keys_info)[0])
+ other_internal_key = agg_xpub.derive_pub_path(other_steps).pubkey[1:]
+ other_input.tap_bip32_paths = {
+ other_internal_key: (set(), KeyOriginInfo(key_origin.fingerprint, other_steps))
+ }
+ other_input.witness_utxo.scriptPubKey = taproot_output_script(other_internal_key, None)
+
+ assert musig_pubnonce_ids(wallet_policy, other_psbt)[(0, 0)] != \
+ musig_pubnonce_ids(wallet_policy, psbt)[(0, 0)]
+
+ signer_1 = Round1OnOtherTxCosigner(other_psbt, 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)
+
+ # run_musig2_test also aggregates the partial signatures and checks the resulting Schnorr
+ # signature against the sighash of `psbt`
+ run_musig2_test(wallet_policy, psbt, [signer_1, signer_2], KEYPATH_SIGHASHES)
+
+
+def test_sign_psbt_musig2_scriptpath_round1_on_another_transaction(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+ # Same as test_sign_psbt_musig2_round1_on_another_transaction, for a musig() in a tapleaf.
+ wallet_policy, wallet_hmac = scriptpath_wallet_policy(speculos_globals)
+
+ psbt = PSBT()
+ psbt.deserialize(SCRIPTPATH_PSBT_B64)
+
+ other_psbt = PSBT()
+ other_psbt.deserialize(SCRIPTPATH_PSBT_B64)
+ other_psbt.tx.vin[0].prevout.hash ^= 1
+ other_psbt.tx.vout[0].nValue += 1000
+ other_psbt.tx.rehash()
+
+ signer_1 = Round1OnOtherTxCosigner(other_psbt, client, wallet_policy, wallet_hmac,
+ navigator=navigator, instructions=sign_psbt_instruction_approve(firmware, save_screenshot=False, has_spend_from_wallet=True), testname=test_name)
+ signer_2 = HotMusig2Cosigner(wallet_policy, SCRIPTPATH_COSIGNER_2_XPRIV)
+
+ 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):
+ # 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, 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)
+ signer_1.generate_public_nonces(psbt)
+ signer_2.generate_public_nonces(psbt)
+
+ other_psbt = PSBT()
+ other_psbt.deserialize(KEYPATH_PSBT_B64)
+ other_psbt.tx.vout[0].nValue += 1000
+ other_psbt.tx.rehash()
+ signer_1.generate_public_nonces(other_psbt)
+ assert other_psbt.inputs[0].musig2_pub_nonces != psbt.inputs[0].musig2_pub_nonces
+
+ with pytest.raises(ExceptionRAPDU) as e:
+ signer_1.generate_partial_signatures(psbt)
+ assert DeviceException.exc.get(e.value.status) == IncorrectDataError
+ assert len(psbt.inputs[0].musig2_partial_sigs) == 0
+
+
+class Round1ForOtherPolicyCosigner(PsbtMusig2Cosigner):
+ """
+ Not a real cosigner: when asked for its pubnonces, it makes the device execute round 1 for a
+ different wallet policy, on a copy of the psbt. Used to check that this does not interfere with
+ the pending session of the policy that is actually being signed.
+ """
+
+ def __init__(self, ledger_cosigner: LedgerMusig2Cosigner) -> None:
+ super().__init__()
+ self.ledger_cosigner = ledger_cosigner
+
+ def get_participant_pubkey(self) -> bip0327.Point:
+ return self.ledger_cosigner.get_participant_pubkey()
+
+ def generate_public_nonces(self, psbt: PSBT) -> None:
+ # the copy must not contain any pubnonce, or the device would execute round 2
+ psbt_copy = PSBT()
+ psbt_copy.deserialize(psbt.serialize())
+ for input in psbt_copy.inputs:
+ input.musig2_pub_nonces.clear()
+ self.ledger_cosigner.generate_public_nonces(psbt_copy)
+ assert any(len(input.musig2_pub_nonces) > 0 for input in psbt_copy.inputs)
+
+ def generate_partial_signatures(self, psbt: PSBT) -> None:
+ pass
+
+
+def test_sign_psbt_musig2_policies_with_same_keys(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):
+ # Two wallet policies with the same keys, but different descriptor templates, must not share the
+ # same psbt_session_id: otherwise, round 1 for one policy would delete the session that the
+ # other policy is waiting to use in round 2.
+ wallet_policy, wallet_hmac = keypath_wallet_policy(speculos_globals)
+
+ # The keys in musig() are sorted, so this policy has the same aggregate key and the same
+ # addresses as wallet_policy; it can therefore execute round 1 on the very same psbt.
+ other_wallet_policy = WalletPolicy(
+ name="Musig for my other ears",
+ descriptor_template="tr(musig(@1,@0)/**)",
+ keys_info=wallet_policy.keys_info
+ )
+ other_wallet_hmac = hmac.new(
+ speculos_globals.wallet_registration_key, other_wallet_policy.id, sha256).digest()
+ assert other_wallet_policy.id != wallet_policy.id
+
+ psbt = PSBT()
+ psbt.deserialize(KEYPATH_PSBT_B64)
+
+ 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)
+ interloper = Round1ForOtherPolicyCosigner(
+ LedgerMusig2Cosigner(client, other_wallet_policy, other_wallet_hmac, testname=test_name))
+ signer_2 = HotMusig2Cosigner(wallet_policy, KEYPATH_COSIGNER_2_XPRIV)
+
+ # the device executes round 1 for wallet_policy, then for other_wallet_policy, then round 2 for
+ # wallet_policy
+ run_musig2_test(wallet_policy, psbt, [signer_1, interloper, signer_2], KEYPATH_SIGHASHES)
def test_sign_psbt_musig2_wrong_pubnonce(navigator: Navigator, firmware: Firmware, client: RaggerClient, test_name: str, speculos_globals: SpeculosGlobals):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.