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") )