[bug]: validateFeeRate and MaxFeeRate accept a feerate that SignNextCommitment refuses after an unrevoked fee decrease

Aperta
#11,604 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
18/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
go
Ambito
backend, payments

Direzione di ricerca

The defect sits in lnwallet/channel.go, in validateFeeRate and MaxFeeRate (around L9511-L9519 and L10075-L10106), where the base balance uses the pending lower feerate while the fee is added back at the tip rate. Reproduce with the htlcswitch link test and the lnwallet test from the report, which show a link failure with allocation 1.0 and a clean sign with 0.5. Done means the fee ceiling respects the unrevoked decrease so the link no longer fails after revocation. Expect a design discussion on the fix, so confirm the approach with maintainers first.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug needs triage
Pre-Submission Checklist
  • I have searched the existing issues and believe this is a new bug.
  • I am not asking a question about how to use lnd, but reporting a bug (otherwise open a discussion).
LND Version

master 8cdbf85c0860 (2026-11-18), v0.21.8-beta and v0.20.8-beta

LND Configuration

max-channel-fee-allocation=1.0, otherwise default (fee exposure limit 500,000 sat).

Backend Version

None. The code runs inside lnd's own packages.

Backend Configuration

None.

OS/Distribution

Linux x86_64

Bug Details & Steps to Reproduce

On lnd master 8cdbf85c0860, validateFeeRate and MaxFeeRate compute the funder's available balance from the view that already has the pending, lower feerate, then add back the fee at the local commitment's tip rate (channel.go L9511-L9519, channel.go L10075-L10106). While the decrease is signed and not revoked, the tip still has the old rate, so the base balance is too large by the difference of the two fees. UpdateFee and the peer's ReceiveUpdateFee accept the rate. SignNextCommitment then fails with "commitment transaction dips peer below chan reserve", which fails the link and sends error. lnd's own fee timer reaches MaxFeeRate through IdealCommitFeeRate with max-channel-fee-allocation=1.0 on non-anchor channels, with the fee exposure check passed. On anchor channels the updater's rate is capped at 2,500 sat/kw in the test, and that rate signs. BOLT 2 says a receiver SHOULD fail the channel when the sender cannot afford the new fee rate.

Test on the channel link, package htlcswitch. The funder has 450,000 sat, so the largest commitment fee it can afford is under the 500,000 sat fee exposure limit. The fee timer proposes a decrease, the peer receives it and the commitment signature but does not revoke, the fee timer fires again with a high network feerate, and then the peer's revocation arrives. The same sequence runs with the default max-channel-fee-allocation of 0.5 and with 1.0:

// Funder's fee timer raises the feerate while an earlier fee decrease is signed
// and not yet revoked, on lnd's channel link with the default fee exposure
// limit (500,000 sat).
package htlcswitch

import (
    "bytes"
    "fmt"
    "strings"
    "testing"
    "time"

    "github.com/btcsuite/btclog/v2"
    "github.com/lightningnetwork/lnd/lnwallet"
    "github.com/lightningnetwork/lnd/lnwallet/chainfee"
    "github.com/lightningnetwork/lnd/lnwire"
    "github.com/stretchr/testify/require"
)

