chancloser: preserve cooperative close variants
What changed, and why it matters
This commit fixes a bug in how the Lightning Network Daemon (LND) handles cooperative channel closes. Previously, when one peer chose a special close variant that omits the 'closee' output, the other peer would not correctly preserve that choice. This could cause both peers to build slightly different closing transactions and fail to agree on the final close. The patch makes the chosen close variant flow through the entire close process so both sides produce and sign the exact same transaction, for both older and newer taproot-style channels.
Reviewers should confirm that `closeSigCloseeOnly` is propagated in all close paths (not just `RemoteCloseStart`), and that omitting the remote output cannot be triggered by a malicious peer to remove a non-dust output against the BOLT spec. The new tests should be run and the change backported to affected release branches because a close-transaction mismatch can stall or break cooperative closes.
Security signals we found
Protocol state machine fix for cooperative close signature mismatch
New enum preserves all three BOLT-spec close-signature variants instead of collapsing them to a boolean
Adds option to omit remote closing output when building local proposal and final transaction
Adds tests covering legacy and taproot variants for both, closer-only, and closee-only cases
Adds integration test verifying both peers sign identical transaction when remote output is omitted
Evidence from the diff
The change replaces a boolean noClosee flag with a three-valued closeSigVariant enum (closeSigBoth, closeSigCloserOnly, closeSigCloseeOnly) throughout the RBF cooperative close state machine. selectAndExtractSig now returns the exact variant selected from the incoming ClosingComplete message, and RemoteCloseStart.ProcessEvent carries it into createClosingSigMessage. A new WithOmittedRemoteCloseOutput() option is added to CreateCloseProposal and CompleteCooperativeClose, and CreateCooperativeCloseTx skips adding the remote output when that option is set. This ensures the closee replies with a signature covering the same transaction variant the closer proposed, matching BOLT spec priorities for legacy and taproot channels.
Changed components
lnwallet/chancloser/rbf_coop_transitions.golnwallet/channel.golnwallet/chancloser/rbf_coop_test.golnwallet/chancloser/rbf_reply_variant_test.golnwallet/close_omitted_output_test.goInspect captured patch +339 / −29
### lnwallet/chancloser/rbf_coop_test.go
@@ -2838,6 +2838,51 @@ func TestRbfCloseClosingNegotiationRemote(t *testing.T) {
closeHarness.assertNoStateTransitions()
})
+ t.Run("recv_offer_closee_only_reply", func(t *testing.T) {
+ terms := *closeTerms
+ terms.RemoteBalance = lnwire.NewMSatFromSatoshis(
+ absoluteFee + 10000,
+ )
+ state := &ClosingNegotiation{
+ PeerState: lntypes.Dual[AsymmetricPeerState]{
+ Remote: &RemoteCloseStart{
+ CloseChannelTerms: &terms,
+ },
+ },
+ CloseChannelTerms: &terms,
+ }
+ h := newCloser(t, &harnessCfg{
+ initialState: fn.Some[ProtocolState](state),
+ })
+ defer h.stopAndAssert()
+
+ h.expectNewCloseSig(localAddr, remoteAddr, absoluteFee, 1)
+ h.expectCloseFinalized(
+ &localSig, &remoteSig, localAddr, remoteAddr,
+ absoluteFee, 1, false,
+ )
+ matcher := func(msg *lnwire.ClosingSig) bool {
+ return msg.ClosingSigs.NoCloserClosee.IsSome() &&
+ msg.ClosingSigs.CloserAndClosee.IsNone() &&
+ msg.ClosingSigs.CloserNoClosee.IsNone()
+ }
+ h.expectMsgSent(singleMsgMatcher(matcher))
+ h.chanCloser.SendEvent(ctx, &OfferReceivedEvent{
+ SigMsg: lnwire.ClosingComplete{
+ FeeSatoshis: absoluteFee,
+ CloserScript: remoteAddr,
+ CloseeScript: localAddr,
+ ClosingSigs: lnwire.ClosingSigs{
+ NoCloserClosee: newSigTlv[tlv.TlvType2](
+ remoteWireSig,
+ ),
+ },
+ },
+ })
+ h.assertStateTransitions(&ClosingNegotiation{})
+ h.waitForMsgSent()
+ })
+
// When both CloserNoClosee AND CloserAndClosee are present (which is
// spec-compliant), the closee should select CloserAndClosee when local
// output is not dust.
### lnwallet/chancloser/rbf_coop_transitions.go
@@ -1361,7 +1361,7 @@ func selectTaprootPartialSigWithNonce(
func createClosingSigMessage(env *Environment, wireSig lnwire.Sig,
localSig input.Signature,
localScript, remoteScript lnwire.DeliveryAddress, fee btcutil.Amount,
- lockTime uint32, noClosee bool) (*lnwire.ClosingSig, error) {
+ lockTime uint32, variant closeSigVariant) (*lnwire.ClosingSig, error) {
var (
closingSigs lnwire.ClosingSigs
@@ -1384,11 +1384,16 @@ func createClosingSigMessage(env *Environment, wireSig lnwire.Sig,
wireSigWithNonce := musigSig.ToWireSig()
partialSig := wireSigWithNonce.PartialSig
- if noClosee {
+ switch variant {
+ case closeSigCloserOnly:
taprootPartialSigs.CloserNoClosee = tlv.SomeRecordT(
tlv.NewRecordT[tlv.TlvType5](partialSig),
)
- } else {
+ case closeSigCloseeOnly:
+ taprootPartialSigs.NoCloserClosee = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType6](partialSig),
+ )
+ default:
taprootPartialSigs.CloserAndClosee = tlv.SomeRecordT(
tlv.NewRecordT[tlv.TlvType7](partialSig),
)
@@ -1410,11 +1415,16 @@ func createClosingSigMessage(env *Environment, wireSig lnwire.Sig,
)
} else {
// Non-taproot: use regular signatures.
- if noClosee {
+ switch variant {
+ case closeSigCloserOnly:
closingSigs.CloserNoClosee = newSigTlv[tlv.TlvType1](
wireSig,
)
- } else {
+ case closeSigCloseeOnly:
+ closingSigs.NoCloserClosee = newSigTlv[tlv.TlvType2](
+ wireSig,
+ )
+ default:
closingSigs.CloserAndClosee = newSigTlv[tlv.TlvType3](
wireSig,
)
@@ -1877,41 +1887,50 @@ func validateSigFields(sigFields SigFieldSet, localIsDust bool) error {
return nil
}
+// closeSigVariant identifies the outputs covered by a closing signature.
+type closeSigVariant uint8
+
+const (
+ closeSigBoth closeSigVariant = iota
+ closeSigCloserOnly
+ closeSigCloseeOnly
+)
+
// selectAndExtractSig selects the appropriate signature field based on BOLT
// spec priority and extracts the signature and nonce.
func selectAndExtractSig(
fields SigFieldSet, localIsDust bool,
-) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], bool,
+) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], closeSigVariant,
error) {
// Select which field to use based on BOLT spec priority.
var (
selectedField fn.Option[SigType]
- isNoClosee bool
+ variant closeSigVariant
)
if localIsDust {
// Spec step 1: Local output is dust, use
// CloserNoClosee.
selectedField = fields.CloserNoClosee
- isNoClosee = true
+ variant = closeSigCloserOnly
} else {
// Spec step 3: Prefer CloserAndClosee if present.
if fields.CloserAndClosee.IsSome() {
selectedField = fields.CloserAndClosee
- isNoClosee = false
+ variant = closeSigBoth
} else {
// Spec step 4: Fallback to NoCloserClosee.
selectedField = fields.NoCloserClosee
- isNoClosee = false
+ variant = closeSigCloseeOnly
}
}
// If the selected field is none, this is an error.
sigType, err := selectedField.UnwrapOrErr(ErrNoSig)
if err != nil {
return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
- false, err
+ closeSigBoth, err
}
// Check if this is a taproot signature (Right side of
@@ -1931,7 +1950,7 @@ func selectAndExtractSig(
sig = partialSigToWireSig(ps.PartialSig)
})
- return sig, nonce, isNoClosee, nil
+ return sig, nonce, variant, nil
}
// extractSigAndNonceFromClosingComplete extracts signature and optional
@@ -1943,7 +1962,7 @@ func selectAndExtractSig(
func extractSigAndNonceFromClosingComplete(
msg lnwire.ClosingComplete,
localIsDust, isTaproot bool,
-) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], bool,
+) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], closeSigVariant,
error) {
// First, parse the message to extract which signature fields are
@@ -1955,33 +1974,38 @@ func extractSigAndNonceFromClosingComplete(
// have regular signatures.
switch {
case isTaproot && !fields.IsTaproot() && fields.HasAnySig():
- return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](), false,
- fmt.Errorf("taproot channel requires taproot " +
- "signatures, got regular signatures")
+ return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
+ closeSigBoth, fmt.Errorf(
+ "taproot channel requires taproot " +
+ "signatures, got regular signatures",
+ )
case !isTaproot && fields.IsTaproot():
- return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](), false,
- fmt.Errorf("non-taproot channel requires regular " +
- "signatures, got taproot signatures")
+ return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
+ closeSigBoth, fmt.Errorf(
+ "non-taproot channel requires regular " +
+ "signatures, got taproot signatures",
+ )
}
// Next, validate that the parsed fields conform to BOLT spec
// requirements based on our (closee's) output dust status.
if err := validateSigFields(fields, localIsDust); err != nil {
- return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](), false, err
+ return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
+ closeSigBoth, err
}
// Finally, select and extract the appropriate signature
// based on BOLT spec priority.
- sig, nonce, isNoClosee, err := selectAndExtractSig(
+ sig, nonce, variant, err := selectAndExtractSig(
fields, localIsDust,
)
if err != nil {
return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
- false, err
+ closeSigBoth, err
}
- return sig, nonce, isNoClosee, nil
+ return sig, nonce, variant, nil
}
// ProcessEvent implements the state transition function for the
@@ -2009,9 +2033,10 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
// Extract the signature and JIT nonce from the ClosingComplete
// message. This function parses, validates, and selects the
// appropriate signature per BOLT spec.
- sig, jitNonce, noClosee, err := extractSigAndNonceFromClosingComplete( //nolint:ll
- msg.SigMsg, l.LocalAmtIsDust(), env.IsTaproot(),
- )
+ sig, jitNonce, variant, err :=
+ extractSigAndNonceFromClosingComplete(
+ msg.SigMsg, l.LocalAmtIsDust(), env.IsTaproot(),
+ )
if err != nil {
return nil, err
}
@@ -2022,6 +2047,13 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
lnwallet.WithCustomPayer(lntypes.Remote),
}
+ if variant == closeSigCloseeOnly {
+ chanOpts = append(
+ chanOpts,
+ lnwallet.WithOmittedRemoteCloseOutput(),
+ )
+ }
+
var remoteSig input.Signature
// For taproot channels, add MusigSession options if available.
@@ -2034,7 +2066,8 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
// This must happen before ProposalClosingOpts() which
// requires the nonce to be set.
remoteSig, err = processRemoteTaprootSig(
- env, msg.SigMsg, jitNonce, noClosee,
+ env, msg.SigMsg, jitNonce,
+ variant == closeSigCloserOnly,
)
if err != nil {
return nil, err
@@ -2110,7 +2143,7 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
closingSigMsg, err := createClosingSigMessage(
env, wireSig, localSig, l.LocalDeliveryScript,
l.RemoteDeliveryScript, msg.SigMsg.FeeSatoshis,
- msg.SigMsg.LockTime, noClosee,
+ msg.SigMsg.LockTime, variant,
)
if err != nil {
return nil, err
### lnwallet/chancloser/rbf_reply_variant_test.go
@@ -0,0 +1,160 @@
+package chancloser
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/btcsuite/btcd/wire/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lnwallet"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+type closeReplyCase struct {
+ name string
+ variant closeSigVariant
+ local, remote btcutil.Amount
+}
+
+func TestCloseeReplyVariants(t *testing.T) {
+ for _, taproot := range []bool{false, true} {
+ for _, tc := range []closeReplyCase{
+ {"both", closeSigBoth, 10000, 10000},
+ {"closer only", closeSigCloserOnly, 1, 10000},
+ {"closee only", closeSigCloseeOnly, 10000, 1},
+ } {
+ name := tc.name + map[bool]string{
+ true: " taproot", false: " legacy",
+ }[taproot]
+ t.Run(name, func(t *testing.T) {
+ testCloseeReplyVariant(t, tc, taproot)
+ })
+ }
+ }
+}
+
+func testCloseeReplyVariant(t *testing.T, tc closeReplyCase, taproot bool) {
+ var scalar btcec.ModNScalar
+ scalar.SetInt(1)
+ key, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ partial := musig2.NewPartialSignature(&scalar, key.PubKey())
+ localPartial := lnwallet.NewMusigPartialSig(
+ &partial, lnwire.Musig2Nonce{}, lnwire.Musig2Nonce{}, nil,
+ fn.None[chainhash.Hash](),
+ )
+ remotePartial := lnwire.PartialSigWithNonce{
+ PartialSig: lnwire.PartialSig{Sig: scalar},
+ Nonce: lnwire.Musig2Nonce{1, 2, 3},
+ }
+
+ msg := lnwire.ClosingComplete{}
+ if taproot {
+ switch tc.variant {
+ case closeSigBoth:
+ msg.TaprootClosingSigs.CloserAndClosee =
+ newPartialSigWithNonceTlv[tlv.TlvType7](
+ remotePartial,
+ )
+ case closeSigCloserOnly:
+ msg.TaprootClosingSigs.CloserNoClosee =
+ newPartialSigWithNonceTlv[tlv.TlvType5](
+ remotePartial,
+ )
+ case closeSigCloseeOnly:
+ msg.TaprootClosingSigs.NoCloserClosee =
+ newPartialSigWithNonceTlv[tlv.TlvType6](
+ remotePartial,
+ )
+ }
+ } else {
+ switch tc.variant {
+ case closeSigBoth:
+ msg.ClosingSigs.CloserAndClosee =
+ newSigTlv[tlv.TlvType3](
+ remoteWireSig,
+ )
+ case closeSigCloserOnly:
+ msg.ClosingSigs.CloserNoClosee =
+ newSigTlv[tlv.TlvType1](
+ remoteWireSig,
+ )
+ case closeSigCloseeOnly:
+ msg.ClosingSigs.NoCloserClosee =
+ newSigTlv[tlv.TlvType2](
+ remoteWireSig,
+ )
+ }
+ }
+ dust := lnwallet.DustLimitForSize(len(localAddr))
+ _, _, variant, err := extractSigAndNonceFromClosingComplete(
+ msg, tc.local < dust, taproot,
+ )
+ require.NoError(t, err)
+ require.Equal(t, tc.variant, variant)
+
+ tx, err := lnwallet.CreateCooperativeCloseTx(
+ wire.TxIn{}, dust, dust, tc.local, tc.remote,
+ localAddr, remoteAddr,
+ )
+ require.NoError(t, err)
+ haveLocal, haveRemote := false, false
+ for _, out := range tx.TxOut {
+ if string(out.PkScript) == string(localAddr) {
+ haveLocal = true
+ }
+ if string(out.PkScript) == string(remoteAddr) {
+ haveRemote = true
+ }
+ }
+ require.Equal(t, tc.variant != closeSigCloserOnly, haveLocal)
+ require.Equal(t, tc.variant != closeSigCloseeOnly, haveRemote)
+
+ env := &Environment{}
+ if taproot {
+ env.LocalMusigSession = newMockMusigSession()
+ env.RemoteMusigSession = newMockMusigSession()
+ }
+ reply, err := createClosingSigMessage(
+ env, localSigWire, localPartial, localAddr,
+ remoteAddr, 0, 0, variant,
+ )
+ require.NoError(t, err)
+
+ // The mock session's nonce is not a valid curve point.
+ if taproot {
+ var nonce lnwire.Musig2Nonce
+ copy(nonce[:33], key.PubKey().SerializeCompressed())
+ copy(nonce[33:], key.PubKey().SerializeCompressed())
+ reply.NextCloseeNonce = newNonceTlv(nonce)
+ }
+ var encoded bytes.Buffer
+ require.NoError(t, reply.Encode(&encoded, 0))
+ var decoded lnwire.ClosingSig
+ require.NoError(t, decoded.Decode(&encoded, 0))
+ result, _ := validateAndExtractSigAndNonce(decoded, taproot)
+ _, err = result.Unpack()
+ require.NoError(t, err)
+ reply = &decoded
+ if taproot {
+ require.Equal(t, variant == closeSigBoth,
+ reply.TaprootPartialSigs.CloserAndClosee.IsSome())
+ require.Equal(t, variant == closeSigCloserOnly,
+ reply.TaprootPartialSigs.CloserNoClosee.IsSome())
+ require.Equal(t, variant == closeSigCloseeOnly,
+ reply.TaprootPartialSigs.NoCloserClosee.IsSome())
+ } else {
+ require.Equal(t, variant == closeSigBoth,
+ reply.ClosingSigs.CloserAndClosee.IsSome())
+ require.Equal(t, variant == closeSigCloserOnly,
+ reply.ClosingSigs.CloserNoClosee.IsSome())
+ require.Equal(t, variant == closeSigCloseeOnly,
+ reply.ClosingSigs.NoCloserClosee.IsSome())
+ }
+}
### lnwallet/channel.go
@@ -8711,6 +8711,8 @@ type chanCloseOpt struct {
customLockTime fn.Option[uint32]
customPayer fn.Option[lntypes.ChannelParty]
+
+ omitRemoteOutput bool
}
// ChanCloseOpt is a closure type that cen be used to modify the set of default
@@ -8731,6 +8733,13 @@ func WithCoopCloseMusigSession(session *MusigSession) ChanCloseOpt {
}
}
+// WithOmittedRemoteCloseOutput omits the remote party's closing output.
+func WithOmittedRemoteCloseOutput() ChanCloseOpt {
+ return func(opts *chanCloseOpt) {
+ opts.omitRemoteOutput = true
+ }
+}
+
// WithExtraCloseOutputs can be used to add extra outputs to the cooperative
// transaction.
func WithExtraCloseOutputs(extraOutputs []CloseOutput) ChanCloseOpt {
@@ -8827,6 +8836,9 @@ func (lc *LightningChannel) CreateCloseProposal(proposedFee btcutil.Amount,
opts.extraCloseOutputs,
))
}
+ if opts.omitRemoteOutput {
+ closeTxOpts = append(closeTxOpts, withOmittedRemoteTxOutput())
+ }
if opts.customSort != nil {
closeTxOpts = append(
closeTxOpts, WithCustomTxSort(opts.customSort),
@@ -8941,6 +8953,9 @@ func (lc *LightningChannel) CompleteCooperativeClose(
opts.extraCloseOutputs,
))
}
+ if opts.omitRemoteOutput {
+ closeTxOpts = append(closeTxOpts, withOmittedRemoteTxOutput())
+ }
if opts.customSort != nil {
closeTxOpts = append(
closeTxOpts, WithCustomTxSort(opts.customSort),
@@ -9725,6 +9740,8 @@ type closeTxOpts struct {
customSequence fn.Option[uint32]
customLockTime fn.Option[uint32]
+
+ omitRemoteOutput bool
}
// defaultCloseTxOpts returns a closeTxOpts struct with default values.
@@ -9738,6 +9755,12 @@ func defaultCloseTxOpts() closeTxOpts {
// transaction is created.
type CloseTxOpt func(*closeTxOpts)
+func withOmittedRemoteTxOutput() CloseTxOpt {
+ return func(o *closeTxOpts) {
+ o.omitRemoteOutput = true
+ }
+}
+
// WithRBFCloseTx signals that the cooperative close tx should signal RBF.
func WithRBFCloseTx() CloseTxOpt {
return func(o *closeTxOpts) {
@@ -9835,7 +9858,7 @@ func CreateCooperativeCloseTx(fundingTxIn wire.TxIn,
}
var remoteOutputIdx fn.Option[int]
- haveRemoteOutput := theirBalance >= remoteDust
+ haveRemoteOutput := theirBalance >= remoteDust && !opts.omitRemoteOutput
if haveRemoteOutput {
// If a party's script is an OP_RETURN, then we set their
// balance to zero.
### lnwallet/close_omitted_output_test.go
@@ -0,0 +1,49 @@
+package lnwallet
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/btcsuite/btcd/wire/v2"
+ "github.com/lightningnetwork/lnd/channeldb"
+ "github.com/stretchr/testify/require"
+)
+
+// TestCooperativeCloseOmittedRemoteOutput verifies both signatures cover the
+// same transaction when the closer omits its non-dust output.
+func TestCooperativeCloseOmittedRemoteOutput(t *testing.T) {
+ alice, bob, err := CreateTestChannels(
+ t, channeldb.SingleFunderTweaklessBit,
+ )
+ require.NoError(t, err)
+ aliceScript, bobScript := bobsPrivKey, testHdSeed[:]
+ fee := btcutil.Amount(10000)
+ omitAlice := WithCustomCoopSort(func(tx *wire.MsgTx) error {
+ var outs []*wire.TxOut
+ for _, out := range tx.TxOut {
+ if !bytes.Equal(out.PkScript, aliceScript) {
+ outs = append(outs, out)
+ }
+ }
+ tx.TxOut = outs
+
+ return nil
+ })
+ aliceSig, aliceTx, _, err := alice.CreateCloseProposal(
+ fee, aliceScript, bobScript, omitAlice,
+ )
+ require.NoError(t, err)
+ bobSig, bobTx, _, err := bob.CreateCloseProposal(
+ fee, bobScript, aliceScript, WithOmittedRemoteCloseOutput(),
+ )
+ require.NoError(t, err)
+ require.Len(t, aliceTx.TxOut, 1)
+ require.Equal(t, aliceTx.TxHash(), bobTx.TxHash())
+ tx, _, err := bob.CompleteCooperativeClose(
+ bobSig, aliceSig, bobScript, aliceScript, fee,
+ WithOmittedRemoteCloseOutput(),
+ )
+ require.NoError(t, err)
+ require.Equal(t, aliceTx.TxHash(), tx.TxHash())
+}Why this scored 59/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.