Merge pull request #11440 from Roasbeef/fix-longstanding-correctness-bugs
What changed, and why it matters
This is a large bug-fix patch for LND (a Bitcoin Lightning Network node) that tightens correctness rules across many subsystems. It prevents several ways a node could mis-handle channel data, accept bad network gossip, commit corrupted database transactions, miscalculate sweep/close transactions, or read oversized wire messages. The patch is defensive: it adds checks and tests rather than removing functionality, and the release notes describe the changes as fixing 'low-level correctness bugs.'
Operators running LND should upgrade to a release containing this patch. Nodes using the etcd backend and watchtower functionality benefit most urgently. Review release notes for the two operator-visible behavior changes: etcd transactions now fail on read errors, and channels with CSV delay zero are rejected.
Security signals we found
Database transaction commit now aborts on read errors (etcd) - prevents silent data corruption / inconsistent state
Gossip zombie marking removed for invalid funding script - prevents denial-of-service / channel graph poisoning
Wire message length bounding added to watchtower protocol - prevents memory exhaustion / malformed message parsing
Dust limit checks corrected for watchtower reward and sweep outputs - prevents creation of non-standard/dust justice transactions
HTLC serialization enforces reader-readable size bound - prevents persisted channel state that cannot be reloaded
Cooperative close handles omitted-output signature variants correctly - prevents signature/transaction mismatch
Aux signatures restricted to taproot-overlay channels - prevents invalid signature data on plain channels
CSV delay of zero rejected - prevents commitment transactions with no breach response time
Sweeper fee budget and retry invariants tightened - prevents stuck or over-budget sweeps
Evidence from the diff
The commit fixes multiple correctness issues: (1) etcd read errors inside transactions are now propagated and abort the commit instead of being silently swallowed; (2) gossip validation no longer marks an SCID as a zombie for an invalid funding script, avoiding poisoning later valid announcements; (3) watchtower wire messages are bounded with io.LimitedReader and MaxPayloadLength is corrected for CreateSessionReply; (4) watchtower reward/sweep dust checks now use each output’s own script size; (5) channel state serialization refuses to write HTLCs whose onion+extra data exceeds the reader’s max; (6) cooperative close now supports the ‘closee-only’ signature variant and omits the remote output consistently; (7) aux HTLC signatures are only attached on taproot-overlay channels; (8) CSV delay of zero is rejected; (9) sweeper fee functions enforce budget invariants and retry more safely when spend checks or starting fee rates fail. Most changes are accompanied by new unit tests.
Changed components
kvdb/etcd backenddiscovery/gossip validationwatchtower client/server wire protocolwatchtower policy (reward/sweep outputs)chanstate HTLC serializationlnwallet cooperative close (RBF and legacy)lnwallet commitment signature handlinglnwallet channel reservation constraintssweep fee bumper / sweeperInspect captured patch +1424 / −119
### chainntnfs/txnotifier.go
@@ -934,14 +934,14 @@ func (n *TxNotifier) dispatchConfDetails(
// already been dispatched, then we can skip dispatching to this
// client.
if details == nil {
- Log.Debugf("Skipped dispatching nil conf details for request "+
+ Log.Tracef("Skipped dispatching nil conf details for request "+
"%v, conf_id=%v", ntfn.ConfRequest, ntfn.ConfID)
return nil
}
if ntfn.dispatched {
- Log.Debugf("Skipped dispatched conf details for request %v "+
+ Log.Tracef("Skipped dispatched conf details for request %v "+
"conf_id=%v", ntfn.ConfRequest, ntfn.ConfID)
return nil
@@ -1337,11 +1337,8 @@ func (n *TxNotifier) updateSpendDetails(spendRequest SpendRequest,
// Return an error if the witness data is not present in the spending
// transaction.
- //
- // NOTE: if the witness stack is empty, we will do a critical log which
- // shuts down the node.
if !details.HasSpenderWitness() {
- Log.Criticalf("Found spending tx for outpoint=%v, but the "+
+ Log.Errorf("Found spending tx for outpoint=%v, but the "+
"transaction %v does not have witness",
spendRequest.OutPoint, details.SpendingTx.TxHash())
@@ -1391,7 +1388,7 @@ func (n *TxNotifier) dispatchSpendDetails(ntfn *SpendNtfn, details *SpendDetail)
// If there are no spend details to dispatch or if the notification has
// already been dispatched, then we can skip dispatching to this client.
if details == nil || ntfn.dispatched {
- Log.Debugf("Skipping dispatch of spend details(%v) for "+
+ Log.Tracef("Skipping dispatch of spend details(%v) for "+
"request %v, dispatched=%v", details, ntfn.SpendRequest,
ntfn.dispatched)
return nil
@@ -1793,7 +1790,7 @@ func (n *TxNotifier) NotifyHeight(height uint32) error {
// If the `confDetails` has already been sent before, we'll
// skip it and continue processing the next one.
if ntfn.dispatched {
- Log.Debugf("Skipped dispatched conf details for "+
+ Log.Tracef("Skipped dispatched conf details for "+
"request %v conf_id=%v", ntfn.ConfRequest,
ntfn.ConfID)
### chanstate/codec.go
@@ -18,6 +18,11 @@ import (
"github.com/lightningnetwork/lnd/tlv"
)
+// maxVarBytesLen is the largest variable length byte slice ReadElement will
+// decode. Writers of persisted state must stay within it, or the record they
+// write can never be read back.
+const maxVarBytesLen = 66000
+
var byteOrder = binary.BigEndian
// UnknownElementType is an error returned when the codec is unable to encode or
@@ -380,7 +385,7 @@ func ReadElement(r io.Reader, element interface{}) error { //nolint:funlen
}
case *[]byte:
- bytes, err := wire.ReadVarBytes(r, 0, 66000, "[]byte")
+ bytes, err := wire.ReadVarBytes(r, 0, maxVarBytesLen, "[]byte")
if err != nil {
return err
}
### chanstate/kv_commitment.go
@@ -108,6 +108,14 @@ func SerializeHtlcs(b io.Writer, htlcs ...HTLC) error {
copy(onionAndExtraData, htlc.OnionBlob[:])
copy(onionAndExtraData[lnwire.OnionPacketSize:], htlc.ExtraData)
+ // Refuse to write an HTLC that the reader would reject, as a
+ // single unreadable HTLC makes the whole channel unreadable.
+ if len(onionAndExtraData) > maxVarBytesLen {
+ return fmt.Errorf("htlc onion and extra data too "+
+ "large: %d > max %d", len(onionAndExtraData),
+ maxVarBytesLen)
+ }
+
if err := WriteElements(b,
//nolint:ll
htlc.Signature, htlc.RHash, htlc.Amt, htlc.RefundTimeout,
### chanstate/kv_commitment_test.go
@@ -0,0 +1,52 @@
+package chanstate
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/stretchr/testify/require"
+)
+
+// TestSerializeHtlcsReadableBound checks that an HTLC is only written while
+// its combined onion and extra data stays within what the reader accepts, so
+// every HTLC that is written can be read back.
+func TestSerializeHtlcsReadableBound(t *testing.T) {
+ t.Parallel()
+
+ const customType = uint64(lnwire.MinCustomRecordsTlvType + 7)
+
+ // newHtlc returns an HTLC with one custom record holding a value of
+ // the given size.
+ newHtlc := func(valueLen int) HTLC {
+ return HTLC{
+ CustomRecords: lnwire.CustomRecords{
+ customType: bytes.Repeat([]byte{1}, valueLen),
+ },
+ }
+ }
+
+ // Measure the TLV overhead of the custom record, which is the same
+ // for every value length between 253 and 65535 bytes.
+ const probeLen = 1_000
+ probe := newHtlc(probeLen)
+ require.NoError(t, serializeHtlcExtraData(&probe))
+ overhead := len(probe.ExtraData) - probeLen
+
+ // The largest value that keeps the HTLC within the reader's limit.
+ maxValueLen := maxVarBytesLen - lnwire.OnionPacketSize - overhead
+
+ // An HTLC exactly at the limit is written and reads back intact.
+ var b bytes.Buffer
+ require.NoError(t, SerializeHtlcs(&b, newHtlc(maxValueLen)))
+
+ htlcs, err := DeserializeHtlcs(&b)
+ require.NoError(t, err)
+ require.Len(t, htlcs, 1)
+ require.Len(t, htlcs[0].CustomRecords[customType], maxValueLen)
+
+ // One more byte would make the record unreadable, so it is refused.
+ b.Reset()
+ err = SerializeHtlcs(&b, newHtlc(maxValueLen+1))
+ require.ErrorContains(t, err, "too large")
+}
### discovery/gossiper.go
@@ -4041,13 +4041,6 @@ func (d *AuthenticatedGossiper) validateFundingTransaction(_ context.Context,
},
)
if err != nil {
- // Mark the edge as a zombie so we won't try to re-validate it
- // on start up.
- zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
- if zErr != nil {
- return wire.OutPoint{}, 0, nil, zErr
- }
-
return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
ErrInvalidFundingOutput, err)
}
### discovery/gossiper_test.go
@@ -743,14 +743,24 @@ func (ctx *testCtx) createAnnouncementWithoutProof(blockHeight uint32,
).Return(info.fundingTx, nil).Once()
case fundingTxPrepTypeInvalidOutput:
+ fundingTx := wire.NewMsgTx(2)
+ _, txOut, err := input.GenFundingPkScript(
+ remoteKeyPub1.SerializeCompressed(),
+ remoteKeyPriv2.PubKey().SerializeCompressed(), 1000,
+ )
+ require.NoError(ctx.t, err)
+ fundingTx.TxOut = append(fundingTx.TxOut, txOut)
+
ctx.chain.On(
"GetBlockHash", int64(blockHeight),
).Return(&chainhash.Hash{}, nil).Once()
ctx.chain.On(
"GetBlock", tmock.Anything,
).Return(
- &wire.MsgBlock{Transactions: []*wire.MsgTx{{}}}, nil,
+ &wire.MsgBlock{
+ Transactions: []*wire.MsgTx{fundingTx},
+ }, nil,
).Once()
case fundingTxPrepTypeSpent:
@@ -4657,9 +4667,8 @@ func TestChanAnnBanningChanPeer(t *testing.T) {
require.False(t, nodePeer.disconnected.Load())
}
-// TestChannelOnChainRejectionZombie tests that if we fail validating a channel
-// due to some sort of on-chain rejection (no funding transaction, or invalid
-// UTXO), then we'll mark the channel as a zombie.
+// TestChannelOnChainRejectionZombie tests which on-chain validation failures
+// mark a channel as a zombie.
func TestChannelOnChainRejectionZombie(t *testing.T) {
t.Parallel()
@@ -4676,7 +4685,9 @@ func TestChannelOnChainRejectionZombie(t *testing.T) {
// We expect this to fail as the transaction isn't present in the
// chain (nor the block).
- assertChanChainRejection(t, ctx, chanAnn, ErrNoFundingTransaction)
+ assertChanChainRejection(
+ t, ctx, chanAnn, ErrNoFundingTransaction, true,
+ )
// Next, we'll make another channel edge, but actually add it to the
// graph this time.
@@ -4687,19 +4698,22 @@ func TestChannelOnChainRejectionZombie(t *testing.T) {
// Instead now, we'll remove it from the set of UTXOs which should
// cause the spentness validation to fail.
- assertChanChainRejection(t, ctx, chanAnn, ErrChannelSpent)
+ assertChanChainRejection(t, ctx, chanAnn, ErrChannelSpent, true)
- // If we cause the funding transaction the chain to fail validation, we
- // should see similar behavior.
+ // A funding script mismatch only proves that this announcement is
+ // invalid. It must not poison the SCID for a later valid announcement.
chanAnn, err = ctx.createRemoteChannelAnnouncement(
3, withFundingTxPrep(fundingTxPrepTypeInvalidOutput),
)
require.NoError(t, err)
- assertChanChainRejection(t, ctx, chanAnn, ErrInvalidFundingOutput)
+ assertChanChainRejection(
+ t, ctx, chanAnn, ErrInvalidFundingOutput, false,
+ )
}
func assertChanChainRejection(t *testing.T, ctx *testCtx,
- edge *lnwire.ChannelAnnouncement1, expectedErr error) {
+ edge *lnwire.ChannelAnnouncement1, expectedErr error,
+ expectZombie bool) {
t.Helper()
@@ -4721,10 +4735,10 @@ func assertChanChainRejection(t *testing.T, ctx *testCtx,
err := mustProcess(t, errPromise.Future())
require.ErrorIs(t, err, expectedErr)
- // This channel should now be present in the zombie channel index.
+ // Check whether the rejection added the channel to the zombie index.
isZombie, err := ctx.router.IsZombieEdge(edge.ShortChannelID)
require.NoError(t, err)
- require.True(t, isZombie, "edge should be marked as zombie")
+ require.Equal(t, expectZombie, isZombie)
}
// TestRecoverGossipPanic tests that the finalizeGossipProcessing function
### docs/release-notes/unreleased/11440.md
@@ -0,0 +1,9 @@
+# Bug Fixes
+
+* [Fixed a number of low-level correctness
+ bugs](https://github.com/lightningnetwork/lnd/pull/11440) across wire message
+ decoding, watchtower policy, sweeper fee and retry handling, the etcd backend,
+ channel state persistence, gossip validation, channel negotiation and
+ cooperative close. Two of these change behavior operators may notice: an etcd
+ transaction now fails when a read inside it fails, instead of committing its
+ writes, and a new channel that negotiates a CSV delay of zero is rejected.
### kvdb/etcd/db.go
@@ -230,7 +230,8 @@ func (db *db) View(f func(tx walletdb.ReadTx) error, reset func()) error {
apply := func(stm STM) error {
reset()
- return f(newReadWriteTx(stm, etcdDefaultRootBucketId, nil))
+ tx := newReadWriteTx(stm, etcdDefaultRootBucketId, nil)
+ return tx.apply(func() error { return f(tx) })
}
_, err := RunSTM(db.cli, apply, db.txQueue, db.getSTMOptions()...)
@@ -252,7 +253,8 @@ func (db *db) Update(f func(tx walletdb.ReadWriteTx) error, reset func()) error
apply := func(stm STM) error {
reset()
- return f(newReadWriteTx(stm, etcdDefaultRootBucketId, nil))
+ tx := newReadWriteTx(stm, etcdDefaultRootBucketId, nil)
+ return tx.apply(func() error { return f(tx) })
}
_, err := RunSTM(db.cli, apply, db.txQueue, db.getSTMOptions()...)
### kvdb/etcd/read_error_test.go
@@ -0,0 +1,160 @@
+//go:build kvdb_etcd
+
+package etcd
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+type failingReadSTM struct {
+ STM
+ err error
+ committed bool
+ rolledBack bool
+}
+
+func (s *failingReadSTM) Get(string) ([]byte, error) {
+ return nil, s.err
+}
+
+func (s *failingReadSTM) Commit() error {
+ s.committed = true
+
+ return nil
+}
+
+func (s *failingReadSTM) Rollback() {
+ s.rolledBack = true
+}
+
+func (s *failingReadSTM) Put(string, string) {}
+
+func (s *failingReadSTM) First(string) (*KV, error) {
+ return nil, s.err
+}
+
+func (s *failingReadSTM) Last(string) (*KV, error) {
+ return nil, s.err
+}
+
+func (s *failingReadSTM) Next(string, string) (*KV, error) {
+ return nil, s.err
+}
+
+func (s *failingReadSTM) Prev(string, string) (*KV, error) {
+ return nil, s.err
+}
+
+func (s *failingReadSTM) Seek(string, string) (*KV, error) {
+ return nil, s.err
+}
+
+func TestErrorlessReadShapes(t *testing.T) {
+ readErr := errors.New("read failed")
+ tests := []struct {
+ name string
+ read func(*readWriteTx)
+ }{
+ {"top-level bucket", func(tx *readWriteTx) {
+ tx.ReadBucket([]byte("bucket"))
+ }},
+ {"nested bucket", func(tx *readWriteTx) {
+ rootBucket(tx).NestedReadBucket([]byte("bucket"))
+ }},
+ {"sequence", func(tx *readWriteTx) {
+ rootBucket(tx).Sequence()
+ }},
+ {"next sequence", func(tx *readWriteTx) {
+ _, _ = rootBucket(tx).NextSequence()
+ }},
+ {"cursor first", func(tx *readWriteTx) {
+ rootBucket(tx).ReadCursor().First()
+ }},
+ {"cursor last", func(tx *readWriteTx) {
+ rootBucket(tx).ReadCursor().Last()
+ }},
+ {"cursor next", func(tx *readWriteTx) {
+ rootBucket(tx).ReadCursor().Next()
+ }},
+ {"cursor prev", func(tx *readWriteTx) {
+ rootBucket(tx).ReadCursor().Prev()
+ }},
+ {"cursor seek", func(tx *readWriteTx) {
+ rootBucket(tx).ReadCursor().Seek([]byte("key"))
+ }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ manualSTM := &failingReadSTM{err: readErr}
+ manual := newReadWriteTx(manualSTM, "test", nil)
+ tc.read(manual)
+ require.ErrorIs(t, manual.Commit(), readErr)
+ require.False(t, manualSTM.committed)
+ require.True(t, manualSTM.rolledBack)
+
+ managedSTM := &failingReadSTM{err: readErr}
+ managed := newReadWriteTx(managedSTM, "test", nil)
+ err := managed.apply(func() error {
+ tc.read(managed)
+
+ return nil
+ })
+ require.ErrorIs(t, err, readErr)
+ require.False(t, managedSTM.committed)
+ })
+ }
+}
+
+func TestFirstReadErrorRetained(t *testing.T) {
+ first := errors.New("first")
+ second := errors.New("second")
+ stm := &failingReadSTM{err: first}
+ tx := newReadWriteTx(stm, "test", nil)
+ rootBucket(tx).Get([]byte("key"))
+ stm.err = second
+ rootBucket(tx).ReadCursor().First()
+ require.ErrorIs(t, tx.Commit(), first)
+ require.True(t, stm.rolledBack)
+ require.False(t, stm.committed)
+}
+
+func TestBucketReadErrorTransaction(t *testing.T) {
+ readErr := errors.New("injected read failure")
+ for _, tc := range []struct {
+ name string
+ err error
+ }{
+ {name: "missing"},
+ {name: "read failure", err: readErr},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ stm := &failingReadSTM{err: tc.err}
+ tx := newReadWriteTx(stm, "test", nil)
+ bucket := rootBucket(tx)
+ require.Nil(t, bucket.Get([]byte("key")))
+ require.ErrorIs(t, tx.Commit(), tc.err)
+ require.Equal(t, tc.err == nil, stm.committed)
+ require.Equal(t, tc.err != nil, stm.rolledBack)
+
+ managed := newReadWriteTx(
+ &failingReadSTM{err: tc.err}, "test", nil,
+ )
+ err := managed.apply(func() error {
+ bucket := rootBucket(managed)
+ require.Nil(t, bucket.Get([]byte("key")))
+
+ return nil
+ })
+ require.ErrorIs(t, err, tc.err)
+
+ readOnly := newReadWriteTx(
+ &failingReadSTM{err: tc.err}, "test", nil,
+ )
+ require.Nil(t, rootBucket(readOnly).Get([]byte("key")))
+ require.ErrorIs(t, readOnly.Rollback(), tc.err)
+ })
+ }
+}
### kvdb/etcd/readwrite_bucket.go
@@ -106,8 +106,7 @@ func (b *readWriteBucket) Get(key []byte) []byte {
// Fetch the associated value.
val, err := b.tx.stm.Get(string(makeValueKey(b.id, key)))
if err != nil {
- // TODO: we should return the error once the
- // kvdb inteface is extended.
+ b.tx.recordReadError(err)
return nil
}
@@ -133,8 +132,7 @@ func (b *readWriteBucket) NestedReadWriteBucket(key []byte) walletdb.ReadWriteBu
bucketKey := makeBucketKey(b.id, key)
bucketVal, err := b.tx.stm.Get(string(bucketKey))
if err != nil {
- // TODO: we should return the error once the
- // kvdb inteface is extended.
+ b.tx.recordReadError(err)
return nil
}
@@ -385,8 +383,7 @@ func (b *readWriteBucket) SetSequence(v uint64) error {
func (b *readWriteBucket) Sequence() uint64 {
val, err := b.tx.stm.Get(string(makeSequenceKey(b.id)))
if err != nil {
- // TODO: This update kvdb interface such that error
- // may be returned here.
+ b.tx.recordReadError(err)
return 0
}
### kvdb/etcd/readwrite_cursor.go
@@ -30,7 +30,7 @@ func (c *readWriteCursor) First() (key, value []byte) {
// Get the first key with the value prefix.
kv, err := c.bucket.tx.stm.First(c.prefix)
if err != nil {
- // TODO: revise this once kvdb interface supports errors
+ c.bucket.tx.recordReadError(err)
return nil, nil
}
@@ -47,7 +47,7 @@ func (c *readWriteCursor) First() (key, value []byte) {
func (c *readWriteCursor) Last() (key, value []byte) {
kv, err := c.bucket.tx.stm.Last(c.prefix)
if err != nil {
- // TODO: revise this once kvdb interface supports errors
+ c.bucket.tx.recordReadError(err)
return nil, nil
}
@@ -64,7 +64,7 @@ func (c *readWriteCursor) Last() (key, value []byte) {
func (c *readWriteCursor) Next() (key, value []byte) {
kv, err := c.bucket.tx.stm.Next(c.prefix, c.currKey)
if err != nil {
- // TODO: revise this once kvdb interface supports errors
+ c.bucket.tx.recordReadError(err)
return nil, nil
}
@@ -81,7 +81,7 @@ func (c *readWriteCursor) Next() (key, value []byte) {
func (c *readWriteCursor) Prev() (key, value []byte) {
kv, err := c.bucket.tx.stm.Prev(c.prefix, c.currKey)
if err != nil {
- // TODO: revise this once kvdb interface supports errors
+ c.bucket.tx.recordReadError(err)
return nil, nil
}
@@ -101,7 +101,7 @@ func (c *readWriteCursor) Seek(seek []byte) (key, value []byte) {
// STM will seek to the next matching key with prefix.
kv, err := c.bucket.tx.stm.Seek(c.prefix, c.prefix+string(seek))
if err != nil {
- // TODO: revise this once kvdb interface supports errors
+ c.bucket.tx.recordReadError(err)
return nil, nil
}
### kvdb/etcd/readwrite_tx.go
@@ -14,6 +14,9 @@ type readWriteTx struct {
// stm is the reference to the parent STM.
stm STM
+ // readErr records the first error from an errorless bucket read.
+ readErr error
+
// rootBucketID holds the sha256 hash of the root bucket id, which is used
// for key space spearation.
rootBucketID [bucketIDLength]byte
@@ -36,6 +39,22 @@ func newReadWriteTx(stm STM, prefix string, lock sync.Locker) *readWriteTx {
}
}
+// recordReadError retains the first failed read for the transaction.
+func (tx *readWriteTx) recordReadError(err error) {
+ if tx.readErr == nil {
+ tx.readErr = err
+ }
+}
+
+// apply runs a managed transaction callback and propagates read errors.
+func (tx *readWriteTx) apply(f func() error) error {
+ if err := f(); err != nil {
+ return err
+ }
+
+ return tx.readErr
+}
+
// rooBucket is a helper function to return the always present
// pseudo root bucket.
func rootBucket(tx *readWriteTx) *readWriteBucket {
@@ -88,7 +107,7 @@ func (tx *readWriteTx) Rollback() error {
tx.stm.Rollback()
tx.active = false
- return nil
+ return tx.readErr
}
// ReadWriteBucket opens the root bucket for read/write access. If the
@@ -122,6 +141,13 @@ func (tx *readWriteTx) Commit() error {
defer tx.lock.Unlock()
}
+ // A failed read must prevent all pending writes from committing.
+ if tx.readErr != nil {
+ tx.stm.Rollback()
+ tx.active = false
+ return tx.readErr
+ }
+
// Try committing the transaction.
if err := tx.stm.Commit(); err != nil {
return err
### lnwallet/chancloser/rbf_coop_test.go
@@ -2838,6 +2838,51 @@ func TestRbfCloseClosingNegotiationRemote(t *testing.T) {
closeHarness.assertNoStateTransitions()
})
+ t.Run("recv_offer_closee_only_reply", func(t *testing.T) {
+ terms := *closeTerms
+ terms.RemoteBalance = lnwire.NewMSatFromSatoshis(
+ absoluteFee + 10000,
+ )
+ state := &ClosingNegotiation{
+ PeerState: lntypes.Dual[AsymmetricPeerState]{
+ Remote: &RemoteCloseStart{
+ CloseChannelTerms: &terms,
+ },
+ },
+ CloseChannelTerms: &terms,
+ }
+ h := newCloser(t, &harnessCfg{
+ initialState: fn.Some[ProtocolState](state),
+ })
+ defer h.stopAndAssert()
+
+ h.expectNewCloseSig(localAddr, remoteAddr, absoluteFee, 1)
+ h.expectCloseFinalized(
+ &localSig, &remoteSig, localAddr, remoteAddr,
+ absoluteFee, 1, false,
+ )
+ matcher := func(msg *lnwire.ClosingSig) bool {
+ return msg.ClosingSigs.NoCloserClosee.IsSome() &&
+ msg.ClosingSigs.CloserAndClosee.IsNone() &&
+ msg.ClosingSigs.CloserNoClosee.IsNone()
+ }
+ h.expectMsgSent(singleMsgMatcher(matcher))
+ h.chanCloser.SendEvent(ctx, &OfferReceivedEvent{
+ SigMsg: lnwire.ClosingComplete{
+ FeeSatoshis: absoluteFee,
+ CloserScript: remoteAddr,
+ CloseeScript: localAddr,
+ ClosingSigs: lnwire.ClosingSigs{
+ NoCloserClosee: newSigTlv[tlv.TlvType2](
+ remoteWireSig,
+ ),
+ },
+ },
+ })
+ h.assertStateTransitions(&ClosingNegotiation{})
+ h.waitForMsgSent()
+ })
+
// When both CloserNoClosee AND CloserAndClosee are present (which is
// spec-compliant), the closee should select CloserAndClosee when local
// output is not dust.
### lnwallet/chancloser/rbf_coop_transitions.go
@@ -1361,7 +1361,7 @@ func selectTaprootPartialSigWithNonce(
func createClosingSigMessage(env *Environment, wireSig lnwire.Sig,
localSig input.Signature,
localScript, remoteScript lnwire.DeliveryAddress, fee btcutil.Amount,
- lockTime uint32, noClosee bool) (*lnwire.ClosingSig, error) {
+ lockTime uint32, variant closeSigVariant) (*lnwire.ClosingSig, error) {
var (
closingSigs lnwire.ClosingSigs
@@ -1384,11 +1384,16 @@ func createClosingSigMessage(env *Environment, wireSig lnwire.Sig,
wireSigWithNonce := musigSig.ToWireSig()
partialSig := wireSigWithNonce.PartialSig
- if noClosee {
+ switch variant {
+ case closeSigCloserOnly:
taprootPartialSigs.CloserNoClosee = tlv.SomeRecordT(
tlv.NewRecordT[tlv.TlvType5](partialSig),
)
- } else {
+ case closeSigCloseeOnly:
+ taprootPartialSigs.NoCloserClosee = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType6](partialSig),
+ )
+ default:
taprootPartialSigs.CloserAndClosee = tlv.SomeRecordT(
tlv.NewRecordT[tlv.TlvType7](partialSig),
)
@@ -1410,11 +1415,16 @@ func createClosingSigMessage(env *Environment, wireSig lnwire.Sig,
)
} else {
// Non-taproot: use regular signatures.
- if noClosee {
+ switch variant {
+ case closeSigCloserOnly:
closingSigs.CloserNoClosee = newSigTlv[tlv.TlvType1](
wireSig,
)
- } else {
+ case closeSigCloseeOnly:
+ closingSigs.NoCloserClosee = newSigTlv[tlv.TlvType2](
+ wireSig,
+ )
+ default:
closingSigs.CloserAndClosee = newSigTlv[tlv.TlvType3](
wireSig,
)
@@ -1877,41 +1887,50 @@ func validateSigFields(sigFields SigFieldSet, localIsDust bool) error {
return nil
}
+// closeSigVariant identifies the outputs covered by a closing signature.
+type closeSigVariant uint8
+
+const (
+ closeSigBoth closeSigVariant = iota
+ closeSigCloserOnly
+ closeSigCloseeOnly
+)
+
// selectAndExtractSig selects the appropriate signature field based on BOLT
// spec priority and extracts the signature and nonce.
func selectAndExtractSig(
fields SigFieldSet, localIsDust bool,
-) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], bool,
+) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], closeSigVariant,
error) {
// Select which field to use based on BOLT spec priority.
var (
selectedField fn.Option[SigType]
- isNoClosee bool
+ variant closeSigVariant
)
if localIsDust {
// Spec step 1: Local output is dust, use
// CloserNoClosee.
selectedField = fields.CloserNoClosee
- isNoClosee = true
+ variant = closeSigCloserOnly
} else {
// Spec step 3: Prefer CloserAndClosee if present.
if fields.CloserAndClosee.IsSome() {
selectedField = fields.CloserAndClosee
- isNoClosee = false
+ variant = closeSigBoth
} else {
// Spec step 4: Fallback to NoCloserClosee.
selectedField = fields.NoCloserClosee
- isNoClosee = false
+ variant = closeSigCloseeOnly
}
}
// If the selected field is none, this is an error.
sigType, err := selectedField.UnwrapOrErr(ErrNoSig)
if err != nil {
return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
- false, err
+ closeSigBoth, err
}
// Check if this is a taproot signature (Right side of
@@ -1931,7 +1950,7 @@ func selectAndExtractSig(
sig = partialSigToWireSig(ps.PartialSig)
})
- return sig, nonce, isNoClosee, nil
+ return sig, nonce, variant, nil
}
// extractSigAndNonceFromClosingComplete extracts signature and optional
@@ -1943,7 +1962,7 @@ func selectAndExtractSig(
func extractSigAndNonceFromClosingComplete(
msg lnwire.ClosingComplete,
localIsDust, isTaproot bool,
-) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], bool,
+) (lnwire.Sig, fn.Option[lnwire.Musig2Nonce], closeSigVariant,
error) {
// First, parse the message to extract which signature fields are
@@ -1955,33 +1974,38 @@ func extractSigAndNonceFromClosingComplete(
// have regular signatures.
switch {
case isTaproot && !fields.IsTaproot() && fields.HasAnySig():
- return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](), false,
- fmt.Errorf("taproot channel requires taproot " +
- "signatures, got regular signatures")
+ return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
+ closeSigBoth, fmt.Errorf(
+ "taproot channel requires taproot " +
+ "signatures, got regular signatures",
+ )
case !isTaproot && fields.IsTaproot():
- return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](), false,
- fmt.Errorf("non-taproot channel requires regular " +
- "signatures, got taproot signatures")
+ return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
+ closeSigBoth, fmt.Errorf(
+ "non-taproot channel requires regular " +
+ "signatures, got taproot signatures",
+ )
}
// Next, validate that the parsed fields conform to BOLT spec
// requirements based on our (closee's) output dust status.
if err := validateSigFields(fields, localIsDust); err != nil {
- return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](), false, err
+ return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
+ closeSigBoth, err
}
// Finally, select and extract the appropriate signature
// based on BOLT spec priority.
- sig, nonce, isNoClosee, err := selectAndExtractSig(
+ sig, nonce, variant, err := selectAndExtractSig(
fields, localIsDust,
)
if err != nil {
return lnwire.Sig{}, fn.None[lnwire.Musig2Nonce](),
- false, err
+ closeSigBoth, err
}
- return sig, nonce, isNoClosee, nil
+ return sig, nonce, variant, nil
}
// ProcessEvent implements the state transition function for the
@@ -2009,9 +2033,10 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
// Extract the signature and JIT nonce from the ClosingComplete
// message. This function parses, validates, and selects the
// appropriate signature per BOLT spec.
- sig, jitNonce, noClosee, err := extractSigAndNonceFromClosingComplete( //nolint:ll
- msg.SigMsg, l.LocalAmtIsDust(), env.IsTaproot(),
- )
+ sig, jitNonce, variant, err :=
+ extractSigAndNonceFromClosingComplete(
+ msg.SigMsg, l.LocalAmtIsDust(), env.IsTaproot(),
+ )
if err != nil {
return nil, err
}
@@ -2022,6 +2047,13 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
lnwallet.WithCustomPayer(lntypes.Remote),
}
+ if variant == closeSigCloseeOnly {
+ chanOpts = append(
+ chanOpts,
+ lnwallet.WithOmittedRemoteCloseOutput(),
+ )
+ }
+
var remoteSig input.Signature
// For taproot channels, add MusigSession options if available.
@@ -2034,7 +2066,8 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
// This must happen before ProposalClosingOpts() which
// requires the nonce to be set.
remoteSig, err = processRemoteTaprootSig(
- env, msg.SigMsg, jitNonce, noClosee,
+ env, msg.SigMsg, jitNonce,
+ variant == closeSigCloserOnly,
)
if err != nil {
return nil, err
@@ -2110,7 +2143,7 @@ func (l *RemoteCloseStart) ProcessEvent(event ProtocolEvent, env *Environment,
closingSigMsg, err := createClosingSigMessage(
env, wireSig, localSig, l.LocalDeliveryScript,
l.RemoteDeliveryScript, msg.SigMsg.FeeSatoshis,
- msg.SigMsg.LockTime, noClosee,
+ msg.SigMsg.LockTime, variant,
)
if err != nil {
return nil, err
### lnwallet/chancloser/rbf_reply_variant_test.go
@@ -0,0 +1,160 @@
+package chancloser
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/btcsuite/btcd/wire/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lnwallet"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+type closeReplyCase struct {
+ name string
+ variant closeSigVariant
+ local, remote btcutil.Amount
+}
+
+func TestCloseeReplyVariants(t *testing.T) {
+ for _, taproot := range []bool{false, true} {
+ for _, tc := range []closeReplyCase{
+ {"both", closeSigBoth, 10000, 10000},
+ {"closer only", closeSigCloserOnly, 1, 10000},
+ {"closee only", closeSigCloseeOnly, 10000, 1},
+ } {
+ name := tc.name + map[bool]string{
+ true: " taproot", false: " legacy",
+ }[taproot]
+ t.Run(name, func(t *testing.T) {
+ testCloseeReplyVariant(t, tc, taproot)
+ })
+ }
+ }
+}
+
+func testCloseeReplyVariant(t *testing.T, tc closeReplyCase, taproot bool) {
+ var scalar btcec.ModNScalar
+ scalar.SetInt(1)
+ key, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ partial := musig2.NewPartialSignature(&scalar, key.PubKey())
+ localPartial := lnwallet.NewMusigPartialSig(
+ &partial, lnwire.Musig2Nonce{}, lnwire.Musig2Nonce{}, nil,
+ fn.None[chainhash.Hash](),
+ )
+ remotePartial := lnwire.PartialSigWithNonce{
+ PartialSig: lnwire.PartialSig{Sig: scalar},
+ Nonce: lnwire.Musig2Nonce{1, 2, 3},
+ }
+
+ msg := lnwire.ClosingComplete{}
+ if taproot {
+ switch tc.variant {
+ case closeSigBoth:
+ msg.TaprootClosingSigs.CloserAndClosee =
+ newPartialSigWithNonceTlv[tlv.TlvType7](
+ remotePartial,
+ )
+ case closeSigCloserOnly:
+ msg.TaprootClosingSigs.CloserNoClosee =
+ newPartialSigWithNonceTlv[tlv.TlvType5](
+ remotePartial,
+ )
+ case closeSigCloseeOnly:
+ msg.TaprootClosingSigs.NoCloserClosee =
+ newPartialSigWithNonceTlv[tlv.TlvType6](
+ remotePartial,
+ )
+ }
+ } else {
+ switch tc.variant {
+ case closeSigBoth:
+ msg.ClosingSigs.CloserAndClosee =
+ newSigTlv[tlv.TlvType3](
+ remoteWireSig,
+ )
+ case closeSigCloserOnly:
+ msg.ClosingSigs.CloserNoClosee =
+ newSigTlv[tlv.TlvType1](
+ remoteWireSig,
+ )
+ case closeSigCloseeOnly:
+ msg.ClosingSigs.NoCloserClosee =
+ newSigTlv[tlv.TlvType2](
+ remoteWireSig,
+ )
+ }
+ }
+ dust := lnwallet.DustLimitForSize(len(localAddr))
+ _, _, variant, err := extractSigAndNonceFromClosingComplete(
+ msg, tc.local < dust, taproot,
+ )
+ require.NoError(t, err)
+ require.Equal(t, tc.variant, variant)
+
+ tx, err := lnwallet.CreateCooperativeCloseTx(
+ wire.TxIn{}, dust, dust, tc.local, tc.remote,
+ localAddr, remoteAddr,
+ )
+ require.NoError(t, err)
+ haveLocal, haveRemote := false, false
+ for _, out := range tx.TxOut {
+ if string(out.PkScript) == string(localAddr) {
+ haveLocal = true
+ }
+ if string(out.PkScript) == string(remoteAddr) {
+ haveRemote = true
+ }
+ }
+ require.Equal(t, tc.variant != closeSigCloserOnly, haveLocal)
+ require.Equal(t, tc.variant != closeSigCloseeOnly, haveRemote)
+
+ env := &Environment{}
+ if taproot {
+ env.LocalMusigSession = newMockMusigSession()
+ env.RemoteMusigSession = newMockMusigSession()
+ }
+ reply, err := createClosingSigMessage(
+ env, localSigWire, localPartial, localAddr,
+ remoteAddr, 0, 0, variant,
+ )
+ require.NoError(t, err)
+
+ // The mock session's nonce is not a valid curve point.
+ if taproot {
+ var nonce lnwire.Musig2Nonce
+ copy(nonce[:33], key.PubKey().SerializeCompressed())
+ copy(nonce[33:], key.PubKey().SerializeCompressed())
+ reply.NextCloseeNonce = newNonceTlv(nonce)
+ }
+ var encoded bytes.Buffer
+ require.NoError(t, reply.Encode(&encoded, 0))
+ var decoded lnwire.ClosingSig
+ require.NoError(t, decoded.Decode(&encoded, 0))
+ result, _ := validateAndExtractSigAndNonce(decoded, taproot)
+ _, err = result.Unpack()
+ require.NoError(t, err)
+ reply = &decoded
+ if taproot {
+ require.Equal(t, variant == closeSigBoth,
+ reply.TaprootPartialSigs.CloserAndClosee.IsSome())
+ require.Equal(t, variant == closeSigCloserOnly,
+ reply.TaprootPartialSigs.CloserNoClosee.IsSome())
+ require.Equal(t, variant == closeSigCloseeOnly,
+ reply.TaprootPartialSigs.NoCloserClosee.IsSome())
+ } else {
+ require.Equal(t, variant == closeSigBoth,
+ reply.ClosingSigs.CloserAndClosee.IsSome())
+ require.Equal(t, variant == closeSigCloserOnly,
+ reply.ClosingSigs.CloserNoClosee.IsSome())
+ require.Equal(t, variant == closeSigCloseeOnly,
+ reply.ClosingSigs.NoCloserClosee.IsSome())
+ }
+}
### lnwallet/channel.go
@@ -5277,7 +5277,10 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel,
SigHash: sigHash,
})
- if len(auxHtlcSigs) > i {
+ // Only taproot overlay channels carry aux signatures, so we
+ // don't attach or persist aux data a peer sends for any other
+ // channel type. This matches the per-HTLC count check below.
+ if chanType.HasTapscriptRoot() && len(auxHtlcSigs) > i {
auxSig := auxHtlcSigs[i]
auxVerifyJob := NewAuxVerifyJob(
auxSig, *keyRing, incoming,
@@ -8711,6 +8714,8 @@ type chanCloseOpt struct {
customLockTime fn.Option[uint32]
customPayer fn.Option[lntypes.ChannelParty]
+
+ omitRemoteOutput bool
}
// ChanCloseOpt is a closure type that cen be used to modify the set of default
@@ -8731,6 +8736,13 @@ func WithCoopCloseMusigSession(session *MusigSession) ChanCloseOpt {
}
}
+// WithOmittedRemoteCloseOutput omits the remote party's closing output.
+func WithOmittedRemoteCloseOutput() ChanCloseOpt {
+ return func(opts *chanCloseOpt) {
+ opts.omitRemoteOutput = true
+ }
+}
+
// WithExtraCloseOutputs can be used to add extra outputs to the cooperative
// transaction.
func WithExtraCloseOutputs(extraOutputs []CloseOutput) ChanCloseOpt {
@@ -8827,6 +8839,9 @@ func (lc *LightningChannel) CreateCloseProposal(proposedFee btcutil.Amount,
opts.extraCloseOutputs,
))
}
+ if opts.omitRemoteOutput {
+ closeTxOpts = append(closeTxOpts, withOmittedRemoteTxOutput())
+ }
if opts.customSort != nil {
closeTxOpts = append(
closeTxOpts, WithCustomTxSort(opts.customSort),
@@ -8941,6 +8956,9 @@ func (lc *LightningChannel) CompleteCooperativeClose(
opts.extraCloseOutputs,
))
}
+ if opts.omitRemoteOutput {
+ closeTxOpts = append(closeTxOpts, withOmittedRemoteTxOutput())
+ }
if opts.customSort != nil {
closeTxOpts = append(
closeTxOpts, WithCustomTxSort(opts.customSort),
@@ -9725,6 +9743,8 @@ type closeTxOpts struct {
customSequence fn.Option[uint32]
customLockTime fn.Option[uint32]
+
+ omitRemoteOutput bool
}
// defaultCloseTxOpts returns a closeTxOpts struct with default values.
@@ -9738,6 +9758,12 @@ func defaultCloseTxOpts() closeTxOpts {
// transaction is created.
type CloseTxOpt func(*closeTxOpts)
+func withOmittedRemoteTxOutput() CloseTxOpt {
+ return func(o *closeTxOpts) {
+ o.omitRemoteOutput = true
+ }
+}
+
// WithRBFCloseTx signals that the cooperative close tx should signal RBF.
func WithRBFCloseTx() CloseTxOpt {
return func(o *closeTxOpts) {
@@ -9835,7 +9861,7 @@ func CreateCooperativeCloseTx(fundingTxIn wire.TxIn,
}
var remoteOutputIdx fn.Option[int]
- haveRemoteOutput := theirBalance >= remoteDust
+ haveRemoteOutput := theirBalance >= remoteDust && !opts.omitRemoteOutput
if haveRemoteOutput {
// If a party's script is an OP_RETURN, then we set their
// balance to zero.
### lnwallet/channel_test.go
@@ -12622,6 +12622,37 @@ func TestAuxSigNotRequiredOnPlainChannel(t *testing.T) {
))
}
+// TestAuxSigIgnoredOnPlainChannel tests that aux signatures sent for a channel
+// without the tapscript root bit are neither attached to the HTLC nor stored
+// with it. Only overlay channels use aux signatures, so the HTLC records of a
+// plain channel must not carry any.
+func TestAuxSigIgnoredOnPlainChannel(t *testing.T) {
+ t.Parallel()
+
+ plainChanType := taprootOverlayChanType &^ channeldb.TapscriptRootBit
+ aliceChannel, bobChannel := createAuxHtlcChannels(t, plainChanType, 1)
+
+ mockAuxSignerWithSigs(bobChannel, 1)
+
+ aliceNewCommit, err := aliceChannel.SignNextCommitment(ctxb)
+ require.NoError(t, err, "unable to sign commitment")
+
+ require.NoError(t, bobChannel.ReceiveNewCommitment(
+ aliceNewCommit.CommitSigs,
+ ))
+
+ // Revoking persists the new local commitment, whose HTLC must not
+ // carry the aux signature.
+ _, _, _, err = bobChannel.RevokeCurrentCommitment()
+ require.NoError(t, err, "unable to revoke commitment")
+
+ htlcs := bobChannel.channelState.LocalCommitment.Htlcs
+ require.Len(t, htlcs, 1)
+
+ sigType := uint64(htlcCustomSigType.TypeVal())
+ require.NotContains(t, htlcs[0].CustomRecords, sigType)
+}
+
// TestAuxSigNotRequiredWithoutAuxSigner tests that an overlay channel on a node
// with no aux signer configured still accepts commitments carrying no aux
// signatures. Without a signer there is nothing that could consume them, so
### lnwallet/close_omitted_output_test.go
@@ -0,0 +1,49 @@
+package lnwallet
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/btcsuite/btcd/wire/v2"
+ "github.com/lightningnetwork/lnd/channeldb"
+ "github.com/stretchr/testify/require"
+)
+
+// TestCooperativeCloseOmittedRemoteOutput verifies both signatures cover the
+// same transaction when the closer omits its non-dust output.
+func TestCooperativeCloseOmittedRemoteOutput(t *testing.T) {
+ alice, bob, err := CreateTestChannels(
+ t, channeldb.SingleFunderTweaklessBit,
+ )
+ require.NoError(t, err)
+ aliceScript, bobScript := bobsPrivKey, testHdSeed[:]
+ fee := btcutil.Amount(10000)
+ omitAlice := WithCustomCoopSort(func(tx *wire.MsgTx) error {
+ var outs []*wire.TxOut
+ for _, out := range tx.TxOut {
+ if !bytes.Equal(out.PkScript, aliceScript) {
+ outs = append(outs, out)
+ }
+ }
+ tx.TxOut = outs
+
+ return nil
+ })
+ aliceSig, aliceTx, _, err := alice.CreateCloseProposal(
+ fee, aliceScript, bobScript, omitAlice,
+ )
+ require.NoError(t, err)
+ bobSig, bobTx, _, err := bob.CreateCloseProposal(
+ fee, bobScript, aliceScript, WithOmittedRemoteCloseOutput(),
+ )
+ require.NoError(t, err)
+ require.Len(t, aliceTx.TxOut, 1)
+ require.Equal(t, aliceTx.TxHash(), bobTx.TxHash())
+ tx, _, err := bob.CompleteCooperativeClose(
+ bobSig, aliceSig, bobScript, aliceScript, fee,
+ WithOmittedRemoteCloseOutput(),
+ )
+ require.NoError(t, err)
+ require.Equal(t, aliceTx.TxHash(), tx.TxHash())
+}
### lnwallet/errors.go
@@ -68,6 +68,14 @@ func ErrCsvDelayTooLarge(remoteDelay, maxDelay uint16) ReservationError {
}
}
+// ErrCsvDelayZero returns an error indicating that a CSV delay of zero was
+// proposed.
+func ErrCsvDelayZero() ReservationError {
+ return ReservationError{
+ errors.New("CSV delay must be greater than zero"),
+ }
+}
+
// ErrChanReserveTooSmall returns an error indicating that the channel reserve
// the remote is requiring is too small to be accepted.
func ErrChanReserveTooSmall(reserve, dustLimit btcutil.Amount) ReservationError {
### lnwallet/reservation.go
@@ -1020,6 +1020,12 @@ func VerifyConstraints(bounds *channeldb.ChannelStateBounds,
commitParams *channeldb.CommitmentParams, maxLocalCSVDelay uint16,
channelCapacity btcutil.Amount) error {
+ // A zero CSV delay leaves no time to respond to a breach of the
+ // commitment it applies to, so we never accept or propose one.
+ if commitParams.CsvDelay == 0 {
+ return ErrCsvDelayZero()
+ }
+
// Fail if the csv delay for our funds exceeds our maximum.
if commitParams.CsvDelay > maxLocalCSVDelay {
return ErrCsvDelayTooLarge(
### lnwallet/reservation_test.go
@@ -7,6 +7,7 @@ import (
"github.com/btcsuite/btcd/btcutil/v2"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/chanstate"
+ "github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/stretchr/testify/require"
)
@@ -435,3 +436,69 @@ func TestValidateInitialBalancesUnionIsAdditive(t *testing.T) {
"usability check adds, so it did "+
"not exercise the property")
}
+
+// TestVerifyConstraintsCsvDelay checks that a CSV delay is accepted only when
+// it is non-zero and within our maximum.
+func TestVerifyConstraintsCsvDelay(t *testing.T) {
+ t.Parallel()
+
+ const (
+ capacity = btcutil.Amount(1_000_000)
+ maxDelay = uint16(2016)
+ )
+
+ dustLimit := DustLimitForSize(input.UnknownWitnessSize)
+ bounds := &channeldb.ChannelStateBounds{
+ ChanReserve: capacity / 100,
+ MaxPendingAmount: lnwire.NewMSatFromSatoshis(capacity),
+ MinHTLC: 1,
+ MaxAcceptedHtlcs: input.MaxHTLCNumber / 2,
+ }
+
+ tests := []struct {
+ name string
+ delay uint16
+ err string
+ }{
+ {
+ name: "zero",
+ delay: 0,
+ err: "CSV delay must be greater than zero",
+ },
+ {
+ name: "one",
+ delay: 1,
+ },
+ {
+ name: "max",
+ delay: maxDelay,
+ },
+ {
+ name: "above max",
+ delay: maxDelay + 1,
+ err: "CSV delay too large",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ params := &channeldb.CommitmentParams{
+ DustLimit: dustLimit,
+ CsvDelay: tc.delay,
+ }
+
+ err := VerifyConstraints(
+ bounds, params, maxDelay, capacity,
+ )
+ if tc.err == "" {
+ require.NoError(t, err)
+
+ return
+ }
+
+ require.ErrorContains(t, err, tc.err)
+ require.ErrorAs(t, err, &ReservationError{})
+ })
+ }
+}
### sweep/fee_budget_retry_test.go
@@ -0,0 +1,111 @@
+package sweep
+
+import (
+ "testing"
+
+ "github.com/btcsuite/btcd/wire/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/input"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
+ "github.com/stretchr/testify/require"
+)
+
+// TestHighStartingFeeRateRetriesWithEstimator ensures an infeasible starting
+// rate is cleared before the next sweep attempt.
+func TestHighStartingFeeRateRetriesWithEstimator(t *testing.T) {
+ tp, _ := createTestPublisher(t)
+ req := createTestBumpRequest()
+ start := chainfee.SatPerKWeight(1200)
+ req.StartingFeeRate = fn.Some(start)
+ r := &monitorRecord{requestID: 1, req: req}
+
+ subscriber := make(chan *BumpResult, 1)
+ tp.subscriberChans.Store(r.requestID, subscriber)
+ tp.records.Store(r.requestID, r)
+ _, err := NewLinearFeeFunction(
+ 1000, 6, &chainfee.MockEstimator{}, req.StartingFeeRate,
+ )
+ require.ErrorIs(t, err, errStartingFeeRateTooHigh)
+ tp.handleInitialTxError(r, err)
+ result := <-subscriber
+ require.Equal(t, TxFailed, result.Event)
+
+ s := New(&UtxoSweeperConfig{})
+ inp := req.Inputs[0]
+ op := inp.OutPoint()
+ s.inputs[op] = &SweeperInput{
+ Input: inp, state: PendingPublish,
+ params: Params{StartingFeeRate: req.StartingFeeRate},
+ }
+ set := &MockInputSet{}
+ set.On("Inputs").Return(req.Inputs).Once()
+
+ err = s.handleBumpEvent(&bumpResp{set: set, result: result})
+ require.NoError(t, err)
+ require.Equal(t, PublishFailed, s.inputs[op].state)
+ require.Equal(
+ t, fn.None[chainfee.SatPerKWeight](),
+ s.inputs[op].params.StartingFeeRate,
+ )
+
+ estimator := &chainfee.MockEstimator{}
+ estimator.On(
+ "EstimateFeePerKW", uint32(6),
+ ).Return(chainfee.SatPerKWeight(700), nil).Once()
+ estimator.On("RelayFeePerKW").Return(
+ chainfee.SatPerKWeight(250),
+ ).Once()
+ fee, err := NewLinearFeeFunction(
+ 1000, 6, estimator, s.inputs[op].params.StartingFeeRate,
+ )
+ require.NoError(t, err)
+ require.Equal(t, chainfee.SatPerKWeight(700), fee.FeeRate())
+ estimator.AssertExpectations(t)
+ set.AssertExpectations(t)
+}
+
+// TestUnknownSpendRetriesWithEstimatedFee checks an infeasible starting hint
+// does not prevent retrying the remaining inputs.
+func TestUnknownSpendRetriesWithEstimatedFee(t *testing.T) {
+ tp, mocks := createTestPublisher(t)
+ first := createTestInput(1000000, input.WitnessKeyHash)
+ second := createTestInput(1000000, input.WitnessKeyHash)
+ start := chainfee.SatPerKWeight(1200)
+ req := &BumpRequest{
+ Inputs: []input.Input{&first, &second},
+ DeliveryAddress: changePkScript,
+ Budget: 10000,
+ MaxFeeRate: 1000,
+ DeadlineHeight: 6,
+ StartingFeeRate: fn.Some(start),
+ }
+ spend := &wire.MsgTx{}
+ spent := map[wire.OutPoint]*wire.MsgTx{first.OutPoint(): spend}
+ r := &monitorRecord{requestID: 1, req: req, spentInputs: spent}
+ mocks.estimator.On("EstimateFeePerKW", uint32(6)).Return(
+ chainfee.SatPerKWeight(700), nil,
+ ).Once()
+ mocks.estimator.On("RelayFeePerKW").Return(
+ chainfee.SatPerKWeight(250),
+ ).Once()
+
+ result := tp.createUnknownSpentBumpResult(r)
+ require.Equal(t, TxUnknownSpend, result.Event)
+ require.ErrorIs(t, result.Err, ErrUnknownSpent)
+ require.Equal(t, spent, result.SpentInputs)
+ require.Equal(t, chainfee.SatPerKWeight(760), result.FeeRate)
+ require.Equal(t, fn.Some(start), req.StartingFeeRate)
+ require.Nil(t, r.feeFunction)
+
+ // Other estimator failures remain fatal and are not retried here.
+ tp2, mocks2 := createTestPublisher(t)
+ otherReq := *req
+ otherReq.StartingFeeRate = fn.None[chainfee.SatPerKWeight]()
+ other := &monitorRecord{req: &otherReq, spentInputs: spent}
+ mocks2.estimator.On("EstimateFeePerKW", uint32(6)).Return(
+ chainfee.SatPerKWeight(0), errDummy,
+ ).Once()
+ failure := tp2.createUnknownSpentBumpResult(other)
+ require.Equal(t, TxFatal, failure.Event)
+ require.ErrorIs(t, failure.Err, errDummy)
+}
### sweep/fee_bumper.go
@@ -47,6 +47,9 @@ var (
// ErrInputMissing is returned when a given input no longer exists,
// e.g., spending from an orphan tx.
ErrInputMissing = errors.New("input no longer exists")
+
+ // errSpendCheckFailed identifies an inconclusive spend check.
+ errSpendCheckFailed = errors.New("spend check failed")
)
var (
@@ -698,9 +701,20 @@ func (t *TxPublisher) createAndCheckTx(r *monitorRecord) (*sweepTxCtx, error) {
// in another tx, or the input is referencing an orphan. When the input is
// spent, it will be handled via the TxUnknownSpend flow by creating a
// TxUnknownSpend bump result, otherwise, a TxFatal bump result is returned.
+// A failed spend check yields a retryable TxFailed result.
func (t *TxPublisher) handleMissingInputs(r *monitorRecord) *BumpResult {
// Get the spending txns.
- spends := t.getSpentInputs(r)
+ spends, err := t.getSpentInputs(r)
+ if err != nil {
+ return &BumpResult{
+ Event: TxFailed,
+ Tx: r.tx,
+ requestID: r.requestID,
+ Err: fmt.Errorf(
+ "%w: %w", errSpendCheckFailed, err,
+ ),
+ }
+ }
// Attach the spending txns.
r.spentInputs = spends
@@ -992,7 +1006,18 @@ func (t *TxPublisher) processRecords() {
log.Tracef("Checking monitor recordID=%v", requestID)
// Check whether the inputs have already been spent.
- spends := t.getSpentInputs(r)
+ //
+ // An inconclusive check doesn't show that any input was spent,
+ // so we proceed as if none were. Skipping the record instead
+ // would stop fee bumps for as long as the check keeps failing,
+ // which a deadline sweep can't afford. If an input was in fact
+ // spent, the mempool rejects the attempt for missing inputs
+ // and the missing input handling takes over.
+ spends, err := t.getSpentInputs(r)
+ if err != nil {
+ log.Errorf("Unable to check spends for record %v, "+
+ "proceeding as unspent: %v", requestID, err)
+ }
// If the any of the inputs has been spent, the record will be
// marked as failed or confirmed.
@@ -1119,9 +1144,10 @@ func (t *TxPublisher) handleInitialTxError(r *monitorRecord, err error) {
case errors.Is(err, ErrTxNoOutput):
result.Event = TxFailed
- // When the error is due to zero fee rate delta, we'll send a TxFailed
- // so these inputs can be retried in the next block.
- case errors.Is(err, ErrZeroFeeRateDelta):
+ // An infeasible starting rate or zero fee rate delta is retryable.
+ // Do not try to initialize the same fee function again here.
+ case errors.Is(err, ErrZeroFeeRateDelta),
+ errors.Is(err, errStartingFeeRateTooHigh):
result.Event = TxFailed
// When the error is due to budget being used up, we'll send a TxFailed
@@ -1431,9 +1457,10 @@ func (t *TxPublisher) isUnknownSpent(r *monitorRecord,
// getSpentInputs performs a non-blocking read on the spending subscriptions to
// see whether any of the monitored inputs has been spent. A map of inputs with
-// their spending txns are returned if found.
+// their spending txns are returned if found. An error indicates that the
+// inputs could not be checked reliably.
func (t *TxPublisher) getSpentInputs(
- r *monitorRecord) map[wire.OutPoint]*wire.MsgTx {
+ r *monitorRecord) (map[wire.OutPoint]*wire.MsgTx, error) {
// Create a slice to record the inputs spent.
spentInputs := make(map[wire.OutPoint]*wire.MsgTx, len(r.req.Inputs))
@@ -1461,10 +1488,10 @@ func (t *TxPublisher) getSpentInputs(
&op, inp.SignDesc().Output.PkScript, heightHint,
)
if err != nil {
- log.Criticalf("Failed to register spend ntfn for "+
- "input=%v: %v", op, err)
-
- return nil
+ return nil, fmt.Errorf(
+ "register spend notification for %v: %w",
+ op, err,
+ )
}
// Remove the subscription when exit.
@@ -1474,9 +1501,9 @@ func (t *TxPublisher) getSpentInputs(
select {
case spend, ok := <-spendEvent.Spend:
if !ok {
- log.Debugf("Spend ntfn for %v canceled", op)
-
- continue
+ return nil, fmt.Errorf(
+ "spend notification for %v closed", op,
+ )
}
spendingTx := spend.SpendingTx
@@ -1492,7 +1519,7 @@ func (t *TxPublisher) getSpentInputs(
}
}
- return spentInputs
+ return spentInputs, nil
}
// calcCurrentConfTarget calculates the current confirmation target based on
@@ -1951,13 +1978,15 @@ func (t *TxPublisher) calculateRetryFeeRate(
// the fee rate data so the sweeper can pick up where we left off.
if feeFunc == nil {
f, err := t.initializeFeeFunction(r.req)
+ if errors.Is(err, errStartingFeeRateTooHigh) {
+ // Retry using an estimated rate without modifying the
+ // monitored record's request.
+ req := *r.req
+ req.StartingFeeRate = fn.None[chainfee.SatPerKWeight]()
+ f, err = t.initializeFeeFunction(&req)
+ }
- // TODO(yy): The only error we would receive here is when the
- // pkScript is not recognized by the weightEstimator. What we
- // should do instead is to check the pkScript immediately after
- // receiving a sweep request so we don't need to check it again,
- // which will also save us from error checking from several
- // callsites.
+ // Propagate any remaining initialization error to the caller.
if err != nil {
log.Errorf("Failed to create fee func for record %v: "+
"%v", r.requestID, err)
### sweep/fee_bumper_test.go
@@ -2323,7 +2323,8 @@ func TestHasInputsSpent(t *testing.T) {
}
// Call the method under test.
- result := tp.getSpentInputs(record)
+ result, err := tp.getSpentInputs(record)
+ require.NoError(t, err)
// Assert the expected map is created.
expected := map[wire.OutPoint]*wire.MsgTx{
@@ -2332,6 +2333,73 @@ func TestHasInputsSpent(t *testing.T) {
require.Equal(t, expected, result)
}
+// TestSpendNotificationFailure ensures failed checks never classify inputs.
+func TestSpendNotificationFailure(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ closed bool
+ }{
+ {name: "registration", err: fmt.Errorf("registration failed")},
+ {
+ name: "shutdown",
+ err: chainntnfs.ErrChainNotifierShuttingDown,
+ },
+ {
+ name: "closed", closed: true,
+ err: chainntnfs.ErrChainNotifierShuttingDown,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tp, m := createTestPublisher(t)
+ req := createTestBumpRequest()
+ op := req.Inputs[0].OutPoint()
+ var event *chainntnfs.SpendEvent
+ err := tc.err
+ if tc.closed {
+ spends := make(chan *chainntnfs.SpendDetail)
+ close(spends)
+ event = &chainntnfs.SpendEvent{
+ Spend: spends, Cancel: func() {},
+ }
+ err = nil
+ }
+ m.notifier.On("RegisterSpendNtfn", &op, mock.Anything,
+ mock.Anything).Return(event, err).Twice()
+ r := &monitorRecord{requestID: 1, req: req}
+ result := tp.handleMissingInputs(r)
+ require.Equal(t, TxFailed, result.Event)
+ if tc.closed {
+ require.ErrorContains(t, result.Err, "closed")
+ } else {
+ require.ErrorIs(t, result.Err, tc.err)
+ }
+
+ // An inconclusive check during record processing must
+ // not stop a broadcast record from being fee bumped.
+ r.tx = &wire.MsgTx{LockTime: 1}
+ r.feeFunction = m.feeFunc
+
+ bumped := make(chan struct{})
+ m.feeFunc.On("IncreaseFeeRate", mock.Anything).Run(
+ func(mock.Arguments) { close(bumped) },
+ ).Return(false, nil).Once()
+
+ tp.records.Store(r.requestID, r)
+ tp.processRecords()
+
+ select {
+ case <-bumped:
+ case <-time.After(time.Second):
+ t.Fatal("record was not fee bumped")
+ }
+
+ _, found := tp.records.Load(r.requestID)
+ require.True(t, found)
+ })
+ }
+}
+
// createTestSpendEvent creates a SpendEvent which places the specified tx in
// the channel, which can be read by a spending subscriber.
func createTestSpendEvent(tx *wire.MsgTx) *chainntnfs.SpendEvent {
### sweep/fee_function.go
@@ -17,6 +17,12 @@ var (
// ErrZeroFeeRateDelta is returned when the fee rate delta is zero.
ErrZeroFeeRateDelta = errors.New("fee rate delta is zero")
+
+ // errStartingFeeRateTooHigh indicates the initial rate exceeds the
+ // budget.
+ errStartingFeeRateTooHigh = errors.New(
+ "starting fee rate exceeds budget",
+ )
)
// mSatPerKWeight represents a fee rate in msat/kw.
@@ -154,6 +160,14 @@ func NewLinearFeeFunction(maxFeeRate chainfee.SatPerKWeight,
return nil, fmt.Errorf("estimate initial fee rate: %w", err)
}
+ // A starting fee above the budget cannot produce an increasing curve.
+ if start > l.endingFeeRate {
+ return nil, fmt.Errorf(
+ "%w: starting fee rate %v exceeds maximum %v",
+ errStartingFeeRateTooHigh, start, l.endingFeeRate,
+ )
+ }
+
// Calculate how much fee rate should be increased per block.
end := l.endingFeeRate
@@ -293,9 +307,9 @@ func (l *LinearFeeFunction) estimateFeeRate(
}
// If the conf target is greater or equal to the max allowed value
- // (1008), we will use the min relay fee instead.
+ // (1008), use the min relay fee capped by the budget.
if confTarget >= chainfee.MaxBlockTarget {
- minFeeRate := l.estimator.RelayFeePerKW()
+ minFeeRate := min(l.estimator.RelayFeePerKW(), l.endingFeeRate)
log.Infof("Conf target %v is greater than max block target, "+
"using min relay fee rate %v", confTarget, minFeeRate)
### sweep/fee_function_invariants_test.go
@@ -0,0 +1,64 @@
+package sweep
+
+import (
+ "testing"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
+ "github.com/stretchr/testify/require"
+)
+
+func TestLinearFeeFunctionBudgetInvariant(t *testing.T) {
+ maxRate := chainfee.SatPerKWeight(1000)
+ estimator := &chainfee.MockEstimator{}
+ _, err := NewLinearFeeFunction(
+ maxRate, 3, estimator, fn.Some(maxRate+1),
+ )
+ require.ErrorIs(t, err, errStartingFeeRateTooHigh)
+
+ f, err := NewLinearFeeFunction(
+ maxRate, 5, estimator, fn.Some(chainfee.SatPerKWeight(500)),
+ )
+ require.NoError(t, err)
+ require.Equal(t, chainfee.SatPerKWeight(500), f.FeeRate())
+ for range 4 {
+ previous := f.FeeRate()
+ _, err := f.Increment()
+ require.NoError(t, err)
+ require.GreaterOrEqual(t, f.FeeRate(), previous)
+ require.LessOrEqual(t, f.FeeRate(), maxRate)
+ }
+ require.Equal(t, maxRate, f.FeeRate())
+
+ // At the deadline the budget maximum is used even with a higher hint.
+ f, err = NewLinearFeeFunction(
+ maxRate, 1, estimator, fn.Some(maxRate+1),
+ )
+ require.NoError(t, err)
+ require.Equal(t, maxRate, f.FeeRate())
+}
+
+func TestStartingFeeRateTooHighIsRetryable(t *testing.T) {
+ tp, _ := createTestPublisher(t)
+ r := &monitorRecord{requestID: 1}
+ subscriber := make(chan *BumpResult, 1)
+ tp.subscriberChans.Store(r.requestID, subscriber)
+ tp.records.Store(r.requestID, r)
+ tp.handleInitialTxError(r, errStartingFeeRateTooHigh)
+ result := <-subscriber
+ require.Equal(t, TxFailed, result.Event)
+ require.ErrorIs(t, result.Err, errStartingFeeRateTooHigh)
+}
+
+func TestLinearFeeFunctionRelayAboveBudget(t *testing.T) {
+ estimator := &chainfee.MockEstimator{}
+ estimator.On("RelayFeePerKW").Return(
+ chainfee.SatPerKWeight(1000),
+ ).Once()
+ _, err := NewLinearFeeFunction(
+ 500, chainfee.MaxBlockTarget, estimator,
+ fn.None[chainfee.SatPerKWeight](),
+ )
+ require.ErrorIs(t, err, ErrZeroFeeRateDelta)
+ estimator.AssertExpectations(t)
+}
### sweep/retry_fee_preservation_test.go
@@ -0,0 +1,91 @@
+package sweep
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/input"
+ "github.com/lightningnetwork/lnd/lnwallet/chainfee"
+ "github.com/stretchr/testify/mock"
+ "github.com/stretchr/testify/require"
+)
+
+// TestSpendCheckRetryPreservesStartingFeeRate ensures an inconclusive spend
+// check does not overwrite the input's fee-rate preference.
+func TestSpendCheckRetryPreservesStartingFeeRate(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ starting fn.Option[chainfee.SatPerKWeight]
+ }{
+ {
+ "explicit starting rate",
+ fn.Some(chainfee.SatPerKWeight(1200)),
+ },
+ {
+ "estimated starting rate",
+ fn.None[chainfee.SatPerKWeight](),
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tp, mocks := createTestPublisher(t)
+ req := createTestBumpRequest()
+ req.StartingFeeRate = tc.starting
+ r := &monitorRecord{requestID: 1, req: req}
+
+ op := req.Inputs[0].OutPoint()
+ mocks.notifier.On(
+ "RegisterSpendNtfn", &op, mock.Anything,
+ mock.Anything,
+ ).Return(nil, errors.New("unavailable")).Once()
+
+ result := tp.handleMissingInputs(r)
+ require.Equal(t, TxFailed, result.Event)
+
+ s := New(&UtxoSweeperConfig{})
+ inp := req.Inputs[0]
+ s.inputs[op] = &SweeperInput{
+ Input: inp, state: PendingPublish,
+ params: Params{StartingFeeRate: tc.starting},
+ }
+ set := &MockInputSet{}
+ set.On("Inputs").Return(req.Inputs).Once()
+
+ err := s.handleBumpEvent(&bumpResp{
+ set: set, result: result,
+ })
+ require.NoError(t, err)
+ require.Equal(t, PublishFailed, s.inputs[op].state)
+ require.Equal(
+ t, tc.starting,
+ s.inputs[op].params.StartingFeeRate,
+ )
+ set.AssertExpectations(t)
+ })
+ }
+}
+
+// TestRetryUpdatesSpecifiedFeeRate ensures ordinary retry results still update
+// the starting fee rate supplied by the fee bumper.
+func TestRetryUpdatesSpecifiedFeeRate(t *testing.T) {
+ s := New(&UtxoSweeperConfig{})
+ inp := createMockInput(t, s, PendingPublish)
+ op := inp.OutPoint()
+ s.inputs[op].params.StartingFeeRate = fn.Some(
+ chainfee.SatPerKWeight(500),
+ )
+ set := &MockInputSet{}
+ set.On("Inputs").Return([]input.Input{inp}).Once()
+
+ err := s.handleBumpEvent(&bumpResp{
+ set: set, result: &BumpResult{
+ Event: TxFailed, Err: errDummy, FeeRate: 900,
+ },
+ })
+ require.NoError(t, err)
+ require.Equal(
+ t, fn.Some(chainfee.SatPerKWeight(900)),
+ s.inputs[op].params.StartingFeeRate,
+ )
+ set.AssertExpectations(t)
+}
### sweep/sweeper.go
@@ -974,7 +974,7 @@ func (s *UtxoSweeper) markInputsPublished(tr *TxRecord, set InputSet) error {
// markInputsPublishFailed marks the list of inputs as failed to be published.
func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
- feeRate chainfee.SatPerKWeight) {
+ feeRate fn.Option[fn.Option[chainfee.SatPerKWeight]]) {
// Reschedule sweep.
for _, inp := range set.Inputs() {
@@ -1003,14 +1003,14 @@ func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
// Update the input's state.
pi.state = PublishFailed
- log.Debugf("Input(%v): updating params: starting fee rate "+
- "[%v -> %v]", op, pi.params.StartingFeeRate,
- feeRate)
-
- // Update the input using the fee rate specified from the
- // BumpResult, which should be the starting fee rate to use for
- // the next sweeping attempt.
- pi.params.StartingFeeRate = fn.Some(feeRate)
+ // An absent update preserves the rate. A present update may
+ // clear it so that the next attempt uses the estimator.
+ feeRate.WhenSome(func(rate fn.Option[chainfee.SatPerKWeight]) {
+ log.Debugf("Input(%v): updating starting fee rate "+
+ "[%v -> %v]", op,
+ pi.params.StartingFeeRate, rate)
+ pi.params.StartingFeeRate = rate
+ })
}
}
@@ -1738,7 +1738,18 @@ func (s *UtxoSweeper) handleBumpEventTxFailed(resp *bumpResp) {
// the inputs specified by the set.
//
// TODO(yy): should we also remove the failed tx from db?
- s.markInputsPublishFailed(resp.set, resp.result.FeeRate)
+ feeRate := fn.Some(fn.Some(r.FeeRate))
+ switch {
+ case errors.Is(r.Err, errSpendCheckFailed):
+ feeRate = fn.None[fn.Option[chainfee.SatPerKWeight]]()
+ case errors.Is(r.Err, errStartingFeeRateTooHigh):
+ log.Warnf("Requested starting fee rate can't be paid from "+
+ "the budget, using the fee estimator instead: %v",
+ r.Err)
+
+ feeRate = fn.Some(fn.None[chainfee.SatPerKWeight]())
+ }
+ s.markInputsPublishFailed(resp.set, feeRate)
}
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
@@ -1989,7 +2000,7 @@ func (s *UtxoSweeper) handleUnknownSpendTx(inp *SweeperInput, tx *wire.MsgTx) {
func (s *UtxoSweeper) handleBumpEventTxUnknownSpend(r *bumpResp) {
// Mark the inputs as publish failed, which means they will be retried
// later.
- s.markInputsPublishFailed(r.set, r.result.FeeRate)
+ s.markInputsPublishFailed(r.set, fn.Some(fn.Some(r.result.FeeRate)))
// Get all the inputs that are not spent in the current sweeping tx.
spentInputs := r.result.SpentInputs
### sweep/sweeper_test.go
@@ -237,7 +237,7 @@ func TestMarkInputsPublishFailed(t *testing.T) {
// Mark the test inputs. We expect the non-exist input and the
// inputInit to be skipped, and the final input to be marked as
// published.
- s.markInputsPublishFailed(set, feeRate)
+ s.markInputsPublishFailed(set, fn.Some(fn.Some(feeRate)))
// We expect unchanged number of pending inputs.
require.Len(s.inputs, 7)
### watchtower/wtclient/client.go
@@ -5,6 +5,7 @@ import (
"crypto/rand"
"errors"
"fmt"
+ "io"
"maps"
"math/big"
"net"
@@ -1005,7 +1006,9 @@ func (c *client) readMessage(peer wtserver.Peer) (wtwire.Message, error) {
// Parse the received message according to the watchtower wire
// specification.
msgReader := bytes.NewReader(rawMsg)
- msg, err := wtwire.ReadMessage(msgReader, 0)
+ msg, err := wtwire.ReadMessage(
+ io.LimitReader(msgReader, int64(len(rawMsg))), 0,
+ )
if err != nil {
err = fmt.Errorf("unable to parse message: %w", err)
c.log.Errorf("Unable to read msg: %v", err)
### watchtower/wtpolicy/policy.go
@@ -49,7 +49,7 @@ var (
ErrRewardExceedsInputs = errors.New("reward amount exceeds input value")
// ErrCreatesDust signals that the session's policy would create a dust
- // output for the victim.
+ // output.
ErrCreatesDust = errors.New("justice transaction creates dust at fee rate")
// ErrAltruistReward signals that the policy is invalid because it
@@ -204,7 +204,8 @@ func (p *Policy) ComputeAltruistOutput(
// ComputeRewardOutputs splits the total funds in a breaching commitment
// transaction between the victim and the tower, according to the sweep fee rate
// and reward rate. The reward to he tower is subtracted first, before
-// splitting the remaining balance amongst the victim and fees.
+// splitting the remaining balance amongst the victim and fees. It validates
+// the reward output; the caller must validate the sweep output's dust limit.
func (p *Policy) ComputeRewardOutputs(totalAmt btcutil.Amount,
txWeight lntypes.WeightUnit,
rewardScript []byte) (btcutil.Amount, btcutil.Amount, error) {
@@ -225,9 +226,8 @@ func (p *Policy) ComputeRewardOutputs(totalAmt btcutil.Amount,
// input value.
sweepAmt := totalAmt - rewardAmt - txFee
- // Check that the created outputs won't be dusty. We'll base the dust
- // computation on the type of the script itself.
- if sweepAmt < lnwallet.DustLimitForSize(len(rewardScript)) {
+ // Check the reward output against its own script's dust limit.
+ if rewardAmt < lnwallet.DustLimitForSize(len(rewardScript)) {
return 0, 0, ErrCreatesDust
}
@@ -293,6 +293,11 @@ func (p *Policy) ComputeJusticeTxOuts(
return nil, err
}
+ // Check the sweep output against its own script's dust limit.
+ if sweepAmt < lnwallet.DustLimitForSize(len(sweepPkScript)) {
+ return nil, ErrCreatesDust
+ }
+
// Add the sweep and reward outputs to the list of txouts.
outputs = append(outputs, &wire.TxOut{
PkScript: sweepPkScript,
### watchtower/wtpolicy/reward_dust_test.go
@@ -0,0 +1,73 @@
+package wtpolicy_test
+
+import (
+ "testing"
+
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/lightningnetwork/lnd/lnwallet"
+ "github.com/lightningnetwork/lnd/watchtower/blob"
+ "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
+ "github.com/stretchr/testify/require"
+)
+
+func TestRewardOutputDust(t *testing.T) {
+ sweepScript := make([]byte, 22)
+ rewardScript := make([]byte, 34)
+ sweepDust := lnwallet.DustLimitForSize(len(sweepScript))
+ rewardDust := lnwallet.DustLimitForSize(len(rewardScript))
+ require.Less(t, sweepDust, rewardDust)
+ tests := []struct {
+ name string
+ sweep, reward btcutil.Amount
+ dusty bool
+ }{
+ {"dusty reward", 10000, rewardDust - 1, true},
+ {"dusty sweep", sweepDust - 1, 10000, true},
+ {"each at own limit", sweepDust, rewardDust, false},
+ {"sweep below reward limit", sweepDust, 10000, false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ p := wtpolicy.Policy{TxPolicy: wtpolicy.TxPolicy{
+ BlobType: blob.TypeRewardCommit,
+ RewardBase: uint32(tc.reward),
+ }}
+ outs, err := p.ComputeJusticeTxOuts(
+ tc.sweep+tc.reward, 0,
+ sweepScript, rewardScript,
+ )
+ if tc.dusty {
+ require.ErrorIs(
+ t, err, wtpolicy.ErrCreatesDust,
+ )
+ require.Nil(t, outs)
+
+ return
+ }
+ require.NoError(t, err)
+ require.Len(t, outs, 2)
+ require.Equal(t, int64(tc.sweep), outs[0].Value)
+ require.Equal(t, int64(tc.reward), outs[1].Value)
+ require.Equal(t, sweepScript, outs[0].PkScript)
+ require.Equal(t, rewardScript, outs[1].PkScript)
+ })
+ }
+
+ // Reversing script sizes must not lower the sweep dust threshold.
+ p := wtpolicy.Policy{TxPolicy: wtpolicy.TxPolicy{
+ BlobType: blob.TypeRewardCommit, RewardBase: uint32(sweepDust),
+ }}
+ _, err := p.ComputeJusticeTxOuts(
+ rewardDust-1+sweepDust, 0, rewardScript, sweepScript,
+ )
+ require.ErrorIs(t, err, wtpolicy.ErrCreatesDust)
+
+ // Altruist sessions continue to produce a single sweep output.
+ p = wtpolicy.Policy{TxPolicy: wtpolicy.TxPolicy{
+ BlobType: blob.TypeAltruistCommit,
+ }}
+ outs, err := p.ComputeJusticeTxOuts(sweepDust, 0, sweepScript, nil)
+ require.NoError(t, err)
+ require.Len(t, outs, 1)
+ require.Equal(t, int64(sweepDust), outs[0].Value)
+}
### watchtower/wtserver/server.go
@@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
+ "io"
"net"
"sync"
"time"
@@ -326,7 +327,9 @@ func (s *Server) readMessage(peer Peer) (wtwire.Message, error) {
}
msgReader := bytes.NewReader(rawMsg)
- msg, err := wtwire.ReadMessage(msgReader, 0)
+ msg, err := wtwire.ReadMessage(
+ io.LimitReader(msgReader, int64(len(rawMsg))), 0,
+ )
if err != nil {
err = fmt.Errorf("unable to parse message: %w", err)
return nil, err
### watchtower/wtwire/create_session_reply.go
@@ -99,5 +99,5 @@ func (m *CreateSessionReply) MsgType() MessageType {
//
// This is part of the wtwire.Message interface.
func (m *CreateSessionReply) MaxPayloadLength(uint32) uint32 {
- return 2 + 3 + MaxCreateSessionReplyDataLength
+ return 2 + 2 + 3 + MaxCreateSessionReplyDataLength
}
### watchtower/wtwire/create_session_reply_boundary_test.go
@@ -0,0 +1,25 @@
+package wtwire
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestCreateSessionReplyMaximumPayload(t *testing.T) {
+ msg := &CreateSessionReply{
+ Data: make([]byte, MaxCreateSessionReplyDataLength),
+ }
+ var buf bytes.Buffer
+ if _, err := WriteMessage(&buf, msg, 0); err != nil {
+ t.Fatalf("write maximum reply: %v", err)
+ }
+ if got := buf.Len() - 2; got != int(msg.MaxPayloadLength(0)) {
+ t.Fatalf(
+ "payload size %d, want %d", got,
+ msg.MaxPayloadLength(0),
+ )
+ }
+ if _, err := ReadMessage(&buf, 0); err != nil {
+ t.Fatalf("read maximum reply: %v", err)
+ }
+}
### watchtower/wtwire/inbound_bounds_test.go
@@ -0,0 +1,99 @@
+package wtwire
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "testing"
+)
+
+func TestInboundFrameBounds(t *testing.T) {
+ tests := []Message{
+ &CreateSessionReply{
+ Data: make([]byte, MaxCreateSessionReplyDataLength),
+ },
+ &DeleteSession{},
+ &StateUpdateReply{},
+ }
+ for _, msg := range tests {
+ t.Run(msg.MsgType().String(), func(t *testing.T) {
+ var frame bytes.Buffer
+ if _, err := WriteMessage(&frame, msg, 0); err != nil {
+ t.Fatal(err)
+ }
+ raw := frame.Bytes()
+ framed := io.LimitReader(
+ bytes.NewReader(raw), int64(len(raw)),
+ )
+ if _, err := ReadMessage(framed, 0); err != nil {
+ t.Fatal(err)
+ }
+ padding := int(msg.MaxPayloadLength(0)) + 1 -
+ (len(raw) - 2)
+ oversized := append(append([]byte(nil), raw...),
+ make([]byte, padding)...)
+ reader := bytes.NewReader(append(oversized, 42))
+ framed = io.LimitReader(reader, int64(len(oversized)))
+ if _, err := ReadMessage(framed, 0); err == nil {
+ t.Fatal("oversized frame accepted")
+ }
+ if reader.Len() != len(oversized)-2+1 {
+ t.Fatalf(
+ "read beyond type: %d bytes remain",
+ reader.Len(),
+ )
+ }
+ })
+ }
+}
+
+func TestInboundUnframedSequentialMessages(t *testing.T) {
+ var b bytes.Buffer
+ for range 2 {
+ if _, err := WriteMessage(&b, &DeleteSession{}, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for range 2 {
+ if _, err := ReadMessage(&b, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if b.Len() != 0 {
+ t.Fatal("unconsumed bytes")
+ }
+}
+
+// TestInboundFramedVarBytesLengthBound rejects lengths larger than the frame
+// before trying to read the declared payload.
+func TestInboundFramedVarBytesLengthBound(t *testing.T) {
+ var b bytes.Buffer
+ _ = binary.Write(&b, binary.BigEndian, uint16(MsgError))
+ b.Write([]byte{0, 0, 0xfd, 0x00, 0x10})
+ frame := io.LimitReader(&b, int64(b.Len()))
+ _, err := ReadMessage(frame, 0)
+ if err == nil || errors.Is(err, io.EOF) ||
+ errors.Is(err, io.ErrUnexpectedEOF) {
+
+ t.Fatalf("expected frame length rejection, got %v", err)
+ }
+ if b.Len() != 0 {
+ t.Fatalf("unexpected remaining bytes: %d", b.Len())
+ }
+}
+
+func TestInboundVarBytesLengthBound(t *testing.T) {
+ var b bytes.Buffer
+ _ = binary.Write(&b, binary.BigEndian, uint16(MsgCreateSessionReply))
+ b.Write([]byte{0, 0, 0, 0, 0xfd, 0xff, 0xff})
+ _, err := ReadMessage(&b, 0)
+ if err == nil || errors.Is(err, io.EOF) ||
+ errors.Is(err, io.ErrUnexpectedEOF) {
+
+ t.Fatalf(
+ "expected length rejection before reading data, got %v",
+ err,
+ )
+ }
+}
### watchtower/wtwire/message.go
@@ -174,7 +174,8 @@ func WriteMessage(w io.Writer, msg Message, pver uint32) (int, error) {
}
// ReadMessage reads, validates, and parses the next Watchtower message from r
-// for the provided protocol version.
+// for the provided protocol version. If r is an io.LimitedReader, its limit
+// must describe the entire message frame, including the message type.
func ReadMessage(r io.Reader, pver uint32) (Message, error) {
// First, we'll read out the first two bytes of the message so we can
// create the proper empty message.
@@ -191,7 +192,21 @@ func ReadMessage(r io.Reader, pver uint32) (Message, error) {
if err != nil {
return nil, err
}
- if err := msg.Decode(r, pver); err != nil {
+ // A limited reader identifies an explicitly bounded message frame.
+ maxPayload := msg.MaxPayloadLength(pver)
+ if framed, ok := r.(*io.LimitedReader); ok &&
+ framed.N > int64(maxPayload) {
+
+ return nil, fmt.Errorf("message payload of type %v exceeds "+
+ "maximum %d bytes", msgType, maxPayload)
+ }
+
+ budget := int64(maxPayload)
+ if framed, ok := r.(*io.LimitedReader); ok {
+ budget = min(budget, framed.N)
+ }
+ limited := &io.LimitedReader{R: r, N: budget}
+ if err := msg.Decode(limited, pver); err != nil {
return nil, err
}
### watchtower/wtwire/wtwire.go
@@ -188,7 +188,13 @@ func ReadElement(r io.Reader, element interface{}) error {
}
case *[]byte:
- bytes, err := wire.ReadVarBytes(r, 0, 66000, "[]byte")
+ maxLen := uint32(66000)
+ if limited, ok := r.(*io.LimitedReader); ok &&
+ limited.N < int64(maxLen) {
+
+ maxLen = uint32(max(limited.N, 0))
+ }
+ bytes, err := wire.ReadVarBytes(r, 0, maxLen, "[]byte")
if err != nil {
return err
}Why this scored 61/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.