From 1351439a15146f5ad1c24185a5dcb65a68183b60 Mon Sep 17 00:00:00 2001 From: ekzyis Date: Thu, 9 Nov 2023 04:10:30 +0100 Subject: [PATCH] Run invoice checks on startup --- db/invoice.go | 34 +++++++++++++++++++++++++++++++++- lnd/invoice.go | 18 ++++++++++++++++++ main.go | 2 ++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/db/invoice.go b/db/invoice.go index 94b6512..82d60db 100644 --- a/db/invoice.go +++ b/db/invoice.go @@ -1,6 +1,9 @@ package db -import "time" +import ( + "database/sql" + "time" +) func (db *DB) CreateInvoice(invoice *Invoice) error { if err := db.QueryRow(""+ @@ -38,6 +41,35 @@ func (db *DB) FetchInvoice(where *FetchInvoiceWhere, invoice *Invoice) error { return nil } +type FetchInvoicesWhere struct { + Unconfirmed bool +} + +func (db *DB) FetchInvoices(where *FetchInvoicesWhere, invoices *[]Invoice) error { + var ( + rows *sql.Rows + invoice Invoice + err error + ) + var ( + query = "SELECT id, pubkey, msats, preimage, hash, bolt11, created_at, expires_at, confirmed_at, held_since, COALESCE(description, '') FROM invoices " + ) + if where.Unconfirmed { + query += "WHERE confirmed_at IS NULL" + } + if rows, err = db.Query(query); err != nil { + return err + } + defer rows.Close() + for rows.Next() { + rows.Scan( + &invoice.Id, &invoice.Pubkey, &invoice.Msats, &invoice.Preimage, &invoice.Hash, + &invoice.PaymentRequest, &invoice.CreatedAt, &invoice.ExpiresAt, &invoice.ConfirmedAt, &invoice.HeldSince, &invoice.Description) + *invoices = append(*invoices, invoice) + } + return nil +} + func (db *DB) ConfirmInvoice(hash string, confirmedAt time.Time, msatsReceived int) error { if _, err := db.Exec("UPDATE invoices SET confirmed_at = $2, msats_received = $3 WHERE hash = $1", hash, confirmedAt, msatsReceived); err != nil { return err diff --git a/lnd/invoice.go b/lnd/invoice.go index 7e5d9b1..337fa8d 100644 --- a/lnd/invoice.go +++ b/lnd/invoice.go @@ -106,3 +106,21 @@ func (lnd *LNDClient) CheckInvoice(d *db.DB, hash lntypes.Hash) { time.Sleep(pollInterval) } } + +func (lnd *LNDClient) CheckInvoices(d *db.DB) error { + var ( + invoices []db.Invoice + err error + hash lntypes.Hash + ) + if err = d.FetchInvoices(&db.FetchInvoicesWhere{Unconfirmed: true}, &invoices); err != nil { + return err + } + for _, invoice := range invoices { + if hash, err = lntypes.MakeHashFromStr(invoice.Hash); err != nil { + return err + } + go lnd.CheckInvoice(d, hash) + } + return nil +} diff --git a/main.go b/main.go index 87a5c34..defd744 100644 --- a/main.go +++ b/main.go @@ -54,6 +54,8 @@ func init() { }); err != nil { log.Printf("[warn] error connecting to LND: %v\n", err) lnd_ = nil + } else { + lnd_.CheckInvoices(db_) } ctx = server.ServerContext{