multi: implement Fail method for sql backend
What changed, and why it matters
This commit adds a missing database method called Fail for the new SQL backend in LND. It lets the code record why a Lightning payment ultimately failed. The change is mostly filling in a previously unimplemented interface method. The commit's own comments note that the implementation does not fully enforce the intended safety rule that all payment attempts must already be failed before this is called, and allows concurrent calls without extra synchronization. That is a design caveat rather than a clear exploitable bug, but it means the SQL backend behaves slightly differently from the older KV backend in edge cases involving concurrent or out-of-order payment updates.
Treat as a normal code-review item, not an emergency. Reviewers should verify that the relaxed precondition is acceptable for the SQL backend and that payment state calculation elsewhere correctly handles cases where Fail is called while HTLC attempts are still in flight. Consider adding tests covering concurrent Fail/Settle/FailAttempt calls and out-of-order lifecycle transitions to ensure no payment can be left in an inconsistent or exploitable state.
Security signals we found
New SQL query updates a single column without row-level locking beyond the transaction
Implementation deliberately does not enforce documented interface precondition
Concurrent calls allowed; last writer wins on fail_reason
RowsAffected check prevents silent no-op on unknown payment hash
Part of a backend migration (KV to SQL) where behavioral parity is a common source of subtle bugs
Evidence from the diff
The patch implements PaymentControl.Fail for the SQL payment store. It adds a FailPayment SQL query that updates payments.fail_reason by payment_identifier, wires it through the generated sqlc querier and interface, and implements SQLStore.Fail to run the update inside ExecTx, check RowsAffected to return ErrPaymentNotInitiated if no row matched, then fetch and reconstruct the MPPPayment. The doc comment explicitly states the implementation does not validate the interface precondition that all active attempts are already failed, and allows concurrent calls without synchronization. This is a functional completeness change for the SQL backend migration; it does not by itself introduce an obvious vulnerability, but it relaxes ordering/synchronization guarantees relative to the interface contract.
Changed components
payments/db/sql_store.gosqldb/sqlc/payments.sql.gosqldb/sqlc/querier.gosqldb/sqlc/queries/payments.sqlInspect captured patch +83 / −0
diff --git a/payments/db/sql_store.go b/payments/db/sql_store.go
index 7f2e1c8..469f0be 100644
--- a/payments/db/sql_store.go
+++ b/payments/db/sql_store.go
@@ -77,6 +77,8 @@ type SQLQueries interface {
SettleAttempt(ctx context.Context, arg sqlc.SettleAttemptParams) error
+ FailPayment(ctx context.Context, arg sqlc.FailPaymentParams) (sql.Result, error)
+
DeletePayment(ctx context.Context, paymentID int64) error
// DeleteFailedAttempts removes all failed HTLCs from the db for a
@@ -1360,3 +1362,67 @@ func (s *SQLStore) SettleAttempt(paymentHash lntypes.Hash,
return mpPayment, nil
}
+
+// Fail records the ultimate reason why a payment failed. This method stores
+// the failure reason for record keeping but does not enforce that all HTLC
+// attempts are resolved - HTLCs may still be in flight when this is called.
+//
+// The payment's actual status transition to StatusFailed is determined by the
+// payment state calculation, which considers both the recorded failure reason
+// and the current state of all HTLC attempts. The status will transition to
+// StatusFailed once all HTLCs are resolved and/or a failure reason is recorded.
+//
+// NOTE: According to the interface contract, this should only be called when
+// all active attempts are already failed. However, the implementation allows
+// concurrent calls and does not validate this precondition, enabling the last
+// failing attempt to record the failure reason without synchronization.
+//
+// This method is part of the PaymentControl interface, which is embedded in
+// the PaymentWriter interface and ultimately the DB interface. It represents
+// step 4 in the payment lifecycle control flow.
+func (s *SQLStore) Fail(paymentHash lntypes.Hash,
+ reason FailureReason) (*MPPayment, error) {
+
+ ctx := context.TODO()
+
+ var mpPayment *MPPayment
+
+ err := s.db.ExecTx(ctx, sqldb.WriteTxOpt(), func(db SQLQueries) error {
+ result, err := db.FailPayment(ctx, sqlc.FailPaymentParams{
+ PaymentIdentifier: paymentHash[:],
+ FailReason: sqldb.SQLInt32(reason),
+ })
+ if err != nil {
+ return err
+ }
+
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rowsAffected == 0 {
+ return ErrPaymentNotInitiated
+ }
+
+ payment, err := db.FetchPayment(ctx, paymentHash[:])
+ if err != nil {
+ return fmt.Errorf("failed to fetch payment: %w", err)
+ }
+ mpPayment, err = fetchPaymentWithCompleteData(
+ ctx, s.cfg.QueryCfg, db, payment,
+ )
+ if err != nil {
+ return fmt.Errorf("failed to fetch payment with "+
+ "complete data: %w", err)
+ }
+
+ return nil
+ }, func() {
+ mpPayment = nil
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to fail payment: %w", err)
+ }
+
+ return mpPayment, nil
+}
diff --git a/sqldb/sqlc/payments.sql.go b/sqldb/sqlc/payments.sql.go
index fb117bc..fd15059 100644
--- a/sqldb/sqlc/payments.sql.go
+++ b/sqldb/sqlc/payments.sql.go
@@ -85,6 +85,19 @@ func (q *Queries) FailAttempt(ctx context.Context, arg FailAttemptParams) error
return err
}
+const failPayment = `-- name: FailPayment :execresult
+UPDATE payments SET fail_reason = $1 WHERE payment_identifier = $2
+`
+
+type FailPaymentParams struct {
+ FailReason sql.NullInt32
+ PaymentIdentifier []byte
+}
+
+func (q *Queries) FailPayment(ctx context.Context, arg FailPaymentParams) (sql.Result, error) {
+ return q.db.ExecContext(ctx, failPayment, arg.FailReason, arg.PaymentIdentifier)
+}
+
const fetchAllInflightAttempts = `-- name: FetchAllInflightAttempts :many
SELECT
ha.id,
diff --git a/sqldb/sqlc/querier.go b/sqldb/sqlc/querier.go
index cc52f06..da022c1 100644
--- a/sqldb/sqlc/querier.go
+++ b/sqldb/sqlc/querier.go
@@ -35,6 +35,7 @@ type Querier interface {
DeleteUnconnectedNodes(ctx context.Context) ([][]byte, error)
DeleteZombieChannel(ctx context.Context, arg DeleteZombieChannelParams) (sql.Result, error)
FailAttempt(ctx context.Context, arg FailAttemptParams) error
+ FailPayment(ctx context.Context, arg FailPaymentParams) (sql.Result, error)
FetchAMPSubInvoiceHTLCs(ctx context.Context, arg FetchAMPSubInvoiceHTLCsParams) ([]FetchAMPSubInvoiceHTLCsRow, error)
FetchAMPSubInvoices(ctx context.Context, arg FetchAMPSubInvoicesParams) ([]AmpSubInvoice, error)
// Fetch all inflight attempts across all payments
diff --git a/sqldb/sqlc/queries/payments.sql b/sqldb/sqlc/queries/payments.sql
index b0183cc..1cc8e23 100644
--- a/sqldb/sqlc/queries/payments.sql
+++ b/sqldb/sqlc/queries/payments.sql
@@ -352,3 +352,6 @@ VALUES (
@htlc_fail_reason,
@failure_msg
);
+
+-- name: FailPayment :execresult
+UPDATE payments SET fail_reason = $1 WHERE payment_identifier = $2;
Why this scored 26/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.