Add the lnurlcash store, models and mint registry

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-13 21:47:52 +00:00
co-authored by Claude Fable 5.1
parent d04669b6d6
commit 1fc9a81cd2
7 changed files with 1116 additions and 0 deletions
+263
View File
@@ -0,0 +1,263 @@
package lnurlcash
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
)
// fakeMint is an in-memory LUD-25 service for tests: payRequest with a fee,
// comment-bound mint invoices, ?p= lookups, split and melt, plus switches to
// drop a response after applying a mutation.
type fakeMint struct {
t *testing.T
srv *httptest.Server
mu sync.Mutex
base int64
ppm int64
pubkey string
notes map[string]int64 // h -> value msat (outstanding)
burned map[string]bool
pending map[string]bool
inv map[string]*fakeInvoice // pr -> invoice
melts []fakeMelt
// failure switches
dropAfterSplit bool
refuseSplit string // reason to answer every split with
meltReason string // reason to answer every melt with
pubkeyChange string
calls map[string]int
}
type fakeInvoice struct {
h string
amount int64
settled bool
}
type fakeMelt struct {
h string
pr string
}
func newFakeMint(t *testing.T) *fakeMint {
m := &fakeMint{
t: t, base: 1000, ppm: 100,
pubkey: "021ab89df9cbd28cdab8c71d228ca40deba1eaebd827f24849ec4f3e919c023555",
notes: map[string]int64{}, burned: map[string]bool{}, pending: map[string]bool{},
inv: map[string]*fakeInvoice{}, calls: map[string]int{},
}
m.srv = httptest.NewServer(http.HandlerFunc(m.handle))
t.Cleanup(m.srv.Close)
return m
}
func (m *fakeMint) url() string { return m.srv.URL }
func (m *fakeMint) hashOf(k1 string) string {
raw, _ := hex.DecodeString(k1)
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
func writeJSON(w http.ResponseWriter, v interface{}) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
func errJSON(w http.ResponseWriter, reason string) {
writeJSON(w, map[string]string{"status": "ERROR", "reason": reason})
}
func (m *fakeMint) handle(w http.ResponseWriter, r *http.Request) {
m.mu.Lock()
defer m.mu.Unlock()
m.calls[r.URL.Path]++
q := r.URL.Query()
pub := m.pubkey
if m.pubkeyChange != "" {
pub = m.pubkeyChange
}
switch {
case r.URL.Path == "/.well-known/lnurlp/mint":
meta := fmt.Sprintf(`[["text/plain","fake mint"],["text/plain","Mint fees: %d,%d"]]`, m.base, m.ppm)
writeJSON(w, map[string]interface{}{
"tag": "payRequest", "callback": m.srv.URL + "/p/cb", "minSendable": 1000, "maxSendable": 100_000_000_000,
"metadata": meta, "withdrawLink": m.srv.URL + "/w", "commentAllowed": 64, "mintPubkey": pub,
})
case r.URL.Path == "/p/cb":
amount, _ := strconv.ParseInt(q.Get("amount"), 10, 64)
h := q.Get("comment")
if len(h) != 64 {
errJSON(w, "comment must be a 64 hex output")
return
}
pr := "fakepr" + strconv.Itoa(len(m.inv)+1) + h[:8]
m.inv[pr] = &fakeInvoice{h: h, amount: amount}
writeJSON(w, map[string]interface{}{"pr": pr, "routes": []string{}, "verify": m.srv.URL + "/v/" + pr})
case strings.HasPrefix(r.URL.Path, "/v/"):
pr := strings.TrimPrefix(r.URL.Path, "/v/")
inv, ok := m.inv[pr]
if !ok {
errJSON(w, "unknown invoice")
return
}
writeJSON(w, map[string]interface{}{"status": "OK", "settled": inv.settled, "preimage": "", "pr": pr})
case r.URL.Path == "/w":
m.withdraw(w, q, pub)
default:
http.NotFound(w, r)
}
}
func (m *fakeMint) withdraw(w http.ResponseWriter, q map[string][]string, pub string) {
get := func(k string) string {
if v := q[k]; len(v) > 0 {
return v[0]
}
return ""
}
k1s := q["k1"]
// informational GET by hash
if p := get("p"); p != "" && len(k1s) == 0 {
v, ok := m.notes[p]
if !ok {
if m.burned[p] {
errJSON(w, "already in use")
} else {
errJSON(w, "unknown note")
}
return
}
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest", "callback": m.srv.URL + "/w", "minWithdrawable": v, "maxWithdrawable": v, "defaultDescription": "fake", "mintPubkey": pub})
return
}
if len(k1s) == 0 {
errJSON(w, "no k1")
return
}
hs := make([]string, 0, len(k1s))
var total int64
for _, k1 := range k1s {
h := m.hashOf(strings.ToLower(k1))
if m.pending[h] {
errJSON(w, "pending")
return
}
v, ok := m.notes[h]
if !ok {
if m.burned[h] {
errJSON(w, "already in use")
} else {
errJSON(w, "unknown note")
}
return
}
hs = append(hs, h)
total += v
}
pr, amount, p1, p2 := get("pr"), get("amount"), get("p1"), get("p2")
switch {
case pr == "" && amount == "" && p1 == "" && len(k1s) == 1:
// informational GET by k1
writeJSON(w, map[string]interface{}{"tag": "withdrawRequest", "callback": m.srv.URL + "/w", "k1": k1s[0], "minWithdrawable": total, "maxWithdrawable": total, "defaultDescription": "fake", "mintPubkey": pub})
case pr != "":
if m.meltReason != "" {
errJSON(w, m.meltReason)
return
}
inv, ok := m.inv[pr]
if ok && inv.amount != total {
errJSON(w, "invoice amount must equal the note value")
return
}
m.pending[hs[0]] = true
m.melts = append(m.melts, fakeMelt{h: hs[0], pr: pr})
writeJSON(w, map[string]string{"status": "OK"})
case amount != "":
if m.refuseSplit != "" {
errJSON(w, m.refuseSplit)
return
}
a, _ := strconv.ParseInt(amount, 10, 64)
if p1 == "" || p2 == "" {
errJSON(w, "p1 and p2 required")
return
}
if _, used := m.notes[p1]; used || m.burned[p1] {
errJSON(w, "already in use")
return
}
change := total - a - m.base
if change <= 0 {
errJSON(w, "insufficient value")
return
}
for _, h := range hs {
delete(m.notes, h)
m.burned[h] = true
}
m.notes[p1] = a
m.notes[p2] = change
if m.dropAfterSplit {
m.dropAfterSplit = false
panic(http.ErrAbortHandler) // connection dropped after the mutation applied
}
writeJSON(w, map[string]string{"status": "OK"})
case p1 != "":
for _, h := range hs {
delete(m.notes, h)
m.burned[h] = true
}
m.notes[p1] = total
writeJSON(w, map[string]string{"status": "OK"})
default:
errJSON(w, "bad request")
}
}
// settle marks a mint invoice paid and credits its note.
func (m *fakeMint) settle(pr string) {
m.mu.Lock()
defer m.mu.Unlock()
inv, ok := m.inv[pr]
if !ok {
m.t.Fatalf("settle: unknown pr %s", pr)
}
inv.settled = true
net := inv.amount - m.base - (inv.amount/1_000_000)*m.ppm - ((inv.amount%1_000_000)*m.ppm)/1_000_000
m.notes[inv.h] = net
}
// finishMelt completes a pending melt: paid burns the note, failed restores it.
func (m *fakeMint) finishMelt(h string, paid bool) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.pending, h)
if paid {
delete(m.notes, h)
m.burned[h] = true
}
}
// claim burns a note as if somebody else redeemed it.
func (m *fakeMint) claim(h string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.notes, h)
m.burned[h] = true
}
func (m *fakeMint) value(h string) (int64, bool) {
m.mu.Lock()
defer m.mu.Unlock()
v, ok := m.notes[h]
return v, ok
}
+255
View File
@@ -0,0 +1,255 @@
package lnurlcash
import (
"context"
"fmt"
"net/http"
"sort"
"strings"
"sync"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// Registry holds the admin-listed mints and their health.
type Registry struct {
cfg *Config
store *Store
client *lnurlcash.Client
alert func(string)
mu sync.RWMutex
mints map[string]*Mint
}
// NewRegistry builds the registry. alert receives admin-worthy messages and
// may be nil. httpClient may be nil (then lnurlcash.NewClient's transport is
// used); a supplied client MUST disable keep-alives and MUST NOT retry.
func NewRegistry(cfg *Config, store *Store, httpClient *http.Client, alert func(string)) *Registry {
client := lnurlcash.NewClient()
if httpClient != nil {
client.HTTP = httpClient
}
if alert == nil {
alert = func(msg string) { log.Warnf("[lnurlcash] alert: %s", msg) }
}
r := &Registry{cfg: cfg, store: store, client: client, alert: alert, mints: map[string]*Mint{}}
for _, mc := range cfg.Mints {
m, err := store.Mint(mc.Name)
if err != nil {
log.Errorf("[lnurlcash] load mint %s: %v", mc.Name, err)
}
if m == nil {
m = &Mint{ID: mc.Name}
}
m.URL = mc.URL
m.PayURL = ResolveMintURL(mc.URL)
r.mints[mc.Name] = m
}
return r
}
// Client is the LNURLcash client every service call goes through.
func (r *Registry) Client() *lnurlcash.Client { return r.client }
// Check validates one mint: reachable, commentAllowed >= 64, a withdrawLink,
// a fee under the cap, and a pinned mintPubkey that has not changed.
func (r *Registry) Check(ctx context.Context, id string) error {
r.mu.RLock()
m, ok := r.mints[id]
r.mu.RUnlock()
if !ok {
return fmt.Errorf("lnurlcash: unknown mint %q", id)
}
err := r.check(ctx, m)
r.mu.Lock()
m.LastCheck = time.Now()
if err != nil {
m.Healthy = false
m.LastError = err.Error()
} else {
m.Healthy = true
m.LastError = ""
}
snapshot := *m
r.mu.Unlock()
if serr := r.store.SaveMint(&snapshot); serr != nil {
log.Errorf("[lnurlcash] save mint %s: %v", id, serr)
}
if err != nil {
log.Warnf("[lnurlcash] mint %s unhealthy: %v", id, err)
}
return err
}
func (r *Registry) check(ctx context.Context, m *Mint) error {
if m.PayURL == "" {
return fmt.Errorf("mint url does not resolve")
}
pay, err := r.client.FetchPayRequest(ctx, m.PayURL)
if err != nil {
return fmt.Errorf("payRequest: %w", err)
}
if pay.WithdrawLink == "" {
return fmt.Errorf("payRequest advertises no withdrawLink: not an LNURLcash mint")
}
if !pay.NamesMintOutput() {
return fmt.Errorf("commentAllowed below %d: the mint cannot mint to a hash", lnurlcash.MintCommentLength)
}
if !lnurlcash.IsAllowedServiceURL(lnurlcash.FromLud17(pay.WithdrawLink)) || !lnurlcash.IsAllowedServiceURL(pay.Callback) {
return fmt.Errorf("mint publishes a callback or withdrawLink that is not https")
}
if pay.HasMintFee && pay.MintFee.FeePpm > r.cfg.MaxMintFeePpm {
return fmt.Errorf("mint fee %d ppm is above max_mint_fee_ppm %d", pay.MintFee.FeePpm, r.cfg.MaxMintFeePpm)
}
pubkey := strings.ToLower(strings.TrimSpace(pay.MintPubkey))
if pubkey == "" {
// LUD-25 publishes the key on the withdraw side; try the mint address.
if addrURL := lnurlcash.MintAddressURL(m.PayURL); addrURL != "" {
if addr, aerr := r.client.FetchMintAddress(ctx, addrURL); aerr == nil {
pubkey = strings.ToLower(strings.TrimSpace(addr.NodePubkey))
}
}
}
if pubkey == "" {
return fmt.Errorf("mint publishes no mintPubkey")
}
if !lnurlcash.IsCompressedPubkey(pubkey) {
return fmt.Errorf("mint publishes a mintPubkey that is not a compressed secp256k1 key")
}
r.mu.Lock()
defer r.mu.Unlock()
m.PayCallback = pay.Callback
m.WithdrawLink = lnurlcash.FromLud17(pay.WithdrawLink)
m.FeeBaseMsat, m.FeePpm = 0, 0
if pay.HasMintFee {
m.FeeBaseMsat, m.FeePpm = pay.MintFee.BaseFeeMsat, pay.MintFee.FeePpm
}
m.CommentAllowed = pay.CommentAllowed
m.MinSendableMsat, m.MaxSendableMsat = pay.MinSendableMsat, pay.MaxSendableMsat
m.LastSeenPubkey = pubkey
if m.PinnedPubkey == "" {
m.PinnedPubkey = pubkey
log.Infof("[lnurlcash] pinned mintPubkey of %s", m.ID)
} else if m.PinnedPubkey != pubkey {
if !m.Disabled {
m.Disabled = true
r.alert(fmt.Sprintf("LNURLcash mint %s changed its mintPubkey (pinned %s…, now %s…). New notes at this mint are disabled until an admin clears the pin.", m.ID, m.PinnedPubkey[:8], pubkey[:8]))
}
return fmt.Errorf("mintPubkey changed; mint disabled")
}
return nil
}
// CheckAll checks every configured mint.
func (r *Registry) CheckAll(ctx context.Context) {
for _, mc := range r.cfg.Mints {
cctx, cancel := context.WithTimeout(ctx, 15*time.Second)
_ = r.Check(cctx, mc.Name)
cancel()
}
}
// RunHealth checks all mints now and then every interval until ctx ends.
func (r *Registry) RunHealth(ctx context.Context, interval time.Duration) {
r.CheckAll(ctx)
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
r.CheckAll(ctx)
}
}
}
// Get returns a copy of a mint's record.
func (r *Registry) Get(id string) (*Mint, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
m, ok := r.mints[id]
if !ok {
return nil, false
}
c := *m
return &c, true
}
// All returns copies of every mint, sorted by id.
func (r *Registry) All() []*Mint {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]*Mint, 0, len(r.mints))
for _, m := range r.mints {
c := *m
out = append(out, &c)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// Usable reports whether new notes may be minted at a mint.
func (m *Mint) Usable() bool {
return m != nil && m.Healthy && !m.Disabled && m.WithdrawLink != "" && m.PayCallback != ""
}
// ForUser returns the mint to mint at for a user: their preference if usable,
// else the configured default. ok is false when none is usable.
func (r *Registry) ForUser(user string) (*Mint, bool) {
if p, err := r.store.Pref(user); err == nil && p != nil {
if m, ok := r.Get(p.DefaultMintID); ok && m.Usable() {
return m, true
}
}
if d := r.cfg.DefaultMint(); d != nil {
if m, ok := r.Get(d.Name); ok && m.Usable() {
return m, true
}
}
for _, m := range r.All() {
if m.Usable() {
return m, true
}
}
return nil, false
}
// ByHost finds a configured mint by the host of a withdraw link or note URL.
func (r *Registry) ByHost(rawURL string) (*Mint, bool) {
host, err := lnurlcash.SpendDomainOf(rawURL)
if err != nil {
return nil, false
}
for _, m := range r.All() {
if h, err := lnurlcash.SpendDomainOf(m.WithdrawLink); err == nil && h == host {
return m, true
}
if h, err := lnurlcash.SpendDomainOf(m.PayURL); err == nil && h == host {
return m, true
}
}
return nil, false
}
// Fee returns a mint's advertised fee.
func (m *Mint) Fee() lnurlcash.MintFee {
return lnurlcash.MintFee{BaseFeeMsat: m.FeeBaseMsat, FeePpm: m.FeePpm}
}
// ClearPin forgets a mint's pinned key and re-enables it (admin action).
func (r *Registry) ClearPin(id string) error {
r.mu.Lock()
m, ok := r.mints[id]
if !ok {
r.mu.Unlock()
return fmt.Errorf("lnurlcash: unknown mint %q", id)
}
m.PinnedPubkey, m.Disabled = "", false
snapshot := *m
r.mu.Unlock()
return r.store.SaveMint(&snapshot)
}
+67
View File
@@ -0,0 +1,67 @@
package lnurlcash
import (
"context"
"strings"
"testing"
)
func testConfig(mintURL string) *Config {
c := &Config{Enabled: true, Mints: []MintConfig{{Name: "fake", URL: mintURL, Default: true}}, SecretEncryptionKey: testKey}
c.Normalize()
return c
}
func TestRegistryCheckAndPin(t *testing.T) {
fm := newFakeMint(t)
s := testStore(t)
cfg := testConfig(fm.url())
alerts := []string{}
r := NewRegistry(cfg, s, nil, func(msg string) { alerts = append(alerts, msg) })
if err := r.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
m, _ := r.Get("fake")
if !m.Usable() || m.PinnedPubkey != fm.pubkey || m.FeeBaseMsat != 1000 || m.FeePpm != 100 || m.WithdrawLink != fm.url()+"/w" {
t.Fatalf("mint not learned: %+v", m)
}
if got, _ := r.ForUser("42"); got.ID != "fake" {
t.Fatal("ForUser must return the default")
}
if got, ok := r.ByHost(fm.url() + "/w?k1=abc"); !ok || got.ID != "fake" {
t.Fatal("ByHost must find the mint")
}
// fee cap
cfg.MaxMintFeePpm = 50
if err := r.Check(context.Background(), "fake"); err == nil || !strings.Contains(err.Error(), "max_mint_fee_ppm") {
t.Fatalf("fee above cap must fail: %v", err)
}
cfg.MaxMintFeePpm = 20000
// pubkey change disables the mint and alerts once
fm.pubkeyChange = "03" + strings.Repeat("ab", 32)
for i := 0; i < 2; i++ {
if err := r.Check(context.Background(), "fake"); err == nil {
t.Fatal("changed pubkey must fail")
}
}
m, _ = r.Get("fake")
if !m.Disabled || m.Usable() || len(alerts) != 1 {
t.Fatalf("mint must be disabled with one alert: %+v alerts=%d", m, len(alerts))
}
if _, ok := r.ForUser("42"); ok {
t.Fatal("no usable mint expected")
}
// the pin survives a restart through the store
r2 := NewRegistry(cfg, s, nil, nil)
m2, _ := r2.Get("fake")
if m2.PinnedPubkey != fm.pubkey || !m2.Disabled {
t.Fatalf("pin not persisted: %+v", m2)
}
fm.pubkeyChange = ""
if err := r2.ClearPin("fake"); err != nil {
t.Fatal(err)
}
if err := r2.Check(context.Background(), "fake"); err != nil {
t.Fatal(err)
}
}
+171
View File
@@ -0,0 +1,171 @@
package lnurlcash
import "time"
// Note states. A note moves forward only; "unknown" is any step whose answer
// was lost and is resolved by the recovery job.
const (
NotePendingInvoice = "pending_invoice" // row written, no invoice yet
NotePendingSettle = "pending_settle" // invoice requested and paid (or paying), not seen at the mint yet
NotePendingCarve = "pending_carve" // secret exists, split not done yet
NoteLive = "live"
NoteClaimed = "claimed"
NoteReclaiming = "reclaiming" // melt sent, LNbits invoice not settled yet
NoteReclaimed = "reclaimed"
NoteFailed = "failed"
NoteUnknown = "unknown"
NoteSpent = "spent" // a funding or dust note burned by the bot's own split
)
// Note kinds.
const (
KindUser = "user" // a note the user holds and shares
KindFunding = "funding" // the note a paid mint invoice created; carved into user notes
KindDust = "dust" // the change left after carving; bot-owned
KindRedeemSplit = "redeem_split" // the whole-sat part split off a fractional external note
)
// Batch states.
const (
BatchPendingInvoice = "pending_invoice"
BatchPendingSettle = "pending_settle"
BatchCarving = "carving"
BatchLive = "live"
BatchPartial = "partial"
BatchClaimed = "claimed"
BatchReclaimed = "reclaimed"
BatchFailed = "failed"
BatchUnknown = "unknown"
)
// Redeem states.
const (
RedeemInfo = "info" // previewed, waiting for the user
RedeemConfirmed = "confirmed" // user pressed add, invoice being created
RedeemMelting = "melting" // melt accepted, waiting for the invoice to settle
RedeemSettled = "settled"
RedeemFailed = "failed"
RedeemUnknown = "unknown"
)
// Note is one LNURLcash note the bot knows the secret of.
type Note struct {
ID string `gorm:"primaryKey"`
BatchID *string `gorm:"index"`
UserName string `gorm:"index"` // lnbits.User.Name: the Telegram user id as text
MintID string `gorm:"index"`
MintURL string // the withdraw link notes are built on
MintPubkey string
Hash string `gorm:"uniqueIndex"` // h = sha256(k1): the note's public name
SecretEnc []byte
ValueMsat int64 // what the user asked for
ReportedMsat int64 // what the mint last reported (authoritative)
GrossMsat int64 // what was paid for it (funding notes)
FeeMsat int64
Memo string
State string `gorm:"index"`
Kind string `gorm:"index"`
Index int // position in its batch, 1-based
InvoicePR string
InvoiceHash string `gorm:"index"`
VerifyURL string
Certificate string
ChatID int64 // group chat the note was posted in, 0 for private
MessageID string // the group message, for edits
ReceiptMessageID string
LanguageCode string
LastProbe time.Time
LastError string
ClaimedAt *time.Time
ReclaimedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
func (Note) TableName() string { return "lnurlcash_notes" }
// Batch groups the notes created by one command.
type Batch struct {
ID string `gorm:"primaryKey"`
UserName string `gorm:"index"`
MintID string
Memo string
Count int
ValueMsat int64 // per note
TotalGrossMsat int64
FeeMsat int64
Strategy string
State string `gorm:"index"`
FundingNoteID string
InvoiceHash string
LastDigestAt time.Time
ChatID int64
LanguageCode string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Batch) TableName() string { return "lnurlcash_batches" }
// Redeem is a received note being melted into the user's balance.
type Redeem struct {
ID string `gorm:"primaryKey"`
UserName string `gorm:"index"`
MintHost string
KnownMint bool
NoteID string `gorm:"index"` // hex(Q), the id the mint files the note under
NoteURLEnc []byte // the full note URL, k1 included, sealed
ReportedMsat int64
State string `gorm:"index"`
InvoicePR string
InvoiceHash string `gorm:"index"`
SplitNoteID *string
LastError string
LanguageCode string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Redeem) TableName() string { return "lnurlcash_redeems" }
// UserPref holds a user's default mint.
type UserPref struct {
UserName string `gorm:"primaryKey"`
DefaultMintID string
UpdatedAt time.Time
}
func (UserPref) TableName() string { return "lnurlcash_user_prefs" }
// Mint is what the registry learned about a configured mint.
type Mint struct {
ID string `gorm:"primaryKey"` // the configured name
URL string
PayURL string
PayCallback string
WithdrawLink string
PinnedPubkey string
LastSeenPubkey string
FeeBaseMsat int64
FeePpm int64
CommentAllowed int64
MinSendableMsat int64
MaxSendableMsat int64
Healthy bool
Disabled bool
LastCheck time.Time
LastError string
CreatedAt time.Time
UpdatedAt time.Time
}
func (Mint) TableName() string { return "lnurlcash_mints" }
// IsFinal reports whether a note state cannot change any more.
func IsFinalNoteState(state string) bool {
switch state {
case NoteClaimed, NoteReclaimed, NoteFailed, NoteSpent:
return true
}
return false
}
+289
View File
@@ -0,0 +1,289 @@
package lnurlcash
import (
"errors"
"fmt"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// Store is the feature's own sqlite file.
type Store struct {
db *gorm.DB
}
// ErrStale is returned by a conditional transition whose row was not in the
// expected state: another worker got there first.
var ErrStale = errors.New("lnurlcash: row is not in the expected state")
// Open opens (and migrates) the database at path. Use "file::memory:?cache=shared"
// in tests.
func Open(path string) (*Store, error) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
return nil, fmt.Errorf("lnurlcash: open %s: %w", path, err)
}
if err := db.AutoMigrate(&Note{}, &Batch{}, &Redeem{}, &UserPref{}, &Mint{}); err != nil {
return nil, fmt.Errorf("lnurlcash: migrate: %w", err)
}
return &Store{db: db}, nil
}
// DB exposes the handle for tests and one-off queries.
func (s *Store) DB() *gorm.DB { return s.db }
// Transaction runs fn atomically.
func (s *Store) Transaction(fn func(tx *gorm.DB) error) error {
return s.db.Transaction(fn)
}
// ---- notes ----
func (s *Store) CreateNotes(tx *gorm.DB, notes []*Note) error {
if tx == nil {
tx = s.db
}
for _, n := range notes {
if err := tx.Create(n).Error; err != nil {
return err
}
}
return nil
}
func (s *Store) Note(id string) (*Note, error) {
var n Note
if err := s.db.First(&n, "id = ?", id).Error; err != nil {
return nil, err
}
return &n, nil
}
func (s *Store) NoteByHash(h string) (*Note, error) {
var n Note
if err := s.db.First(&n, "hash = ?", h).Error; err != nil {
return nil, err
}
return &n, nil
}
func (s *Store) NoteByInvoiceHash(h string) (*Note, error) {
var n Note
if err := s.db.First(&n, "invoice_hash = ?", h).Error; err != nil {
return nil, err
}
return &n, nil
}
// TransitionNote moves a note from one state to another, applying patch, and
// returns ErrStale when the note was not in the from state. from may be empty
// to skip the check.
func (s *Store) TransitionNote(id, from, to string, patch map[string]interface{}) error {
if patch == nil {
patch = map[string]interface{}{}
}
patch["state"] = to
patch["updated_at"] = time.Now()
q := s.db.Model(&Note{}).Where("id = ?", id)
if from != "" {
q = q.Where("state = ?", from)
}
res := q.Updates(patch)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrStale
}
return nil
}
// UpdateNote applies a patch without a state check.
func (s *Store) UpdateNote(id string, patch map[string]interface{}) error {
patch["updated_at"] = time.Now()
return s.db.Model(&Note{}).Where("id = ?", id).Updates(patch).Error
}
func (s *Store) NotesByState(states []string, kinds []string, limit int) ([]*Note, error) {
var notes []*Note
q := s.db.Where("state IN ?", states).Order("last_probe asc, created_at asc")
if len(kinds) > 0 {
q = q.Where("kind IN ?", kinds)
}
if limit > 0 {
q = q.Limit(limit)
}
return notes, q.Find(&notes).Error
}
func (s *Store) NotesInBatch(batchID string) ([]*Note, error) {
var notes []*Note
return notes, s.db.Where("batch_id = ?", batchID).Order("`index` asc").Find(&notes).Error
}
// UserNotes lists a user's own notes, newest first.
func (s *Store) UserNotes(user string, states []string) ([]*Note, error) {
var notes []*Note
q := s.db.Where("user_name = ? AND kind = ?", user, KindUser).Order("created_at desc")
if len(states) > 0 {
q = q.Where("state IN ?", states)
}
return notes, q.Find(&notes).Error
}
// Outstanding returns how many live or in-flight user notes a user has and
// their total requested value.
func (s *Store) Outstanding(user string) (count int64, sumMsat int64, err error) {
type row struct {
N int64
S int64
}
var r row
err = s.db.Model(&Note{}).
Select("count(*) as n, coalesce(sum(value_msat), 0) as s").
Where("user_name = ? AND kind = ? AND state NOT IN ?", user, KindUser,
[]string{NoteClaimed, NoteReclaimed, NoteFailed, NoteSpent}).
Scan(&r).Error
return r.N, r.S, err
}
// LiveNotesOlderThan lists live user notes created before t.
func (s *Store) LiveNotesOlderThan(t time.Time) ([]*Note, error) {
var notes []*Note
return notes, s.db.Where("state = ? AND kind = ? AND created_at < ?", NoteLive, KindUser, t).Find(&notes).Error
}
// ---- batches ----
func (s *Store) CreateBatch(tx *gorm.DB, b *Batch) error {
if tx == nil {
tx = s.db
}
return tx.Create(b).Error
}
func (s *Store) Batch(id string) (*Batch, error) {
var b Batch
if err := s.db.First(&b, "id = ?", id).Error; err != nil {
return nil, err
}
return &b, nil
}
func (s *Store) TransitionBatch(id, from, to string, patch map[string]interface{}) error {
if patch == nil {
patch = map[string]interface{}{}
}
patch["state"] = to
patch["updated_at"] = time.Now()
q := s.db.Model(&Batch{}).Where("id = ?", id)
if from != "" {
q = q.Where("state = ?", from)
}
res := q.Updates(patch)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrStale
}
return nil
}
func (s *Store) UpdateBatch(id string, patch map[string]interface{}) error {
patch["updated_at"] = time.Now()
return s.db.Model(&Batch{}).Where("id = ?", id).Updates(patch).Error
}
func (s *Store) BatchesByState(states []string) ([]*Batch, error) {
var bs []*Batch
return bs, s.db.Where("state IN ?", states).Order("created_at asc").Find(&bs).Error
}
// UserBatches lists a user's batches with more than one note, newest first.
func (s *Store) UserBatches(user string) ([]*Batch, error) {
var bs []*Batch
return bs, s.db.Where("user_name = ? AND count > 1", user).Order("created_at desc").Find(&bs).Error
}
// ---- redeems ----
func (s *Store) CreateRedeem(r *Redeem) error { return s.db.Create(r).Error }
func (s *Store) Redeem(id string) (*Redeem, error) {
var r Redeem
if err := s.db.First(&r, "id = ?", id).Error; err != nil {
return nil, err
}
return &r, nil
}
func (s *Store) RedeemByInvoiceHash(h string) (*Redeem, error) {
var r Redeem
if err := s.db.First(&r, "invoice_hash = ?", h).Error; err != nil {
return nil, err
}
return &r, nil
}
func (s *Store) TransitionRedeem(id, from, to string, patch map[string]interface{}) error {
if patch == nil {
patch = map[string]interface{}{}
}
patch["state"] = to
patch["updated_at"] = time.Now()
q := s.db.Model(&Redeem{}).Where("id = ?", id)
if from != "" {
q = q.Where("state = ?", from)
}
res := q.Updates(patch)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrStale
}
return nil
}
func (s *Store) RedeemsByState(states []string) ([]*Redeem, error) {
var rs []*Redeem
return rs, s.db.Where("state IN ?", states).Order("created_at asc").Find(&rs).Error
}
// ---- prefs and mints ----
func (s *Store) Pref(user string) (*UserPref, error) {
var p UserPref
err := s.db.First(&p, "user_name = ?", user).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return &p, err
}
func (s *Store) SetPref(user, mintID string) error {
return s.db.Save(&UserPref{UserName: user, DefaultMintID: mintID, UpdatedAt: time.Now()}).Error
}
func (s *Store) Mint(id string) (*Mint, error) {
var m Mint
err := s.db.First(&m, "id = ?", id).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return &m, err
}
func (s *Store) SaveMint(m *Mint) error { return s.db.Save(m).Error }
func (s *Store) Mints() ([]*Mint, error) {
var ms []*Mint
return ms, s.db.Order("id asc").Find(&ms).Error
}
+59
View File
@@ -0,0 +1,59 @@
package lnurlcash
import (
"testing"
"time"
)
func testStore(t *testing.T) *Store {
t.Helper()
s, err := Open("file:" + t.Name() + "?mode=memory&cache=shared")
if err != nil {
t.Fatal(err)
}
return s
}
func TestStoreTransitions(t *testing.T) {
s := testStore(t)
n := &Note{ID: "note-1", UserName: "42", Hash: "aa", ValueMsat: 1000_000, State: NotePendingCarve, Kind: KindUser}
if err := s.CreateNotes(nil, []*Note{n}); err != nil {
t.Fatal(err)
}
if err := s.TransitionNote("note-1", NoteLive, NoteClaimed, nil); err != ErrStale {
t.Fatalf("wrong-state transition must be stale, got %v", err)
}
if err := s.TransitionNote("note-1", NotePendingCarve, NoteLive, map[string]interface{}{"reported_msat": 1000_000}); err != nil {
t.Fatal(err)
}
got, _ := s.Note("note-1")
if got.State != NoteLive || got.ReportedMsat != 1000_000 {
t.Fatalf("unexpected note %+v", got)
}
count, sum, err := s.Outstanding("42")
if err != nil || count != 1 || sum != 1000_000 {
t.Fatalf("outstanding: %d %d %v", count, sum, err)
}
if err := s.TransitionNote("note-1", NoteLive, NoteClaimed, nil); err != nil {
t.Fatal(err)
}
count, _, _ = s.Outstanding("42")
if count != 0 {
t.Fatal("claimed notes must not count as outstanding")
}
if p, err := s.Pref("42"); err != nil || p != nil {
t.Fatal("no pref expected")
}
if err := s.SetPref("42", "21mint"); err != nil {
t.Fatal(err)
}
if p, _ := s.Pref("42"); p == nil || p.DefaultMintID != "21mint" {
t.Fatal("pref not stored")
}
old := &Note{ID: "note-2", UserName: "42", Hash: "bb", State: NoteLive, Kind: KindUser, CreatedAt: time.Now().Add(-48 * time.Hour)}
_ = s.CreateNotes(nil, []*Note{old})
older, _ := s.LiveNotesOlderThan(time.Now().Add(-24 * time.Hour))
if len(older) != 1 || older[0].ID != "note-2" {
t.Fatalf("expected note-2, got %v", older)
}
}
+12
View File
@@ -12,6 +12,7 @@ import (
"time"
"github.com/LightningTipBot/LightningTipBot/internal/database"
"github.com/LightningTipBot/LightningTipBot/internal/lnurlcash"
"github.com/LightningTipBot/LightningTipBot/internal/str"
"github.com/eko/gocache/store"
@@ -33,6 +34,8 @@ type Databases struct {
Users *gorm.DB
Transactions *gorm.DB
Groups *gorm.DB
// LNURLCash is nil when the feature is disabled.
LNURLCash *lnurlcash.Store
}
const (
@@ -136,10 +139,19 @@ func AutoMigration() *Databases {
panic(err)
}
var cashStore *lnurlcash.Store
if internal.Configuration.LNURLCash.Enabled {
cashStore, err = lnurlcash.Open(internal.Configuration.Database.LNURLCashPath)
if err != nil {
panic(err)
}
}
return &Databases{
Users: orm,
Transactions: txLogger,
Groups: groupsDb,
LNURLCash: cashStore,
}
}