You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bit4sat/lndrpc/invoice_watcher.go

78 lines
1.5 KiB
Go

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)
}
}