invoices: require complete payment collection
What changed, and why it matters
This commit changes how LND handles multi-part Lightning payments when one part fails after the preimage was already released. Previously, the invoice could be marked as fully paid even if one shard was later reclaimed by the payer on-chain. Now the invoice is canceled when any released shard fails, while still keeping the funds that were successfully collected. This prevents a merchant from incorrectly believing they were paid in full and possibly shipping goods or services based on an invoice that ultimately did not fully settle.
Review the change for correctness in edge cases such as AMP invoices (explicitly excluded), overpayment scenarios, and interactions with hold invoices. Ensure RPC consumers handle the new `FAILED` HTLC state and `PreimageReleased` field appropriately. Consider whether any monitoring or alerting needs to flag partially-collected canceled invoices.
Security signals we found
Changes invoice settlement semantics for released-but-failed HTLCs
Adds new persisted HTLC state `HtlcStateFailed`
Prevents invoice from reaching `ContractSettled` when any released shard fails
Adds RPC exposure of `PreimageReleased` and `FAILED` HTLC state
Includes recovery/restart regression tests to prevent premature settlement
Updates replay logic to treat `HtlcStateFailed` like `HtlcStateCanceled`
Evidence from the diff
The patch introduces a new HTLC state HtlcStateFailed to distinguish final on-chain failures after preimage release from pre-release cancellations (HtlcStateCanceled). For ordinary (non-AMP) invoices in ContractPendingSettle, the final invoice state now becomes ContractCanceled if any released HTLC failed, even if others settled. The successfully settled amount is retained in AmtPaid, but SettleIndex and SettleDate remain zero. The RPC layer exposes this via a new PreimageReleased boolean and a new FAILED HTLC state. Extensive tests cover recovery after restart, batch finalization, replay behavior, and database migration.
Changed components
invoices/invoices.goinvoices/update.goinvoices/update_invoice.golnrpc/invoicesrpc/utils.goinvoices/invoiceregistry_test.goinvoices/invoices_test.goinvoices/settle_collection_registry_test.goinvoices/settle_collection_test.goinvoices/sql_migration_test.golnrpc/invoicesrpc/addinvoice_test.goInspect captured patch +492 / −49
### invoices/invoiceregistry_test.go
@@ -481,6 +481,10 @@ func TestInvoiceRegistry(t *testing.T) {
name: "PendingSettleOnChainLoss",
test: testPendingSettleOnChainLoss,
},
+ {
+ name: "PendingSettleMixedRecovery",
+ test: testPendingSettleMixedRecovery,
+ },
{
name: "PendingSettleDuplicateReconcileOnStart",
test: testPendingSettleDuplicateReconcileOnStart,
@@ -3992,7 +3996,7 @@ func testPendingSettleOnChainLoss(t *testing.T,
require.Zero(t, update.AmtPaid)
require.Zero(t, update.SettleIndex)
require.Equal(
- t, invpkg.HtlcStateCanceled,
+ t, invpkg.HtlcStateFailed,
update.Htlcs[getCircuitKey(0)].State,
)
@@ -4075,7 +4079,7 @@ func testPendingSettleDuplicateReconcileOnStart(t *testing.T,
require.Equal(t, invpkg.ContractSettled, stored.State)
require.Equal(t, testInvoiceAmount, stored.AmtPaid)
require.EqualValues(t, 1, stored.SettleIndex)
- require.Equal(t, invpkg.HtlcStateCanceled, stored.Htlcs[key].State)
+ require.Equal(t, invpkg.HtlcStateFailed, stored.Htlcs[key].State)
}
// failingFinalizeDB arranges transient write failures while delegating all
@@ -4286,7 +4290,7 @@ func testPendingSettleRecordedOutcomeWins(t *testing.T,
{
name: "failure recorded during scan",
recordFailure: true,
- wantHtlcState: invpkg.HtlcStateCanceled,
+ wantHtlcState: invpkg.HtlcStateFailed,
wantState: invpkg.ContractCanceled,
},
{
### invoices/invoices.go
@@ -222,12 +222,13 @@ const (
// ContractOpen means the invoice has only been created.
ContractOpen ContractState = 0
- // ContractSettled means an ordinary invoice completed a final payment,
- // possibly for less than its requested amount. A later duplicate HTLC
- // can still await its own final outcome while the parent stays settled.
+ // ContractSettled means an ordinary invoice collected every released
+ // payment HTLC. A later duplicate HTLC can still await its own final
+ // outcome while the parent stays settled.
ContractSettled ContractState = 1
- // ContractCanceled means the invoice has been canceled.
+ // ContractCanceled means the invoice has been canceled. If a released
+ // HTLC failed, AmtPaid retains the funds collected from other HTLCs.
ContractCanceled ContractState = 2
// ContractAccepted means the HTLC has been accepted but not settled
@@ -238,9 +239,9 @@ const (
// released the preimage, but at least one of its htlcs has not been
// irrevocably settled yet. Until then the payer can still recover an
// htlc on chain, so the invoice must not be reported as paid. The
- // invoice can no longer be canceled, and moves to ContractSettled
- // once every outcome is known and at least one HTLC settled, or to
- // ContractCanceled if all failed. AMP invoices retain their existing
+ // invoice cannot be manually canceled. Once every outcome is known,
+ // it moves to ContractSettled only if all released HTLCs settled, or
+ // ContractCanceled if any failed. AMP invoices retain their existing
// set-level settlement behavior and do not enter this state.
ContractPendingSettle ContractState = 4
)
@@ -562,9 +563,14 @@ const (
// HtlcStatePendingSettle indicates that we released the preimage for
// an ordinary htlc, but its settlement is not irrevocable yet. It moves
// to HtlcStateSettled once the settle is locked in off chain or the
- // htlc is swept on chain, and to HtlcStateCanceled if the payer
+ // htlc is swept on chain, and to HtlcStateFailed if the payer
// reclaims it on chain instead.
HtlcStatePendingSettle
+
+ // HtlcStateFailed indicates a final failure after an ordinary HTLC's
+ // preimage was released. Unlike an attempt canceled before release,
+ // this prevents a pending invoice from completing successfully.
+ HtlcStateFailed
)
// String identifies the HTLC state in logs, distinguishing preimage release
@@ -582,6 +588,9 @@ func (h HtlcState) String() string {
case HtlcStatePendingSettle:
return "PendingSettle"
+
+ case HtlcStateFailed:
+ return "Failed"
}
return "Unknown"
@@ -590,7 +599,7 @@ func (h HtlcState) String() string {
// PreimageReleased returns true if we decided to settle the htlc and may have
// revealed its preimage to our peer, whether or not the settle is final yet.
// The preimage of such an htlc must stay available so that it can be claimed
-// on chain.
+// on chain. A final failure no longer has an outstanding claim.
func (h HtlcState) PreimageReleased() bool {
return h == HtlcStateSettled || h == HtlcStatePendingSettle
}
### invoices/invoices_test.go
@@ -219,6 +219,10 @@ func TestInvoices(t *testing.T) {
name: "FinalizeHtlcs",
test: testFinalizeHtlcs,
},
+ {
+ name: "SettleCollection",
+ test: testSettleCollection,
+ },
}
makeKeyValueDB := func(t *testing.T) invpkg.InvoiceDB {
@@ -2918,8 +2922,8 @@ func testAddInvoiceInvalidFeatureDeps(t *testing.T,
))
}
-// testFinalizeHtlcs asserts that a settled invoice waits for the final outcome
-// of its htlcs, and that only the htlcs that settled count as paid.
+// testFinalizeHtlcs asserts that an invoice waits for every final outcome,
+// then cancels on partial collection while preserving the received funds.
func testFinalizeHtlcs(t *testing.T,
makeDB func(t *testing.T) invpkg.InvoiceDB) {
@@ -3017,28 +3021,28 @@ func testFinalizeHtlcs(t *testing.T,
)
require.ErrorIs(t, err, invpkg.ErrHTLCAlreadySettled)
- // The payer reclaims the second htlc on chain. The invoice is settled
- // for the amount of the first htlc only.
+ // The payer reclaims the second htlc on chain. The invoice is canceled
+ // but retains the amount collected from the first htlc.
dbInvoice, err = db.UpdateInvoice(
ctxb, ref, nil, getFinalizeHtlcs(false, htlc1),
)
require.NoError(t, err)
- require.Equal(t, invpkg.ContractSettled, dbInvoice.State)
+ require.Equal(t, invpkg.ContractCanceled, dbInvoice.State)
require.Equal(t, amt/2, dbInvoice.AmtPaid)
- require.EqualValues(t, 1, dbInvoice.SettleIndex)
- require.False(t, dbInvoice.SettleDate.IsZero())
+ require.Zero(t, dbInvoice.SettleIndex)
+ require.True(t, dbInvoice.SettleDate.IsZero())
require.Equal(
- t, invpkg.HtlcStateCanceled, dbInvoice.Htlcs[htlc1].State,
+ t, invpkg.HtlcStateFailed, dbInvoice.Htlcs[htlc1].State,
)
// The stored invoice matches.
stored, err := db.LookupInvoice(ctxb, ref)
require.NoError(t, err)
- require.Equal(t, invpkg.ContractSettled, stored.State)
+ require.Equal(t, invpkg.ContractCanceled, stored.State)
require.Equal(t, amt/2, stored.AmtPaid)
- require.EqualValues(t, 1, stored.SettleIndex)
+ require.Zero(t, stored.SettleIndex)
require.Equal(t, invpkg.HtlcStateSettled, stored.Htlcs[htlc0].State)
- require.Equal(t, invpkg.HtlcStateCanceled, stored.Htlcs[htlc1].State)
+ require.Equal(t, invpkg.HtlcStateFailed, stored.Htlcs[htlc1].State)
pending, err = db.FetchPendingInvoices(ctxb)
require.NoError(t, err)
### invoices/settle_collection_registry_test.go
@@ -0,0 +1,130 @@
+package invoices_test
+
+import (
+ "testing"
+ "time"
+
+ "github.com/lightningnetwork/lnd/clock"
+ invpkg "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/stretchr/testify/require"
+)
+
+// testPendingSettleMixedRecovery checks that a released failure survives a
+// registry restart without prematurely canceling or crediting the payment.
+func testPendingSettleMixedRecovery(t *testing.T,
+ makeDB func(t *testing.T) (invpkg.InvoiceDB, *clock.TestClock)) {
+
+ t.Parallel()
+
+ // Arrange a released two-shard payment on the real selected backend,
+ // keeping its database and clock across a later registry restart.
+ db, testClock := makeDB(t)
+ invoice := newInvoice(t, false, false)
+ _, err := db.AddInvoice(t.Context(), invoice, testInvoicePaymentHash)
+ require.NoError(t, err)
+ ref := invpkg.InvoiceRefByHash(testInvoicePaymentHash)
+ failedKey, successKey := getCircuitKey(0), getCircuitKey(1)
+ htlcs := make(map[invpkg.CircuitKey]*invpkg.HtlcAcceptDesc)
+ for _, key := range []invpkg.CircuitKey{failedKey, successKey} {
+ htlcs[key] = &invpkg.HtlcAcceptDesc{
+ Amt: testInvoiceAmount / 2,
+ CustomRecords: make(record.CustomSet),
+ }
+ }
+ _, err = db.UpdateInvoice(t.Context(), ref, nil,
+ func(inv *invpkg.Invoice) (*invpkg.InvoiceUpdateDesc, error) {
+ return &invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.AddHTLCsUpdate,
+ AddHtlcs: htlcs,
+ State: &invpkg.InvoiceStateUpdateDesc{
+ NewState: invpkg.ContractPendingSettle,
+ Preimage: inv.Terms.PaymentPreimage,
+ },
+ }, nil
+ },
+ )
+ require.NoError(t, err)
+
+ // makeRegistryDB reuses persistent invoice state after the registry
+ // restarts, so recovery reads the actual stored failure.
+ makeRegistryDB := func(*testing.T) (invpkg.InvoiceDB,
+ *clock.TestClock) {
+
+ return db, testClock
+ }
+ // Act by persisting the first released failure before starting a new
+ // registry; its sibling still needs a final collection outcome.
+ _, err = db.UpdateInvoice(
+ t.Context(), ref, nil, getFinalizeHtlcs(false, failedKey),
+ )
+ require.NoError(t, err)
+
+ // Assert that one failure cannot finish a payment while another shard
+ // can still be claimed, and that failure evidence survives in storage.
+ stored, err := db.LookupInvoice(t.Context(), ref)
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractPendingSettle, stored.State)
+ require.Equal(t, invpkg.HtlcStateFailed, stored.Htlcs[failedKey].State)
+ require.Equal(t, testInvoiceAmount/2, stored.AmtPaid)
+ require.Zero(t, stored.SettleIndex)
+
+ // Arrange fresh subscriptions after restart so the recovered pending
+ // invoice and any later paid event are observed independently.
+ ctx := newTestContext(t, nil, makeRegistryDB)
+ all, err := ctx.registry.SubscribeNotifications(
+ t.Context(), stored.AddIndex, 0,
+ )
+ require.NoError(t, err)
+ defer all.Cancel()
+ single, err := ctx.registry.SubscribeSingleInvoice(
+ t.Context(), testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
+ defer single.Cancel()
+ var update *invpkg.Invoice
+ select {
+ case update = <-single.Updates:
+ case <-time.After(testTimeout):
+ t.Fatal("missing initial invoice update")
+ }
+ require.Equal(t, invpkg.ContractPendingSettle, update.State)
+
+ // Act by delivering the remaining success after restart; the stored
+ // failure must still prevent successful completion of the payment.
+ ctx.finalizeHtlc(ref, successKey, true)
+ for update.State == invpkg.ContractPendingSettle {
+ select {
+ case update = <-single.Updates:
+ case <-time.After(testTimeout):
+ t.Fatal("missing mixed-outcome invoice update")
+ }
+ }
+ // Assert that cancellation preserves the collected funds and both final
+ // outcomes without allocating settlement metadata or issuing paid
+ // events.
+ require.Equal(t, invpkg.ContractCanceled, update.State)
+ require.Equal(t, testInvoiceAmount/2, update.AmtPaid)
+ require.Equal(
+ t, invpkg.HtlcStateSettled, update.Htlcs[successKey].State,
+ )
+ require.Equal(t, invpkg.HtlcStateFailed, update.Htlcs[failedKey].State)
+ require.Zero(t, update.SettleIndex)
+ require.True(t, update.SettleDate.IsZero())
+ select {
+ case inv := <-all.SettledInvoices:
+ t.Fatalf("partial collection reported as paid: %v", inv)
+ case <-time.After(100 * time.Millisecond):
+ }
+
+ // Act by replaying the failed circuit through off-chain admission;
+ // the final failure must remain a normal invoice rejection.
+ resolution, err := ctx.registry.NotifyExitHopHtlc(
+ testInvoicePaymentHash, testInvoiceAmount/2, testHtlcExpiry,
+ testCurrentHeight, failedKey, nil, nil, testPayload,
+ )
+ require.NoError(t, err)
+ // Assert the stored final failure returns a normal HTLC rejection,
+ // preserving the canceled payment rather than reviving its preimage.
+ checkFailResolution(t, resolution, invpkg.ResultReplayToCanceled)
+}
### invoices/settle_collection_test.go
@@ -0,0 +1,227 @@
+package invoices_test
+
+import (
+ "testing"
+
+ "github.com/lightningnetwork/lnd/graph/db/models"
+ invpkg "github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/record"
+ "github.com/stretchr/testify/require"
+)
+
+// testSettleCollection checks persisted collection outcomes through each
+// invoice database backend, including failures followed by later successes.
+func testSettleCollection(t *testing.T,
+ makeDB func(t *testing.T) invpkg.InvoiceDB) {
+
+ t.Parallel()
+
+ const value = lnwire.MilliSatoshi(1_000_000)
+ tests := []struct {
+ name string
+ outcomes [2]bool
+ batch bool
+ preCanceled bool
+ perHTLC lnwire.MilliSatoshi
+ wantState invpkg.ContractState
+ }{
+ {
+ name: "failure first",
+ outcomes: [2]bool{false, true},
+ perHTLC: value / 2,
+ wantState: invpkg.ContractCanceled,
+ },
+ {
+ name: "all success",
+ outcomes: [2]bool{true, true},
+ perHTLC: value / 2,
+ wantState: invpkg.ContractSettled,
+ },
+ {
+ name: "all failed",
+ outcomes: [2]bool{false, false},
+ perHTLC: value / 2,
+ wantState: invpkg.ContractCanceled,
+ },
+ {
+ name: "mixed batch",
+ outcomes: [2]bool{true, false},
+ batch: true,
+ perHTLC: value / 2,
+ wantState: invpkg.ContractCanceled,
+ },
+ {
+ name: "overpayment with loss",
+ outcomes: [2]bool{true, false},
+ batch: true,
+ perHTLC: 3 * value / 2,
+ wantState: invpkg.ContractCanceled,
+ },
+ {
+ name: "prior canceled attempt",
+ outcomes: [2]bool{true, true},
+ preCanceled: true,
+ perHTLC: value / 2,
+ wantState: invpkg.ContractSettled,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ // Arrange: Persist a two-shard payment awaiting
+ // final outcomes. Optionally precede it with a
+ // canceled attempt to check later collections.
+ ctx := t.Context()
+ db := makeDB(t)
+ invoice, err := randInvoice(value)
+ require.NoError(t, err)
+ payHash := invoice.Terms.PaymentPreimage.Hash()
+ _, err = db.AddInvoice(ctx, invoice, payHash)
+ require.NoError(t, err)
+ ref := invpkg.InvoiceRefByHash(payHash)
+ apply := func(update *invpkg.InvoiceUpdateDesc) {
+ callback := func(*invpkg.Invoice) (
+ *invpkg.InvoiceUpdateDesc, error) {
+
+ return update, nil
+ }
+ _, err := db.UpdateInvoice(
+ ctx, ref, nil, callback,
+ )
+ require.NoError(t, err)
+ }
+
+ canceledKey := models.CircuitKey{HtlcID: 0}
+ keys := [2]models.CircuitKey{{HtlcID: 1}, {HtlcID: 2}}
+ accepts := make(
+ map[models.CircuitKey]*invpkg.HtlcAcceptDesc,
+ )
+ for _, key := range append(keys[:], canceledKey) {
+ accepts[key] = &invpkg.HtlcAcceptDesc{
+ Amt: test.perHTLC,
+ CustomRecords: make(record.CustomSet),
+ }
+ }
+
+ // A timed-out attempt must not poison a later payment.
+ prior := make(
+ map[models.CircuitKey]*invpkg.HtlcAcceptDesc,
+ )
+ if test.preCanceled {
+ prior[canceledKey] = accepts[canceledKey]
+ apply(&invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.AddHTLCsUpdate,
+ AddHtlcs: prior,
+ })
+ cancels := map[models.CircuitKey]struct{}{
+ canceledKey: {},
+ }
+ apply(&invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.CancelHTLCsUpdate,
+ CancelHtlcs: cancels,
+ })
+ }
+ delete(accepts, canceledKey)
+ state := &invpkg.InvoiceStateUpdateDesc{
+ NewState: invpkg.ContractPendingSettle,
+ Preimage: invoice.Terms.PaymentPreimage,
+ }
+ apply(&invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.AddHTLCsUpdate,
+ AddHtlcs: accepts,
+ State: state,
+ })
+
+ // Act: Apply single outcomes in order; batch cases
+ // defer the update until both outcomes are ready.
+ var collected lnwire.MilliSatoshi
+ for n, success := range test.outcomes {
+ if success {
+ collected += test.perHTLC
+ }
+ if test.batch {
+ continue
+ }
+
+ _, err = db.UpdateInvoice(ctx, ref, nil,
+ getFinalizeHtlcs(success, keys[n]),
+ )
+ require.NoError(t, err)
+
+ // Assert: Reload before the remaining shard
+ // finishes; the invoice must stay pending.
+ stored, err := db.LookupInvoice(ctx, ref)
+ require.NoError(t, err)
+ htlcState := stored.Htlcs[keys[n]].State
+ if n == 0 {
+ require.Equal(
+ t, invpkg.ContractPendingSettle,
+ stored.State,
+ )
+ require.Equal(t, collected+test.perHTLC,
+ stored.AmtPaid)
+ require.Zero(t, stored.SettleIndex)
+ require.True(
+ t, stored.SettleDate.IsZero(),
+ )
+ want := invpkg.HtlcStateFailed
+ if success {
+ want = invpkg.HtlcStateSettled
+ }
+ require.Equal(t, want, htlcState)
+ }
+ }
+
+ if test.batch {
+ // Act: Submit both outcomes together to check
+ // collection within a single database update.
+ finalize := map[models.CircuitKey]bool{
+ keys[0]: test.outcomes[0],
+ keys[1]: test.outcomes[1],
+ }
+ update := &invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.
+ FinalizeHTLCsUpdate,
+ FinalizeHtlcs: finalize,
+ }
+ callback := func(*invpkg.Invoice) (
+ *invpkg.InvoiceUpdateDesc, error) {
+
+ return update, nil
+ }
+ _, err = db.UpdateInvoice(
+ ctx, ref, nil, callback,
+ )
+ require.NoError(t, err)
+ }
+
+ // Assert: Reload to check final state, receipts,
+ // settlement metadata and stored HTLC outcomes.
+ stored, err := db.LookupInvoice(ctx, ref)
+ require.NoError(t, err)
+ require.Equal(t, test.wantState, stored.State)
+ require.Equal(t, collected, stored.AmtPaid)
+ if test.wantState == invpkg.ContractSettled {
+ require.NotZero(t, stored.SettleIndex)
+ require.False(t, stored.SettleDate.IsZero())
+ } else {
+ require.Zero(t, stored.SettleIndex)
+ require.True(t, stored.SettleDate.IsZero())
+ }
+ for n, key := range keys {
+ want := invpkg.HtlcStateFailed
+ if test.outcomes[n] {
+ want = invpkg.HtlcStateSettled
+ }
+ require.Equal(t, want, stored.Htlcs[key].State)
+ }
+ if test.preCanceled {
+ require.Equal(t, invpkg.HtlcStateCanceled,
+ stored.Htlcs[canceledKey].State)
+ }
+ })
+ }
+}
### invoices/sql_migration_test.go
@@ -115,6 +115,11 @@ func randHTLCRapid(t *rapid.T, invoice *Invoice, amt lnwire.MilliSatoshi) (
case ContractCanceled:
htlc.State = HtlcStateCanceled
+ if !invoice.IsAMP() {
+ htlc.State = rapid.SampledFrom([]HtlcState{
+ HtlcStateCanceled, HtlcStateFailed,
+ }).Draw(t, "canceledHtlcState")
+ }
htlc.ResolveTime = randInvoiceTime(invoice)
case ContractAccepted:
### invoices/update.go
@@ -121,7 +121,7 @@ func resolveReplayedHtlc(ctx *invoiceUpdateCtx, inv *Invoice) (bool,
}
switch htlc.State {
- case HtlcStateCanceled:
+ case HtlcStateCanceled, HtlcStateFailed:
return true, ctx.failRes(ResultReplayToCanceled), nil
case HtlcStateAccepted:
### invoices/update_invoice.go
@@ -629,7 +629,7 @@ func finalizeHTLCs(invoice *Invoice, updateTime time.Time,
newState := HtlcStateSettled
if !settled {
- newState = HtlcStateCanceled
+ newState = HtlcStateFailed
}
err := resolveHtlc(key, htlc, newState, updateTime, updater)
@@ -640,18 +640,21 @@ func finalizeHTLCs(invoice *Invoice, updateTime time.Time,
// The amount paid only counts htlcs that settled or may still settle.
var amtPaid lnwire.MilliSatoshi
- var pending bool
+ var pending, failed bool
for _, htlc := range invoice.Htlcs {
if htlc.State.PreimageReleased() {
amtPaid += htlc.Amt
}
pending = pending || htlc.State == HtlcStatePendingSettle
+ failed = failed || htlc.State == HtlcStateFailed
}
if invoice.State == ContractPendingSettle && !pending {
newState := ContractSettled
- if amtPaid == 0 {
+ // Only a lost released HTLC prevents collection. Earlier
+ // canceled attempts never released a preimage and don't count.
+ if failed {
newState = ContractCanceled
}
### lnrpc/invoicesrpc/addinvoice_test.go
@@ -13,6 +13,7 @@ import (
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/invoices"
"github.com/lightningnetwork/lnd/lnrpc"
+ "github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/zpay32"
@@ -31,53 +32,90 @@ var (
)
// TestCreateRPCInvoiceFinalHtlcOutcomes verifies that RPC callers see pending
-// releases without final timestamps and completed outcomes with their credit.
+// releases without final timestamps and can distinguish released collection
+// failures from cancellations that did not release the invoice preimage.
func TestCreateRPCInvoiceFinalHtlcOutcomes(t *testing.T) {
t.Parallel()
- // Arrange the two snapshots previously checked by the database test.
- // Both children have stored timestamps even when pending, so zero RPC
- // times must result from hiding provisional resolution information.
+ // Arrange snapshots with known preimages so release history must come
+ // from payment outcomes rather than secret availability. Stored times
+ // also distinguish final outcomes from provisional pending timestamps.
const amount = lnwire.MilliSatoshi(1000)
resolvedAt := time.Unix(10, 0)
+ preimage := lntypes.Preimage{1}
testCases := []struct {
name string
state invoices.ContractState
- htlcStates [2]invoices.HtlcState
+ htlcStates []invoices.HtlcState
rpcState lnrpc.Invoice_InvoiceState
- rpcHtlcState [2]lnrpc.InvoiceHTLCState
+ rpcHtlcState []lnrpc.InvoiceHTLCState
amtPaid lnwire.MilliSatoshi
resolveTime int64
+ released bool
}{
{
name: "pending outcomes",
state: invoices.ContractPendingSettle,
- htlcStates: [2]invoices.HtlcState{
+ htlcStates: []invoices.HtlcState{
invoices.HtlcStatePendingSettle,
invoices.HtlcStatePendingSettle,
},
rpcState: lnrpc.Invoice_PENDING_SETTLE,
- rpcHtlcState: [2]lnrpc.InvoiceHTLCState{
+ rpcHtlcState: []lnrpc.InvoiceHTLCState{
lnrpc.InvoiceHTLCState_PENDING_SETTLE,
lnrpc.InvoiceHTLCState_PENDING_SETTLE,
},
amtPaid: amount,
resolveTime: 0,
+ released: true,
},
{
- name: "final outcomes",
- state: invoices.ContractSettled,
- htlcStates: [2]invoices.HtlcState{
+ name: "mixed final outcomes",
+ state: invoices.ContractCanceled,
+ htlcStates: []invoices.HtlcState{
invoices.HtlcStateSettled,
- invoices.HtlcStateCanceled,
+ invoices.HtlcStateFailed,
},
- rpcState: lnrpc.Invoice_SETTLED,
- rpcHtlcState: [2]lnrpc.InvoiceHTLCState{
+ rpcState: lnrpc.Invoice_CANCELED,
+ rpcHtlcState: []lnrpc.InvoiceHTLCState{
lnrpc.InvoiceHTLCState_SETTLED,
- lnrpc.InvoiceHTLCState_CANCELED,
+ lnrpc.InvoiceHTLCState_FAILED,
},
amtPaid: amount / 2,
resolveTime: resolvedAt.Unix(),
+ released: true,
+ },
+ {
+ name: "canceled before release",
+ state: invoices.ContractCanceled,
+ htlcStates: []invoices.HtlcState{
+ invoices.HtlcStateCanceled,
+ },
+ rpcState: lnrpc.Invoice_CANCELED,
+ rpcHtlcState: []lnrpc.InvoiceHTLCState{
+ lnrpc.InvoiceHTLCState_CANCELED,
+ },
+ resolveTime: resolvedAt.Unix(),
+ },
+ {
+ name: "all released HTLCs failed",
+ state: invoices.ContractCanceled,
+ htlcStates: []invoices.HtlcState{
+ invoices.HtlcStateFailed,
+ },
+ rpcState: lnrpc.Invoice_CANCELED,
+ rpcHtlcState: []lnrpc.InvoiceHTLCState{
+ lnrpc.InvoiceHTLCState_FAILED,
+ },
+ resolveTime: resolvedAt.Unix(),
+ released: true,
+ },
+ {
+ name: "legacy settled without HTLCs",
+ state: invoices.ContractSettled,
+ rpcState: lnrpc.Invoice_SETTLED,
+ amtPaid: amount,
+ released: true,
},
}
@@ -92,7 +130,8 @@ func TestCreateRPCInvoiceFinalHtlcOutcomes(t *testing.T) {
State: tc.state,
AmtPaid: tc.amtPaid,
Terms: invoices.ContractTerm{
- Value: amount,
+ Value: amount,
+ PaymentPreimage: &preimage,
},
}
invoice.Htlcs = make(
@@ -113,15 +152,18 @@ func TestCreateRPCInvoiceFinalHtlcOutcomes(t *testing.T) {
// and subscriptions, without involving storage.
rpcInvoice, err := CreateRPCInvoice(invoice, nil)
- // Assert states and paid credit at the RPC boundary.
- // Pending children hide provisional times; final
- // children expose their actual resolution time.
+ // Assert states, release history and credit at the RPC
+ // boundary. Pending children hide provisional times;
+ // final children expose their actual resolution time.
require.NoError(t, err)
require.Equal(t, tc.rpcState, rpcInvoice.State)
+ require.Equal(
+ t, tc.released, rpcInvoice.PreimageReleased,
+ )
require.EqualValues(
t, tc.amtPaid, rpcInvoice.AmtPaidMsat,
)
- require.Len(t, rpcInvoice.Htlcs, 2)
+ require.Len(t, rpcInvoice.Htlcs, len(tc.rpcHtlcState))
for n, htlc := range rpcInvoice.Htlcs {
require.Equal(t, tc.rpcHtlcState[n], htlc.State)
require.Equal(
### lnrpc/invoicesrpc/utils.go
@@ -80,6 +80,12 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
satAmtPaid := invoice.AmtPaid.ToSatoshis()
isSettled := invoice.State == invoices.ContractSettled
+ isAMP := invoice.IsAMP()
+
+ // State records the release decision, unlike a known preimage, which
+ // ordinary invoices can have before payment. Preserve legacy settled
+ // headers even when their original HTLC records are unavailable.
+ preimageReleased := !isAMP && invoice.State.PreimageReleased()
var state lnrpc.Invoice_InvoiceState
switch invoice.State {
@@ -113,12 +119,23 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
state = lnrpc.InvoiceHTLCState_SETTLED
case invoices.HtlcStateCanceled:
state = lnrpc.InvoiceHTLCState_CANCELED
+ case invoices.HtlcStateFailed:
+ state = lnrpc.InvoiceHTLCState_FAILED
case invoices.HtlcStatePendingSettle:
state = lnrpc.InvoiceHTLCState_PENDING_SETTLE
default:
return nil, fmt.Errorf("unknown state %v", htlc.State)
}
+ // A canceled parent can still carry release history after every
+ // released child failed. Keep this separate from the predicate
+ // used for active claims and paid-value accounting.
+ if !isAMP && (htlc.State.PreimageReleased() ||
+ htlc.State == invoices.HtlcStateFailed) {
+
+ preimageReleased = true
+ }
+
rpcHtlc := lnrpc.InvoiceHTLC{
ChanId: key.ChanID.ToUint64(),
HtlcIndex: key.HtlcID,
@@ -164,7 +181,8 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
// pending HTLC has no final resolution time to expose to RPC
// callers.
if htlc.State == invoices.HtlcStateSettled ||
- htlc.State == invoices.HtlcStateCanceled {
+ htlc.State == invoices.HtlcStateCanceled ||
+ htlc.State == invoices.HtlcStateFailed {
rpcHtlc.ResolveTime = htlc.ResolveTime.Unix()
}
@@ -204,9 +222,10 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
Features: CreateRPCFeatures(invoice.Terms.Features),
IsKeysend: invoice.IsKeysend(),
PaymentAddr: invoice.Terms.PaymentAddr[:],
- IsAmp: invoice.IsAMP(),
+ IsAmp: isAMP,
IsBlinded: invoice.IsBlinded(),
}
+ rpcInvoice.PreimageReleased = preimageReleased
rpcInvoice.AmpInvoiceState = make(map[string]*lnrpc.AMPInvoiceState)
for setID, ampState := range invoice.AMPState {Why this scored 59/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.