func TestLinkFeeRaiseAfterUnrevokedDecrease(t *testing.T) {
    for _, alloc := range []float64{1.0, DefaultMaxLinkFeeAllocation} {
        t.Run(fmt.Sprintf("alloc=%v", alloc), func(t *testing.T) {
            // The funder holds 450,000 sat, so that the largest
            // commitment fee it can afford stays below the 500,000
            // sat exposure limit.
            h, err := newSingleLinkTestHarness(t, 450_000, 4_500)
            require.NoError(t, err)

            link := h.aliceLink.(*channelLink)
            link.cfg.MaxFeeAllocation = alloc
            failures := make(chan LinkFailureError, 1)
            link.cfg.OnChannelFailure = func(_ lnwire.ChannelID,
                _ lnwire.ShortChannelID, e LinkFailureError) {

                failures <- e
            }
            logBuf := &bytes.Buffer{}
            link.log = btclog.NewSLogger(btclog.NewDefaultHandler(
                logBuf, btclog.WithNoTimestamp(),
            ))
            require.NoError(t, h.start())

            est := link.cfg.FeeEstimator.(*mockFeeEstimator)
            sent := link.cfg.Peer.(*mockPeer).sentMsgs

            // tick fires the link's fee timer with the given network
            // feerate and the relay floor.
            tick := func(net chainfee.SatPerKWeight) {
                link.updateFeeTimer.Reset(time.Millisecond)
                select {
                case est.byteFeeIn <- net:
                case <-time.After(5 * time.Second):
                    t.Fatal("link did not sample the network fee")
                }
                select {
                case est.relayFee <- chainfee.FeePerKwFloor:
                case <-time.After(5 * time.Second):
                    t.Fatal("link did not sample the relay fee")
                }
            }
            next := func() lnwire.Message {
                select {
                case m := <-sent:
                    return m
                case <-time.After(3 * time.Second):
                    return nil
                }
            }

            // 1. The fee timer proposes a decrease. The link sends
            // update_fee and commitment_signed, and bob does not revoke.
            tick(1000)
            fee1, ok := next().(*lnwire.UpdateFee)
            require.True(t, ok)
            sig, ok := next().(*lnwire.CommitSig)
            require.True(t, ok)
            require.NoError(t, h.bobChannel.ReceiveUpdateFee(
                chainfee.SatPerKWeight(fee1.FeePerKw),
            ))
            require.NoError(t, h.bobChannel.ReceiveNewCommitment(
                &lnwallet.CommitSigs{
                    CommitSig: sig.CommitSig, HtlcSigs: sig.HtlcSigs,
                },
            ))

            // 2. The fee timer fires again with a high network feerate.
            tick(1_000_000_000)
            m := next()
            fee2, ok := m.(*lnwire.UpdateFee)
            if !ok {
                t.Logf("alloc %v: no second update_fee (got %T); "+
                    "feerate stays %d", alloc, m, fee1.FeePerKw)
                return
            }
            t.Logf("alloc %v: decrease to %d, then update_fee %d",
                alloc, fee1.FeePerKw, fee2.FeePerKw)
            require.NoError(t, h.bobChannel.ReceiveUpdateFee(
                chainfee.SatPerKWeight(fee2.FeePerKw),
            ))

            // 3. Bob's revocation arrives. The link owes a commitment
            // and signs it.
            rev, _, _, err := h.bobChannel.RevokeCurrentCommitment()
            require.NoError(t, err)
            link.HandleChannelUpdate(rev)

            select {
            case e := <-failures:
                t.Logf("alloc %v: link failed: %v", alloc, e.Error())
                for _, l := range strings.Split(logBuf.String(), "\n") {
                    if strings.Contains(l, "unable to update commitment") {
                        t.Logf("alloc %v: link log: %s", alloc, l)
                    }
                }
            case <-time.After(5 * time.Second):
                t.Logf("alloc %v: link did not fail", alloc)
            }
            for m := next(); m != nil; m = next() {
                t.Logf("alloc %v: link then sent %T", alloc, m)
            }
        })
    }
}

Run go test -count=1 -run TestLinkFeeRaiseAfterUnrevokedDecrease -v ./htlcswitch/. The output is the same on master, v0.21.8-beta and v0.20.8-beta:

    link_fee_raise_test.go:95: alloc 1: decrease to 1000, then update_fee 620093
    link_fee_raise_test.go:109: alloc 1: link failed: internal error
    link_fee_raise_test.go:112: alloc 1: link log: [ERR]: failing link: unable to update commitment: commitment transaction dips peer below chan reserve: our balance below chan reserve with error: internal error
    link_fee_raise_test.go:95: alloc 0.5: decrease to 1000, then update_fee 310046
    link_fee_raise_test.go:116: alloc 0.5: link did not fail
    link_fee_raise_test.go:119: alloc 0.5: link then sent *lnwire.CommitSig

With allocation 1.0 the link passes the fee exposure check (the fee at 620,093 sat/kw is about 449,000 sat), sends update_fee, and fails when it signs after the revocation. With allocation 0.5 the same sequence signs.

The same defect at the wallet level, without the link:

Test, package lnwallet_test:

// Funder's UpdateFee at MaxFeeRate while an earlier fee decrease is signed and
// not yet revoked.
package lnwallet_test

import (
    "context"
    "testing"

    "github.com/lightningnetwork/lnd/channeldb"
    "github.com/lightningnetwork/lnd/lnwallet"
    "github.com/lightningnetwork/lnd/lnwallet/chainfee"
)

// round plays: (optional) Alice's fee decrease to low, signed and received
// by Bob but not yet revoked; then Alice's update to the rate rateFn picks;
// then Bob's revocation reaches Alice and Alice signs, as her link does
// right after a revocation when she owes a commitment.
func round(t *testing.T, chanType channeldb.ChannelType, decrease bool,
    rateFn func(a *lnwallet.LightningChannel) chainfee.SatPerKWeight) (
    chainfee.SatPerKWeight, error, error) {

    ctx := context.Background()
    alice, bob, err := lnwallet.CreateTestChannels(t, chanType)
    if err != nil {
        t.Fatal(err)
    }
    if decrease {
        if err := alice.UpdateFee(253); err != nil {
            t.Fatal(err)
        }
        if err := bob.ReceiveUpdateFee(253); err != nil {
            t.Fatal(err)
        }
        sig, err := alice.SignNextCommitment(ctx)
        if err != nil {
            t.Fatal(err)
        }
        if err := bob.ReceiveNewCommitment(sig.CommitSigs); err != nil {
            t.Fatal(err)
        }
    }
    rate := rateFn(alice)
    updErr := alice.UpdateFee(rate)
    if updErr != nil {
        return rate, updErr, nil
    }
    if err := bob.ReceiveUpdateFee(rate); err != nil {
        t.Logf("  bob refuses update_fee %d: %v", rate, err)
    }
    if decrease {
        rev, _, _, err := bob.RevokeCurrentCommitment()
        if err != nil {
            t.Fatal(err)
        }
        if _, _, err := alice.ReceiveRevocation(rev); err != nil {
            t.Fatal(err)
        }
    }
    _, signErr := alice.SignNextCommitment(ctx)
    return rate, nil, signErr
}

