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>
163 lines
4.5 KiB
Go
163 lines
4.5 KiB
Go
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")
|
|
)
|