← Back to Pull requests

sweep: keep budget-bound fees publishable #11534

Open
ziggie1984 opened this pull request with 542 lines diff across 9 files
View on GitHub
ziggie1984 ziggie1984 commented on Nov 07, 2026 15:53 UTC
Author

Change

Keep budget-bound sweep transactions publishable at the fee boundary:

derive the maximum fee rate from the budget with explicit floor rounding, so converting it back to a fee cannot exceed the budget;
track change discarded below the dust limit separately and allow only that exact amount above the target fee budget;
retain ErrNotEnoughBudget for every other unexplained overrun.

Budget therefore caps the fee targeted by the fee function. As before, change that cannot form a standard output is added to the actual transaction fee, but it no longer causes the transaction to be rejected by the final budget sanity check.

Motivation

NewSatPerKWeight rounds to the nearest sat/kw. At the budget-derived maximum rate this can make FeeForWeight exceed the budget by a few satoshis. In addition, prepareSweepTx adds dust change to the fee. The final strict budget check rejected both transactions before mempool acceptance, and a deadline sweep could deterministically fail again on every retry.

The rounding fix is implemented as a reusable chainfee.NewSatPerKWeightFloor constructor. The dust exception carries its provenance through transaction construction instead of applying a generic dust-sized tolerance, so unrelated fee errors remain fatal to the attempt.

Testing

