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