diff --git a/lndrpc/commands.go b/lndrpc/commands.go index d72c36c..d8a8c3d 100644 --- a/lndrpc/commands.go +++ b/lndrpc/commands.go @@ -82,18 +82,3 @@ func AddInvoiceSat(desc string, satVal int64) (*lnrpc.Invoice, error) { return lookupInvoiceRhash(resp.RHash) } - -// Blocks until the invoice is paid or expired -func WatchInvoice(addIndex uint64) (*lnrpc.Invoice, error) { - ctxb := context.Background() - client, cleanUp := getClient() - defer cleanUp() - - subscription := &lnrpc.InvoiceSubscription{} - - subscriptionClient, err := client.SubscribeInvoices(ctxb, subscription) - if err != nil { - //return nil, err - } - -} diff --git a/lndrpc/invoice_watcher.go b/lndrpc/invoice_watcher.go new file mode 100644 index 0000000..feddf3c --- /dev/null +++ b/lndrpc/invoice_watcher.go @@ -0,0 +1,77 @@ +package lndrpc + +import ( + "io" + "log" + + "git.sp4ke.com/sp4ke/bit4sat/db" + lnrpc "github.com/lightningnetwork/lnd/lnrpc" + "github.com/mediocregopher/radix/v3" + "golang.org/x/net/context" +) + +const ( + LastSettledInvoiceIndexKey = "last_invoice_settled_index_cursor" +) + +// Last watched invoice +func getLastSettledInvoiceIndex() uint64 { + var cursor uint64 + + err := db.DB.Redis.Do(radix.FlatCmd(&cursor, "GET", LastSettledInvoiceIndexKey)) + if err != nil { + log.Fatal(err) + } + + return cursor +} + +func setLastSettledInvoiceIndex(index uint64) { + err := db.DB.Redis.Do(radix.FlatCmd(nil, "SET", LastSettledInvoiceIndexKey, index)) + if err != nil { + log.Fatal(err) + } +} + +// Runs in a goroutine and keep swatching invoices +func WatchInvoice(settleIndex uint64) { + + // Get the last invoice index cursor + cursor := getLastSettledInvoiceIndex() + log.Println(cursor) + + ctxb := context.Background() + client, cleanUp := getClient() + defer cleanUp() + + subscription := &lnrpc.InvoiceSubscription{} + + invoiceStream, err := client.SubscribeInvoices(ctxb, subscription) + if err != nil { + //return nil, err + } + + for { + invoice, err := invoiceStream.Recv() + if err == io.EOF { + break + } + + if err != nil { + log.Printf("error invoice stream %s", err) + break + } + + log.Printf("Received invoice \n%s\n", invoice) + + // We are only interested in settled invoices + if !invoice.Settled { + continue + } + + // Invoice was settled we need to save it and also notify the pubsub channel + // Save last settled index + setLastSettledInvoiceIndex(invoice.SettleIndex) + } + +} diff --git a/main.go b/main.go index d96fa83..a51a861 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,14 @@ package main -import ( - "git.sp4ke.com/sp4ke/bit4sat/api" - "git.sp4ke.com/sp4ke/bit4sat/db" -) +import "git.sp4ke.com/sp4ke/bit4sat/lndrpc" func main() { - defer db.DB.Sql.Close() + go lndrpc.WatchInvoice(0) + <-make(chan bool) - api := api.NewAPI() - api.Run() + //defer db.DB.Sql.Close() + + //api := api.NewAPI() + //api.Run() }