What changed, and why it matters
This commit changes how the Lightning Network Daemon (LND) records the final result of ordinary payment attempts (HTLCs) for invoices. It adds a way to find invoices whose child payments are still awaiting a final outcome, and applies those outcomes inside the existing invoice update process. The change is a correctness/robustness improvement rather than an obvious security fix, but it touches settlement accounting and state transitions, which are security-sensitive in a payment system.
Treat as a normal code-review item. Verify that finalizeHTLCs cannot be invoked in a way that bypasses existing preimage or cancellation invariants, that the new FetchPendingSettleInvoices query does not expose stale or inconsistent state to callers, and that the amount-paid recomputation cannot be manipulated to over- or under-report invoice value. No immediate security response is indicated by the commit alone.
Security signals we found
Touches invoice settlement state machine and HTLC finalization
Changes amount-paid recomputation after HTLC resolution
Adds duplicate/already-settled HTLC rejection (ErrHTLCAlreadySettled)
Adds new database query paths for pending-settle invoices
No explicit security claim, CVE, or researcher attribution in commit
Evidence from the diff
The patch introduces a new invoice update type, FinalizeHTLCsUpdate, and a new query, FetchPendingSettleInvoices, for both the KV and SQL invoice stores. It allows LND to discover invoices containing HTLCs in HtlcStatePendingSettle and then resolve them to HtlcStateSettled or HtlcStateCanceled within the invoice transaction. It recomputes the amount paid, removes failed value, and transitions the parent invoice from ContractPendingSettle to ContractSettled or ContractCanceled once no pending HTLCs remain. It also ensures the first settlement index is assigned only once. The commit does not describe a vulnerability or credit a reporter, and no advisory or CVE is referenced.
Changed components
channeldb/invoices.goinvoices/interface.goinvoices/mock.goinvoices/sql_store.goinvoices/update_invoice.goInspect captured patch +193 / −4
### channeldb/invoices.go
@@ -476,6 +476,33 @@ func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket,
func (d *DB) FetchPendingInvoices(_ context.Context) (
map[lntypes.Hash]invpkg.Invoice, error) {
+ return d.fetchInvoices(func(invoice *invpkg.Invoice) bool {
+ return invoice.IsPending()
+ })
+}
+
+// FetchPendingSettleInvoices returns all invoices that contain at least one
+// htlc whose final outcome is still pending. The KV backend has no index over
+// htlc states, so it discovers them by scanning the invoice bucket.
+func (d *DB) FetchPendingSettleInvoices(_ context.Context) (
+ map[lntypes.Hash]invpkg.Invoice, error) {
+
+ return d.fetchInvoices(func(invoice *invpkg.Invoice) bool {
+ for _, htlc := range invoice.Htlcs {
+ if htlc.State == invpkg.HtlcStatePendingSettle {
+ return true
+ }
+ }
+
+ return false
+ })
+}
+
+// fetchInvoices returns all invoices matching the given predicate. The result
+// is keyed by payment hash.
+func (d *DB) fetchInvoices(predicate func(*invpkg.Invoice) bool) (
+ map[lntypes.Hash]invpkg.Invoice, error) {
+
result := make(map[lntypes.Hash]invpkg.Invoice)
err := kvdb.View(d, func(tx kvdb.RTx) error {
@@ -510,7 +537,7 @@ func (d *DB) FetchPendingInvoices(_ context.Context) (
return err
}
- if invoice.IsPending() {
+ if predicate(&invoice) {
var paymentHash lntypes.Hash
copy(paymentHash[:], k)
result[paymentHash] = invoice
@@ -878,6 +905,9 @@ func (k *kvInvoiceUpdater) Finalize(updateType invpkg.UpdateType) error {
// invoice. All HTLCs which were accepted are now canceled, so
// we persist this state.
return k.storeCancelHtlcsUpdate()
+
+ case invpkg.FinalizeHTLCsUpdate:
+ return k.storeFinalizeHtlcsUpdate()
}
return fmt.Errorf("unknown update type: %v", updateType)
@@ -970,6 +1000,22 @@ func (k *kvInvoiceUpdater) storeSettleHodlInvoiceUpdate() error {
return k.serializeAndStoreInvoice()
}
+// storeFinalizeHtlcsUpdate persists final ordinary outcomes and assigns the
+// first settlement index only once. Later duplicate HTLCs retain the parent
+// index, and AMP keeps allocating its set metadata in storeAddHtlcsUpdate.
+func (k *kvInvoiceUpdater) storeFinalizeHtlcsUpdate() error {
+ if k.invoice.State == invpkg.ContractSettled &&
+ k.invoice.SettleIndex == 0 {
+
+ err := k.setSettleMetaFields(nil)
+ if err != nil {
+ return err
+ }
+ }
+
+ return k.serializeAndStoreInvoice()
+}
+
// setSettleMetaFields updates the metadata associated with settlement of an
// invoice. If a non-nil setID is passed in, then the value will be append to
// the invoice number as well, in order to allow us to detect repeated payments
### invoices/interface.go
@@ -48,6 +48,11 @@ type InvoiceDB interface {
FetchPendingInvoices(ctx context.Context) (map[lntypes.Hash]Invoice,
error)
+ // FetchPendingSettleInvoices returns all invoices that contain at least
+ // one htlc whose final outcome is still pending.
+ FetchPendingSettleInvoices(ctx context.Context) (
+ map[lntypes.Hash]Invoice, error)
+
// QueryInvoices allows a caller to query the invoice database for
// invoices within the specified add index range.
QueryInvoices(ctx context.Context, q InvoiceQuery) (InvoiceSlice, error)
### invoices/mock.go
@@ -56,6 +56,15 @@ func (m *MockInvoiceDB) FetchPendingInvoices(ctx context.Context) (
return args.Get(0).(map[lntypes.Hash]Invoice), args.Error(1)
}
+// FetchPendingSettleInvoices returns the configured recovery candidates so
+// startup tests can distinguish child-state discovery from pending parents.
+func (m *MockInvoiceDB) FetchPendingSettleInvoices(ctx context.Context) (
+ map[lntypes.Hash]Invoice, error) {
+
+ args := m.Called(ctx)
+ return args.Get(0).(map[lntypes.Hash]Invoice), args.Error(1)
+}
+
func (m *MockInvoiceDB) QueryInvoices(q InvoiceQuery) (InvoiceSlice, error) {
args := m.Called(q)
invoiceSlice, _ := args.Get(0).(InvoiceSlice)
### invoices/sql_store.go
@@ -73,6 +73,12 @@ type SQLInvoiceQueries interface { //nolint:interfacebloat
FetchPendingInvoices(ctx context.Context,
arg sqlc.FetchPendingInvoicesParams) ([]sqlc.Invoice, error)
+ // FetchPendingSettleInvoices returns invoices containing at least one
+ // pending-settle HTLC, ordered by id ascending.
+ FetchPendingSettleInvoices(ctx context.Context,
+ arg sqlc.FetchPendingSettleInvoicesParams) ([]sqlc.Invoice,
+ error)
+
// FilterInvoicesBySettleIndex returns settled invoices whose
// settle_index is >= the given bound, ordered by id ascending. The
// caller must always supply a concrete lower bound so the planner can
@@ -761,9 +767,8 @@ func (i *SQLStore) LookupInvoice(ctx context.Context,
return *invoice, nil
}
-// FetchPendingInvoices returns all the invoices that are currently in a
-// "pending" state. An invoice is pending if it has been created but not yet
-// settled or canceled.
+// FetchPendingInvoices returns all invoices that are currently in a pending
+// state.
func (i *SQLStore) FetchPendingInvoices(ctx context.Context) (
map[lntypes.Hash]Invoice, error) {
@@ -813,6 +818,56 @@ func (i *SQLStore) FetchPendingInvoices(ctx context.Context) (
return invoices, nil
}
+// FetchPendingSettleInvoices returns all invoices containing at least one htlc
+// whose final outcome is still pending.
+func (i *SQLStore) FetchPendingSettleInvoices(ctx context.Context) (
+ map[lntypes.Hash]Invoice, error) {
+
+ var invoices map[lntypes.Hash]Invoice
+
+ readTxOpt := sqldb.ReadTxOpt()
+ err := i.db.ExecTx(ctx, readTxOpt, func(db SQLInvoiceQueries) error {
+ var cursor int64
+ limit := int32(i.opts.paginationLimit)
+ for {
+ params := sqlc.FetchPendingSettleInvoicesParams{
+ IDCursor: cursor,
+ NumLimit: limit,
+ }
+
+ rows, err := db.FetchPendingSettleInvoices(ctx, params)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return fmt.Errorf("unable to get pending-"+
+ "settle invoices from db: %w", err)
+ }
+
+ for _, row := range rows {
+ hash, invoice, err := fetchInvoiceData(
+ ctx, db, row, nil, true,
+ )
+ if err != nil {
+ return err
+ }
+
+ invoices[*hash] = *invoice
+ cursor = row.ID
+ }
+
+ if int32(len(rows)) < limit {
+ return nil
+ }
+ }
+ }, func() {
+ invoices = make(map[lntypes.Hash]Invoice)
+ })
+ if err != nil {
+ return nil, fmt.Errorf("unable to fetch pending-settle "+
+ "invoices: %w", err)
+ }
+
+ return invoices, nil
+}
+
// InvoicesSettledSince can be used by callers to catch up any settled invoices
// they missed within the settled invoice time series. We'll return all known
// settled invoice that have a settle index higher than the passed idx.
### invoices/update_invoice.go
@@ -144,6 +144,12 @@ func UpdateInvoice(hash *lntypes.Hash, invoice *Invoice,
return nil, err
}
+ case FinalizeHTLCsUpdate:
+ err := finalizeHTLCs(invoice, updateTime, update, updater)
+ if err != nil {
+ return nil, err
+ }
+
default:
return nil, fmt.Errorf("unknown update type: %s",
update.UpdateType)
@@ -589,6 +595,74 @@ func cancelInvoice(invoice *Invoice, hash *lntypes.Hash,
return nil
}
+// finalizeHTLCs applies final ordinary HTLC outcomes within the invoice
+// transaction. Failed value is removed from the paid amount; the parent
+// completes after its pending HTLCs do, while an already-settled parent keeps
+// its terminal state when a later duplicate finishes.
+func finalizeHTLCs(invoice *Invoice, updateTime time.Time,
+ update *InvoiceUpdateDesc, updater InvoiceUpdater) error {
+
+ if len(update.FinalizeHtlcs) == 0 {
+ return errors.New("no htlcs to finalize")
+ }
+
+ for key, settled := range update.FinalizeHtlcs {
+ htlc, ok := invoice.Htlcs[key]
+ if !ok {
+ return fmt.Errorf("finalize of non-existent htlc %v",
+ key)
+ }
+
+ // Identify a repeated success so callers can distinguish this
+ // state rejection from an unrelated storage failure.
+ if htlc.State == HtlcStateSettled {
+ return fmt.Errorf("htlc %v: %w", key,
+ ErrHTLCAlreadySettled)
+ }
+
+ if htlc.State != HtlcStatePendingSettle {
+ return fmt.Errorf("htlc %v finalized in state %v", key,
+ htlc.State)
+ }
+
+ newState := HtlcStateSettled
+ if !settled {
+ newState = HtlcStateCanceled
+ }
+
+ err := resolveHtlc(key, htlc, newState, updateTime, updater)
+ if err != nil {
+ return err
+ }
+ }
+
+ // The amount paid only counts htlcs that settled or may still settle.
+ var amtPaid lnwire.MilliSatoshi
+ var pending bool
+ for _, htlc := range invoice.Htlcs {
+ if htlc.State.PreimageReleased() {
+ amtPaid += htlc.Amt
+ }
+
+ pending = pending || htlc.State == HtlcStatePendingSettle
+ }
+
+ if invoice.State == ContractPendingSettle && !pending {
+ newState := ContractSettled
+ if amtPaid == 0 {
+ newState = ContractCanceled
+ }
+
+ err := updater.UpdateInvoiceState(newState, nil)
+ if err != nil {
+ return err
+ }
+ invoice.State = newState
+ }
+
+ return updateInvoiceAmtPaid(invoice, amtPaid, updater)
+}
+
// getUpdatedInvoiceState validates and processes an invoice state update. The
// new state to transition to is returned, so the caller is able to select
// exactly how the invoice state is updated. Note that for AMP invoices thisWhy this scored 39/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.