From a6f4f0dfc9c4249c6b34f0e8096e665754d75b2a Mon Sep 17 00:00:00 2001 From: yyforyongyu Date: Thu, 24 Nov 2022 17:52:04 +0800 Subject: [PATCH] channeldb: add method `removable` to decide removing payments This commit adds a new method, `removable`, to help decide whether deleting a payment is allowed. --- channeldb/payment_status.go | 28 ++++++++++++++++++++++++++++ channeldb/payments.go | 17 +++++++++-------- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/channeldb/payment_status.go b/channeldb/payment_status.go index 2d19546a2..17ffd3e88 100644 --- a/channeldb/payment_status.go +++ b/channeldb/payment_status.go @@ -75,3 +75,31 @@ func (ps PaymentStatus) initializable() error { return fmt.Errorf("%w: %v", ErrUnknownPaymentStatus, ps) } } + +// removable returns an error to specify whether deleting the payment with its +// current status is allowed. A payment cannot be safely deleted if it has +// inflight HTLCs. +func (ps PaymentStatus) removable() error { + switch ps { + // The payment has been created but has no HTLCs and can be removed. + case StatusInitiated: + return nil + + // There are still inflight HTLCs and the payment needs to wait for the + // final outcomes. + case StatusInFlight: + return ErrPaymentInFlight + + // The payment has been attempted and is succeeded and is allowed to be + // removed. + case StatusSucceeded: + return nil + + // Failed payments are allowed to be removed. + case StatusFailed: + return nil + + default: + return fmt.Errorf("%w: %v", ErrUnknownPaymentStatus, ps) + } +} diff --git a/channeldb/payments.go b/channeldb/payments.go index 93abe4fb1..168a355cf 100644 --- a/channeldb/payments.go +++ b/channeldb/payments.go @@ -783,12 +783,12 @@ func (d *DB) DeletePayment(paymentHash lntypes.Hash, return err } - // If the status is InFlight, we cannot safely delete + // If the payment has inflight HTLCs, we cannot safely delete // the payment information, so we return an error. - if paymentStatus == StatusInFlight { - return fmt.Errorf("payment '%v' has status InFlight "+ - "and therefore cannot be deleted", - paymentHash.String()) + if err := paymentStatus.removable(); err != nil { + return fmt.Errorf("payment '%v' has inflight HTLCs"+ + "and therefore cannot be deleted: %w", + paymentHash.String(), err) } // Delete the failed HTLC attempts we found. @@ -888,9 +888,10 @@ func (d *DB) DeletePayments(failedOnly, failedHtlcsOnly bool) error { return err } - // If the status is InFlight, we cannot safely delete - // the payment information, so we return early. - if paymentStatus == StatusInFlight { + // If the payment has inflight HTLCs, we cannot safely + // delete the payment information, so we return an nil + // to skip it. + if err := paymentStatus.removable(); err != nil { return nil }