Merge pull request #11246 from Roasbeef/fix-musig2-session-lifecycle
What changed, and why it matters
This commit fixes how LND manages temporary MuSig2 signing sessions for Taproot Lightning channels. Previously, these sessions could be left alive longer than necessary or leak if a signing round failed or was aborted. The patch releases the backing signer session as soon as the local node no longer needs it, and adds regression tests to confirm sessions are cleaned up. It also fixes a related error-handling bug where an invalid MuSig2 partial commitment signature was rejected without including the commitment height and transaction details that the remote peer needs for debugging.
Review and merge. The change is defensive and improves resource hygiene for Taproot channels. Operators running nodes with many Taproot channels should upgrade to avoid potential accumulation of stale MuSig2 sessions. No immediate emergency response is indicated because the issue appears to be a resource leak rather than a direct fund-stealing vulnerability.
Security signals we found
Resource leak / denial of service: leaked MuSig2 signer sessions could accumulate in the signer's session set, potentially exhausting session limits or memory over time.
Defense in depth: cleanup-on-error ensures failed signing or verification attempts do not leave live sessions behind.
Error-handling improvement: invalid MuSig2 partial commitment signatures now carry commitment height and transaction bytes, matching existing ECDSA invalid-commit-sig behavior.
Regression tests added for session lifecycle cleanup in both commitment and cooperative-close paths.
Evidence from the diff
The PR changes the lifecycle of MuSig2 sessions in LND’s lnwallet and chancloser packages. It introduces a Cleanup() method on MusigSession that calls MuSig2Cleanup on the backing signer and nils the session reference. SignCommit is split into a transient variant (signCommitAndCleanup) that releases the signer session after producing a partial signature, used when the local node sends its partial sig to the remote party for combination. VerifyCommitSig now defers Cleanup() so failed verifications do not leak sessions. CombineSigs nils the local session reference once all partial signatures are combined, because the signer already drops the session internally. The cooperative close RBF state machine’s InvalidateNonce now also calls Cleanup() and returns an error, preventing leaked sessions on completed or aborted rounds. A separate fix in channel.go makes InvalidPartialCommitSigError unwrap to InvalidCommitSigError so the link sends commitment height/transaction debug data to the remote peer on invalid MuSig2 partial signatures.
Changed components
lnwallet/musig_session.golnwallet/channel.golnwallet/wallet.golnwallet/chancloser/rbf_coop_transitions.golnwallet/chancloser/interface.gopeer/musig_chan_closer.goinput/musig2_session_manager.goInspect captured patch +459 / −32
### docs/release-notes/release-notes-0.22.0.md
@@ -79,6 +79,18 @@
`NodeAnnouncement2` address decoders, where all decoded addresses aliased
one scratch array and truncated records decoded without an error.
+* Taproot commitment signing and verification now [release transient MuSig2
+ signer sessions](https://github.com/lightningnetwork/lnd/pull/11246) once
+ the local node no longer needs them. Force-close and cooperative-close
+ signing continue to retain their sessions until signature combination, with
+ cooperative-close rounds releasing their session when the round completes
+ or is aborted.
+
+* [Fixed a bug](https://github.com/lightningnetwork/lnd/pull/11283) where an
+ invalid MuSig2 partial commitment signature on a taproot channel was
+ rejected without the commitment height and transaction attached, and
+ without sending those debug details to the remote peer.
+
# New Features
## Functional Enhancements
@@ -242,6 +254,8 @@
* George Tsagkarelis
* Jared Tobin
* Kevin Cai
+* Nishant Bansal
* Vandit Singh
* Viktor Torstensson
+* Pins
* s1ns3nz0
### input/musig2_session_manager.go
@@ -42,6 +42,13 @@ type MusigSessionManager struct {
musig2Sessions *lnutils.SyncMap[MuSig2SessionID, *MuSig2State]
}
+// NumLiveSessions returns the number of MuSig2 sessions that are currently
+// held by this manager. This is used by callers (and tests) to verify that
+// sessions are released once they're no longer needed.
+func (m *MusigSessionManager) NumLiveSessions() int {
+ return m.musig2Sessions.Len()
+}
+
// NewMusigSessionManager creates a new musig manager given an abstract key
// fetcher.
func NewMusigSessionManager(keyFetcher PrivKeyFetcher) *MusigSessionManager {
### lnwallet/chancloser/chancloser_test.go
@@ -304,7 +304,7 @@ func (m *mockMusigSession) InitRemoteNonce(nonce *musig2.Nonces) {
m.remoteNonce = *nonce
}
-func (m *mockMusigSession) InvalidateNonce() {}
+func (m *mockMusigSession) InvalidateNonce() error { return nil }
func (m *mockMusigSession) ClosingNonce() (*musig2.Nonces, error) {
return &musig2.Nonces{
### lnwallet/chancloser/interface.go
@@ -140,6 +140,8 @@ type MusigSession interface {
// InvalidateNonce clears the cached local nonce, forcing a fresh
// nonce to be generated on the next call to ClosingNonce. This
// must be called after each RBF round completes to prevent nonce
- // reuse across iterations.
- InvalidateNonce()
+ // reuse across iterations. Any backing signer session created for
+ // the round is also released; a completed round has no further use
+ // for it, and an aborted round would otherwise leak it.
+ InvalidateNonce() error
}
### lnwallet/chancloser/rbf_coop_test.go
@@ -3309,7 +3309,9 @@ func (m *strictNonceMusigSession) InitRemoteNonce(nonce *musig2.Nonces) {
m.remoteNonce = *nonce
}
-func (m *strictNonceMusigSession) InvalidateNonce() {}
+func (m *strictNonceMusigSession) InvalidateNonce() error {
+ return nil
+}
func (m *strictNonceMusigSession) ClosingNonce() (*musig2.Nonces, error) {
return &musig2.Nonces{
### lnwallet/chancloser/rbf_coop_transitions.go
@@ -1602,9 +1602,14 @@ func (l *LocalOfferSent) ProcessEvent(event ProtocolEvent, env *Environment,
// Invalidate the closer nonce now that the round is complete.
// The next RBF round will generate a fresh nonce in
- // LocalCloseStart.
+ // LocalCloseStart. This also releases the backing signer
+ // session, as this round has no further use for it.
if env.IsTaproot() {
- env.LocalMusigSession.InvalidateNonce()
+ err := env.LocalMusigSession.InvalidateNonce()
+ if err != nil {
+ return nil, fmt.Errorf("unable to "+
+ "invalidate closer nonce: %w", err)
+ }
}
// As we're about to broadcast a new version of the co-op close
@@ -2091,9 +2096,15 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
// Invalidate the closee nonce that was consumed for signing.
// This forces createClosingSigMessage to generate a fresh
- // nonce for NextCloseeNonce in the next RBF round.
+ // nonce for NextCloseeNonce in the next RBF round. This also
+ // releases the backing signer session, as this round has no
+ // further use for it.
if env.IsTaproot() {
- env.RemoteMusigSession.InvalidateNonce()
+ err := env.RemoteMusigSession.InvalidateNonce()
+ if err != nil {
+ return nil, fmt.Errorf("unable to "+
+ "invalidate closee nonce: %w", err)
+ }
}
closingSigMsg, err := createClosingSigMessage(
### lnwallet/channel.go
@@ -4274,7 +4274,7 @@ func (lc *LightningChannel) SignNextCommitment(
// a musig2 channel. The encoded normal ECDSA signature will be
// just blank.
remoteSession := lc.musigSessions.RemoteSession
- musig, err := remoteSession.SignCommit(
+ musig, err := remoteSession.signCommitAndCleanup(
newCommitView.txn,
)
if err != nil {
@@ -4397,7 +4397,7 @@ func (lc *LightningChannel) resignMusigCommit(
commitTx *wire.MsgTx) (lnwire.OptPartialSigWithNonceTLV, error) {
remoteSession := lc.musigSessions.RemoteSession
- musig, err := remoteSession.SignCommit(commitTx)
+ musig, err := remoteSession.signCommitAndCleanup(commitTx)
if err != nil {
var none lnwire.OptPartialSigWithNonceTLV
return none, err
@@ -5360,6 +5360,12 @@ func (i *InvalidPartialCommitSigError) Error() string {
i.invalidPartialSigError)
}
+// Unwrap returns the embedded InvalidCommitSigError, so callers matching on
+// *InvalidCommitSigError also handle invalid musig2 partial signatures.
+func (i *InvalidPartialCommitSigError) Unwrap() error {
+ return &i.InvalidCommitSigError
+}
+
// InvalidHtlcSigError is a struct that implements the error interface to
// report a failure to validate an htlc signature from a remote peer. We'll use
// the items in this struct to generate a rich error message for the remote
@@ -5531,7 +5537,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error {
if err != nil {
close(cancelChan)
- var sigErr invalidPartialSigError
+ var sigErr *invalidPartialSigError
if errors.As(err, &sigErr) {
// If we fail to validate their commitment
// signature, we'll generate a special error to
@@ -5541,7 +5547,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error {
var txBytes bytes.Buffer
_ = localCommitTx.Serialize(&txBytes)
return &InvalidPartialCommitSigError{
- invalidPartialSigError: &sigErr,
+ invalidPartialSigError: sigErr,
InvalidCommitSigError: InvalidCommitSigError{ //nolint:ll
commitHeight: nextHeight,
commitTx: txBytes.Bytes(),
### lnwallet/channel_test.go
@@ -6458,6 +6458,56 @@ func TestInvalidCommitSigError(t *testing.T) {
}
}
+// TestInvalidPartialCommitSigError tests that if the remote party sends us an
+// invalid musig2 partial signature for a taproot channel, then we'll reject it
+// and return an InvalidPartialCommitSigError carrying the commitment details.
+// The error must also match *InvalidCommitSigError, as that's what the link
+// uses to decide whether to send the debug data to the remote party.
+func TestInvalidPartialCommitSigError(t *testing.T) {
+ t.Parallel()
+
+ // First, we'll make a taproot channel between Alice and Bob.
+ aliceChannel, bobChannel, err := CreateTestChannels(
+ t, channeldb.SingleFunderTweaklessBit|
+ channeldb.AnchorOutputsBit|
+ channeldb.SimpleTaprootFeatureBit,
+ )
+ require.NoError(t, err, "unable to create test channels")
+
+ // With the channel established, we'll now send a single HTLC from
+ // Alice to Bob.
+ var htlcAmt lnwire.MilliSatoshi = 100000
+ htlc, _ := createHTLC(0, htlcAmt)
+ addAndReceiveHTLC(t, aliceChannel, bobChannel, htlc, nil)
+
+ // Alice will now attempt to initiate a state transition.
+ aliceNewCommit, err := aliceChannel.SignNextCommitment(ctxb)
+ require.NoError(t, err, "unable to sign new commit")
+
+ // Before the partial signature gets to Bob, we'll mutate it, such
+ // that the signature is now actually invalid.
+ partialSig, err := aliceNewCommit.PartialSig.UnwrapOrErrV(
+ errNoPartialSig,
+ )
+ require.NoError(t, err)
+ partialSig.Sig.SetInt(1)
+ aliceNewCommit.PartialSig = lnwire.MaybePartialSigWithNonce(
+ &partialSig,
+ )
+
+ // Bob should reject this new state, and return the proper error.
+ err = bobChannel.ReceiveNewCommitment(aliceNewCommit.CommitSigs)
+ require.Error(t, err)
+
+ var partialSigErr *InvalidPartialCommitSigError
+ require.ErrorAs(t, err, &partialSigErr)
+ require.EqualValues(t, 1, partialSigErr.commitHeight)
+ require.NotEmpty(t, partialSigErr.commitTx)
+
+ var commitSigErr *InvalidCommitSigError
+ require.ErrorAs(t, err, &commitSigErr)
+}
+
// TestChannelUnilateralCloseHtlcResolution tests that in the case of a
// unilateral channel closure, then the party that didn't broadcast the
// commitment is able to properly sweep all relevant outputs.
### lnwallet/musig_session.go
@@ -2,6 +2,7 @@ package lnwallet
import (
"bytes"
+ "errors"
"fmt"
"io"
@@ -336,6 +337,22 @@ func (m *MusigSession) FinalizeSession(signingNonce musig2.Nonces) error {
return nil
}
+// Cleanup releases the backing signer session once it is no longer needed.
+func (m *MusigSession) Cleanup() error {
+ if m.session == nil {
+ return nil
+ }
+
+ err := m.signer.MuSig2Cleanup(m.session.SessionID)
+ if err != nil {
+ return fmt.Errorf("unable to clean up musig2 session: %w", err)
+ }
+
+ m.session = nil
+
+ return nil
+}
+
// taprootKeyspendSighash generates the sighash for a taproot key spend. As
// this is a musig2 channel output, the keyspend is the only path we can take.
func taprootKeyspendSighash(tx *wire.MsgTx, pkScript []byte,
@@ -356,6 +373,34 @@ func taprootKeyspendSighash(tx *wire.MsgTx, pkScript []byte,
// remote) nonce. Given nonces should only ever be used once, once the method
// returns a new nonce is returned, w/ the existing nonce blanked out.
func (m *MusigSession) SignCommit(tx *wire.MsgTx) (*MusigPartialSig, error) {
+ return m.signCommit(tx, false)
+}
+
+// signCommitAndCleanup signs a commitment and releases the backing signer
+// session before returning. This is used when the partial signature is sent to
+// the remote party, which is responsible for combining it.
+func (m *MusigSession) signCommitAndCleanup(
+ tx *wire.MsgTx) (*MusigPartialSig, error) {
+
+ return m.signCommit(tx, true)
+}
+
+// signCommit signs the passed commitment and optionally releases the backing
+// signer session before returning.
+func (m *MusigSession) signCommit(tx *wire.MsgTx,
+ cleanUp bool) (*MusigPartialSig, error) {
+
+ // On the transient path we release the backing session even when
+ // signing fails, so the failed attempt doesn't leave a live session
+ // behind.
+ cleanupOnErr := func(err error) error {
+ if !cleanUp {
+ return err
+ }
+
+ return errors.Join(err, m.Cleanup())
+ }
+
switch {
// If we already have a session, then we don't need to finalize as this
// was done up front (symmetric nonce case, like for co-op close).
@@ -376,7 +421,7 @@ func (m *MusigSession) SignCommit(tx *wire.MsgTx) (*MusigPartialSig, error) {
})
signingNonce, err := musig2.GenNonces(nonceOpts...)
if err != nil {
- return nil, err
+ return nil, cleanupOnErr(err)
}
// When using deterministic nonce generation (test vector
@@ -387,7 +432,7 @@ func (m *MusigSession) SignCommit(tx *wire.MsgTx) (*MusigPartialSig, error) {
})
if err := m.FinalizeSession(*signingNonce); err != nil {
- return nil, err
+ return nil, cleanupOnErr(err)
}
// Otherwise, we're trying to make a new commitment transaction without
@@ -402,7 +447,7 @@ func (m *MusigSession) SignCommit(tx *wire.MsgTx) (*MusigPartialSig, error) {
tx, m.inputTxOut.PkScript, m.inputTxOut.Value,
)
if err != nil {
- return nil, err
+ return nil, cleanupOnErr(err)
}
// Now that we have our session created, we'll use it to generate the
@@ -414,25 +459,29 @@ func (m *MusigSession) SignCommit(tx *wire.MsgTx) (*MusigPartialSig, error) {
m.session.SessionID[:], m.nonces.String())
sig, err := m.signer.MuSig2Sign(
- m.session.SessionID, sigHashMsg, false,
+ m.session.SessionID, sigHashMsg, cleanUp,
)
if err != nil {
- return nil, err
+ return nil, cleanupOnErr(err)
}
tapscriptRoot := fn.MapOption(muSig2TweakToRoot)(m.tapscriptTweak)
-
- return NewMusigPartialSig(
+ partialSig := NewMusigPartialSig(
sig, m.session.PublicNonce, m.combinedNonce, m.signerKeys,
tapscriptRoot,
- ), nil
+ )
+ if cleanUp {
+ m.session = nil
+ }
+
+ return partialSig, nil
}
// Refresh is called once we receive a new verification nonce from the remote
// party after sending a signature. This nonce will be coupled within the
// revoke-and-ack message of the remote party.
-func (m *MusigSession) Refresh(verificationNonce *musig2.Nonces,
-) (*MusigSession, error) {
+func (m *MusigSession) Refresh(
+ verificationNonce *musig2.Nonces) (*MusigSession, error) {
return NewPartialMusigSession(
*verificationNonce, m.localKey, m.remoteKey, m.signer,
@@ -523,6 +572,16 @@ func (m *MusigSession) VerifyCommitSig(commitTx *wire.MsgTx,
return nil, fmt.Errorf("sig not provided")
}
+ // Release the backing signer session once we're done, whether the
+ // verification succeeded or failed.
+ defer func() {
+ err := m.Cleanup()
+ if err != nil {
+ walletLog.Errorf("unable to clean up musig2 "+
+ "session: %v", err)
+ }
+ }()
+
// Before we can verify the signature, we'll need to finalize the
// session by binding the remote party's provided signing nonce.
if err := m.FinalizeSession(musig2.Nonces{
@@ -588,16 +647,24 @@ func (m *MusigSession) VerifyCommitSig(commitTx *wire.MsgTx,
// CombineSigs combines the passed partial signatures into a valid schnorr
// signature.
-func (m *MusigSession) CombineSigs(sigs ...*musig2.PartialSignature,
-) (*schnorr.Signature, error) {
+func (m *MusigSession) CombineSigs(
+ sigs ...*musig2.PartialSignature) (*schnorr.Signature, error) {
- sig, _, err := m.signer.MuSig2CombineSig(
+ sig, haveAll, err := m.signer.MuSig2CombineSig(
m.session.SessionID, sigs,
)
if err != nil {
return nil, err
}
+ // Once all partial signatures have been combined, the signer has
+ // nothing left for this session and drops it from its session set. We
+ // mirror that here so a later Cleanup isn't run against a session the
+ // signer already removed.
+ if haveAll {
+ m.session = nil
+ }
+
return sig, nil
}
### lnwallet/musig_session_test.go
@@ -1,6 +1,7 @@
package lnwallet
import (
+ "crypto/sha256"
"testing"
"github.com/btcsuite/btcd/btcec/v2"
@@ -27,12 +28,80 @@ type muSessionHarness struct {
bobCommit *wire.MsgTx
aliceSession *MusigPairSession
+ aliceSigner *trackingMusigSigner
bobSession *MusigPairSession
+ bobSigner *trackingMusigSigner
t *testing.T
}
+// trackingMusigSigner records the sessions created and cleaned up by the
+// signer so tests can assert their lifecycle without reaching into its private
+// session map.
+type trackingMusigSigner struct {
+ *input.MockSigner
+
+ activeSessions map[input.MuSig2SessionID]struct{}
+}
+
+func newTrackingMusigSigner(signer *input.MockSigner) *trackingMusigSigner {
+ return &trackingMusigSigner{
+ MockSigner: signer,
+ activeSessions: make(map[input.MuSig2SessionID]struct{}),
+ }
+}
+
+// MuSig2CreateSession records each session created by the backing signer.
+func (s *trackingMusigSigner) MuSig2CreateSession(
+ version input.MuSig2Version, keyLoc keychain.KeyLocator,
+ signerKeys []*btcec.PublicKey, tweaks *input.MuSig2Tweaks,
+ otherNonces [][musig2.PubNonceSize]byte,
+ localNonces *musig2.Nonces) (*input.MuSig2SessionInfo, error) {
+
+ session, err := s.MockSigner.MuSig2CreateSession(
+ version, keyLoc, signerKeys, tweaks, otherNonces, localNonces,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ s.activeSessions[session.SessionID] = struct{}{}
+
+ return session, nil
+}
+
+// MuSig2Cleanup records each session removed from the backing signer.
+func (s *trackingMusigSigner) MuSig2Cleanup(
+ sessionID input.MuSig2SessionID) error {
+
+ err := s.MockSigner.MuSig2Cleanup(sessionID)
+ if err != nil {
+ return err
+ }
+
+ delete(s.activeSessions, sessionID)
+
+ return nil
+}
+
+// MuSig2Sign records sessions removed atomically by the signing call.
+func (s *trackingMusigSigner) MuSig2Sign(sessionID input.MuSig2SessionID,
+ msg [sha256.Size]byte,
+ cleanUp bool) (*musig2.PartialSignature, error) {
+
+ sig, err := s.MockSigner.MuSig2Sign(sessionID, msg, cleanUp)
+ if err != nil {
+ return nil, err
+ }
+
+ if cleanUp {
+ delete(s.activeSessions, sessionID)
+ }
+
+ return sig, nil
+}
+
func (h *muSessionHarness) selectSession(nodeName nodeType) *MusigPairSession {
var targetSession *MusigPairSession
switch nodeName {
@@ -78,7 +147,9 @@ func (h *muSessionHarness) refreshSession(nodeName nodeType,
func (h *muSessionHarness) SignCommitment(nodeName nodeType) *MusigPartialSig {
targetSession := h.selectSession(nodeName)
- sig, err := targetSession.RemoteSession.SignCommit(h.bobCommit)
+ sig, err := targetSession.RemoteSession.signCommitAndCleanup(
+ h.bobCommit,
+ )
require.NoError(h.t, err)
return sig
@@ -107,7 +178,9 @@ func (h *muSessionHarness) VerifyAndSignCommitment(nodeName nodeType,
// Next, sign a new version of the commitment for the remote party.
// This uses a JIT nonce that'll be sent along side the signature, and
// consumes the verification nonce of the remote party.
- remoteSig, err := muSession.RemoteSession.SignCommit(h.aliceCommit)
+ remoteSig, err := muSession.RemoteSession.signCommitAndCleanup(
+ h.aliceCommit,
+ )
require.NoError(h.t, err)
return remoteSig, nextVerificationNonce
@@ -162,15 +235,19 @@ func newMuSessionHarness(t *testing.T) *muSessionHarness {
})
alicePriv, alicePub := btcec.PrivKeyFromBytes(testWalletPrivKey)
- aliceSigner := input.NewMockSigner([]*btcec.PrivateKey{alicePriv}, nil)
+ aliceSigner := newTrackingMusigSigner(input.NewMockSigner(
+ []*btcec.PrivateKey{alicePriv}, nil,
+ ))
aliceVerificationNonce, err := musig2.GenNonces(
musig2.WithPublicKey(alicePub),
)
require.NoError(t, err)
bobPriv, bobPub := btcec.PrivKeyFromBytes(bobsPrivKey)
- bobSigner := input.NewMockSigner([]*btcec.PrivateKey{bobPriv}, nil)
+ bobSigner := newTrackingMusigSigner(input.NewMockSigner(
+ []*btcec.PrivateKey{bobPriv}, nil,
+ ))
bobVerificationNonce, err := musig2.GenNonces(
musig2.WithPublicKey(bobPub),
@@ -211,8 +288,10 @@ func newMuSessionHarness(t *testing.T) *muSessionHarness {
return &muSessionHarness{
aliceCommit: aliceCommit,
aliceSession: aliceSession,
+ aliceSigner: aliceSigner,
bobCommit: bobCommit,
bobSession: bobSession,
+ bobSigner: bobSigner,
t: t,
}
}
@@ -254,6 +333,9 @@ func TestMusigSesssion(t *testing.T) {
// Alice's new verification nonce.
muSessions.ProcessVerificationNonce(nodeBob, aliceNonce)
+ require.Empty(t, muSessions.aliceSigner.activeSessions)
+ require.Empty(t, muSessions.bobSigner.activeSessions)
+
// Modify the commitments after each round to simulate
// the LN protocol commitment randomness structure
// (sequence+locktime change each state, etc).
@@ -262,6 +344,30 @@ func TestMusigSesssion(t *testing.T) {
}
})
+ t.Run("retained session", func(t *testing.T) {
+ muSessions := newMuSessionHarness(t)
+ remoteSession := muSessions.aliceSession.RemoteSession
+
+ _, err := remoteSession.SignCommit(muSessions.bobCommit)
+ require.NoError(t, err)
+ require.Len(t, muSessions.aliceSigner.activeSessions, 1)
+
+ require.NoError(t, remoteSession.Cleanup())
+ require.Empty(t, muSessions.aliceSigner.activeSessions)
+ })
+
+ t.Run("invalid signature cleanup", func(t *testing.T) {
+ muSessions := newMuSessionHarness(t)
+ aliceSig := muSessions.SignCommitment(nodeAlice).ToWireSig()
+ aliceSig.Sig.SetInt(0)
+
+ _, err := muSessions.bobSession.LocalSession.VerifyCommitSig(
+ muSessions.bobCommit, aliceSig,
+ )
+ require.Error(t, err)
+ require.Empty(t, muSessions.bobSigner.activeSessions)
+ })
+
t.Run("no_finalize_error", func(t *testing.T) {
// If a local party attempts to sign for their local commitment
// without finalizing first, they'll get this error.
### lnwallet/wallet.go
@@ -1861,7 +1861,8 @@ func (l *LightningWallet) signCommitTx(pendingReservation *ChannelReservation,
// transaction. We use the remote session as this is for the
// remote commitment transaction.
musigSessions := pendingReservation.musigSessions
- partialSig, err := musigSessions.RemoteSession.SignCommit(
+ remoteSession := musigSessions.RemoteSession
+ partialSig, err := remoteSession.signCommitAndCleanup(
commitTx,
)
if err != nil {
### peer/musig_chan_closer.go
@@ -130,10 +130,20 @@ func (m *MusigChanCloser) InitRemoteNonce(nonce *musig2.Nonces) {
// InvalidateNonce clears the cached local nonce, forcing a fresh nonce to be
// generated on the next call to ClosingNonce. This prevents nonce reuse across
-// RBF iterations.
-func (m *MusigChanCloser) InvalidateNonce() {
+// RBF iterations. Any backing signer session is also released, as an aborted
+// round never reaches CombineSigs, which is the only other place the session
+// would be cleaned up.
+func (m *MusigChanCloser) InvalidateNonce() error {
m.localNonce = nil
+
+ if m.musigSession == nil {
+ return nil
+ }
+
+ err := m.musigSession.Cleanup()
m.musigSession = nil
+
+ return err
}
// A compile-time assertion to ensure MusigChanCloser implements the
### peer/musig_chan_closer_test.go
@@ -0,0 +1,151 @@
+package peer
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/btcsuite/btcd/txscript/v2"
+ "github.com/lightningnetwork/lnd/channeldb"
+ "github.com/lightningnetwork/lnd/input"
+ "github.com/lightningnetwork/lnd/lnwallet"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
+ "github.com/stretchr/testify/require"
+)
+
+// newDeliveryScript returns a dummy P2TR-compatible delivery script for the
+// co-op close tests.
+func newDeliveryScript(prefix byte) []byte {
+ script := bytes.Repeat([]byte{prefix}, 34)
+ script[0] = txscript.OP_1
+ script[1] = txscript.OP_DATA_32
+
+ return script
+}
+
+// TestMusigChanCloserCompletedRoundCleanup drives a full cooperative close
+// round against the real MusigSessionManager: both parties create their
+// partial signatures over the same close transaction via
+// CreateCloseProposal, the closer combines them via
+// CompleteCooperativeClose, and both then invalidate their nonce as the RBF
+// transitions do once a round completes.
+//
+// This is a regression test for two bugs: the round used to leave the
+// backing signer session in the manager when it completed, and once that was
+// fixed via Cleanup-on-InvalidateNonce, the post-round cleanup errored with
+// "session not found" because the signer had already dropped the session
+// during CombineSigs while MusigSession still held a reference to it.
+func TestMusigChanCloserCompletedRoundCleanup(t *testing.T) {
+ t.Parallel()
+
+ chanType := channeldb.SingleFunderTweaklessBit |
+ channeldb.AnchorOutputsBit | channeldb.SimpleTaprootFeatureBit
+
+ aliceChan, bobChan, err := lnwallet.CreateTestChannels(t, chanType)
+ require.NoError(t, err, "unable to create test channels")
+
+ // Both channels are backed by mock signers that hold real
+ // MusigSessionManagers, so we can watch their live session sets.
+ aliceSigner, ok := aliceChan.Signer.(*input.MockSigner)
+ require.True(t, ok, "expected mock signer for alice")
+ bobSigner, ok := bobChan.Signer.(*input.MockSigner)
+ require.True(t, ok, "expected mock signer for bob")
+
+ aliceCloser := NewMusigChanCloser(aliceChan)
+ bobCloser := NewMusigChanCloser(bobChan)
+
+ aliceScript := newDeliveryScript(0x01)
+ bobScript := newDeliveryScript(0x02)
+
+ // Exchange nonces: each party generates its own closing nonce and
+ // hands the public part to the other party, mirroring the shutdown /
+ // closing_complete nonce exchange.
+ aliceNonce, err := aliceCloser.ClosingNonce()
+ require.NoError(t, err, "unable to generate alice nonce")
+
+ bobNonce, err := bobCloser.ClosingNonce()
+ require.NoError(t, err, "unable to generate bob nonce")
+
+ aliceCloser.InitRemoteNonce(bobNonce)
+ bobCloser.InitRemoteNonce(aliceNonce)
+
+ // Both parties create their closing options, which creates the backing
+ // signer session on each side.
+ aliceOpts, err := aliceCloser.ProposalClosingOpts()
+ require.NoError(t, err, "unable to get alice closing opts")
+ require.Equal(t, 1, aliceSigner.NumLiveSessions())
+
+ bobOpts, err := bobCloser.ProposalClosingOpts()
+ require.NoError(t, err, "unable to get bob closing opts")
+ require.Equal(t, 1, bobSigner.NumLiveSessions())
+
+ // Both parties now sign the same close transaction.
+ feeRate := chainfee.SatPerKWeight(10000)
+ fee := aliceChan.CalcFee(feeRate)
+
+ aliceSig, aliceCloseTx, _, err := aliceChan.CreateCloseProposal(
+ fee, aliceScript, bobScript, aliceOpts...,
+ )
+ require.NoError(t, err, "unable to create alice close proposal")
+
+ bobSig, bobCloseTx, _, err := bobChan.CreateCloseProposal(
+ fee, bobScript, aliceScript, bobOpts...,
+ )
+ require.NoError(t, err, "unable to create bob close proposal")
+
+ // Both proposals must be over the same transaction for the partial
+ // signatures to combine.
+ require.Equal(t, aliceCloseTx.TxHash(), bobCloseTx.TxHash(),
+ "close proposals differ")
+
+ // The round completes: the closer (Alice) combines both partial
+ // signatures into the final schnorr signature. This drives the real
+ // MusigSessionManager, which drops the session from its set once all
+ // partial signatures are combined.
+ alicePartialSig, ok := aliceSig.(*lnwallet.MusigPartialSig)
+ require.True(t, ok, "expected musig partial sig for alice")
+ bobPartialSig, ok := bobSig.(*lnwallet.MusigPartialSig)
+ require.True(t, ok, "expected musig partial sig for bob")
+
+ localSig, remoteSig, combineOpts, err := aliceCloser.CombineClosingOpts(
+ alicePartialSig.ToWireSig().PartialSig,
+ bobPartialSig.ToWireSig().PartialSig,
+ )
+ require.NoError(t, err, "unable to combine closing opts")
+
+ _, _, err = aliceChan.CompleteCooperativeClose(
+ localSig, remoteSig, aliceScript, bobScript, fee,
+ combineOpts...,
+ )
+ require.NoError(t, err, "unable to complete cooperative close")
+
+ // The signer dropped the session during the combine, so nothing is
+ // live at this point.
+ require.Equal(t, 0, aliceSigner.NumLiveSessions(),
+ "combined session should be gone from the manager")
+
+ // The RBF transitions call InvalidateNonce once the round completes.
+ // This must not error even though the signer already removed the
+ // session during CombineSigs.
+ require.NoError(t, aliceCloser.InvalidateNonce(),
+ "post-round InvalidateNonce must not error")
+ require.Equal(t, 0, aliceSigner.NumLiveSessions())
+
+ // The closee (Bob) does the same on its side.
+ bobLocalSig, bobRemoteSig, bobCombineOpts, err :=
+ bobCloser.CombineClosingOpts(
+ bobPartialSig.ToWireSig().PartialSig,
+ alicePartialSig.ToWireSig().PartialSig,
+ )
+ require.NoError(t, err, "unable to combine bob closing opts")
+
+ _, _, err = bobChan.CompleteCooperativeClose(
+ bobLocalSig, bobRemoteSig, bobScript, aliceScript, fee,
+ bobCombineOpts...,
+ )
+ require.NoError(t, err, "unable to complete bob cooperative close")
+
+ require.Equal(t, 0, bobSigner.NumLiveSessions())
+ require.NoError(t, bobCloser.InvalidateNonce(),
+ "post-round InvalidateNonce must not error")
+ require.Equal(t, 0, bobSigner.NumLiveSessions())
+}Why this scored 51/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.