diff --git a/src/db.go b/src/db.go index 041e92a..7064796 100644 --- a/src/db.go +++ b/src/db.go @@ -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 diff --git a/src/lnd.go b/src/lnd.go index 1670e82..0f8cc0c 100644 --- a/src/lnd.go +++ b/src/lnd.go @@ -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 diff --git a/src/server.go b/src/server.go index 508d9c5..fea6638 100644 --- a/src/server.go +++ b/src/server.go @@ -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) diff --git a/src/worker.go b/src/worker.go new file mode 100644 index 0000000..d9e1175 --- /dev/null +++ b/src/worker.go @@ -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 +}