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
+427
View File
@@ -0,0 +1,427 @@
package db
import (
"context"
"database/sql"
"errors"
"strings"
"github.com/noderunners/dlbot/internal/ids"
)
// Money errors.
var (
ErrInsufficient = errors.New("db: insufficient balance")
ErrDuplicate = errors.New("db: duplicate entry")
)
// isUniqueViolation recognizes a unique constraint error on both engines.
func isUniqueViolation(err error) bool {
if err == nil {
return false
}
msg := err.Error()
return strings.Contains(msg, "UNIQUE constraint failed") || // sqlite
strings.Contains(msg, "duplicate key value") || strings.Contains(msg, "23505") // postgres
}
// --- wallets ---------------------------------------------------------------
const walletCols = `id, owner_type, owner_id, balance, created_at`
func scanWallet(sc interface{ Scan(...any) error }) (*Wallet, error) {
var w Wallet
if err := sc.Scan(&w.ID, &w.OwnerType, &w.OwnerID, &w.Balance, &w.CreatedAt); err != nil {
return nil, notFound(err)
}
return &w, nil
}
// GetWallet loads a wallet by ID.
func (s *Store) GetWallet(ctx context.Context, id string) (*Wallet, error) {
return scanWallet(s.row(ctx, `SELECT `+walletCols+` FROM wallets WHERE id = ?`, id))
}
// FindWallet loads the wallet of an owner, or ErrNotFound.
func (s *Store) FindWallet(ctx context.Context, ownerType string, ownerID int64) (*Wallet, error) {
return scanWallet(s.row(ctx, `SELECT `+walletCols+` FROM wallets WHERE owner_type = ? AND owner_id = ?`,
ownerType, ownerID))
}
// EnsureWallet returns the wallet of an owner, creating it when needed.
func (s *Store) EnsureWallet(ctx context.Context, ownerType string, ownerID int64) (*Wallet, error) {
w, err := s.FindWallet(ctx, ownerType, ownerID)
if err == nil || !errors.Is(err, ErrNotFound) {
return w, err
}
_, err = s.exec(ctx, `INSERT INTO wallets (id, owner_type, owner_id, balance, created_at)
VALUES (?, ?, ?, 0, ?) ON CONFLICT (owner_type, owner_id) DO NOTHING`,
ids.New(), ownerType, ownerID, NowMilli())
if err != nil {
return nil, err
}
return s.FindWallet(ctx, ownerType, ownerID)
}
// --- ledger ----------------------------------------------------------------
// AddLedger appends an entry and moves the wallet balance in the same
// transaction. It must be called inside InTx.
//
// The entry is idempotent on DedupeKey: when an entry with that key exists
// nothing changes and applied is false. A debit that the balance cannot
// cover fails with ErrInsufficient and changes nothing.
func (s *Store) AddLedger(ctx context.Context, e *LedgerEntry) (applied bool, err error) {
if !s.inTx {
return false, errors.New("db: AddLedger needs a transaction")
}
if e.Amount <= 0 {
return false, errors.New("db: ledger amount must be positive")
}
if e.DedupeKey == "" {
return false, errors.New("db: ledger entry needs a dedupe key")
}
var exists int
err = s.row(ctx, `SELECT COUNT(*) FROM ledger WHERE dedupe_key = ?`, e.DedupeKey).Scan(&exists)
if err != nil {
return false, err
}
if exists > 0 {
return false, nil
}
var n int64
switch e.Kind {
case LedgerCredit, LedgerRefund:
n, err = s.exec(ctx, `UPDATE wallets SET balance = balance + ? WHERE id = ?`, e.Amount, e.WalletID)
case LedgerDebit:
n, err = s.exec(ctx, `UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?`,
e.Amount, e.WalletID, e.Amount)
if err == nil && n == 0 {
return false, ErrInsufficient
}
default:
return false, errors.New("db: unknown ledger kind " + e.Kind)
}
if err != nil {
return false, err
}
if n == 0 {
return false, ErrNotFound
}
if err := s.row(ctx, `SELECT balance FROM wallets WHERE id = ?`, e.WalletID).Scan(&e.BalanceAfter); err != nil {
return false, err
}
if e.ID == "" {
e.ID = ids.New()
}
if e.CreatedAt == 0 {
e.CreatedAt = NowMilli()
}
_, err = s.exec(ctx, `INSERT INTO ledger (id, wallet_id, kind, amount, balance_after, reason, ref,
dedupe_key, actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt)
if isUniqueViolation(err) {
// Lost a race against the same key on another connection. The
// surrounding transaction must roll back, which undoes the balance.
return false, ErrDuplicate
}
return err == nil, err
}
// LedgerBalance recomputes a wallet balance from the ledger alone.
func (s *Store) LedgerBalance(ctx context.Context, walletID string) (int64, error) {
var sum sql.NullInt64
err := s.row(ctx, `SELECT SUM(CASE WHEN kind = 'debit' THEN -amount ELSE amount END)
FROM ledger WHERE wallet_id = ?`, walletID).Scan(&sum)
return sum.Int64, err
}
// WalletMismatch describes a wallet whose cached balance disagrees with
// its ledger.
type WalletMismatch struct {
WalletID string
Balance int64
Ledger int64
}
// VerifyWallets compares every cached balance with its ledger and returns
// the wallets that disagree. An empty result means the books are sound.
func (s *Store) VerifyWallets(ctx context.Context) ([]WalletMismatch, error) {
rows, err := s.rows(ctx, `SELECT w.id, w.balance,
COALESCE((SELECT SUM(CASE WHEN l.kind = 'debit' THEN -l.amount ELSE l.amount END)
FROM ledger l WHERE l.wallet_id = w.id), 0) AS ledger_sum
FROM wallets w`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []WalletMismatch
for rows.Next() {
var m WalletMismatch
if err := rows.Scan(&m.WalletID, &m.Balance, &m.Ledger); err != nil {
return nil, err
}
if m.Balance != m.Ledger {
out = append(out, m)
}
}
return out, rows.Err()
}
// ListLedger returns the newest entries of a wallet.
func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]*LedgerEntry, error) {
rows, err := s.rows(ctx, `SELECT id, wallet_id, kind, amount, balance_after, reason, ref, dedupe_key,
actor_id, created_at FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`,
walletID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*LedgerEntry
for rows.Next() {
var e LedgerEntry
if err := rows.Scan(&e.ID, &e.WalletID, &e.Kind, &e.Amount, &e.BalanceAfter, &e.Reason, &e.Ref,
&e.DedupeKey, &e.ActorID, &e.CreatedAt); err != nil {
return nil, err
}
out = append(out, &e)
}
return out, rows.Err()
}
// --- passes ----------------------------------------------------------------
// PassUntil returns when the wallet's pass coverage ends, or 0 when no
// pass is active at now. Passes bought while one is active are stacked
// end to end, so the latest expiry is the end of coverage.
func (s *Store) PassUntil(ctx context.Context, walletID string, now int64) (int64, error) {
var until sql.NullInt64
err := s.row(ctx, `SELECT MAX(expires_at) FROM passes WHERE wallet_id = ? AND expires_at > ?`,
walletID, now).Scan(&until)
return until.Int64, err
}
// AddPass grants a pass of the given length in milliseconds. When a pass
// is still active the new one starts where it ends.
func (s *Store) AddPass(ctx context.Context, walletID, kind string, lengthMS int64, source string, now int64) (*Pass, error) {
start := now
until, err := s.PassUntil(ctx, walletID, now)
if err != nil {
return nil, err
}
if until > start {
start = until
}
p := &Pass{
ID: ids.New(), WalletID: walletID, Kind: kind, StartsAt: start, ExpiresAt: start + lengthMS,
Source: source, CreatedAt: now,
}
_, err = s.exec(ctx, `INSERT INTO passes (id, wallet_id, kind, starts_at, expires_at, source, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`, p.ID, p.WalletID, p.Kind, p.StartsAt, p.ExpiresAt, p.Source, p.CreatedAt)
return p, err
}
// ExtendPass pushes the end of the current pass coverage out by lengthMS.
// It reports false when the wallet has no active pass.
func (s *Store) ExtendPass(ctx context.Context, walletID string, lengthMS, now int64) (bool, error) {
until, err := s.PassUntil(ctx, walletID, now)
if err != nil || until == 0 {
return false, err
}
n, err := s.exec(ctx, `UPDATE passes SET expires_at = expires_at + ? WHERE wallet_id = ? AND expires_at = ?`,
lengthMS, walletID, until)
return n > 0, err
}
// --- purchases -------------------------------------------------------------
const purchaseCols = `id, user_id, wallet_id, product, amount_sats, status, payment_hash, bolt11, chat_id,
message_id, message_is_photo, lang, request_id, profile, delivery_id, fulfilled, created_at,
expires_at, paid_at`
func scanPurchase(sc interface{ Scan(...any) error }) (*Purchase, error) {
var p Purchase
err := sc.Scan(&p.ID, &p.UserID, &p.WalletID, &p.Product, &p.AmountSats, &p.Status, &p.PaymentHash,
&p.Bolt11, &p.ChatID, &p.MessageID, &p.MessageIsPhoto, &p.Lang, &p.RequestID, &p.Profile,
&p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt)
if err != nil {
return nil, notFound(err)
}
return &p, nil
}
func scanPurchases(rows *sql.Rows, err error) ([]*Purchase, error) {
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Purchase
for rows.Next() {
p, err := scanPurchase(rows)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// InsertPurchase stores a new purchase.
func (s *Store) InsertPurchase(ctx context.Context, p *Purchase) error {
_, err := s.exec(ctx, `INSERT INTO purchases (`+purchaseCols+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
p.ID, p.UserID, p.WalletID, p.Product, p.AmountSats, p.Status, p.PaymentHash, p.Bolt11, p.ChatID,
p.MessageID, p.MessageIsPhoto, p.Lang, p.RequestID, p.Profile, p.DeliveryID, p.Fulfilled,
p.CreatedAt, p.ExpiresAt, p.PaidAt)
return err
}
// GetPurchase loads a purchase by ID.
func (s *Store) GetPurchase(ctx context.Context, id string) (*Purchase, error) {
return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE id = ?`, id))
}
// GetPurchaseByHash loads a purchase by its Lightning payment hash.
func (s *Store) GetPurchaseByHash(ctx context.Context, hash string) (*Purchase, error) {
return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE payment_hash = ?`, hash))
}
// MarkPurchasePaid moves a purchase to paid from any unpaid status and
// reports whether this call did it. This single conditional update is what
// makes settlement idempotent: however many webhooks and polls race, one
// of them wins and the rest see false.
func (s *Store) MarkPurchasePaid(ctx context.Context, id string, now int64) (bool, error) {
n, err := s.exec(ctx, `UPDATE purchases SET status = 'paid', paid_at = ?
WHERE id = ? AND status IN ('pending', 'expired', 'cancelled')`, now, id)
return n == 1, err
}
// ClosePurchase moves a pending purchase to expired or cancelled.
func (s *Store) ClosePurchase(ctx context.Context, id, status string) (bool, error) {
n, err := s.exec(ctx, `UPDATE purchases SET status = ? WHERE id = ? AND status = 'pending'`, status, id)
return n == 1, err
}
// MarkPurchaseFulfilled records that the follow-up of a paid purchase (the
// download it was for) has been handled, and reports whether this call
// was the first to do so.
func (s *Store) MarkPurchaseFulfilled(ctx context.Context, id string) (bool, error) {
n, err := s.exec(ctx, `UPDATE purchases SET fulfilled = ? WHERE id = ? AND fulfilled = ?`, true, id, false)
return n == 1, err
}
// SetPurchaseMessage records the message that shows the invoice.
func (s *Store) SetPurchaseMessage(ctx context.Context, id string, chatID, messageID int64, isPhoto bool) error {
_, err := s.exec(ctx, `UPDATE purchases SET chat_id = ?, message_id = ?, message_is_photo = ? WHERE id = ?`,
chatID, messageID, isPhoto, id)
return err
}
// UnsettledPurchases lists purchases that may still turn out to be paid:
// every pending one, plus those closed after the given time. A payment can
// arrive in the moment an invoice expires or is cancelled.
func (s *Store) UnsettledPurchases(ctx context.Context, closedAfter int64, limit int) ([]*Purchase, error) {
return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases
WHERE status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?)
ORDER BY created_at LIMIT ?`, closedAfter, limit))
}
// UnfulfilledPaidPurchases lists paid purchases whose follow-up has not
// run yet, for example because the core stopped right after settlement.
func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Purchase, error) {
return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases
WHERE status = 'paid' AND fulfilled = ? ORDER BY paid_at LIMIT ?`, false, limit))
}
// CountPaidPurchases counts the paid purchases of a user, donations aside.
func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid'
AND product <> 'donation'`, userID).Scan(&n)
return n, err
}
// CountPurchases counts purchases by status, for metrics.
func (s *Store) CountPurchases(ctx context.Context, status string) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE status = ?`, status).Scan(&n)
return n, err
}
// --- usage -----------------------------------------------------------------
// GetUsage returns what a user consumed on a day (YYYYMMDD).
func (s *Store) GetUsage(ctx context.Context, userID int64, day int) (Usage, error) {
var u Usage
err := s.row(ctx, `SELECT downloads, bytes FROM usage_daily WHERE user_id = ? AND day = ?`,
userID, day).Scan(&u.Downloads, &u.Bytes)
if errors.Is(err, sql.ErrNoRows) {
return Usage{}, nil
}
return u, err
}
// AddUsage adds to a user's counters for a day. Negative values give back.
func (s *Store) AddUsage(ctx context.Context, userID int64, day, downloads int, bytes int64) error {
_, err := s.exec(ctx, `INSERT INTO usage_daily (user_id, day, downloads, bytes) VALUES (?, ?, ?, ?)
ON CONFLICT (user_id, day) DO UPDATE SET
downloads = usage_daily.downloads + excluded.downloads,
bytes = usage_daily.bytes + excluded.bytes`, userID, day, downloads, bytes)
return err
}
// --- gift codes ------------------------------------------------------------
// InsertGiftCode stores a new code.
func (s *Store) InsertGiftCode(ctx context.Context, g *GiftCode) error {
if g.CreatedAt == 0 {
g.CreatedAt = NowMilli()
}
_, err := s.exec(ctx, `INSERT INTO gift_codes (code, kind, amount, max_uses, uses, expires_at,
created_by, created_at) VALUES (?, ?, ?, ?, 0, ?, ?, ?)`,
g.Code, g.Kind, g.Amount, g.MaxUses, g.ExpiresAt, g.CreatedBy, g.CreatedAt)
if isUniqueViolation(err) {
return ErrDuplicate
}
return err
}
// GetGiftCode loads a code.
func (s *Store) GetGiftCode(ctx context.Context, code string) (*GiftCode, error) {
var g GiftCode
err := s.row(ctx, `SELECT code, kind, amount, max_uses, uses, expires_at, created_by, created_at
FROM gift_codes WHERE code = ?`, code).Scan(&g.Code, &g.Kind, &g.Amount, &g.MaxUses, &g.Uses,
&g.ExpiresAt, &g.CreatedBy, &g.CreatedAt)
if err != nil {
return nil, notFound(err)
}
return &g, nil
}
// UseGiftCode takes one use of a code for a user. It must run in a
// transaction. used is false when the code is spent, expired or was
// already redeemed by this user.
func (s *Store) UseGiftCode(ctx context.Context, code string, userID, now int64) (used bool, err error) {
if !s.inTx {
return false, errors.New("db: UseGiftCode needs a transaction")
}
var seen int
if err := s.row(ctx, `SELECT COUNT(*) FROM gift_redemptions WHERE code = ? AND user_id = ?`,
code, userID).Scan(&seen); err != nil {
return false, err
}
if seen > 0 {
return false, nil
}
n, err := s.exec(ctx, `UPDATE gift_codes SET uses = uses + 1 WHERE code = ? AND uses < max_uses
AND (expires_at = 0 OR expires_at > ?)`, code, now)
if err != nil || n == 0 {
return false, err
}
_, err = s.exec(ctx, `INSERT INTO gift_redemptions (code, user_id, created_at) VALUES (?, ?, ?)`,
code, userID, now)
if isUniqueViolation(err) {
return false, ErrDuplicate
}
return err == nil, err
}