Run CheckInvoice jobs on startup

This commit is contained in:
ekzyis 2023-09-09 22:52:51 +02:00
parent d987934ba4
commit b2c7f28200
4 changed files with 47 additions and 2 deletions

View File

@ -137,6 +137,32 @@ func (db *DB) FetchInvoice(invoiceId string, invoice *Invoice) error {
return nil
}
type FetchInvoicesWhere struct {
Expired bool
}
func (db *DB) FetchInvoices(where *FetchInvoicesWhere, invoices *[]Invoice) error {
query := "" +
"SELECT id, msats, msats_received, preimage, hash, bolt11, created_at, expires_at, confirmed_at, held_since " +
"FROM invoices i "
if where.Expired {
query += "WHERE i.expires_at <= CURRENT_TIMESTAMP"
} else {
query += "WHERE i.expires_at > CURRENT_TIMESTAMP"
}
rows, err := db.Query(query)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var inv Invoice
rows.Scan(&inv.Id, &inv.Msats, &inv.ReceivedMsats, &inv.Preimage, &inv.PaymentHash, &inv.PaymentRequest, &inv.CreatedAt, &inv.ExpiresAt, &inv.ConfirmedAt, &inv.HeldSince)
*invoices = append(*invoices, inv)
}
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

View File

@ -81,7 +81,9 @@ func (lnd *LndClient) CheckInvoice(hash string) {
log.Printf("lookup invoice: hash=%s", hash)
invoice, err := lnd.LookupInvoice(context.TODO(), &lnrpc.PaymentHash{RHashStr: hash})
if err != nil {
panic(err)
log.Println(err)
time.Sleep(5 * time.Second)
continue
}
if time.Now().After(time.Unix(invoice.CreationDate+invoice.Expiry, 0)) {
log.Printf("invoice expired: hash=%s", hash)
@ -89,7 +91,9 @@ func (lnd *LndClient) CheckInvoice(hash string) {
}
if invoice.SettleDate != 0 && invoice.AmtPaidMsat > 0 {
if err := db.ConfirmInvoice(hash, time.Unix(invoice.SettleDate, 0), int(invoice.AmtPaidMsat)); err != nil {
panic(err)
log.Println(err)
time.Sleep(5 * time.Second)
continue
}
log.Printf("invoice confirmed: hash=%s", hash)
break

View File

@ -74,6 +74,9 @@ func main() {
}))
e.Use(sessionHandler)
e.HTTPErrorHandler = httpErrorHandler
if err := RunJobs(); err != nil {
log.Fatal(err)
}
err := e.Start(fmt.Sprintf("%s:%d", "127.0.0.1", PORT))
if err != http.ErrServerClosed {
log.Fatal(err)

12
src/worker.go Normal file
View File

@ -0,0 +1,12 @@
package main
func RunJobs() error {
var invoices []Invoice
if err := db.FetchInvoices(&FetchInvoicesWhere{Expired: false}, &invoices); err != nil {
return err
}
for _, inv := range invoices {
go lnd.CheckInvoice(inv.PaymentHash)
}
return nil
}