What changed, and why it matters
This commit changes how LND marks invoices as 'paid.' Previously, when a payment arrived, LND immediately marked the invoice as fully settled. Now, for ordinary, multi-part, and hold invoices, LND first releases the payment preimage to the peer but keeps the invoice in a new 'pending settle' state. It only flips the invoice to 'settled' once the underlying HTLC outcomes are recorded as final. AMP invoices keep their old behavior for now. The change is designed to prevent double-counting, incorrect settlement indexes, and premature credit allocation if a payment later fails or is replayed.
Treat this as a behavior-hardening change rather than an active vulnerability fix. Reviewers should verify that all code paths that previously assumed immediate settlement now handle ContractPendingSettle correctly, especially around RPC subscriptions, accounting, and any external integrations that poll invoice state. Run the updated integration tests and confirm that the new FinalizeHTLCsUpdate path is exercised on restart/replay paths.
Security signals we found
New intermediate state prevents premature settlement-index allocation and credit finalization before HTLC finality
Replayed HTLCs in HtlcStatePendingSettle are now re-settled so a peer that already learned the preimage is not left without resolution
Canceling an invoice is blocked once the preimage has been released (ContractPendingSettle), reducing risk of inconsistent state
RPC projection hides ResolveTime for pending-settle HTLCs, avoiding misleading final timestamps
Hold invoice settlement now also uses pending-settle semantics, matching ordinary/MPP behavior
Evidence from the diff
The patch introduces a new invoice contract state ContractPendingSettle and a new HTLC state HtlcStatePendingSettle. For non-AMP invoices, NotifyExitHopHtlc and SettleHodlInvoice now transition invoices to ContractPendingSettle and HTLCs to HtlcStatePendingSettle when the preimage is released, instead of immediately moving to ContractSettled/HtlcStateSettled. Final settlement is then driven by a new FinalizeHTLCsUpdate path that records per-HTLC final outcomes. The RPC layer maps the new state to Invoice_PENDING_SETTLE and hides ResolveTime for pending HTLCs. Settlement-index allocation is deferred to finalization for ordinary/hodl invoices, while AMP continues to allocate per-set settlement indexes at preimage release. Tests are updated to call finalizeHtlc before asserting final settlement.
Changed components
invoices/invoiceregistry.goinvoices/update.goinvoices/update_invoice.gochanneldb/invoices.golnrpc/invoicesrpc/utils.goinvoices/invoiceregistry_test.goinvoices/invoices_test.goinvoices/update_invoice_test.goinvoices/sql_migration_test.golnrpc/invoicesrpc/addinvoice_test.goitest/lnd_mpp_test.goitest/lnd_route_blinding_test.goitest/lnd_routing_test.goitest/lnd_single_hop_invoice_test.goitest/lnd_sweep_test.goInspect captured patch +516 / −130
### channeldb/invoices.go
@@ -955,18 +955,8 @@ func (k *kvInvoiceUpdater) storeAddHtlcsUpdate() error {
}
}
- // If this is a non-AMP invoice, then the state can eventually go to
- // ContractSettled, so we pass in nil value as part of
- // setSettleMetaFields.
- if !invoiceIsAMP && k.invoice.State == invpkg.ContractSettled {
- err := k.setSettleMetaFields(nil)
- if err != nil {
- return err
- }
- }
-
- // As we don't update the settle index above for AMP invoices, we'll do
- // it here for each sub-AMP invoice that was settled.
+ // Ordinary invoices allocate their index at finalization. AMP keeps
+ // allocating its existing per-set settlement index at preimage release.
for settledSetID := range k.settledSetIDs {
err := k.setSettleMetaFields(&settledSetID)
if err != nil {
@@ -990,13 +980,8 @@ func (k *kvInvoiceUpdater) storeAddHtlcsUpdate() error {
}
// storeSettleHodlInvoiceUpdate updates the invoice in the database after
-// settling a hodl invoice.
+// releasing a hodl preimage. Finalization assigns its settlement index.
func (k *kvInvoiceUpdater) storeSettleHodlInvoiceUpdate() error {
- err := k.setSettleMetaFields(nil)
- if err != nil {
- return err
- }
-
return k.serializeAndStoreInvoice()
}
### invoices/invoiceregistry.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "maps"
"sync"
"sync/atomic"
"time"
@@ -347,7 +348,8 @@ func (i *InvoiceRegistry) invoiceEventLoop() {
// invoice subscribers of cancel and accept events.
state := event.invoice.State
if state != ContractCanceled &&
- state != ContractAccepted {
+ state != ContractAccepted &&
+ state != ContractPendingSettle {
i.dispatchToClients(event)
}
@@ -1323,6 +1325,13 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
log.Tracef("Settlement resolution: %T %v", resolution, resolution)
+ // Wait for the final outcome of all htlcs we released the preimage
+ // for. We hold the registry lock until the links learn the
+ // resolutions below, so no outcome can arrive before this.
+ if _, ok := resolution.(*HtlcSettleResolution); ok {
+ i.trackPendingSettles(ctx.hash, invoice)
+ }
+
switch res := resolution.(type) {
case *HtlcFailResolution:
// Inspect latest htlc state on the invoice. If it is found,
@@ -1366,11 +1375,13 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
"outcome: %v, at accept height: %v",
res.Outcome, res.AcceptHeight))
- // Also settle any previously accepted htlcs. If a htlc is
- // marked as settled, we should follow now and settle the htlc
- // with our peer.
+ // Also settle any previously accepted htlcs. If we released
+ // the preimage of an htlc, we should follow now and settle the
+ // htlc with our peer.
setID := ctx.setID()
- settledHtlcSet := invoice.HTLCSet(setID, HtlcStateSettled)
+ settledHtlcSet := invoice.HTLCSet(setID, HtlcStatePendingSettle)
+ finalHtlcSet := invoice.HTLCSet(setID, HtlcStateSettled)
+ maps.Copy(settledHtlcSet, finalHtlcSet)
for key, htlc := range settledHtlcSet {
preimage := res.Preimage
if htlc.AMP != nil && htlc.AMP.Preimage != nil {
@@ -1490,14 +1501,14 @@ func (i *InvoiceRegistry) SettleHodlInvoice(ctx context.Context,
case ContractCanceled:
return nil, ErrInvoiceAlreadyCanceled
- case ContractSettled:
+ case ContractSettled, ContractPendingSettle:
return nil, ErrInvoiceAlreadySettled
}
return &InvoiceUpdateDesc{
UpdateType: SettleHodlInvoiceUpdate,
State: &InvoiceStateUpdateDesc{
- NewState: ContractSettled,
+ NewState: ContractPendingSettle,
Preimage: &preimage,
},
}, nil
@@ -1524,14 +1535,19 @@ func (i *InvoiceRegistry) SettleHodlInvoice(ctx context.Context,
log.Debugf("Invoice%v: settled with preimage %v", invoiceRef,
invoice.Terms.PaymentPreimage)
- // In the callback, we marked the invoice as settled. UpdateInvoice will
- // have seen this and should have moved all htlcs that were accepted to
- // the settled state. In the loop below, we go through all of these and
- // notify links and resolvers that are waiting for resolution. Any htlcs
- // that were already settled before, will be notified again. This isn't
- // necessary but doesn't hurt either.
+ // Wait for the final outcome of the htlcs before the links and
+ // resolvers learn the preimage.
+ i.trackPendingSettles(hash, invoice)
+
+ // In the callback, we marked the invoice as pending settle.
+ // UpdateInvoice will have seen this and should have moved all htlcs
+ // that were accepted to the pending settle state. In the loop below,
+ // we go through all of these and notify links and resolvers that are
+ // waiting for resolution. Any htlcs that were already settled before,
+ // will be notified again. This isn't necessary but doesn't hurt
+ // either.
for key, htlc := range invoice.Htlcs {
- if htlc.State != HtlcStateSettled {
+ if !htlc.State.PreimageReleased() {
continue
}
### invoices/invoiceregistry_test.go
@@ -1188,6 +1188,9 @@ func testSettleInvoice(t *testing.T,
t.Parallel()
+ // Arrange: Prepare both notification forms and an open invoice so
+ // release and final settlement can be observed independently.
+
ctx := newTestContext(t, nil, makeDB)
ctxb := t.Context()
@@ -1244,7 +1247,9 @@ func testSettleInvoice(t *testing.T,
hodlChan := make(chan interface{}, 1)
- // Try to settle invoice with an htlc that expires too soon.
+ // Try to settle invoice with an htlc that expires too soon. Act: Try an
+ // unseen expired child before releasing a valid payment; final outcomes
+ // are delivered separately below.
resolution, err := ctx.registry.NotifyExitHopHtlc(
testInvoicePaymentHash, testInvoice.Terms.Value,
uint32(testCurrentHeight)+testInvoiceCltvDelta-1,
@@ -1260,6 +1265,16 @@ func testSettleInvoice(t *testing.T,
)
require.Equal(t, testCurrentHeight, failResolution.AcceptHeight)
+ // Rejecting an unseen expired HTLC must not create a stored child or
+ // release the invoice. Keep this assertion beside the existing expiry
+ // case instead of duplicating its setup in a separate height test.
+ unpaid, err := ctx.registry.LookupInvoice(
+ ctxb, testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractOpen, unpaid.State)
+ require.Empty(t, unpaid.Htlcs)
+
// Settle invoice with a slightly higher amount.
amtPaid := lnwire.MilliSatoshi(100500)
resolution, err = ctx.registry.NotifyExitHopHtlc(
@@ -1271,39 +1286,35 @@ func testSettleInvoice(t *testing.T,
t.Fatal(err)
}
require.NotNil(t, resolution)
+ // Assert expiry leaves the invoice open and unrecorded, release reports
+ // pending, and final events establish the settled amount and index.
settleResolution := checkSettleResolution(
t, resolution, testInvoicePreimage,
)
require.Equal(t, invpkg.ResultSettled, settleResolution.Outcome)
- // We expect the settled state to be sent to the single invoice
- // subscriber.
+ // We released the preimage, but the htlc isn't irrevocably settled
+ // yet. We expect the pending settle state to be sent to the single
+ // invoice subscriber.
select {
case update := <-subscription.Updates:
- if update.State != invpkg.ContractSettled {
- t.Fatalf("expected state ContractOpen, but got %v",
- update.State)
- }
- if update.AmtPaid != amtPaid {
- t.Fatal("invoice AmtPaid incorrect")
- }
+ require.Equal(t, invpkg.ContractPendingSettle, update.State)
+ require.Equal(t, amtPaid, update.AmtPaid)
+ require.Zero(t, update.SettleIndex)
case <-time.After(testTimeout):
t.Fatal("no update received")
}
- // We expect a settled notification to be sent out.
+ // Subscribers to all invoices must not see the invoice as settled
+ // yet.
select {
case settledInvoice := <-allSubscriptions.SettledInvoices:
- if settledInvoice.State != invpkg.ContractSettled {
- t.Fatalf("expected state ContractOpen, but got %v",
- settledInvoice.State)
- }
- case <-time.After(testTimeout):
- t.Fatal("no update received")
+ t.Fatalf("unexpected settled invoice: %v", settledInvoice)
+ case <-time.After(100 * time.Millisecond):
}
// Try to settle again with the same htlc id. We need this idempotent
- // behaviour after a restart.
+ // behaviour after a restart, also while the settlement is pending.
resolution, err = ctx.registry.NotifyExitHopHtlc(
testInvoicePaymentHash, amtPaid, testHtlcExpiry,
testCurrentHeight, getCircuitKey(0), hodlChan,
@@ -1316,6 +1327,37 @@ func testSettleInvoice(t *testing.T,
)
require.Equal(t, invpkg.ResultReplayToSettled, settleResolution.Outcome)
+ // The preimage is out, so the invoice can no longer be canceled.
+ err = ctx.registry.CancelInvoice(ctxb, testInvoicePaymentHash)
+ require.ErrorIs(t, err, invpkg.ErrInvoiceAlreadySettled)
+
+ // The link reports that the settle is locked in.
+ ref := invpkg.InvoiceRefByHash(testInvoicePaymentHash)
+ ctx.finalizeHtlc(ref, getCircuitKey(0), true)
+
+ // We expect the settled state to be sent to the single invoice
+ // subscriber.
+ select {
+ case update := <-subscription.Updates:
+ require.Equal(t, invpkg.ContractSettled, update.State)
+ require.Equal(t, amtPaid, update.AmtPaid)
+ require.Equal(
+ t, invpkg.HtlcStateSettled,
+ update.Htlcs[getCircuitKey(0)].State,
+ )
+ case <-time.After(testTimeout):
+ t.Fatal("no update received")
+ }
+
+ // We expect a settled notification to be sent out.
+ select {
+ case settledInvoice := <-allSubscriptions.SettledInvoices:
+ require.Equal(t, invpkg.ContractSettled, settledInvoice.State)
+ require.EqualValues(t, 1, settledInvoice.SettleIndex)
+ case <-time.After(testTimeout):
+ t.Fatal("no update received")
+ }
+
// Try to settle again with a new higher-valued htlc. This payment
// should also be accepted, to prevent any change in behaviour for a
// paid invoice that may open up a probe vector.
@@ -1355,6 +1397,14 @@ func testSettleInvoice(t *testing.T,
amtPaid+amtPaid+600, inv.AmtPaid)
}
+ // The duplicate htlc is pending settlement, while the invoice remains
+ // settled.
+ require.Equal(t, invpkg.ContractSettled, inv.State)
+ require.Equal(
+ t, invpkg.HtlcStatePendingSettle,
+ inv.Htlcs[getCircuitKey(1)].State,
+ )
+
// Try to cancel.
err = ctx.registry.CancelInvoice(ctxb, testInvoicePaymentHash)
require.ErrorIs(t, err, invpkg.ErrInvoiceAlreadySettled)
@@ -1528,10 +1578,12 @@ func testSettleHoldInvoice(t *testing.T,
idb, clock := makeDB(t)
// Instantiate and start the invoice ctx.registry.
+ finalHtlcs := newMockFinalHtlcSource(t)
cfg := invpkg.RegistryConfig{
FinalCltvRejectDelta: testFinalCltvRejectDelta,
Clock: clock,
HtlcInterceptor: &invpkg.MockHtlcModifier{},
+ FinalHtlcSource: finalHtlcs,
}
expiryWatcher := invpkg.NewInvoiceExpiryWatcher(
@@ -1541,7 +1593,11 @@ func testSettleHoldInvoice(t *testing.T,
err := registry.Start()
require.NoError(t, err)
- defer registry.Stop()
+ // Stop the registry before database cleanup and surface any failure
+ // to finish the finality subscription's shutdown.
+ defer func() {
+ require.NoError(t, registry.Stop())
+ }()
ctxb := t.Context()
allSubscriptions, err := registry.SubscribeNotifications(ctxb, 0, 0)
@@ -1652,12 +1708,36 @@ func testSettleHoldInvoice(t *testing.T,
htlcResolution, _ := (<-hodlChan).(invpkg.HtlcResolution)
require.NotNil(t, htlcResolution)
+ // Assert explicit hold release reports pending; the final outcome then
+ // establishes settlement and its first index.
settleResolution := checkSettleResolution(
t, htlcResolution, testInvoicePreimage,
)
require.Equal(t, testCurrentHeight, settleResolution.AcceptHeight)
require.Equal(t, invpkg.ResultSettled, settleResolution.Outcome)
+ // The single invoice subscriber learns that the settlement is pending.
+ update = <-subscription.Updates
+ require.Equal(t, invpkg.ContractPendingSettle, update.State)
+ require.Equal(
+ t, invpkg.HtlcStatePendingSettle,
+ update.Htlcs[getCircuitKey(0)].State,
+ )
+
+ // Settling again is idempotent while pending, and canceling fails.
+ err = registry.SettleHodlInvoice(ctxb, testInvoicePreimage)
+ require.ErrorIs(t, err, invpkg.ErrInvoiceAlreadySettled)
+
+ err = registry.CancelInvoice(ctxb, testInvoicePaymentHash)
+ require.ErrorIs(t, err, invpkg.ErrInvoiceAlreadySettled)
+
+ // The settle is locked in.
+ finalHtlcs.outcomes <- invpkg.FinalHtlcOutcome{
+ Key: getCircuitKey(0),
+ Settled: true,
+ Offchain: true,
+ }
+
// We expect a settled notification to be sent out for both all and
// single invoice subscribers.
settledInvoice := <-allSubscriptions.SettledInvoices
@@ -1817,6 +1897,9 @@ func testKeySendImpl(t *testing.T, keySendEnabled bool,
cfg := defaultRegistryConfig()
cfg.AcceptKeySend = keySendEnabled
+ // Arrange: Configure keysend support and its preimage record so
+ // spontaneous invoice creation follows the normal registry path.
+
ctx := newTestContext(t, &cfg, makeDB)
allSubscriptions, err := ctx.registry.SubscribeNotifications(
@@ -1841,6 +1924,8 @@ func testKeySendImpl(t *testing.T, keySendEnabled bool,
},
}
+ // Act: Notify the registry of the keysend child before delivering any
+ // final channel result.
resolution, err := ctx.registry.NotifyExitHopHtlc(
hash, amt, expiry,
testCurrentHeight, getCircuitKey(10), hodlChan,
@@ -1878,18 +1963,24 @@ func testKeySendImpl(t *testing.T, keySendEnabled bool,
return
}
- checkSubscription := func() {
+ checkSubscription := func(hash lntypes.Hash, key invpkg.CircuitKey) {
// We expect a new invoice notification to be sent out.
newInvoice := <-allSubscriptions.NewInvoices
require.Equal(t, newInvoice.State, invpkg.ContractOpen)
+ // The invoice is settled once the htlc is final.
+ ctx.finalizeHtlc(invpkg.InvoiceRefByHash(hash), key, true)
+
// We expect a settled notification to be sent out.
settledInvoice := <-allSubscriptions.SettledInvoices
require.Equal(t, settledInvoice.State, invpkg.ContractSettled)
}
+ // Assert enabled keysend releases a preimage before final settlement,
+ // while disabled or invalid keysend follows its existing rejection
+ // path.
checkSettleResolution(t, resolution, preimage)
- checkSubscription()
+ checkSubscription(hash, getCircuitKey(10))
// Replay the same keysend payment. We expect an identical resolution,
// but no event should be generated.
@@ -1924,7 +2015,7 @@ func testKeySendImpl(t *testing.T, keySendEnabled bool,
require.Nil(t, err)
checkSettleResolution(t, resolution, preimage2)
- checkSubscription()
+ checkSubscription(hash2, getCircuitKey(20))
}
// testHoldKeysend tests receiving a spontaneous payment that is held.
@@ -1953,6 +2044,9 @@ func testHoldKeysendImpl(t *testing.T, timeoutKeysend bool,
cfg := defaultRegistryConfig()
cfg.AcceptKeySend = true
cfg.KeysendHoldTime = holdDuration
+ // Arrange: Configure the existing hold timer and keysend payload so
+ // timeout and explicit release share the same registry lifecycle.
+
ctx := newTestContext(t, &cfg, makeDB)
ctxb := t.Context()
@@ -1976,6 +2070,8 @@ func testHoldKeysendImpl(t *testing.T, timeoutKeysend bool,
},
}
+ // Act: Submit the held keysend payment and allow the selected release
+ // path to run before finalization.
resolution, err := ctx.registry.NotifyExitHopHtlc(
hash, amt, expiry, testCurrentHeight, getCircuitKey(10),
hodlChan, nil, keysendPayload,
@@ -2028,6 +2124,12 @@ func testHoldKeysendImpl(t *testing.T, timeoutKeysend bool,
ctxb, *newInvoice.Terms.PaymentPreimage,
))
+ // The invoice is settled once the htlc is final.
+ payHash := newInvoice.Terms.PaymentPreimage.Hash()
+ ctx.finalizeHtlc(
+ invpkg.InvoiceRefByHash(payHash), getCircuitKey(10), true,
+ )
+
// We expect a settled notification to be sent out.
settledInvoice := <-allSubscriptions.SettledInvoices
require.Equal(t, settledInvoice.State, invpkg.ContractSettled)
@@ -2042,6 +2144,9 @@ func testMppPayment(t *testing.T,
t.Parallel()
defer timeout()()
+ // Arrange: Create an ordinary invoice and MPP payload so neither
+ // partial shard can release a preimage by itself.
+
ctx := newTestContext(t, nil, makeDB)
ctxb := t.Context()
@@ -2058,6 +2163,8 @@ func testMppPayment(t *testing.T,
// Send htlc 1.
hodlChan1 := make(chan interface{}, 1)
+ // Act: Deliver the two shards through NotifyExitHopHtlc, then supply
+ // their final results independently.
resolution, err := ctx.registry.NotifyExitHopHtlc(
testInvoicePaymentHash, testInvoice.Terms.Value/2,
testHtlcExpiry, testCurrentHeight, getCircuitKey(10),
@@ -2118,9 +2225,23 @@ func testMppPayment(t *testing.T,
settleResolution.Outcome)
}
+ // The invoice waits for both htlcs to be final.
+ inv, err := ctx.registry.LookupInvoice(ctxb, testInvoicePaymentHash)
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractPendingSettle, inv.State)
+
+ ref := invpkg.InvoiceRefByHash(testInvoicePaymentHash)
+ ctx.finalizeHtlc(ref, getCircuitKey(11), true)
+
+ inv, err = ctx.registry.LookupInvoice(ctxb, testInvoicePaymentHash)
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractPendingSettle, inv.State)
+
+ ctx.finalizeHtlc(ref, getCircuitKey(12), true)
+
// Check that settled amount is equal to the sum of values of the htlcs
// 2 and 3.
- inv, err := ctx.registry.LookupInvoice(ctxb, testInvoicePaymentHash)
+ inv, err = ctx.registry.LookupInvoice(ctxb, testInvoicePaymentHash)
require.NoError(t, err)
if inv.State != invpkg.ContractSettled {
t.Fatal("expected invoice to be settled")
@@ -2141,6 +2262,8 @@ func testMppPaymentWithOverpayment(t *testing.T,
ctxb := t.Context()
f := func(overpaymentRand uint64) bool {
+ // Arrange a fresh invoice for each generated overpayment so
+ // samples cannot share payment state.
ctx := newTestContext(t, nil, makeDB)
// Add the invoice.
@@ -2159,6 +2282,8 @@ func testMppPaymentWithOverpayment(t *testing.T,
// Send htlc 1.
hodlChan1 := make(chan interface{}, 1)
+ // Act: Complete the set through the registry and provide final
+ // outcomes after the preimages are released.
resolution, err := ctx.registry.NotifyExitHopHtlc(
testInvoicePaymentHash, testInvoice.Terms.Value/2,
testHtlcExpiry, testCurrentHeight, getCircuitKey(11),
@@ -2193,17 +2318,36 @@ func testMppPaymentWithOverpayment(t *testing.T,
settleResolution.Outcome)
}
- // Check that settled amount is equal to the sum of values of
- // the htlcs 1 and 2.
+ // Both htlcs count towards the amount paid while the invoice
+ // waits for them to be final.
inv, err := ctx.registry.LookupInvoice(
ctxb, testInvoicePaymentHash,
)
require.NoError(t, err)
+ require.Equal(t, invpkg.ContractPendingSettle, inv.State)
+ require.Equal(
+ t, testInvoice.Terms.Value+overpayment, inv.AmtPaid,
+ )
+
+ // Finalize both shards to preserve the overpayment property
+ // without multiplying the separately tested failed-shard path.
+ ref := invpkg.InvoiceRefByHash(testInvoicePaymentHash)
+ ctx.finalizeHtlc(ref, getCircuitKey(11), true)
+ ctx.finalizeHtlc(ref, getCircuitKey(12), true)
+
+ // Assert the complete overpayment survives finalization of both
+ // shards, independently of their initially provisional credit.
+ inv, err = ctx.registry.LookupInvoice(
+ ctxb, testInvoicePaymentHash,
+ )
+ require.NoError(t, err)
if inv.State != invpkg.ContractSettled {
t.Fatal("expected invoice to be settled")
}
- return inv.AmtPaid == testInvoice.Terms.Value+overpayment
+ expectedAmt := testInvoice.Terms.Value + overpayment
+
+ return inv.AmtPaid == expectedAmt
}
if err := quick.Check(f, nil); err != nil {
t.Fatalf("amount incorrect: %v", err)
@@ -2429,6 +2573,9 @@ func testHeightExpiryWithRegistryImpl(t *testing.T, numParts int, settle bool,
t.Parallel()
defer timeout()()
+ // Arrange: Prepare the existing expiry watcher and selected invoice
+ // shape to compare held expiry with an already-released payment.
+
ctx := newTestContext(t, nil, makeDB)
require.Greater(t, numParts, 0, "test requires at least one part")
@@ -2454,11 +2601,13 @@ func testHeightExpiryWithRegistryImpl(t *testing.T, numParts int, settle bool,
htlcAmt := testInvoice.Terms.Value / lnwire.MilliSatoshi(numParts)
hodlChan := make(chan interface{}, numParts)
- for i := 0; i < numParts; i++ {
+ for i := range numParts {
// We bump our expiry height for each htlc so that we can test
// that the lowest expiry height is used.
expiry := testHtlcExpiry + uint32(i)
+ // Act: Submit the payment parts through the registry before
+ // advancing height or finalizing the released children.
resolution, err := ctx.registry.NotifyExitHopHtlc(
testInvoicePaymentHash, htlcAmt, expiry,
testCurrentHeight, getCircuitKey(uint64(i)), hodlChan,
@@ -2498,9 +2647,12 @@ func testHeightExpiryWithRegistryImpl(t *testing.T, numParts int, settle bool,
err = ctx.registry.SettleHodlInvoice(ctxb, testInvoicePreimage)
require.NoError(t, err)
- for i := 0; i < numParts; i++ {
+ for range numParts {
resolution, _ := (<-hodlChan).(invpkg.HtlcResolution)
require.NotNil(t, resolution)
+ // Assert an unreleased payment expires, while released
+ // preimages cannot be canceled and their outcomes
+ // establish final settlement.
settleResolution := checkSettleResolution(
t, resolution, testInvoicePreimage,
)
@@ -2515,8 +2667,9 @@ func testHeightExpiryWithRegistryImpl(t *testing.T, numParts int, settle bool,
}
// If we did not settle the invoice before its expiry, we now expect
- // a cancellation.
- expectedState := invpkg.ContractSettled
+ // a cancellation. Otherwise the invoice must not be canceled while its
+ // settlement is pending.
+ expectedState := invpkg.ContractPendingSettle
if !settle {
expectedState = invpkg.ContractCanceled
@@ -2533,6 +2686,21 @@ func testHeightExpiryWithRegistryImpl(t *testing.T, numParts int, settle bool,
require.NoError(t, err)
require.Equal(t, expectedState, inv.State, "expected "+
"hold invoice: %v, got: %v", expectedState, inv.State)
+
+ if !settle {
+ return
+ }
+
+ // Once all htlcs are final, the invoice is settled.
+ ref := invpkg.InvoiceRefByHash(testInvoicePaymentHash)
+ for i := range numParts {
+ ctx.finalizeHtlc(ref, getCircuitKey(uint64(i)), true)
+ }
+
+ inv, err = ctx.registry.LookupInvoice(ctxb, testInvoicePaymentHash)
+ require.NoError(t, err)
+ require.Equal(t, invpkg.ContractSettled, inv.State)
+ require.Equal(t, testInvoice.Terms.Value, inv.AmtPaid)
}
// testMultipleSetHeightExpiry pays a hold invoice with two mpp sets, testing
@@ -2733,6 +2901,9 @@ func testSettleInvoicePaymentAddrRequiredOptionalGrace(t *testing.T,
t.Parallel()
+ // Arrange: Prepare the payment-address feature variants and grace-
+ // period input using the existing invoice fixture.
+
ctx := newTestContext(t, nil, makeDB)
ctxb := t.Context()
@@ -2799,6 +2970,8 @@ func testSettleInvoicePaymentAddrRequiredOptionalGrace(t *testing.T,
// We'll now attempt to settle the invoice as normal, this should work
// no problem as we should allow these existing invoices to be settled.
hodlChan := make(chan interface{}, 1)
+ // Act: Submit the payment during the configured grace period before
+ // delivering its final channel result.
resolution, err := ctx.registry.NotifyExitHopHtlc(
testInvoicePaymentHash, testInvoiceAmount, testHtlcExpiry,
testCurrentHeight, getCircuitKey(10), hodlChan,
@@ -2813,12 +2986,26 @@ func testSettleInvoicePaymentAddrRequiredOptionalGrace(t *testing.T,
}
require.Equal(t, settleResolution.Outcome, invpkg.ResultSettled)
+ // We expect the pending settle state to be sent to the single invoice
+ // subscriber.
+ select {
+ case update := <-subscription.Updates:
+ require.Equal(t, invpkg.ContractPendingSettle, update.State)
+ case <-time.After(testTimeout):
+ t.Fatal("no update received")
+ }
+
+ ctx.finalizeHtlc(
+ invpkg.InvoiceRefByHash(testInvoicePaymentHash),
+ getCircuitKey(10), true,
+ )
+
// We expect the settled state to be sent to the single invoice
// subscriber.
select {
case update := <-subscription.Updates:
if update.State != invpkg.ContractSettled {
- t.Fatalf("expected state ContractOpen, but got %v",
+ t.Fatalf("expected state ContractSettled, but got %v",
update.State)
}
if update.AmtPaid != invoice.Terms.Value {
@@ -3040,7 +3227,7 @@ func testSpontaneousAmpPaymentImpl(
// Record the hodl channels of all HTLCs but the last one, which
// received its resolution directly from NotifyExitHopHtlc.
hodlChans := make(map[lntypes.Preimage]chan interface{})
- for i := 0; i < numShards; i++ {
+ for i := range numShards {
isFinalShard := i == numShards-1
hodlChan := make(chan interface{}, 1)
@@ -3086,6 +3273,7 @@ func testSpontaneousAmpPaymentImpl(
checkFailResolution(
t, resolution, invpkg.ResultInvoiceNotFound,
)
+
continue
}
### invoices/invoices_test.go
@@ -1,6 +1,7 @@
package invoices_test
import (
+ "context"
"crypto/rand"
"database/sql"
"fmt"
@@ -431,7 +432,7 @@ func testInvoiceWorkflowImpl(t *testing.T, test invWorkflowTest,
// now have the settled bit toggle to true and a non-default
// SettledDate
payAmt := fakeInvoice.Terms.Value * 2
- _, err = db.UpdateInvoice(ctxb, ref, nil, getUpdateInvoice(0, payAmt))
+ _, err = settleInvoice(db, ref, 0, payAmt)
require.NoError(t, err, "unable to settle invoice")
dbInvoice2, err := db.LookupInvoice(ctxb, ref)
require.NoError(t, err, "unable to fetch invoice")
@@ -1012,11 +1013,7 @@ func testInvoiceAddTimeSeries(t *testing.T,
paymentHash := invoice.Terms.PaymentPreimage.Hash()
ref := invpkg.InvoiceRefByHash(paymentHash)
- _, err := db.UpdateInvoice(
- ctxb, ref, nil, getUpdateInvoice(
- htlcID, invoice.Terms.Value,
- ),
- )
+ _, err := settleInvoice(db, ref, htlcID, invoice.Terms.Value)
if err != nil {
t.Fatalf("unable to settle invoice: %v", err)
}
@@ -1297,9 +1294,7 @@ func testFetchPendingInvoices(t *testing.T,
}
ref := invpkg.InvoiceRefByHash(paymentHash)
- _, err = db.UpdateInvoice(
- ctxb, ref, nil, getUpdateInvoice(htlcID, amt),
- )
+ _, err = settleInvoice(db, ref, htlcID, amt)
require.NoError(t, err)
settleTestInvoice(invoice, htlcID, settleIndex)
@@ -1375,10 +1370,7 @@ func testFetchPendingInvoicesAccepted(t *testing.T,
settledHash := settledInvoice.Terms.PaymentPreimage.Hash()
_, err = db.AddInvoice(ctxb, settledInvoice, settledHash)
require.NoError(t, err)
- _, err = db.UpdateInvoice(
- ctxb, invpkg.InvoiceRefByHash(settledHash), nil,
- getUpdateInvoice(2, amt),
- )
+ _, err = settleInvoice(db, invpkg.InvoiceRefByHash(settledHash), 2, amt)
require.NoError(t, err)
// Add a canceled invoice – it must also NOT appear in the pending
@@ -1445,9 +1437,7 @@ func testDuplicateSettleInvoice(t *testing.T,
// With the invoice in the DB, we'll now attempt to settle the invoice.
ref := invpkg.InvoiceRefByHash(payHash)
- dbInvoice, err := db.UpdateInvoice(
- ctxb, ref, nil, getUpdateInvoice(0, amt),
- )
+ dbInvoice, err := settleInvoice(db, ref, 0, amt)
require.NoError(t, err, "unable to settle invoice")
// We'll update what we expect the settle invoice to be so that our
@@ -1527,9 +1517,7 @@ func testQueryInvoices(t *testing.T,
// We'll only settle half of all invoices created.
if i%2 == 0 {
ref := invpkg.InvoiceRefByHash(paymentHash)
- _, err := db.UpdateInvoice(
- ctxb, ref, nil, getUpdateInvoice(htlcID, amt),
- )
+ _, err := settleInvoice(db, ref, htlcID, amt)
if err != nil {
t.Fatalf("unable to settle invoice: %v", err)
}
@@ -1902,7 +1890,7 @@ func getUpdateInvoice(htlcID uint64,
return func(invoice *invpkg.Invoice) (*invpkg.InvoiceUpdateDesc,
error) {
- if invoice.State == invpkg.ContractSettled {
+ if invoice.State.PreimageReleased() {
return nil, invpkg.ErrInvoiceAlreadySettled
}
@@ -1917,7 +1905,7 @@ func getUpdateInvoice(htlcID uint64,
UpdateType: invpkg.AddHTLCsUpdate,
State: &invpkg.InvoiceStateUpdateDesc{
Preimage: invoice.Terms.PaymentPreimage,
- NewState: invpkg.ContractSettled,
+ NewState: invpkg.ContractPendingSettle,
},
AddHtlcs: htlcs,
}
@@ -1926,6 +1914,46 @@ func getUpdateInvoice(htlcID uint64,
}
}
+// getFinalizeHtlcs returns an invoice update callback that records the final
+// outcome of the given htlcs, which must be pending settlement.
+func getFinalizeHtlcs(settled bool,
+ keys ...models.CircuitKey) invpkg.InvoiceUpdateCallback {
+
+ return func(invoice *invpkg.Invoice) (*invpkg.InvoiceUpdateDesc,
+ error) {
+
+ finalize := make(map[models.CircuitKey]bool, len(keys))
+ for _, key := range keys {
+ finalize[key] = settled
+ }
+
+ return &invpkg.InvoiceUpdateDesc{
+ UpdateType: invpkg.FinalizeHTLCsUpdate,
+ FinalizeHtlcs: finalize,
+ }, nil
+ }
+}
+
+// settleInvoice settles the invoice with a single htlc, and then records that
+// the htlc is irrevocably settled, as the registry does once it learns the
+// final outcome of the htlc.
+func settleInvoice(db invpkg.InvoiceDB, ref invpkg.InvoiceRef, htlcID uint64,
+ amt lnwire.MilliSatoshi) (*invpkg.Invoice, error) {
+
+ ctxb := context.Background()
+ inv, err := db.UpdateInvoice(
+ ctxb, ref, nil, getUpdateInvoice(htlcID, amt),
+ )
+ if err != nil {
+ return inv, err
+ }
+
+ return db.UpdateInvoice(
+ ctxb, ref, nil,
+ getFinalizeHtlcs(true, models.CircuitKey{HtlcID: htlcID}),
+ )
+}
+
// testCustomRecords tests that custom records are properly recorded in the
// invoice database.
func testCustomRecords(t *testing.T,
@@ -2737,11 +2765,9 @@ func testDeleteInvoices(t *testing.T,
// Settle the second invoice.
if i == 1 {
- invoice, err = db.UpdateInvoice(
- ctxb, invpkg.InvoiceRefByHash(paymentHash), nil,
- getUpdateInvoice(
- uint64(i), invoice.Terms.Value,
- ),
+ invoice, err = settleInvoice(
+ db, invpkg.InvoiceRefByHash(paymentHash),
+ uint64(i), invoice.Terms.Value,
)
require.NoError(t, err, "unable to settle invoice")
}
### invoices/sql_migration_test.go
@@ -109,6 +109,10 @@ func randHTLCRapid(t *rapid.T, invoice *Invoice, amt lnwire.MilliSatoshi) (
htlc.State = HtlcStateSettled
htlc.ResolveTime = randInvoiceTime(invoice)
+ case ContractPendingSettle:
+ htlc.State = HtlcStatePendingSettle
+ htlc.ResolveTime = randInvoiceTime(invoice)
+
case ContractCanceled:
htlc.State = HtlcStateCanceled
htlc.ResolveTime = randInvoiceTime(invoice)
@@ -696,10 +700,16 @@ func generateTestInvoiceRapid(t *rapid.T, mpp bool, amp bool) *Invoice {
created := randTime()
- const maxContractState = 3
+ const maxContractState = 4
state := ContractState(
rapid.IntRange(0, maxContractState).Draw(t, "ContractState"),
)
+
+ // AMP keeps its existing settled fixtures; only ordinary invoices
+ // produce the new pending state in this change.
+ if amp && state == ContractPendingSettle {
+ state = ContractSettled
+ }
var (
settled time.Time
settleIndex uint64
@@ -733,7 +743,7 @@ func generateTestInvoiceRapid(t *rapid.T, mpp bool, amp bool) *Invoice {
}
for _, htlc := range invoice.Htlcs {
- if htlc.State == HtlcStateSettled {
+ if htlc.State.PreimageReleased() {
invoice.AmtPaid += htlc.Amt
}
}
### invoices/update.go
@@ -127,7 +127,9 @@ func resolveReplayedHtlc(ctx *invoiceUpdateCtx, inv *Invoice) (bool,
case HtlcStateAccepted:
return true, ctx.acceptRes(resultReplayToAccepted), nil
- case HtlcStateSettled:
+ // A replayed htlc whose settle isn't final yet must be settled again,
+ // otherwise we could withhold a preimage our peer already learned.
+ case HtlcStateSettled, HtlcStatePendingSettle:
var preimage *lntypes.Preimage
switch {
// AMP invoices store a separate preimage on each HTLC.
@@ -374,8 +376,14 @@ func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
htlcPreimage = *inv.Terms.PaymentPreimage
}
+ // Ordinary invoices wait for final outcomes. AMP keeps its existing
+ // release-time set settlement until its finality work is introduced.
+ newState := ContractPendingSettle
+ if ctx.amp != nil {
+ newState = ContractSettled
+ }
update.State = &InvoiceStateUpdateDesc{
- NewState: ContractSettled,
+ NewState: newState,
Preimage: inv.Terms.PaymentPreimage,
HTLCPreimages: htlcPreimages,
SetID: setID,
@@ -561,7 +569,7 @@ func updateLegacy(ctx *invoiceUpdateCtx,
case ContractAccepted:
return &update, ctx.acceptRes(resultDuplicateToAccepted), nil
- case ContractSettled:
+ case ContractSettled, ContractPendingSettle:
// Legacy settlement uses the invoice-level payment preimage.
preimage := inv.Terms.PaymentPreimage
if preimage == nil {
@@ -592,7 +600,7 @@ func updateLegacy(ctx *invoiceUpdateCtx,
}
update.State = &InvoiceStateUpdateDesc{
- NewState: ContractSettled,
+ NewState: ContractPendingSettle,
Preimage: preimage,
}
### invoices/update_invoice.go
@@ -372,7 +372,7 @@ func addHTLCs(invoice *Invoice, hash *lntypes.Hash, updateTime time.Time,
}
accepted := htlc.State == HtlcStateAccepted
- settled := htlc.State == HtlcStateSettled
+ settled := htlc.State.PreimageReleased()
invoiceStateReady := accepted || settled
if !invoiceIsAMP {
@@ -452,13 +452,14 @@ func settleHodlInvoice(invoice *Invoice, hash *lntypes.Hash,
"not a hodl invoice", invoice.AddIndex)
}
- // TODO(positiveblue): because NewState can only be ContractSettled we
- // can remove it from the API and set it here directly.
+ // TODO(positiveblue): because NewState can only be
+ // ContractPendingSettle we can remove it from the API and set it here
+ // directly.
switch {
case update == nil:
fallthrough
- case update.NewState != ContractSettled:
+ case update.NewState != ContractPendingSettle:
return fmt.Errorf("unable to settle hodl invoice: "+
"not valid InvoiceUpdateDesc.State: %v", update)
@@ -474,34 +475,35 @@ func settleHodlInvoice(invoice *Invoice, hash *lntypes.Hash,
return err
}
- if newState == nil || *newState != ContractSettled {
+ if newState == nil || *newState != ContractPendingSettle {
return fmt.Errorf("unable to settle hodl invoice: "+
- "new computed state is not settled: %s", newState)
+ "new computed state is not pending settle: %s",
+ newState)
}
err = updater.UpdateInvoiceState(
- ContractSettled, update.Preimage,
+ ContractPendingSettle, update.Preimage,
)
if err != nil {
return err
}
- invoice.State = ContractSettled
+ invoice.State = ContractPendingSettle
invoice.Terms.PaymentPreimage = update.Preimage
// TODO(positiveblue): this logic can be further simplified.
var amtPaid lnwire.MilliSatoshi
for key, htlc := range invoice.Htlcs {
settled, _, err := getUpdatedHtlcState(
- htlc, ContractSettled, nil,
+ htlc, ContractPendingSettle, nil,
)
if err != nil {
return err
}
if settled {
err = resolveHtlc(
- key, htlc, HtlcStateSettled, updateTime,
+ key, htlc, HtlcStatePendingSettle, updateTime,
updater,
)
if err != nil {
@@ -676,6 +678,12 @@ func getUpdatedInvoiceState(invoice *Invoice, hash *lntypes.Hash,
return nil, ErrInvoiceCannotOpen
}
+ // Ordinary invoices settle only through final outcomes. AMP keeps its
+ // existing set settlement updates while its parent invoice stays open.
+ if !invoice.IsAMP() && update.NewState == ContractSettled {
+ return nil, ErrInvoiceCannotSettle
+ }
+
switch invoice.State {
// Once a contract is accepted, we can only transition to settled or
// canceled. Forbid transitioning back into this state. Otherwise this
@@ -734,14 +742,19 @@ func getUpdatedInvoiceState(invoice *Invoice, hash *lntypes.Hash,
// Fail if we still don't have a preimage when transitioning to
// settle the non-AMP invoice.
- case update.NewState == ContractSettled &&
+ case update.NewState == ContractPendingSettle &&
invoice.Terms.PaymentPreimage == nil:
return nil, errors.New("unknown preimage")
}
return &update.NewState, nil
+ // Once we released the preimage, the invoice can neither be canceled
+ // nor settled again. It only moves on through a FinalizeHTLCsUpdate.
+ case ContractPendingSettle:
+ return nil, ErrInvoiceAlreadySettled
+
// Once settled, we are in a terminal state.
case ContractSettled:
return nil, ErrInvoiceAlreadySettled
@@ -868,28 +881,30 @@ func getUpdatedHtlcState(htlc *InvoiceHTLC,
settled = true
}
- // Only persist the changes if the invoice is moving to the
- // settled state, and we're actually updating the state to
- // settled.
+ // Ordinary preimage release waits for a final outcome. AMP
+ // retains its current release-time HTLC settlement behavior.
newState := htlc.State
if settled {
newState = HtlcStateSettled
+ if htlc.AMP == nil {
+ newState = HtlcStatePendingSettle
+ }
}
return persist && settled, newState, nil
}
- if invoiceState == ContractSettled {
+ if invoiceState.PreimageReleased() {
// Check that we can settle the HTLCs. For legacy and MPP HTLCs
// this will be a NOP, but for AMP HTLCs this asserts that we
// have a valid hash/preimage pair. Passing true permits the
- // method to update the HTLC to HtlcStateSettled.
+ // method to persist the ordinary pending or AMP settled state.
return trySettle(true)
}
- // We should never find a settled HTLC on an invoice that isn't in
- // ContractSettled.
- if htlc.State == HtlcStateSettled {
+ // We should never find an HTLC we released the preimage for on an
+ // invoice that we didn't settle.
+ if htlc.State.PreimageReleased() {
return false, htlc.State, ErrHTLCAlreadySettled
}
### invoices/update_invoice_test.go
@@ -24,6 +24,8 @@ type updateHTLCTest struct {
func TestUpdateHTLC(t *testing.T) {
t.Parallel()
+ // Arrange accepted, released and final children with fixed timestamps
+ // so the cases distinguish preimage release from a final resolution.
testNow := time.Now()
setID := [32]byte{0x01}
ampRecord := record.NewAMP([32]byte{0x02}, setID, 3)
@@ -130,7 +132,7 @@ func TestUpdateHTLC(t *testing.T) {
AcceptTime: testNow,
ResolveTime: testNow,
Expiry: 40,
- State: HtlcStateSettled,
+ State: HtlcStatePendingSettle,
CustomRecords: make(record.CustomSet),
WireCustomRecords: make(lnwire.CustomRecords),
AMP: nil,
@@ -743,15 +745,23 @@ func TestUpdateHTLC(t *testing.T) {
},
}
+ // Act on each independent child; the helper applies the returned
+ // transition and asserts the complete child and any expected error.
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
testUpdateHTLC(t, test, testNow)
})
}
}
+// testUpdateHTLC applies one transition to a copy, preserving the table's
+// original child while checking both its resulting state and timestamp.
func testUpdateHTLC(t *testing.T, test updateHTLCTest, now time.Time) {
+ // Arrange an isolated child so another case cannot inherit mutations.
htlc := test.input.Copy()
+
+ // Act through the shared state selector, applying only changes it
+ // requests, as the invoice updater does when storing a resolution.
stateChanged, state, err := getUpdatedHtlcState(
htlc, test.invState, test.setID,
)
@@ -760,6 +770,8 @@ func testUpdateHTLC(t *testing.T, test updateHTLCTest, now time.Time) {
htlc.ResolveTime = now
}
+ // Assert the full returned state and error, including preservation of
+ // a released child's timestamp when no transition is permitted.
require.Equal(t, test.expErr, err)
require.Equal(t, test.output, *htlc)
}
@@ -864,6 +876,8 @@ func TestResolveReplayedHtlcSettled(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
+ // Arrange an existing final child and its recorded
+ // preimage, checking the stored replay evidence.
circuitKey := CircuitKey{HtlcID: 1}
ctx := &invoiceUpdateCtx{
hash: test.paymentHash,
@@ -882,9 +896,15 @@ func TestResolveReplayedHtlcSettled(t *testing.T) {
},
}
+ // Act through replay resolution before new-shard
+ // checks.
replayed, resolution, err := resolveReplayedHtlc(
ctx, invoice,
)
+
+ // Assert replay is recognized and returns the
+ // appropriate preimage or validation error without
+ // creating a new HTLC.
require.True(t, replayed)
switch {
@@ -1113,12 +1133,17 @@ func TestUpdateLegacyRejectsNilPreimageSettle(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
+ // Arrange the open/paid paths without a preimage
+ // so neither can produce a fulfill for a new circuit.
ctx, invoice := newLegacyUpdateTestContext(
t, test.state,
)
invoice.Terms.PaymentPreimage = nil
+ // Act through legacy admission rather than replay.
update, resolution, err := updateLegacy(ctx, invoice)
+ // Assert normal rejection without an update or an
+ // internal error that would fail the link.
require.NoError(t, err)
require.Nil(t, update)
requireFailResolution(
### itest/lnd_mpp_test.go
@@ -89,7 +89,9 @@ func testSendMultiPathPayment(ht *lntest.HarnessTest) {
require.GreaterOrEqual(ht, succeeded, minExpectedShards,
"expected shards not reached")
- // Make sure Bob show the invoice as settled for the full amount.
+ // The payer can finish before Bob locks in the settle. Wait through
+ // the existing address-based assertion before checking final credit.
+ ht.AssertInvoiceSettled(mts.bob, invoices[0].PaymentAddr)
inv := mts.bob.RPC.LookupInvoice(rHash)
require.EqualValues(ht, paymentAmt, inv.AmtPaidSat,
### itest/lnd_route_blinding_test.go
@@ -1078,6 +1078,7 @@ func testMPPToSingleBlindedPath(ht *lntest.HarnessTest) {
"expected shards not reached")
// Make sure Dave show the invoice as settled for the full amount.
+ ht.AssertInvoiceSettled(dave, invoiceResp.PaymentAddr)
inv := dave.RPC.LookupInvoice(invoiceResp.RHash)
require.EqualValues(ht, paymentAmt, inv.AmtPaidSat,
@@ -1212,8 +1213,7 @@ func testBlindedRouteDummyHops(ht *lntest.HarnessTest) {
)
// Make sure Dave show the invoice as settled.
- inv := dave.RPC.LookupInvoice(invoiceResp.RHash)
- require.Equal(ht, lnrpc.Invoice_SETTLED, inv.State)
+ ht.AssertInvoiceSettled(dave, invoiceResp.PaymentAddr)
// Let's also test the case where Dave is not the introduction node.
// We restart Carol so that she supports route blinding.
@@ -1254,8 +1254,7 @@ func testBlindedRouteDummyHops(ht *lntest.HarnessTest) {
)
// Make sure Dave show the invoice as settled.
- inv = dave.RPC.LookupInvoice(invoiceResp.RHash)
- require.Equal(ht, lnrpc.Invoice_SETTLED, inv.State)
+ ht.AssertInvoiceSettled(dave, invoiceResp.PaymentAddr)
}
// testMPPToMultipleBlindedPaths tests that a two-shard MPP payment can be sent
@@ -1394,6 +1393,7 @@ func testMPPToMultipleBlindedPaths(ht *lntest.HarnessTest) {
"expected shards not reached")
// Make sure Dave show the invoice as settled for the full amount.
+ ht.AssertInvoiceSettled(dave, invoiceResp.PaymentAddr)
inv := dave.RPC.LookupInvoice(invoiceResp.RHash)
require.EqualValues(ht, paymentAmt, inv.AmtPaidSat,
### itest/lnd_routing_test.go
@@ -792,8 +792,7 @@ func testScidAliasRoutingHints(ht *lntest.HarnessTest) {
// Check that Dave's invoice appears as settled.
invoices := dave.RPC.ListInvoices(&lnrpc.ListInvoiceRequest{})
require.Len(ht, invoices.Invoices, 1, "expected one invoice")
- require.Equal(ht, invoices.Invoices[0].State, lnrpc.Invoice_SETTLED,
- "expected settled invoice")
+ ht.AssertInvoiceSettled(dave, invoices.Invoices[0].PaymentAddr)
// We'll now delete the alias again, but only on Carol's end. That
// should be enough to make the payment fail, since she doesn't know
### itest/lnd_single_hop_invoice_test.go
@@ -48,9 +48,7 @@ func testSingleHopInvoice(ht *lntest.HarnessTest) {
ht.CompletePaymentRequests(alice, []string{invoiceResp.PaymentRequest})
// Bob's invoice should now be found and marked as settled.
- dbInvoice := bob.RPC.LookupInvoice(invoiceResp.RHash)
- require.Equal(ht, lnrpc.Invoice_SETTLED, dbInvoice.State,
- "bob's invoice should be marked as settled")
+ ht.AssertInvoiceSettled(bob, invoiceResp.PaymentAddr)
// With the payment completed all balance related stats should be
// properly updated.
### itest/lnd_sweep_test.go
@@ -1909,9 +1909,10 @@ func testFeeReplacement(ht *lntest.HarnessTest) {
// Suspend Bob so he won't get the preimage from Carol.
restartBob := ht.SuspendNode(bob)
- // Carol settles the first invoice.
+ // Carol settles the first invoice. Since Bob is offline, the settle
+ // can't be locked in, so the invoice is pending settlement.
carol.RPC.SettleInvoice(preimages[0])
- ht.AssertInvoiceState(streams[0], lnrpc.Invoice_SETTLED)
+ ht.AssertInvoiceState(streams[0], lnrpc.Invoice_PENDING_SETTLE)
// Carol goes offline so the preimage won't be sent to Bob.
restartCarol := ht.SuspendNode(carol)
### lnrpc/invoicesrpc/addinvoice_test.go
@@ -4,13 +4,15 @@ import (
"encoding/hex"
"fmt"
"testing"
+ "time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/chainhash/v2"
"github.com/btcsuite/btcd/wire/v2"
"github.com/lightningnetwork/lnd/chanstate"
"github.com/lightningnetwork/lnd/graph/db/models"
"github.com/lightningnetwork/lnd/invoices"
+ "github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/zpay32"
@@ -28,6 +30,108 @@ var (
pubkey = btcec.NewPublicKey(new(btcec.FieldVal).SetInt(4), pubKeyY)
)
+// TestCreateRPCInvoiceFinalHtlcOutcomes verifies that RPC callers see pending
+// releases without final timestamps and completed outcomes with their credit.
+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.
+ const amount = lnwire.MilliSatoshi(1000)
+ resolvedAt := time.Unix(10, 0)
+ testCases := []struct {
+ name string
+ state invoices.ContractState
+ htlcStates [2]invoices.HtlcState
+ rpcState lnrpc.Invoice_InvoiceState
+ rpcHtlcState [2]lnrpc.InvoiceHTLCState
+ amtPaid lnwire.MilliSatoshi
+ resolveTime int64
+ }{
+ {
+ name: "pending outcomes",
+ state: invoices.ContractPendingSettle,
+ htlcStates: [2]invoices.HtlcState{
+ invoices.HtlcStatePendingSettle,
+ invoices.HtlcStatePendingSettle,
+ },
+ rpcState: lnrpc.Invoice_PENDING_SETTLE,
+ rpcHtlcState: [2]lnrpc.InvoiceHTLCState{
+ lnrpc.InvoiceHTLCState_PENDING_SETTLE,
+ lnrpc.InvoiceHTLCState_PENDING_SETTLE,
+ },
+ amtPaid: amount,
+ resolveTime: 0,
+ },
+ {
+ name: "final outcomes",
+ state: invoices.ContractSettled,
+ htlcStates: [2]invoices.HtlcState{
+ invoices.HtlcStateSettled,
+ invoices.HtlcStateCanceled,
+ },
+ rpcState: lnrpc.Invoice_SETTLED,
+ rpcHtlcState: [2]lnrpc.InvoiceHTLCState{
+ lnrpc.InvoiceHTLCState_SETTLED,
+ lnrpc.InvoiceHTLCState_CANCELED,
+ },
+ amtPaid: amount / 2,
+ resolveTime: resolvedAt.Unix(),
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ // Arrange invoice fields without request parsing.
+ // Circuit IDs distinguish children in the ordered
+ // RPC response without involving a backend.
+ invoice := &invoices.Invoice{
+ State: tc.state,
+ AmtPaid: tc.amtPaid,
+ Terms: invoices.ContractTerm{
+ Value: amount,
+ },
+ }
+ invoice.Htlcs = make(
+ map[models.CircuitKey]*invoices.InvoiceHTLC,
+ )
+ for n, state := range tc.htlcStates {
+ key := models.CircuitKey{
+ HtlcID: uint64(n),
+ }
+ invoice.Htlcs[key] = &invoices.InvoiceHTLC{
+ State: state,
+ Amt: amount / 2,
+ ResolveTime: resolvedAt,
+ }
+ }
+
+ // Act through the mapper used by invoice responses
+ // 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.
+ require.NoError(t, err)
+ require.Equal(t, tc.rpcState, rpcInvoice.State)
+ require.EqualValues(
+ t, tc.amtPaid, rpcInvoice.AmtPaidMsat,
+ )
+ require.Len(t, rpcInvoice.Htlcs, 2)
+ for n, htlc := range rpcInvoice.Htlcs {
+ require.Equal(t, tc.rpcHtlcState[n], htlc.State)
+ require.Equal(
+ t, tc.resolveTime, htlc.ResolveTime,
+ )
+ }
+ })
+ }
+}
+
// TestAddInvoiceRejectsCltvAboveMaxIncoming asserts that invoice creation
// rejects final CLTV deltas above the supported maximum.
func TestAddInvoiceRejectsCltvAboveMaxIncoming(t *testing.T) {
### lnrpc/invoicesrpc/utils.go
@@ -95,6 +95,9 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
case invoices.ContractAccepted:
state = lnrpc.Invoice_ACCEPTED
+ case invoices.ContractPendingSettle:
+ state = lnrpc.Invoice_PENDING_SETTLE
+
default:
return nil, fmt.Errorf("unknown invoice state %v",
invoice.State)
@@ -110,6 +113,8 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
state = lnrpc.InvoiceHTLCState_SETTLED
case invoices.HtlcStateCanceled:
state = lnrpc.InvoiceHTLCState_CANCELED
+ case invoices.HtlcStatePendingSettle:
+ state = lnrpc.InvoiceHTLCState_PENDING_SETTLE
default:
return nil, fmt.Errorf("unknown state %v", htlc.State)
}
@@ -155,8 +160,12 @@ func CreateRPCInvoice(invoice *invoices.Invoice,
}
}
- // Only report resolved times if htlc is resolved.
- if htlc.State != invoices.HtlcStateAccepted {
+ // Preimage release records a timestamp internally, but a
+ // pending HTLC has no final resolution time to expose to RPC
+ // callers.
+ if htlc.State == invoices.HtlcStateSettled ||
+ htlc.State == invoices.HtlcStateCanceled {
+
rpcHtlc.ResolveTime = htlc.ResolveTime.Unix()
}
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.