funding: bound the commit fee rate an initiator can impose on us
What changed, and why it matters
This change prevents a remote user from opening a Lightning channel with an outrageously high on-chain fee. Before the patch, an initiator could set a commitment fee so large that most of the channel's money would be eaten by fees, leaving a channel that is effectively unusable and must be closed on the blockchain. The patch caps the fee a remote peer can impose at ten times LND's own fee estimate, with a hard floor of 100 sat/vbyte, and rejects the channel if the proposed fee exceeds that cap.
This is a defensive hardening patch. Operators should upgrade to a release containing this commit. No configuration change is required; the bound is automatic.
Security signals we found
Adds BOLT-02 required rejection of unreasonably large feerate_per_kw
Caps remote-imposed commitment fee rate at 10x local estimate with 100 sat/vbyte floor
Uses a sentinel error to avoid text-based error matching
Includes regression tests for multiplier, floor, estimator failure, and interaction with reserve check
Evidence from the diff
The commit adds BOLT-02 enforcement in the fundee path: after cheap admission checks, fundeeProcessOpenChannel calls checkCommitFeeRate, which compares the OpenChannel FeePerKiloWeight against maxRemoteCommitFeeRate. That bound is max(10 * EstimateFeePerKW(3), 100 sat/vbyte). If the estimator fails, the static 100 sat/vbyte floor is used. A new sentinel error, ErrCommitFeeRateTooLargeBase, lets the funding manager identify the rejection without parsing the peer-facing message. Tests verify the multiplier, the floor fallback, estimator-error fallback, and that the new check does not mask the existing balances-below-reserve check.
Changed components
funding/manager.gofunding/manager_test.golnwallet/errors.goInspect captured patch +491 / −4
### funding/manager.go
@@ -108,8 +108,33 @@ const (
// can have. After this point, pending channel opens will start to be
// rejected.
pendingChansLimit = 50
+
+ // commitFeeConfTarget is the conf target we use when we need a fee
+ // rate for a commitment transaction. We target the near blocks so
+ // that we can execute a timely unilateral close if needed. It is
+ // shared by the outbound fee we pay and the bound we place on the
+ // fee rate an inbound initiator may impose, so the two can't drift
+ // apart; see maxRemoteCommitFeeRate.
+ commitFeeConfTarget = 3
+
+ // maxCommitFeeRateMultiplier is the multiple of our own commitment fee
+ // rate estimate that we'll tolerate as the initial fee rate of a
+ // channel opened by a remote peer. BOLT-02 requires that we fail a
+ // channel whose feerate_per_kw we consider "unreasonably large", but
+ // leaves the threshold up to each implementation. Both CLN and Eclair
+ // settle on 10x their own estimate, so we do the same.
+ maxCommitFeeRateMultiplier = 10
)
+// minCommitFeeRateCap is the floor we place on the maximum commitment fee rate
+// we'll accept from a channel initiator. Our fee estimator can report a very
+// low rate on a quiet chain, or fall back to the relay fee entirely, and we
+// don't want that to make us reject a channel opened at a rate that's high
+// relative to our estimate yet perfectly sane in absolute terms. At 100
+// sat/vbyte a commitment transaction confirms under any realistic mempool
+// condition, so we never treat anything at or below it as unreasonable.
+var minCommitFeeRateCap = chainfee.SatPerKVByte(100 * 1000).FeePerKWeight()
+
var (
// ErrFundingManagerShuttingDown is an error returned when attempting to
// process a funding request/message but the funding manager has already
@@ -1431,6 +1456,62 @@ func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
}
}
+// maxRemoteCommitFeeRate returns the highest commitment fee rate we're willing
+// to accept from the initiator of an inbound channel. The bound scales with our
+// own view of the current network fee rate, but never drops below
+// minCommitFeeRateCap, so a low or stale estimate can't make us turn away
+// channels opened at an absolutely reasonable rate.
+func (f *Manager) maxRemoteCommitFeeRate() chainfee.SatPerKWeight {
+ // We use the same conf target we'd use for a channel we open
+ // ourselves, so that the bound tracks the rate we consider necessary
+ // for a timely unilateral close.
+ ourFeeRate, err := f.cfg.FeeEstimator.EstimateFeePerKW(
+ commitFeeConfTarget,
+ )
+ if err != nil {
+ // A fee estimate isn't essential here: without one we simply
+ // fall back to the absolute bound rather than failing an
+ // otherwise valid channel.
+ log.Warnf("Unable to estimate commitment fee rate, using "+
+ "static bound of %v: %v", minCommitFeeRateCap, err)
+
+ return minCommitFeeRateCap
+ }
+
+ maxFeeRate := ourFeeRate * maxCommitFeeRateMultiplier
+ if maxFeeRate < minCommitFeeRateCap {
+ return minCommitFeeRateCap
+ }
+
+ return maxFeeRate
+}
+
+// checkCommitFeeRate fails the funding flow if the commitment fee rate the
+// initiator proposed in open_channel is above the bound we derive from our
+// own fee estimate, as BOLT-02 requires. It reports whether the flow was
+// failed, and so whether the caller must return.
+//
+// The bound is consulted only after the caller's cheap admission checks have
+// passed, so a peer that is over its pending-channel limit can't drive fee
+// estimation work on the funding goroutine.
+func (f *Manager) checkCommitFeeRate(peer lnpeer.Peer, cid *chanIdentifier,
+ msg *lnwire.OpenChannel) bool {
+
+ commitFeeRate := chainfee.SatPerKWeight(msg.FeePerKiloWeight)
+ maxCommitFeeRate := f.maxRemoteCommitFeeRate()
+ if commitFeeRate <= maxCommitFeeRate {
+ return false
+ }
+
+ f.failFundingFlow(
+ peer, cid, lnwallet.ErrCommitFeeRateTooLarge(
+ commitFeeRate, maxCommitFeeRate,
+ ),
+ )
+
+ return true
+}
+
// fundeeProcessOpenChannel creates an initial 'ChannelReservation' within the
// wallet, then responds to the source peer with an accept channel message
// progressing the funding workflow.
@@ -1556,6 +1637,14 @@ func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
return
}
+ // Enforce BOLT-02: the receiver MUST fail the channel if it considers
+ // feerate_per_kw unreasonably large. The initiator pays the commitment
+ // fee out of its own balance, so an absurd rate burns most of the
+ // channel capacity before either party can use it.
+ if f.checkCommitFeeRate(peer, cid, msg) {
+ return
+ }
+
// We'll also reject any requests to create channels until we're fully
// synced to the network as we won't be able to properly validate the
// confirmation of the funding transaction.
@@ -5032,10 +5121,12 @@ func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
}
// First, we'll query the fee estimator for a fee that should get the
- // commitment transaction confirmed by the next few blocks (conf target
- // of 3). We target the near blocks here to ensure that we'll be able
- // to execute a timely unilateral channel closure if needed.
- commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
+ // commitment transaction confirmed by the next few blocks. We target
+ // the near blocks here to ensure that we'll be able to execute a
+ // timely unilateral channel closure if needed.
+ commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(
+ commitFeeConfTarget,
+ )
if err != nil {
msg.Err <- err
return
### funding/manager_test.go
@@ -4226,6 +4226,383 @@ func TestFundingManagerPushAmountAtCapacity(t *testing.T) {
}
}
+// feeEstimatorStub is a chainfee.Estimator whose single fee estimate is set
+// per test, including the error case a real estimator reports when it has no
+// data. The embedding keeps the two methods the funding manager never calls
+// from having to be defined here.
+type feeEstimatorStub struct {
+ chainfee.Estimator
+
+ feeRate chainfee.SatPerKWeight
+ err error
+}
+
+// EstimateFeePerKW returns the rate configured on the stub, or its
+// error.
+func (f feeEstimatorStub) EstimateFeePerKW(
+ confTarget uint32,
+) (chainfee.SatPerKWeight, error) {
+
+ return f.feeRate, f.err
+}
+
+// anchorOpenChannel builds a complete, valid OpenChannel that proposes
+// the given feerate, funding amount, and reserve. It is a helper for the
+// tests below so the deeply nested struct literal can sit at a level of
+// indentation the 80-column limit can accommodate.
+func anchorOpenChannel(
+ feeRate chainfee.SatPerKWeight,
+ fundingAmt btcutil.Amount,
+ reserve btcutil.Amount,
+ channelType *lnwire.ChannelType,
+) *lnwire.OpenChannel {
+
+ return &lnwire.OpenChannel{
+ ChainHash: *fundingNetParams.GenesisHash,
+ PendingChannelID: [32]byte{0x01},
+ FundingAmount: fundingAmt,
+ DustLimit: 573,
+ MaxValueInFlight: lnwire.NewMSatFromSatoshis(
+ fundingAmt,
+ ),
+ ChannelReserve: reserve,
+ CsvDelay: 4,
+ // The BOLT-02 limit on accepted HTLCs.
+ MaxAcceptedHTLCs: 483,
+ FundingKey: alicePrivKey.PubKey(),
+ RevocationPoint: alicePrivKey.PubKey(),
+ PaymentPoint: alicePrivKey.PubKey(),
+ DelayedPaymentPoint: alicePrivKey.PubKey(),
+ HtlcPoint: alicePrivKey.PubKey(),
+ FirstCommitmentPoint: alicePrivKey.PubKey(),
+ ChannelType: channelType,
+ FeePerKiloWeight: uint32(feeRate),
+ }
+}
+
+// TestFundingManagerCommitFeeRateTooLarge asserts that the bound we place on
+// the feerate_per_kw an inbound initiator may propose is the one we intend, and
+// that the fundee enforces it: a rate above the bound is rejected, and a rate
+// exactly at it is accepted.
+//
+// The bound is derived from a stub estimator, and the expected bounds are
+// written out in the table rather than read back from the funding manager, so
+// that a wrong multiplier, a missing floor, or a changed fallback fails the
+// test instead of redefining what is expected.
+func TestFundingManagerCommitFeeRateTooLarge(t *testing.T) {
+ t.Parallel()
+
+ // The bounds are written as literals rather than derived from
+ // maxCommitFeeRateMultiplier and minCommitFeeRateCap, because a test
+ // that computes its expectation from the constant under test passes for
+ // any value that constant happens to hold.
+ const (
+ // The floor is 100 sat/vbyte, which is 25000 sat/kw, and is
+ // what the bound falls back to on a low estimate or an
+ // estimator error.
+ floorBound = chainfee.SatPerKWeight(25000)
+
+ // The estimate the 10x case scales from, chosen so that the
+ // bound lands well above the floor: 62500 * 10 is 625000
+ // sat/kw.
+ highEstimate = chainfee.SatPerKWeight(62500)
+ tenTimesEstimate = chainfee.SatPerKWeight(625000)
+ )
+
+ // The floor is 100 sat/vbyte, as the table below assumes.
+ require.Equal(t, floorBound, minCommitFeeRateCap,
+ "minCommitFeeRateCap must be 100 sat/vbyte")
+ require.Equal(t, tenTimesEstimate, highEstimate*10,
+ "62500 sat/kw scaled by ten is 625000 sat/kw")
+
+ tests := []struct {
+ name string
+
+ // estimator describes what our own fee estimator reports.
+ feeRate chainfee.SatPerKWeight
+ err error
+
+ // expectedBound is the highest rate the fundee must accept.
+ expectedBound chainfee.SatPerKWeight
+ }{
+ {
+ // The bound scales with our own estimate, which is
+ // what keeps it tracking the current chain.
+ name: "ten times our estimate",
+ feeRate: highEstimate,
+ expectedBound: tenTimesEstimate,
+ },
+ {
+ // A quiet chain can leave the estimate very low, and
+ // 10x of a very small number is still a very small
+ // number. The floor keeps us from turning away a
+ // channel that is sane in absolute terms.
+ name: "low estimate falls back to the floor",
+ feeRate: 1000,
+ expectedBound: floorBound,
+ },
+ {
+ // A transient estimator failure must not fail an
+ // otherwise valid channel, so the floor stands in.
+ name: "estimator error falls back to the floor",
+ err: errors.New("estimator unavailable"),
+
+ expectedBound: floorBound,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ estimator := feeEstimatorStub{
+ feeRate: test.feeRate,
+ err: test.err,
+ }
+ alice, bob := setupFundingManagers(
+ t, func(cfg *Config) {
+ cfg.FeeEstimator = estimator
+ },
+ )
+ t.Cleanup(func() {
+ tearDownFundingManagers(t, alice, bob)
+ })
+
+ // Both peers advertise anchors with zero-fee HTLCs and
+ // static remote keys, which settles the channel type
+ // without taproot or scid-alias bits interfering.
+ featureBits := []lnwire.FeatureBit{
+ lnwire.AnchorsZeroFeeHtlcTxOptional,
+ lnwire.StaticRemoteKeyOptional,
+ lnwire.ExplicitChannelTypeOptional,
+ }
+ alice.localFeatures = featureBits
+ alice.remoteFeatures = featureBits
+ bob.localFeatures = featureBits
+ bob.remoteFeatures = featureBits
+
+ // The initiator proposes the anchor channel type
+ // explicitly.
+ channelType := lnwire.ChannelType(
+ *lnwire.NewRawFeatureVector(
+ lnwire.StaticRemoteKeyRequired,
+ lnwire.AnchorsZeroFeeHtlcTxRequired,
+ ),
+ )
+
+ // The channel has to afford the rate at the bound: the
+ // initiator pays the commitment fee out of its own
+ // balance, and a channel that cannot pay it is rejected
+ // for that reason before any feerate is considered. At
+ // 625000 sat/kw the 1124-weight anchor commitment costs
+ // 702500 sat, and its two anchor outputs add 660 sat,
+ // so the channel is sized to leave the initiator well
+ // of the two-times-dust guard and of the reserve it
+ // names, even at the highest bound in the table.
+ const fundingAmt = btcutil.Amount(10000000)
+
+ // The reserve the initiator names, near the 1% BOLT-02
+ // suggests.
+ const initiatorReserve = fundingAmt / 100
+
+ // newOpenChanMsg builds the OpenChannel the
+ // initiator sends, with feerate_per_kw overridden.
+ // Every other field is a complete, valid open,
+ // built by the helper above, so the positive case
+ // below cannot pass on a later failure.
+ newOpenChanMsg := func(
+ feeRate chainfee.SatPerKWeight,
+ ) *lnwire.OpenChannel {
+
+ return anchorOpenChannel(
+ feeRate, fundingAmt, initiatorReserve,
+ &channelType,
+ )
+ }
+
+ // One satoshi per kw above the expected bound must be
+ // rejected with the spec-aligned error.
+ tooLarge := test.expectedBound + 1
+ bob.fundingMgr.ProcessFundingMsg(
+ newOpenChanMsg(tooLarge), alice,
+ )
+ msg := assertFundingMsgSent(t, bob.msgChan, "Error")
+ errMsg, ok := msg.(*lnwire.Error)
+ require.True(t, ok,
+ "expected *lnwire.Error, got %T", msg)
+
+ // The message carries the exact bound we expect,
+ // and its text is derived from the same constructor
+ // the daemon uses, so this pins the rate and the bound
+ // reported as well as the wording the remote peer
+ // sees.
+ expected := lnwallet.ErrCommitFeeRateTooLarge(
+ tooLarge, test.expectedBound,
+ )
+ require.Equal(t, expected.Error(), string(errMsg.Data))
+
+ // The error the daemon builds is the one this test
+ // claims to be pinning: it must be identifiable by
+ // the sentinel rather than only by its text.
+ require.ErrorIs(t, expected,
+ lnwallet.ErrCommitFeeRateTooLargeBase,
+ )
+
+ // The bound itself is acceptable: Bob must answer with
+ // an AcceptChannel, which proves the channel is not
+ // refused over its feerate. An unrelated error, or no
+ // answer at all, fails here rather than passing.
+ bob.fundingMgr.ProcessFundingMsg(
+ newOpenChanMsg(test.expectedBound), alice,
+ )
+
+ accept := assertFundingMsgSent(
+ t, bob.msgChan, "AcceptChannel",
+ )
+ _, ok = accept.(*lnwire.AcceptChannel)
+ require.True(t, ok, "expected *lnwire.AcceptChannel, "+
+ "got %T", accept)
+ })
+ }
+}
+
+// TestFundingManagerBalancesBelowReserve asserts that the fundee rejects an
+// incoming OpenChannel when neither party would hold more than the reserve the
+// initiator named in open_channel. That is the BOLT-02 condition that makes a
+// channel unusable: neither side could add an HTLC without dipping below its
+// reserve.
+//
+// The check compares both balances against the reserve from open_channel, not
+// against the reserve we name in accept_channel. The two are made to differ
+// here, ours the lower of the two, so a regression to comparing each balance
+// against its own reserve would accept a channel the spec requires us to
+// reject.
+//
+// Reaching that band at all takes a small channel carrying a large commitment
+// fee: the initiator's reserve must be within a fifth of capacity, since
+// VerifyConstraints caps it there, so the initiator's balance has to fall below
+// a fifth of capacity while staying above the two-times-dust guard. A high
+// feerate on a small channel is exactly that case, and it is the case the
+// feerate cap must not be allowed to mask.
+func TestFundingManagerBalancesBelowReserve(t *testing.T) {
+ t.Parallel()
+
+ // A static estimator makes the commitment fee, and so the initiator's
+ // initial balance, a fixed number this test can reason about. The fee
+ // is computed from the weight of the anchor commitment rather than
+ // hardcoded, so a change to the commitment format fails an assertion
+ // here instead of silently moving the balances.
+ const commitFeeRate = chainfee.SatPerKWeight(45000)
+
+ // The commitment fee is rounded down, as BOLT#03 specifies.
+ commitFee := commitFeeRate.FeeForWeight(input.AnchorCommitWeight)
+
+ alice, bob := setupFundingManagers(t, func(cfg *Config) {
+ cfg.FeeEstimator = chainfee.NewStaticEstimator(commitFeeRate, 0)
+
+ // An anchor channel's own commitment feerate is capped at this
+ // value, and the message carries whatever survives the cap. It
+ // has to be at least the rate we want to open at, or the
+ // initiator opens at a lower rate than this test computes.
+ cfg.MaxAnchorsCommitFeeRate = commitFeeRate
+ })
+ t.Cleanup(func() {
+ tearDownFundingManagers(t, alice, bob)
+ })
+
+ // The channel type is negotiated from the peers' feature bits alone,
+ // so both sides have to advertise anchors with zero-fee HTLCs. That is
+ // also the smallest commitment for a given feerate, which keeps the
+ // commitment fee below the initiator's balance.
+ featureBits := []lnwire.FeatureBit{
+ lnwire.StaticRemoteKeyOptional,
+ lnwire.AnchorsZeroFeeHtlcTxOptional,
+ }
+ alice.localFeatures = featureBits
+ alice.remoteFeatures = featureBits
+ bob.localFeatures = featureBits
+ bob.remoteFeatures = featureBits
+
+ const capacity = btcutil.Amount(60000)
+
+ // The initiator pushes a small amount to the fundee, so that neither
+ // balance clears its reserve.
+ const pushAmt = btcutil.Amount(900)
+
+ // The two anchor outputs are paid out of the initiator's balance on top
+ // of the commitment fee, and the push comes out of it as well.
+ initiatorBalance := capacity - commitFee -
+ lnwallet.AnchorSize*2 - pushAmt
+ fundeeBalance := pushAmt
+
+ // The reserve the initiator names in open_channel, which must clear
+ // both balances without exceeding the fifth of capacity that
+ // VerifyConstraints allows.
+ initiatorReserve := btcutil.Amount(9000)
+
+ // The reserve we name in accept_channel, below the initiator's, so
+ // that comparing each balance against its own reserve would accept
+ // this channel. Bob's default reserve for a 60000 sat channel is his
+ // dust limit, well below this.
+ const acceptReserve = btcutil.Amount(600)
+
+ // Both balances must sit at or below the initiator's reserve for the
+ // check to fire, above the two-times-dust guard so that the earlier
+ // funder-balance-dust check in NewChannelReservation cannot fire
+ // first, and below the cap VerifyConstraints places on the reserve.
+ require.LessOrEqual(t, int64(initiatorBalance), int64(initiatorReserve))
+ require.LessOrEqual(t, int64(fundeeBalance), int64(initiatorReserve))
+ require.Greater(t, int64(fundeeBalance),
+ 2*int64(lnwallet.DustLimitUnknownWitness()))
+ require.Less(t, int64(initiatorReserve), int64(capacity/5)+1)
+
+ updateChan := make(chan *lnrpc.OpenStatusUpdate)
+ errChan := make(chan error, 1)
+ initReq := &InitFundingMsg{
+ Peer: bob,
+ TargetPubkey: bob.privKey.PubKey(),
+ ChainHash: *fundingNetParams.GenesisHash,
+ LocalFundingAmt: capacity,
+ PushAmt: lnwire.NewMSatFromSatoshis(pushAmt),
+ RemoteChanReserve: initiatorReserve,
+ Private: true,
+ Updates: updateChan,
+ Err: errChan,
+ }
+ alice.fundingMgr.InitFundingWorkflow(initReq)
+
+ // The open_channel must carry the reserve we asked for, so that the
+ // comparison this test is about is the one being made.
+ aliceMsg := assertFundingMsgSent(t, alice.msgChan, "OpenChannel")
+ openChanMsg, ok := aliceMsg.(*lnwire.OpenChannel)
+ require.True(t, ok, "expected *lnwire.OpenChannel, got %T", aliceMsg)
+ require.EqualValues(t, initiatorReserve, openChanMsg.ChannelReserve)
+
+ // The feerate cap must not be what rejects this channel, or the
+ // reserve check would be masked. Bob's estimator is the static one his
+ // funding manager was built with, so the bound is exactly ten times
+ // that rate.
+ require.Less(t, uint64(openChanMsg.FeePerKiloWeight), uint64(
+ commitFeeRate*10,
+ ))
+
+ bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
+
+ // Bob must refuse the channel rather than answer with an
+ // AcceptChannel, and he must do so for the balance reason. The message
+ // is built from the same constructor the daemon uses, so it pins the
+ // balances reported as well as the wording.
+ bobMsg := assertFundingMsgSent(t, bob.msgChan, "Error")
+ errMsg, ok := bobMsg.(*lnwire.Error)
+ require.True(t, ok, "expected *lnwire.Error, got %T", bobMsg)
+
+ expected := lnwallet.ErrBalancesBelowReserve(
+ fundeeBalance, initiatorBalance, initiatorReserve,
+ acceptReserve,
+ )
+ require.Equal(t, expected.Error(), string(errMsg.Data))
+}
+
// TestFundingManagerRejectPublicTaprootInitiator checks that a public taproot
// channel request is rejected by the initiator before an OpenChannel message is
// sent to the peer.
### lnwallet/errors.go
@@ -106,6 +106,25 @@ func ErrPushAmountTooLarge(pushAmt lnwire.MilliSatoshi,
}
}
+// ErrCommitFeeRateTooLargeBase is the sentinel wrapped by
+// ErrCommitFeeRateTooLarge, so that a caller inside the daemon can identify
+// the rejection with errors.Is instead of matching on the wording of the
+// message that goes out to the remote peer.
+var ErrCommitFeeRateTooLargeBase = errors.New("commitment fee rate " +
+ "unreasonably large")
+
+// ErrCommitFeeRateTooLarge returns an error indicating that the commitment fee
+// rate proposed by the channel initiator is unreasonably large, as described by
+// BOLT-02.
+func ErrCommitFeeRateTooLarge(feeRate,
+ maxFeeRate chainfee.SatPerKWeight) ReservationError {
+
+ return ReservationError{
+ fmt.Errorf("%w: %v, max is %v",
+ ErrCommitFeeRateTooLargeBase, feeRate, maxFeeRate),
+ }
+}
+
// ErrBalancesBelowReserveBase is the sentinel wrapped by
// ErrBalancesBelowReserve, so that callers can identify the rejection without
// matching on its message text.Why this scored 64/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.