invoices: reject stale shards at set completion
What changed, and why it matters
This change fixes a bug in how Lightning Network invoices handle multi-part payments (MPP/AMP). Previously, a payment shard accepted early could sit until the rest of the payment arrived. By then, its timeout might be too close to the current blockchain height to safely settle, yet the system would still complete the payment. Now, when the final shard arrives, every previously accepted shard is re-checked for a safe timeout. If any shard is too close to expiring, the whole payment set is cancelled, the invoice stays open, and the final shard is rejected. This prevents a situation where funds could be released for a payment that can no longer be claimed on-chain in time.
Review and merge. The change is defensive and well-tested. Operators should upgrade nodes that accept MPP/AMP invoices to avoid the risk of attempting to settle shards with insufficient remaining CLTV delta. No immediate external mitigation is required beyond patching.
Security signals we found
Fixes stale/expiring HTLC shard acceptance in MPP/AMP invoice settlement
Adds revalidation loop over accepted HTLC set at completion time
Introduces new set-level failure result ResultHtlcSetExpiryTooSoon
Cancels entire HTLC set and keeps invoice open on unsafe expiry
Prevents settlement when a shard's CLTV delta has become insufficient while held
Refactors AMP reconstruction failure path to share cancellation helper
Evidence from the diff
The patch modifies updateMpp in invoices/update.go to revalidate all already-accepted HTLCs in an MPP or AMP set at the moment a completing shard arrives (setComplete). It computes minRejectExpiry (currentHeight + finalCltvRejectDelta) and minInvoiceExpiry (currentHeight + inv.Terms.FinalCltvDelta), and if any accepted htlc.Expiry is below either threshold, it returns cancelHtlcSetUpdate(htlcSet, setID) plus ResultHtlcSetExpiryTooSoon. A new resolution result ResultHtlcSetExpiryTooSoon is added and classified as a set failure. Tests cover both MPP and AMP, both invoice delta and reject delta cases, and an on-chain resolver replay scenario. The fix also refactors the existing AMP reconstruction failure cancellation path to use the same cancelHtlcSetUpdate helper.
Changed components
invoices/update.goinvoices/resolution_result.goinvoices/invoiceregistry_test.goinvoices/update_invoice_test.goInspect captured patch +241 / −29
### 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) {Why this scored 62/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.