go test ./lnwallet/chainfee ./sweep -count=1

  • make lint-native
  • Diff: 542 lines (+476 / -66) across 9 files Reviewer: TechLateef Review duration: 19396m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.57) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 542 lines diff across 9 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.377
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    12 items
    github-actions[bot] github-actions[bot] commented on Nov 07, 2026 15:55 UTC
    Bot

    🔴 PR Severity: CRITICAL

    gh pr files | 6 files | 256 lines changed

    <details>
    <summary>🔴 <strong>Critical</strong> (3 files)</summary>

  • lnwallet/chainfee/rates.go - fee rate estimation logic used by wallet/sweep fee calculations

  • sweep/fee_bumper.go - core fee-bumping logic for sweeping outputs on-chain

  • sweep/sweeper.go - output sweeping / fund recovery logic
  • </details>

    <details>
    <summary>🟢 <strong>Low</strong> (3 files)</summary>

  • docs/release-notes/unreleased/11534.md - release notes

  • lnwallet/chainfee/rates_test.go - test-only change

  • sweep/fee_bumper_test.go - test-only change
  • </details>

    Analysis

    This PR modifies fee rate calculation (lnwallet/chainfee/rates.go) and fee-bumping/sweeping logic (sweep/fee_bumper.go, sweep/sweeper.go). Both lnwallet/ and sweep/ are CRITICAL-tier packages governing on-chain fund recovery and fee-bumping behavior, so an expert review is recommended. The change touches multiple distinct critical packages, though it remains small in scope (4 non-test files, ~105 non-test lines changed), well under the thresholds that would otherwise trigger a severity bump.

    ---
    <sub>To override, add a severity-override-{critical,high,medium,low} label.</sub>
    <!-- pr-severity-bot -->

    starius starius commented on code on Nov 08, 2026 04:15 UTC
    Code Review
    sweep/fee_bumper.go:1
    @@ -1802,10 +1827,11 @@ func prepareSweepTx(inputs []input.Input, changePkScript lnwallet.AddrWithKey,
     		// this case we'll return an error. This could happen when
     		// creating a tx that has an anchor as the only input.
     		if requiredOutput == 0 {
    -			return 0, noChange, noLocktime, ErrTxNoOutput
    +			return nil, ErrTxNoOutput
     		}

    Both cases are fixed when the set has a required output. One is left: without a required output, as in an anchor CPFP, dust change still returns ErrTxNoOutput, so a set created at its deadline fails the same way in every block.

    Example: an anchor (330 sat), budget 100,000 sat, and one 99,671 sat P2WKH UTXO, 767 wu with the change output.

    1. The floored rate is 130,378 sat/kw, and the fee is 99,999 sat.
    2. The change is 2 sat, below the 330 sat dust limit.
    3. There's no required output, so prepareSweepTx returns ErrTxNoOutput.

    It needs the spendable value to land less than the dust limit above the budget, so it's rare, but once it happens it repeats. One fix: when there's no required output, keep a change output at the dust limit and lower the fee by the difference (99,671 sat here instead of 99,999). A test with this anchor set at confTarget = 1 would cover it.

    github-actions[bot] github-actions[bot] commented on Nov 10, 2026 12:07 UTC
    Bot

    ⚠️ Severity changed: critical → low (files changed since last classification)

    🟢 PR Severity: LOW

    override label severity-override-low | 9 files | 542 lines changed

    A severity-override-low label is present on this PR, so automated classification was skipped and the severity is pinned to LOW per the override.

    Analysis

    For reference, since the last bot comment the file set changed: three files were added (lnrpc/walletrpc/walletkit.pb.go, lnrpc/walletrpc/walletkit.proto, lnrpc/walletrpc/walletkit.swagger.json), alongside the previously-flagged lnwallet/chainfee/rates.go, sweep/fee_bumper.go, and sweep/sweeper.go changes. Absent the override, this would likely classify as HIGH or CRITICAL (the PR touches sweep/ and lnwallet/, which are CRITICAL-tier packages, plus lnrpc//.proto, which are HIGH/MEDIUM-tier). Since a maintainer has explicitly overridden this to LOW, no further classification was performed.

    ---
    <sub>To override, add a severity-override-{critical,high,medium,low} label.</sub>
    <!-- pr-severity-bot -->

    Amirhosein Amirhosein commented on Nov 10, 2026 21:18 UTC
    Reviewer

    Reviewed all 4 commits at 1941871689f9377424fc4a533eb2a55e78507753 and ran the unit tests with -race:

    go test -v -race -count=1 ./lnwallet/chainfee/... ./sweep/...
    

    The floor constructor (NewSatPerKWeightFloor) in MaxFeeRateAllowed and tracking discardedDust through prepareSweepTx -> sweepTxCtx.exceedsBudget cleanly solve the boundary rejections when required outputs are present.

    One boundary question on commit 194187168 (sweep: retain dust change for outputless sweeps) in sweep/fee_bumper.go:1825-1836:

    case changeAmt < changeFloor && requiredOutput == 0:
    	feeReduction := changeFloor - changeAmt
    	if feeReduction > txFee {
    		return nil, ErrTxNoOutput
    	}
    
    	txFee -= feeReduction
    	changeAmt = changeFloor
    

    Since changeAmt = totalInput - txFee when requiredOutput == 0, feeReduction simplifies to txFee - (totalInput - changeFloor):

    1. totalInput == changeFloor (feeReduction == txFee):
    If the input value equals changeFloor (e.g. a lone 330-sat anchor input with a 330-sat P2TR changeFloor), feeReduction == txFee for any txFee <= 330. Because the check is strict (feeReduction > txFee), prepareSweepTx no longer returns ErrTxNoOutput and instead sets txFee = 0 and changeAmt = 330.
    2. totalInput - changeFloor below the relay fee floor:
    When totalInput > changeFloor by less than the minimum relay fee, clamping txFee down to totalInput - changeFloor produces a fee below mempool relay requirements. In createRBFCompliantTx, CheckMempoolAcceptance rejects it with ErrMinRelayFeeNotMet, and each retry step rebuilds the same clamped txFee = totalInput - changeFloor until the fee function reaches max fee position or txFee > totalInput hits ErrNotEnoughInputs, without ever becoming publishable.

    Would it make sense to use if feeReduction >= txFee (or check that the reduced txFee still covers the minimum relay fee floor) and add a unit test for the totalInput == changeFloor equality case?

    TechLateef TechLateef approved these changes on Nov 11, 2026 05:52 UTC
    Approved Reviewer

    Looks good overall the budget boundary is pinned from both sides
    in the tests.

    One note, pre-existing and not related to this PR: the comment in
    TestCreateAndCheckTxAtBudgetBoundary mentions that the aux
    sweeper's extra output isn't counted in MaxFeeRateAllowed's
    weight estimate, so a derived rate can overshoot the budget by
    that output's weight. The budget check still catches it
    (ErrNotEnoughBudget -> retry next block, no overspend
    broadcasts), but it may be worth a TODO(issue) so the limitation
    doesn't just live in a test comment. No change needed here.

    litbot-9000 litbot-9000 commented on Nov 18, 2026 06:27 UTC
    Contributor

    @starius: review reminder
    @ziggie1984, remember to re-request review from reviewers when ready

    MPins MPins commented on Nov 18, 2026 19:00 UTC
    Contributor

    Reviewed all 4 commits at 1941871689f9377424fc4a533eb2a55e78507753 and ran the unit tests with -race:

    >
    > go test -v -race -count=1 ./lnwallet/chainfee/... ./sweep/...
    > 

    > The floor constructor (NewSatPerKWeightFloor) in MaxFeeRateAllowed and tracking discardedDust through prepareSweepTx -> sweepTxCtx.exceedsBudget cleanly solve the boundary rejections when required outputs are present.

    > One boundary question on commit 194187168 (sweep: retain dust change for outputless sweeps) in sweep/fee_bumper.go:1825-1836:

    >
    > case changeAmt < changeFloor && requiredOutput == 0:
    > 	feeReduction := changeFloor - changeAmt
    > 	if feeReduction > txFee {
    > 		return nil, ErrTxNoOutput
    > 	}
    > 
    > 	txFee -= feeReduction
    > 	changeAmt = changeFloor
    > 

    > Since changeAmt = totalInput - txFee when requiredOutput == 0, feeReduction simplifies to txFee - (totalInput - changeFloor):

    > 1. totalInput == changeFloor (feeReduction == txFee):

    If the input value equals changeFloor (e.g. a lone 330-sat anchor input with a 330-sat P2TR changeFloor), feeReduction == txFee for any txFee <= 330. Because the check is strict (feeReduction > txFee), prepareSweepTx no longer returns ErrTxNoOutput and instead sets txFee = 0 and changeAmt = 330.

    > 2. totalInput - changeFloor below the relay fee floor:

    When totalInput > changeFloor by less than the minimum relay fee, clamping txFee down to totalInput - changeFloor produces a fee below mempool relay requirements. In createRBFCompliantTx, CheckMempoolAcceptance rejects it with ErrMinRelayFeeNotMet, and each retry step rebuilds the same clamped txFee = totalInput - changeFloor until the fee function reaches max fee position or txFee > totalInput hits ErrNotEnoughInputs, without ever becoming publishable.

    >

    Would it make sense to use if feeReduction >= txFee (or check that the reduced txFee still covers the minimum relay fee floor) and add a unit test for the totalInput == changeFloor equality case?

    Confirmed both edges with a throwaway test against prepareSweepTx, and they look reachable in practice: the anchor resolver offers a lone anchor with budget 330 after the commitment confirms, so no wallet inputs get added. At every rate from 253 up to the budget max:

    P2TR change (floor 330): fee = 0, the equality case.
    P2WPKH change (floor 294): fee = 36 sat (81 sat/kw).

    The second one suggests >= alone wouldn't be enough: there feeReduction is still below txFee, so the check doesn't fire and the tx goes out with 36 sat. The min relay check seems like the option that covers both.

    +1 on the test too: as an experiment I changed the check to >= locally, and the whole sweep package still passes, so nothing pins the equality case today.

    MPins MPins commented on code on Nov 18, 2026 20:09 UTC
    Code Review
    lnwallet/chainfee/rates.go:1
    @@ -70,6 +70,19 @@ func NewSatPerKWeight(fee btcutil.Amount, wu lntypes.WeightUnit) SatPerKWeight {
     	return SatPerKWeight(fee.MulF64(1000 / float64(wu)))
     }
     
    +// NewSatPerKWeightFloor creates a new fee rate in sat/kw, rounding down to
    +// ensure that converting the rate back to a fee never exceeds fee. A zero
    +// weight yields a zero fee rate.
    +func NewSatPerKWeightFloor(fee btcutil.Amount,
    +	wu lntypes.WeightUnit) SatPerKWeight {
    +
    +	if wu == 0 {
    +		return 0
    +	}
    +
    +	return SatPerKWeight(fee * 1000 / btcutil.Amount(wu))

    nit: fee * 1000 can wrap in int64 for a budget above ~9.22e15 sat (only reachable with an absurd RPC budget, and the resulting tx is just invalid). Capping at btcutil.MaxSatoshi would rule it out, if you think it's worth it.

    MPins MPins commented on code on Nov 18, 2026 20:48 UTC
    Code Review
    sweep/fee_bumper.go:1
    @@ -1790,26 +1817,36 @@ func prepareSweepTx(inputs []input.Input, changePkScript lnwallet.AddrWithKey,
     		len(changePkScript.DeliveryAddress),
     	)
     
    +	addChangeOutput := true
     	switch {
    -	// If the change amount is dust, we'll move it into the fees, and
    -	// ignore it.
    +	// If there is no required output, discarding dust change would leave
    +	// the transaction without any outputs. Reduce the fee just enough to
    +	// create a standard change output instead.
    +	case changeAmt < changeFloor && requiredOutput == 0:
    +		feeReduction := changeFloor - changeAmt
    +		if feeReduction > txFee {
    +			return nil, ErrTxNoOutput
    +		}
    +
    +		log.Infof("Change amt %v below dustlimit %v, reducing fee "+
    +			"by %v to retain the change output", changeAmt,
    +			changeFloor, feeReduction)
    +
    +		txFee -= feeReduction
    +		changeAmt = changeFloor
    +
    +	// If the change amount is dust and another output remains, move the
    +	// change into the fee and omit the change output.

    A small observation on this branch, separate from what @Amirhosein already raised. Once the change hits changeFloor, the actual fee stays pinned at totalInput - changeFloor, no matter how much higher the fee rate goes. So from that point:

  • each RBF attempt pays the same absolute fee (only the locktime changes), so it ends in ErrInsufficientFee and handleReplacementTxError returns None every block;

  • BumpResult.FeeRate still reports the nominal f.FeeRate(), which also feeds lastFeeRate/StartingFeeRate, while Fee reports what was actually paid.
  • That's fund-safe, since there's nothing more to pay with a single output, and it's strictly better than the previous ErrTxNoOutput. A short comment noting that the bump saturates here would help, and reporting the effective rate might avoid confusing PendingSweeps output. What do you think?

    MPins MPins commented on code on Nov 18, 2026 20:58 UTC
    Code Review
    sweep/fee_bumper_test.go:1
    @@ -519,6 +569,182 @@ func TestCreateAndCheckTx(t *testing.T) {
     	}
     }
     
    +// TestCreateAndCheckTxAtBudgetBoundary checks that a sweep tx created at the
    +// budget-derived max fee rate passes the budget check, even when the tx's
    +// change is below the dust limit and is added to the fee. Before the fix, the
    +// max fee rate was rounded to the nearest sat/kw, so the target fee could
    +// exceed the budget, and discarded dust always pushed the final fee above it.
    +// Both made the tx fail the budget check on every attempt.
    +func TestCreateAndCheckTxAtBudgetBoundary(t *testing.T) {
    +	t.Parallel()
    +
    +	const (
    +		// numWalletInputs is the number of P2WKH inputs without a
    +		// required output. Together with the input below, they give
    +		// a tx weight of 2522 wu, which is large enough for a
    +		// rounded-up fee rate to overshoot the budget.
    +		numWalletInputs  = 7
    +		walletInputValue = 10_000
    +
    +		// budget is chosen so that the budget-derived fee rate,
    +		// rounded to the nearest sat/kw, gives a fee above it.
    +		budget = btcutil.Amount(100_024)
    +
    +		// dust is the change left over after paying the target fee,
    +		// which is below the dust limit of the change script.
    +		dust = btcutil.Amount(100)
    +	)
    +
    +	tp, m := createTestPublisher(t)
    +
    +	// The aux sweeper's extra output isn't accounted for when deriving
    +	// the max fee rate from the budget, so remove it to keep the tx
    +	// weight the same in both places.
    +	tp.cfg.AuxSweeper = fn.None[AuxSweeper]()
    +
    +	// Create an input with a required output, so that the tx still has an
    +	// output after the dust change is discarded.
    +	requiredOutput := &wire.TxOut{
    +		Value:    10_000,
    +		PkScript: make([]byte, input.P2WPKHSize),
    +	}
    +	requiredInput := &input.MockInput{}
    +	defer requiredInput.AssertExpectations(t)
    +
    +	requiredInput.On("WitnessType").Return(input.WitnessKeyHash)
    +	requiredInput.On("RequiredTxOut").Return(requiredOutput)
    +	requiredInput.On("RequiredLockTime").Return(uint32(0), false)
    +	requiredInput.On("UnconfParent").Return(nil)
    +	requiredInput.On("ResolutionBlob").Return(fn.None[tlv.Blob]())
    +	requiredInput.On("OutPoint").Return(wire.OutPoint{Index: 1})
    +	requiredInput.On("BlocksToMaturity").Return(uint32(0))
    +	requiredInput.On("CraftInputScript", mock.Anything, mock.Anything,
    +		mock.Anything, mock.Anything, mock.Anything,
    +	).Return(&input.Script{}, nil)
    +
    +	inputs := []input.Input{requiredInput}
    +	for range numWalletInputs {
    +		inp := createTestInput(walletInputValue, input.WitnessKeyHash)
    +		inputs = append(inputs, &inp)
    +	}
    +
    +	req := &BumpRequest{
    +		DeliveryAddress: changePkScript,
    +		Inputs:          inputs,
    +		Budget:          budget,
    +		MaxFeeRate:      chainfee.SatPerKWeight(1_000_000),
    +	}
    +
    +	// The budget, not the MaxFeeRate, bounds the max fee rate.
    +	maxFeeRate, err := req.MaxFeeRateAllowed()
    +	require.NoError(t, err)
    +
    +	weight, err := calcSweepTxWeight(
    +		inputs, [][]byte{changePkScript.DeliveryAddress},
    +	)
    +	require.NoError(t, err)
    +	require.EqualValues(t, 2522, weight)
    +
    +	// Rounding the budget-derived fee rate to the nearest sat/kw would
    +	// give a fee above the budget, while the floored rate doesn't.
    +	roundedRate := chainfee.NewSatPerKWeight(budget, weight)
    +	require.Greater(t, roundedRate.FeeForWeight(weight), budget)
    +
    +	targetFee := maxFeeRate.FeeForWeight(weight)
    +	require.LessOrEqual(t, targetFee, budget)
    +
    +	// The discarded dust takes the final fee above the budget.
    +	require.Greater(t, targetFee+dust, budget)
    +	require.Less(t, dust, lnwallet.DustLimitForSize(
    +		len(changePkScript.DeliveryAddress),
    +	))
    +
    +	// Fund the required input so that exactly the dust is left over after
    +	// the required output, the target fee and the wallet inputs.
    +	walletTotal := btcutil.Amount(numWalletInputs * walletInputValue)
    +	requiredValue := btcutil.Amount(requiredOutput.Value) + targetFee +
    +		dust - walletTotal
    +	requiredInput.On("SignDesc").Return(&input.SignDescriptor{
    +		Output: &wire.TxOut{Value: int64(requiredValue)},
    +	})
    +
    +	// The fee function has reached its ending fee rate, which is the max
    +	// fee rate allowed by the budget.
    +	m.feeFunc.On("FeeRate").Return(maxFeeRate)
    +	m.signer.On("ComputeInputScript", mock.Anything,
    +		mock.Anything).Return(&input.Script{}, nil)
    +	m.wallet.On("CheckMempoolAcceptance", mock.Anything).Return(nil).Once()
    +
    +	r := &monitorRecord{
    +		req:         req,
    +		feeFunction: m.feeFunc,
    +	}
    +
    +	sweepCtx, err := tp.createAndCheckTx(r)
    +	require.NoError(t, err)
    +
    +	// The dust is added to the fee, and the tx only has the required
    +	// output.
    +	require.Equal(t, targetFee+dust, sweepCtx.fee)
    +	require.Equal(t, dust, sweepCtx.discardedDust)
    +	require.Len(t, sweepCtx.tx.TxOut, 1)
    +}
    +
    +// TestPrepareSweepTxAtBudgetBoundaryWithoutRequiredOutput checks that an
    +// anchor CPFP at its budget-derived maximum fee rate remains publishable when
    +// its change would otherwise be dust. Since there is no required output, the
    +// fee must be reduced just enough to retain a standard change output.
    +func TestPrepareSweepTxAtBudgetBoundaryWithoutRequiredOutput(t *testing.T) {

    nit: this test also passes if MaxFeeRateAllowed goes back to the old rounding NewSatPerKWeight: 100,000 sat * 1000 / 767 wu = 130,378.09 sat/kw, which rounds and floors to the same value. So only TestCreateAndCheckTxAtBudgetBoundary would catch a regression of the floor. If this test is also meant to guard it, a weight where the fraction is >= .5 would make the old rounding fail here.

    MPins MPins commented on Nov 18, 2026 21:07 UTC
    Reviewer

    Reviewed at 1941871689 and ran the chainfee and sweep unit tests. The floor conversion and the discardedDust accounting look right to me, and the overshoot over the budget stays bounded by the discarded dust. Left a note on the outputless branch, where the fee stops growing once the change hits changeFloor, and a +1 with some numbers on Amirhosein's min relay edge.

    Reviewers
    Assignees
    ziggie1984 ziggie1984
    Labels
    risk: low confidence: 91.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 57.4% (MEDIUM) · Higher = larger blast radius
    57.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 91.7% · Lower = rushed or shallow review
    91.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.8% · Safe to merge
    4.8%