func short(err error) string {
    if err == nil {
        return "ok"
    }
    s := err.Error()
    if len(s) > 110 {
        s = s[:110]
    }
    return s
}

func TestUpdateFeeAfterUnrevokedDecrease(t *testing.T) {
    types := []struct {
        name string
        ct   channeldb.ChannelType
    }{
        {"tweakless", channeldb.SingleFunderTweaklessBit},
        {"anchors", channeldb.SingleFunderTweaklessBit | channeldb.AnchorOutputsBit | channeldb.ZeroHtlcTxFeeBit},
    }
    maxRate := func(alloc float64) func(a *lnwallet.LightningChannel) chainfee.SatPerKWeight {
        return func(a *lnwallet.LightningChannel) chainfee.SatPerKWeight {
            r, _ := a.MaxFeeRate(alloc)
            return r
        }
    }
    // What lnd's link computes in handleUpdateFee (htlcswitch/link.go handleUpdateFee): IdealCommitFeeRate(net fee, relay floor, anchor cap, alloc),
    // with a network fee above every cap and the anchor cap at its
    // default of 10 sat/vB (2500 sat/kw).
    ideal := func(alloc float64) func(a *lnwallet.LightningChannel) chainfee.SatPerKWeight {
        return func(a *lnwallet.LightningChannel) chainfee.SatPerKWeight {
            return a.IdealCommitFeeRate(1_000_000_000, chainfee.FeePerKwFloor, 2500, alloc)
        }
    }
    for _, ty := range types {
        for _, c := range []struct {
            name     string
            decrease bool
            fn       func(a *lnwallet.LightningChannel) chainfee.SatPerKWeight
        }{
            {"MaxFeeRate(1.0) alone            ", false, maxRate(1.0)},
            {"MaxFeeRate(1.0) after a decrease ", true, maxRate(1.0)},
            {"MaxFeeRate(0.5) after a decrease ", true, maxRate(0.5)},
            {"link ideal 1.0 after a decrease  ", true, ideal(1.0)},
            {"link ideal 0.5 after a decrease  ", true, ideal(0.5)},
        } {
            rate, upd, sign := round(t, ty.ct, c.decrease, c.fn)
            t.Logf("%-9s %s rate=%-7d UpdateFee: %s; SignNextCommitment: %s",
                ty.name, c.name, rate, short(upd), short(sign))
        }
    }
}

Run go test -count=1 -run TestUpdateFeeAfterUnrevokedDecrease -v ./lnwallet/. The test prints one row per case and does not assert. Each row shows the rate, the result of UpdateFee and the result of SignNextCommitment. The output is the same on v0.21.8-beta and v0.20.8-beta, apart from the line prefix. The output is:

tweakless MaxFeeRate(1.0) alone             rate=676794154 UpdateFee: ok; SignNextCommitment: ok
tweakless MaxFeeRate(1.0) after a decrease  rate=676801267 UpdateFee: ok; SignNextCommitment: commitment transaction dips peer below chan reserve: our balance below chan reserve
tweakless MaxFeeRate(0.5) after a decrease  rate=338400633 UpdateFee: ok; SignNextCommitment: ok
tweakless link ideal 1.0 after a decrease   rate=676801267 UpdateFee: ok; SignNextCommitment: commitment transaction dips peer below chan reserve: our balance below chan reserve
tweakless link ideal 0.5 after a decrease   rate=338400633 UpdateFee: ok; SignNextCommitment: ok
anchors   MaxFeeRate(1.0) alone             rate=435941555 UpdateFee: ok; SignNextCommitment: ok
anchors   MaxFeeRate(1.0) after a decrease  rate=435948182 UpdateFee: ok; SignNextCommitment: commitment transaction dips peer below chan reserve: our balance below chan reserve
anchors   MaxFeeRate(0.5) after a decrease  rate=217974091 UpdateFee: ok; SignNextCommitment: ok
anchors   link ideal 1.0 after a decrease   rate=2500    UpdateFee: ok; SignNextCommitment: ok
anchors   link ideal 0.5 after a decrease   rate=2500    UpdateFee: ok; SignNextCommitment: ok
Expected Behavior

The fee timer does not send an update_fee that the link then cannot sign. In every wallet row where UpdateFee returns ok, SignNextCommitment also returns ok. The rows "after a decrease" with allocation 1.0 show UpdateFee returning ok and SignNextCommitment failing. MaxFeeRate returns a rate that the next SignNextCommitment can sign.

Debug Information

No response

Environment

No response

Lingua principale
Go
Stelle
8.2k
Fork
2.3k
Merge medio
1g 11h
PR unite (30g)
103

Preparare l'ambiente

  • Include un Dockerfile o un file Docker Compose
  • Ha un modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di lightningnetwork/lnd

Tutte le issue di lightningnetwork/lnd

Issue simili

Altre issue su Go

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.