Merge pull request #11551 from ziggie1984/public-pr149-sanitized
What changed, and why it matters
This change fixes a bug in LND's invoice handling for multi-part payments (MPP and AMP). When a payment is split into several pieces (HTLCs), each piece is accepted individually. Previously, an old accepted piece could become too close to its expiry while waiting for the remaining pieces to arrive. Once the final piece arrived and completed the set, LND would settle all pieces without rechecking their expiries. This could let a piece be settled on-chain with too little time left, potentially causing funds loss if the on-chain claim fails to confirm in time. The fix revalidates every accepted piece's expiry at the moment the set completes, and cancels the whole set if any piece is now too close to expiry.
Treat this as a security-relevant bug fix and include it in the next maintenance release. Node operators accepting MPP/AMP payments should upgrade. Review whether any additional proactive expiry revalidation is needed while HTLCs are held before set completion.
Security signals we found
Fixes missing revalidation of accepted HTLC CLTV expiries at MPP/AMP set completion
Prevents settlement of shards whose on-chain claim window has become unsafe while held
Adds new fail resolution ResultHtlcSetExpiryTooSoon and cancels the entire affected set
Includes unit tests for MPP, AMP, replayed AMP HTLC near expiry, and RPC failure mapping
Refactors cancelHtlcSetUpdate helper to reuse set-cancellation logic
Evidence from the diff
In invoices/update.go, updateMpp now computes setComplete before the final settlement path. When setComplete is true, it iterates over htlcSet and revalidates each previously accepted HTLC’s Expiry against both currentHeight+finalCltvRejectDelta and currentHeight+inv.Terms.FinalCltvDelta. If any shard fails, it returns cancelHtlcSetUpdate(htlcSet, setID) plus ResultHtlcSetExpiryTooSoon. A new resolution result ResultHtlcSetExpiryTooSoon is added to invoices/resolution_result.go and mapped to FailureDetail_INVOICE_EXPIRY_TOO_SOON in lnrpc/routerrpc/subscribe_events.go. Tests cover MPP and AMP cases, including a replayed AMP HTLC near expiry and RPC failure mapping. The patch is defensive and partial in the sense that it only cancels at set-completion time, not proactively as blocks advance.
Changed components
invoices/update.goinvoices/resolution_result.goinvoices/invoiceregistry_test.goinvoices/update_invoice_test.golnrpc/routerrpc/subscribe_events.golnrpc/routerrpc/subscribe_events_test.goInspect captured patch +281 / −34
### docs/release-notes/unreleased/11551.md
@@ -0,0 +1,6 @@
+# Bug Fixes
+
+* [The expiries of all accepted HTLCs in an MPP or AMP set are now
+ revalidated](https://github.com/lightningnetwork/lnd/pull/11551) when the
+ set becomes complete, and the set is canceled if any of them no longer meets
+ the final CLTV requirements.
### invoices/invoiceregistry_test.go
@@ -1052,8 +1052,9 @@ func testLookupAMPHtlcPreimageSetIsolation(t *testing.T,
)
}
-// testReplayedAMPHtlcNearExpiry asserts that a recorded AMP HTLC replayed near
-// expiry is resolved from its persisted invoice state.
+// testReplayedAMPHtlcNearExpiry asserts that a held AMP HTLC replayed by the
+// on-chain resolver remains accepted, but cannot be used to settle its set once
+// its expiry is too close at the set's completion height.
func testReplayedAMPHtlcNearExpiry(t *testing.T,
makeDB func(t *testing.T) (invpkg.InvoiceDB, *clock.TestClock)) {
@@ -1074,9 +1075,9 @@ func testReplayedAMPHtlcNearExpiry(t *testing.T,
sharer, err := amp.NewSeedSharer()
require.NoError(t, err)
- left, _, err := sharer.Split()
+ left, right, err := sharer.Split()
require.NoError(t, err)
- shardA := left.Child(0)
+ shardA, shardB := left.Child(0), right.Child(1)
payload := func(child *amp.Child, index uint32) *mockPayload {
return &mockPayload{
@@ -1085,7 +1086,8 @@ func testReplayedAMPHtlcNearExpiry(t *testing.T,
}
}
- // Record shard A as accepted at the minimum expiry.
+ // Shard A arrives with the minimum accepted expiry and is held until
+ // the set completes.
minExpiry := uint32(testCurrentHeight + testFinalCltvRejectDelta)
resolution, err := ctx.registry.NotifyExitHopHtlc(
shardA.Hash, 300, minExpiry, testCurrentHeight,
@@ -1095,14 +1097,53 @@ func testReplayedAMPHtlcNearExpiry(t *testing.T,
require.NoError(t, err)
require.Nil(t, resolution)
- // Replay shard A one block later and verify its recorded result.
+ // The channel goes on-chain and the resolver replays shard A one block
+ // later. It must still be accepted rather than failed by the expiry
+ // check for new HTLCs.
resolverChan := make(chan interface{}, 1)
resolution, err = ctx.registry.NotifyExitHopHtlc(
shardA.Hash, 300, minExpiry, testCurrentHeight+1,
getCircuitKey(1), resolverChan, nil, payload(shardA, 0),
)
require.NoError(t, err)
require.Nil(t, resolution)
+
+ // Shard B would complete the set, but shard A no longer has a
+ // sufficient CLTV delta at the current height.
+ resolution, err = ctx.registry.NotifyExitHopHtlc(
+ shardB.Hash, 60, uint32(testCurrentHeight+40),
+ testCurrentHeight+1, getCircuitKey(2),
+ make(chan interface{}, 1), nil, payload(shardB, 1),
+ )
+ require.NoError(t, err)
+ checkFailResolution(
+ t, resolution, invpkg.ResultHtlcSetExpiryTooSoon,
+ )
+
+ // The failed completion attempt must cancel shard A, leave the invoice
+ // open and not record shard B.
+ invoice, err := ctx.registry.LookupInvoiceByRef(
+ t.Context(), invpkg.InvoiceRefBySetID(setID),
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractOpen, invoice.State)
+ htlcA, ok := invoice.Htlcs[getCircuitKey(1)]
+ require.True(t, ok)
+ require.Equal(t, invpkg.HtlcStateCanceled, htlcA.State)
+ _, ok = invoice.Htlcs[getCircuitKey(2)]
+ require.False(t, ok)
+
+ select {
+ case resolution := <-resolverChan:
+ htlcResolution, ok := resolution.(invpkg.HtlcResolution)
+ require.True(t, ok)
+ checkFailResolution(
+ t, htlcResolution, invpkg.ResultHtlcSetExpiryTooSoon,
+ )
+
+ case <-time.After(testTimeout):
+ t.Fatal("resolver not notified of stale set cancellation")
+ }
}
// testReplayedHoldKeysendNearExpiry asserts that a held keysend HTLC that is
### invoices/resolution_result.go
@@ -121,6 +121,10 @@ const (
// hash/preimage pairs were invalid for at least one HTLC in the set.
ResultAmpReconstruction
+ // ResultHtlcSetExpiryTooSoon is returned when an accepted HTLC can no
+ // longer safely settle at the height when its set becomes complete.
+ ResultHtlcSetExpiryTooSoon
+
// ExternalValidationFailed is returned when the external validation
// failed.
ExternalValidationFailed
@@ -197,6 +201,9 @@ func (f FailResolutionResult) FailureString() string {
case ResultAmpReconstruction:
return "amp reconstruction failed"
+ case ResultHtlcSetExpiryTooSoon:
+ return "htlc set contains an expiry that is too soon"
+
case ExternalValidationFailed:
return "external validation failed"
@@ -217,6 +224,7 @@ func (f FailResolutionResult) IsSetFailure() bool {
ResultHtlcSetTotalTooLow,
ResultHtlcSetTotalMismatch,
ResultHtlcSetOverpayment,
+ ResultHtlcSetExpiryTooSoon,
ExternalValidationFailed:
return true
### invoices/update.go
@@ -288,16 +288,40 @@ func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
// Add amount of new htlc.
newSetTotal += ctx.amtPaid
+ setComplete := newSetTotal >= totalAmt
// The invoice is still open. Check the expiry.
- if ctx.expiry < uint32(ctx.currentHeight+ctx.finalCltvRejectDelta) {
+ minRejectExpiry := uint32(
+ ctx.currentHeight + ctx.finalCltvRejectDelta,
+ )
+ if ctx.expiry < minRejectExpiry {
return nil, ctx.failRes(ResultExpiryTooSoon), nil
}
- if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
+ minInvoiceExpiry := uint32(
+ ctx.currentHeight + inv.Terms.FinalCltvDelta,
+ )
+ if ctx.expiry < minInvoiceExpiry {
return nil, ctx.failRes(ResultExpiryTooSoon), nil
}
+ // Before completing the set, ensure every previously accepted shard
+ // is still safe to settle at the current height. A shard may have
+ // satisfied these checks when it was first accepted but become stale
+ // while waiting for the rest of the set.
+ if setComplete {
+ for _, htlc := range htlcSet {
+ if htlc.Expiry < minRejectExpiry ||
+ htlc.Expiry < minInvoiceExpiry {
+
+ return cancelHtlcSetUpdate(htlcSet, setID),
+ ctx.failRes(
+ ResultHtlcSetExpiryTooSoon,
+ ), nil
+ }
+ }
+ }
+
if setID != nil && *setID == BlankPayAddr {
return nil, ctx.failRes(ResultAmpError), nil
}
@@ -313,7 +337,6 @@ func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
}
// If the invoice cannot be settled yet, only record the htlc.
- setComplete := newSetTotal >= totalAmt
if !setComplete {
return &update, ctx.acceptRes(resultPartialAccepted), nil
}
@@ -335,26 +358,7 @@ func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
var failRes *HtlcFailResolution
htlcPreimages, failRes = reconstructAMPPreimages(ctx, htlcSet)
if failRes != nil {
- // Reconstruction failure is a set-local condition: only
- // the HTLCs of this set can never settle. Cancel just
- // this set and keep the invoice open, since reusable
- // static AMP invoices may carry other accepted sets
- // that are unaffected by the failure. The current HTLC
- // is failed directly via failRes and was never added
- // to the invoice, so it is not part of the cancel set.
- cancelHtlcs := make(
- map[CircuitKey]struct{}, len(htlcSet),
- )
- for key := range htlcSet {
- cancelHtlcs[key] = struct{}{}
- }
-
- update.UpdateType = CancelHTLCsUpdate
- update.CancelHtlcs = cancelHtlcs
- update.AddHtlcs = nil
- update.SetID = (*SetID)(setID)
-
- return &update, failRes, nil
+ return cancelHtlcSetUpdate(htlcSet, setID), failRes, nil
}
// The preimage for _this_ HTLC will be the one with context's
@@ -374,6 +378,24 @@ func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
return &update, ctx.settleRes(htlcPreimage, ResultSettled), nil
}
+// cancelHtlcSetUpdate returns an update that cancels every previously accepted
+// HTLC in a payment set while leaving the invoice open. The completing HTLC is
+// not included because it has not been added to the invoice yet.
+func cancelHtlcSetUpdate(htlcSet HTLCSet,
+ setID *[32]byte) *InvoiceUpdateDesc {
+
+ cancelHtlcs := make(map[CircuitKey]struct{}, len(htlcSet))
+ for key := range htlcSet {
+ cancelHtlcs[key] = struct{}{}
+ }
+
+ return &InvoiceUpdateDesc{
+ UpdateType: CancelHTLCsUpdate,
+ CancelHtlcs: cancelHtlcs,
+ SetID: (*SetID)(setID),
+ }
+}
+
// HTLCSet is a map of CircuitKey to InvoiceHTLC.
type HTLCSet = map[CircuitKey]*InvoiceHTLC
### invoices/update_invoice_test.go
@@ -949,6 +949,147 @@ func TestUpdateInvoiceRejectsAmpInvoiceInLegacyPath(t *testing.T) {
requireFailResolution(t, resolution, ResultHtlcInvoiceTypeMismatch)
}
+// TestUpdateMppRejectsStaleShard asserts that an MPP or AMP set cannot settle
+// using a previously accepted shard whose expiry is now too close.
+func TestUpdateMppRejectsStaleShard(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ isAMP bool
+ finalDelta int32
+ finalRejectDelta int32
+ }{
+ {
+ name: "mpp invoice delta",
+ finalDelta: 4,
+ finalRejectDelta: 2,
+ },
+ {
+ name: "amp invoice delta",
+ isAMP: true,
+ finalDelta: 4,
+ finalRejectDelta: 2,
+ },
+ {
+ name: "mpp reject delta",
+ finalDelta: 2,
+ finalRejectDelta: 4,
+ },
+ {
+ name: "amp reject delta",
+ isAMP: true,
+ finalDelta: 2,
+ finalRejectDelta: 4,
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ t.Parallel()
+
+ const (
+ currentHeight = int32(10)
+ totalAmt = lnwire.MilliSatoshi(100)
+ )
+
+ preimage := lntypes.Preimage{1}
+ payAddr := [32]byte{2}
+ setID := [32]byte{3}
+ features := lnwire.NewFeatureVector(
+ nil, lnwire.Features,
+ )
+
+ ctx := &invoiceUpdateCtx{
+ hash: preimage.Hash(),
+ circuitKey: CircuitKey{HtlcID: 2},
+ amtPaid: 40,
+ expiry: 20,
+ currentHeight: currentHeight,
+ finalCltvRejectDelta: testCase.finalRejectDelta,
+ mpp: record.NewMPP(
+ totalAmt, payAddr,
+ ),
+ customRecords: make(record.CustomSet),
+ wireCustomRecords: make(lnwire.CustomRecords),
+ }
+
+ htlc := &InvoiceHTLC{
+ Amt: 60,
+ MppTotalAmt: totalAmt,
+ Expiry: 13,
+ State: HtlcStateAccepted,
+ }
+
+ if testCase.isAMP {
+ ampRecord := record.NewAMP(
+ [32]byte{4}, setID, 0,
+ )
+ ctx.amp = record.NewAMP([32]byte{5}, setID, 1)
+ htlc.AMP = &InvoiceHtlcAMPData{
+ Record: *ampRecord,
+ Hash: lntypes.Hash{6},
+ }
+ features = lnwire.NewFeatureVector(
+ lnwire.NewRawFeatureVector(
+ lnwire.AMPRequired,
+ ),
+ lnwire.Features,
+ )
+ }
+
+ invoice := &Invoice{
+ State: ContractOpen,
+ Terms: ContractTerm{
+ FinalCltvDelta: testCase.finalDelta,
+ PaymentPreimage: &preimage,
+ PaymentAddr: payAddr,
+ Value: totalAmt,
+ Features: features,
+ },
+ Htlcs: map[CircuitKey]*InvoiceHTLC{
+ {HtlcID: 1}: htlc,
+ },
+ }
+ if testCase.isAMP {
+ otherSetID := [32]byte{9}
+ otherRecord := record.NewAMP(
+ [32]byte{8}, otherSetID, 0,
+ )
+ invoice.Htlcs[CircuitKey{HtlcID: 3}] =
+ &InvoiceHTLC{
+ Amt: 60,
+ MppTotalAmt: totalAmt,
+ Expiry: 20,
+ State: HtlcStateAccepted,
+ AMP: &InvoiceHtlcAMPData{
+ Record: *otherRecord,
+ Hash: lntypes.Hash{7},
+ },
+ }
+ }
+
+ update, resolution, err := updateMpp(ctx, invoice)
+ require.NoError(t, err)
+ require.NotNil(t, update)
+ require.Equal(t, CancelHTLCsUpdate, update.UpdateType)
+ require.Equal(
+ t, map[CircuitKey]struct{}{{HtlcID: 1}: {}},
+ update.CancelHtlcs,
+ )
+ require.Empty(t, update.AddHtlcs)
+ if testCase.isAMP {
+ require.Equal(t, (*SetID)(&setID), update.SetID)
+ } else {
+ require.Nil(t, update.SetID)
+ }
+ requireFailResolution(
+ t, resolution, ResultHtlcSetExpiryTooSoon,
+ )
+ })
+ }
+}
+
// TestUpdateLegacyRejectsNilPreimageSettle checks the outcome when a legacy
// settlement has no invoice-level preimage.
func TestUpdateLegacyRejectsNilPreimageSettle(t *testing.T) {
### lnrpc/routerrpc/subscribe_events.go
@@ -180,6 +180,9 @@ func rpcFailureResolution(invoiceFailure invoices.FailResolutionResult) (
case invoices.ResultExpiryTooSoon:
return FailureDetail_INVOICE_EXPIRY_TOO_SOON, nil
+ case invoices.ResultHtlcSetExpiryTooSoon:
+ return FailureDetail_INVOICE_EXPIRY_TOO_SOON, nil
+
case invoices.ResultCanceled:
return FailureDetail_INVOICE_CANCELED, nil
### lnrpc/routerrpc/subscribe_events_test.go
@@ -12,9 +12,35 @@ import (
func TestRPCInvoiceProcessingFailureResolution(t *testing.T) {
t.Parallel()
- failureDetail, err := rpcFailureResolution(
- invoices.ResultInvoiceInterceptorError,
- )
- require.NoError(t, err)
- require.Equal(t, FailureDetail_INVOICE_INTERCEPTOR_ERROR, failureDetail)
+ tests := []struct {
+ name string
+ result invoices.FailResolutionResult
+ expected FailureDetail
+ }{
+ {
+ name: "invoice expiry too soon",
+ result: invoices.ResultExpiryTooSoon,
+ expected: FailureDetail_INVOICE_EXPIRY_TOO_SOON,
+ },
+ {
+ name: "htlc set expiry too soon",
+ result: invoices.ResultHtlcSetExpiryTooSoon,
+ expected: FailureDetail_INVOICE_EXPIRY_TOO_SOON,
+ },
+ {
+ name: "invoice interceptor error",
+ result: invoices.ResultInvoiceInterceptorError,
+ expected: FailureDetail_INVOICE_INTERCEPTOR_ERROR,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ failureDetail, err := rpcFailureResolution(test.result)
+ require.NoError(t, err)
+ require.Equal(t, test.expected, failureDetail)
+ })
+ }
}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.