Merge pull request #11575 from Roasbeef/rbf-coop-close-lifecycle
What changed, and why it matters
This commit fixes bugs in LND's new RBF-style cooperative channel close feature. Previously, fee-bump requests could be dropped or block the peer's main goroutine while waiting for an in-progress offer. The patch buffers those requests inside the state machine, lets callers cancel only their own buffered bump, and ensures that once a close is confirmed the channel and switch link are torn down for both locally and remotely initiated closes. It also cleans up how the peer recovers from state-machine errors and retries.
Treat this as a bug-fix patch for the RBF cooperative close subsystem. Reviewers should verify that buffered `LocalCloseReq` events cannot be replayed after `CloseFin`, that `CancelPendingOffer` sequence numbers cannot collide or be forged by a remote peer, and that `WipeChannel` is safe to call from the lifecycle sentinel goroutine. Operators running nodes that use RBF cooperative close should plan to upgrade once this reaches a release.
Security signals we found
Denial-of-service / liveness fix: fee-bump requests no longer block the peer's `channelManager` goroutine while waiting for an in-flight offer.
State consistency fix: buffered fee-bump requests are now part of the FSM state instead of being dropped during shutdown or flush.
Resource-leak fix: confirmed RBF closes now tear down the active channel state and switch link for both local and remote-initiated closes.
Race/identity fix: RPC callers are bound to a specific live closer via `isSameLiveRbfCloser`, preventing stale observers from acting on replaced or stopped state machines.
Error-handling fix: FSM errors now answer waiting callers and retire the stopped closer before re-initializing, avoiding leaked registrations and duplicate endpoints.
Evidence from the diff
The change refactors the RBF cooperative close lifecycle in lnwallet/chancloser and peer/brontide. It introduces LocalCloseReq and CancelPendingOffer protocol events, buffers pending fee-bump offers in ShutdownPending, ChannelFlushing, and LocalOfferSent, and routes them through the FSM instead of blocking channelManager. LocalCloseReq is accepted in every state. CancelPendingOffer is sequence-scoped so a cancelled RPC caller only retracts its own unstarted bump. CloseFin now triggers a single lifecycle sentinel (rbfCloserLifecycleSentinel) that retires the closer, reports success, and calls WipeChannel to remove the active channel and switch link. ReportError now aborts waiting callers, retires the old closer, and re-initializes a fresh one only when an active channel still exists. The generic state machine gains a Done() channel.
Changed components
lnwallet/chancloser/rbf_coop_states.golnwallet/chancloser/rbf_coop_transitions.golnwallet/chancloser/rbf_coop_test.gopeer/brontide.gopeer/brontide_test.gopeer/test_utils.goprotofsm/state_machine.goInspect captured patch +1538 / −424
### docs/release-notes/unreleased/11575.md
@@ -0,0 +1,8 @@
+# Bug Fixes
+
+* [RBF cooperative close fee bumps](https://github.com/lightningnetwork/lnd/pull/11575)
+ are now buffered inside the `RbfChanCloser` state machine instead of being
+ dropped during shutdown or flushing or blocking the peer's `channelManager`
+ goroutine while waiting on an in-flight offer. Confirmed RBF closes also now
+ tear down the channel's active state and switch link for both local and
+ remote-initiated closes.
### lnwallet/chancloser/rbf_coop_states.go
@@ -75,7 +75,7 @@ type ProtocolEvent interface {
type ProtocolEvents interface {
SendShutdown | ShutdownReceived | ShutdownComplete | ChannelFlushed |
SendOfferEvent | OfferReceivedEvent | LocalSigReceived |
- SpendEvent
+ SpendEvent | LocalCloseReq | CancelPendingOffer
}
// SpendEvent indicates that a transaction spending the funding outpoint has
@@ -116,6 +116,45 @@ type SendShutdown struct {
// protocolSealed indicates that this struct is a ProtocolEvent instance.
func (s *SendShutdown) protocolSealed() {}
+// PendingLocalOffer holds a fee-bump request buffered while the state machine
+// cannot yet send a new closing_complete offer.
+type PendingLocalOffer struct {
+ // TargetFeeRate is the requested fee rate for the next offer.
+ TargetFeeRate chainfee.SatPerVByte
+
+ // Seq identifies the caller request so a cancelled caller only retracts
+ // its own unstarted bump.
+ Seq uint64
+}
+
+// LocalCloseReq represents a local cooperative close or fee-bump request. It
+// is valid in every state of the RBF closer, avoiding out-of-band state polling
+// and blocking waits.
+type LocalCloseReq struct {
+ // DeliveryAddr is the address we'd like to receive the funds to on the
+ // initial shutdown. Ignored once shutdown has already begun.
+ DeliveryAddr fn.Option[lnwire.DeliveryAddress]
+
+ // TargetFeeRate is the explicit fee rate requested by the caller, or
+ // None when resuming a shutdown from persisted state.
+ TargetFeeRate fn.Option[chainfee.SatPerVByte]
+
+ // Seq uniquely identifies this request when buffered.
+ Seq uint64
+}
+
+// protocolSealed indicates that this struct is a ProtocolEvent instance.
+func (l *LocalCloseReq) protocolSealed() {}
+
+// CancelPendingOffer retracts a buffered fee-bump request if it has not yet
+// been sent and still matches Seq.
+type CancelPendingOffer struct {
+ Seq uint64
+}
+
+// protocolSealed indicates that this struct is a ProtocolEvent instance.
+func (c *CancelPendingOffer) protocolSealed() {}
+
// ShutdownReceived indicates that we received a shutdown event so we need to
// enter the flushing state.
//
@@ -492,6 +531,14 @@ type ShutdownPending struct {
// NonceState tracks the nonces exchanged during shutdown for taproot
// channels.
NonceState NonceState
+
+ // LocalCloseRequested is true once a local close or restart shutdown
+ // has been initiated.
+ LocalCloseRequested bool
+
+ // PendingBump holds a fee-bump request that arrived while shutdown was
+ // already pending.
+ PendingBump fn.Option[PendingLocalOffer]
}
// String returns the name of the state for ShutdownPending.
@@ -536,6 +583,14 @@ type ChannelFlushing struct {
// NonceState tracks the nonces exchanged during shutdown for taproot
// channels.
NonceState NonceState
+
+ // LocalCloseRequested is true once a local close or restart shutdown
+ // has been initiated.
+ LocalCloseRequested bool
+
+ // PendingBump holds a fee-bump request that arrived while the channel
+ // was flushing.
+ PendingBump fn.Option[PendingLocalOffer]
}
// String returns the name of the state for ChannelFlushing.
@@ -753,7 +808,7 @@ func (l *LocalCloseStart) String() string {
// event.
func (l *LocalCloseStart) ShouldRouteTo(event ProtocolEvent) bool {
switch event.(type) {
- case *SendOfferEvent:
+ case *SendOfferEvent, *LocalCloseReq:
return true
default:
return false
@@ -796,6 +851,10 @@ type LocalOfferSent struct {
// signatures without re-signing, which prevents nonce reuse across
// RBF iterations. Only set for taproot channels.
LocalMusigSig fn.Option[lnwallet.MusigPartialSig]
+
+ // PendingOffer holds a fee-bump request that arrived while waiting for
+ // the remote party's signature on the current offer.
+ PendingOffer fn.Option[PendingLocalOffer]
}
// String returns the name of the state for LocalOfferSent, including proposed.
@@ -807,7 +866,7 @@ func (l *LocalOfferSent) String() string {
// event.
func (l *LocalOfferSent) ShouldRouteTo(event ProtocolEvent) bool {
switch event.(type) {
- case *LocalSigReceived:
+ case *LocalSigReceived, *LocalCloseReq, *CancelPendingOffer:
return true
default:
return false
@@ -868,13 +927,14 @@ func (c *ClosePending) ShouldRouteTo(event ProtocolEvent) bool {
return true
default:
switch {
- case c.Party == lntypes.Local && isType[*SendOfferEvent](event):
+ case c.Party == lntypes.Local &&
+ (isType[*SendOfferEvent](event) ||
+ isType[*LocalCloseReq](event)):
return true
case c.Party == lntypes.Remote && isType[*OfferReceivedEvent](
event,
):
-
return true
}
@@ -970,13 +1030,14 @@ func (c *CloseErr) ShouldRouteTo(event ProtocolEvent) bool {
return true
default:
switch {
- case c.Party == lntypes.Local && isType[*SendOfferEvent](event):
+ case c.Party == lntypes.Local &&
+ (isType[*SendOfferEvent](event) ||
+ isType[*LocalCloseReq](event)):
return true
case c.Party == lntypes.Remote && isType[*OfferReceivedEvent](
event,
):
-
return true
}
### lnwallet/chancloser/rbf_coop_test.go
@@ -3460,3 +3460,255 @@ func TestLocalOfferSentUsesStoredSig(t *testing.T) {
"NonceState (not NextCloseeNonce from ClosingSig)",
)
}
+
+// TestRbfLocalCloseReqBuffering verifies that LocalCloseReq is absorbed across
+// ShutdownPending, ChannelFlushing, and LocalOfferSent without error, and that
+// CancelPendingOffer only retracts a matching buffered bump.
+func TestRbfLocalCloseReqBuffering(t *testing.T) {
+ t.Parallel()
+ ctx := t.Context()
+
+ localBalance := lnwire.NewMSatFromSatoshis(500_000)
+ remoteBalance := lnwire.NewMSatFromSatoshis(500_000)
+ initialRate := chainfee.FeePerKwFloor.FeePerVByte()
+ bumpRate := initialRate * 5
+ bumpAbsFee := btcutil.Amount(5000)
+
+ t.Run("bump_in_shutdown_pending_and_flushing", func(t *testing.T) {
+ startingState := &ShutdownPending{
+ IdealFeeRate: fn.Some(initialRate),
+ ShutdownScripts: ShutdownScripts{
+ LocalDeliveryScript: localAddr,
+ },
+ LocalCloseRequested: true,
+ }
+ closeHarness := newCloser(t, &harnessCfg{
+ initialState: fn.Some[ProtocolState](startingState),
+ })
+ defer closeHarness.stopAndAssert()
+
+ // Send a bump while still in ShutdownPending.
+ closeHarness.chanCloser.SendEvent(ctx, &LocalCloseReq{
+ TargetFeeRate: fn.Some(bumpRate),
+ Seq: 1,
+ })
+ closeHarness.assertStateTransitions(&ShutdownPending{})
+
+ // Receive remote shutdown and transition to ChannelFlushing.
+ closeHarness.expectFinalBalances(fn.None[ShutdownBalances]())
+ closeHarness.expectIncomingAddsDisabled()
+ closeHarness.chanCloser.SendEvent(ctx, &ShutdownReceived{
+ ShutdownScript: remoteAddr,
+ })
+ closeHarness.assertStateTransitions(&ChannelFlushing{})
+
+ // Send another bump while flushing; it should supersede the
+ // previous one.
+ higherRate := bumpRate * 2
+ closeHarness.chanCloser.SendEvent(ctx, &LocalCloseReq{
+ TargetFeeRate: fn.Some(higherRate),
+ Seq: 2,
+ })
+ closeHarness.assertStateTransitions(&ChannelFlushing{})
+
+ // Cancelling the superseded seq must not clear seq 2.
+ closeHarness.chanCloser.SendEvent(ctx, &CancelPendingOffer{
+ Seq: 1,
+ })
+ closeHarness.assertStateTransitions(&ChannelFlushing{})
+
+ // Once flushed, the closer should immediately propose at
+ // higherRate.
+ balanceAfterClose := localBalance.ToSatoshis() - bumpAbsFee
+ flushEvent := &ChannelFlushed{
+ ShutdownBalances: ShutdownBalances{
+ LocalBalance: localBalance,
+ RemoteBalance: remoteBalance,
+ },
+ }
+ closeHarness.expectHalfSignerIteration(
+ flushEvent, balanceAfterClose, bumpAbsFee, noDustExpect,
+ false,
+ )
+ })
+
+ t.Run("bump_in_shutdown_pending_unpayable_enters_close_err", func(t *testing.T) { //nolint:ll
+ startingState := &ShutdownPending{
+ IdealFeeRate: fn.Some(initialRate),
+ ShutdownScripts: ShutdownScripts{
+ LocalDeliveryScript: localAddr,
+ },
+ }
+ closeHarness := newCloser(t, &harnessCfg{
+ initialState: fn.Some[ProtocolState](startingState),
+ })
+ defer closeHarness.stopAndAssert()
+
+ closeHarness.chanCloser.SendEvent(ctx, &LocalCloseReq{
+ TargetFeeRate: fn.Some(bumpRate),
+ Seq: 1,
+ })
+ closeHarness.assertStateTransitions(&ShutdownPending{})
+
+ closeHarness.expectFinalBalances(fn.None[ShutdownBalances]())
+ closeHarness.expectIncomingAddsDisabled()
+ closeHarness.chanCloser.SendEvent(ctx, &ShutdownReceived{
+ ShutdownScript: remoteAddr,
+ })
+ closeHarness.assertStateTransitions(&ChannelFlushing{})
+
+ closeHarness.expectFeeEstimate(bumpAbsFee, 2)
+ closeHarness.chanCloser.SendEvent(ctx, &ChannelFlushed{
+ ShutdownBalances: ShutdownBalances{
+ LocalBalance: 0,
+ RemoteBalance: remoteBalance,
+ },
+ })
+ closeHarness.assertStateTransitions(
+ &ClosingNegotiation{}, &ClosingNegotiation{},
+ )
+ negState := assertStateT[*ClosingNegotiation](closeHarness)
+ _, isCloseErr := negState.PeerState.GetForParty(
+ lntypes.Local,
+ ).(*CloseErr)
+ require.True(t, isCloseErr)
+ })
+
+ t.Run("bump_in_local_offer_sent_fires_after_sig", func(t *testing.T) {
+ closeTerms := &CloseChannelTerms{
+ ShutdownScripts: ShutdownScripts{
+ LocalDeliveryScript: localAddr,
+ RemoteDeliveryScript: remoteAddr,
+ },
+ ShutdownBalances: ShutdownBalances{
+ LocalBalance: localBalance,
+ RemoteBalance: remoteBalance,
+ },
+ }
+ startingState := &ClosingNegotiation{
+ PeerState: lntypes.Dual[AsymmetricPeerState]{
+ Local: &LocalOfferSent{
+ CloseChannelTerms: closeTerms,
+ ProposedFee: 1000,
+ ProposedFeeRate: initialRate,
+ LocalSig: localSigWire,
+ },
+ Remote: &RemoteCloseStart{
+ CloseChannelTerms: closeTerms,
+ },
+ },
+ CloseChannelTerms: closeTerms,
+ }
+ closeHarness := newCloser(t, &harnessCfg{
+ initialState: fn.Some[ProtocolState](startingState),
+ })
+ defer closeHarness.stopAndAssert()
+
+ // Buffer a bump while awaiting the peer's ClosingSig.
+ closeHarness.chanCloser.SendEvent(ctx, &LocalCloseReq{
+ TargetFeeRate: fn.Some(bumpRate),
+ Seq: 7,
+ })
+ closeHarness.assertStateTransitions(&ClosingNegotiation{})
+
+ // Completing the first round should broadcast tx 1 and
+ // immediately emit a second offer at bumpRate.
+ closeHarness.expectCloseFinalized(
+ &localSig, &remoteSig, localAddr, remoteAddr, 1000,
+ localBalance.ToSatoshis()-1000, true,
+ )
+ balanceAfterBump := localBalance.ToSatoshis() - bumpAbsFee
+ closeHarness.expectFeeEstimate(bumpAbsFee, 1)
+ closeHarness.expectNewCloseSig(
+ localAddr, remoteAddr, bumpAbsFee, balanceAfterBump,
+ )
+ closeHarness.expectMsgSent(singleMsgMatcher(
+ func(cc *lnwire.ClosingComplete) bool {
+ return cc.FeeSatoshis == bumpAbsFee
+ },
+ ))
+
+ closeHarness.chanCloser.SendEvent(ctx, &LocalSigReceived{
+ SigMsg: lnwire.ClosingSig{
+ CloserScript: localAddr,
+ CloseeScript: remoteAddr,
+ ClosingSigs: lnwire.ClosingSigs{
+ CloserAndClosee: newSigTlv[tlv.TlvType3]( //nolint:ll
+ remoteWireSig,
+ ),
+ },
+ },
+ })
+ closeHarness.assertStateTransitions(
+ &ClosingNegotiation{}, &ClosingNegotiation{},
+ &ClosingNegotiation{},
+ )
+ negState := assertStateT[*ClosingNegotiation](closeHarness)
+ offerSent, ok := negState.PeerState.GetForParty(
+ lntypes.Local,
+ ).(*LocalOfferSent)
+ require.True(t, ok)
+ require.Equal(t, bumpAbsFee, offerSent.ProposedFee)
+ require.Equal(t, bumpRate, offerSent.ProposedFeeRate)
+ closeHarness.waitForMsgSent()
+ })
+
+ t.Run("cancelled_bump_in_local_offer_sent_not_offered", func(t *testing.T) { //nolint:ll
+ closeTerms := &CloseChannelTerms{
+ ShutdownScripts: ShutdownScripts{
+ LocalDeliveryScript: localAddr,
+ RemoteDeliveryScript: remoteAddr,
+ },
+ ShutdownBalances: ShutdownBalances{
+ LocalBalance: localBalance,
+ RemoteBalance: remoteBalance,
+ },
+ }
+ startingState := &ClosingNegotiation{
+ PeerState: lntypes.Dual[AsymmetricPeerState]{
+ Local: &LocalOfferSent{
+ CloseChannelTerms: closeTerms,
+ ProposedFee: 1000,
+ ProposedFeeRate: initialRate,
+ LocalSig: localSigWire,
+ },
+ Remote: &RemoteCloseStart{
+ CloseChannelTerms: closeTerms,
+ },
+ },
+ CloseChannelTerms: closeTerms,
+ }
+ closeHarness := newCloser(t, &harnessCfg{
+ initialState: fn.Some[ProtocolState](startingState),
+ })
+ defer closeHarness.stopAndAssert()
+
+ closeHarness.chanCloser.SendEvent(ctx, &LocalCloseReq{
+ TargetFeeRate: fn.Some(bumpRate),
+ Seq: 9,
+ })
+ closeHarness.assertStateTransitions(&ClosingNegotiation{})
+ closeHarness.chanCloser.SendEvent(ctx, &CancelPendingOffer{
+ Seq: 9,
+ })
+ closeHarness.assertStateTransitions(&ClosingNegotiation{})
+
+ closeHarness.expectCloseFinalized(
+ &localSig, &remoteSig, localAddr, remoteAddr, 1000,
+ localBalance.ToSatoshis()-1000, true,
+ )
+ closeHarness.chanCloser.SendEvent(ctx, &LocalSigReceived{
+ SigMsg: lnwire.ClosingSig{
+ CloserScript: localAddr,
+ CloseeScript: remoteAddr,
+ ClosingSigs: lnwire.ClosingSigs{
+ CloserAndClosee: newSigTlv[tlv.TlvType3]( //nolint:ll
+ remoteWireSig,
+ ),
+ },
+ },
+ })
+ closeHarness.assertLocalClosePending()
+ closeHarness.assertNoStateTransitions()
+ })
+}
### lnwallet/chancloser/rbf_coop_transitions.go
@@ -249,48 +249,20 @@ func (c *ChannelActive) ProcessEvent(event ProtocolEvent, env *Environment,
// with a special SendPredicate, then go to the ShutdownPending where
// we'll wait for the remote to send their shutdown.
case *SendShutdown:
- // If we have an upfront shutdown addr or a delivery addr then
- // we'll use that. Otherwise, we'll generate a new delivery
- // addr.
- shutdownScript, err := env.LocalUpfrontShutdown.Alt(
- msg.DeliveryAddr,
- ).UnwrapOrFuncErr(env.NewDeliveryScript)
- if err != nil {
- return nil, err
- }
-
- // We'll emit some daemon events to send the shutdown message
- // and disable the channel on the network level. In this case,
- // we don't need a post send event as receive their shutdown is
- // what'll move us beyond the ShutdownPending state.
- daemonEvents, closeeNonce, err := sendShutdownEvents(
- env.ChanID, env.ChanPoint, shutdownScript,
- env.ChanPeer, fn.None[ProtocolEvent](),
- env.ChanObserver, env, msg.CloseeNonce,
+ return c.processSendShutdown(
+ msg.DeliveryAddr, fn.Some(msg.IdealFeeRate),
+ msg.CloseeNonce, env,
)
- if err != nil {
- return nil, err
- }
- chancloserLog.Infof("ChannelPoint(%v): sending shutdown msg, "+
- "delivery_script=%x", env.ChanPoint, shutdownScript)
+ case *LocalCloseReq:
+ return c.processSendShutdown(
+ msg.DeliveryAddr, msg.TargetFeeRate,
+ fn.None[lnwire.Musig2Nonce](), env,
+ )
- // From here, we'll transition to the shutdown pending state. In
- // this state we await their shutdown message (self loop), then
- // also the flushing event.
+ case *CancelPendingOffer:
return &CloseStateTransition{
- NextState: &ShutdownPending{
- IdealFeeRate: fn.Some(msg.IdealFeeRate),
- ShutdownScripts: ShutdownScripts{
- LocalDeliveryScript: shutdownScript,
- },
- NonceState: NonceState{
- LocalCloseeNonce: closeeNonce,
- },
- },
- NewEvents: fn.Some(RbfEvent{
- ExternalEvents: daemonEvents,
- }),
+ NextState: c,
}, nil
// When we receive a shutdown from the remote party, we'll validate the
@@ -381,6 +353,59 @@ func (c *ChannelActive) ProcessEvent(event ProtocolEvent, env *Environment,
}
}
+// processSendShutdown validates or creates the local delivery script and
+// emits the daemon events needed to send the shutdown message, transitioning
+// ChannelActive into ShutdownPending.
+func (c *ChannelActive) processSendShutdown(
+ deliveryAddr fn.Option[lnwire.DeliveryAddress],
+ idealFeeOpt fn.Option[chainfee.SatPerVByte],
+ closeeNonce fn.Option[lnwire.Musig2Nonce], env *Environment,
+) (*CloseStateTransition, error) {
+
+ // If we have an upfront shutdown addr or a delivery addr then we'll
+ // use that. Otherwise, we'll generate a new delivery addr.
+ shutdownScript, err := env.LocalUpfrontShutdown.Alt(
+ deliveryAddr,
+ ).UnwrapOrFuncErr(env.NewDeliveryScript)
+ if err != nil {
+ return nil, err
+ }
+
+ // We'll emit some daemon events to send the shutdown message and
+ // disable the channel on the network level. In this case, we don't need
+ // a post send event as receiving their shutdown is what'll move us
+ // beyond the ShutdownPending state.
+ daemonEvents, localCloseeNonce, err := sendShutdownEvents(
+ env.ChanID, env.ChanPoint, shutdownScript, env.ChanPeer,
+ fn.None[ProtocolEvent](), env.ChanObserver, env, closeeNonce,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ chancloserLog.Infof("ChannelPoint(%v): sending shutdown msg, "+
+ "delivery_script=%x", env.ChanPoint, shutdownScript)
+
+ // From here, we'll transition to the shutdown pending state. In this
+ // state we await their shutdown message (self loop), then also the
+ // flushing event.
+ return &CloseStateTransition{
+ NextState: &ShutdownPending{
+ IdealFeeRate: idealFeeOpt,
+ ShutdownScripts: ShutdownScripts{
+ LocalDeliveryScript: shutdownScript,
+ },
+ NonceState: NonceState{
+ LocalCloseeNonce: localCloseeNonce,
+ },
+ LocalCloseRequested: true,
+ },
+ NewEvents: fn.Some(RbfEvent{
+ ExternalEvents: daemonEvents,
+ }),
+ }, nil
+}
+
// ProcessEvent takes a protocol event, and implements a state transition for
// the state. Our path to this state will determine the set of valid events. If
// we were the one that sent the shutdown, then we'll just wait on the
@@ -417,6 +442,27 @@ func (s *ShutdownPending) ProcessEvent(event ProtocolEvent, env *Environment,
NextState: s,
}, nil
+ // Buffer a fee-bump request (or record the initial local close rate)
+ // while shutdown is pending.
+ case *LocalCloseReq:
+ nextState := *s
+ applyLocalCloseReqToPending(
+ &nextState.LocalCloseRequested, &nextState.IdealFeeRate,
+ &nextState.PendingBump, msg,
+ )
+
+ return &CloseStateTransition{
+ NextState: &nextState,
+ }, nil
+
+ case *CancelPendingOffer:
+ nextState := *s
+ cancelPendingBump(&nextState.PendingBump, msg.Seq)
+
+ return &CloseStateTransition{
+ NextState: &nextState,
+ }, nil
+
// When we receive a shutdown from the remote party, we'll validate the
// shutdown message, then transition to the ChannelFlushing state.
case *ShutdownReceived:
@@ -495,7 +541,9 @@ func (s *ShutdownPending) ProcessEvent(event ProtocolEvent, env *Environment,
LocalDeliveryScript: s.LocalDeliveryScript, //nolint:ll
RemoteDeliveryScript: msg.ShutdownScript, //nolint:ll
},
- NonceState: updatedNonceState,
+ NonceState: updatedNonceState,
+ LocalCloseRequested: s.LocalCloseRequested,
+ PendingBump: s.PendingBump,
},
NewEvents: newEvents,
}, nil
@@ -538,9 +586,11 @@ func (s *ShutdownPending) ProcessEvent(event ProtocolEvent, env *Environment,
// We'll stay here until we receive the ChannelFlushed event.
return &CloseStateTransition{
NextState: &ChannelFlushing{
- IdealFeeRate: s.IdealFeeRate,
- ShutdownScripts: s.ShutdownScripts,
- NonceState: s.NonceState,
+ IdealFeeRate: s.IdealFeeRate,
+ ShutdownScripts: s.ShutdownScripts,
+ NonceState: s.NonceState,
+ LocalCloseRequested: s.LocalCloseRequested,
+ PendingBump: s.PendingBump,
},
NewEvents: newEvents,
}, nil
@@ -588,6 +638,27 @@ func (c *ChannelFlushing) ProcessEvent(event ProtocolEvent, env *Environment,
NextState: c,
}, nil
+ // Buffer a fee-bump request while the channel is flushing so we offer
+ // the requested fee rate as soon as flushing completes.
+ case *LocalCloseReq:
+ nextState := *c
+ applyLocalCloseReqToPending(
+ &nextState.LocalCloseRequested, &nextState.IdealFeeRate,
+ &nextState.PendingBump, msg,
+ )
+
+ return &CloseStateTransition{
+ NextState: &nextState,
+ }, nil
+
+ case *CancelPendingOffer:
+ nextState := *c
+ cancelPendingBump(&nextState.PendingBump, msg.Seq)
+
+ return &CloseStateTransition{
+ NextState: &nextState,
+ }, nil
+
// If we receive the ChannelFlushed event, then the coast is clear so
// we'll now morph into the dual peer state so we can handle any
// messages needed to drive forward the close process.
@@ -604,10 +675,22 @@ func (c *ChannelFlushing) ProcessEvent(event ProtocolEvent, env *Environment,
chancloserLog.Infof("ChannelPoint(%v): channel flushed! "+
"proceeding with co-op close", env.ChanPoint)
- // If an ideal fee rate was specified, then we'll use that,
- // otherwise we'll fall back to the default value given in the
- // env.
- idealFeeRate := c.IdealFeeRate.UnwrapOr(env.DefaultFeeRate)
+ // If an explicit fee bump arrived while we were waiting on
+ // shutdown or flushing, prefer its fee rate. Otherwise, fall
+ // back to the ideal fee rate or the environment default.
+ var (
+ idealFeeRate chainfee.SatPerVByte
+ explicitBump bool
+ )
+ c.PendingBump.WhenSome(func(bump PendingLocalOffer) {
+ idealFeeRate = bump.TargetFeeRate
+ explicitBump = true
+ })
+ if !explicitBump {
+ idealFeeRate = c.IdealFeeRate.UnwrapOr(
+ env.DefaultFeeRate,
+ )
+ }
// We'll then use that fee rate to determine the absolute fee
// we'd propose.
@@ -637,7 +720,7 @@ func (c *ChannelFlushing) ProcessEvent(event ProtocolEvent, env *Environment,
//
// TODO(roasbeef): also only proceed if was higher than fee in
// last round?
- if closeTerms.LocalCanPayFees(absoluteFee) {
+ if closeTerms.LocalCanPayFees(absoluteFee) || explicitBump {
// Each time we go into this negotiation flow, we'll
// kick off our local state with a new close attempt.
// So we'll emit a internal event to drive forward that
@@ -679,6 +762,36 @@ func (c *ChannelFlushing) ProcessEvent(event ProtocolEvent, env *Environment,
}
}
+// applyLocalCloseReqToPending records an initial local close fee rate or
+// buffers a fee-bump request while the closer is in ShutdownPending or
+// ChannelFlushing.
+func applyLocalCloseReqToPending(localRequested *bool,
+ idealFeeRate *fn.Option[chainfee.SatPerVByte],
+ pendingBump *fn.Option[PendingLocalOffer], msg *LocalCloseReq) {
+
+ if !*localRequested && idealFeeRate.IsNone() {
+ *localRequested = true
+ *idealFeeRate = msg.TargetFeeRate
+ return
+ }
+
+ msg.TargetFeeRate.WhenSome(func(rate chainfee.SatPerVByte) {
+ *pendingBump = fn.Some(PendingLocalOffer{
+ TargetFeeRate: rate,
+ Seq: msg.Seq,
+ })
+ })
+}
+
+// cancelPendingBump clears pendingBump if its sequence matches seq.
+func cancelPendingBump(pendingBump *fn.Option[PendingLocalOffer], seq uint64) {
+ pendingBump.WhenSome(func(bump PendingLocalOffer) {
+ if bump.Seq == seq {
+ *pendingBump = fn.None[PendingLocalOffer]()
+ }
+ })
+}
+
// processNegotiateEvent is a helper function that processes a new event to
// local channel state once we're in the ClosingNegotiation state.
func processNegotiateEvent(c *ClosingNegotiation, event ProtocolEvent,
@@ -1046,6 +1159,13 @@ func (c *ClosingNegotiation) ProcessEvent(event ProtocolEvent, env *Environment,
"chan state", env.ChanPoint, event)
// Drive forward the remote state based on the next event.
return processNegotiateEvent(c, event, env, lntypes.Remote)
+
+ case isType[*CancelPendingOffer](event):
+ // The local side already sent or superseded the buffered offer;
+ // treat late cancellation as a no-op.
+ return &CloseStateTransition{
+ NextState: c,
+ }, nil
}
return nil, fmt.Errorf("%w: received %T while in %v",
@@ -1130,185 +1250,197 @@ func (l *LocalCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
// If we receive a SendOfferEvent, then we'll use the specified fee
// rate to generate for the closing transaction with our ideal fee
// rate.
- case *SendOfferEvent:
- // given the state of the local/remote outputs.
- // First, we'll figure out the absolute fee rate we should pay
- localTxOut, remoteTxOut := l.DeriveCloseTxOuts()
- absoluteFee := env.FeeEstimator.EstimateFee(
- env.ChanType, localTxOut, remoteTxOut, nil,
- msg.TargetFeeRate.FeePerKWeight(),
+ case *LocalCloseReq:
+ return l.processSendOffer(
+ msg.TargetFeeRate.UnwrapOr(env.DefaultFeeRate), env,
)
- // If we can't actually pay for fees here, then we'll just do a
- // noop back to the same state to await a new fee rate.
- if !l.LocalCanPayFees(absoluteFee) {
- chancloserLog.Infof("ChannelPoint(%v): unable to pay "+
- "fee=%v with local balance %v, skipping "+
- "closing_complete", env.ChanPoint, absoluteFee,
- l.LocalBalance)
-
- return &CloseStateTransition{
- NextState: &CloseErr{
- CloseChannelTerms: l.CloseChannelTerms,
- Party: lntypes.Local,
- ErrState: NewErrStateCantPayForFee(
- l.LocalBalance.ToSatoshis(),
- absoluteFee,
- ),
- },
- }, nil
- }
+ case *SendOfferEvent:
+ return l.processSendOffer(msg.TargetFeeRate, env)
+ }
- // Now that we know what fee we want to pay, we'll create a new
- // signature over our co-op close transaction. For our
- // proposals, we'll just always use the known RBF sequence
- // value.
- localScript := l.LocalDeliveryScript
+ return nil, fmt.Errorf("%w: received %T while in LocalCloseStart",
+ ErrInvalidStateTransition, event)
+}
- var closeOpts []lnwallet.ChanCloseOpt
- closeOpts = append(closeOpts,
- lnwallet.WithCustomSequence(mempool.MaxRBFSequence),
- lnwallet.WithCustomPayer(lntypes.Local),
- )
+// processSendOffer attempts to construct and send a closing_complete offer at
+// targetFeeRate, or transitions to CloseErr if the local balance cannot cover
+// the fee.
+func (l *LocalCloseStart) processSendOffer(targetFeeRate chainfee.SatPerVByte,
+ env *Environment) (*CloseStateTransition, error) {
+ // given the state of the local/remote outputs.
+ // First, we'll figure out the absolute fee rate we should pay
+ localTxOut, remoteTxOut := l.DeriveCloseTxOuts()
+ absoluteFee := env.FeeEstimator.EstimateFee(
+ env.ChanType, localTxOut, remoteTxOut, nil,
+ targetFeeRate.FeePerKWeight(),
+ )
- // For taproot channels, we need to use the LocalMusigSession
- // for signing when we're the closer (sending closing_complete).
- if env.IsTaproot() {
- // Initialize with the remote's closee nonce for
- // signing. This may be using the very first nonce they
- // send in shutdown, or the nonce they sent in
- // ClosingSig after responding to our prior offer.
- initLocalMusigCloseeNonce(
- env, l.NonceState.RemoteCloseeNonce,
- )
+ // If we can't actually pay for fees here, then we'll just do a
+ // noop back to the same state to await a new fee rate.
+ if !l.LocalCanPayFees(absoluteFee) {
+ chancloserLog.Infof("ChannelPoint(%v): unable to pay "+
+ "fee=%v with local balance %v, skipping "+
+ "closing_complete", env.ChanPoint, absoluteFee,
+ l.LocalBalance)
- // Generate our JIT closer nonce. This sets the internal
- // localNonce field in LocalMusigSession.
- _, err := env.LocalMusigSession.ClosingNonce()
- if err != nil {
- return nil, fmt.Errorf("failed to generate "+
- "JIT closer nonce: %w", err)
- }
+ return &CloseStateTransition{
+ NextState: &CloseErr{
+ CloseChannelTerms: l.CloseChannelTerms,
+ Party: lntypes.Local,
+ ErrState: NewErrStateCantPayForFee(
+ l.LocalBalance.ToSatoshis(),
+ absoluteFee,
+ ),
+ },
+ }, nil
+ }
- //nolint:ll
- musigOpts, err := env.LocalMusigSession.ProposalClosingOpts()
- if err != nil {
- return nil, fmt.Errorf("failed to get musig "+
- "closing opts: %w", err)
- }
- closeOpts = append(closeOpts, musigOpts...)
- }
+ // Now that we know what fee we want to pay, we'll create a new
+ // signature over our co-op close transaction. For our
+ // proposals, we'll just always use the known RBF sequence
+ // value.
+ localScript := l.LocalDeliveryScript
- rawSig, closeTx, closeBalance, err := env.CloseSigner.CreateCloseProposal( //nolint:ll
- absoluteFee, localScript, l.RemoteDeliveryScript,
- closeOpts...,
- )
- if err != nil {
- return nil, fmt.Errorf("unable to create close "+
- "proposal: %w", err)
- }
+ var closeOpts []lnwallet.ChanCloseOpt
+ closeOpts = append(closeOpts,
+ lnwallet.WithCustomSequence(mempool.MaxRBFSequence),
+ lnwallet.WithCustomPayer(lntypes.Local),
+ )
- // Depending on the channel type, we'll be encoding a normal
- // sig, or a musig2 partial sig.
- var (
- wireSig lnwire.Sig
- musigPartialSig *lnwallet.MusigPartialSig
+ // For taproot channels, we need to use the LocalMusigSession
+ // for signing when we're the closer (sending closing_complete).
+ if env.IsTaproot() {
+ // Initialize with the remote's closee nonce for
+ // signing. This may be using the very first nonce they
+ // send in shutdown, or the nonce they sent in
+ // ClosingSig after responding to our prior offer.
+ initLocalMusigCloseeNonce(
+ env, l.NonceState.RemoteCloseeNonce,
)
- // Depending on the channel type, we'll either have a partial
- // signature, or a regular signature.
- switch {
- case env.IsTaproot():
- var ok bool
- musigPartialSig, ok = rawSig.(*lnwallet.MusigPartialSig)
- if !ok {
- return nil, fmt.Errorf("expected "+
- "MusigPartialSig for taproot "+
- "channel, got %T", rawSig)
- }
+ // Generate our JIT closer nonce. This sets the internal
+ // localNonce field in LocalMusigSession.
+ _, err := env.LocalMusigSession.ClosingNonce()
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate "+
+ "JIT closer nonce: %w", err)
+ }
- // Convert to schnorr shell format for wire sig.
- schnorrSig := musigPartialSig.ToSchnorrShell()
- wireSig, err = lnwire.NewSigFromSignature(schnorrSig)
- if err != nil {
- return nil, err
- }
- default:
- // For non-taproot channels, use regular signature
- // conversion.
- wireSig, err = lnwire.NewSigFromSignature(rawSig)
- if err != nil {
- return nil, err
- }
+ musigOpts, err := env.LocalMusigSession.ProposalClosingOpts()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get musig "+
+ "closing opts: %w", err)
}
+ closeOpts = append(closeOpts, musigOpts...)
+ }
- chancloserLog.Infof("closing w/ local_addr=%x, "+
- "remote_addr=%x, fee=%v", localScript[:],
- l.RemoteDeliveryScript[:], absoluteFee)
+ rawSig, closeTx, closeBalance, err := env.CloseSigner.CreateCloseProposal( //nolint:ll
+ absoluteFee, localScript, l.RemoteDeliveryScript,
+ closeOpts...,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("unable to create close "+
+ "proposal: %w", err)
+ }
- chancloserLog.Infof("proposing closing_tx=%v",
- spew.Sdump(closeTx))
+ // Depending on the channel type, we'll be encoding a normal
+ // sig, or a musig2 partial sig.
+ var (
+ wireSig lnwire.Sig
+ musigPartialSig *lnwallet.MusigPartialSig
+ )
- var noClosee, noCloser bool
- switch {
- case remoteTxOut == nil:
- noClosee = true
- case closeBalance < lnwallet.DustLimitForSize(len(localScript)):
- noCloser = true
+ // Depending on the channel type, we'll either have a partial
+ // signature, or a regular signature.
+ switch {
+ case env.IsTaproot():
+ var ok bool
+ musigPartialSig, ok = rawSig.(*lnwallet.MusigPartialSig)
+ if !ok {
+ return nil, fmt.Errorf("expected "+
+ "MusigPartialSig for taproot "+
+ "channel, got %T", rawSig)
}
- // Create the appropriate signature structures based on channel
- // type.
- closingSigs, taprootClosingSigs, err := encodeClosingSignatures(
- env, wireSig, musigPartialSig, noCloser, noClosee,
- )
+ // Convert to schnorr shell format for wire sig.
+ schnorrSig := musigPartialSig.ToSchnorrShell()
+ wireSig, err = lnwire.NewSigFromSignature(schnorrSig)
if err != nil {
return nil, err
}
-
- closingCompleteMsg := &lnwire.ClosingComplete{
- ChannelID: env.ChanID,
- CloserScript: l.LocalDeliveryScript,
- CloseeScript: l.RemoteDeliveryScript,
- FeeSatoshis: absoluteFee,
- LockTime: env.BlockHeight,
- ClosingSigs: closingSigs,
- TaprootClosingSigs: taprootClosingSigs,
+ default:
+ // For non-taproot channels, use regular signature
+ // conversion.
+ wireSig, err = lnwire.NewSigFromSignature(rawSig)
+ if err != nil {
+ return nil, err
}
+ }
- // TODO(roasbeef): type alias for protocol event
- sendEvent := protofsm.DaemonEventSet{&protofsm.SendMsgEvent[ProtocolEvent]{ //nolint:ll
- TargetPeer: env.ChanPeer,
- Msgs: []lnwire.Message{closingCompleteMsg},
- }}
+ chancloserLog.Infof("closing w/ local_addr=%x, "+
+ "remote_addr=%x, fee=%v", localScript[:],
+ l.RemoteDeliveryScript[:], absoluteFee)
- chancloserLog.Infof("ChannelPoint(%v): sending closing sig "+
- "to remote party, fee_sats=%v", env.ChanPoint,
- absoluteFee)
+ chancloserLog.Infof("proposing closing_tx=%v",
+ spew.Sdump(closeTx))
- // For taproot channels, stash the full MusigPartialSig so
- // LocalOfferSent can combine signatures without re-signing.
- var localMusigSig fn.Option[lnwallet.MusigPartialSig]
- if musigPartialSig != nil {
- localMusigSig = fn.Some(*musigPartialSig)
- }
+ var noClosee, noCloser bool
+ switch {
+ case remoteTxOut == nil:
+ noClosee = true
+ case closeBalance < lnwallet.DustLimitForSize(len(localScript)):
+ noCloser = true
+ }
- return &CloseStateTransition{
- NextState: &LocalOfferSent{
- ProposedFee: absoluteFee,
- ProposedFeeRate: msg.TargetFeeRate,
- LocalSig: wireSig,
- LocalMusigSig: localMusigSig,
- CloseChannelTerms: l.CloseChannelTerms,
- },
- NewEvents: fn.Some(RbfEvent{
- ExternalEvents: sendEvent,
- }),
- }, nil
+ // Create the appropriate signature structures based on channel
+ // type.
+ closingSigs, taprootClosingSigs, err := encodeClosingSignatures(
+ env, wireSig, musigPartialSig, noCloser, noClosee,
+ )
+ if err != nil {
+ return nil, err
}
- return nil, fmt.Errorf("%w: received %T while in LocalCloseStart",
- ErrInvalidStateTransition, event)
+ closingCompleteMsg := &lnwire.ClosingComplete{
+ ChannelID: env.ChanID,
+ CloserScript: l.LocalDeliveryScript,
+ CloseeScript: l.RemoteDeliveryScript,
+ FeeSatoshis: absoluteFee,
+ LockTime: env.BlockHeight,
+ ClosingSigs: closingSigs,
+ TaprootClosingSigs: taprootClosingSigs,
+ }
+
+ // TODO(roasbeef): type alias for protocol event
+ sendEvent := protofsm.DaemonEventSet{&protofsm.SendMsgEvent[ProtocolEvent]{ //nolint:ll
+ TargetPeer: env.ChanPeer,
+ Msgs: []lnwire.Message{closingCompleteMsg},
+ }}
+
+ chancloserLog.Infof("ChannelPoint(%v): sending closing sig "+
+ "to remote party, fee_sats=%v", env.ChanPoint,
+ absoluteFee)
+
+ // For taproot channels, stash the full MusigPartialSig so
+ // LocalOfferSent can combine signatures without re-signing.
+ var localMusigSig fn.Option[lnwallet.MusigPartialSig]
+ if musigPartialSig != nil {
+ localMusigSig = fn.Some(*musigPartialSig)
+ }
+
+ return &CloseStateTransition{
+ NextState: &LocalOfferSent{
+ ProposedFee: absoluteFee,
+ ProposedFeeRate: targetFeeRate,
+ LocalSig: wireSig,
+ LocalMusigSig: localMusigSig,
+ CloseChannelTerms: l.CloseChannelTerms,
+ },
+ NewEvents: fn.Some(RbfEvent{
+ ExternalEvents: sendEvent,
+ }),
+ }, nil
}
// selectTaprootPartialSigWithNonce selects the PartialSigWithNonce to use from
@@ -1642,16 +1774,55 @@ func (l *LocalOfferSent) ProcessEvent(event ProtocolEvent, env *Environment,
lnutils.SpewLogClosure(closeTx),
)
+ var internalEvents []ProtocolEvent
+ l.PendingOffer.WhenSome(func(offer PendingLocalOffer) {
+ internalEvents = append(
+ internalEvents, &SendOfferEvent{
+ TargetFeeRate: offer.TargetFeeRate,
+ },
+ )
+ })
+
+ newEvents := protofsm.EmittedEvent[ProtocolEvent]{
+ ExternalEvents: broadcastEvent,
+ }
+ if len(internalEvents) > 0 {
+ newEvents.InternalEvent = internalEvents
+ }
+
return &CloseStateTransition{
NextState: &ClosePending{
CloseTx: closeTx,
FeeRate: l.ProposedFeeRate,
CloseChannelTerms: l.CloseChannelTerms,
Party: lntypes.Local,
},
- NewEvents: fn.Some(protofsm.EmittedEvent[ProtocolEvent]{
- ExternalEvents: broadcastEvent,
- }),
+ NewEvents: fn.Some(newEvents),
+ }, nil
+
+ case *LocalCloseReq:
+ nextState := *l
+ nextState.PendingOffer = fn.Some(PendingLocalOffer{
+ TargetFeeRate: msg.TargetFeeRate.UnwrapOr(
+ env.DefaultFeeRate,
+ ),
+ Seq: msg.Seq,
+ })
+
+ return &CloseStateTransition{
+ NextState: &nextState,
+ }, nil
+
+ case *CancelPendingOffer:
+ nextState := *l
+ nextState.PendingOffer.WhenSome(func(offer PendingLocalOffer) {
+ if offer.Seq == msg.Seq {
+ nextState.PendingOffer = fn.None[PendingLocalOffer]() //nolint:ll
+ }
+ })
+
+ return &CloseStateTransition{
+ NextState: &nextState,
}, nil
}
@@ -2220,14 +2391,12 @@ func (c *ClosePending) ProcessEvent(event ProtocolEvent, env *Environment,
// transition to the LocalCloseStart state, so we can sign a new closing
// tx.
case *SendOfferEvent:
- return &CloseStateTransition{
- NextState: &LocalCloseStart{
- CloseChannelTerms: c.CloseChannelTerms,
- },
- NewEvents: fn.Some(protofsm.EmittedEvent[ProtocolEvent]{
- InternalEvent: []ProtocolEvent{msg},
- }),
- }, nil
+ return transitionToLocalOffer(c.CloseChannelTerms, msg)
+
+ case *LocalCloseReq:
+ return transitionToLocalOffer(c.CloseChannelTerms, &SendOfferEvent{ //nolint:ll
+ TargetFeeRate: msg.TargetFeeRate.UnwrapOr(env.DefaultFeeRate), //nolint:ll
+ })
// If we get an offer received event, then we're doing a state
// transition to the RemoteCloseStart, as the remote peer wants to sign
@@ -2272,14 +2441,12 @@ func (c *CloseErr) ProcessEvent(event ProtocolEvent, env *Environment,
// transition to the LocalCloseStart state, so we can sign a new closing
// tx.
case *SendOfferEvent:
- return &CloseStateTransition{
- NextState: &LocalCloseStart{
- CloseChannelTerms: c.CloseChannelTerms,
- },
- NewEvents: fn.Some(protofsm.EmittedEvent[ProtocolEvent]{
- InternalEvent: []ProtocolEvent{msg},
- }),
- }, nil
+ return transitionToLocalOffer(c.CloseChannelTerms, msg)
+
+ case *LocalCloseReq:
+ return transitionToLocalOffer(c.CloseChannelTerms, &SendOfferEvent{ //nolint:ll
+ TargetFeeRate: msg.TargetFeeRate.UnwrapOr(env.DefaultFeeRate), //nolint:ll
+ })
// If we get an offer received event, then we're doing a state
// transition to the RemoteCloseStart, as the remote peer wants to sign
@@ -2299,3 +2466,18 @@ func (c *CloseErr) ProcessEvent(event ProtocolEvent, env *Environment,
}, nil
}
}
+
+// transitionToLocalOffer transitions from a terminal or error peer state back
+// into LocalCloseStart with offer queued as an internal event.
+func transitionToLocalOffer(terms *CloseChannelTerms,
+ offer *SendOfferEvent) (*CloseStateTransition, error) {
+
+ return &CloseStateTransition{
+ NextState: &LocalCloseStart{
+ CloseChannelTerms: terms,
+ },
+ NewEvents: fn.Some(protofsm.EmittedEvent[ProtocolEvent]{
+ InternalEvent: []ProtocolEvent{offer},
+ }),
+ }, nil
+}
### peer/brontide.go
@@ -713,6 +713,11 @@ type Brontide struct {
// reachable here.
activeCloseReqs *closeReqRegistry
+ // rbfBumpSeq assigns a unique sequence number to each RPC RBF close
+ // or fee-bump request so a cancelled caller only retracts its own
+ // unstarted bump.
+ rbfBumpSeq atomic.Uint64
+
// linkFailures decouples link failure producers from the channelManager
// that consumes them. Each link reports at most one failure, and the
// unbounded queue preserves every report without making a link wait for
@@ -1942,7 +1947,7 @@ func (p *Brontide) unregisterRbfCloseActor(chanPoint wire.OutPoint) {
// machine and the router endpoint it registered. Callers should prefer this
// over calling activeChanCloses.Delete directly so none of them can drift
// out of sync with the active closers map.
-func (p *Brontide) deleteActiveChanCloser(chanID lnwire.ChannelID,
+func (p *Brontide) retireChanCloserResources(chanID lnwire.ChannelID,
chanPoint wire.OutPoint) {
// Take the closer out of the map first. Everything below is done once
@@ -1978,13 +1983,19 @@ func (p *Brontide) deleteActiveChanCloser(chanID lnwire.ChannelID,
})
}
+ p.unregisterRbfCloseActor(chanPoint)
+}
+
+func (p *Brontide) deleteActiveChanCloser(chanID lnwire.ChannelID,
+ chanPoint wire.OutPoint) {
+
+ p.retireChanCloserResources(chanID, chanPoint)
+
// Tell any caller still waiting that the close is over. A caller that
// knows a different reason answers it before retiring the closer, so
// the claim below then finds nothing left to report and this is the
// fallback for the paths that retire a closer on their own.
p.abortRemainingCloseReqs(chanID, ErrCoopCloseAbortedByLinkFailure)
-
- p.unregisterRbfCloseActor(chanPoint)
}
// abandonChanClosers answers every caller still waiting on this peer, and
@@ -4374,6 +4385,18 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
closeReq *htlcswitch.ChanClose,
coopCloseStates chancloser.RbfStateSub) {
+ p.observeRbfCloseUpdatesWithSeq(
+ chanCloser, closeReq, coopCloseStates, 0,
+ )
+}
+
+// observeRbfCloseUpdatesWithSeq observes state transitions for a single RPC
+// caller and cancels any buffered fee bump identified by bumpSeq if the caller
+// exits before it is sent.
+func (p *Brontide) observeRbfCloseUpdatesWithSeq(
+ chanCloser *chancloser.RbfChanCloser, closeReq *htlcswitch.ChanClose,
+ coopCloseStates chancloser.RbfStateSub, bumpSeq uint64) {
+
newStateChan := coopCloseStates.NewItemCreated.ChanOut()
defer chanCloser.RemoveStateSub(coopCloseStates)
@@ -4383,11 +4406,11 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
)
maybeNotifyTxBroadcast := func(state chancloser.AsymmetricPeerState,
- party lntypes.ChannelParty) {
+ party lntypes.ChannelParty) bool {
// First, check to see if we have an error to report to the
- // caller. If so, then we''ll return that error and exit, as the
- // stream will exit as well.
+ // caller. If so, then we'll report it and signal the observer
+ // to exit immediately.
if closeErr, ok := state.(*chancloser.CloseErr); ok {
// We hit an error during the last state transition, so
// we'll extract the error then send it to the
@@ -4399,15 +4422,15 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
p.reportRbfCloseErr(closeReq, err)
- return
+ return true
}
closePending, ok := state.(*chancloser.ClosePending)
// If this isn't the close pending state, we aren't at the
// terminal state yet.
if !ok {
- return
+ return false
}
// Only notify if the fee rate is greater.
@@ -4419,7 +4442,7 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
"a higher fee rate of %v", closeReq.ChanPoint,
newFeeRate, lastFeeRate)
- return
+ return false
}
feeRate := closePending.FeeRate
@@ -4442,14 +4465,16 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
}:
case <-closeReq.Done():
- return
+ return false
case <-p.cg.Done():
- return
+ return false
}
}
lastTxids.SetForParty(party, closingTxid)
+
+ return false
}
peerLog.Infof("Observing RBF close updates for channel %v",
@@ -4470,36 +4495,33 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
// Each side may have gained a new co-op close
// tx, so we'll examine both to see if they've
// changed.
- maybeNotifyTxBroadcast(
+ localDone := maybeNotifyTxBroadcast(
peerState.GetForParty(lntypes.Local),
lntypes.Local,
)
- maybeNotifyTxBroadcast(
+ if localDone {
+ return
+ }
+ remoteDone := maybeNotifyTxBroadcast(
peerState.GetForParty(lntypes.Remote),
lntypes.Remote,
)
+ if remoteDone {
+ return
+ }
// Otherwise, if we're transition to CloseFin, then we
// know that we're done.
case *chancloser.CloseFin:
- // To clean up, we'll remove the chan closer
- // from the active map, and send the final
- // update to the client.
- closingTxid := closeState.ConfirmedTx.TxHash()
-
- chanID := lnwire.NewChanIDFromOutPoint(
- *closeReq.ChanPoint,
- )
-
- p.reportRbfCloseSuccess(chanID, closingTxid)
-
- p.deleteActiveChanCloser(
- chanID, *closeReq.ChanPoint,
- )
-
+ // The per-closer lifecycle sentinel owns final,
+ // success delivery, and channel/link teardown
+ // so local and remote closes clean up equally.
return
}
+ case <-chanCloser.Done():
+ return
+
// The caller is gone: either it cancelled, or the peer is
// shutting down. Nothing will read an outcome, so give up the
// record rather than leaving it for a retirement to find and
@@ -4509,6 +4531,15 @@ func (p *Brontide) observeRbfCloseUpdates(chanCloser *chancloser.RbfChanCloser,
*closeReq.ChanPoint,
)
p.releaseCloseReq(chanID, closeReq)
+ if bumpSeq != 0 {
+ ctx, cancel := p.cg.Create(context.Background())
+ chanCloser.SendEvent(
+ ctx, &chancloser.CancelPendingOffer{
+ Seq: bumpSeq,
+ },
+ )
+ cancel()
+ }
return
@@ -4566,20 +4597,49 @@ func (c *chanErrorReporter) ReportError(chanErr error) {
err)
}
+ // Capture the point before aborting callers so actor cleanup can still
+ // find it if the channel is already gone from activeChannels. Take the
+ // failed closer out of activeChanCloses and answer any waiting callers
+ // before re-initializing so callers never lose their observer when the
+ // stopped FSM exits and cannot bind to the stopped closer.
+ chanPoint, _ := c.peer.chanPointForCloser(c.chanID)
+ oldCloser, hadCloser := c.peer.activeChanCloses.LoadAndDelete(c.chanID)
+ c.peer.abortRemainingCloseReqs(c.chanID, chanErr)
+
// After we send the error message to the peer, we'll re-initialize the
// coop close state machine as they may send a shutdown message to
// retry the coop close.
lnChan, ok := c.peer.activeChannels.Load(c.chanID)
- if !ok {
+ if !ok || lnChan == nil {
+ if ok && lnChan == nil {
+ c.peer.log.Debugf("channel %v is pending, not "+
+ "re-initializing coop close state machine",
+ c.chanID)
+ }
+ if hadCloser {
+ c.peer.unregisterRbfCloseActor(chanPoint)
+ oldCloser.WhenRight(func(r *chancloser.RbfChanCloser) {
+ go func() {
+ c.peer.msgRouter.WhenSome(func(m msgmux.Router) { //nolint:ll
+ _ = m.UnregisterEndpoint(
+ r.Name(),
+ )
+ })
+ r.Stop()
+ }()
+ })
+ }
+
return
}
- if lnChan == nil {
- c.peer.log.Debugf("channel %v is pending, not "+
- "re-initializing coop close state machine",
- c.chanID)
-
- return
+ // Stop the old FSM asynchronously without unregistering from
+ // msgRouter, since initRbfChanCloser below synchronously replaces the
+ // same endpoint.
+ if hadCloser {
+ oldCloser.WhenRight(func(r *chancloser.RbfChanCloser) {
+ go r.Stop()
+ })
}
if _, err := c.peer.initRbfChanCloser(lnChan); err != nil {
@@ -4592,27 +4652,26 @@ func (c *chanErrorReporter) ReportError(chanErr error) {
}
}
-// chanFlushEventSentinel is used to send the RBF coop close state machine the
-// channel flushed event. We'll wait until the state machine enters the
-// ChannelFlushing state, then request the link to send the event once flushed.
+// rbfCloserLifecycleSentinel watches the lifecycle of a single RBF chan closer
+// state machine: it notifies the link to emit ChannelFlushed once when the
+// closer enters ChannelFlushing, and tears down the closer, active channel, and
+// switch link once the closer reaches CloseFin.
//
// NOTE: This MUST be run as a goroutine.
-func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
+func (p *Brontide) rbfCloserLifecycleSentinel(
+ chanCloser *chancloser.RbfChanCloser,
link htlcswitch.ChannelUpdateHandler,
- channel *lnwallet.LightningChannel) {
+ channel *lnwallet.LightningChannel,
+ coopCloseStates chancloser.RbfStateSub) {
defer p.cg.WgDone()
-
- // If there's no link, then the channel has already been flushed, so we
- // don't need to continue.
- if link == nil {
- return
- }
-
- coopCloseStates := chanCloser.RegisterStateEvents()
defer chanCloser.RemoveStateSub(coopCloseStates)
+ ctx, cancel := p.cg.Create(context.Background())
+ defer cancel()
+
newStateChan := coopCloseStates.NewItemCreated.ChanOut()
+ flushRegistered := false
sendChanFlushed := func() {
chanState := channel.StateSnapshot()
@@ -4625,39 +4684,57 @@ func (p *Brontide) chanFlushEventSentinel(chanCloser *chancloser.RbfChanCloser,
LocalBalance: chanState.LocalBalance,
RemoteBalance: chanState.RemoteBalance,
}
- ctx := context.Background()
chanCloser.SendEvent(ctx, &chancloser.ChannelFlushed{
ShutdownBalances: chanBalances,
})
}
- // We'll wait until the channel enters the ChannelFlushing state. We
- // exit after a success loop. As after the first RBF iteration, the
- // channel will always be flushed.
for {
select {
case newState, ok := <-newStateChan:
if !ok {
return
}
- if _, ok := newState.(*chancloser.ChannelFlushing); ok {
+ switch closeState := newState.(type) {
+ case *chancloser.ChannelFlushing:
+ if link == nil || flushRegistered {
+ continue
+ }
+ flushRegistered = true
+
peerLog.Infof("ChannelPoint(%v): rbf coop "+
"close is awaiting a flushed state, "+
- "registering with link..., ",
+ "registering with link...",
channel.ChannelPoint())
- // Request the link to send the event once the
- // channel is flushed. We only need this event
- // sent once, so we can exit now.
- ctx, cancel := p.cg.Create(context.Background())
- defer cancel()
-
_ = link.OnFlushedOnce(ctx, sendChanFlushed)
+ case *chancloser.CloseFin:
+ chanPoint := channel.ChannelPoint()
+ chanID := lnwire.NewChanIDFromOutPoint(
+ chanPoint,
+ )
+
+ var closingTxid chainhash.Hash
+ if closeState.ConfirmedTx != nil {
+ closingTxid = closeState.ConfirmedTx.TxHash() //nolint:ll
+ }
+
+ // Retire the closer from activeChanCloses
+ // before delivering success so a concurrent
+ // caller cannot register after takeAll and be
+ // left stranded.
+ p.retireChanCloserResources(chanID, chanPoint)
+ p.reportRbfCloseSuccess(chanID, closingTxid)
+ p.WipeChannel(&chanPoint)
+
return
}
+ case <-chanCloser.Done():
+ return
+
case <-p.cg.Done():
return
}
@@ -4784,6 +4861,7 @@ func (p *Brontide) initRbfChanCloser(
ctx := context.Background()
chanCloser := protofsm.NewStateMachine(protoCfg)
+ coopCloseStates := chanCloser.RegisterStateEvents()
chanCloser.Start(ctx)
// Finally, we'll register this new endpoint with the message router so
@@ -4794,6 +4872,7 @@ func (p *Brontide) initRbfChanCloser(
return r.RegisterEndpoint(&chanCloser)
})
if err != nil {
+ chanCloser.RemoveStateSub(coopCloseStates)
chanCloser.Stop()
return nil, fmt.Errorf("unable to register endpoint for co-op "+
@@ -4814,6 +4893,7 @@ func (p *Brontide) initRbfChanCloser(
channel.ChannelPoint(), p, p.cfg.ActorSystem,
)
if err := actorWrapper.registerActor(); err != nil {
+ chanCloser.RemoveStateSub(coopCloseStates)
chanCloser.Stop()
p.deleteActiveChanCloser(
chanID, channel.ChannelPoint(),
@@ -4825,10 +4905,11 @@ func (p *Brontide) initRbfChanCloser(
}
// Now that we've created the rbf closer state machine, we'll launch a
- // new goroutine to eventually send in the ChannelFlushed event once
- // needed.
+ // new goroutine to manage flushing and CloseFin teardown.
p.cg.WgAdd(1)
- go p.chanFlushEventSentinel(&chanCloser, link, channel)
+ go p.rbfCloserLifecycleSentinel(
+ &chanCloser, link, channel, coopCloseStates,
+ )
return &chanCloser, nil
}
@@ -4858,6 +4939,22 @@ func shutdownStartFeeRate(s shutdownInit) fn.Option[chainfee.SatPerKWeight] {
return fn.FlattenOption(feeRateOpt)
}
+// shutdownStartCtx returns the caller context from an RPC close request, or
+// context.Background() for a restart-initiated shutdown.
+func shutdownStartCtx(s shutdownInit) context.Context {
+ var reqOpt fn.Option[*htlcswitch.ChanClose]
+ whenRPCShutdown(s, func(req *htlcswitch.ChanClose) {
+ reqOpt = fn.Some(req)
+ })
+
+ req := reqOpt.UnwrapOr(nil)
+ if req != nil && req.Ctx != nil {
+ return req.Ctx
+ }
+
+ return context.Background()
+}
+
// shutdownStartAddr returns the delivery address that should be used when
// restarting the shutdown process. If we didn't send a shutdown before we
// restarted, and the user didn't initiate one either, then None is returned.
@@ -4905,60 +5002,9 @@ func newRPCShutdownInit(req *htlcswitch.ChanClose) shutdownInit {
)
}
-// waitUntilRbfCoastClear waits until the RBF co-op close state machine has
-// advanced to a terminal state before attempting another fee bump.
-func waitUntilRbfCoastClear(ctx context.Context,
- rbfCloser *chancloser.RbfChanCloser) error {
-
- coopCloseStates := rbfCloser.RegisterStateEvents()
- newStateChan := coopCloseStates.NewItemCreated.ChanOut()
- defer rbfCloser.RemoveStateSub(coopCloseStates)
-
- isTerminalState := func(newState chancloser.RbfState) bool {
- // If we're not in the negotiation sub-state, then we aren't at
- // the terminal state yet.
- state, ok := newState.(*chancloser.ClosingNegotiation)
- if !ok {
- return false
- }
-
- localState := state.PeerState.GetForParty(lntypes.Local)
-
- // If this isn't the close pending state, we aren't at the
- // terminal state yet.
- _, ok = localState.(*chancloser.ClosePending)
-
- return ok
- }
-
- // Before we enter the subscription loop below, check to see if we're
- // already in the terminal state.
- rbfState, err := rbfCloser.CurrentState()
- if err != nil {
- return err
- }
- if isTerminalState(rbfState) {
- return nil
- }
-
- peerLog.Debugf("Waiting for RBF iteration to complete...")
-
- for {
- select {
- case newState := <-newStateChan:
- if isTerminalState(newState) {
- return nil
- }
-
- case <-ctx.Done():
- return fmt.Errorf("context canceled")
- }
- }
-}
-
// startRbfChanCloser kicks off the co-op close process using the new RBF based
// co-op close protocol. This is called when we're the one that's initiating
-// the cooperative channel close.
+// the cooperative channel close, or requesting a fee bump.
//
// TODO(roasbeef): just accept the two shutdown pointer params instead??
func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
@@ -4982,50 +5028,24 @@ func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
chanPoint)
}
- defaultFeePerKw, err := shutdownStartFeeRate(
- shutdown,
- ).UnwrapOrFuncErr(func() (chainfee.SatPerKWeight, error) {
- return p.cfg.FeeEstimator.EstimateFeePerKW(
- p.cfg.CoopCloseTargetConfs,
- )
- })
- if err != nil {
- return fmt.Errorf("unable to estimate fee: %w", err)
- }
-
- // A failure inside the callback cannot be returned through it, so it is
- // recorded here and returned below. A caller that is not told the close
- // never started waits on a request nothing is left to resolve.
- var startErr error
+ targetFeeOpt := fn.MapOption(func(fee chainfee.SatPerKWeight) chainfee.SatPerVByte { //nolint:ll
+ return fee.FeePerVByte()
+ })(shutdownStartFeeRate(shutdown))
chanCloser.WhenRight(func(rbfCloser *chancloser.RbfChanCloser) {
- peerLog.Infof("ChannelPoint(%v): rbf-coop close requested, "+
- "sending shutdown", chanPoint)
-
- rbfState, err := rbfCloser.CurrentState()
- if err != nil {
- peerLog.Warnf("ChannelPoint(%v): unable to get "+
- "current state for rbf-coop close: %v",
- chanPoint, err)
-
- // No caller has been recorded yet, so this is the only
- // path that can answer the one that asked for the
- // close.
- startErr = fmt.Errorf("unable to get current state "+
- "for rbf-coop close: %w", err)
-
- return
- }
+ peerLog.Infof("ChannelPoint(%v): rbf-coop close requested",
+ chanPoint)
coopCloseStates := rbfCloser.RegisterStateEvents()
+ var bumpSeq uint64
// Before we send our event below, we'll launch a goroutine to
- // watch for the final terminal state to send updates to the RPC
- // client. We only need to do this if there's an RPC caller.
+ // watch for updates and send them to the RPC client. We only
+ // need to do this if there's an RPC caller.
var rpcShutdown bool
whenRPCShutdown(shutdown, func(req *htlcswitch.ChanClose) {
rpcShutdown = true
-
+ bumpSeq = p.rbfBumpSeq.Add(1)
// Record the caller against the channel so that
// retiring the closer can tell it how the close
// ended. The RBF closer itself carries no request.
@@ -5038,7 +5058,7 @@ func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
// and its caller waits on a close nothing reaches.
// Answer it here. The state subscription is dropped by
// hand, since no observer will run to drop it.
- if _, live := p.activeChanCloses.Load(chanID); !live {
+ if !p.isSameLiveRbfCloser(chanID, rbfCloser) {
rbfCloser.RemoveStateSub(coopCloseStates)
p.claimAndAnswerRetiredCaller(chanID, req)
@@ -5048,68 +5068,55 @@ func (p *Brontide) startRbfChanCloser(shutdown shutdownInit,
go func() {
defer p.cg.WgDone()
- p.observeRbfCloseUpdates(
+ p.observeRbfCloseUpdatesWithSeq(
rbfCloser, req, coopCloseStates,
+ bumpSeq,
)
}()
})
if !rpcShutdown {
defer rbfCloser.RemoveStateSub(coopCloseStates)
}
+ sendBaseCtx := shutdownStartCtx(shutdown)
- ctx, _ := p.cg.Create(context.Background())
- feeRate := defaultFeePerKw.FeePerVByte()
-
- // Depending on the state of the state machine, we'll either
- // kick things off by sending shutdown, or attempt to send a new
- // offer to the remote party.
- switch rbfState.(type) {
- // The channel is still active, so we'll now kick off the co-op
- // close process by instructing it to send a shutdown message to
- // the remote party.
- case *chancloser.ChannelActive:
- rbfCloser.SendEvent(
- context.Background(),
- &chancloser.SendShutdown{
- IdealFeeRate: feeRate,
- DeliveryAddr: shutdownStartAddr(
- shutdown,
- ),
- },
- )
+ sendCtx, cancelSend := p.cg.Create(sendBaseCtx)
+ defer cancelSend()
- // If we haven't yet sent an offer (didn't have enough funds at
- // the prior fee rate), or we've sent an offer, then we'll
- // trigger a new offer event.
- case *chancloser.ClosingNegotiation:
- // Before we send the event below, we'll wait until
- // we're in a semi-terminal state.
- err := waitUntilRbfCoastClear(ctx, rbfCloser)
- if err != nil {
- peerLog.Warnf("ChannelPoint(%v): unable to "+
- "wait for coast to clear: %v",
- chanPoint, err)
+ rbfCloser.SendEvent(sendCtx, &chancloser.LocalCloseReq{
+ DeliveryAddr: shutdownStartAddr(shutdown),
+ TargetFeeRate: targetFeeOpt,
+ Seq: bumpSeq,
+ })
+ })
- return
- }
+ return nil
+}
- event := chancloser.ProtocolEvent(
- &chancloser.SendOfferEvent{
- TargetFeeRate: feeRate,
- },
- )
- rbfCloser.SendEvent(ctx, event)
+// isSameLiveRbfCloser reports whether chanID is still mapped to rbfCloser and
+// that rbfCloser has not been asked to stop.
+func (p *Brontide) isSameLiveRbfCloser(chanID lnwire.ChannelID,
+ rbfCloser *chancloser.RbfChanCloser) bool {
- default:
- peerLog.Warnf("ChannelPoint(%v): unexpected state "+
- "for rbf-coop close: %T", chanPoint, rbfState)
- }
+ current, live := p.activeChanCloses.Load(chanID)
+ if !live {
+ return false
+ }
+
+ var same bool
+ current.WhenRight(func(cur *chancloser.RbfChanCloser) {
+ same = cur == rbfCloser
})
+ if !same {
+ return false
+ }
- // A callback that failed before the close could start is reported
- // to the caller here, since nothing else owns the request yet.
- return startErr
+ select {
+ case <-rbfCloser.Done():
+ return false
+ default:
+ return true
+ }
}
// handleLocalCloseReq kicks-off the workflow to execute a cooperative or
### peer/brontide_test.go
@@ -19,6 +19,7 @@ import (
"github.com/btcsuite/btcd/wire/v2"
"github.com/lightningnetwork/lnd/actor"
"github.com/lightningnetwork/lnd/chainntnfs"
+ "github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/chanstate"
"github.com/lightningnetwork/lnd/contractcourt"
"github.com/lightningnetwork/lnd/fn/v2"
@@ -27,10 +28,13 @@ import (
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnpeer"
"github.com/lightningnetwork/lnd/lntest/wait"
+ "github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwallet"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwallet/chancloser"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/msgmux"
+ "github.com/lightningnetwork/lnd/protofsm"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/tlv"
"github.com/lightningnetwork/lnd/tor"
@@ -4426,3 +4430,589 @@ func useTestCloseRouter(t *testing.T, p *Brontide) {
p.msgRouter = fn.Some[msgmux.Router](router)
p.globalMsgRouter = true
}
+
+// rbfIssueFeeEstimator records the fee rate of every offer the closer builds,
+// and keeps the local balance too small to sign one.
+type rbfIssueFeeEstimator struct {
+ fees chan chainfee.SatPerKWeight
+}
+
+func (f *rbfIssueFeeEstimator) EstimateFee(_ channeldb.ChannelType,
+ _, _ *wire.TxOut, _ []*wire.TxOut,
+ fee chainfee.SatPerKWeight) btcutil.Amount {
+
+ f.fees <- fee
+ return 1000
+}
+
+type rbfIssueObserver struct {
+ chancloser.ChanStateObserver
+}
+
+func (*rbfIssueObserver) FinalBalances() fn.Option[chancloser.ShutdownBalances] { //nolint:ll
+ return fn.None[chancloser.ShutdownBalances]()
+}
+
+func (*rbfIssueObserver) DisableIncomingAdds() error {
+ return nil
+}
+
+// startIssueRbfMachine starts an RBF closer in the given state and stores it
+// as the peer's closer for the channel.
+func startIssueRbfMachine(t *testing.T, p *Brontide, point wire.OutPoint,
+ initial chancloser.RbfState, fees *rbfIssueFeeEstimator,
+) *chancloser.RbfChanCloser {
+
+ t.Helper()
+ machine := protofsm.NewStateMachine(chancloser.RbfChanCloserCfg{
+ InitialState: initial,
+ Env: &chancloser.Environment{
+ ChainParams: p.cfg.Wallet.Cfg.NetParams,
+ ChanPoint: point,
+ ChanObserver: &rbfIssueObserver{},
+ FeeEstimator: fees,
+ DefaultFeeRate: 1,
+ },
+ })
+ machine.Start(t.Context())
+ t.Cleanup(machine.Stop)
+ p.activeChanCloses.Store(
+ lnwire.NewChanIDFromOutPoint(point), makeRbfCloser(&machine),
+ )
+
+ return &machine
+}
+
+// newIssueBump returns a CloseChannel fee bump request to 5000 sat/kw.
+func newIssueBump(ctx context.Context,
+ point *wire.OutPoint) *htlcswitch.ChanClose {
+
+ req := newTestCloseRequest(point, 10)
+ req.Ctx = ctx
+ req.CloseType = contractcourt.CloseRegular
+ req.TargetFeePerKw = 5000
+
+ return req
+}
+
+func newIssueTerms(t *testing.T) *chancloser.CloseChannelTerms {
+ return &chancloser.CloseChannelTerms{
+ ShutdownScripts: chancloser.ShutdownScripts{
+ LocalDeliveryScript: genScript(t, p2wshAddress),
+ RemoteDeliveryScript: genScript(t, p2wshAddress),
+ },
+ }
+}
+
+func newIssueNegotiation(t *testing.T,
+ local chancloser.AsymmetricPeerState) *chancloser.ClosingNegotiation {
+
+ terms := newIssueTerms(t)
+
+ return &chancloser.ClosingNegotiation{
+ PeerState: lntypes.Dual[chancloser.AsymmetricPeerState]{
+ Local: local,
+ Remote: &chancloser.RemoteCloseStart{
+ CloseChannelTerms: terms,
+ },
+ },
+ CloseChannelTerms: terms,
+ }
+}
+
+func enableTestRbfClose(t *testing.T, p *Brontide, h *peerTestCtx) {
+ t.Helper()
+ rbfBits := lnwire.NewRawFeatureVector(lnwire.RbfCoopCloseOptional)
+ p.cfg.Features = lnwire.NewFeatureVector(rbfBits, lnwire.Features)
+ p.remoteFeatures = lnwire.NewFeatureVector(rbfBits, lnwire.Features)
+ require.True(t, p.rbfCoopCloseAllowed(h.channel.ChanType()))
+}
+
+func requireCloseReqTaken(t *testing.T, p *Brontide, req *htlcswitch.ChanClose,
+ msg string) {
+
+ t.Helper()
+ taken := make(chan struct{})
+ go func() {
+ p.HandleLocalCloseChanReqs(req)
+ close(taken)
+ }()
+ select {
+ case <-taken:
+ case <-time.After(timeout):
+ t.Fatalf("%s: the channel manager did not take a second "+
+ "close request within %v", msg, timeout)
+ }
+}
+
+func requireFeeOffered(t *testing.T, fees *rbfIssueFeeEstimator,
+ want chainfee.SatPerKWeight) {
+
+ t.Helper()
+ var seen []chainfee.SatPerKWeight
+ deadline := time.After(timeout)
+ for {
+ select {
+ case fee := <-fees.fees:
+ if fee == want {
+ return
+ }
+ seen = append(seen, fee)
+
+ case <-deadline:
+ t.Fatalf("no offer at the requested %v within %v; "+
+ "offers built: %v", want, timeout, seen)
+ }
+ }
+}
+
+// TestRbfBumpDuringRestoredShutdown verifies that a fee bump arriving while a
+// close is in ShutdownPending is buffered and evaluated once shutdown finishes.
+func TestRbfBumpDuringRestoredShutdown(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ fees := &rbfIssueFeeEstimator{
+ fees: make(chan chainfee.SatPerKWeight, 4),
+ }
+ scripts := newIssueTerms(t).ShutdownScripts
+ machine := startIssueRbfMachine(
+ t, p, point, &chancloser.ShutdownPending{
+ ShutdownScripts: scripts,
+ IdealFeeRate: fn.Some(chainfee.SatPerVByte(1)),
+ }, fees,
+ )
+
+ req := newIssueBump(t.Context(), &point)
+ require.NoError(t, p.startRbfChanCloser(newRPCShutdownInit(req), point))
+
+ // The peer's Shutdown arrives and the channel flushes with zero local
+ // balance, so the buffered bump should produce ErrStateCantPayForFee.
+ machine.SendEvent(t.Context(), &chancloser.ShutdownReceived{
+ ShutdownScript: genScript(t, p2wshAddress),
+ })
+ machine.SendEvent(t.Context(), &chancloser.ChannelFlushed{
+ ShutdownBalances: chancloser.ShutdownBalances{
+ RemoteBalance: 10_000_000,
+ },
+ })
+
+ requireFeeOffered(t, fees, req.TargetFeePerKw)
+
+ select {
+ case err := <-req.ErrChan(t.Context()):
+ require.ErrorContains(t, err, "cannot pay for fee")
+ case <-time.After(timeout):
+ t.Fatal("caller did not receive unpayable-fee error")
+ }
+}
+
+// TestRbfBumpWaitKeepsChannelManagerFree verifies that a fee bump while Local
+// is in LocalOfferSent never blocks the peer's channelManager goroutine.
+func TestRbfBumpWaitKeepsChannelManagerFree(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ enableTestRbfClose(t, p, h)
+ fees := &rbfIssueFeeEstimator{
+ fees: make(chan chainfee.SatPerKWeight, 4),
+ }
+ startIssueRbfMachine(t, p, point, newIssueNegotiation(t,
+ &chancloser.LocalOfferSent{CloseChannelTerms: newIssueTerms(t)},
+ ), fees)
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ p.HandleLocalCloseChanReqs(newIssueBump(t.Context(), &point))
+ requireCloseReqTaken(
+ t, p, newIssueBump(t.Context(), &point), "bump waiting",
+ )
+}
+
+// TestRbfBumpWaitEndsOnCallerCancel verifies that cancelling a bump caller's
+// context releases its registration and leaves channelManager responsive.
+func TestRbfBumpWaitEndsOnCallerCancel(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ chanID := lnwire.NewChanIDFromOutPoint(point)
+ enableTestRbfClose(t, p, h)
+ fees := &rbfIssueFeeEstimator{
+ fees: make(chan chainfee.SatPerKWeight, 4),
+ }
+ startIssueRbfMachine(t, p, point, newIssueNegotiation(t,
+ &chancloser.LocalOfferSent{CloseChannelTerms: newIssueTerms(t)},
+ ), fees)
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ ctx, cancel := context.WithCancel(t.Context())
+ p.HandleLocalCloseChanReqs(newIssueBump(ctx, &point))
+ err = wait.Predicate(func() bool {
+ return p.activeCloseReqs.peek(chanID) != nil
+ }, timeout)
+ require.NoError(t, err)
+ cancel()
+ err = wait.Predicate(func() bool {
+ return p.activeCloseReqs.peek(chanID) == nil
+ }, timeout)
+ require.NoError(t, err)
+
+ requireCloseReqTaken(
+ t, p, newIssueBump(t.Context(), &point), "caller cancelled",
+ )
+}
+
+// TestRbfBumpWithoutClosePending verifies that fee bumps proceed immediately
+// when Local is in CloseErr or LocalCloseStart.
+func TestRbfBumpWithoutClosePending(t *testing.T) {
+ t.Parallel()
+
+ for _, name := range []string{"CloseErr", "LocalCloseStart"} {
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ fees := &rbfIssueFeeEstimator{
+ fees: make(chan chainfee.SatPerKWeight, 4),
+ }
+ terms := newIssueTerms(t)
+ var local chancloser.AsymmetricPeerState = &chancloser.LocalCloseStart{ //nolint:ll
+ CloseChannelTerms: terms,
+ }
+ if name == "CloseErr" {
+ local = &chancloser.CloseErr{
+ CloseChannelTerms: terms,
+ Party: lntypes.Local,
+ ErrState: chancloser.NewErrStateCantPayForFee( //nolint:ll
+ 0, 1000,
+ ),
+ }
+ }
+ startIssueRbfMachine(
+ t, p, point, newIssueNegotiation(t, local), fees, //nolint:ll
+ )
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ req := newIssueBump(t.Context(), &point)
+ require.NoError(t, p.startRbfChanCloser(
+ newRPCShutdownInit(req), point,
+ ))
+ requireFeeOffered(t, fees, req.TargetFeePerKw)
+ })
+ }
+}
+
+// TestRbfCloseFinWipesChannelAndLink verifies that CloseFin tears down the
+// closer, activeChannels entry, and switch link for both locally initiated and
+// remote-initiated RBF cooperative closes.
+func TestRbfCloseFinWipesChannelAndLink(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ localInitiated bool
+ withLink bool
+ }{
+ {
+ name: "local_initiated",
+ localInitiated: true,
+ withLink: true,
+ },
+ {
+ name: "remote_initiated",
+ localInitiated: false,
+ withLink: true,
+ },
+ {
+ name: "restored_no_link",
+ localInitiated: false,
+ withLink: false,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ harness, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ alicePeer := harness.peer
+ bobChan := harness.channel
+ chanPoint := bobChan.ChannelPoint()
+ chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
+
+ removedLinks := make(chan lnwire.ChannelID, 1)
+ harness.mockSwitch.removedLinks = removedLinks
+ if tc.withLink {
+ harness.mockSwitch.links = append(
+ harness.mockSwitch.links,
+ newMockUpdateHandler(chanID),
+ )
+ }
+ useTestCloseRouter(t, alicePeer)
+ rbfCloser := initTestRbfCloser(t, alicePeer, bobChan)
+ t.Cleanup(func() {
+ alicePeer.Disconnect(context.Canceled)
+ })
+
+ var closeReq *htlcswitch.ChanClose
+ if tc.localInitiated {
+ closeReq = newTestCloseRequest(&chanPoint, 5)
+ alicePeer.activeCloseReqs.add(chanID, closeReq)
+ stateSub := rbfCloser.RegisterStateEvents()
+ alicePeer.cg.WgAdd(1)
+ go func() {
+ defer alicePeer.cg.WgDone()
+ alicePeer.observeRbfCloseUpdates(
+ rbfCloser, closeReq, stateSub,
+ )
+ }()
+ }
+ closingTx := wire.NewMsgTx(2)
+ rbfCloser.SendEvent(t.Context(), &chancloser.SpendEvent{
+ Tx: closingTx,
+ })
+ // The closer, channel, and switch link must all be
+ // removed.
+ err = wait.Predicate(func() bool {
+ _, closerFound := alicePeer.activeChanCloses.Load( //nolint:ll
+ chanID,
+ )
+ _, chanFound := alicePeer.activeChannels.Load( //nolint:ll
+ chanID,
+ )
+
+ return !closerFound && !chanFound &&
+ !rbfCloser.IsRunning()
+ }, timeout)
+ require.NoError(t, err)
+ if tc.withLink {
+ select {
+ case removedID := <-removedLinks:
+ require.Equal(t, chanID, removedID)
+ case <-time.After(timeout):
+ t.Fatal("switch link not removed")
+ }
+ }
+ if tc.localInitiated {
+ select {
+ case update := <-closeReq.Updates:
+ cu, ok := update.(*ChannelCloseUpdate)
+ require.True(t, ok, "got %T", update)
+ require.True(t, cu.Success)
+ var gotHash chainhash.Hash
+ copy(gotHash[:], cu.ClosingTxid)
+ require.Equal(
+ t, closingTx.TxHash(), gotHash,
+ )
+ case <-time.After(timeout):
+ t.Fatal("missing close confirmation")
+ }
+ }
+ })
+ }
+}
+
+// TestRbfCloseErrDoesNotLeakOnRetry verifies that an unpayable fee bump exits
+// its observer on CloseErr without later emitting a late cancellation that
+// re-notifies a subsequent retry caller.
+func TestRbfCloseErrDoesNotLeakOnRetry(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ fees := &rbfIssueFeeEstimator{
+ fees: make(chan chainfee.SatPerKWeight, 4),
+ }
+ terms := newIssueTerms(t)
+ terms.LocalBalance = 0
+ startIssueRbfMachine(t, p, point, newIssueNegotiation(t,
+ &chancloser.LocalCloseStart{CloseChannelTerms: terms},
+ ), fees)
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ // First bump fails with CloseErr and resolves caller 1.
+ ctx1, cancel1 := context.WithCancel(t.Context())
+ req1 := newIssueBump(ctx1, &point)
+ require.NoError(t, p.startRbfChanCloser(
+ newRPCShutdownInit(req1), point,
+ ))
+ requireFeeOffered(t, fees, req1.TargetFeePerKw)
+ select {
+ case err := <-req1.ErrChan(t.Context()):
+ require.ErrorContains(t, err, "cannot pay for fee")
+ case <-time.After(timeout):
+ t.Fatal("caller 1 did not receive unpayable-fee error")
+ }
+
+ // Register caller 2 and cancel caller 1; caller 2 must not receive
+ // caller 1's stale CloseErr.
+ chanID := lnwire.NewChanIDFromOutPoint(point)
+ req2 := newIssueBump(t.Context(), &point)
+ p.activeCloseReqs.add(chanID, req2)
+ machineAny, ok := p.activeChanCloses.Load(chanID)
+ require.True(t, ok)
+ machineAny.WhenRight(func(m *chancloser.RbfChanCloser) {
+ sub := m.RegisterStateEvents()
+ p.cg.WgAdd(1)
+ go func() {
+ defer p.cg.WgDone()
+ p.observeRbfCloseUpdates(m, req2, sub)
+ }()
+ })
+ cancel1()
+ select {
+ case err := <-req2.ErrChan(t.Context()):
+ t.Fatalf("caller 2 got stale err: %v", err)
+ case <-time.After(shortTimeout):
+ }
+}
+
+// TestRbfReportErrorAnswersCallersAndRetiresCloser verifies that when the RBF
+// FSM errors out, ReportError aborts waiting RPC callers with the FSM error,
+// retires the stopped closer when no active channel remains, and replaces it
+// cleanly when an active channel is present.
+func TestRbfReportErrorAnswersCallersAndRetiresCloser(t *testing.T) {
+ t.Parallel()
+
+ t.Run("active_channel_replaces_and_answers", func(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ chanID := lnwire.NewChanIDFromOutPoint(point)
+ useTestCloseRouter(t, p)
+
+ oldCloser := initTestRbfCloser(t, p, h.channel)
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ req := newTestCloseRequest(&point, 5)
+ p.activeCloseReqs.add(chanID, req)
+ stateSub := oldCloser.RegisterStateEvents()
+ p.cg.WgAdd(1)
+ go func() {
+ defer p.cg.WgDone()
+ p.observeRbfCloseUpdates(oldCloser, req, stateSub)
+ }()
+
+ fsmErr := errors.New("test fsm transition error")
+ go newChanErrorReporter(chanID, p).ReportError(fsmErr)
+ select {
+ case out := <-p.outgoingQueue:
+ _, ok := out.msg.(*lnwire.Error)
+ require.True(t, ok, "expected lnwire.Error")
+ case <-time.After(timeout):
+ t.Fatal("expected error message on outgoingQueue")
+ }
+ oldCloser.Stop()
+
+ select {
+ case gotErr := <-req.ErrChan(t.Context()):
+ require.ErrorIs(t, gotErr, fsmErr)
+ case <-time.After(timeout):
+ t.Fatal("waiting caller was not answered")
+ }
+
+ // A fresh live replacement closer should be installed.
+ err = wait.Predicate(func() bool {
+ cur, found := p.activeChanCloses.Load(chanID)
+ if !found {
+ return false
+ }
+ var replaced *chancloser.RbfChanCloser
+ cur.WhenRight(func(c *chancloser.RbfChanCloser) { //nolint:ll
+ replaced = c
+ })
+
+ return replaced != nil && replaced != oldCloser &&
+ replaced.IsRunning()
+ }, timeout)
+ require.NoError(t, err)
+ })
+
+ t.Run("missing_channel_retires_closer", func(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ chanID := lnwire.NewChanIDFromOutPoint(point)
+ useTestCloseRouter(t, p)
+
+ oldCloser := initTestRbfCloser(t, p, h.channel)
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ p.activeChannels.Delete(chanID)
+ req := newTestCloseRequest(&point, 5)
+ p.activeCloseReqs.add(chanID, req)
+
+ fsmErr := errors.New("test fsm transition error")
+ go newChanErrorReporter(chanID, p).ReportError(fsmErr)
+ select {
+ case out := <-p.outgoingQueue:
+ _, ok := out.msg.(*lnwire.Error)
+ require.True(t, ok, "expected lnwire.Error")
+ case <-time.After(timeout):
+ t.Fatal("expected error message on outgoingQueue")
+ }
+
+ select {
+ case gotErr := <-req.ErrChan(t.Context()):
+ require.ErrorIs(t, gotErr, fsmErr)
+ case <-time.After(timeout):
+ t.Fatal("waiting caller was not answered")
+ }
+ _, found := p.activeChanCloses.Load(chanID)
+ require.False(t, found)
+ err = wait.Predicate(func() bool {
+ return !oldCloser.IsRunning()
+ }, timeout)
+ require.NoError(t, err)
+ })
+}
+
+// TestRbfIsSameLiveCloserRejectsReplacedOrStopped verifies the identity and
+// liveness guard used before binding an RPC caller to an RBF closer.
+func TestRbfIsSameLiveCloserRejectsReplacedOrStopped(t *testing.T) {
+ t.Parallel()
+
+ h, err := createTestPeerWithChannel(t, noUpdate)
+ require.NoError(t, err)
+ p := h.peer
+ point := h.channel.ChannelPoint()
+ chanID := lnwire.NewChanIDFromOutPoint(point)
+ fees := &rbfIssueFeeEstimator{
+ fees: make(chan chainfee.SatPerKWeight, 4),
+ }
+ t.Cleanup(func() { p.Disconnect(context.Canceled) })
+
+ first := startIssueRbfMachine(
+ t, p, point, &chancloser.ChannelActive{}, fees,
+ )
+ require.True(t, p.isSameLiveRbfCloser(chanID, first))
+
+ // Stopping the same closer must fail the liveness check even while it
+ // remains in activeChanCloses.
+ first.Stop()
+ require.False(t, p.isSameLiveRbfCloser(chanID, first))
+
+ // Replacing the map entry with a fresh closer must reject the old one.
+ second := startIssueRbfMachine(
+ t, p, point, &chancloser.ChannelActive{}, fees,
+ )
+ require.False(t, p.isSameLiveRbfCloser(chanID, first))
+ require.True(t, p.isSameLiveRbfCloser(chanID, second))
+}
### peer/test_utils.go
@@ -358,7 +358,8 @@ func createTestPeerWithChannel(t *testing.T, updateChan func(a,
// mockMessageSwitch is a mock implementation of the messageSwitch interface
// used for testing without relying on a *htlcswitch.Switch in unit tests.
type mockMessageSwitch struct {
- links []htlcswitch.ChannelUpdateHandler
+ links []htlcswitch.ChannelUpdateHandler
+ removedLinks chan lnwire.ChannelID
}
// BestHeight currently returns a dummy value.
@@ -372,7 +373,14 @@ func (m *mockMessageSwitch) CircuitModifier() htlcswitch.CircuitModifier {
}
// RemoveLink currently does nothing.
-func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {}
+func (m *mockMessageSwitch) RemoveLink(cid lnwire.ChannelID) {
+ if m.removedLinks != nil {
+ select {
+ case m.removedLinks <- cid:
+ default:
+ }
+ }
+}
// CreateAndAddLink currently returns a dummy value.
func (m *mockMessageSwitch) CreateAndAddLink(cfg htlcswitch.ChannelLinkConfig,
### protofsm/state_machine.go
@@ -244,6 +244,12 @@ func (s *StateMachine[Event, Env]) Stop() {
})
}
+// Done returns a channel that is closed once the state machine has been asked
+// to stop.
+func (s *StateMachine[Event, Env]) Done() <-chan struct{} {
+ return s.quit
+}
+
// SendEvent sends a new event to the state machine.
//
// TODO(roasbeef): bool if processed?Why this scored 45/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.