Phase 2: money

Lightning payments through LNbits, wallets, passes, credits, the
entitlement resolver and priority lanes.

- internal/entitle: pure resolver (one-off, own pass, group pass, group
  credits, own credits, free) with a table-driven suite and an invariant
  check over every input combination
- internal/billing: wallets, append-only ledger with dedupe keys, stacking
  passes, purchases, gift codes, referral reward
- LNbits client verified against v0.12.12 and v1.7.1 source
- Settlement by one conditional UPDATE: idempotent under any mix of
  webhooks, polls and the check button. Webhooks are unsigned, so every
  payment is confirmed with LNbits before it is credited
- Polling fallback, reconciliation of all unsettled invoices at startup,
  late payments still honored, no expiry while LNbits is unreachable
- Charge, quota and job are written in one transaction; failed, cancelled
  and undeliverable downloads are refunded exactly once
- Paid lane first with one slot of the fleet reserved for free users
- Daily download quota and daily volume cap, per-user and per-group rate
  limits
- Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice
  message that flips to paid, over-limit offer (passes or this file only),
  deep links from groups, skip the queue
- Fake LNbits server for tests; end-to-end money flows including a payment
  made while the core was down

Cashu redemption is behind an interface and not implemented.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 08:09:35 +00:00
co-authored by Claude Fable 5.2
parent 3b361c17a1
commit 0d50f453a0
42 changed files with 7040 additions and 140 deletions
+656
View File
@@ -0,0 +1,656 @@
// Package billing handles money: wallets, the append-only ledger, passes,
// invoices and their settlement.
//
// Safety rules this package enforces:
//
// - A purchase is settled by one conditional UPDATE. However many
// webhooks and polls race for the same invoice, exactly one wins.
// - A webhook is only a hint. LNbits webhooks are unsigned, so the
// payment is always confirmed with LNbits before anything is credited.
// - Webhooks can be lost (LNbits sends each one once), so unsettled
// invoices are also polled, and all of them are checked at startup.
// - A payment that arrives after its invoice was cancelled or expired is
// still credited. Money received is never dropped.
package billing
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/noderunners/dlbot/internal/billing/lnbits"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/entitle"
"github.com/noderunners/dlbot/internal/ids"
)
// Products that can be bought.
const (
ProductPassDay = "pass_day"
ProductPassWeek = "pass_week"
ProductPassMonth = "pass_month"
ProductCredits = "credits"
ProductOneOff = "one_off"
ProductSkipQueue = "skip_queue"
ProductDonation = "donation"
)
// Products lists every product, for validation and catalog checks.
var Products = []string{
ProductPassDay, ProductPassWeek, ProductPassMonth, ProductCredits,
ProductOneOff, ProductSkipQueue, ProductDonation,
}
// ValidProduct reports whether name is a product that exists.
func ValidProduct(name string) bool {
for _, p := range Products {
if p == name {
return true
}
}
return false
}
// Amount bounds for products whose amount the buyer picks.
const (
MinAmount = 10
MaxAmount = 5_000_000
)
// Errors returned by this package.
var (
ErrDisabled = errors.New("billing: payments are not configured")
ErrBadProduct = errors.New("billing: unknown product")
ErrBadAmount = errors.New("billing: amount out of range")
ErrNotOwner = errors.New("billing: purchase belongs to another user")
ErrGiftInvalid = errors.New("billing: gift code is not valid")
ErrGiftUsed = errors.New("billing: gift code was already used")
ErrLightningDown = errors.New("billing: lightning backend unreachable")
)
// Lightning is the payment backend. *lnbits.Client implements it.
type Lightning interface {
CreateInvoice(ctx context.Context, sats int64, memo string, expiry time.Duration, webhook string) (*lnbits.Invoice, error)
Paid(ctx context.Context, paymentHash string) (bool, error)
Health(ctx context.Context) error
}
// EventType says what happened to a purchase.
type EventType string
// The purchase events.
const (
EventPaid EventType = "paid"
EventExpired EventType = "expired"
EventCancelled EventType = "cancelled"
)
// Event is sent to listeners after the change is committed.
type Event struct {
Type EventType
Purchase *db.Purchase
}
// Billing is the money service.
type Billing struct {
store *db.Store
ln Lightning
cfg config.Config
log *slog.Logger
now func() time.Time
mu sync.Mutex
listeners []func(Event)
reachable bool
stats Stats
}
// Stats are counters for metrics.
type Stats struct {
InvoicesCreated int64
InvoicesSettled int64
}
// New creates the service. ln may be nil, which disables payments while
// wallets, grants and gift codes keep working.
func New(store *db.Store, ln Lightning, cfg config.Config, log *slog.Logger) *Billing {
if log == nil {
log = slog.Default()
}
return &Billing{store: store, ln: ln, cfg: cfg, log: log, now: time.Now, reachable: ln != nil}
}
// SetClock replaces the time source, for tests.
func (b *Billing) SetClock(now func() time.Time) { b.now = now }
// Enabled reports whether invoices can be created.
func (b *Billing) Enabled() bool { return b.ln != nil }
// Reachable reports whether the last call to the payment backend worked.
func (b *Billing) Reachable() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.reachable
}
// Stats returns a copy of the counters.
func (b *Billing) Stats() Stats {
b.mu.Lock()
defer b.mu.Unlock()
return b.stats
}
func (b *Billing) setReachable(ok bool) {
b.mu.Lock()
b.reachable = ok
b.mu.Unlock()
}
// Subscribe registers a listener for purchase events. Listeners are called
// synchronously and must not block.
func (b *Billing) Subscribe(fn func(Event)) {
b.mu.Lock()
defer b.mu.Unlock()
b.listeners = append(b.listeners, fn)
}
func (b *Billing) emit(t EventType, p *db.Purchase) {
b.mu.Lock()
ls := b.listeners
b.mu.Unlock()
for _, fn := range ls {
fn(Event{Type: t, Purchase: p})
}
}
func (b *Billing) nowMilli() int64 { return b.now().UnixMilli() }
// --- wallets ---------------------------------------------------------------
// Wallet returns the wallet of a user or group, creating it when needed.
func (b *Billing) Wallet(ctx context.Context, ownerType string, ownerID int64) (*db.Wallet, error) {
return b.store.EnsureWallet(ctx, ownerType, ownerID)
}
// State returns what the entitlement resolver needs to know about an
// owner's wallet. An owner without a wallet has an empty state.
func (b *Billing) State(ctx context.Context, ownerType string, ownerID int64) (entitle.Wallet, error) {
w, err := b.store.FindWallet(ctx, ownerType, ownerID)
if errors.Is(err, db.ErrNotFound) {
return entitle.Wallet{}, nil
}
if err != nil {
return entitle.Wallet{}, err
}
until, err := b.store.PassUntil(ctx, w.ID, b.nowMilli())
if err != nil {
return entitle.Wallet{}, err
}
return entitle.Wallet{ID: w.ID, PassUntil: until, Credits: w.Balance}, nil
}
// Credit adds sats to a wallet. The dedupe key makes it idempotent.
func (b *Billing) Credit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
return b.move(ctx, db.LedgerCredit, walletID, sats, reason, ref, dedupe, actor)
}
// Debit takes sats from a wallet, or fails with db.ErrInsufficient.
func (b *Billing) Debit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
return b.move(ctx, db.LedgerDebit, walletID, sats, reason, ref, dedupe, actor)
}
// Refund gives sats back to a wallet.
func (b *Billing) Refund(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
return b.move(ctx, db.LedgerRefund, walletID, sats, reason, ref, dedupe, actor)
}
func (b *Billing) move(ctx context.Context, kind, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) {
var applied bool
err := b.store.InTx(ctx, func(tx *db.Store) error {
var err error
applied, err = tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: walletID, Kind: kind, Amount: sats, Reason: reason, Ref: ref,
DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(),
})
return err
})
if errors.Is(err, db.ErrDuplicate) {
return false, nil
}
return applied, err
}
// PassLength returns how long a pass kind lasts.
func PassLength(kind string) time.Duration {
switch kind {
case "day":
return 24 * time.Hour
case "week":
return 7 * 24 * time.Hour
case "month":
return 30 * 24 * time.Hour
}
return 0
}
// passKind maps a product to its pass kind, or "".
func passKind(product string) string {
switch product {
case ProductPassDay:
return "day"
case ProductPassWeek:
return "week"
case ProductPassMonth:
return "month"
}
return ""
}
// GrantPass gives a wallet a pass without payment (owner grants, gifts).
func (b *Billing) GrantPass(ctx context.Context, walletID, kind, source string) (*db.Pass, error) {
length := PassLength(kind)
if length == 0 {
return nil, ErrBadProduct
}
var pass *db.Pass
err := b.store.InTx(ctx, func(tx *db.Store) error {
var err error
pass, err = tx.AddPass(ctx, walletID, kind, length.Milliseconds(), source, b.nowMilli())
return err
})
return pass, err
}
// --- purchases -------------------------------------------------------------
// Price returns the price in sats of a product. amount is used for the
// products whose amount the buyer or the caller decides.
func (b *Billing) Price(product string, amount int64) (int64, error) {
p := b.cfg.Prices
switch product {
case ProductPassDay, ProductPassWeek, ProductPassMonth:
return p.PassPrice(passKind(product)), nil
case ProductSkipQueue:
return p.SkipQueue, nil
case ProductCredits, ProductDonation, ProductOneOff:
if amount < MinAmount || amount > MaxAmount {
return 0, ErrBadAmount
}
return amount, nil
}
return 0, ErrBadProduct
}
// NewPurchase describes an invoice to create.
type NewPurchase struct {
// UserID is the payer. The invoice message goes to their private chat.
UserID int64
// WalletID is the wallet that benefits: the payer's or a group's.
WalletID string
Product string
// Amount is required for credits, donations and one-off payments.
Amount int64
// Memo is the description shown in the payer's Lightning wallet.
Memo string
Lang string
// RequestID and Profile name a download to start once paid.
RequestID string
Profile string
// DeliveryID names the waiting delivery for a skip-the-queue payment.
DeliveryID string
}
// CreatePurchase creates a Lightning invoice and records what it is for.
func (b *Billing) CreatePurchase(ctx context.Context, np NewPurchase) (*db.Purchase, error) {
if b.ln == nil {
return nil, ErrDisabled
}
price, err := b.Price(np.Product, np.Amount)
if err != nil {
return nil, err
}
if price <= 0 {
return nil, ErrBadAmount
}
expiry := b.cfg.LNbits.InvoiceExpiry.D()
inv, err := b.ln.CreateInvoice(ctx, price, np.Memo, expiry, b.WebhookURL())
if err != nil {
b.setReachable(false)
b.log.Error("create invoice failed", "product", np.Product, "user_id", np.UserID, "err", err)
return nil, fmt.Errorf("%w: %v", ErrLightningDown, err)
}
b.setReachable(true)
now := b.nowMilli()
p := &db.Purchase{
ID: ids.New(),
UserID: np.UserID,
WalletID: np.WalletID,
Product: np.Product,
AmountSats: price,
Status: db.PurchasePending,
PaymentHash: inv.PaymentHash,
Bolt11: inv.Bolt11,
Lang: np.Lang,
RequestID: np.RequestID,
Profile: np.Profile,
DeliveryID: np.DeliveryID,
CreatedAt: now,
ExpiresAt: now + expiry.Milliseconds(),
}
if err := b.store.InsertPurchase(ctx, p); err != nil {
return nil, err
}
b.mu.Lock()
b.stats.InvoicesCreated++
b.mu.Unlock()
// The payment hash identifies the invoice but is not a secret: it is
// printed inside every BOLT11 string. The invoice itself is not logged.
b.log.Info("invoice created", "purchase_id", p.ID, "product", p.Product, "sats", price,
"user_id", np.UserID, "wallet_id", np.WalletID)
return p, nil
}
// WebhookURL returns the address LNbits is asked to call, or "" when the
// core has no public URL. Without it settlement relies on polling.
func (b *Billing) WebhookURL() string {
if b.cfg.PublicURL == "" || b.cfg.LNbits.WebhookSecret == "" {
return ""
}
return b.cfg.PublicURL + "/lnbits/webhook/" + b.cfg.LNbits.WebhookSecret
}
// HandleWebhook processes a payment notification. The notification is not
// trusted: the invoice is looked up by hash and its status is read from
// LNbits before anything is credited. Unknown hashes are ignored.
func (b *Billing) HandleWebhook(ctx context.Context, paymentHash string) error {
p, err := b.store.GetPurchaseByHash(ctx, paymentHash)
if errors.Is(err, db.ErrNotFound) {
b.log.Warn("webhook for unknown payment hash")
return nil
}
if err != nil {
return err
}
_, err = b.checkOne(ctx, p)
return err
}
// Check asks LNbits about one purchase and settles it when paid. It
// returns the purchase in its current state.
func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (*db.Purchase, error) {
p, err := b.store.GetPurchase(ctx, purchaseID)
if err != nil {
return nil, err
}
if p.UserID != userID {
return nil, ErrNotOwner
}
if p.Status != db.PurchasePaid {
if _, err := b.checkOne(ctx, p); err != nil {
return nil, err
}
}
return b.store.GetPurchase(ctx, purchaseID)
}
// checkOne confirms a purchase with LNbits and settles or expires it.
func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, err error) {
if p.Status == db.PurchasePaid {
return false, nil
}
if b.ln == nil {
return false, ErrDisabled
}
paid, err := b.ln.Paid(ctx, p.PaymentHash)
if err != nil {
if errors.Is(err, lnbits.ErrNotFound) {
// LNbits does not know the invoice (for example after a wallet
// reset). It can never be paid, so it only expires.
paid = false
} else {
b.setReachable(false)
return false, fmt.Errorf("%w: %v", ErrLightningDown, err)
}
}
b.setReachable(true)
if paid {
return b.Settle(ctx, p.ID)
}
// Only expire after LNbits said "not paid". While LNbits cannot be
// asked, an invoice stays open rather than risk telling a payer that
// their paid invoice expired.
if p.Status == db.PurchasePending && b.nowMilli() > p.ExpiresAt {
closed, err := b.store.ClosePurchase(ctx, p.ID, db.PurchaseExpired)
if err != nil {
return false, err
}
if closed {
p.Status = db.PurchaseExpired
b.log.Info("invoice expired", "purchase_id", p.ID, "product", p.Product)
b.emit(EventExpired, p)
}
}
return false, nil
}
// Settle marks a purchase as paid and grants what it bought, in one
// transaction. It is idempotent: the second and later calls return false
// and change nothing. Callers must have confirmed the payment.
func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) {
var (
settled bool
p *db.Purchase
)
err := b.store.InTx(ctx, func(tx *db.Store) error {
now := b.nowMilli()
won, err := tx.MarkPurchasePaid(ctx, purchaseID, now)
if err != nil || !won {
return err
}
if p, err = tx.GetPurchase(ctx, purchaseID); err != nil {
return err
}
switch {
case p.Product == ProductCredits:
if _, err := tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: p.WalletID, Kind: db.LedgerCredit, Amount: p.AmountSats,
Reason: "purchase", Ref: p.ID, DedupeKey: "purchase:" + p.ID, ActorID: p.UserID, CreatedAt: now,
}); err != nil {
return err
}
case passKind(p.Product) != "":
kind := passKind(p.Product)
if _, err := tx.AddPass(ctx, p.WalletID, kind, PassLength(kind).Milliseconds(), p.ID, now); err != nil {
return err
}
}
// A purchase with nothing to start afterwards is complete here.
if p.RequestID == "" && p.DeliveryID == "" {
if _, err := tx.MarkPurchaseFulfilled(ctx, p.ID); err != nil {
return err
}
p.Fulfilled = true
}
if err := b.rewardReferrer(ctx, tx, p, now); err != nil {
return err
}
settled = true
return nil
})
if errors.Is(err, db.ErrDuplicate) {
return false, nil // another connection settled it first
}
if err != nil || !settled {
return false, err
}
b.mu.Lock()
b.stats.InvoicesSettled++
b.mu.Unlock()
b.log.Info("invoice settled", "purchase_id", p.ID, "product", p.Product, "sats", p.AmountSats,
"user_id", p.UserID, "wallet_id", p.WalletID)
b.emit(EventPaid, p)
return true, nil
}
// rewardReferrer credits the inviter on the invited user's first real
// purchase. The dedupe key allows one reward per invited user, ever.
func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purchase, now int64) error {
reward := b.cfg.Prices.ReferralReward
if reward <= 0 || p.Product == ProductDonation {
return nil
}
u, err := tx.GetUser(ctx, p.UserID)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil || u.ReferredBy == 0 {
return err
}
n, err := tx.CountPaidPurchases(ctx, p.UserID)
if err != nil || n != 1 {
return err
}
w, err := tx.EnsureWallet(ctx, db.OwnerUser, u.ReferredBy)
if err != nil {
return err
}
_, err = tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: w.ID, Kind: db.LedgerCredit, Amount: reward, Reason: "referral",
Ref: fmt.Sprint(p.UserID), DedupeKey: fmt.Sprintf("referral:%d", p.UserID), CreatedAt: now,
})
return err
}
// Cancel closes a pending purchase on the payer's request. If the invoice
// is paid anyway, the payment is still credited when it is detected.
func (b *Billing) Cancel(ctx context.Context, purchaseID string, userID int64) (*db.Purchase, error) {
p, err := b.store.GetPurchase(ctx, purchaseID)
if err != nil {
return nil, err
}
if p.UserID != userID {
return nil, ErrNotOwner
}
closed, err := b.store.ClosePurchase(ctx, p.ID, db.PurchaseCancelled)
if err != nil {
return nil, err
}
if closed {
p.Status = db.PurchaseCancelled
b.emit(EventCancelled, p)
}
return p, nil
}
// ConvertToCredits turns a paid purchase that could not deliver what it
// was for (the job is gone, the card expired) into credits of the same
// amount on the payer's wallet. Money received is never lost.
func (b *Billing) ConvertToCredits(ctx context.Context, p *db.Purchase) (bool, error) {
if p.Status != db.PurchasePaid {
return false, errors.New("billing: only paid purchases can be converted")
}
w, err := b.store.EnsureWallet(ctx, db.OwnerUser, p.UserID)
if err != nil {
return false, err
}
return b.Credit(ctx, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID)
}
// --- reconciliation --------------------------------------------------------
// ReconcileResult summarizes one reconciliation pass.
type ReconcileResult struct {
Checked int
Settled int
Errors int
}
// Reconcile checks unsettled purchases against LNbits: all pending ones,
// plus those that expired or were cancelled within the given window. It is
// run with a long window at startup and with a short one while polling.
func (b *Billing) Reconcile(ctx context.Context, window time.Duration) (ReconcileResult, error) {
var res ReconcileResult
if b.ln == nil {
return res, nil
}
list, err := b.store.UnsettledPurchases(ctx, b.nowMilli()-window.Milliseconds(), 1000)
if err != nil {
return res, err
}
for _, p := range list {
if ctx.Err() != nil {
return res, ctx.Err()
}
res.Checked++
settled, err := b.checkOne(ctx, p)
if err != nil {
res.Errors++
if errors.Is(err, ErrLightningDown) {
// No point hammering a backend that is down.
return res, err
}
b.log.Error("reconcile purchase", "purchase_id", p.ID, "err", err)
continue
}
if settled {
res.Settled++
}
}
return res, nil
}
// Windows used by Run.
const (
startupWindow = 7 * 24 * time.Hour
pollWindow = time.Hour
)
// Run reconciles everything once and then keeps polling until ctx ends.
// Pending invoices are checked every interval. Invoices that closed
// recently are checked on every twelfth pass, which is enough to catch a
// payment that crossed with an expiry.
func (b *Billing) Run(ctx context.Context) {
if b.ln == nil {
return
}
if res, err := b.Reconcile(ctx, startupWindow); err != nil {
b.log.Error("startup reconciliation failed, will keep trying", "err", err)
} else {
b.log.Info("startup reconciliation done", "checked", res.Checked, "settled", res.Settled)
}
interval := b.cfg.LNbits.PollInterval.D()
if interval <= 0 {
interval = 5 * time.Second
}
t := time.NewTicker(interval)
defer t.Stop()
for tick := 1; ; tick++ {
select {
case <-ctx.Done():
return
case <-t.C:
window := time.Duration(0)
if tick%12 == 0 {
window = pollWindow
}
if _, err := b.Reconcile(ctx, window); err != nil && ctx.Err() == nil {
b.log.Warn("payment poll failed", "err", err)
}
}
}
}
// Health checks the payment backend and remembers the outcome.
func (b *Billing) Health(ctx context.Context) error {
if b.ln == nil {
return nil
}
err := b.ln.Health(ctx)
b.setReachable(err == nil)
return err
}
+757
View File
@@ -0,0 +1,757 @@
package billing_test
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/billing/lnbits"
"github.com/noderunners/dlbot/internal/billing/lnbitstest"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/db/dbtest"
)
const alice = int64(1001)
type rig struct {
t *testing.T
ln *lnbitstest.Server
hooks *httptest.Server // receives webhooks like the core's HTTP API
sqldb *db.DB
store *db.Store
cfg config.Config
b *billing.Billing
now atomic.Int64
mu sync.Mutex
events []billing.Event
}
func newRig(t *testing.T) *rig {
t.Helper()
r := &rig{t: t, ln: lnbitstest.New(), sqldb: dbtest.Open(t)}
t.Cleanup(r.ln.Close)
r.store = r.sqldb.Store()
r.now.Store(time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC).UnixMilli())
// A stand-in for the core's webhook endpoint: it hands the payment
// hash from the body to the billing service, like internal/api does.
r.hooks = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
hash, ok := billing.ParseWebhook(req.Body)
if ok {
_ = r.b.HandleWebhook(req.Context(), hash)
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(r.hooks.Close)
r.cfg = config.Default()
r.cfg.LNbits.URL = r.ln.URL()
r.cfg.LNbits.InvoiceKey = lnbitstest.Key
r.cfg.LNbits.WebhookSecret = "hook-secret"
r.cfg.PublicURL = r.hooks.URL
r.b = r.newBilling()
return r
}
// newBilling builds a service on the rig's database, as a restarted core
// would.
func (r *rig) newBilling() *billing.Billing {
b := billing.New(r.store, lnbits.New(r.cfg.LNbits.URL, r.cfg.LNbits.InvoiceKey), r.cfg, nil)
b.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) })
b.Subscribe(func(ev billing.Event) {
r.mu.Lock()
r.events = append(r.events, ev)
r.mu.Unlock()
})
return b
}
func (r *rig) advance(d time.Duration) { r.now.Add(d.Milliseconds()) }
func (r *rig) wallet(user int64) *db.Wallet {
r.t.Helper()
w, err := r.b.Wallet(context.Background(), db.OwnerUser, user)
if err != nil {
r.t.Fatal(err)
}
return w
}
func (r *rig) buy(user int64, product string, amount int64) *db.Purchase {
r.t.Helper()
p, err := r.b.CreatePurchase(context.Background(), billing.NewPurchase{
UserID: user, WalletID: r.wallet(user).ID, Product: product, Amount: amount, Memo: "test " + product, Lang: "en",
})
if err != nil {
r.t.Fatalf("CreatePurchase: %v", err)
}
return p
}
func (r *rig) purchase(id string) *db.Purchase {
r.t.Helper()
p, err := r.store.GetPurchase(context.Background(), id)
if err != nil {
r.t.Fatal(err)
}
return p
}
func (r *rig) balance(user int64) int64 { return r.wallet(user).Balance }
func (r *rig) count(t billing.EventType) int {
r.mu.Lock()
defer r.mu.Unlock()
n := 0
for _, e := range r.events {
if e.Type == t {
n++
}
}
return n
}
// booksBalance fails the test when any wallet disagrees with its ledger.
func (r *rig) booksBalance() {
r.t.Helper()
bad, err := r.store.VerifyWallets(context.Background())
if err != nil {
r.t.Fatal(err)
}
if len(bad) > 0 {
r.t.Fatalf("wallet balances disagree with the ledger: %+v", bad)
}
}
func (r *rig) ledger(user int64) []*db.LedgerEntry {
r.t.Helper()
es, err := r.store.ListLedger(context.Background(), r.wallet(user).ID, 100)
if err != nil {
r.t.Fatal(err)
}
return es
}
func TestCreatePurchaseCreatesInvoice(t *testing.T) {
r := newRig(t)
p := r.buy(alice, billing.ProductCredits, 1000)
if p.Status != db.PurchasePending || p.AmountSats != 1000 || p.PaymentHash == "" || !strings.HasPrefix(p.Bolt11, "lnbc") {
t.Fatalf("purchase = %+v", p)
}
if got := p.ExpiresAt - p.CreatedAt; got != (10 * time.Minute).Milliseconds() {
t.Fatalf("expiry = %d ms, want 10 minutes", got)
}
inv, _ := r.ln.Last()
if inv.AmountSats != 1000 || inv.Memo != "test credits" || inv.Expiry != 600 ||
inv.Webhook != r.hooks.URL+"/lnbits/webhook/hook-secret" {
t.Fatalf("invoice at LNbits = %+v", inv)
}
if r.balance(alice) != 0 {
t.Fatal("an unpaid invoice must not credit anything")
}
}
func TestPricesComeFromConfig(t *testing.T) {
r := newRig(t)
for product, want := range map[string]int64{
billing.ProductPassDay: 700, billing.ProductPassWeek: 3000, billing.ProductPassMonth: 9000,
billing.ProductSkipQueue: 50,
} {
if p := r.buy(alice, product, 999_999); p.AmountSats != want {
t.Errorf("%s costs %d, want %d (the buyer must not set the price)", product, p.AmountSats, want)
}
}
for _, bad := range []int64{0, 9, -5, billing.MaxAmount + 1} {
_, err := r.b.CreatePurchase(context.Background(), billing.NewPurchase{
UserID: alice, WalletID: r.wallet(alice).ID, Product: billing.ProductCredits, Amount: bad,
})
if !errors.Is(err, billing.ErrBadAmount) {
t.Errorf("credits amount %d: %v, want ErrBadAmount", bad, err)
}
}
_, err := r.b.CreatePurchase(context.Background(), billing.NewPurchase{UserID: alice, Product: "yacht"})
if !errors.Is(err, billing.ErrBadProduct) {
t.Errorf("unknown product: %v", err)
}
}
// Acceptance: webhooks are idempotent.
func TestWebhookIsIdempotent(t *testing.T) {
r := newRig(t)
p := r.buy(alice, billing.ProductCredits, 5000)
if err := r.ln.Pay(p.PaymentHash); err != nil { // first webhook
t.Fatal(err)
}
// LNbits (or a proxy, or an attacker replaying traffic) delivers the
// same notification many more times, in parallel with polls.
var wg sync.WaitGroup
for i := 0; i < 12; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
if i%3 == 0 {
_, _ = r.b.Reconcile(context.Background(), time.Hour)
return
}
if err := r.ln.SendWebhook(p.PaymentHash); err != nil {
t.Errorf("webhook: %v", err)
}
}(i)
}
wg.Wait()
if got := r.balance(alice); got != 5000 {
t.Fatalf("balance = %d, want exactly one credit of 5000", got)
}
if es := r.ledger(alice); len(es) != 1 || es[0].Kind != db.LedgerCredit || es[0].Amount != 5000 ||
es[0].BalanceAfter != 5000 || es[0].DedupeKey != "purchase:"+p.ID {
t.Fatalf("ledger = %+v", es)
}
if got := r.purchase(p.ID); got.Status != db.PurchasePaid || got.PaidAt == 0 || !got.Fulfilled {
t.Fatalf("purchase = %+v", got)
}
if n := r.count(billing.EventPaid); n != 1 {
t.Fatalf("paid events = %d, want 1", n)
}
if s := r.b.Stats(); s.InvoicesCreated != 1 || s.InvoicesSettled != 1 {
t.Fatalf("stats = %+v", s)
}
r.booksBalance()
}
func TestForgedWebhookCreditsNothing(t *testing.T) {
r := newRig(t)
p := r.buy(alice, billing.ProductCredits, 5000)
// Somebody who learned the webhook URL claims the invoice was paid.
if err := r.ln.SendWebhook(p.PaymentHash); err != nil {
t.Fatal(err)
}
if r.balance(alice) != 0 || r.purchase(p.ID).Status != db.PurchasePending {
t.Fatal("an unconfirmed webhook must not settle anything")
}
// A hash that is not ours is ignored without an error.
if err := r.b.HandleWebhook(context.Background(), strings.Repeat("ab", 32)); err != nil {
t.Fatalf("unknown hash: %v", err)
}
}
func TestPassPurchaseAndStacking(t *testing.T) {
r := newRig(t)
ctx := context.Background()
day := (24 * time.Hour).Milliseconds()
p := r.buy(alice, billing.ProductPassDay, 0)
if err := r.ln.Pay(p.PaymentHash); err != nil {
t.Fatal(err)
}
st, err := r.b.State(ctx, db.OwnerUser, alice)
if err != nil {
t.Fatal(err)
}
if st.PassUntil != r.now.Load()+day || st.Credits != 0 {
t.Fatalf("state after day pass = %+v", st)
}
// A week pass bought while the day pass runs starts when it ends.
p2 := r.buy(alice, billing.ProductPassWeek, 0)
if err := r.ln.Pay(p2.PaymentHash); err != nil {
t.Fatal(err)
}
st, _ = r.b.State(ctx, db.OwnerUser, alice)
if st.PassUntil != r.now.Load()+8*day {
t.Fatalf("stacked pass ends in %d ms, want 8 days", st.PassUntil-r.now.Load())
}
// After everything expired a new pass starts now, not in the past.
r.advance(30 * 24 * time.Hour)
if st, _ = r.b.State(ctx, db.OwnerUser, alice); st.PassUntil != 0 {
t.Fatalf("pass should have expired, until=%d", st.PassUntil)
}
p3 := r.buy(alice, billing.ProductPassDay, 0)
if err := r.ln.Pay(p3.PaymentHash); err != nil {
t.Fatal(err)
}
if st, _ = r.b.State(ctx, db.OwnerUser, alice); st.PassUntil != r.now.Load()+day {
t.Fatalf("new pass after expiry ends in %d ms, want 1 day", st.PassUntil-r.now.Load())
}
if r.balance(alice) != 0 {
t.Fatal("a pass must not touch the credit balance")
}
}
func TestLostWebhookIsCaughtByPolling(t *testing.T) {
r := newRig(t)
r.ln.DropWebhooks = true
p := r.buy(alice, billing.ProductCredits, 2000)
if err := r.ln.Pay(p.PaymentHash); err != nil {
t.Fatal(err)
}
if r.balance(alice) != 0 {
t.Fatal("nothing should be credited before the poll")
}
res, err := r.b.Reconcile(context.Background(), 0)
if err != nil || res.Checked != 1 || res.Settled != 1 {
t.Fatalf("reconcile = %+v, %v", res, err)
}
if r.balance(alice) != 2000 {
t.Fatalf("balance = %d", r.balance(alice))
}
// Polling again finds nothing left to do.
if res, _ := r.b.Reconcile(context.Background(), time.Hour); res.Checked != 0 {
t.Fatalf("a settled purchase was checked again: %+v", res)
}
}
// Acceptance: reconciliation on startup.
func TestStartupReconciliation(t *testing.T) {
r := newRig(t)
r.ln.DropWebhooks = true
paid := r.buy(alice, billing.ProductCredits, 3000)
passPaid := r.buy(alice, billing.ProductPassDay, 0)
unpaid := r.buy(alice, billing.ProductCredits, 1000)
// The core goes down. While it is away two invoices are paid and all
// three run past their expiry.
for _, p := range []*db.Purchase{paid, passPaid} {
if err := r.ln.Pay(p.PaymentHash); err != nil {
t.Fatal(err)
}
}
r.advance(3 * time.Hour)
// A fresh core starts on the same database.
restarted := r.newBilling()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { defer close(done); restarted.Run(ctx) }()
deadline := time.Now().Add(5 * time.Second)
for r.purchase(unpaid.ID).Status == db.PurchasePending || r.purchase(passPaid.ID).Status != db.PurchasePaid {
if time.Now().After(deadline) {
t.Fatal("startup reconciliation did not finish")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
<-done
if r.purchase(paid.ID).Status != db.PurchasePaid || r.balance(alice) != 3000 {
t.Fatalf("paid credits invoice: status=%s balance=%d", r.purchase(paid.ID).Status, r.balance(alice))
}
st, _ := restarted.State(context.Background(), db.OwnerUser, alice)
if st.PassUntil != r.now.Load()+(24*time.Hour).Milliseconds() {
t.Fatalf("the pass paid during downtime was not granted: %+v", st)
}
if r.purchase(unpaid.ID).Status != db.PurchaseExpired {
t.Fatalf("unpaid invoice status = %s, want expired", r.purchase(unpaid.ID).Status)
}
r.booksBalance()
}
func TestExpiryAndLatePayment(t *testing.T) {
r := newRig(t)
r.ln.DropWebhooks = true
p := r.buy(alice, billing.ProductCredits, 1500)
r.advance(9 * time.Minute)
if _, err := r.b.Reconcile(context.Background(), 0); err != nil {
t.Fatal(err)
}
if r.purchase(p.ID).Status != db.PurchasePending {
t.Fatal("the invoice must stay open until its expiry")
}
r.advance(2 * time.Minute)
if _, err := r.b.Reconcile(context.Background(), 0); err != nil {
t.Fatal(err)
}
if r.purchase(p.ID).Status != db.PurchaseExpired || r.count(billing.EventExpired) != 1 {
t.Fatalf("status = %s, expired events = %d", r.purchase(p.ID).Status, r.count(billing.EventExpired))
}
// The payment crossed with the expiry: the payer's wallet sent it in
// the last second. The money arrived, so it must be credited.
if err := r.ln.Pay(p.PaymentHash); err != nil {
t.Fatal(err)
}
if res, _ := r.b.Reconcile(context.Background(), 0); res.Checked != 0 {
t.Fatal("a zero window only looks at pending invoices")
}
res, err := r.b.Reconcile(context.Background(), time.Hour)
if err != nil || res.Settled != 1 {
t.Fatalf("late payment not settled: %+v, %v", res, err)
}
if r.purchase(p.ID).Status != db.PurchasePaid || r.balance(alice) != 1500 {
t.Fatalf("status=%s balance=%d", r.purchase(p.ID).Status, r.balance(alice))
}
}
func TestCancelledButPaidIsStillCredited(t *testing.T) {
r := newRig(t)
p := r.buy(alice, billing.ProductCredits, 800)
if _, err := r.b.Cancel(context.Background(), p.ID, 9999); !errors.Is(err, billing.ErrNotOwner) {
t.Fatalf("cancel by a stranger: %v", err)
}
got, err := r.b.Cancel(context.Background(), p.ID, alice)
if err != nil || got.Status != db.PurchaseCancelled || r.count(billing.EventCancelled) != 1 {
t.Fatalf("cancel = %+v, %v", got, err)
}
// The user pays the invoice they still had open in their wallet.
if err := r.ln.Pay(p.PaymentHash); err != nil {
t.Fatal(err)
}
if r.purchase(p.ID).Status != db.PurchasePaid || r.balance(alice) != 800 {
t.Fatalf("status=%s balance=%d", r.purchase(p.ID).Status, r.balance(alice))
}
}
func TestCheckButton(t *testing.T) {
r := newRig(t)
r.ln.DropWebhooks = true
p := r.buy(alice, billing.ProductCredits, 400)
got, err := r.b.Check(context.Background(), p.ID, alice)
if err != nil || got.Status != db.PurchasePending {
t.Fatalf("check before payment = %+v, %v", got, err)
}
if _, err := r.b.Check(context.Background(), p.ID, 9999); !errors.Is(err, billing.ErrNotOwner) {
t.Fatalf("check by a stranger: %v", err)
}
_ = r.ln.Pay(p.PaymentHash)
got, err = r.b.Check(context.Background(), p.ID, alice)
if err != nil || got.Status != db.PurchasePaid || r.balance(alice) != 400 {
t.Fatalf("check after payment = %+v, %v", got, err)
}
// Checking a paid purchase does not ask LNbits again.
_, before := r.ln.Calls()
if _, err := r.b.Check(context.Background(), p.ID, alice); err != nil {
t.Fatal(err)
}
if _, after := r.ln.Calls(); after != before {
t.Fatal("a settled purchase should not be checked with LNbits")
}
}
func TestLightningDown(t *testing.T) {
r := newRig(t)
r.ln.DropWebhooks = true
p := r.buy(alice, billing.ProductCredits, 600)
_ = r.ln.Pay(p.PaymentHash)
r.ln.SetDown(true)
_, err := r.b.CreatePurchase(context.Background(), billing.NewPurchase{
UserID: alice, WalletID: r.wallet(alice).ID, Product: billing.ProductCredits, Amount: 100,
})
if !errors.Is(err, billing.ErrLightningDown) || r.b.Reachable() {
t.Fatalf("create while down: %v, reachable=%v", err, r.b.Reachable())
}
// Past its expiry and LNbits cannot be asked: the invoice must stay
// open, because it may well have been paid.
r.advance(time.Hour)
if _, err := r.b.Reconcile(context.Background(), time.Hour); !errors.Is(err, billing.ErrLightningDown) {
t.Fatalf("reconcile while down: %v", err)
}
if r.purchase(p.ID).Status != db.PurchasePending || r.count(billing.EventExpired) != 0 {
t.Fatal("an invoice must not expire while LNbits is unreachable")
}
r.ln.SetDown(false)
if res, err := r.b.Reconcile(context.Background(), time.Hour); err != nil || res.Settled != 1 {
t.Fatalf("reconcile after recovery: %+v, %v", res, err)
}
if r.balance(alice) != 600 || !r.b.Reachable() {
t.Fatalf("balance=%d reachable=%v", r.balance(alice), r.b.Reachable())
}
if err := r.b.Health(context.Background()); err != nil {
t.Fatalf("health: %v", err)
}
}
func TestWorksWithLNbitsV1Responses(t *testing.T) {
r := newRig(t)
r.ln.V1 = true
p := r.buy(alice, billing.ProductCredits, 250)
if !strings.HasPrefix(p.Bolt11, "lnbc") {
t.Fatalf("bolt11 not read from the v1 response: %q", p.Bolt11)
}
if err := r.ln.Pay(p.PaymentHash); err != nil {
t.Fatal(err)
}
if r.balance(alice) != 250 {
t.Fatalf("balance = %d", r.balance(alice))
}
}
func TestWrongKeyIsReported(t *testing.T) {
r := newRig(t)
bad := billing.New(r.store, lnbits.New(r.ln.URL(), "wrong-key"), r.cfg, nil)
_, err := bad.CreatePurchase(context.Background(), billing.NewPurchase{
UserID: alice, WalletID: r.wallet(alice).ID, Product: billing.ProductCredits, Amount: 100,
})
if !errors.Is(err, billing.ErrLightningDown) {
t.Fatalf("create with a wrong key: %v", err)
}
if strings.Contains(err.Error(), "wrong-key") {
t.Fatalf("the key leaked into the error: %v", err)
}
off := billing.New(r.store, nil, r.cfg, nil)
if _, err := off.CreatePurchase(context.Background(), billing.NewPurchase{Product: billing.ProductCredits, Amount: 100}); !errors.Is(err, billing.ErrDisabled) {
t.Fatalf("create without a backend: %v", err)
}
if off.Enabled() {
t.Fatal("billing without a backend must report disabled")
}
}
func TestReferralRewardOnFirstPurchaseOnly(t *testing.T) {
r := newRig(t)
ctx := context.Background()
const inviter, invited = int64(500), int64(501)
for _, id := range []int64{inviter, invited} {
if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil {
t.Fatal(err)
}
}
if ok, err := r.store.SetReferrer(ctx, invited, inviter); err != nil || !ok {
t.Fatalf("SetReferrer = %v, %v", ok, err)
}
// A referrer can be set once, never to oneself, never to a stranger.
if ok, _ := r.store.SetReferrer(ctx, invited, 777); ok {
t.Fatal("the referrer must not be replaced")
}
if ok, _ := r.store.SetReferrer(ctx, inviter, inviter); ok {
t.Fatal("self-referral must be refused")
}
if ok, _ := r.store.SetReferrer(ctx, inviter, 424242); ok {
t.Fatal("an unknown referrer must be refused")
}
// A donation is not a purchase and earns nothing.
_ = r.ln.Pay(r.buy(invited, billing.ProductDonation, 500).PaymentHash)
if r.balance(inviter) != 0 {
t.Fatal("a donation must not trigger the referral reward")
}
_ = r.ln.Pay(r.buy(invited, billing.ProductCredits, 1000).PaymentHash)
if r.balance(inviter) != 200 {
t.Fatalf("inviter balance = %d, want the 200 sat reward", r.balance(inviter))
}
_ = r.ln.Pay(r.buy(invited, billing.ProductPassDay, 0).PaymentHash)
if r.balance(inviter) != 200 {
t.Fatalf("inviter balance = %d, the reward must be paid once", r.balance(inviter))
}
if n, _ := r.store.CountReferrals(ctx, inviter); n != 1 {
t.Fatalf("referrals = %d", n)
}
r.booksBalance()
}
func TestLedgerRules(t *testing.T) {
r := newRig(t)
ctx := context.Background()
w := r.wallet(alice)
if ok, err := r.b.Credit(ctx, w.ID, 300, "grant", "", "grant:1", 0); err != nil || !ok {
t.Fatalf("credit = %v, %v", ok, err)
}
// The same dedupe key is applied once.
if ok, err := r.b.Credit(ctx, w.ID, 300, "grant", "", "grant:1", 0); err != nil || ok {
t.Fatalf("duplicate credit = %v, %v, want not applied", ok, err)
}
if ok, err := r.b.Debit(ctx, w.ID, 120, "download", "d1", "download:d1", alice); err != nil || !ok {
t.Fatalf("debit = %v, %v", ok, err)
}
// A debit larger than the balance fails and changes nothing.
if _, err := r.b.Debit(ctx, w.ID, 181, "download", "d2", "download:d2", alice); !errors.Is(err, db.ErrInsufficient) {
t.Fatalf("overdraft: %v, want ErrInsufficient", err)
}
if ok, err := r.b.Refund(ctx, w.ID, 120, "refund", "d1", "refund:d1", 0); err != nil || !ok {
t.Fatalf("refund = %v, %v", ok, err)
}
if ok, _ := r.b.Refund(ctx, w.ID, 120, "refund", "d1", "refund:d1", 0); ok {
t.Fatal("a refund must not be applied twice")
}
if _, err := r.b.Credit(ctx, w.ID, 0, "x", "", "zero", 0); err == nil {
t.Fatal("a zero amount must be rejected")
}
if _, err := r.b.Credit(ctx, w.ID, 5, "x", "", "", 0); err == nil {
t.Fatal("an entry without a dedupe key must be rejected")
}
if got := r.balance(alice); got != 300 {
t.Fatalf("balance = %d, want 300", got)
}
es := r.ledger(alice)
if len(es) != 3 {
t.Fatalf("ledger has %d entries, want 3 (credit, debit, refund)", len(es))
}
// Newest first: refund, debit, credit. Each row records the balance.
want := []struct {
kind string
after int64
}{{db.LedgerRefund, 300}, {db.LedgerDebit, 180}, {db.LedgerCredit, 300}}
for i, w := range want {
if es[i].Kind != w.kind || es[i].BalanceAfter != w.after {
t.Errorf("entry %d = %s after=%d, want %s after=%d", i, es[i].Kind, es[i].BalanceAfter, w.kind, w.after)
}
}
if sum, _ := r.store.LedgerBalance(ctx, w.ID); sum != 300 {
t.Fatalf("ledger sum = %d", sum)
}
r.booksBalance()
// The check catches a balance that was changed behind the ledger.
if _, err := r.sqldb.SQL.ExecContext(ctx, `UPDATE wallets SET balance = balance + 1 WHERE id = ?`, w.ID); err != nil {
t.Fatal(err)
}
bad, err := r.store.VerifyWallets(ctx)
if err != nil || len(bad) != 1 || bad[0].WalletID != w.ID || bad[0].Balance != 301 || bad[0].Ledger != 300 {
t.Fatalf("VerifyWallets = %+v, %v", bad, err)
}
}
func TestConcurrentDebitsNeverOverdraw(t *testing.T) {
r := newRig(t)
ctx := context.Background()
w := r.wallet(alice)
if _, err := r.b.Credit(ctx, w.ID, 500, "grant", "", "seed", 0); err != nil {
t.Fatal(err)
}
var ok, short atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 20; i++ { // 20 debits of 50 against 500 sats
wg.Add(1)
go func(i int) {
defer wg.Done()
applied, err := r.b.Debit(ctx, w.ID, 50, "download", "", "d:"+string(rune('a'+i)), alice)
switch {
case err == nil && applied:
ok.Add(1)
case errors.Is(err, db.ErrInsufficient):
short.Add(1)
default:
t.Errorf("debit: applied=%v err=%v", applied, err)
}
}(i)
}
wg.Wait()
if ok.Load() != 10 || short.Load() != 10 || r.balance(alice) != 0 {
t.Fatalf("ok=%d short=%d balance=%d, want 10/10/0", ok.Load(), short.Load(), r.balance(alice))
}
r.booksBalance()
}
func TestConvertToCredits(t *testing.T) {
r := newRig(t)
ctx := context.Background()
p := r.buy(alice, billing.ProductOneOff, 150)
if _, err := r.b.ConvertToCredits(ctx, p); err == nil {
t.Fatal("an unpaid purchase must not be converted")
}
_ = r.ln.Pay(p.PaymentHash)
if r.balance(alice) != 0 {
t.Fatal("a one-off payment is not credits by itself")
}
paid := r.purchase(p.ID)
for i := 0; i < 3; i++ {
if _, err := r.b.ConvertToCredits(ctx, paid); err != nil {
t.Fatal(err)
}
}
if r.balance(alice) != 150 {
t.Fatalf("balance = %d, want one conversion of 150", r.balance(alice))
}
}
func TestGiftCodes(t *testing.T) {
r := newRig(t)
ctx := context.Background()
const bob = int64(1002)
credits, err := r.b.NewGiftCode(ctx, billing.GiftCredits, 400, 2, 0, 1)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(credits.Code, "NR-") || len(credits.Code) != 17 {
t.Fatalf("code shape = %q", credits.Code)
}
// Users type codes in lower case and with spaces.
typed := " " + strings.ToLower(credits.Code) + " "
res, err := r.b.RedeemGift(ctx, alice, typed)
if err != nil || res.Sats != 400 || r.balance(alice) != 400 {
t.Fatalf("redeem = %+v, %v, balance %d", res, err, r.balance(alice))
}
if _, err := r.b.RedeemGift(ctx, alice, credits.Code); !errors.Is(err, billing.ErrGiftUsed) {
t.Fatalf("same user twice: %v", err)
}
if _, err := r.b.RedeemGift(ctx, bob, credits.Code); err != nil {
t.Fatalf("second user: %v", err)
}
if _, err := r.b.RedeemGift(ctx, 1003, credits.Code); !errors.Is(err, billing.ErrGiftUsed) {
t.Fatalf("third user on a two-use code: %v", err)
}
if r.balance(alice) != 400 || r.balance(bob) != 400 {
t.Fatalf("balances = %d, %d", r.balance(alice), r.balance(bob))
}
pass, err := r.b.NewGiftCode(ctx, billing.GiftWeek, 0, 1, 0, 1)
if err != nil {
t.Fatal(err)
}
res, err = r.b.RedeemGift(ctx, alice, pass.Code)
if err != nil || res.PassUntil != r.now.Load()+(7*24*time.Hour).Milliseconds() {
t.Fatalf("pass gift = %+v, %v", res, err)
}
expiring, _ := r.b.NewGiftCode(ctx, billing.GiftCredits, 100, 1, r.now.Load()+1000, 1)
r.advance(2 * time.Second)
if _, err := r.b.RedeemGift(ctx, alice, expiring.Code); !errors.Is(err, billing.ErrGiftUsed) {
t.Fatalf("expired code: %v", err)
}
for _, bad := range []string{"", "NR-NOPE-NOPE-NOPE", "'; DROP TABLE wallets; --"} {
if _, err := r.b.RedeemGift(ctx, alice, bad); !errors.Is(err, billing.ErrGiftInvalid) {
t.Errorf("code %q: %v, want ErrGiftInvalid", bad, err)
}
}
if _, err := r.b.NewGiftCode(ctx, "yacht", 1, 1, 0, 1); !errors.Is(err, billing.ErrBadProduct) {
t.Fatalf("unknown gift kind: %v", err)
}
r.booksBalance()
}
func TestGrantPassAndState(t *testing.T) {
r := newRig(t)
ctx := context.Background()
// A user who never had a wallet has an empty state and gets none made.
st, err := r.b.State(ctx, db.OwnerUser, 31337)
if err != nil || st.ID != "" || st.Credits != 0 || st.PassUntil != 0 {
t.Fatalf("state of a stranger = %+v, %v", st, err)
}
if _, err := r.store.FindWallet(ctx, db.OwnerUser, 31337); !errors.Is(err, db.ErrNotFound) {
t.Fatal("State must not create wallets")
}
w := r.wallet(alice)
if _, err := r.b.GrantPass(ctx, w.ID, "month", "owner"); err != nil {
t.Fatal(err)
}
st, _ = r.b.State(ctx, db.OwnerUser, alice)
if st.PassUntil != r.now.Load()+(30*24*time.Hour).Milliseconds() || st.ID != w.ID {
t.Fatalf("state = %+v", st)
}
if _, err := r.b.GrantPass(ctx, w.ID, "decade", "owner"); !errors.Is(err, billing.ErrBadProduct) {
t.Fatalf("unknown pass kind: %v", err)
}
// Group wallets are separate from user wallets with the same number.
g, err := r.b.Wallet(ctx, db.OwnerGroup, alice)
if err != nil || g.ID == w.ID {
t.Fatalf("group wallet = %+v, %v", g, err)
}
}
+162
View File
@@ -0,0 +1,162 @@
package billing
import (
"context"
"crypto/rand"
"errors"
"strconv"
"strings"
"github.com/noderunners/dlbot/internal/db"
)
// Gift code kinds.
const (
GiftCredits = "credits"
GiftDay = "day"
GiftWeek = "week"
GiftMonth = "month"
)
// codeAlphabet avoids look-alike characters (0/O, 1/I/L).
const codeAlphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
// NewGiftCode creates a redeemable code. kind is "credits" with an amount
// in sats, or a pass kind. expiresAt is unix milliseconds, 0 for never.
func (b *Billing) NewGiftCode(ctx context.Context, kind string, amount int64, maxUses int, expiresAt, createdBy int64) (*db.GiftCode, error) {
switch kind {
case GiftCredits:
if amount < 1 || amount > MaxAmount {
return nil, ErrBadAmount
}
case GiftDay, GiftWeek, GiftMonth:
amount = 0
default:
return nil, ErrBadProduct
}
if maxUses < 1 {
maxUses = 1
}
for attempt := 0; attempt < 5; attempt++ {
g := &db.GiftCode{
Code: randomCode(), Kind: kind, Amount: amount, MaxUses: maxUses,
ExpiresAt: expiresAt, CreatedBy: createdBy, CreatedAt: b.nowMilli(),
}
err := b.store.InsertGiftCode(ctx, g)
if errors.Is(err, db.ErrDuplicate) {
continue
}
return g, err
}
return nil, errors.New("billing: could not generate a unique gift code")
}
// randomCode returns a code like "NR-7KQ2-M9XA-4TBP": 12 random characters
// from a 31 letter alphabet, about 59 bits.
func randomCode() string {
var raw [12]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("billing: no entropy: " + err.Error())
}
var sb strings.Builder
sb.WriteString("NR")
for i, v := range raw {
if i%4 == 0 {
sb.WriteByte('-')
}
sb.WriteByte(codeAlphabet[int(v)%len(codeAlphabet)])
}
return sb.String()
}
// NormalizeCode cleans up a code as typed by a user.
func NormalizeCode(s string) string {
s = strings.ToUpper(strings.TrimSpace(s))
return strings.Join(strings.Fields(s), "")
}
// GiftResult says what a redeemed code gave.
type GiftResult struct {
Kind string
Sats int64 // credits added
PassUntil int64 // new end of pass coverage, unix milliseconds
}
// RedeemGift applies a gift code to the user's wallet. Each user can use a
// code once, and a code stops working after its maximum number of uses.
func (b *Billing) RedeemGift(ctx context.Context, userID int64, code string) (*GiftResult, error) {
code = NormalizeCode(code)
if code == "" {
return nil, ErrGiftInvalid
}
res := &GiftResult{}
err := b.store.InTx(ctx, func(tx *db.Store) error {
g, err := tx.GetGiftCode(ctx, code)
if errors.Is(err, db.ErrNotFound) {
return ErrGiftInvalid
}
if err != nil {
return err
}
now := b.nowMilli()
used, err := tx.UseGiftCode(ctx, code, userID, now)
if err != nil {
return err
}
if !used {
return ErrGiftUsed
}
w, err := tx.EnsureWallet(ctx, db.OwnerUser, userID)
if err != nil {
return err
}
res.Kind = g.Kind
if g.Kind == GiftCredits {
res.Sats = g.Amount
_, err = tx.AddLedger(ctx, &db.LedgerEntry{
WalletID: w.ID, Kind: db.LedgerCredit, Amount: g.Amount, Reason: "gift", Ref: code,
DedupeKey: "gift:" + code + ":" + strconv.FormatInt(userID, 10), ActorID: userID, CreatedAt: now,
})
return err
}
pass, err := tx.AddPass(ctx, w.ID, g.Kind, PassLength(g.Kind).Milliseconds(), "gift:"+code, now)
if err != nil {
return err
}
res.PassUntil = pass.ExpiresAt
return nil
})
if errors.Is(err, db.ErrDuplicate) {
return nil, ErrGiftUsed
}
if err != nil {
return nil, err
}
b.log.Info("gift code redeemed", "user_id", userID, "kind", res.Kind, "sats", res.Sats)
return res, nil
}
// --- Cashu -----------------------------------------------------------------
// Cashu redeems ecash tokens into sats. The bot only talks to this
// interface; see cashu.go for the mint client behind it.
type Cashu interface {
// Redeem melts a token and returns the sats that arrived. It must be
// safe to call twice with the same token: a spent token is an error.
Redeem(ctx context.Context, token string) (sats int64, err error)
}
// IsCashuToken reports whether text looks like a Cashu token (V3 "cashuA"
// or V4 "cashuB").
func IsCashuToken(text string) bool {
t := strings.TrimSpace(text)
return strings.HasPrefix(t, "cashuA") || strings.HasPrefix(t, "cashuB")
}
// Cashu errors.
var (
ErrCashuDisabled = errors.New("billing: cashu is not configured")
ErrCashuMint = errors.New("billing: cashu mint is not on the allow list")
ErrCashuInvalid = errors.New("billing: cashu token is not valid")
ErrCashuSpent = errors.New("billing: cashu token was already spent")
)
+194
View File
@@ -0,0 +1,194 @@
// Package lnbits is a small client for the LNbits HTTP API.
//
// It was written against the LNbits source at v0.12.12 and checked against
// v1.7.1. Only three calls are used and they are the same in both:
//
// POST /api/v1/payments create an invoice (invoice key)
// GET /api/v1/payments/{hash} payment status (invoice key)
// GET /api/v1/wallet wallet info, used as a health check
//
// The one difference: v0.12 returns the invoice as "payment_request", v1
// returns the payment object with "bolt11". Both are read.
package lnbits
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// ErrNotFound is returned when LNbits does not know a payment hash.
var ErrNotFound = errors.New("lnbits: payment not found")
// Invoice is a created Lightning invoice.
type Invoice struct {
PaymentHash string
Bolt11 string
}
// Client talks to one LNbits wallet with its invoice key. The invoice key
// can create invoices and read payments but cannot spend, so a leaked key
// cannot drain the wallet.
type Client struct {
baseURL string
key string
http *http.Client
}
// New creates a client. baseURL is the LNbits root, for example
// https://lnbits.example.com.
func New(baseURL, invoiceKey string) *Client {
return &Client{
baseURL: strings.TrimRight(baseURL, "/"),
key: invoiceKey,
http: &http.Client{Timeout: 20 * time.Second},
}
}
type createRequest struct {
Out bool `json:"out"`
Amount int64 `json:"amount"`
Unit string `json:"unit"`
Memo string `json:"memo"`
Expiry int64 `json:"expiry,omitempty"`
Webhook string `json:"webhook,omitempty"`
}
type createResponse struct {
PaymentHash string `json:"payment_hash"`
PaymentRequest string `json:"payment_request"`
Bolt11 string `json:"bolt11"`
}
// CreateInvoice asks LNbits for an invoice of the given amount in sats.
// webhook may be empty; LNbits posts to it once when the invoice is paid.
func (c *Client) CreateInvoice(ctx context.Context, sats int64, memo string, expiry time.Duration, webhook string) (*Invoice, error) {
if sats <= 0 {
return nil, errors.New("lnbits: amount must be positive")
}
body, err := json.Marshal(createRequest{
Out: false, Amount: sats, Unit: "sat", Memo: memo,
Expiry: int64(expiry.Seconds()), Webhook: webhook,
})
if err != nil {
return nil, err
}
var resp createResponse
if err := c.do(ctx, http.MethodPost, "/api/v1/payments", body, &resp); err != nil {
return nil, err
}
inv := &Invoice{PaymentHash: resp.PaymentHash, Bolt11: resp.PaymentRequest}
if inv.Bolt11 == "" {
inv.Bolt11 = resp.Bolt11
}
if inv.PaymentHash == "" || inv.Bolt11 == "" {
return nil, errors.New("lnbits: invoice response lacks payment_hash or invoice")
}
return inv, nil
}
type statusResponse struct {
Paid bool `json:"paid"`
}
// Paid reports whether the invoice with the given payment hash is settled.
func (c *Client) Paid(ctx context.Context, paymentHash string) (bool, error) {
if !isHex(paymentHash) {
return false, ErrNotFound
}
var resp statusResponse
if err := c.do(ctx, http.MethodGet, "/api/v1/payments/"+paymentHash, nil, &resp); err != nil {
return false, err
}
return resp.Paid, nil
}
// Health checks that LNbits is reachable and accepts the key.
func (c *Client) Health(ctx context.Context) error {
var resp map[string]any
return c.do(ctx, http.MethodGet, "/api/v1/wallet", nil, &resp)
}
func (c *Client) do(ctx context.Context, method, path string, body []byte, out any) error {
var rd io.Reader
if body != nil {
rd = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, rd)
if err != nil {
return err
}
req.Header.Set("X-Api-Key", c.key)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
// The error text of net/http includes the URL but never headers, so
// the key cannot leak through it.
return fmt.Errorf("lnbits: %s %s: %w", method, path, err)
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return fmt.Errorf("lnbits: %s %s: %w", method, path, err)
}
switch {
case resp.StatusCode == http.StatusNotFound:
return ErrNotFound
case resp.StatusCode < 200 || resp.StatusCode > 299:
return &StatusError{Code: resp.StatusCode, Detail: detail(data)}
}
if out == nil {
return nil
}
if err := json.Unmarshal(data, out); err != nil {
return fmt.Errorf("lnbits: %s %s: bad response: %w", method, path, err)
}
return nil
}
// StatusError is a non-2xx answer from LNbits.
type StatusError struct {
Code int
Detail string
}
func (e *StatusError) Error() string {
return fmt.Sprintf("lnbits: http %d: %s", e.Code, e.Detail)
}
// detail extracts the "detail" field LNbits puts in error bodies.
func detail(data []byte) string {
var doc struct {
Detail any `json:"detail"`
}
if json.Unmarshal(data, &doc) == nil && doc.Detail != nil {
return fmt.Sprint(doc.Detail)
}
s := strings.TrimSpace(string(data))
if len(s) > 200 {
s = s[:200]
}
return s
}
func isHex(s string) bool {
if len(s) == 0 || len(s) > 128 {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
return false
}
}
return true
}
+270
View File
@@ -0,0 +1,270 @@
// Package lnbitstest is a fake LNbits server for tests. It implements the
// three endpoints the bot uses, with the request and response shapes of
// the real server, and lets a test pay invoices, replay or drop webhooks
// and take the server down.
package lnbitstest
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
)
// Key is the invoice key the fake accepts.
const Key = "fake-invoice-key-0123456789abcdef"
// Invoice is an invoice created through the fake.
type Invoice struct {
PaymentHash string
Bolt11 string
AmountSats int64
Memo string
Webhook string
Expiry int64 // seconds
Paid bool
// WebhooksSent counts webhook posts for this invoice.
WebhooksSent int
}
// Server is the fake LNbits.
type Server struct {
HTTP *httptest.Server
mu sync.Mutex
// V1 makes responses look like LNbits v1.x (invoice in "bolt11").
V1 bool
// DropWebhooks simulates webhooks that never arrive.
DropWebhooks bool
down bool
invoices map[string]*Invoice
order []string
statusCalls int
createCalls int
}
// New starts a fake server.
func New() *Server {
s := &Server{invoices: map[string]*Invoice{}}
s.HTTP = httptest.NewServer(http.HandlerFunc(s.handle))
return s
}
// URL returns the server root to use as LNBITS_URL.
func (s *Server) URL() string { return s.HTTP.URL }
// Close stops the server.
func (s *Server) Close() { s.HTTP.Close() }
// SetDown makes every request fail with 503 while down is true.
func (s *Server) SetDown(down bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.down = down
}
// Invoices returns copies of all invoices in creation order.
func (s *Server) Invoices() []Invoice {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Invoice, 0, len(s.order))
for _, h := range s.order {
out = append(out, *s.invoices[h])
}
return out
}
// Last returns the most recently created invoice.
func (s *Server) Last() (Invoice, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.order) == 0 {
return Invoice{}, false
}
return *s.invoices[s.order[len(s.order)-1]], true
}
// WaitInvoice waits until at least n invoices exist and returns the n-th.
func (s *Server) WaitInvoice(n int, timeout time.Duration) (Invoice, bool) {
deadline := time.Now().Add(timeout)
for {
s.mu.Lock()
if len(s.order) >= n {
inv := *s.invoices[s.order[n-1]]
s.mu.Unlock()
return inv, true
}
s.mu.Unlock()
if time.Now().After(deadline) {
return Invoice{}, false
}
time.Sleep(5 * time.Millisecond)
}
}
// Calls returns how many create and status requests were served.
func (s *Server) Calls() (creates, statuses int) {
s.mu.Lock()
defer s.mu.Unlock()
return s.createCalls, s.statusCalls
}
// Pay marks an invoice as paid and, unless DropWebhooks is set, posts the
// webhook the way LNbits does: once, unsigned, with the payment as body.
func (s *Server) Pay(paymentHash string) error {
s.mu.Lock()
inv, ok := s.invoices[paymentHash]
if !ok {
s.mu.Unlock()
return fmt.Errorf("lnbitstest: unknown invoice %s", paymentHash)
}
inv.Paid = true
drop := s.DropWebhooks
s.mu.Unlock()
if drop {
return nil
}
return s.SendWebhook(paymentHash)
}
// SendWebhook posts the webhook of an invoice again, which is how tests
// simulate duplicate deliveries. It works for unpaid invoices too, so a
// test can send a forged "paid" notification.
func (s *Server) SendWebhook(paymentHash string) error {
s.mu.Lock()
inv, ok := s.invoices[paymentHash]
if !ok {
s.mu.Unlock()
return fmt.Errorf("lnbitstest: unknown invoice %s", paymentHash)
}
url := inv.Webhook
body, _ := json.Marshal(map[string]any{
"payment_hash": inv.PaymentHash,
"checking_id": inv.PaymentHash,
"amount": inv.AmountSats * 1000, // LNbits reports millisats
"memo": inv.Memo,
"bolt11": inv.Bolt11,
"pending": false,
"webhook": inv.Webhook,
})
inv.WebhooksSent++
s.mu.Unlock()
if url == "" {
return nil
}
resp, err := http.Post(url, "application/json", bytes.NewReader(body))
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("lnbitstest: webhook answered %d", resp.StatusCode)
}
return nil
}
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
down := s.down
s.mu.Unlock()
if down {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"detail": "Service Unavailable"})
return
}
if r.Header.Get("X-Api-Key") != Key {
writeJSON(w, http.StatusUnauthorized, map[string]any{"detail": "Invoice (or Admin) key required."})
return
}
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/wallet":
writeJSON(w, http.StatusOK, map[string]any{"name": "test wallet", "balance": 0})
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/payments":
s.create(w, r)
case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/v1/payments/"):
s.status(w, strings.TrimPrefix(r.URL.Path, "/api/v1/payments/"))
default:
writeJSON(w, http.StatusNotFound, map[string]any{"detail": "Not Found"})
}
}
func (s *Server) create(w http.ResponseWriter, r *http.Request) {
var req struct {
Out bool `json:"out"`
Amount float64 `json:"amount"`
Unit string `json:"unit"`
Memo string `json:"memo"`
Expiry int64 `json:"expiry"`
Webhook string `json:"webhook"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "bad json"})
return
}
if req.Out {
// Paying needs the admin key, which the bot must never have.
writeJSON(w, http.StatusUnauthorized, map[string]any{"detail": "Admin key required."})
return
}
if req.Amount <= 0 {
writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "amount must be positive"})
return
}
var raw [32]byte
_, _ = rand.Read(raw[:])
hash := hex.EncodeToString(raw[:])
inv := &Invoice{
PaymentHash: hash,
Bolt11: fmt.Sprintf("lnbc%dn1fake%s", int64(req.Amount)*10, hash),
AmountSats: int64(req.Amount),
Memo: req.Memo,
Webhook: req.Webhook,
Expiry: req.Expiry,
}
s.mu.Lock()
s.createCalls++
s.invoices[hash] = inv
s.order = append(s.order, hash)
v1 := s.V1
s.mu.Unlock()
if v1 {
writeJSON(w, http.StatusCreated, map[string]any{
"payment_hash": hash, "bolt11": inv.Bolt11, "checking_id": hash,
"amount": inv.AmountSats * 1000, "status": "pending",
})
return
}
writeJSON(w, http.StatusCreated, map[string]any{
"payment_hash": hash, "payment_request": inv.Bolt11, "checking_id": hash, "lnurl_response": nil,
})
}
func (s *Server) status(w http.ResponseWriter, hash string) {
s.mu.Lock()
s.statusCalls++
inv, ok := s.invoices[hash]
var paid bool
if ok {
paid = inv.Paid
}
s.mu.Unlock()
if !ok {
writeJSON(w, http.StatusNotFound, map[string]any{"detail": "Payment does not exist."})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"paid": paid, "preimage": nil, "details": map[string]any{"payment_hash": hash, "pending": !paid},
})
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
+19
View File
@@ -0,0 +1,19 @@
package billing
import (
"encoding/json"
"io"
)
// ParseWebhook reads the payment hash from an LNbits webhook body. LNbits
// posts the whole payment object; only the hash is used, and only as a
// pointer to the purchase that is then confirmed with LNbits itself.
func ParseWebhook(body io.Reader) (paymentHash string, ok bool) {
var doc struct {
PaymentHash string `json:"payment_hash"`
}
if err := json.NewDecoder(io.LimitReader(body, 64*1024)).Decode(&doc); err != nil {
return "", false
}
return doc.PaymentHash, doc.PaymentHash != ""
}