deleting expired invoices based on their actual expiry date.

also fixes a possible bug that could have caused pending outgoing
payments to be deleted and affecting the balance. probably never happened.
This commit is contained in:
fiatjaf 2020-09-02 00:58:21 -03:00
parent d2650d6e2c
commit 4447a48724
3 changed files with 28 additions and 13 deletions

View file

@ -1,7 +1,9 @@
from typing import List, Optional, Dict
import datetime
from uuid import uuid4
from typing import List, Optional, Dict
from lnbits.db import open_db
from lnbits import bolt11
from lnbits.settings import DEFAULT_WALLET_NAME
from .models import User, Wallet, Payment
@ -190,14 +192,31 @@ def get_wallet_payments(
return [Payment.from_row(row) for row in rows]
def delete_wallet_payments_expired(wallet_id: str, *, seconds: int = 86400) -> None:
def delete_expired_invoices() -> None:
with open_db() as db:
rows = db.fetchall(
"""
SELECT bolt11
FROM apipayments
WHERE pending = 1 AND amount > 0 AND time < strftime('%s', 'now') - 86400
"""
)
for (payment_request,) in rows:
try:
invoice = bolt11.decode(payment_request)
except:
continue
expiration_date = datetime.datetime.fromtimestamp(invoice.date + invoice.expiry)
if expiration_date > datetime.datetime.utcnow():
continue
db.execute(
"""
DELETE
FROM apipayments WHERE wallet = ? AND pending = 1 AND time < strftime('%s', 'now') - ?
DELETE FROM apipayments
WHERE pending = 1 AND payment_hash = ?
""",
(wallet_id, seconds),
(invoice.payment_hash,),
)

View file

@ -43,11 +43,6 @@ class Wallet(NamedTuple):
return get_wallet_payments(self.id, complete=complete, pending=pending, outgoing=outgoing, incoming=incoming)
def delete_expired_payments(self, seconds: int = 86400) -> None:
from .crud import delete_wallet_payments_expired
delete_wallet_payments_expired(self.id, seconds=seconds)
class Payment(NamedTuple):
checking_id: str

View file

@ -5,6 +5,7 @@ from binascii import unhexlify
from lnbits import bolt11
from lnbits.core import core_app
from lnbits.core.services import create_invoice, pay_invoice
from lnbits.core.crud import delete_expired_invoices
from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.settings import WALLET
@ -13,7 +14,7 @@ from lnbits.settings import WALLET
@api_check_wallet_key("invoice")
def api_payments():
if "check_pending" in request.args:
g.wallet.delete_expired_payments()
delete_expired_invoices()
for payment in g.wallet.get_payments(complete=False, pending=True):
if payment.is_uncheckable: