Skip to content

sweep: keep budget-bound fees publishable - #11534

Open
ziggie1984 wants to merge 4 commits into
lightningnetwork:masterfrom
ziggie1984:fix-sweep-budget-boundary
Open

ziggie1984 wants to merge 4 commits into
lightningnetwork:masterfrom
ziggie1984:fix-sweep-budget-boundary

Conversation

@ziggie1984

Copy link
Copy Markdown
Collaborator

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

@github-actions github-actions Bot added ci-hold CI is held; remove this label to run CI severity-critical Requires expert review - security/consensus critical labels Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

🔴 PR Severity: CRITICAL

gh pr files | 6 files | 256 lines changed

🔴 Critical (3 files)
  • 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
🟢 Low (3 files)
  • docs/release-notes/unreleased/11534.md - release notes
  • lnwallet/chainfee/rates_test.go - test-only change
  • sweep/fee_bumper_test.go - test-only change

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.


To override, add a severity-override-{critical,high,medium,low} label.

@ziggie1984
ziggie1984 requested a review from starius November 7, 2026 17:25
@ziggie1984 ziggie1984 removed the ci-hold CI is held; remove this label to run CI label Nov 7, 2026
@ziggie1984
ziggie1984 force-pushed the fix-sweep-budget-boundary branch from fe5a2fe to 52cc319 Compare November 7, 2026 17:48
@ziggie1984 ziggie1984 added the severity-override-low Manual override to low label Nov 7, 2026
Comment thread sweep/fee_bumper.go Outdated
Comment on lines 1829 to 1831
if requiredOutput == 0 {
return 0, noChange, noLocktime, ErrTxNoOutput
return nil, ErrTxNoOutput
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 github-actions Bot added severity-low Best-effort review and removed severity-critical Requires expert review - security/consensus critical labels Nov 10, 2026
@github-actions

Copy link
Copy Markdown

⚠️ 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.


To override, add a severity-override-{critical,high,medium,low} label.

@ziggie1984
ziggie1984 requested a review from starius November 10, 2026 12:24

@Amirhosein Amirhosein left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@ziggie1984 ziggie1984 self-assigned this Nov 11, 2026

@TechLateef TechLateef left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

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

@MPins

MPins commented Nov 18, 2026

Copy link
Copy Markdown
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 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

return 0
}

return SatPerKWeight(fee * 1000 / btcutil.Amount(wu))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread sweep/fee_bumper.go
Comment on lines +1822 to +1839
// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread sweep/fee_bumper_test.go
// 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

severity-low Best-effort review severity-override-low Manual override to low

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants