What changed, and why it matters
This commit fixes a bug in LND's transaction sweeping logic. Previously, when the node couldn't reliably check whether an input had already been spent (for example, because a notifier registration failed or a subscription closed unexpectedly), the code could either crash the node or wrongly treat the input as unspent. The patch makes these failures retryable instead of fatal, preserves the user's chosen fee rate instead of resetting it to zero, and continues fee-bumping deadline sweeps even when the spend check is inconclusive. This prevents stuck funds or incorrect fee handling during network or backend hiccups.
Treat this as a defensive hardening fix and include it in the next maintenance release. Operators running nodes that experience backend notifier instability should prioritize upgrading. No immediate emergency response is indicated because the issue is primarily a reliability/DoS concern rather than a remote exploit.
Security signals we found
Previously inconclusive spend checks could be treated as 'not spent', potentially leading to invalid transaction publication or missed spend detection
Notifier registration failures previously logged `Criticalf` and returned `nil`, risking node crash or unsafe fallback behavior
Closed spend subscriptions were silently ignored, allowing false 'unspent' classification
Retryable failure path now preserves existing fee preference, avoiding zero-fee follow-up sweeps
Deadline sweeps continue fee-bumping despite backend uncertainty, reducing risk of HTLC timeout failures
Evidence from the diff
The patch changes TxPublisher.getSpentInputs to return an error when spend-notification registration or the subscription channel fails, instead of logging a critical message and returning nil. handleMissingInputs now converts that error into a TxFailed (retryable) BumpResult wrapping errSpendCheckFailed. During processRecords, an inconclusive check is logged and the record is treated as unspent so fee-bumping continues. UtxoSweeper.markInputsPublishFailed now accepts an optional optional fee rate; when the failure is errSpendCheckFailed, the existing StartingFeeRate is preserved rather than overwritten by the BumpResult’s zero fee rate. Tests cover registration failures, notifier shutdown, closed channels, and fee-rate preservation.
Changed components
sweep/fee_bumper.gosweep/sweeper.gosweep/fee_bumper_test.gosweep/retry_fee_preservation_test.gosweep/sweeper_test.goInspect captured patch +215 / −25
### sweep/fee_bumper.go
@@ -47,6 +47,9 @@ var (
// ErrInputMissing is returned when a given input no longer exists,
// e.g., spending from an orphan tx.
ErrInputMissing = errors.New("input no longer exists")
+
+ // errSpendCheckFailed identifies an inconclusive spend check.
+ errSpendCheckFailed = errors.New("spend check failed")
)
var (
@@ -698,9 +701,20 @@ func (t *TxPublisher) createAndCheckTx(r *monitorRecord) (*sweepTxCtx, error) {
// in another tx, or the input is referencing an orphan. When the input is
// spent, it will be handled via the TxUnknownSpend flow by creating a
// TxUnknownSpend bump result, otherwise, a TxFatal bump result is returned.
+// A failed spend check yields a retryable TxFailed result.
func (t *TxPublisher) handleMissingInputs(r *monitorRecord) *BumpResult {
// Get the spending txns.
- spends := t.getSpentInputs(r)
+ spends, err := t.getSpentInputs(r)
+ if err != nil {
+ return &BumpResult{
+ Event: TxFailed,
+ Tx: r.tx,
+ requestID: r.requestID,
+ Err: fmt.Errorf(
+ "%w: %w", errSpendCheckFailed, err,
+ ),
+ }
+ }
// Attach the spending txns.
r.spentInputs = spends
@@ -992,7 +1006,18 @@ func (t *TxPublisher) processRecords() {
log.Tracef("Checking monitor recordID=%v", requestID)
// Check whether the inputs have already been spent.
- spends := t.getSpentInputs(r)
+ //
+ // An inconclusive check doesn't show that any input was spent,
+ // so we proceed as if none were. Skipping the record instead
+ // would stop fee bumps for as long as the check keeps failing,
+ // which a deadline sweep can't afford. If an input was in fact
+ // spent, the mempool rejects the attempt for missing inputs
+ // and the missing input handling takes over.
+ spends, err := t.getSpentInputs(r)
+ if err != nil {
+ log.Errorf("Unable to check spends for record %v, "+
+ "proceeding as unspent: %v", requestID, err)
+ }
// If the any of the inputs has been spent, the record will be
// marked as failed or confirmed.
@@ -1412,9 +1437,10 @@ func (t *TxPublisher) isUnknownSpent(r *monitorRecord,
// getSpentInputs performs a non-blocking read on the spending subscriptions to
// see whether any of the monitored inputs has been spent. A map of inputs with
-// their spending txns are returned if found.
+// their spending txns are returned if found. An error indicates that the
+// inputs could not be checked reliably.
func (t *TxPublisher) getSpentInputs(
- r *monitorRecord) map[wire.OutPoint]*wire.MsgTx {
+ r *monitorRecord) (map[wire.OutPoint]*wire.MsgTx, error) {
// Create a slice to record the inputs spent.
spentInputs := make(map[wire.OutPoint]*wire.MsgTx, len(r.req.Inputs))
@@ -1442,10 +1468,10 @@ func (t *TxPublisher) getSpentInputs(
&op, inp.SignDesc().Output.PkScript, heightHint,
)
if err != nil {
- log.Criticalf("Failed to register spend ntfn for "+
- "input=%v: %v", op, err)
-
- return nil
+ return nil, fmt.Errorf(
+ "register spend notification for %v: %w",
+ op, err,
+ )
}
// Remove the subscription when exit.
@@ -1455,9 +1481,9 @@ func (t *TxPublisher) getSpentInputs(
select {
case spend, ok := <-spendEvent.Spend:
if !ok {
- log.Debugf("Spend ntfn for %v canceled", op)
-
- continue
+ return nil, fmt.Errorf(
+ "spend notification for %v closed", op,
+ )
}
spendingTx := spend.SpendingTx
@@ -1473,7 +1499,7 @@ func (t *TxPublisher) getSpentInputs(
}
}
- return spentInputs
+ return spentInputs, nil
}
// calcCurrentConfTarget calculates the current confirmation target based on
### sweep/fee_bumper_test.go
@@ -2247,7 +2247,8 @@ func TestHasInputsSpent(t *testing.T) {
}
// Call the method under test.
- result := tp.getSpentInputs(record)
+ result, err := tp.getSpentInputs(record)
+ require.NoError(t, err)
// Assert the expected map is created.
expected := map[wire.OutPoint]*wire.MsgTx{
@@ -2256,6 +2257,73 @@ func TestHasInputsSpent(t *testing.T) {
require.Equal(t, expected, result)
}
+// TestSpendNotificationFailure ensures failed checks never classify inputs.
+func TestSpendNotificationFailure(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ closed bool
+ }{
+ {name: "registration", err: fmt.Errorf("registration failed")},
+ {
+ name: "shutdown",
+ err: chainntnfs.ErrChainNotifierShuttingDown,
+ },
+ {
+ name: "closed", closed: true,
+ err: chainntnfs.ErrChainNotifierShuttingDown,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tp, m := createTestPublisher(t)
+ req := createTestBumpRequest()
+ op := req.Inputs[0].OutPoint()
+ var event *chainntnfs.SpendEvent
+ err := tc.err
+ if tc.closed {
+ spends := make(chan *chainntnfs.SpendDetail)
+ close(spends)
+ event = &chainntnfs.SpendEvent{
+ Spend: spends, Cancel: func() {},
+ }
+ err = nil
+ }
+ m.notifier.On("RegisterSpendNtfn", &op, mock.Anything,
+ mock.Anything).Return(event, err).Twice()
+ r := &monitorRecord{requestID: 1, req: req}
+ result := tp.handleMissingInputs(r)
+ require.Equal(t, TxFailed, result.Event)
+ if tc.closed {
+ require.ErrorContains(t, result.Err, "closed")
+ } else {
+ require.ErrorIs(t, result.Err, tc.err)
+ }
+
+ // An inconclusive check during record processing must
+ // not stop a broadcast record from being fee bumped.
+ r.tx = &wire.MsgTx{LockTime: 1}
+ r.feeFunction = m.feeFunc
+
+ bumped := make(chan struct{})
+ m.feeFunc.On("IncreaseFeeRate", mock.Anything).Run(
+ func(mock.Arguments) { close(bumped) },
+ ).Return(false, nil).Once()
+
+ tp.records.Store(r.requestID, r)
+ tp.processRecords()
+
+ select {
+ case <-bumped:
+ case <-time.After(time.Second):
+ t.Fatal("record was not fee bumped")
+ }
+
+ _, found := tp.records.Load(r.requestID)
+ require.True(t, found)
+ })
+ }
+}
+
// createTestSpendEvent creates a SpendEvent which places the specified tx in
// the channel, which can be read by a spending subscriber.
func createTestSpendEvent(tx *wire.MsgTx) *chainntnfs.SpendEvent {
### sweep/retry_fee_preservation_test.go
@@ -0,0 +1,91 @@
+package sweep
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/input"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
+ "github.com/stretchr/testify/mock"
+ "github.com/stretchr/testify/require"
+)
+
+// TestSpendCheckRetryPreservesStartingFeeRate ensures an inconclusive spend
+// check does not overwrite the input's fee-rate preference.
+func TestSpendCheckRetryPreservesStartingFeeRate(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ starting fn.Option[chainfee.SatPerKWeight]
+ }{
+ {
+ "explicit starting rate",
+ fn.Some(chainfee.SatPerKWeight(1200)),
+ },
+ {
+ "estimated starting rate",
+ fn.None[chainfee.SatPerKWeight](),
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tp, mocks := createTestPublisher(t)
+ req := createTestBumpRequest()
+ req.StartingFeeRate = tc.starting
+ r := &monitorRecord{requestID: 1, req: req}
+
+ op := req.Inputs[0].OutPoint()
+ mocks.notifier.On(
+ "RegisterSpendNtfn", &op, mock.Anything,
+ mock.Anything,
+ ).Return(nil, errors.New("unavailable")).Once()
+
+ result := tp.handleMissingInputs(r)
+ require.Equal(t, TxFailed, result.Event)
+
+ s := New(&UtxoSweeperConfig{})
+ inp := req.Inputs[0]
+ s.inputs[op] = &SweeperInput{
+ Input: inp, state: PendingPublish,
+ params: Params{StartingFeeRate: tc.starting},
+ }
+ set := &MockInputSet{}
+ set.On("Inputs").Return(req.Inputs).Once()
+
+ err := s.handleBumpEvent(&bumpResp{
+ set: set, result: result,
+ })
+ require.NoError(t, err)
+ require.Equal(t, PublishFailed, s.inputs[op].state)
+ require.Equal(
+ t, tc.starting,
+ s.inputs[op].params.StartingFeeRate,
+ )
+ set.AssertExpectations(t)
+ })
+ }
+}
+
+// TestRetryUpdatesSpecifiedFeeRate ensures ordinary retry results still update
+// the starting fee rate supplied by the fee bumper.
+func TestRetryUpdatesSpecifiedFeeRate(t *testing.T) {
+ s := New(&UtxoSweeperConfig{})
+ inp := createMockInput(t, s, PendingPublish)
+ op := inp.OutPoint()
+ s.inputs[op].params.StartingFeeRate = fn.Some(
+ chainfee.SatPerKWeight(500),
+ )
+ set := &MockInputSet{}
+ set.On("Inputs").Return([]input.Input{inp}).Once()
+
+ err := s.handleBumpEvent(&bumpResp{
+ set: set, result: &BumpResult{
+ Event: TxFailed, Err: errDummy, FeeRate: 900,
+ },
+ })
+ require.NoError(t, err)
+ require.Equal(
+ t, fn.Some(chainfee.SatPerKWeight(900)),
+ s.inputs[op].params.StartingFeeRate,
+ )
+ set.AssertExpectations(t)
+}
### sweep/sweeper.go
@@ -974,7 +974,7 @@ func (s *UtxoSweeper) markInputsPublished(tr *TxRecord, set InputSet) error {
// markInputsPublishFailed marks the list of inputs as failed to be published.
func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
- feeRate chainfee.SatPerKWeight) {
+ feeRate fn.Option[fn.Option[chainfee.SatPerKWeight]]) {
// Reschedule sweep.
for _, inp := range set.Inputs() {
@@ -1003,14 +1003,14 @@ func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
// Update the input's state.
pi.state = PublishFailed
- log.Debugf("Input(%v): updating params: starting fee rate "+
- "[%v -> %v]", op, pi.params.StartingFeeRate,
- feeRate)
-
- // Update the input using the fee rate specified from the
- // BumpResult, which should be the starting fee rate to use for
- // the next sweeping attempt.
- pi.params.StartingFeeRate = fn.Some(feeRate)
+ // An absent update preserves the rate. A present update may
+ // clear it so that the next attempt uses the estimator.
+ feeRate.WhenSome(func(rate fn.Option[chainfee.SatPerKWeight]) {
+ log.Debugf("Input(%v): updating starting fee rate "+
+ "[%v -> %v]", op,
+ pi.params.StartingFeeRate, rate)
+ pi.params.StartingFeeRate = rate
+ })
}
}
@@ -1731,7 +1731,12 @@ func (s *UtxoSweeper) handleBumpEventTxFailed(resp *bumpResp) {
// the inputs specified by the set.
//
// TODO(yy): should we also remove the failed tx from db?
- s.markInputsPublishFailed(resp.set, resp.result.FeeRate)
+ feeRate := fn.Some(fn.Some(r.FeeRate))
+ switch {
+ case errors.Is(r.Err, errSpendCheckFailed):
+ feeRate = fn.None[fn.Option[chainfee.SatPerKWeight]]()
+ }
+ s.markInputsPublishFailed(resp.set, feeRate)
}
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
@@ -1982,7 +1987,7 @@ func (s *UtxoSweeper) handleUnknownSpendTx(inp *SweeperInput, tx *wire.MsgTx) {
func (s *UtxoSweeper) handleBumpEventTxUnknownSpend(r *bumpResp) {
// Mark the inputs as publish failed, which means they will be retried
// later.
- s.markInputsPublishFailed(r.set, r.result.FeeRate)
+ s.markInputsPublishFailed(r.set, fn.Some(fn.Some(r.result.FeeRate)))
// Get all the inputs that are not spent in the current sweeping tx.
spentInputs := r.result.SpentInputs
### sweep/sweeper_test.go
@@ -237,7 +237,7 @@ func TestMarkInputsPublishFailed(t *testing.T) {
// Mark the test inputs. We expect the non-exist input and the
// inputInit to be skipped, and the final input to be marked as
// published.
- s.markInputsPublishFailed(set, feeRate)
+ s.markInputsPublishFailed(set, fn.Some(fn.Some(feeRate)))
// We expect unchanged number of pending inputs.
require.Len(s.inputs, 7)Why this scored 57/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.