Files
Media-download-telegram-bot/internal/billing/billing_test.go
T
MichilisandClaude Fable 5.2 7d4893bc3f Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration.

- Pull-based worker protocol over HTTP: claim (long poll), heartbeat,
  complete, fail, upload, source, probe. Workers need no inbound ports
- cmd/worker: standalone stateless worker with health endpoint and
  scheduled yt-dlp self-update
- Per-worker bearer tokens, stored hashed, revocable; identity always
  taken from the token; actions only on jobs the worker holds a lease for
- Tags: site_tags routes a site's jobs and lookups to workers that carry
  the required tags
- Drain, /workers, /ytdlp update, and "core worker add|revoke|list"
- Link lookups can run on remote workers (PROBE_MODE), so the core needs
  no yt-dlp and no residential address
- Postgres backend with pgx, same schema and queries; per-user advisory
  lock and job row lock where SQLite's serial writes were relied on
- The whole test suite runs on SQLite and on Postgres
- S3 storage backend with presigned worker uploads, sharing a conformance
  suite with the local backend
- Dockerfile with core, worker and faketelegram targets, docker-compose
  with optional Postgres and local Bot API server, systemd units
- deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks
  that the other one delivers the file
- Fixes found on the way: /cancel could let the next playlist item start;
  a refund note could be missing when the sweep refunded first

Docker was not available on the build machine: the compose files were
validated with "docker compose config" only. The acceptance scenario was
run with real processes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:27:11 +00:00

758 lines
25 KiB
Go

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, r.sqldb.Rebind(`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)
}
}