Merge pull request #11151 from Roasbeef/reject-absurd-feerates
What changed, and why it matters
This commit adds two safety checks to LND's channel-opening process. When someone tries to open a Lightning channel with LND, LND now rejects the request if the proposed on-chain fee rate is absurdly high (more than 10 times LND's own fee estimate, with a minimum floor of 100 sat/vbyte), or if the initial balances are so low that neither party could actually use the channel. These checks prevent attackers or misconfigured peers from tying up LND's resources on channels that would be useless or economically harmful.
This is a defensive hardening patch. Operators should upgrade to a release containing this commit. No immediate incident response is indicated, but node operators may wish to review logs for rejected channel opens with 'unreasonably large' or 'below their channel reserve' errors to identify misconfigured or probing peers.
Security signals we found
New inbound-channel fee-rate cap enforcing BOLT-02 'unreasonably large' rejection
New balance-reserve validation preventing dead-on-arrival channels
Fee cap scales with local estimate but is floored to avoid rejecting sane channels during low-fee periods
Sentinel errors added for programmatic identification of rejections
Extensive unit and integration test coverage for both rejection and acceptance cases
Evidence from the diff
The patch implements BOLT-02 requirements in funding/manager.go and lnwallet/reservation.go. It introduces maxRemoteCommitFeeRate(), which computes a cap of 10x the local fee estimate at a 3-block confirmation target, floored at minCommitFeeRateCap (100 sat/vbyte = 25,000 sat/kw). fundeeProcessOpenChannel now calls checkCommitFeeRate() to fail the funding flow when the inbound open_channel’s FeePerKiloWeight exceeds this cap. A second check, validateInitialBalances(), is added to ChannelReservation and invoked in handleSingleContribution; it rejects channels where both to_local and to_remote are at or below the channel_reserve_satoshis from open_channel (spec MUST), or where neither side clears its own reserve (usability policy). New sentinel errors (ErrCommitFeeRateTooLargeBase, ErrBalancesBelowReserveBase) and ReservationError.Unwrap() support errors.Is identification. Comprehensive unit and integration tests are included.
Changed components
funding/manager.golnwallet/reservation.golnwallet/wallet.golnwallet/errors.golntest/harness.godocs/release-notes/unreleased/11151.mdInspect captured patch +1243 / −26
### docs/release-notes/unreleased/11151.md
@@ -0,0 +1,16 @@
+# Technical and Architectural Updates
+
+## BOLT Spec Updates
+
+* The fundee now [rejects absurdly high channel
+ feerates](https://github.com/lightningnetwork/lnd/pull/11151), covering the
+ two BOLT-02 checks that bound the commitment feerate an initiator can impose.
+ An incoming `open_channel` is failed if its `feerate_per_kw` exceeds ten times
+ our own estimate (never below 100 sat/vbyte, so a low or stale estimate can't
+ turn away sane channels), or if its `to_local` and `to_remote` amounts both
+ land at or under the `channel_reserve_satoshis` it proposed. Both amounts
+ are compared against that one reserve, as BOLT-02 specifies, rather than
+ against the reserve we name in our own `accept_channel`. Because all
+ channels are single funder, an initiator proposing such a feerate mostly
+ burns its own capacity; the checks stop it from also spending one of our
+ pending channel slots on a channel that could never be used.
### 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.
### itest/list_on_test.go
@@ -262,6 +262,10 @@ var allTestCases = []*lntest.TestCase{
Name: "maximum channel size",
TestFunc: testMaxChannelSize,
},
+ {
+ Name: "reject absurd commit feerate",
+ TestFunc: testRejectAbsurdCommitFeerate,
+ },
{
Name: "wumbo channels",
TestFunc: testWumboChannels,
### itest/lnd_reject_absurd_feerate_test.go
@@ -0,0 +1,220 @@
+package itest
+
+import (
+ "fmt"
+
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/lightningnetwork/lnd/input"
+ "github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lnrpc/walletrpc"
+ "github.com/lightningnetwork/lnd/lntest"
+ "github.com/lightningnetwork/lnd/lntest/node"
+ "github.com/lightningnetwork/lnd/lnwallet"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
+ "github.com/stretchr/testify/require"
+)
+
+// testRejectAbsurdCommitFeerate covers the two BOLT-02 checks that bound the
+// commitment feerate a channel initiator can impose on the fundee: a
+// feerate_per_kw the fundee considers unreasonably large, and an initial
+// commitment whose outputs both sit at or below the reserve the initiator
+// named. Each check is exercised in both directions, so a fundee that simply
+// refused everything would fail the positive case.
+//
+// Both rejections are driven by what the initiator proposes, so each node is
+// started with its own --fee.url pointing at a fee service this test controls.
+// That is what lets the test dial feerate_per_kw through the ordinary funding
+// flow rather than hand-crafting wire messages. The harness-wide fee service
+// cannot be used, since both nodes would share it and the initiator and the
+// fundee need to disagree about the current feerate.
+func testRejectAbsurdCommitFeerate(ht *lntest.HarnessTest) {
+ // The low feerate the fundee considers sane. The fundee's bound is
+ // floored at 25000 sat/kw, so pointing it here makes that floor the
+ // bound, and anything above 25000 sat/kw is unreasonably large to it.
+ const lowFeeRate = chainfee.SatPerKWeight(2500)
+
+ // A feerate no realistic mempool needs a commitment to beat.
+ const absurdFeeRate = chainfee.SatPerKWeight(100000)
+
+ // Start a fee service per node. --fee.url is appended after the
+ // harness's own value, and the last occurrence of a scalar option
+ // wins, so each node ends up with its own estimator.
+ aliceFees := lntest.NewFeeService(ht.T)
+ require.NoError(ht, aliceFees.Start())
+ ht.Cleanup(func() {
+ require.NoError(ht, aliceFees.Stop())
+ })
+
+ bobFees := lntest.NewFeeService(ht.T)
+ require.NoError(ht, bobFees.Start())
+ ht.Cleanup(func() {
+ require.NoError(ht, bobFees.Stop())
+ })
+
+ aliceFees.SetFeeRate(lowFeeRate, 1)
+ bobFees.SetFeeRate(lowFeeRate, 1)
+
+ // Bob is the fundee and enforces both checks. Alice is the initiator,
+ // and is given a high anchor fee cap so that the rate she may propose
+ // is not what limits the absurd case below (the default cap is 10
+ // sat/vbyte). The cap has no effect on a tweakless channel, which is
+ // what the reserve case opens.
+ alice := ht.NewNodeWithCoins("Alice", []string{
+ "--fee.url=" + aliceFees.URL(),
+ "--max-commit-fee-rate-anchors=400",
+ })
+ bob := ht.NewNode("Bob", []string{
+ "--fee.url=" + bobFees.URL(),
+ })
+
+ ht.EnsureConnected(alice, bob)
+
+ // estimateFee asks a node to estimate a fee through the same estimator
+ // the funding manager consults, so this reads back the rate that node
+ // would actually put in open_channel. The walletkit call is used
+ // rather than the lnrpc one because it takes no address and so needs
+ // no spendable funds, which Bob does not have.
+ estimateFee := func(n *node.HarnessNode) chainfee.SatPerKWeight {
+ resp, err := n.RPC.WalletKit.EstimateFee(
+ ht.Context(),
+ &walletrpc.EstimateFeeRequest{ConfTarget: 3},
+ )
+ require.NoError(ht, err, "%s EstimateFee", n.Name())
+
+ return chainfee.SatPerKWeight(resp.SatPerKw)
+ }
+
+ // feerateSubTest runs one feerate case. The fundee always sits at
+ // lowFeeRate, so its bound is the 25000 sat/kw floor; the initiator is
+ // pointed at feeRate and the outcome is asserted against expectReject.
+ feerateSubTest := func(feeRate chainfee.SatPerKWeight,
+ expectReject bool) {
+
+ aliceFees.SetFeeRate(feeRate, 1)
+ bobFees.SetFeeRate(lowFeeRate, 1)
+
+ proposed := estimateFee(alice)
+ bound := estimateFee(bob) * 10
+ ht.Logf("feerate case: initiator proposes %v, fundee bound %v",
+ proposed, bound)
+
+ params := lntest.OpenChannelParams{
+ Amt: 1_000_000,
+ Private: true,
+ }
+
+ if !expectReject {
+ ht.OpenChannel(alice, bob, params)
+ ht.AssertNumPendingOpenChannels(alice, 0)
+ ht.AssertNumPendingOpenChannels(bob, 0)
+
+ return
+ }
+
+ // The case only proves the feerate check if the initiator's
+ // proposal really is above the fundee's bound.
+ require.Greater(ht, int64(proposed), int64(bound),
+ "the initiator's feerate must exceed the fundee's "+
+ "bound for this case to mean anything")
+
+ ht.OpenChannelAssertErr(
+ alice, bob, params, fmt.Errorf("unreasonably large"),
+ )
+ }
+
+ // A rate the fundee treats as unreasonably large must fail the
+ // channel, and the same flow at a rate it accepts must succeed.
+ feerateSubTest(absurdFeeRate, true)
+ feerateSubTest(lowFeeRate, false)
+
+ // Now the reserve check. It fires only when the initiator's balance and
+ // the fundee's both sit at or below the reserve the initiator named,
+ // which takes a commitment fee large enough to eat most of the
+ // channel.
+ //
+ // The reserve the fundee will accept is capped at a fifth of the
+ // channel capacity, so the initiator's balance has to fall below that
+ // cap while staying above the two-times-dust guard in
+ // NewChannelReservation -- otherwise an earlier check would be the one
+ // refusing the open. The fundee is pushed nothing, so it sits at zero
+ // and is trivially at or below the same reserve.
+ //
+ // The channel is opened tweakless, whose commitment weight has no
+ // anchor outputs, so the whole commitment fee comes off the amount
+ // left over after it.
+ const (
+ reserveChanAmt = btcutil.Amount(100_000)
+ commitWeight = input.CommitWeight
+ )
+
+ // Just under the fifth-of-capacity cap the fundee enforces.
+ initiatorReserve := uint64(reserveChanAmt/5) - 1
+
+ // The smallest commitment fee that drops the initiator's balance to or
+ // below the reserve it named, and the feerate that produces it.
+ minFee := uint64(reserveChanAmt) - initiatorReserve
+ minFeeRate := (minFee*1000 + commitWeight - 1) / commitWeight
+ reserveCaseFeeRate := chainfee.SatPerKWeight(minFeeRate)
+
+ // The fundee's own rate must leave its feerate bound clear of the
+ // rate the initiator proposes, or the feerate check would reject the
+ // channel first and this case would prove nothing about reserves.
+ const reserveCaseBobRate = chainfee.SatPerKWeight(20000)
+
+ require.Less(ht, int64(minFeeRate), int64(reserveCaseBobRate)*10,
+ "the reserve case needs the feerate check not to fire first")
+
+ fee := reserveCaseFeeRate.FeeForWeight(commitWeight)
+ initiatorBalance := reserveChanAmt - fee
+
+ ht.Logf("reserve case: capacity=%v, fee=%v, initiator balance=%v, "+
+ "reserve=%v", int64(reserveChanAmt), int64(fee),
+ int64(initiatorBalance), initiatorReserve)
+
+ // Guard the premises the rejection depends on, so a change to the
+ // commitment format or the dust limit fails loudly here rather than
+ // making the assertion below pass or fail for the wrong reason.
+ require.LessOrEqual(ht, int64(initiatorBalance),
+ int64(initiatorReserve),
+ "the initiator's balance must be at or below "+
+ "the reserve it named")
+ require.Greater(ht, int64(initiatorBalance),
+ 2*int64(lnwallet.DustLimitUnknownWitness()),
+ "the initiator's balance must clear the funder-balance-dust "+
+ "guard, or that check would reject the open instead")
+
+ aliceFees.SetFeeRate(reserveCaseFeeRate, 1)
+ bobFees.SetFeeRate(reserveCaseBobRate, 1)
+
+ proposed := estimateFee(alice)
+ feerateBound := estimateFee(bob) * 10
+ ht.Logf("reserve case: initiator proposes %v, fundee bound %v",
+ proposed, feerateBound)
+ require.LessOrEqual(ht, int64(proposed), int64(feerateBound),
+ "the reserve case needs the feerate check not to fire first")
+
+ params := lntest.OpenChannelParams{
+ Amt: reserveChanAmt,
+ Private: true,
+ CommitmentType: lnrpc.CommitmentType_STATIC_REMOTE_KEY,
+ RemoteChanReserveSat: initiatorReserve,
+ }
+ ht.OpenChannelAssertErr(
+ alice, bob, params, lnwallet.ErrBalancesBelowReserveBase,
+ )
+
+ // The positive direction: the same channel shape opens once the
+ // initiator's balance clears the reserve it names.
+ aliceFees.SetFeeRate(lowFeeRate, 1)
+ bobFees.SetFeeRate(lowFeeRate, 1)
+
+ ht.OpenChannel(alice, bob, lntest.OpenChannelParams{
+ Amt: reserveChanAmt,
+ Private: true,
+ CommitmentType: lnrpc.CommitmentType_STATIC_REMOTE_KEY,
+ RemoteChanReserveSat: initiatorReserve,
+ })
+
+ ht.AssertNumPendingOpenChannels(alice, 0)
+ ht.AssertNumPendingOpenChannels(bob, 0)
+}
### lntest/harness.go
@@ -990,6 +990,13 @@ type OpenChannelParams struct {
// activates the default configured fee rate.
UseFeeRate bool
+ // RemoteChanReserveSat is the channel reserve, in satoshis, that the
+ // initiator requires the remote peer to maintain. It is the value that
+ // rides in open_channel as channel_reserve_satoshis, and so the value
+ // BOLT-02 compares both initial commitment outputs against. Zero leaves
+ // the node's own default in place.
+ RemoteChanReserveSat uint64
+
// FundMax is a boolean indicating whether the channel should be funded
// with the maximum possible amount from the wallet.
FundMax bool
@@ -1041,28 +1048,29 @@ func (h *HarnessTest) prepareOpenChannel(srcNode, destNode *node.HarnessNode,
// Prepare the request.
return &lnrpc.OpenChannelRequest{
- NodePubkey: destNode.PubKey[:],
- LocalFundingAmount: int64(p.Amt),
- PushSat: int64(p.PushAmt),
- Private: p.Private,
- TargetConf: confTarget,
- MinConfs: minConfs,
- SpendUnconfirmed: p.SpendUnconfirmed,
- MinHtlcMsat: int64(p.MinHtlc),
- RemoteMaxHtlcs: uint32(p.RemoteMaxHtlcs),
- FundingShim: p.FundingShim,
- SatPerVbyte: uint64(p.SatPerVByte),
- CommitmentType: p.CommitmentType,
- ZeroConf: p.ZeroConf,
- ScidAlias: p.ScidAlias,
- BaseFee: p.BaseFee,
- FeeRate: p.FeeRate,
- UseBaseFee: p.UseBaseFee,
- UseFeeRate: p.UseFeeRate,
- FundMax: p.FundMax,
- Memo: p.Memo,
- Outpoints: p.Outpoints,
- CloseAddress: p.CloseAddress,
+ NodePubkey: destNode.PubKey[:],
+ LocalFundingAmount: int64(p.Amt),
+ PushSat: int64(p.PushAmt),
+ Private: p.Private,
+ TargetConf: confTarget,
+ MinConfs: minConfs,
+ SpendUnconfirmed: p.SpendUnconfirmed,
+ MinHtlcMsat: int64(p.MinHtlc),
+ RemoteMaxHtlcs: uint32(p.RemoteMaxHtlcs),
+ FundingShim: p.FundingShim,
+ SatPerVbyte: uint64(p.SatPerVByte),
+ RemoteChanReserveSat: p.RemoteChanReserveSat,
+ CommitmentType: p.CommitmentType,
+ ZeroConf: p.ZeroConf,
+ ScidAlias: p.ScidAlias,
+ BaseFee: p.BaseFee,
+ FeeRate: p.FeeRate,
+ UseBaseFee: p.UseBaseFee,
+ UseFeeRate: p.UseFeeRate,
+ FundMax: p.FundMax,
+ Memo: p.Memo,
+ Outpoints: p.Outpoints,
+ CloseAddress: p.CloseAddress,
}
}
### lnwallet/errors.go
@@ -22,6 +22,14 @@ type ReservationError struct {
// interface.
var _ error = (*ReservationError)(nil)
+// Unwrap returns the wrapped error, so that the sentinels a constructor wraps
+// with %w can be matched by callers with errors.Is. Callers inside the daemon
+// use it to decide whether to fail a funding flow; the remote peer only ever
+// sees Error().
+func (e ReservationError) Unwrap() error {
+ return e.error
+}
+
// ErrZeroCapacity returns an error indicating the funder attempted to put zero
// funds into the channel.
func ErrZeroCapacity() ReservationError {
@@ -98,6 +106,53 @@ 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.
+var ErrBalancesBelowReserveBase = errors.New("both initial balances are " +
+ "below their channel reserve")
+
+// ErrBalancesBelowReserve returns an error indicating that a channel could
+// never be used, because neither party would hold more than the reserve it is
+// required to maintain on the initial commitment transaction. BOLT-02 requires
+// that we fail a channel whose initial outputs are both at or below the
+// reserve the initiator named in open_channel, and a channel where neither
+// side can spend is rejected for the same reason.
+//
+// Both reserves are reported so the message distinguishes the two: ourReserve
+// is the reserve the initiator requires of us, and theirReserve is the reserve
+// we require of them in accept_channel.
+func ErrBalancesBelowReserve(localBalance, theirBalance, ourReserve,
+ theirReserve btcutil.Amount) ReservationError {
+
+ return ReservationError{
+ fmt.Errorf("%w: to_local %v sat against our reserve %v sat, "+
+ "to_remote %v sat against their reserve %v sat",
+ ErrBalancesBelowReserveBase, int64(localBalance),
+ int64(ourReserve), int64(theirBalance),
+ int64(theirReserve)),
+ }
+}
+
// ErrMinHtlcTooLarge returns an error indicating that the MinHTLC value the
// remote required is too large to be accepted.
func ErrMinHtlcTooLarge(minHtlc,
### lnwallet/reservation.go
@@ -647,6 +647,67 @@ func (r *ChannelReservation) validateReserveBounds() bool {
return minChanReserve >= maxDustLimit
}
+// validateInitialBalances fails a channel that could never be used: one where
+// neither side's initial commitment output clears the reserve that side is
+// required to maintain. In that case neither party can add an HTLC without
+// dipping below its reserve, so the channel is dead on arrival.
+//
+// Two checks are made, and both are needed:
+//
+// 1. The BOLT#02 requirement, which the receiver of open_channel MUST apply:
+// both to_local and to_remote are less than or equal to
+// channel_reserve_satoshis, the single value the initiator named in
+// open_channel. That value is the reserve the initiator requires of us.
+//
+// 2. A usability check, comparing each output against the reserve its own
+// side must maintain: to_local against the reserve the initiator named for
+// us, and to_remote against the reserve we named for them in accept_channel.
+// That is what decides whether either side can actually spend, since the two
+// reserves are independent and may differ in either direction.
+//
+// Neither check implies the other. When our accept_channel reserve is the
+// lower of the two, check 1 can reject a channel the initiator could still
+// use, and the spec requires that; when our reserve is the higher, check 1
+// accepts a channel where neither side can spend, which check 2 catches. The
+// second check is therefore a local policy that is in places stricter than
+// the letter of the spec, and it is deliberately additive rather than a
+// reinterpretation of the first.
+//
+// This function should be called with the lock held.
+func (r *ChannelReservation) validateInitialBalances() error {
+ commitment := r.partialState.LocalCommitment
+ ourInitialBalance := commitment.LocalBalance.ToSatoshis()
+ theirInitialBalance := commitment.RemoteBalance.ToSatoshis()
+
+ // The reserve in our contribution is the one the initiator set in
+ // open_channel: the reserve the initiator requires OF US, which is the
+ // single value BOLT#02 compares both initial outputs against. The one
+ // in their contribution is the reserve WE named for them in
+ // accept_channel.
+ reserveInitiatorRequiresOfUs := r.ourContribution.ChanReserve
+ reserveWeRequireOfThem := r.theirContribution.ChanReserve
+
+ // Check 1: the spec's own comparison, both outputs against the
+ // initiator's reserve of us. This is a MUST, so it stays even though
+ // it can turn away a channel the initiator could still use.
+ failsSpecMUST := ourInitialBalance <= reserveInitiatorRequiresOfUs &&
+ theirInitialBalance <= reserveInitiatorRequiresOfUs
+
+ // Check 2: each output against the reserve its own side must maintain,
+ // which is exactly the condition under which neither side can spend.
+ failsUsability := ourInitialBalance <= reserveInitiatorRequiresOfUs &&
+ theirInitialBalance <= reserveWeRequireOfThem
+
+ if failsSpecMUST || failsUsability {
+ return ErrBalancesBelowReserve(
+ ourInitialBalance, theirInitialBalance,
+ reserveInitiatorRequiresOfUs, reserveWeRequireOfThem,
+ )
+ }
+
+ return nil
+}
+
// OurContribution returns the wallet's fully populated contribution to the
// pending payment channel. See 'ChannelContribution' for further details
// regarding the contents of a contribution.
### lnwallet/reservation_test.go
@@ -6,6 +6,7 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil/v2"
"github.com/lightningnetwork/lnd/channeldb"
+ "github.com/lightningnetwork/lnd/chanstate"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/stretchr/testify/require"
)
@@ -58,3 +59,379 @@ func TestReservationAuxChanStatePopulatesNegotiatedConfigs(t *testing.T) {
require.Equal(t, *localCfg, auxState.LocalChanCfg)
require.Equal(t, *remoteCfg, auxState.RemoteChanCfg)
}
+
+// TestValidateInitialBalances checks the two conditions that fail a channel
+// whose initial commitment leaves neither side able to spend.
+//
+// The first is the BOLT#02 MUST: both initial outputs at or below the single
+// channel_reserve_satoshis the initiator named in open_channel, which is the
+// reserve the initiator requires of us. The second is the usability check:
+// each output at or below the reserve its own side must maintain. The
+// configurations below are chosen so the two differ.
+func TestValidateInitialBalances(t *testing.T) {
+ t.Parallel()
+
+ // initiatorReserve is the channel_reserve_satoshis the initiator
+ // proposed in open_channel: the reserve they require of us.
+ const initiatorReserve = btcutil.Amount(10000)
+
+ // acceptReserve is the reserve we name in accept_channel: the reserve
+ // we require of them. It is deliberately below the initiator's, which
+ // is the configuration where the spec check rejects a channel the
+ // usability check would accept.
+ const acceptReserve = btcutil.Amount(5000)
+
+ // chanCfg builds the minimal channel config validateInitialBalances
+ // reads: the reserve the party it belongs to must maintain.
+ chanCfg := func(reserve btcutil.Amount) *channeldb.ChannelConfig {
+ bounds := channeldb.ChannelStateBounds{
+ ChanReserve: reserve,
+ }
+
+ return &channeldb.ChannelConfig{
+ ChannelStateBounds: bounds,
+ }
+ }
+
+ tests := []struct {
+ name string
+ initiatorReserve btcutil.Amount
+
+ // acceptReserve overrides the package-level value for cases
+ // that need our reserve to sit above the initiator's.
+ acceptReserve btcutil.Amount
+
+ ourBalance btcutil.Amount
+ theirBalance btcutil.Amount
+ expectErr bool
+ }{
+ {
+ // The common case for a fundee: we start at zero with
+ // no push, but the initiator holds nearly the full
+ // capacity.
+ name: "only initiator above reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 0,
+ theirBalance: 1000000,
+ },
+ {
+ // The mirror image, which is what a full push looks
+ // like.
+ name: "only fundee above reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 1000000,
+ theirBalance: 0,
+ },
+ {
+ name: "both above reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 500000,
+ theirBalance: 500000,
+ },
+ {
+ // The reporter's example: an absurd commitment fee rate
+ // burns the capacity before either party can use the
+ // channel.
+ name: "both below reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 0,
+ theirBalance: 9000,
+ expectErr: true,
+ },
+ {
+ // Both balances sit above the reserve we name in
+ // accept_channel, so the usability check alone would
+ // accept. The spec check still fires, because both are
+ // at or below the initiator's reserve.
+ name: "both above accept reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 9000,
+ theirBalance: 9000,
+ expectErr: true,
+ },
+ {
+ // The spec check rejects a USABLE channel
+ // here, and that is intentional: it is a MUST,
+ // not a heuristic. Our accept reserve is
+ // 5000 and the initiator's balance is 8000,
+ // so they can still spend, but both outputs
+ // are at or below the initiator's 10000
+ // reserve, so BOLT#02 requires us to fail the
+ // channel.
+ //
+ // This case exists to pin that behaviour. A
+ // future change that "fixes" the
+ // over-rejection by dropping the spec
+ // comparison must fail here.
+ name: "spec rejects one-sided",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 0,
+ theirBalance: 8000,
+ expectErr: true,
+ },
+ {
+ // Our balance is above the initiator's reserve, which
+ // clears the spec check, and the initiator's balance
+ // clears the reserve we named for them, so neither
+ // check fires.
+ name: "one side above initiator reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: 10001,
+ theirBalance: 0,
+ },
+ {
+ // The dead-channel case the spec check alone misses.
+ // The initiator names a reserve of us BELOW the reserve
+ // we name of them, so their balance sits above the
+ // initiator's reserve and the spec check does not fire.
+ // But it is at or below the reserve we
+ // require of them, and our own balance is
+ // at or below the initiator's, so neither
+ // side can spend.
+ name: "dead channel above reserve",
+ initiatorReserve: 1000,
+ acceptReserve: 5000,
+ ourBalance: 0,
+ theirBalance: 5000,
+ expectErr: true,
+ },
+ {
+ // The spec fails on "less than or equal to", so a
+ // balance sitting exactly at the reserve doesn't save
+ // the channel: no HTLC could be added without dipping
+ // below it.
+ name: "both exactly at reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: initiatorReserve,
+ theirBalance: initiatorReserve,
+ expectErr: true,
+ },
+ {
+ // A single satoshi above the reserve is enough for the
+ // channel to be considered usable.
+ name: "one satoshi above reserve",
+ initiatorReserve: initiatorReserve,
+ acceptReserve: acceptReserve,
+ ourBalance: initiatorReserve,
+ theirBalance: initiatorReserve + 1,
+ },
+ {
+ // A zero reserve is legitimate, in which case a
+ // channel with any balance at all is fine.
+ name: "zero reserve with balance",
+ initiatorReserve: 0,
+ acceptReserve: 0,
+ ourBalance: 0,
+ theirBalance: 1,
+ },
+ {
+ // A zero reserve does not help a channel with no funds
+ // anywhere: both balances are still at or below it.
+ name: "zero reserve without balance",
+ initiatorReserve: 0,
+ acceptReserve: 0,
+ ourBalance: 0,
+ theirBalance: 0,
+ expectErr: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ commit := channeldb.ChannelCommitment{
+ LocalBalance: lnwire.NewMSatFromSatoshis(
+ test.ourBalance,
+ ),
+ RemoteBalance: lnwire.NewMSatFromSatoshis(
+ test.theirBalance,
+ ),
+ }
+
+ res := &ChannelReservation{
+ ourContribution: &ChannelContribution{
+ ChannelConfig: chanCfg(
+ test.initiatorReserve,
+ ),
+ },
+ theirContribution: &ChannelContribution{
+ ChannelConfig: chanCfg(
+ test.acceptReserve,
+ ),
+ },
+ partialState: &chanstate.OpenChannel{
+ LocalCommitment: commit,
+ },
+ }
+
+ err := res.validateInitialBalances()
+ if !test.expectErr {
+ require.NoError(t, err)
+ return
+ }
+
+ // The rejection is identified by the sentinel rather
+ // than by its message text, so the assertion does not
+ // depend on the wording we send the remote peer.
+ require.ErrorIs(t, err, ErrBalancesBelowReserveBase)
+ })
+ }
+}
+
+// TestValidateInitialBalancesUnionIsAdditive drives the real check across a
+// sweep of reserves and balances and asserts the property that makes the
+// usability comparison safe to layer onto the spec one: every channel it
+// rejects beyond what the spec comparison alone would reject must be one where
+// NEITHER side can spend. Adding it therefore costs us no usable channel.
+//
+// The predicate the spec comparison would apply is computed here independently,
+// and the rejection itself comes from validateInitialBalances, so this test
+// would fail if the implementation drifted from the property.
+func TestValidateInitialBalancesUnionIsAdditive(t *testing.T) {
+ t.Parallel()
+
+ // msat is a shorthand for the long constructor below, so the
+ // reservation builder stays within the column limit.
+ msat := lnwire.NewMSatFromSatoshis
+
+ chanCfg := func(reserve btcutil.Amount) *channeldb.ChannelConfig {
+ return &channeldb.ChannelConfig{
+ ChannelStateBounds: channeldb.ChannelStateBounds{
+ ChanReserve: reserve,
+ },
+ }
+ }
+
+ amounts := []btcutil.Amount{
+ 0, 1, 4999, 5000, 5001, 9999, 10000, 10001, 20000,
+ }
+
+ // The reserve the initiator names for us, and the reserve we name for
+ // them in accept_channel. Both directions of their relationship are
+ // exercised, since that is what decides which comparison bites.
+ reserves := []btcutil.Amount{1000, 5000, 10000, 20000}
+
+ addedRejections := 0
+
+ reservation := func(
+ ourBalance, theirBalance btcutil.Amount,
+ ourReserve, theirReserve btcutil.Amount,
+ ) *ChannelReservation {
+
+ return &ChannelReservation{
+ ourContribution: &ChannelContribution{
+ ChannelConfig: chanCfg(ourReserve),
+ },
+ theirContribution: &ChannelContribution{
+ ChannelConfig: chanCfg(theirReserve),
+ },
+ partialState: &chanstate.OpenChannel{
+ LocalCommitment: channeldb.ChannelCommitment{
+ LocalBalance: msat(ourBalance),
+ RemoteBalance: msat(theirBalance),
+ },
+ },
+ }
+ }
+
+ for _, ourReserve := range reserves {
+ for _, theirReserve := range reserves {
+ for _, ourBalance := range amounts {
+ for _, theirBalance := range amounts {
+ res := reservation(
+ ourBalance, theirBalance,
+ ourReserve, theirReserve,
+ )
+
+ err := res.validateInitialBalances()
+
+ // What the BOLT-02 comparison on its
+ // own would have done, computed here
+ // rather than read from the code under
+ // test.
+ specAlone := ourBalance <= ourReserve &&
+ theirBalance <= ourReserve
+
+ // A channel is usable if either side
+ // can add an HTLC without dipping below
+ // the reserve that side must maintain.
+ usable := ourBalance > ourReserve ||
+ theirBalance > theirReserve
+
+ rejected := err != nil
+
+ // The spec comparison must never be
+ // bypassed: whenever it fires, so must
+ // the check.
+ if specAlone && !rejected {
+ t.Fatalf("spec comparison did "+
+ "not reject: our=%v "+
+ "their=%v "+
+ "ourReserve=%v "+
+ "theirReserve=%v",
+ ourBalance,
+ theirBalance,
+ ourReserve,
+ theirReserve,
+ )
+ }
+
+ // Any rejection beyond the spec's must
+ // be a channel neither side can spend
+ // on.
+ if rejected && !specAlone {
+ addedRejections++
+
+ if usable {
+ t.Fatalf("rejected a "+
+ "usable "+
+ "channel the "+
+ "spec allows: "+
+ "our=%v "+
+ "their=%v "+
+ "ourRes=%v "+
+ "theirRes=%v",
+ ourBalance,
+ theirBalance,
+ ourReserve,
+ theirReserve,
+ )
+ }
+ }
+
+ // And the converse: a channel where
+ // neither side can spend must not be
+ // accepted.
+ if !usable && !rejected {
+ t.Fatalf("accepted a dead "+
+ "channel: our=%v "+
+ "their=%v "+
+ "ourReserve=%v "+
+ "theirReserve=%v",
+ ourBalance,
+ theirBalance,
+ ourReserve,
+ theirReserve,
+ )
+ }
+ }
+ }
+ }
+ }
+
+ // The sweep has to actually reach the added-rejection band, or the
+ // assertions above would vacuously hold.
+ require.Positive(t, addedRejections,
+ "the sweep never hit a channel the "+
+ "usability check adds, so it did "+
+ "not exercise the property")
+}
### lnwallet/wallet.go
@@ -2126,6 +2126,14 @@ func (l *LightningWallet) handleSingleContribution(req *addSingleContributionMsg
return
}
+ // Now that both reserves are known, make sure the channel the initiator
+ // is proposing could actually be used: at least one side must start out
+ // above its reserve.
+ if err := pendingReservation.validateInitialBalances(); err != nil {
+ req.err <- err
+ return
+ }
+
// Initialize an empty sha-chain for them, tracking the current pending
// revocation hash (we don't yet know the preimage so we can't add it
// to the chain).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.