diff --git a/.env.example b/.env.example index 0f65f12..7f75f25 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,11 @@ TELEGRAM_UPDATE_WORKERS=8 # Telegram user IDs allowed to use owner commands, comma separated. OWNER_IDS= +# Public HTTPS base URL of this server, without a trailing slash. Used for +# payment webhooks, "open in wallet" links and the Mini App. Payments work +# without it (invoices are then settled by polling only). +PUBLIC_URL= + # --- HTTP ------------------------------------------------------------------- # Listen address of the health endpoint and the webhook. HTTP_LISTEN=:8080 @@ -65,6 +70,53 @@ QUEUE_MAX_ATTEMPTS=2 FREE_MAX_SIZE_MB=50 FREE_MAX_DURATION=10m FREE_ACTIVE_JOBS=1 +# Per UTC day. 0 means no cap. +FREE_DAILY_DOWNLOADS=5 +FREE_DAILY_MB=250 + +# --- Paid limits (passes, credits, one-off payments) ------------------------ +# Sizes above TELEGRAM_MAX_UPLOAD_MB need a local Bot API server. +PAID_MAX_SIZE_MB=2000 +PAID_MAX_DURATION=3h +PAID_ACTIVE_JOBS=3 +PAID_DAILY_DOWNLOADS=100 +# The daily volume cap applies to paying users too. +PAID_DAILY_MB=20000 + +# --- Payments (LNbits) ------------------------------------------------------ +# Leave LNBITS_URL and LNBITS_INVOICE_KEY empty to run without payments. +LNBITS_URL= +# The wallet's INVOICE key (read only). Never give the bot the admin key. +LNBITS_INVOICE_KEY= +# Random string. It becomes part of the webhook path that LNbits calls: +# /lnbits/webhook/ +LNBITS_WEBHOOK_SECRET= +# How often unsettled invoices are checked, as a fallback for lost webhooks. +LNBITS_POLL_INTERVAL=5s +# How long an invoice can be paid. +INVOICE_EXPIRY=10m + +# --- Prices in sats --------------------------------------------------------- +PRICE_PASS_DAY=700 +PRICE_PASS_WEEK=3000 +PRICE_PASS_MONTH=9000 +# Cost of one download when credits pay. +PRICE_CREDIT_DOWNLOAD=50 +# "Pay for this file only": base plus a step per started 100 MB. +PRICE_ONE_OFF_BASE=100 +PRICE_ONE_OFF_PER_100MB=50 +# Moving one waiting free job to the priority lane. +PRICE_SKIP_QUEUE=50 +# Top-up and tip amounts offered as buttons. +CREDIT_PACKS=1000,5000,20000 +DONATION_AMOUNTS=500,2100,10000 +# Credited to the inviter on an invited user's first purchase. 0 turns it off. +REFERRAL_REWARD=200 + +# --- Rate limits ------------------------------------------------------------ +# Links per minute. 0 means no limit. +RATE_USER_PER_MINUTE=10 +RATE_GROUP_PER_MINUTE=30 # --- Logging ---------------------------------------------------------------- # debug, info, warn or error. diff --git a/README.md b/README.md index dacc793..c47337c 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ A Telegram bot that downloads video and audio from links, in private chats and in groups. Written in Go on top of yt-dlp. -> Status: Phase 1 of 8 (core bot). Payments, the cache, remote workers, +> Status: Phase 2 of 8 (core bot and payments). The cache, remote workers, > group settings, the Mini App and more languages follow. See > [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md) for the decisions made so far. @@ -16,7 +16,14 @@ and in groups. Written in Go on top of yt-dlp. - One status message, edited live: queued with position and wait, downloading with a progress bar, processing, sending, done. - A database backed queue with leases, one automatic retry and cancel. -- Free tier limits: size, duration, one active job, bounded queue. +- Free tier limits: size, duration, daily quota, one active job. +- Payments in sats over Lightning (LNbits): day, week and month passes, + credits, "pay for this file only" and "skip the queue". Paid downloads + get higher limits and a priority lane, with one slot always kept for free + users. +- Money is safe: append-only ledger, idempotent settlement, reconciliation + at startup, automatic refunds for failed downloads. +- Gift codes, referral rewards and tips. - Friendly, translated error messages. Raw tool output stays in the logs. ## Quick start @@ -58,6 +65,29 @@ curl localhost:8080/healthz | `/info ` | Show formats and sizes without downloading | | `/queue` | Your downloads in progress | | `/cancel` | Cancel your downloads | +| `/account` | Your pass, balance and usage today (private chat) | +| `/limits` | The limits that apply to you right now | +| `/buy` | Buy a pass or credits (private chat) | +| `/credits` | Balance and top up (private chat) | +| `/redeem ` | Use a gift code (private chat) | +| `/referral` | Your invite link and how many joined (private chat) | +| `/donate` | Send a tip (private chat) | + +### Turning on payments + +Payments are off until LNbits is configured. You need an LNbits wallet and +its **invoice key** (not the admin key: the bot never needs to spend). + +```sh +LNBITS_URL=https://your-lnbits.example.com +LNBITS_INVOICE_KEY=... +# Optional but recommended, for instant settlement and the wallet button: +PUBLIC_URL=https://bot.example.com +LNBITS_WEBHOOK_SECRET=$(openssl rand -hex 16) +``` + +Without `PUBLIC_URL` payments still work: invoices are settled by polling +LNbits every few seconds. ## Configuration @@ -75,6 +105,9 @@ The settings you are most likely to touch: | `FREE_MAX_SIZE_MB` | `50` | Size cap per download | | `FREE_MAX_DURATION` | `10m` | Duration cap per download | | `FREE_ACTIVE_JOBS` | `1` | Active downloads per user | +| `FREE_DAILY_DOWNLOADS` | `5` | Downloads per day on the free tier | +| `PRICE_PASS_DAY` / `_WEEK` / `_MONTH` | `700` / `3000` / `9000` | Pass prices in sats | +| `PRICE_CREDIT_DOWNLOAD` | `50` | Cost of a download paid with credits | | `QUEUE_FREE_MAX_LEN` | `20` | Most queued free jobs | | `DB_DSN` | `data/dlbot.db` | SQLite file | | `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` | @@ -102,6 +135,8 @@ yt-dlp. cmd/core the bot gateway (and, for now, the embedded worker) internal/bot Telegram handlers, cards, status, delivery internal/service download rules shared by all front ends +internal/entitle who pays and which limits apply (pure function) +internal/billing wallets, ledger, passes, invoices, LNbits client internal/sched the job queue internal/worker the download worker internal/ytdlp yt-dlp and ffprobe wrapper diff --git a/config.example.toml b/config.example.toml index c295b84..e9e44c0 100644 --- a/config.example.toml +++ b/config.example.toml @@ -6,6 +6,9 @@ # Telegram user IDs allowed to use owner commands. owners = [] +# Public HTTPS base URL of this server, without a trailing slash. +public_url = "" + [telegram] api_url = "https://api.telegram.org" mode = "polling" # polling or webhook @@ -44,6 +47,40 @@ max_attempts = 2 max_size_mb = 50 max_duration = "10m" active_jobs = 1 +daily_downloads = 5 # per UTC day, 0 for no cap +daily_mb = 250 + +# Passes, credits and one-off payments all run under these limits. +[limits.paid] +max_size_mb = 2000 # above telegram.max_upload_mb needs a local Bot API server +max_duration = "3h" +active_jobs = 3 +daily_downloads = 100 +daily_mb = 20000 # applies to paying users too + +# Payments. Set the invoice key through LNBITS_INVOICE_KEY in the +# environment, not here. +[lnbits] +url = "" +poll_interval = "5s" +invoice_expiry = "10m" + +# All prices are in sats. +[prices] +pass_day = 700 +pass_week = 3000 +pass_month = 9000 +credit_per_download = 50 +one_off_base = 100 +one_off_per_100mb = 50 +skip_queue = 50 +credit_packs = [1000, 5000, 20000] +donation_amounts = [500, 2100, 10000] +referral_reward = 200 + +[rate] +user_per_minute = 10 +group_per_minute = 30 [log] level = "info" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fcc7611..b248edb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -34,6 +34,9 @@ phase; sections for later phases say so. | `internal/workerproto` | Messages between core and worker. | | `internal/ytdlp` | yt-dlp and ffprobe behind a `Runner` interface, error classes. | | `internal/media` | Format profiles: best, 1080, 720, 480, mp3, m4a, subs:lang, thumb. | +| `internal/entitle` | Pure entitlement resolver: what pays, which limits apply. | +| `internal/billing` | Wallets, ledger, passes, invoices, settlement, gift codes. | +| `internal/billing/lnbits` | LNbits HTTP client. | | `internal/links` | URL extraction, validation, redaction. | | `internal/storage` | `Storage` interface and the local disk backend. | | `internal/db` | Schema migrations and queries for SQLite and Postgres. | @@ -48,7 +51,8 @@ Dependencies point one way: `bot` uses `service`, `service` uses `sched`, ## Data model -Four tables carry Phase 1. +Four tables carry downloads. Money adds `wallets`, `ledger`, `passes`, +`purchases`, `usage_daily` and the gift code tables, described under Money. - **users**: one row per Telegram user, with detected and chosen language. - **requests**: one row per link a user sent. It holds the metadata shown on @@ -130,6 +134,92 @@ same size and duration caps on the real file, because metadata is often missing. When the cache arrives, a cache hit goes through `service.Start` like everything else: it only skips the worker. +## Money + +### Who pays: the entitlement resolver + +`internal/entitle.Resolve` is a pure function. It gets the requester's +wallet state, the group's (when there is one), the configured tiers and the +price, and returns what pays, what to charge, the limits and the queue +lane. It has no database and no clock, so its rules are a table of test +cases plus a check of invariants over every combination of inputs. + +The order is: a one-off payment for this file, own pass, group pass, group +credits (if the group's spending rule allows this requester), own credits, +free. The wallet always belongs to the person who pressed the button. + +`service.Start` is the only caller that acts on a decision. In one database +transaction it debits the wallet (when credits pay), counts the download +against the daily quota and inserts the job. Either all three happen or +none. + +### Wallets and the ledger + +A wallet belongs to a user or a group. Its history is the `ledger` table: +rows are inserted and never changed. Each row has a kind (credit, debit, +refund), a positive amount, the balance after it and a `dedupe_key` with a +unique index. `wallets.balance` is a cached sum that is updated in the same +transaction as each row. `VerifyWallets` recomputes every balance from the +ledger and reports any wallet that disagrees. + +The dedupe key is what makes money operations safe to repeat. Crediting a +purchase uses `purchase:`, charging a download `download:`, +refunding it `refund:`. Running any of them twice changes nothing. + +### Invoices + +``` + /buy or an over-limit offer + | + v + billing.CreatePurchase ---- POST /api/v1/payments ----> LNbits + | | + purchases row (pending, payment_hash) | user pays + | v + | <--- POST /lnbits/webhook/ --- (once, unsigned) + | <--- poll GET /api/v1/payments/ (every few seconds) + v + billing.checkOne: ask LNbits "is it paid?" + | + v + billing.Settle: UPDATE purchases SET status='paid' WHERE status<>'paid' + | (one winner, whatever races) + v + credit ledger or add pass, referral reward, then a "paid" event + | + v + bot: edit the invoice message, start the download it was for +``` + +Three properties matter: + +- **Idempotent.** Settlement is one conditional UPDATE inside a + transaction. Webhooks, polls and the "Check payment" button can all fire + for the same invoice; exactly one wins. +- **Not trusting.** LNbits does not sign webhooks. The body is only used to + find the purchase; the payment is confirmed with LNbits before anything + is credited. +- **Not forgetting.** LNbits sends a webhook once. Pending invoices are + polled, all unsettled invoices are checked at startup, and a paid + purchase whose follow-up did not run (the core stopped in between) is + picked up by the bot's reconcile loop. + +### Lanes and the reserved slot + +A job's lane is decided when it is queued and stored with it. Workers claim +paid jobs first. One slot of the fleet is reserved for the free lane: when +a claim would take the last idle slot and no free job is running, a waiting +free job is served first. The reservation is free when nobody waits in the +free lane. + +### Refunds + +`service.Release` gives back what an undelivered download took: the sats +and the quota slot. It is guarded by a `released` flag on the delivery and +by the ledger dedupe key, so every failure path can call it without +coordination. The reconcile loop also sweeps for deliveries that ended +without a file and were never released. + ## Internationalization Handlers never contain user-facing text. They call `i18n.Bundle` with a @@ -155,3 +245,8 @@ all output. URLs are redacted before they are logged. `tg/fakeserver`, an HTTP server that speaks enough of the Bot API to push updates in and record every call, including multipart uploads. - One opt-in test runs the real yt-dlp against a public test file. +- Payments are tested against `billing/lnbitstest`, a fake LNbits that + speaks the real request and response shapes and lets a test pay invoices, + replay or drop webhooks and take the server down. +- The end-to-end harness fails a test when the core logs a missing + translation key or a recovered panic. diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index b889ddc..ab81368 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -140,3 +140,125 @@ yt-dlp behaviors that shaped the wrapper: API URLs contain the token. - No age verification or KYC flow exists or is planned. Content a site gates behind a login is reported as "needs a login". + +## Phase 2 + +### Verified LNbits facts + +Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current). + +- `POST /api/v1/payments` with the invoice key creates an invoice. Fields + used: `out=false`, `amount`, `unit="sat"`, `memo`, `expiry`, `webhook`. + v0.12 answers with `payment_request`, v1.x with the payment object and + `bolt11`. The client reads either. +- `GET /api/v1/payments/{payment_hash}` answers `{"paid": bool, ...}` in + both versions, and 404 for an unknown hash. +- The webhook is a single `POST` of the payment as JSON. **It is not signed + and it is not retried.** This shaped the design: a webhook is treated as a + hint, the payment is confirmed with LNbits before anything is credited, + and polling is a required fallback, not an optimization. +- Only the invoice key is needed. The bot never holds a key that can spend. + +### Entitlement + +- **Order** is exactly as specified: own pass, group pass, group credits, + own credits, free. A one-off payment for the file sits in front of all of + them, since it was bought for exactly that download. +- **Credits are used before the free tier.** A user with enough credits pays + per download even for a small file that the free tier would have allowed. + This follows the specified order literally. What they get for it is the + paid limits and the priority lane. +- **Credits cost a flat price per download** (`PRICE_CREDIT_DOWNLOAD`, 50 + sats), whatever the size. "Per extra" spending is "Skip the queue". +- **All paid sources share one tier** (`limits.paid`) and one lane. Pass + holders, credit payers and one-off payers queue first come first served + among themselves. +- **Group wallets** are in the resolver and its tests now. They get their + data in Phase 5; until then every request resolves as in a private chat. + +### Limits + +- **A day** is a UTC calendar day, for both the download quota and the + volume cap. +- The **daily download quota** counts when a job is queued and is given back + when the download fails or is cancelled. The **daily volume** counts bytes + actually delivered. A user can therefore overshoot the volume cap by one + file, since the size is only known afterwards. +- Quota and volume are tracked per requester, also when a group pays. +- **Rate limit:** 10 links per minute per user and 30 per group, in memory. + A restart forgets it. + +### Payments + +- **Invoices are personal** and only ever appear in the private chat. In a + group, a refused download shows a "Buy for me" deep link instead. +- **"Open in wallet"** needs `PUBLIC_URL`. Telegram accepts only http and + https in URL buttons, so the button opens a small page of the core that + forwards to the `lightning:` link. Without `PUBLIC_URL` the button is + left out and the invoice is still scannable and copyable. +- **Copyable BOLT11:** the invoice is in a code block in the caption, where + one tap copies it. Telegram's dedicated copy button is limited to 256 + characters, which is shorter than most invoices. +- **No job exists before payment.** An over-limit download is queued only + when its invoice settles, so "unpaid jobs are cancelled" holds by + construction: there is nothing to cancel. +- **A payment that arrives late is still honored.** If an invoice is paid + after it expired or was cancelled, it is credited when detected (invoices + closed within the last hour are polled; all of the last 7 days are checked + at startup). +- **An invoice does not expire while LNbits is unreachable.** It could have + been paid, and telling a payer that a paid invoice expired is worse than + leaving one open a little longer. +- **A payment whose purpose is gone becomes credits.** If a one-off or + skip-the-queue payment settles after the download finished or the card + expired, the same amount is credited to the payer's balance and they are + told. Lightning payments cannot be sent back. +- **One-off price** is `base + step * started 100 MB`, with an unknown size + priced as 200 MB. + +### Refunds + +- A download is retried once automatically. When it then fails, is + cancelled, or cannot be sent to Telegram, what it cost is given back: + credits return to the wallet they came from (also group wallets), a + one-off payment becomes credits on the payer's wallet, and the slot in the + daily quota is freed. +- **A pass is not extended automatically** after a failed download. Under a + pass a download costs nothing, so there is nothing to refund except the + quota slot, which is freed. Extending a pass exists as an operation + (`ExtendPass`) for the owner's `/refund` command. +- "Skip the queue" is not refunded when the promoted download later fails. + The priority was delivered. + +### Skip the queue + +- The button appears on the **queued status** of a job in the free lane, + not on the link card. On the card there is no job yet to move. It costs + `PRICE_SKIP_QUEUE`, paid from credits when the balance covers it and by + invoice otherwise. + +### Reserved free slot + +- The reservation applies when the fleet has at least two slots. With a + single slot, reserving it would lock paying users out, so paid simply goes + first. +- Fleet capacity is the sum of the capacities of workers that claimed in + the last 90 seconds. It is kept in memory and rebuilt within seconds of a + restart. + +### Gift codes, Cashu, referrals + +- Gift codes are fully implemented: credits or a pass, a maximum number of + uses, an optional expiry, one use per user. +- **Cashu is behind the `billing.Cashu` interface and not implemented.** + `/redeem` recognizes a Cashu token and answers that tokens are not + accepted. Redeeming means melting the token at its mint into a Lightning + payment to our own invoice, with fee reserve and input fee handling and + V4 tokens in CBOR. That is not "straightforward" enough to ship without a + real mint to test against. +- **Referral:** the link is `t.me/?start=ref_`. Only a user + who is new to the bot can be referred, once, and not by themselves. The + reward (200 sats) is credited on their first paid purchase. Donations do + not count as a purchase. +- **Telegram Stars** as a second payment method is not built ("optional + later" in the brief). diff --git a/go.mod b/go.mod index bee0ad2..dfc9e3b 100644 --- a/go.mod +++ b/go.mod @@ -27,6 +27,7 @@ require ( github.com/ncruces/go-strftime v1.1.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/sethvargo/go-retry v0.5.0 // indirect + github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.78.0 // indirect diff --git a/go.sum b/go.sum index b4b4784..c342f82 100644 --- a/go.sum +++ b/go.sum @@ -44,6 +44,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= diff --git a/internal/api/payments.go b/internal/api/payments.go new file mode 100644 index 0000000..4f3964a --- /dev/null +++ b/internal/api/payments.go @@ -0,0 +1,87 @@ +package api + +import ( + "crypto/subtle" + "html" + "net/http" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" +) + +// Payments serves the two payment routes of the core: +// +// POST /lnbits/webhook/{secret} payment notifications from LNbits +// GET /pay/{purchase} "open in wallet" page for an invoice +type Payments struct { + Billing *billing.Billing + Store *db.Store + I18n *i18n.Bundle + // Secret is the random path segment that LNbits was given. An empty + // secret disables the webhook route. + Secret string +} + +// Register adds the routes to the server. +func (s *Server) RegisterPayments(p Payments) { + if p.Secret != "" { + s.mux.HandleFunc("POST /lnbits/webhook/{secret}", p.webhook) + } + s.mux.HandleFunc("GET /pay/{purchase}", p.payPage) +} + +// webhook accepts a notification. LNbits does not sign its webhooks, so +// the secret in the path only keeps strangers out; the payment itself is +// confirmed with LNbits by the billing service before anything is +// credited. The answer is always 200 for a well-formed request: LNbits +// does not retry, and polling covers anything that fails here. +func (p Payments) webhook(w http.ResponseWriter, r *http.Request) { + if subtle.ConstantTimeCompare([]byte(r.PathValue("secret")), []byte(p.Secret)) != 1 { + http.NotFound(w, r) + return + } + hash, ok := billing.ParseWebhook(r.Body) + if !ok { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + // Errors are logged by the billing service and retried by its poller. + _ = p.Billing.HandleWebhook(r.Context(), hash) + w.WriteHeader(http.StatusOK) +} + +// payPage forwards a browser to the lightning: link of an invoice. +// Telegram URL buttons only accept http and https, which is why this small +// hop exists. The purchase ID in the path is unguessable, and the page +// shows nothing but the invoice, which is meant to be shared with a wallet. +func (p Payments) payPage(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("X-Content-Type-Options", "nosniff") + pur, err := p.Store.GetPurchase(r.Context(), r.PathValue("purchase")) + lang := i18n.Default + if err == nil { + lang = pur.Lang + } + t := func(id string) string { return html.EscapeString(p.I18n.T(lang, id, nil)) } + page := func(code int, body string) { + w.WriteHeader(code) + _, _ = w.Write([]byte(`` + + `` + t("pay.title") + + `` + body + ``)) + } + if err != nil || pur.Status != db.PurchasePending { + page(http.StatusGone, `

`+t("pay.gone")+`

`) + return + } + link := "lightning:" + pur.Bolt11 + esc := html.EscapeString(link) + page(http.StatusOK, `

`+t("pay.hint")+ + `

`+t("pay.open")+``+html.EscapeString(pur.Bolt11)+`
`) +} diff --git a/internal/app/app.go b/internal/app/app.go index 3917fdc..0c49f6b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -14,6 +14,8 @@ import ( "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/api" + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/billing/lnbits" "github.com/noderunners/dlbot/internal/bot" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" @@ -45,6 +47,7 @@ type App struct { Store *db.Store Storage storage.Storage Sched *sched.Scheduler + Billing *billing.Billing Service *service.Service Bot *bot.Bot HTTP *api.Server @@ -105,7 +108,10 @@ func Redactor(secrets ...string) func(groups []string, a slog.Attr) slog.Attr { // Secrets lists the configured values that must never appear in logs. func Secrets(cfg config.Config) []string { - return []string{cfg.Telegram.Token, cfg.Telegram.WebhookSecret} + return []string{ + cfg.Telegram.Token, cfg.Telegram.WebhookSecret, + cfg.LNbits.InvoiceKey, cfg.LNbits.WebhookSecret, + } } // New opens the database and storage and builds every component. Nothing @@ -160,7 +166,12 @@ func New(ctx context.Context, opts Options) (*App, error) { FreeMaxLen: cfg.Queue.FreeMaxLen, MaxAttempts: cfg.Queue.MaxAttempts, }, log) - a.Service = service.New(cfg, a.Store, a.Sched, a.runner, log) + var ln billing.Lightning + if cfg.LNbits.Enabled() { + ln = lnbits.New(cfg.LNbits.URL, cfg.LNbits.InvoiceKey) + } + a.Billing = billing.New(a.Store, ln, cfg, log) + a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.runner, log) if a.tgBot, err = tg.NewBot(cfg.Telegram.Token, cfg.Telegram.APIURL); err != nil { return fail(fmt.Errorf("app: telegram client: %w", err)) @@ -171,6 +182,7 @@ func New(ctx context.Context, opts Options) (*App, error) { Store: a.Store, Sched: a.Sched, Service: a.Service, + Billing: a.Billing, Storage: a.Storage, I18n: tr, Log: log, @@ -184,6 +196,9 @@ func New(ctx context.Context, opts Options) (*App, error) { } a.HTTP = api.New(cfg.HTTP.Listen, func(ctx context.Context) error { return a.DB.SQL.PingContext(ctx) }, log) + a.HTTP.RegisterPayments(api.Payments{ + Billing: a.Billing, Store: a.Store, I18n: tr, Secret: cfg.LNbits.WebhookSecret, + }) if cfg.Worker.Embedded { a.worker = worker.New(worker.Config{ @@ -220,7 +235,8 @@ func (a *App) Run(ctx context.Context) error { close(a.ready) a.log.Info("core started", "bot", a.Bot.Username(), "mode", a.cfg.Telegram.Mode, "http", a.HTTP.Addr(), "db", a.cfg.Database.Driver, "storage", a.cfg.Storage.Backend, - "embedded_worker", a.cfg.Worker.Embedded) + "embedded_worker", a.cfg.Worker.Embedded, "payments", a.Billing.Enabled(), + "payment_webhook", a.Billing.WebhookURL() != "") var wg sync.WaitGroup run := func(fn func()) { @@ -240,6 +256,7 @@ func (a *App) Run(ctx context.Context) error { } }) run(func() { a.Sched.Run(ctx) }) + run(func() { a.Billing.Run(ctx) }) if a.worker != nil { run(func() { a.worker.Run(ctx) }) } diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 7ef98fb..2fe9519 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -81,9 +81,15 @@ func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config) func (h *harness) boot() { h.t.Helper() ctx, cancel := context.WithCancel(context.Background()) + // DLBOT_TEST_LOG=1 prints the core's log, which helps with a failing test. + var logOut io.Writer = io.Discard + if os.Getenv("DLBOT_TEST_LOG") != "" { + logOut = os.Stderr + } + base := slog.NewTextHandler(logOut, &slog.HandlerOptions{Level: slog.LevelDebug}) a, err := app.New(ctx, app.Options{ Config: h.cfg, - Log: slog.New(slog.NewTextHandler(io.Discard, nil)), + Log: slog.New(&guardHandler{Handler: base, t: h.t}), Runner: h.runner, Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) }, }) @@ -102,6 +108,35 @@ func (h *harness) boot() { } } +// guardHandler fails the test when the core logs something that is always +// a bug: a message ID that is missing from the catalog, or a panic. +type guardHandler struct { + slog.Handler + t *testing.T +} + +func (g *guardHandler) Handle(ctx context.Context, r slog.Record) error { + if strings.HasPrefix(r.Message, "i18n: missing message") || r.Message == "panic recovered" { + var sb strings.Builder + r.Attrs(func(a slog.Attr) bool { + if a.Key != "stack" { + fmt.Fprintf(&sb, " %s=%v", a.Key, a.Value) + } + return true + }) + g.t.Errorf("core logged a bug: %s%s", r.Message, sb.String()) + } + return g.Handler.Handle(ctx, r) +} + +func (g *guardHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &guardHandler{Handler: g.Handler.WithAttrs(attrs), t: g.t} +} + +func (g *guardHandler) WithGroup(name string) slog.Handler { + return &guardHandler{Handler: g.Handler.WithGroup(name), t: g.t} +} + func (h *harness) stop() { if h.cancel == nil { return @@ -739,7 +774,7 @@ func TestCommandMenuIsRegistered(t *testing.T) { if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil { t.Fatal(err) } - if len(cmds) != 7 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" { + if len(cmds) != 9 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" { t.Fatalf("commands = %+v", cmds) } for _, c := range cmds { diff --git a/internal/app/money_test.go b/internal/app/money_test.go new file mode 100644 index 0000000..00a435d --- /dev/null +++ b/internal/app/money_test.go @@ -0,0 +1,1113 @@ +package app_test + +import ( + "bytes" + "context" + "fmt" + "io" + "net" + "net/http" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/billing/lnbitstest" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +const bigLink = "https://example.com/big" + +// bigInfo is an 80 MB, one minute video: over the free size cap, well +// inside the paid one. +func bigInfo() *ytdlp.Info { + return &ytdlp.Info{ + Type: "video", ID: "big1", Title: "Big Video", Extractor: "fake", Duration: 60, + Formats: []ytdlp.Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 1080, Filesize: 80 << 20}}, + } +} + +// moneyHarness adds a fake LNbits to the harness. +type moneyHarness struct { + *harness + ln *lnbitstest.Server +} + +func freePort(t *testing.T) string { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + return l.Addr().String() +} + +func startMoney(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *moneyHarness { + t.Helper() + ln := lnbitstest.New() + t.Cleanup(ln.Close) + if fake == nil { + fake = &ytdlptest.Fake{} + } + if fake.Infos == nil { + fake.Infos = map[string]*ytdlp.Info{} + } + fake.Infos[bigLink] = bigInfo() + addr := freePort(t) + h := start(t, fake, func(c *config.Config) { + c.HTTP.Listen = addr + c.PublicURL = "http://" + addr + c.LNbits.URL = ln.URL() + c.LNbits.InvoiceKey = lnbitstest.Key + c.LNbits.WebhookSecret = "test-hook-secret" + // Polling is slow on purpose: tests that pass quickly prove the + // webhook path. Tests of the polling path shorten it. + c.LNbits.PollInterval = config.Duration(time.Hour) + c.Telegram.MaxUploadMB = 2000 + if mut != nil { + mut(c) + } + }) + return &moneyHarness{harness: h, ln: ln} +} + +func (h *moneyHarness) wallet(user int64) *db.Wallet { + h.t.Helper() + w, err := h.app.Billing.Wallet(context.Background(), db.OwnerUser, user) + if err != nil { + h.t.Fatal(err) + } + return w +} + +func (h *moneyHarness) balance(user int64) int64 { return h.wallet(user).Balance } + +func (h *moneyHarness) grant(user, sats int64) { + h.t.Helper() + if _, err := h.app.Billing.Credit(context.Background(), h.wallet(user).ID, sats, "test", "", fmt.Sprintf("test:%d:%d", user, time.Now().UnixNano()), 0); err != nil { + h.t.Fatal(err) + } +} + +// invoice waits for the n-th invoice at LNbits and for the bot message +// that shows it. +func (h *moneyHarness) invoice(after, n int) (lnbitstest.Invoice, fakeserver.Call) { + h.t.Helper() + inv, ok := h.ln.WaitInvoice(n, 10*time.Second) + if !ok { + h.t.Fatalf("invoice %d was not created", n) + } + msg := h.wait(after, "sendPhoto|sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), inv.Bolt11) + }) + return inv, msg +} + +func (h *moneyHarness) pay(inv lnbitstest.Invoice) { + h.t.Helper() + if err := h.ln.Pay(inv.PaymentHash); err != nil { + h.t.Fatalf("pay: %v", err) + } +} + +func (h *moneyHarness) booksBalance() { + h.t.Helper() + bad, err := h.app.Store.VerifyWallets(context.Background()) + if err != nil || len(bad) > 0 { + h.t.Fatalf("wallet balances disagree with the ledger: %+v, %v", bad, err) + } +} + +func (h *moneyHarness) deliveriesOf(user int64, status string) []*db.Delivery { + h.t.Helper() + rows, err := h.app.DB.SQL.Query(`SELECT id FROM deliveries WHERE user_id = ? AND status = ? ORDER BY id`, user, status) + if err != nil { + h.t.Fatal(err) + } + var idList []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + h.t.Fatal(err) + } + idList = append(idList, id) + } + rows.Close() + var out []*db.Delivery + for _, id := range idList { + d, err := h.app.Store.GetDelivery(context.Background(), id) + if err != nil { + h.t.Fatal(err) + } + out = append(out, d) + } + return out +} + +// waitInvoiceSaved waits until the bot recorded which message shows the +// invoice, which happens just after Telegram accepted that message. +func (h *moneyHarness) waitInvoiceSaved(inv lnbitstest.Invoice) *db.Purchase { + h.t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + p, err := h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash) + if err == nil && p.MessageID != 0 { + return p + } + if time.Now().After(deadline) { + h.t.Fatalf("the invoice message was never recorded: %+v, %v", p, err) + } + time.Sleep(5 * time.Millisecond) + } +} + +// waitSent waits until the user has n delivered files and returns them. +func (h *moneyHarness) waitSent(user int64, n int) []*db.Delivery { + h.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + d := h.deliveriesOf(user, db.DeliverySent) + if len(d) == n { + return d + } + if time.Now().After(deadline) { + h.t.Fatalf("%d sent deliveries for user %d, want %d", len(d), user, n) + } + time.Sleep(20 * time.Millisecond) + } +} + +func labels(c fakeserver.Call) string { + var out []string + for _, b := range c.Buttons() { + out = append(out, b.Text) + } + return strings.Join(out, " | ") +} + +// --- buying ---------------------------------------------------------------- + +func TestBuyDayPassSettledByWebhook(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/buy") + menu := h.wait(seq, "sendMessage", textHas("Passes and credits")) + want := "Day pass · 700 sats | Week pass · 3,000 sats | Month pass · 9,000 sats | 1,000 sats | 5,000 sats | 20,000 sats" + if labels(menu) != want { + t.Fatalf("buy buttons = %q\nwant %q", labels(menu), want) + } + if !strings.Contains(menu.Text(), "50 sats each") || !strings.Contains(menu.Text(), "1.95 GB") { + t.Fatalf("buy text = %q", menu.Text()) + } + + seq = h.press(alice, alice, menu, "by:pass_day") + inv, msg := h.invoice(seq, 1) + if inv.AmountSats != 700 || inv.Expiry != 600 || inv.Memo != "The Noderunners Download Bot: Day pass" || + !strings.HasSuffix(inv.Webhook, "/lnbits/webhook/test-hook-secret") { + t.Fatalf("invoice at LNbits = %+v", inv) + } + if msg.Method != "sendPhoto" || msg.Files["photo"].Name != "invoice.png" || msg.Files["photo"].Size < 500 { + t.Fatalf("the invoice must be a QR photo: %s %+v", msg.Method, msg.Files) + } + if !strings.Contains(msg.Text(), ""+inv.Bolt11+"") || !strings.Contains(msg.Text(), "Day pass") || + !strings.Contains(msg.Text(), "700 sats") || !strings.Contains(msg.Text(), "10 minutes") { + t.Fatalf("invoice caption = %q", msg.Text()) + } + btns := msg.Buttons() + if len(btns) != 3 || btns[0].Text != "Open in wallet" || !strings.Contains(btns[0].URL, "/pay/") || + !strings.HasPrefix(btns[1].Data, "pc:") || !strings.HasPrefix(btns[2].Data, "px:") { + t.Fatalf("invoice buttons = %+v", btns) + } + // Telegram rejects lightning: links in buttons, so it must be http(s). + if !strings.HasPrefix(btns[0].URL, "http") { + t.Fatalf("open-in-wallet URL = %q", btns[0].URL) + } + + h.pay(inv) // LNbits calls the webhook + paid := h.wait(seq, "editMessageCaption", textHas("Paid.")) + if paid.MessageID != msg.MessageID || len(paid.Buttons()) != 0 || + !strings.Contains(paid.Text(), "Your pass is active until") { + t.Fatalf("paid message = %q buttons=%v", paid.Text(), paid.Buttons()) + } + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/account") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "Pass: active until") && strings.Contains(c.Text(), "Downloads: 0 of 100") + }) + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/limits") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "(Your pass)") && strings.Contains(c.Text(), "Length per download: 3 hours") + }) + + // With the pass the 80 MB file goes through, in the paid lane. + card := h.card(alice, alice, bigLink) + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "sendVideo", nil) + sent := h.waitSent(alice, 1) + if sent[0].Source != "own_pass" || sent[0].ChargeSats != 0 { + t.Fatalf("delivery = %+v", sent) + } + job, _ := h.app.Store.GetJob(context.Background(), sent[0].JobID) + if job.Lane != db.LanePaid || job.MaxSize != 2000<<20 { + t.Fatalf("job lane=%s max_size=%d", job.Lane, job.MaxSize) + } + h.booksBalance() +} + +func TestCreditsTopUpAndPayPerDownload(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance: 0 sats")) + seq = h.press(alice, alice, menu, "by:credits:1000") + inv, _ := h.invoice(seq, 1) + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("Your balance is now 1,000 sats.")) + + card := h.card(alice, alice, bigLink) + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "sendVideo", nil) + h.wait(seq, edits, textHas("Done")) + if got := h.balance(alice); got != 950 { + t.Fatalf("balance = %d, want 950 after one 50 sat download", got) + } + sent := h.waitSent(alice, 1) + if sent[0].Source != "own_credits" || sent[0].ChargeSats != 50 || sent[0].Released { + t.Fatalf("delivery = %+v", sent[0]) + } + usage, _ := h.app.Service.Usage(context.Background(), alice) + if usage.Downloads != 1 || usage.Bytes != 1024 { + t.Fatalf("usage = %+v", usage) + } + h.booksBalance() +} + +// --- acceptance: refunds --------------------------------------------------- + +func TestFailedDownloadIsRefunded(t *testing.T) { + netErr := &ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "reset"} + h := startMoney(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{link: {netErr, netErr}}}, nil) + h.grant(alice, 200) + + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + failed := h.wait(seq, edits, textHas("That did not work")) + if !strings.Contains(failed.Text(), "50 sats went back to your balance.") { + t.Fatalf("failure text = %q", failed.Text()) + } + // It was retried once before the refund. + if n := len(h.fake.Downloads()); n != 2 { + t.Fatalf("downloads = %d, want 2", n) + } + if got := h.balance(alice); got != 200 { + t.Fatalf("balance = %d, want the full 200 back", got) + } + es, _ := h.app.Store.ListLedger(context.Background(), h.wallet(alice).ID, 10) + if len(es) != 3 || es[0].Kind != db.LedgerRefund || es[0].Amount != 50 || es[1].Kind != db.LedgerDebit || es[1].Amount != 50 { + t.Fatalf("ledger = %+v", es) + } + // The failed attempt does not use up the daily quota either. + if usage, _ := h.app.Service.Usage(context.Background(), alice); usage.Downloads != 0 { + t.Fatalf("usage after refund = %+v", usage) + } + d := h.deliveriesOf(alice, db.DeliveryFailed) + if len(d) != 1 || !d[0].Released { + t.Fatalf("delivery = %+v", d) + } + // Refunding again changes nothing. + for i := 0; i < 3; i++ { + if n, err := h.app.Service.Release(context.Background(), d[0].ID); err != nil || n != 0 { + t.Fatalf("second release = %d, %v", n, err) + } + } + if got := h.balance(alice); got != 200 { + t.Fatalf("balance after repeated release = %d", got) + } + h.booksBalance() +} + +func TestCancelledDownloadIsRefunded(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := startMoney(t, &ytdlptest.Fake{Block: block}, nil) + h.grant(alice, 100) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + status := h.wait(seq, edits, textHas("Downloading")) + if got := h.balance(alice); got != 50 { + t.Fatalf("balance while running = %d, want 50", got) + } + seq = h.press(alice, alice, status, "jc:") + h.wait(seq, edits, func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "Cancelled") && strings.Contains(c.Text(), "50 sats went back") + }) + if got := h.balance(alice); got != 100 { + t.Fatalf("balance after cancel = %d", got) + } +} + +func TestSendFailureIsRefunded(t *testing.T) { + h := startMoney(t, nil, nil) + h.grant(alice, 100) + card := h.card(alice, alice, link) + for i := 0; i < 3; i++ { + h.srv.FailNext("sendVideo", 500, "Internal Server Error") + } + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "could not send the file") && strings.Contains(c.Text(), "50 sats went back") + }) + if got := h.balance(alice); got != 100 { + t.Fatalf("balance = %d", got) + } +} + +// --- over-limit flow ------------------------------------------------------- + +func TestOverLimitPayForThisFileOnly(t *testing.T) { + h := startMoney(t, &ytdlptest.Fake{FileSize: 4096}, nil) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + if !strings.Contains(offer.Text(), "larger than your limit of 50.0 MB") { + t.Fatalf("offer text = %q", offer.Text()) + } + // 80 MB is one started 100 MB step: 100 base + 50. + want := "Day pass · 700 sats | Week pass · 3,000 sats | Month pass · 9,000 sats | This file only · 150 sats" + if labels(offer) != want { + t.Fatalf("offer buttons = %q", labels(offer)) + } + for _, b := range offer.Buttons() { + if b.URL != "" { + t.Fatalf("a private offer must not use URL buttons: %+v", b) + } + } + if n := len(h.fake.Downloads()); n != 0 { + t.Fatalf("an over-limit file was downloaded %d times before payment", n) + } + + seq = h.press(alice, alice, offer, "ob:one_off") + inv, _ := h.invoice(seq, 1) + if inv.AmountSats != 150 { + t.Fatalf("one-off price = %d", inv.AmountSats) + } + h.pay(inv) + video := h.wait(seq, "sendVideo", nil) + if video.Files["video"].Size != 4096 { + t.Fatalf("video = %+v", video.Files) + } + // The original card became the status message. + done := h.wait(seq, edits, textHas("Done")) + if done.MessageID != card.MessageID { + t.Fatalf("status went to message %d, want the card %d", done.MessageID, card.MessageID) + } + sent := h.waitSent(alice, 1) + if sent[0].Source != "one_off" || sent[0].ChargeSats != 150 { + t.Fatalf("delivery = %+v", sent) + } + job, _ := h.app.Store.GetJob(context.Background(), sent[0].JobID) + if job.Lane != db.LanePaid { + t.Fatalf("a one-off job must be in the paid lane, got %s", job.Lane) + } + if h.balance(alice) != 0 { + t.Fatal("a delivered one-off must not leave credits behind") + } + + // It was for one file. The next big file is refused again. + card = h.card(alice, alice, bigLink) + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "sendMessage", textHas("You can lift the limit")) +} + +func TestOneOffIsRefundedAsCreditsWhenTheDownloadFails(t *testing.T) { + h := startMoney(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{ + bigLink: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "private"}}, + }}, nil) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + seq = h.press(alice, alice, offer, "ob:one_off") + inv, _ := h.invoice(seq, 1) + h.pay(inv) + h.wait(seq, edits, func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "That did not work") && strings.Contains(c.Text(), "150 sats went back to your balance") + }) + // A Lightning payment cannot be sent back, so it becomes credits. + if got := h.balance(alice); got != 150 { + t.Fatalf("balance = %d, want 150", got) + } + h.booksBalance() +} + +func TestOverLimitBuyPassStartsTheDownload(t *testing.T) { + h := startMoney(t, nil, nil) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + seq = h.press(alice, alice, offer, "ob:pass_week") + inv, _ := h.invoice(seq, 1) + if inv.AmountSats != 3000 { + t.Fatalf("week pass price = %d", inv.AmountSats) + } + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("Your pass is active until")) + h.wait(seq, "sendVideo", nil) + if sent := h.waitSent(alice, 1); sent[0].Source != "own_pass" { + t.Fatalf("delivery = %+v", sent) + } +} + +func TestGroupOverLimitUsesDeepLinks(t *testing.T) { + h := startMoney(t, nil, nil) + card := h.card(group, alice, "/dl "+bigLink) + seq := h.press(group, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + if offer.ChatID() != group { + t.Fatalf("the offer must answer in the group") + } + btns := offer.Buttons() + if len(btns) != 1 || btns[0].Text != "Buy for me" || btns[0].Data != "" { + t.Fatalf("group offer buttons = %+v", btns) + } + prefix := "https://t.me/" + fakeserver.BotUsername + "?start=buy_" + if !strings.HasPrefix(btns[0].URL, prefix) { + t.Fatalf("deep link = %q", btns[0].URL) + } + payload := strings.TrimPrefix(btns[0].URL, "https://t.me/"+fakeserver.BotUsername+"?start=") + for _, r := range payload { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-') { + t.Fatalf("start parameter %q has a character Telegram does not allow", payload) + } + } + + // Somebody else opening the link gets nothing. + seq = h.srv.Seq() + h.srv.PushMessage(bob, bob, "/start "+payload) + h.wait(seq, "sendMessage", textHas("expired")) + + // The requester lands in the private chat and gets the real offer. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/start "+payload) + private := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + if private.ChatID() != alice { + t.Fatal("the private offer went to the wrong chat") + } + seq = h.press(alice, alice, private, "ob:one_off") + inv, msg := h.invoice(seq, 1) + if msg.ChatID() != alice { + t.Fatal("the invoice must go to the private chat, never to the group") + } + h.pay(inv) + // The file is delivered where it was asked for: in the group. + video := h.wait(seq, "sendVideo", nil) + if video.ChatID() != group { + t.Fatalf("the file went to %d, want the group", video.ChatID()) + } +} + +func TestPaymentsDisabledFallsBackToPlainRefusal(t *testing.T) { + h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{bigLink: bigInfo()}}, nil) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + alert := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "larger than your limit") || alert.Params["show_alert"] != "true" { + t.Fatalf("alert = %+v", alert.Params) + } + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/buy") + h.wait(seq, "sendMessage", textHas("Payments are not set up")) +} + +// --- invoices: expiry, cancel, check, polling ------------------------------ + +func TestUnpaidInvoiceExpiresAndNothingStarts(t *testing.T) { + h := startMoney(t, nil, func(c *config.Config) { + c.LNbits.InvoiceExpiry = config.Duration(300 * time.Millisecond) + c.LNbits.PollInterval = config.Duration(50 * time.Millisecond) + }) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + seq = h.press(alice, alice, offer, "ob:one_off") + _, msg := h.invoice(seq, 1) + + expired := h.wait(seq, "editMessageCaption", textHas("has expired")) + if expired.MessageID != msg.MessageID || len(expired.Buttons()) != 0 { + t.Fatalf("expired message = %+v", expired.Params) + } + h.never(seq, "sendVideo", nil) + if n := len(h.fake.Downloads()); n != 0 { + t.Fatalf("an unpaid download ran %d times", n) + } + if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)) + len(h.jobs(db.JobDone)); n != 0 { + t.Fatalf("%d jobs exist for an unpaid invoice", n) + } +} + +func TestLostWebhookIsCaughtByPollingAndByTheCheckButton(t *testing.T) { + h := startMoney(t, nil, func(c *config.Config) { c.LNbits.PollInterval = config.Duration(80 * time.Millisecond) }) + h.ln.DropWebhooks = true + + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance")) + seq = h.press(alice, alice, menu, "by:credits:5000") + inv, msg := h.invoice(seq, 1) + + // Pressing "Check payment" before paying says so and changes nothing. + seq = h.press(alice, alice, msg, "pc:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "Not paid yet") + }) + h.pay(inv) // no webhook is sent + h.wait(seq, "editMessageCaption", textHas("Your balance is now 5,000 sats.")) + if h.balance(alice) != 5000 { + t.Fatalf("balance = %d", h.balance(alice)) + } + // A late press finds it settled. + seq = h.press(alice, alice, msg, "pc:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "Payment received") + }) + if h.balance(alice) != 5000 { + t.Fatalf("balance after a second check = %d", h.balance(alice)) + } +} + +func TestCheckButtonSettlesWithoutWebhookOrPoll(t *testing.T) { + h := startMoney(t, nil, nil) // polling every hour + h.ln.DropWebhooks = true + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance")) + seq = h.press(alice, alice, menu, "by:credits:1000") + inv, msg := h.invoice(seq, 1) + h.pay(inv) + seq = h.press(alice, alice, msg, "pc:") + h.wait(seq, "editMessageCaption", textHas("Your balance is now 1,000 sats.")) +} + +func TestCancelInvoice(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance")) + seq = h.press(alice, alice, menu, "by:credits:1000") + inv, msg := h.invoice(seq, 1) + + // Bob cannot cancel or check Alice's invoice. + seq2 := h.press(alice, bob, msg, "px:") + h.wait(seq2, "answerCallbackQuery", nil) + p, _ := h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash) + if p.Status != db.PurchasePending { + t.Fatalf("a stranger changed the purchase to %s", p.Status) + } + + seq = h.press(alice, alice, msg, "px:") + h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool { + return c.Params["message_id"] == fmt.Sprint(msg.MessageID) + }) + p, _ = h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash) + if p.Status != db.PurchaseCancelled { + t.Fatalf("status = %s", p.Status) + } +} + +// --- acceptance: reconciliation on startup, end to end --------------------- + +func TestPaymentDuringDowntimeIsSettledAndFulfilledOnStartup(t *testing.T) { + h := startMoney(t, &ytdlptest.Fake{FileSize: 2048}, nil) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + seq = h.press(alice, alice, offer, "ob:one_off") + inv, _ := h.invoice(seq, 1) + + h.waitInvoiceSaved(inv) + + // The core goes down. The user pays while it is away, so the webhook + // has nowhere to go. + h.stop() + h.ln.DropWebhooks = true + h.pay(inv) + + seq = h.srv.Seq() + h.boot() + h.wait(seq, "editMessageCaption", textHas("Paid.")) + video := h.wait(seq, "sendVideo", nil) + if video.Files["video"].Size != 2048 { + t.Fatalf("video = %+v", video.Files) + } + p, _ := h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash) + if p.Status != db.PurchasePaid || !p.Fulfilled { + t.Fatalf("purchase = %+v", p) + } + h.waitSent(alice, 1) + time.Sleep(200 * time.Millisecond) + if n := len(h.fake.Downloads()); n != 1 { + t.Fatalf("the paid file was downloaded %d times, want once", n) + } +} + +// --- daily quota ----------------------------------------------------------- + +func TestDailyQuota(t *testing.T) { + failing := "https://example.com/fails" + h := startMoney(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{ + failing: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "x"}}, + }}, func(c *config.Config) { c.Limits.Free.DailyDownloads = 2 }) + + // A failed download does not count. + card := h.card(alice, alice, failing) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, textHas("That did not work")) + + for i := 0; i < 2; i++ { + card := h.card(alice, alice, fmt.Sprintf("https://example.com/ok%d", i)) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, textHas("Done")) + } + card = h.card(alice, alice, "https://example.com/third") + seq = h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You used your 2 downloads for today")) + // A pass lifts the quota; "this file only" would not, so it is absent. + if labels(offer) != "Day pass · 700 sats | Week pass · 3,000 sats | Month pass · 9,000 sats" { + t.Fatalf("quota offer buttons = %q", labels(offer)) + } + if n := len(h.fake.Downloads()); n != 3 { + t.Fatalf("downloads = %d, want 3 (one failed, two fine)", n) + } + // Another user has their own quota. + card = h.card(bob, bob, "https://example.com/bob") + seq = h.press(bob, bob, card, "dl:") + h.wait(seq, edits, textHas("Done")) +} + +func TestDailyVolumeCapAppliesToPaidUsers(t *testing.T) { + h := startMoney(t, &ytdlptest.Fake{FileSize: 3 << 20}, func(c *config.Config) { c.Limits.Paid.DailyMB = 2 }) + if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil { + t.Fatal(err) + } + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, textHas("Done")) // 3 MB delivered, cap is 2 MB + + card = h.card(alice, alice, "https://example.com/more") + seq = h.press(alice, alice, card, "dl:") + alert := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "daily volume of 2.0 MB") { + t.Fatalf("alert = %q", alert.Params["text"]) + } +} + +// --- skip the queue -------------------------------------------------------- + +// queued sets up a busy single worker with alice's job running and bob's +// job waiting, and returns bob's queued status message. +func (h *moneyHarness) queued() fakeserver.Call { + h.t.Helper() + first := h.card(alice, alice, "https://example.com/running") + h.press(alice, alice, first, "dl:") + h.waitJobs(db.JobRunning, 1) + second := h.card(bob, bob, "https://example.com/waiting") + seq := h.press(bob, bob, second, "dl:") + return h.wait(seq, edits, textHas("In the queue")) +} + +func TestSkipTheQueueWithCredits(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) + h.grant(bob, 40) // not enough for a paid download, so bob queues as free + status := h.queued() + if labels(status) != "Skip the queue · 50 sats | Cancel" { + t.Fatalf("queued buttons = %q", labels(status)) + } + // Alice cannot skip bob's job. + seq := h.press(bob, alice, status, "sq:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "belong to the person who asked") + }) + + h.grant(bob, 20) // now 60 + seq = h.press(bob, bob, status, "sq:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "moved to the front") + }) + if got := h.balance(bob); got != 10 { + t.Fatalf("balance = %d, want 10", got) + } + q := h.jobs(db.JobQueued) + if len(q) != 1 || q[0].Lane != db.LanePaid { + t.Fatalf("queued job = %+v", q) + } + // The button is gone once the job is in the paid lane. + after := h.wait(seq, edits, func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "In the queue") && labels(c) == "Cancel" + }) + _ = after + // Pressing the stale button again costs nothing. + seq = h.press(bob, bob, status, "sq:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "not waiting in the queue anymore") + }) + if got := h.balance(bob); got != 10 { + t.Fatalf("balance after a second press = %d", got) + } + h.booksBalance() +} + +func TestSkipTheQueueWithInvoice(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) + status := h.queued() + seq := h.press(bob, bob, status, "sq:") + inv, _ := h.invoice(seq, 1) + if inv.AmountSats != 50 { + t.Fatalf("skip price = %d", inv.AmountSats) + } + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("Paid.")) + deadline := time.Now().Add(5 * time.Second) + for { + if q := h.jobs(db.JobQueued); len(q) == 1 && q[0].Lane == db.LanePaid { + break + } + if time.Now().After(deadline) { + t.Fatal("the job was not promoted after payment") + } + time.Sleep(20 * time.Millisecond) + } + if h.balance(bob) != 0 { + t.Fatal("a fulfilled skip must not leave credits") + } +} + +func TestSkipPaymentThatArrivesTooLateBecomesCredits(t *testing.T) { + block := make(chan struct{}) + h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) + status := h.queued() + seq := h.press(bob, bob, status, "sq:") + inv, _ := h.invoice(seq, 1) + + close(block) // both jobs finish before bob pays + h.waitJobs(db.JobDone, 2) + h.pay(inv) + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "had already left the queue") && strings.Contains(c.Text(), "50 sats were added") + }) + if got := h.balance(bob); got != 50 { + t.Fatalf("balance = %d, want the 50 sats as credits", got) + } + h.booksBalance() +} + +// --- HTTP routes ----------------------------------------------------------- + +func TestWebhookEndpoint(t *testing.T) { + h := startMoney(t, nil, nil) + h.ln.DropWebhooks = true + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance")) + seq = h.press(alice, alice, menu, "by:credits:1000") + inv, _ := h.invoice(seq, 1) + + base := "http://" + h.app.HTTP.Addr() + post := func(path, body string) int { + resp, err := http.Post(base+path, "application/json", bytes.NewBufferString(body)) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + return resp.StatusCode + } + body := fmt.Sprintf(`{"payment_hash": %q, "pending": false, "amount": 1000000}`, inv.PaymentHash) + + if code := post("/lnbits/webhook/wrong-secret", body); code != http.StatusNotFound { + t.Fatalf("wrong secret answered %d, want 404", code) + } + if code := post("/lnbits/webhook/test-hook-secret", "not json"); code != http.StatusBadRequest { + t.Fatalf("bad body answered %d, want 400", code) + } + // A correct secret with an invoice that is not paid: accepted, ignored. + if code := post("/lnbits/webhook/test-hook-secret", body); code != http.StatusOK { + t.Fatalf("forged webhook answered %d", code) + } + if h.balance(alice) != 0 { + t.Fatal("a forged webhook credited the wallet") + } + // Once LNbits confirms, the very same request settles it, once. + if err := h.ln.Pay(inv.PaymentHash); err != nil { + t.Fatal(err) + } + for i := 0; i < 5; i++ { + if code := post("/lnbits/webhook/test-hook-secret", body); code != http.StatusOK { + t.Fatalf("webhook answered %d", code) + } + } + if got := h.balance(alice); got != 1000 { + t.Fatalf("balance = %d, want exactly 1000", got) + } + h.booksBalance() +} + +func TestPayPage(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance")) + seq = h.press(alice, alice, menu, "by:credits:1000") + inv, msg := h.invoice(seq, 1) + url := msg.Buttons()[0].URL + + get := func(u string) (int, string) { + resp, err := http.Get(u) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(b) + } + code, body := get(url) + if code != 200 || !strings.Contains(body, `href="lightning:`+inv.Bolt11+`"`) || !strings.Contains(body, "Open in wallet") { + t.Fatalf("pay page = %d %s", code, body) + } + if code, _ := get("http://" + h.app.HTTP.Addr() + "/pay/doesnotexist"); code != http.StatusGone { + t.Fatalf("unknown purchase answered %d, want 410", code) + } + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("Paid.")) + if code, body := get(url); code != http.StatusGone || strings.Contains(body, inv.Bolt11) { + t.Fatalf("a paid invoice must not be offered again: %d", code) + } +} + +// --- other money commands -------------------------------------------------- + +func TestRedeemGiftCode(t *testing.T) { + h := startMoney(t, nil, nil) + g, err := h.app.Billing.NewGiftCode(context.Background(), billing.GiftCredits, 300, 1, 0, 1) + if err != nil { + t.Fatal(err) + } + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/redeem") + h.wait(seq, "sendMessage", textHas("Send the code after the command")) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/redeem "+strings.ToLower(g.Code)) + h.wait(seq, "sendMessage", textHas("300 sats were added to your balance")) + if h.balance(alice) != 300 { + t.Fatalf("balance = %d", h.balance(alice)) + } + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/redeem "+g.Code) + h.wait(seq, "sendMessage", textHas("already used")) + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/redeem NR-AAAA-BBBB-CCCC") + h.wait(seq, "sendMessage", textHas("not valid")) + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/redeem cashuAeyJ0b2tlbiI6W119") + h.wait(seq, "sendMessage", textHas("Cashu tokens are not accepted")) +} + +func TestReferralRewardEndToEnd(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/referral") + ref := h.wait(seq, "sendMessage", textHas("Invite friends")) + link := fmt.Sprintf("https://t.me/%s?start=ref_%d", fakeserver.BotUsername, alice) + if !strings.Contains(ref.Text(), link) || !strings.Contains(ref.Text(), "you get 200 sats") || + !strings.Contains(ref.Text(), "You invited 0 people") { + t.Fatalf("referral text = %q", ref.Text()) + } + + // Bob is new and arrives through the link. + seq = h.srv.Seq() + h.srv.PushMessage(bob, bob, fmt.Sprintf("/start ref_%d", alice)) + h.wait(seq, "sendMessage", textHas("welcome")) + // Alice already knows the bot: a link to herself or from bob does nothing. + h.srv.PushMessage(alice, alice, fmt.Sprintf("/start ref_%d", bob)) + + seq = h.srv.Seq() + h.srv.PushMessage(bob, bob, "/credits") + menu := h.wait(seq, "sendMessage", textHas("Your balance")) + seq = h.press(bob, bob, menu, "by:credits:1000") + inv, _ := h.invoice(seq, 1) + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("Paid.")) + + if got := h.balance(alice); got != 200 { + t.Fatalf("inviter balance = %d, want 200", got) + } + if got := h.balance(bob); got != 1000 { + t.Fatalf("invited balance = %d", got) + } + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/referral") + h.wait(seq, "sendMessage", textHas("You invited 1 person so far")) + u, _ := h.app.Store.GetUser(context.Background(), alice) + if u.ReferredBy != 0 { + t.Fatalf("an existing user was referred: %+v", u) + } + h.booksBalance() +} + +func TestDonate(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/donate") + menu := h.wait(seq, "sendMessage", textHas("Thank you for supporting")) + if labels(menu) != "500 sats | 2,100 sats | 10,000 sats" { + t.Fatalf("donation buttons = %q", labels(menu)) + } + seq = h.press(alice, alice, menu, "by:donation:2100") + inv, _ := h.invoice(seq, 1) + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("Thank you for the support.")) + if h.balance(alice) != 0 { + t.Fatal("a donation must not become credits") + } +} + +func TestBuyerCannotChooseThePriceOfAPass(t *testing.T) { + h := startMoney(t, nil, nil) + seq := h.srv.Seq() + // A crafted callback asks for a day pass for 1 sat. + h.srv.PushCallback(alice, alice, 1, "by:pass_day:1") + inv, _ := h.invoice(seq, 1) + if inv.AmountSats != 700 { + t.Fatalf("a crafted callback got a pass for %d sats", inv.AmountSats) + } + seq = h.srv.Seq() + h.srv.PushCallback(alice, alice, 1, "by:credits:-5") + h.wait(seq, "sendMessage", textHas("amount is not possible")) + seq = h.srv.Seq() + h.srv.PushCallback(alice, alice, 1, "by:yacht") + h.wait(seq, "sendMessage", textHas("amount is not possible")) +} + +func TestMoneyCommandsInGroupsPointToPrivateChat(t *testing.T) { + h := startMoney(t, nil, nil) + for _, cmd := range []string{"/buy", "/account", "/credits", "/redeem X", "/referral", "/donate"} { + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, cmd) + c := h.wait(seq, "sendMessage", textHas("private chat")) + if b := c.Buttons(); len(b) != 1 || b[0].URL != "https://t.me/"+fakeserver.BotUsername { + t.Fatalf("%s: buttons = %+v", cmd, b) + } + } + if n, _ := h.ln.Calls(); n != 0 { + t.Fatalf("%d invoices were created from a group", n) + } +} + +func TestLightningDownIsExplained(t *testing.T) { + h := startMoney(t, nil, nil) + h.ln.SetDown(true) + seq := h.srv.Seq() + h.srv.PushCallback(alice, alice, 1, "by:pass_day") + h.wait(seq, "sendMessage", textHas("cannot reach the payment service")) +} + +func TestRateLimit(t *testing.T) { + h := startMoney(t, nil, func(c *config.Config) { c.Rate.UserPerMinute = 3 }) + seq := h.srv.Seq() + for i := 0; i < 6; i++ { + h.srv.PushMessage(alice, alice, fmt.Sprintf("https://example.com/r%d", i)) + } + h.wait(seq, "sendMessage", textHas("That is a lot of links")) + time.Sleep(300 * time.Millisecond) + if n := len(h.fake.Probes()); n != 3 { + t.Fatalf("probes = %d, want 3", n) + } + notices := 0 + for _, c := range h.srv.Calls("sendMessage") { + if strings.Contains(c.Text(), "That is a lot of links") { + notices++ + } + } + if notices != 1 { + t.Fatalf("rate limit notices = %d, want 1", notices) + } + // Other users are not affected. + h.card(bob, bob, "https://example.com/bob") +} + +func TestEntitlementSurvivesInService(t *testing.T) { + // The decision the service makes must follow the resolver's order with + // real wallets behind it. + h := startMoney(t, nil, nil) + ctx := context.Background() + who := service.Who{UserID: alice, ChatID: alice, ChatType: "private"} + source := func() string { + d, err := h.app.Service.Entitlement(ctx, who, false) + if err != nil { + t.Fatal(err) + } + return string(d.Source) + } + if got := source(); got != "free" { + t.Fatalf("no wallet: %s", got) + } + h.grant(alice, 49) + if got := source(); got != "free" { + t.Fatalf("49 sats: %s", got) + } + h.grant(alice, 1) + if got := source(); got != "own_credits" { + t.Fatalf("50 sats: %s", got) + } + if _, err := h.app.Billing.GrantPass(ctx, h.wallet(alice).ID, "day", "test"); err != nil { + t.Fatal(err) + } + if got := source(); got != "own_pass" { + t.Fatalf("with a pass: %s", got) + } + if d, _ := h.app.Service.Entitlement(ctx, who, true); d.Source != "one_off" { + t.Fatalf("one-off: %s", d.Source) + } +} + +func TestPaymentIsConfirmedEvenWhenTheInvoiceMessageIsUnknown(t *testing.T) { + // The core can stop in the instant between Telegram accepting the + // invoice message and the bot saving its ID. The payer must still hear + // that the payment arrived. + h := startMoney(t, nil, nil) + ctx := context.Background() + p, err := h.app.Billing.CreatePurchase(ctx, billing.NewPurchase{ + UserID: alice, WalletID: h.wallet(alice).ID, Product: billing.ProductCredits, Amount: 1000, Lang: "en", + }) + if err != nil { + t.Fatal(err) + } + seq := h.srv.Seq() + if err := h.ln.Pay(p.PaymentHash); err != nil { // no invoice message was ever recorded + t.Fatal(err) + } + confirm := h.wait(seq, "sendMessage", textHas("Paid.")) + if confirm.ChatID() != alice || !strings.Contains(confirm.Text(), "Your balance is now 1,000 sats.") { + t.Fatalf("confirmation = %q to %d", confirm.Text(), confirm.ChatID()) + } + time.Sleep(400 * time.Millisecond) + n := 0 + for _, c := range h.srv.Calls("sendMessage") { + if strings.Contains(c.Text(), "Paid.") { + n++ + } + } + if n != 1 { + t.Fatalf("%d confirmations were sent, want 1", n) + } +} diff --git a/internal/billing/billing.go b/internal/billing/billing.go new file mode 100644 index 0000000..6f4cb22 --- /dev/null +++ b/internal/billing/billing.go @@ -0,0 +1,656 @@ +// 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 +} diff --git a/internal/billing/billing_test.go b/internal/billing/billing_test.go new file mode 100644 index 0000000..9b19f3c --- /dev/null +++ b/internal/billing/billing_test.go @@ -0,0 +1,757 @@ +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, `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) + } +} diff --git a/internal/billing/gift.go b/internal/billing/gift.go new file mode 100644 index 0000000..ccfe67f --- /dev/null +++ b/internal/billing/gift.go @@ -0,0 +1,162 @@ +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") +) diff --git a/internal/billing/lnbits/client.go b/internal/billing/lnbits/client.go new file mode 100644 index 0000000..d059f32 --- /dev/null +++ b/internal/billing/lnbits/client.go @@ -0,0 +1,194 @@ +// Package lnbits is a small client for the LNbits HTTP API. +// +// It was written against the LNbits source at v0.12.12 and checked against +// v1.7.1. Only three calls are used and they are the same in both: +// +// POST /api/v1/payments create an invoice (invoice key) +// GET /api/v1/payments/{hash} payment status (invoice key) +// GET /api/v1/wallet wallet info, used as a health check +// +// The one difference: v0.12 returns the invoice as "payment_request", v1 +// returns the payment object with "bolt11". Both are read. +package lnbits + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +// ErrNotFound is returned when LNbits does not know a payment hash. +var ErrNotFound = errors.New("lnbits: payment not found") + +// Invoice is a created Lightning invoice. +type Invoice struct { + PaymentHash string + Bolt11 string +} + +// Client talks to one LNbits wallet with its invoice key. The invoice key +// can create invoices and read payments but cannot spend, so a leaked key +// cannot drain the wallet. +type Client struct { + baseURL string + key string + http *http.Client +} + +// New creates a client. baseURL is the LNbits root, for example +// https://lnbits.example.com. +func New(baseURL, invoiceKey string) *Client { + return &Client{ + baseURL: strings.TrimRight(baseURL, "/"), + key: invoiceKey, + http: &http.Client{Timeout: 20 * time.Second}, + } +} + +type createRequest struct { + Out bool `json:"out"` + Amount int64 `json:"amount"` + Unit string `json:"unit"` + Memo string `json:"memo"` + Expiry int64 `json:"expiry,omitempty"` + Webhook string `json:"webhook,omitempty"` +} + +type createResponse struct { + PaymentHash string `json:"payment_hash"` + PaymentRequest string `json:"payment_request"` + Bolt11 string `json:"bolt11"` +} + +// CreateInvoice asks LNbits for an invoice of the given amount in sats. +// webhook may be empty; LNbits posts to it once when the invoice is paid. +func (c *Client) CreateInvoice(ctx context.Context, sats int64, memo string, expiry time.Duration, webhook string) (*Invoice, error) { + if sats <= 0 { + return nil, errors.New("lnbits: amount must be positive") + } + body, err := json.Marshal(createRequest{ + Out: false, Amount: sats, Unit: "sat", Memo: memo, + Expiry: int64(expiry.Seconds()), Webhook: webhook, + }) + if err != nil { + return nil, err + } + var resp createResponse + if err := c.do(ctx, http.MethodPost, "/api/v1/payments", body, &resp); err != nil { + return nil, err + } + inv := &Invoice{PaymentHash: resp.PaymentHash, Bolt11: resp.PaymentRequest} + if inv.Bolt11 == "" { + inv.Bolt11 = resp.Bolt11 + } + if inv.PaymentHash == "" || inv.Bolt11 == "" { + return nil, errors.New("lnbits: invoice response lacks payment_hash or invoice") + } + return inv, nil +} + +type statusResponse struct { + Paid bool `json:"paid"` +} + +// Paid reports whether the invoice with the given payment hash is settled. +func (c *Client) Paid(ctx context.Context, paymentHash string) (bool, error) { + if !isHex(paymentHash) { + return false, ErrNotFound + } + var resp statusResponse + if err := c.do(ctx, http.MethodGet, "/api/v1/payments/"+paymentHash, nil, &resp); err != nil { + return false, err + } + return resp.Paid, nil +} + +// Health checks that LNbits is reachable and accepts the key. +func (c *Client) Health(ctx context.Context) error { + var resp map[string]any + return c.do(ctx, http.MethodGet, "/api/v1/wallet", nil, &resp) +} + +func (c *Client) do(ctx context.Context, method, path string, body []byte, out any) error { + var rd io.Reader + if body != nil { + rd = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, rd) + if err != nil { + return err + } + req.Header.Set("X-Api-Key", c.key) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + // The error text of net/http includes the URL but never headers, so + // the key cannot leak through it. + return fmt.Errorf("lnbits: %s %s: %w", method, path, err) + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return fmt.Errorf("lnbits: %s %s: %w", method, path, err) + } + switch { + case resp.StatusCode == http.StatusNotFound: + return ErrNotFound + case resp.StatusCode < 200 || resp.StatusCode > 299: + return &StatusError{Code: resp.StatusCode, Detail: detail(data)} + } + if out == nil { + return nil + } + if err := json.Unmarshal(data, out); err != nil { + return fmt.Errorf("lnbits: %s %s: bad response: %w", method, path, err) + } + return nil +} + +// StatusError is a non-2xx answer from LNbits. +type StatusError struct { + Code int + Detail string +} + +func (e *StatusError) Error() string { + return fmt.Sprintf("lnbits: http %d: %s", e.Code, e.Detail) +} + +// detail extracts the "detail" field LNbits puts in error bodies. +func detail(data []byte) string { + var doc struct { + Detail any `json:"detail"` + } + if json.Unmarshal(data, &doc) == nil && doc.Detail != nil { + return fmt.Sprint(doc.Detail) + } + s := strings.TrimSpace(string(data)) + if len(s) > 200 { + s = s[:200] + } + return s +} + +func isHex(s string) bool { + if len(s) == 0 || len(s) > 128 { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') { + return false + } + } + return true +} diff --git a/internal/billing/lnbitstest/server.go b/internal/billing/lnbitstest/server.go new file mode 100644 index 0000000..fa1a3f3 --- /dev/null +++ b/internal/billing/lnbitstest/server.go @@ -0,0 +1,270 @@ +// Package lnbitstest is a fake LNbits server for tests. It implements the +// three endpoints the bot uses, with the request and response shapes of +// the real server, and lets a test pay invoices, replay or drop webhooks +// and take the server down. +package lnbitstest + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "time" +) + +// Key is the invoice key the fake accepts. +const Key = "fake-invoice-key-0123456789abcdef" + +// Invoice is an invoice created through the fake. +type Invoice struct { + PaymentHash string + Bolt11 string + AmountSats int64 + Memo string + Webhook string + Expiry int64 // seconds + Paid bool + // WebhooksSent counts webhook posts for this invoice. + WebhooksSent int +} + +// Server is the fake LNbits. +type Server struct { + HTTP *httptest.Server + + mu sync.Mutex + // V1 makes responses look like LNbits v1.x (invoice in "bolt11"). + V1 bool + // DropWebhooks simulates webhooks that never arrive. + DropWebhooks bool + down bool + invoices map[string]*Invoice + order []string + statusCalls int + createCalls int +} + +// New starts a fake server. +func New() *Server { + s := &Server{invoices: map[string]*Invoice{}} + s.HTTP = httptest.NewServer(http.HandlerFunc(s.handle)) + return s +} + +// URL returns the server root to use as LNBITS_URL. +func (s *Server) URL() string { return s.HTTP.URL } + +// Close stops the server. +func (s *Server) Close() { s.HTTP.Close() } + +// SetDown makes every request fail with 503 while down is true. +func (s *Server) SetDown(down bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.down = down +} + +// Invoices returns copies of all invoices in creation order. +func (s *Server) Invoices() []Invoice { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]Invoice, 0, len(s.order)) + for _, h := range s.order { + out = append(out, *s.invoices[h]) + } + return out +} + +// Last returns the most recently created invoice. +func (s *Server) Last() (Invoice, bool) { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.order) == 0 { + return Invoice{}, false + } + return *s.invoices[s.order[len(s.order)-1]], true +} + +// WaitInvoice waits until at least n invoices exist and returns the n-th. +func (s *Server) WaitInvoice(n int, timeout time.Duration) (Invoice, bool) { + deadline := time.Now().Add(timeout) + for { + s.mu.Lock() + if len(s.order) >= n { + inv := *s.invoices[s.order[n-1]] + s.mu.Unlock() + return inv, true + } + s.mu.Unlock() + if time.Now().After(deadline) { + return Invoice{}, false + } + time.Sleep(5 * time.Millisecond) + } +} + +// Calls returns how many create and status requests were served. +func (s *Server) Calls() (creates, statuses int) { + s.mu.Lock() + defer s.mu.Unlock() + return s.createCalls, s.statusCalls +} + +// Pay marks an invoice as paid and, unless DropWebhooks is set, posts the +// webhook the way LNbits does: once, unsigned, with the payment as body. +func (s *Server) Pay(paymentHash string) error { + s.mu.Lock() + inv, ok := s.invoices[paymentHash] + if !ok { + s.mu.Unlock() + return fmt.Errorf("lnbitstest: unknown invoice %s", paymentHash) + } + inv.Paid = true + drop := s.DropWebhooks + s.mu.Unlock() + if drop { + return nil + } + return s.SendWebhook(paymentHash) +} + +// SendWebhook posts the webhook of an invoice again, which is how tests +// simulate duplicate deliveries. It works for unpaid invoices too, so a +// test can send a forged "paid" notification. +func (s *Server) SendWebhook(paymentHash string) error { + s.mu.Lock() + inv, ok := s.invoices[paymentHash] + if !ok { + s.mu.Unlock() + return fmt.Errorf("lnbitstest: unknown invoice %s", paymentHash) + } + url := inv.Webhook + body, _ := json.Marshal(map[string]any{ + "payment_hash": inv.PaymentHash, + "checking_id": inv.PaymentHash, + "amount": inv.AmountSats * 1000, // LNbits reports millisats + "memo": inv.Memo, + "bolt11": inv.Bolt11, + "pending": false, + "webhook": inv.Webhook, + }) + inv.WebhooksSent++ + s.mu.Unlock() + if url == "" { + return nil + } + resp, err := http.Post(url, "application/json", bytes.NewReader(body)) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode >= 300 { + return fmt.Errorf("lnbitstest: webhook answered %d", resp.StatusCode) + } + return nil +} + +func (s *Server) handle(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + down := s.down + s.mu.Unlock() + if down { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"detail": "Service Unavailable"}) + return + } + if r.Header.Get("X-Api-Key") != Key { + writeJSON(w, http.StatusUnauthorized, map[string]any{"detail": "Invoice (or Admin) key required."}) + return + } + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/wallet": + writeJSON(w, http.StatusOK, map[string]any{"name": "test wallet", "balance": 0}) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/payments": + s.create(w, r) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/v1/payments/"): + s.status(w, strings.TrimPrefix(r.URL.Path, "/api/v1/payments/")) + default: + writeJSON(w, http.StatusNotFound, map[string]any{"detail": "Not Found"}) + } +} + +func (s *Server) create(w http.ResponseWriter, r *http.Request) { + var req struct { + Out bool `json:"out"` + Amount float64 `json:"amount"` + Unit string `json:"unit"` + Memo string `json:"memo"` + Expiry int64 `json:"expiry"` + Webhook string `json:"webhook"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "bad json"}) + return + } + if req.Out { + // Paying needs the admin key, which the bot must never have. + writeJSON(w, http.StatusUnauthorized, map[string]any{"detail": "Admin key required."}) + return + } + if req.Amount <= 0 { + writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "amount must be positive"}) + return + } + var raw [32]byte + _, _ = rand.Read(raw[:]) + hash := hex.EncodeToString(raw[:]) + inv := &Invoice{ + PaymentHash: hash, + Bolt11: fmt.Sprintf("lnbc%dn1fake%s", int64(req.Amount)*10, hash), + AmountSats: int64(req.Amount), + Memo: req.Memo, + Webhook: req.Webhook, + Expiry: req.Expiry, + } + s.mu.Lock() + s.createCalls++ + s.invoices[hash] = inv + s.order = append(s.order, hash) + v1 := s.V1 + s.mu.Unlock() + + if v1 { + writeJSON(w, http.StatusCreated, map[string]any{ + "payment_hash": hash, "bolt11": inv.Bolt11, "checking_id": hash, + "amount": inv.AmountSats * 1000, "status": "pending", + }) + return + } + writeJSON(w, http.StatusCreated, map[string]any{ + "payment_hash": hash, "payment_request": inv.Bolt11, "checking_id": hash, "lnurl_response": nil, + }) +} + +func (s *Server) status(w http.ResponseWriter, hash string) { + s.mu.Lock() + s.statusCalls++ + inv, ok := s.invoices[hash] + var paid bool + if ok { + paid = inv.Paid + } + s.mu.Unlock() + if !ok { + writeJSON(w, http.StatusNotFound, map[string]any{"detail": "Payment does not exist."}) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "paid": paid, "preimage": nil, "details": map[string]any{"payment_hash": hash, "pending": !paid}, + }) +} + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(v) +} diff --git a/internal/billing/webhook.go b/internal/billing/webhook.go new file mode 100644 index 0000000..5c2fdfd --- /dev/null +++ b/internal/billing/webhook.go @@ -0,0 +1,19 @@ +package billing + +import ( + "encoding/json" + "io" +) + +// ParseWebhook reads the payment hash from an LNbits webhook body. LNbits +// posts the whole payment object; only the hash is used, and only as a +// pointer to the purchase that is then confirmed with LNbits itself. +func ParseWebhook(body io.Reader) (paymentHash string, ok bool) { + var doc struct { + PaymentHash string `json:"payment_hash"` + } + if err := json.NewDecoder(io.LimitReader(body, 64*1024)).Decode(&doc); err != nil { + return "", false + } + return doc.PaymentHash, doc.PaymentHash != "" +} diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 1201146..996b88a 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -13,6 +13,7 @@ import ( "github.com/mymmrac/telego" + "github.com/noderunners/dlbot/internal/billing" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/i18n" @@ -29,6 +30,9 @@ type Deps struct { Store *db.Store Sched *sched.Scheduler Service *service.Service + Billing *billing.Billing + // Cashu redeems ecash tokens. Nil turns that part of /redeem off. + Cashu billing.Cashu Storage storage.Storage I18n *i18n.Bundle Log *slog.Logger @@ -44,6 +48,8 @@ type Bot struct { store *db.Store sched *sched.Scheduler svc *service.Service + bill *billing.Billing + cashu billing.Cashu storage storage.Storage tr *i18n.Bundle log *slog.Logger @@ -51,10 +57,12 @@ type Bot struct { id int64 username string - events chan sched.Event - uploads chan struct{} // limits concurrent uploads to Telegram - bg sync.WaitGroup - baseCtx context.Context + events chan sched.Event + payEvents chan billing.Event + uploads chan struct{} // limits concurrent uploads to Telegram + rate *rateLimiter + bg sync.WaitGroup + baseCtx context.Context statusMu sync.Mutex statuses map[string]*statusState // by delivery ID @@ -63,6 +71,9 @@ type Bot struct { // Tunables, shortened in tests. reconcileEvery time.Duration statusMinGap time.Duration + // invoiceGrace is how long a paid purchase may lack an invoice message + // before the payer is told in a new message. + invoiceGrace time.Duration } // New creates the bot and learns its own username, which is needed to @@ -84,6 +95,8 @@ func New(ctx context.Context, d Deps) (*Bot, error) { store: d.Store, sched: d.Sched, svc: d.Service, + bill: d.Billing, + cashu: d.Cashu, storage: d.Storage, tr: d.I18n, log: d.Log, @@ -91,12 +104,15 @@ func New(ctx context.Context, d Deps) (*Bot, error) { id: me.ID, username: me.Username, events: make(chan sched.Event, 1024), + payEvents: make(chan billing.Event, 256), uploads: make(chan struct{}, 4), + rate: newRateLimiter(), baseCtx: ctx, statuses: map[string]*statusState{}, sending: map[string]bool{}, reconcileEvery: 5 * time.Second, statusMinGap: 3 * time.Second, + invoiceGrace: 5 * time.Second, } d.Sched.Subscribe(func(ev sched.Event) { select { @@ -105,6 +121,13 @@ func New(ctx context.Context, d Deps) (*Bot, error) { // The reconcile loop picks up anything dropped here. } }) + d.Billing.Subscribe(func(ev billing.Event) { + select { + case b.payEvents <- ev: + default: + // The reconcile loop picks up unfulfilled purchases. + } + }) return b, nil } @@ -116,6 +139,7 @@ func (b *Bot) Username() string { return b.username } func (b *Bot) SetTimings(reconcile, statusGap time.Duration) { b.reconcileEvery = reconcile b.statusMinGap = statusGap + b.invoiceGrace = 4 * reconcile } // Run processes updates and job events until ctx ends, then waits for diff --git a/internal/bot/card.go b/internal/bot/card.go index ae8bfa0..a1a936c 100644 --- a/internal/bot/card.go +++ b/internal/bot/card.go @@ -4,6 +4,7 @@ import ( "context" "errors" "html" + "strconv" "strings" "time" @@ -36,6 +37,16 @@ type linkRequest struct { // startLink runs the link flow in the background so a slow metadata lookup // never blocks other updates of the chat. func (b *Bot) startLink(ctx context.Context, lr linkRequest) { + userOK := b.rate.allow("u:"+strconv.FormatInt(lr.act.user.ID, 10), b.cfg.Rate.UserPerMinute, time.Minute) + groupOK := isPrivate(lr.chatType) || + b.rate.allow("g:"+strconv.FormatInt(lr.chatID, 10), b.cfg.Rate.GroupPerMinute, time.Minute) + if !userOK || !groupOK { + // One notice per minute is enough; more would be its own flood. + if b.rate.allow("n:"+strconv.FormatInt(lr.chatID, 10)+":"+strconv.FormatInt(lr.act.user.ID, 10), 1, time.Minute) { + _, _ = b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lr.act.lang, "notice.rate_limited", nil), nil) + } + return + } b.goBG("link", func() { b.linkFlow(ctx, lr) }) } @@ -104,7 +115,7 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { ReplyMarkup: kb, }) if err == nil { - if err := b.store.SetRequestCard(ctx, req.ID, int64(msg.MessageID), true); err != nil { + if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), true); err != nil { log.Error("save card", "err", err) } b.deleteMessage(ctx, lr.chatID, phID) @@ -200,6 +211,14 @@ func (b *Bot) cbDownload(ctx context.Context, q *telego.CallbackQuery, act actor if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil { b.log.Error("release request", "request_id", req.ID, "err", rerr) } + var le *service.LimitError + if errors.As(err, &le) && le.Upgradable { + // Over the limit, but a pass or a one-off payment would cover + // it: offer those instead of a dead end. + b.answer(ctx, q, "", false) + b.offerUpgrade(ctx, req.ChatID, cardID, act.lang, req, profile, le, isPrivate(req.ChatType)) + return + } b.answer(ctx, q, b.startErrorText(act.lang, err), true) return } diff --git a/internal/bot/commands.go b/internal/bot/commands.go index 31b620a..d860fd3 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -3,6 +3,7 @@ package bot import ( "context" "errors" + "strconv" "strings" "github.com/mymmrac/telego" @@ -53,6 +54,20 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { b.cmdQueue(ctx, m, act) case "cancel": b.cmdCancel(ctx, m, act) + case "buy": + b.cmdBuy(ctx, m, act) + case "account": + b.cmdAccount(ctx, m, act) + case "limits": + b.cmdLimits(ctx, m, act) + case "credits": + b.cmdCredits(ctx, m, act) + case "donate": + b.cmdDonate(ctx, m, act) + case "redeem": + b.cmdRedeem(ctx, m, act, commandArgs(m)) + case "referral": + b.cmdReferral(ctx, m, act) default: if private { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil) @@ -78,6 +93,16 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { } } +// commandArgs returns the text after the command of a message. +func commandArgs(m *telego.Message) string { + for _, e := range m.Entities { + if e.Type == telego.EntityTypeBotCommand && e.Offset == 0 && e.Length <= len(m.Text) { + return strings.TrimSpace(m.Text[e.Length:]) + } + } + return "" +} + // parseCommand finds a bot command at the start of the message. forUs is // false when the command names a different bot (/dl@otherbot). func (b *Bot) parseCommand(m *telego.Message) (cmd string, forUs, isCmd bool) { @@ -119,18 +144,42 @@ func messageLinks(m *telego.Message) []string { } func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { - key := "start.private" if !isPrivate(m.Chat.Type) { - key = "start.group" + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.group", nil), nil) + return } - _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, i18n.Args{"Name": act.user.FirstName}), nil) + // Deep links arrive as "/start ". + payload := commandArgs(m) + switch { + case strings.HasPrefix(payload, "buy_"): + b.startBuyLink(ctx, m, act, strings.TrimPrefix(payload, "buy_")) + return + case strings.HasPrefix(payload, "skip_"): + b.startSkipLink(ctx, m, act, strings.TrimPrefix(payload, "skip_")) + return + case payload == "buy": + b.showBuy(ctx, m.Chat.ID, act) + return + case strings.HasPrefix(payload, "ref_"): + // Only somebody who is new to the bot can be referred. + if referrer, err := strconv.ParseInt(strings.TrimPrefix(payload, "ref_"), 10, 64); err == nil && act.user.IsNew { + if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil { + b.log.Error("set referrer", "user_id", act.user.ID, "err", err) + } + } + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), nil) } func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) { - lim := b.svc.LimitsFor(ctx, act.user.ID) + dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}, false) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{ - "MaxSize": b.tr.Size(act.lang, lim.MaxSize), - "MaxDuration": b.tr.Span(act.lang, secondsDuration(lim.MaxDuration)), + "MaxSize": b.tr.Size(act.lang, dec.Limits.MaxSize), + "MaxDuration": b.tr.Span(act.lang, secondsDuration(dec.Limits.MaxDuration)), }), nil) } @@ -241,14 +290,29 @@ func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int6 if err != nil { return err } + note := b.release(ctx, d) job, err := b.store.GetJob(ctx, d.JobID) if err != nil { return nil } - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)) + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+note) return nil } +// release gives back what an undelivered download took and returns a line +// to append to the status when sats were refunded. +func (b *Bot) release(ctx context.Context, d *db.Delivery) string { + refunded, err := b.svc.Release(context.WithoutCancel(ctx), d.ID) + if err != nil { + b.log.Error("release delivery", "delivery_id", d.ID, "err", err) + return "" + } + if refunded <= 0 { + return "" + } + return "\n" + b.tr.HTML(d.Lang, "status.refunded", i18n.Args{"Amount": b.tr.Sats(d.Lang, refunded)}) +} + func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { act, err := b.actorFor(ctx, &q.From) if err != nil { @@ -265,6 +329,16 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { b.cbDownload(ctx, q, act, id, arg) case cbCancelCard: b.cbCancelCard(ctx, q, act, id) + case cbSkipQueue: + b.cbSkip(ctx, q, act, id) + case cbBuy: + b.cbBuyProduct(ctx, q, act, id, arg) + case cbOfferBuy: + b.cbOffer(ctx, q, act, id, arg) + case cbPayCheck: + b.cbPayCheck(ctx, q, act, id) + case cbPayCancel: + b.cbPayCancel(ctx, q, act, id) case cbCancelJob: err := b.cancelDelivery(ctx, id, act.user.ID) switch { @@ -283,11 +357,17 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { } } -// limitText renders a limit refusal for the user. +// limitText renders a limit refusal for the user as plain text. func (b *Bot) limitText(lang string, le *service.LimitError) string { + l := le.Decision.Limits + count := l.ActiveJobs + if le.Code == service.LimitDailyDownloads { + count = l.DailyDownloads + } return b.tr.T(lang, "limit."+le.Code, i18n.Args{ - "MaxSize": b.tr.Size(lang, le.Limits.MaxSize), - "MaxDuration": b.tr.Span(lang, secondsDuration(le.Limits.MaxDuration)), - "Count": le.Limits.ActiveJobs, + "MaxSize": b.tr.Size(lang, l.MaxSize), + "MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)), + "MaxVolume": b.tr.Size(lang, l.DailyBytes), + "Count": count, }) } diff --git a/internal/bot/deliver.go b/internal/bot/deliver.go index 7104f41..638115c 100644 --- a/internal/bot/deliver.go +++ b/internal/bot/deliver.go @@ -103,10 +103,11 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuse case tg.IsBlocked(err): log.Info("requester unreachable", "err", err) _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "blocked") + b.release(ctx, d) case tg.IsFileTooBig(err): log.Warn("telegram refused file size", "size", job.FileSize, "err", err) _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "too_large") - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")) + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")+b.release(ctx, d)) case d.Attempts+1 < maxSendAttempts: log.Warn("send failed, will retry", "attempt", d.Attempts+1, "err", err) if wait := tg.RetryAfter(err); wait > 0 && wait <= time.Minute { @@ -116,13 +117,16 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuse default: log.Error("send failed, giving up", "err", err) _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "send_failed") - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")) + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")+b.release(ctx, d)) } return "" } if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil { log.Error("mark delivery sent", "err", err) } + if err := b.svc.RecordDelivered(context.WithoutCancel(ctx), d, job.FileSize); err != nil { + log.Error("record usage", "err", err) + } log.Info("file delivered", "size", job.FileSize, "profile", job.Profile) b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil)) return fileID @@ -311,7 +315,8 @@ func (b *Bot) failJob(ctx context.Context, jobID string) { if err != nil || !took { continue } - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)) + // The automatic retry is spent: give back what the download cost. + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)+b.release(ctx, d)) } b.removeStored(ctx, job) } @@ -330,7 +335,7 @@ func (b *Bot) cleanupCancelled(ctx context.Context, jobID string) { if err != nil || !took { continue } - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)) + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+b.release(ctx, d)) } } // The worker may have uploaded before it noticed the cancel. diff --git a/internal/bot/keyboards.go b/internal/bot/keyboards.go index 727342a..9a746bc 100644 --- a/internal/bot/keyboards.go +++ b/internal/bot/keyboards.go @@ -16,6 +16,11 @@ const ( cbDownload = "dl" // dl:: cbCancelCard = "cx" // cx: cbCancelJob = "jc" // jc: + cbSkipQueue = "sq" // sq: + cbBuy = "by" // by:[:] + cbOfferBuy = "ob" // ob::: + cbPayCheck = "pc" // pc: + cbPayCancel = "px" // px: ) func cbData(parts ...string) string { return strings.Join(parts, ":") } @@ -88,3 +93,20 @@ func (b *Bot) cancelJobKeyboard(lang, deliveryID string) *telego.InlineKeyboardM button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelJob, deliveryID)), }) } + +// queuedKeyboard adds "Skip the queue" to the Cancel button of a job that +// waits in the free lane. +func (b *Bot) queuedKeyboard(lang, deliveryID string) *telego.InlineKeyboardMarkup { + skip := b.tr.T(lang, "btn.with_size", i18n.Args{ + "Label": b.tr.T(lang, "btn.skip_queue", nil), + "Size": b.tr.Sats(lang, b.cfg.Prices.SkipQueue), + }) + return keyboard( + []telego.InlineKeyboardButton{button(skip, cbData(cbSkipQueue, deliveryID))}, + []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelJob, deliveryID))}, + ) +} + +func urlButton(text, url string) telego.InlineKeyboardButton { + return telego.InlineKeyboardButton{Text: text, URL: url} +} diff --git a/internal/bot/menu.go b/internal/bot/menu.go index dd675ec..4438c95 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -9,7 +9,7 @@ import ( // menuCommands are the commands shown in Telegram's command menu, in // order. Names are lowercase ASCII in every language; only descriptions // are translated, under "menu.". -var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "help"} +var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "account", "buy", "help"} // RegisterCommands publishes the command menu. A failure is logged and // otherwise ignored: the bot works without a menu. diff --git a/internal/bot/money.go b/internal/bot/money.go new file mode 100644 index 0000000..08103dc --- /dev/null +++ b/internal/bot/money.go @@ -0,0 +1,860 @@ +package bot + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "github.com/mymmrac/telego" + qrcode "github.com/skip2/go-qrcode" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/entitle" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +// privateOnly answers a money command sent in a group with a pointer to +// the private chat, and reports whether the command may continue. +func (b *Bot) privateOnly(ctx context.Context, m *telego.Message, act actor) bool { + if isPrivate(m.Chat.Type) { + return true + } + kb := keyboard([]telego.InlineKeyboardButton{ + urlButton(b.tr.T(act.lang, "btn.open_private", nil), "https://t.me/"+b.username), + }) + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.private_only", nil), kb) + return false +} + +// productTitle is the display name of a product. +func (b *Bot) productTitle(lang, product string) string { + return b.tr.T(lang, "product."+product, nil) +} + +// priced renders "Label · 700 sats" for a button. +func (b *Bot) priced(lang, label string, sats int64) string { + return b.tr.T(lang, "btn.with_size", i18n.Args{"Label": label, "Size": b.tr.Sats(lang, sats)}) +} + +// passButtons are the three pass buttons. data builds the callback data +// for a product. +func (b *Bot) passButtons(lang string, data func(product string) string) [][]telego.InlineKeyboardButton { + p := b.cfg.Prices + return [][]telego.InlineKeyboardButton{ + { + button(b.priced(lang, b.productTitle(lang, billing.ProductPassDay), p.PassDay), data(billing.ProductPassDay)), + button(b.priced(lang, b.productTitle(lang, billing.ProductPassWeek), p.PassWeek), data(billing.ProductPassWeek)), + }, + { + button(b.priced(lang, b.productTitle(lang, billing.ProductPassMonth), p.PassMonth), data(billing.ProductPassMonth)), + }, + } +} + +// amountButtons renders one button per amount for a product. +func (b *Bot) amountButtons(lang, product string, amounts []int64) []telego.InlineKeyboardButton { + var row []telego.InlineKeyboardButton + for _, a := range amounts { + row = append(row, button(b.tr.Sats(lang, a), cbData(cbBuy, product, strconv.FormatInt(a, 10)))) + } + return row +} + +// --- commands ---------------------------------------------------------------- + +func (b *Bot) cmdBuy(ctx context.Context, m *telego.Message, act actor) { + if !b.privateOnly(ctx, m, act) { + return + } + b.showBuy(ctx, m.Chat.ID, act) +} + +func (b *Bot) showBuy(ctx context.Context, chat int64, act actor) { + if !b.bill.Enabled() { + _, _ = b.send(ctx, chat, 0, b.tr.HTML(act.lang, "buy.unavailable", nil), nil) + return + } + paid := b.cfg.Limits.Paid + rows := b.passButtons(act.lang, func(product string) string { return cbData(cbBuy, product) }) + rows = append(rows, b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks)) + text := b.tr.HTML(act.lang, "buy.intro", i18n.Args{ + "MaxSize": b.tr.Size(act.lang, min64(paid.MaxSizeMB<<20, b.cfg.MaxUploadBytes())), + "MaxDuration": b.tr.Span(act.lang, paid.MaxDuration.D()), + "PerDownload": b.tr.Sats(act.lang, b.cfg.Prices.CreditPerDownload), + }) + _, _ = b.send(ctx, chat, 0, text, keyboard(rows...)) +} + +func min64(a, b int64) int64 { + if b > 0 && (a == 0 || b < a) { + return b + } + return a +} + +func (b *Bot) cmdCredits(ctx context.Context, m *telego.Message, act actor) { + if !b.privateOnly(ctx, m, act) { + return + } + st, err := b.bill.State(ctx, db.OwnerUser, act.user.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + text := b.tr.HTML(act.lang, "credits.text", i18n.Args{ + "Balance": b.tr.Sats(act.lang, st.Credits), + "PerDownload": b.tr.Sats(act.lang, b.cfg.Prices.CreditPerDownload), + }) + var kb *telego.InlineKeyboardMarkup + if b.bill.Enabled() { + kb = keyboard(b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks)) + } + _, _ = b.send(ctx, m.Chat.ID, 0, text, kb) +} + +func (b *Bot) cmdDonate(ctx context.Context, m *telego.Message, act actor) { + if !b.privateOnly(ctx, m, act) { + return + } + if !b.bill.Enabled() { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "buy.unavailable", nil), nil) + return + } + kb := keyboard(b.amountButtons(act.lang, billing.ProductDonation, b.cfg.Prices.DonationAmounts)) + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "donate.intro", nil), kb) +} + +func (b *Bot) cmdAccount(ctx context.Context, m *telego.Message, act actor) { + if !b.privateOnly(ctx, m, act) { + return + } + who := service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type} + st, err := b.bill.State(ctx, db.OwnerUser, act.user.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + dec, err := b.svc.Entitlement(ctx, who, false) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + usage, err := b.svc.Usage(ctx, act.user.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + lang := act.lang + var sb strings.Builder + sb.WriteString(b.tr.HTML(lang, "account.title", nil)) + sb.WriteString("\n") + if st.PassUntil > 0 { + sb.WriteString(b.tr.HTML(lang, "account.pass_active", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(st.PassUntil))})) + } else { + sb.WriteString(b.tr.HTML(lang, "account.pass_none", nil)) + } + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "account.balance", i18n.Args{"Balance": b.tr.Sats(lang, st.Credits)})) + sb.WriteString("\n\n") + sb.WriteString(b.tr.HTML(lang, "account.today", nil)) + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "account.usage_downloads", i18n.Args{ + "Used": b.tr.Number(lang, int64(usage.Downloads)), "Max": b.capNumber(lang, int64(dec.Limits.DailyDownloads)), + })) + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "account.usage_volume", i18n.Args{ + "Used": b.tr.Size(lang, usage.Bytes), "Max": b.capSize(lang, dec.Limits.DailyBytes), + })) + var kb *telego.InlineKeyboardMarkup + if b.bill.Enabled() { + kb = keyboard(b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })...) + } + _, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), kb) +} + +func (b *Bot) capNumber(lang string, n int64) string { + if n <= 0 { + return b.tr.T(lang, "account.unlimited", nil) + } + return b.tr.Number(lang, n) +} + +func (b *Bot) capSize(lang string, n int64) string { + if n <= 0 { + return b.tr.T(lang, "account.unlimited", nil) + } + return b.tr.Size(lang, n) +} + +func (b *Bot) cmdLimits(ctx context.Context, m *telego.Message, act actor) { + who := service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type} + dec, err := b.svc.Entitlement(ctx, who, false) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + lang := act.lang + l := dec.Limits + text := b.tr.HTML(lang, "limits.text", i18n.Args{ + "Tier": b.tr.T(lang, "source."+string(dec.Source), nil), + "MaxSize": b.capSize(lang, l.MaxSize), + "MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)), + "ActiveJobs": b.capNumber(lang, int64(l.ActiveJobs)), + "DailyDownloads": b.capNumber(lang, int64(l.DailyDownloads)), + "DailyVolume": b.capSize(lang, l.DailyBytes), + }) + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, nil) +} + +func (b *Bot) cmdReferral(ctx context.Context, m *telego.Message, act actor) { + if !b.privateOnly(ctx, m, act) { + return + } + n, err := b.store.CountReferrals(ctx, act.user.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + link := "https://t.me/" + b.username + "?start=ref_" + strconv.FormatInt(act.user.ID, 10) + text := b.tr.HTML(act.lang, "referral.text", i18n.Args{ + "Link": link, + "Reward": b.tr.Sats(act.lang, b.cfg.Prices.ReferralReward), + "Count": n, + }) + _, _ = b.send(ctx, m.Chat.ID, 0, text, nil) +} + +func (b *Bot) cmdRedeem(ctx context.Context, m *telego.Message, act actor, arg string) { + if !b.privateOnly(ctx, m, act) { + return + } + lang := act.lang + arg = strings.TrimSpace(arg) + if arg == "" { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.usage", nil), nil) + return + } + if billing.IsCashuToken(arg) { + b.redeemCashu(ctx, m.Chat.ID, act, arg) + return + } + res, err := b.bill.RedeemGift(ctx, act.user.ID, arg) + switch { + case errors.Is(err, billing.ErrGiftInvalid): + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.invalid", nil), nil) + case errors.Is(err, billing.ErrGiftUsed): + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.used", nil), nil) + case err != nil: + b.internalError(ctx, m.Chat.ID, act, err) + case res.Kind == billing.GiftCredits: + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.credits", i18n.Args{"Amount": b.tr.Sats(lang, res.Sats)}), nil) + default: + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.pass", i18n.Args{ + "Until": b.tr.DateTime(lang, time.UnixMilli(res.PassUntil)), + }), nil) + } +} + +func (b *Bot) redeemCashu(ctx context.Context, chat int64, act actor, token string) { + lang := act.lang + if b.cashu == nil { + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.cashu_off", nil), nil) + return + } + sats, err := b.cashu.Redeem(ctx, token) + switch { + case errors.Is(err, billing.ErrCashuMint): + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.cashu_mint", nil), nil) + return + case errors.Is(err, billing.ErrCashuSpent): + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.used", nil), nil) + return + case err != nil: + b.log.Warn("cashu redeem failed", "user_id", act.user.ID, "err", err) + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.invalid", nil), nil) + return + } + w, err := b.bill.Wallet(ctx, db.OwnerUser, act.user.ID) + if err != nil { + b.internalError(ctx, chat, act, err) + return + } + // The mint already paid us, so this credit must not be lost: the dedupe + // key is derived from the token and survives a retry. + if _, err := b.bill.Credit(ctx, w.ID, sats, "cashu", "", "cashu:"+tokenDigest(token), act.user.ID); err != nil { + b.internalError(ctx, chat, act, err) + return + } + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.credits", i18n.Args{"Amount": b.tr.Sats(lang, sats)}), nil) +} + +func (b *Bot) internalError(ctx context.Context, chat int64, act actor, err error) { + b.log.Error("handler failed", "user_id", act.user.ID, "err", err) + _, _ = b.send(ctx, chat, 0, b.tr.HTML(act.lang, "error.internal", nil), nil) +} + +// --- buying ---------------------------------------------------------------- + +// purchaseContext ties a purchase to something that starts once it is paid. +type purchaseContext struct { + requestID string + profile string + deliveryID string +} + +// startPurchase creates the invoice and shows it in the private chat. +func (b *Bot) startPurchase(ctx context.Context, chat int64, act actor, product string, amount int64, pc purchaseContext) { + lang := act.lang + // Callback data comes from the client. Check the product before it is + // used for anything, including a catalog lookup. + if !billing.ValidProduct(product) { + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil) + return + } + w, err := b.bill.Wallet(ctx, db.OwnerUser, act.user.ID) + if err != nil { + b.internalError(ctx, chat, act, err) + return + } + p, err := b.bill.CreatePurchase(ctx, billing.NewPurchase{ + UserID: act.user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang, + Memo: b.tr.T(lang, "invoice.memo", i18n.Args{"Title": b.productTitle(lang, product)}), + RequestID: pc.requestID, Profile: pc.profile, DeliveryID: pc.deliveryID, + }) + switch { + case errors.Is(err, billing.ErrDisabled): + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.unavailable", nil), nil) + return + case errors.Is(err, billing.ErrLightningDown): + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.backend_down", nil), nil) + return + case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct): + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil) + return + case err != nil: + b.internalError(ctx, chat, act, err) + return + } + b.sendInvoice(ctx, chat, p) +} + +// invoiceText is the caption of the invoice message. +func (b *Bot) invoiceText(p *db.Purchase) string { + lang := p.Lang + minutes := b.cfg.LNbits.InvoiceExpiry.D() + return b.tr.HTML(lang, "invoice.caption", i18n.Args{ + "Title": b.productTitle(lang, p.Product), + "Amount": b.tr.Sats(lang, p.AmountSats), + "Invoice": p.Bolt11, + "Valid": b.tr.Span(lang, minutes), + }) +} + +func (b *Bot) invoiceKeyboard(p *db.Purchase) *telego.InlineKeyboardMarkup { + lang := p.Lang + var rows [][]telego.InlineKeyboardButton + // Telegram only accepts http and https in URL buttons, so "open in + // wallet" goes through a small page of ours that forwards to the + // lightning: link. + if b.cfg.PublicURL != "" { + rows = append(rows, []telego.InlineKeyboardButton{ + urlButton(b.tr.T(lang, "btn.open_wallet", nil), b.cfg.PublicURL+"/pay/"+p.ID), + }) + } + rows = append(rows, []telego.InlineKeyboardButton{ + button(b.tr.T(lang, "btn.check_payment", nil), cbData(cbPayCheck, p.ID)), + button(b.tr.T(lang, "btn.cancel", nil), cbData(cbPayCancel, p.ID)), + }) + return keyboard(rows...) +} + +// sendInvoice shows the invoice: a QR code with the BOLT11 string in the +// caption, where a tap copies it. Without a QR (it should not fail) the +// same content goes out as text. +func (b *Bot) sendInvoice(ctx context.Context, chat int64, p *db.Purchase) { + text := b.invoiceText(p) + kb := b.invoiceKeyboard(p) + // Upper case BOLT11 lets the QR code use its compact alphanumeric mode. + png, err := qrcode.Encode(strings.ToUpper(p.Bolt11), qrcode.Medium, 512) + if err == nil { + msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ + ChatID: chatID(chat), + Photo: telego.InputFile{File: namedReader{Reader: strings.NewReader(string(png)), name: "invoice.png"}}, + Caption: clip(text, 1024), + ParseMode: telego.ModeHTML, + ReplyMarkup: kb, + }) + if err == nil { + b.rememberInvoice(ctx, p, chat, int64(msg.MessageID), true) + return + } + b.log.Warn("invoice photo failed, sending text", "purchase_id", p.ID, "err", err) + } + msg, err := b.send(ctx, chat, 0, text, kb) + if err != nil { + return + } + b.rememberInvoice(ctx, p, chat, int64(msg.MessageID), false) +} + +// rememberInvoice saves which message shows an invoice. The invoice can be +// settled, expired or cancelled in the moment between Telegram showing it +// and this save, and the event for that had no message to edit. So after +// saving, the message is brought in line with the purchase once more. +func (b *Bot) rememberInvoice(ctx context.Context, p *db.Purchase, chat, messageID int64, isPhoto bool) { + // Saved even during shutdown, or a restart could never edit it. + if err := b.store.SetPurchaseMessage(context.WithoutCancel(ctx), p.ID, chat, messageID, isPhoto); err != nil { + b.log.Error("save invoice message", "purchase_id", p.ID, "err", err) + return + } + cur, err := b.store.GetPurchase(ctx, p.ID) + if err != nil || cur.Status == db.PurchasePending { + return + } + b.showPurchaseState(ctx, cur) +} + +// showPurchaseState makes the invoice message reflect a closed purchase. +func (b *Bot) showPurchaseState(ctx context.Context, p *db.Purchase) { + if p.MessageID == 0 { + return // not shown yet; rememberInvoice catches up + } + lang := p.Lang + switch p.Status { + case db.PurchasePaid: + _ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.paidText(ctx, p), nil) + case db.PurchaseExpired: + _ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.tr.HTML(lang, "invoice.expired", i18n.Args{ + "Title": b.productTitle(lang, p.Product), + }), nil) + case db.PurchaseCancelled: + if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(p.ChatID), MessageID: int(p.MessageID)}); err != nil { + _ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.tr.HTML(lang, "invoice.cancelled", nil), nil) + } + } +} + +// cbBuyProduct handles the product buttons of /buy, /credits and /donate. +func (b *Bot) cbBuyProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, amountArg string) { + b.answer(ctx, q, "", false) + amount, _ := strconv.ParseInt(amountArg, 10, 64) + b.startPurchase(ctx, act.user.ID, act, product, amount, purchaseContext{}) +} + +// cbOffer handles the buttons of an over-limit offer: buy something and +// then start the download it was offered for. +func (b *Bot) cbOffer(ctx context.Context, q *telego.CallbackQuery, act actor, product, rest string) { + requestID, profileArg, _ := strings.Cut(rest, ":") + req, err := b.store.GetRequest(ctx, requestID) + if err != nil || req.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + profile, perr := media.Parse(profileArg) + info, ierr := service.ParseCardInfo(req.Info) + if perr != nil || ierr != nil || req.Status != db.RequestReady { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + var amount int64 + if product == billing.ProductOneOff { + amount = b.cfg.Prices.OneOffPrice(info.Sizes[string(profile)]) + } + b.startPurchase(ctx, act.user.ID, act, product, amount, purchaseContext{requestID: req.ID, profile: string(profile)}) +} + +func (b *Bot) cbPayCheck(ctx context.Context, q *telego.CallbackQuery, act actor, purchaseID string) { + p, err := b.bill.Check(ctx, purchaseID, act.user.ID) + switch { + case errors.Is(err, billing.ErrLightningDown): + b.answer(ctx, q, b.tr.T(act.lang, "buy.backend_down_short", nil), true) + case err != nil: + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + case p.Status == db.PurchasePaid: + // The paid event edits the message; this only closes the spinner. + b.answer(ctx, q, b.tr.T(act.lang, "notice.paid", nil), false) + case p.Status == db.PurchasePending: + b.answer(ctx, q, b.tr.T(act.lang, "notice.not_paid_yet", nil), false) + default: + b.answer(ctx, q, b.tr.T(act.lang, "notice.invoice_closed", nil), false) + } +} + +func (b *Bot) cbPayCancel(ctx context.Context, q *telego.CallbackQuery, act actor, purchaseID string) { + if _, err := b.bill.Cancel(ctx, purchaseID, act.user.ID); err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false) +} + +// --- payment events -------------------------------------------------------- + +func (b *Bot) handlePayEvent(ctx context.Context, ev billing.Event) { + // The event carries the purchase as it was inside the transaction. + // Read it again: the invoice message may have been saved since. + p, err := b.store.GetPurchase(ctx, ev.Purchase.ID) + if err != nil { + b.log.Error("load purchase for event", "purchase_id", ev.Purchase.ID, "err", err) + return + } + b.showPurchaseState(ctx, p) + if ev.Type == billing.EventPaid { + if p.MessageID == 0 { + b.goBG("confirm-payment", func() { b.confirmWithoutInvoice(ctx, p.ID) }) + } + b.fulfil(ctx, p) + } +} + +// confirmWithoutInvoice tells a payer that their payment arrived when the +// invoice message is unknown. Normally the message is saved a moment after +// it is sent and rememberInvoice updates it. If the core stopped exactly in +// between, nothing would ever confirm the payment, so after a short wait a +// new message does. +func (b *Bot) confirmWithoutInvoice(ctx context.Context, purchaseID string) { + sleepCtx(ctx, b.invoiceGrace) + p, err := b.store.GetPurchase(ctx, purchaseID) + if err != nil || p.MessageID != 0 || p.Status != db.PurchasePaid { + return + } + msg, err := b.send(ctx, p.UserID, 0, b.paidText(ctx, p), nil) + if err != nil { + return + } + if err := b.store.SetPurchaseMessage(context.WithoutCancel(ctx), p.ID, p.UserID, int64(msg.MessageID), false); err != nil { + b.log.Error("save payment confirmation", "purchase_id", p.ID, "err", err) + } +} + +// paidText is what the invoice message becomes once it is settled. +func (b *Bot) paidText(ctx context.Context, p *db.Purchase) string { + lang := p.Lang + text := b.tr.HTML(lang, "invoice.paid", i18n.Args{ + "Title": b.productTitle(lang, p.Product), + "Amount": b.tr.Sats(lang, p.AmountSats), + }) + w, err := b.store.GetWallet(ctx, p.WalletID) + if err != nil { + return text + } + switch p.Product { + case billing.ProductCredits: + text += "\n" + b.tr.HTML(lang, "invoice.balance", i18n.Args{"Balance": b.tr.Sats(lang, w.Balance)}) + case billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth: + if until, err := b.store.PassUntil(ctx, w.ID, db.NowMilli()); err == nil && until > 0 { + text += "\n" + b.tr.HTML(lang, "invoice.pass_until", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(until))}) + } + case billing.ProductDonation: + text += "\n" + b.tr.HTML(lang, "invoice.thanks", nil) + } + return text +} + +// fulfilPending runs the follow-up of paid purchases that never got one, +// for example because the core stopped right after the payment arrived. +func (b *Bot) fulfilPending(ctx context.Context) { + list, err := b.store.UnfulfilledPaidPurchases(ctx, 100) + if err != nil { + b.log.Error("list unfulfilled purchases", "err", err) + return + } + for _, p := range list { + b.fulfil(ctx, p) + } +} + +// fulfil starts what a paid purchase was for: the download behind an +// over-limit offer, or the promotion of a waiting job. Every step is +// idempotent, and the purchase is marked fulfilled only at the end, so an +// interruption repeats the follow-up instead of losing it. When the thing +// that was paid for is no longer possible, the payment becomes credits. +func (b *Bot) fulfil(ctx context.Context, p *db.Purchase) { + cur, err := b.store.GetPurchase(ctx, p.ID) + if err != nil || cur.Fulfilled || cur.Status != db.PurchasePaid { + return + } + p = cur + done := true + switch { + case p.DeliveryID != "": + done = b.fulfilSkip(ctx, p) + case p.RequestID != "": + done = b.fulfilDownload(ctx, p) + } + if !done { + return // a transient error; the reconcile loop tries again + } + if _, err := b.store.MarkPurchaseFulfilled(ctx, p.ID); err != nil { + b.log.Error("mark purchase fulfilled", "purchase_id", p.ID, "err", err) + } +} + +func (b *Bot) fulfilSkip(ctx context.Context, p *db.Purchase) bool { + d, err := b.store.GetDelivery(ctx, p.DeliveryID) + if err == nil { + job, jerr := b.store.GetJob(ctx, d.JobID) + if jerr == nil { + if job.Lane == db.LanePaid && job.Active() { + return true // already promoted by an earlier attempt + } + promoted, perr := b.sched.Promote(ctx, job.ID) + if perr != nil { + b.log.Error("promote job", "job_id", job.ID, "err", perr) + return false + } + if promoted { + b.refreshStatus(ctx, job.ID) + return true + } + } + } + // The job started or finished before the payment arrived. + return b.convertToCredits(ctx, p, "pay.too_late_skip") +} + +func (b *Bot) fulfilDownload(ctx context.Context, p *db.Purchase) bool { + oneOff := p.Product == billing.ProductOneOff + fallback := func() bool { + if oneOff { + return b.convertToCredits(ctx, p, "pay.too_late_file") + } + return true // a pass or credits were granted, nothing is owed + } + req, err := b.store.GetRequest(ctx, p.RequestID) + if err != nil { + return fallback() + } + // An earlier attempt may have started the job already. + if n, err := b.store.CountDeliveriesForRequest(ctx, req.ID); err != nil { + return false + } else if n > 0 { + return true + } + profile, perr := media.Parse(p.Profile) + info, ierr := service.ParseCardInfo(req.Info) + if perr != nil || ierr != nil { + return fallback() + } + took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen) + if err != nil { + return false + } + if !took { + return fallback() + } + sp := service.StartParams{ + Request: req, Info: info, Profile: profile, + StatusMessageID: req.CardMessageID, StatusIsPhoto: req.CardIsPhoto, + ReplyToMessageID: req.SourceMessageID, + } + if oneOff { + sp.OneOff = p + } + job, _, err := b.svc.Start(ctx, sp) + if err != nil { + if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil { + b.log.Error("release request", "request_id", req.ID, "err", rerr) + } + var le *service.LimitError + if !errors.As(err, &le) { + b.log.Error("start paid download", "purchase_id", p.ID, "err", err) + return false + } + // Even paid limits refuse it (for example one job too many). + _, _ = b.send(ctx, p.ChatID, 0, b.tr.HTML(p.Lang, "pay.not_started", i18n.Args{"Reason": b.limitText(p.Lang, le)}), nil) + return fallback() + } + b.refreshStatus(ctx, job.ID) + return true +} + +// convertToCredits turns a payment whose purpose is gone into credits and +// tells the payer. +func (b *Bot) convertToCredits(ctx context.Context, p *db.Purchase, key string) bool { + if _, err := b.bill.ConvertToCredits(ctx, p); err != nil { + b.log.Error("convert purchase to credits", "purchase_id", p.ID, "err", err) + return false + } + _, _ = b.send(ctx, p.ChatID, 0, b.tr.HTML(p.Lang, key, i18n.Args{"Amount": b.tr.Sats(p.Lang, p.AmountSats)}), nil) + return true +} + +// --- over-limit offer -------------------------------------------------------- + +// encodeProfile makes a profile safe for a /start parameter, which only +// allows letters, digits, "_" and "-". +func encodeProfile(p string) string { return strings.ReplaceAll(p, ":", "--") } + +func decodeProfile(s string) string { return strings.Replace(s, "--", ":", 1) } + +// offerUpgrade shows what the requester can buy to get a refused download. +// In a private chat the buttons create invoices. In a group they are deep +// links into the private chat, because invoices are personal. +func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string, req *db.Request, profile media.Profile, le *service.LimitError, private bool) { + text := b.limitText(lang, le) + "\n\n" + b.tr.HTML(lang, "over.options", nil) + var rows [][]telego.InlineKeyboardButton + if private { + rows = b.passButtons(lang, func(product string) string { + return cbData(cbOfferBuy, product, req.ID, string(profile)) + }) + if le.Code == service.LimitTooLarge || le.Code == service.LimitTooLong { + price := b.cfg.Prices.OneOffPrice(le.Size) + rows = append(rows, []telego.InlineKeyboardButton{ + button(b.priced(lang, b.tr.T(lang, "btn.this_file", nil), price), + cbData(cbOfferBuy, billing.ProductOneOff, req.ID, string(profile))), + }) + } + } else { + link := "https://t.me/" + b.username + "?start=buy_" + req.ID + "_" + encodeProfile(string(profile)) + rows = append(rows, []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.buy_for_me", nil), link)}) + } + _, _ = b.send(ctx, chat, replyTo, text, keyboard(rows...)) +} + +// startBuyLink handles /start buy__, the deep link from +// a group offer. It shows the same offer in private, or starts the +// download right away when the requester's limits now allow it. +func (b *Bot) startBuyLink(ctx context.Context, m *telego.Message, act actor, payload string) { + requestID, profileArg, _ := strings.Cut(payload, "_") + req, err := b.store.GetRequest(ctx, requestID) + profile, perr := media.Parse(decodeProfile(profileArg)) + if err != nil || perr != nil || req.UserID != act.user.ID || req.Status != db.RequestReady { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil) + return + } + info, err := service.ParseCardInfo(req.Info) + if err != nil { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil) + return + } + who := service.Who{UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType} + err = b.svc.Preview(ctx, who, info, profile) + var le *service.LimitError + switch { + case err == nil: + // They bought something in the meantime: just start it. + if b.startFromRequest(ctx, req, info, profile, nil) == nil { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "over.started", nil), nil) + } + case errors.As(err, &le) && le.Upgradable: + b.offerUpgrade(ctx, m.Chat.ID, 0, act.lang, req, profile, le, true) + case errors.As(err, &le): + _, _ = b.send(ctx, m.Chat.ID, 0, b.limitText(act.lang, le), nil) + default: + b.internalError(ctx, m.Chat.ID, act, err) + } +} + +// startFromRequest takes a ready request and starts its download, using +// the card as the status message. +func (b *Bot) startFromRequest(ctx context.Context, req *db.Request, info *service.CardInfo, profile media.Profile, oneOff *db.Purchase) error { + took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen) + if err != nil { + return err + } + if !took { + return errors.New("bot: request is no longer ready") + } + job, _, err := b.svc.Start(ctx, service.StartParams{ + Request: req, Info: info, Profile: profile, + StatusMessageID: req.CardMessageID, StatusIsPhoto: req.CardIsPhoto, + ReplyToMessageID: req.SourceMessageID, OneOff: oneOff, + }) + if err != nil { + if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil { + b.log.Error("release request", "request_id", req.ID, "err", rerr) + } + return err + } + b.refreshStatus(ctx, job.ID) + return nil +} + +// --- skip the queue -------------------------------------------------------- + +// cbSkip handles "Skip the queue" on a waiting job. Credits pay at once. +// Without enough credits an invoice is created, in the private chat. +func (b *Bot) cbSkip(ctx context.Context, q *telego.CallbackQuery, act actor, deliveryID string) { + lang := act.lang + d, err := b.store.GetDelivery(ctx, deliveryID) + if err != nil { + b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false) + return + } + if d.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(lang, "notice.not_yours", nil), false) + return + } + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil || job.Status != db.JobQueued || job.Lane != db.LaneFree { + b.answer(ctx, q, b.tr.T(lang, "notice.skip_too_late", nil), false) + return + } + price := b.cfg.Prices.SkipQueue + if b.skipWithCredits(ctx, act, d, job, price) { + b.answer(ctx, q, b.tr.T(lang, "notice.skipped", nil), false) + b.refreshStatus(ctx, job.ID) + return + } + if q.Message != nil && !isPrivate(q.Message.GetChat().Type) { + // Send the requester to the private chat, where the invoice goes. + err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{ + CallbackQueryID: q.ID, URL: "https://t.me/" + b.username + "?start=skip_" + d.ID, + }) + if err != nil { + b.answer(ctx, q, b.tr.T(lang, "notice.skip_private", nil), true) + } + return + } + b.answer(ctx, q, "", false) + b.startPurchase(ctx, act.user.ID, act, billing.ProductSkipQueue, 0, purchaseContext{deliveryID: d.ID}) +} + +// skipWithCredits pays for the promotion from the requester's balance. It +// reports false when the balance does not cover it. +func (b *Bot) skipWithCredits(ctx context.Context, act actor, d *db.Delivery, job *db.Job, price int64) bool { + st, err := b.bill.State(ctx, db.OwnerUser, act.user.ID) + if err != nil || st.ID == "" || st.Credits < price { + return false + } + applied, err := b.bill.Debit(ctx, st.ID, price, "skip_queue", d.ID, "skip:"+d.ID, act.user.ID) + if err != nil || !applied { + return false + } + promoted, err := b.sched.Promote(ctx, job.ID) + if err != nil || !promoted { + // The job got a worker in the meantime: give the sats back. + if _, rerr := b.bill.Refund(ctx, st.ID, price, "skip_queue_refund", d.ID, "skip-refund:"+d.ID, 0); rerr != nil { + b.log.Error("refund skip", "delivery_id", d.ID, "err", rerr) + } + return false + } + return true +} + +// startSkipLink handles /start skip_, the deep link from a group. +func (b *Bot) startSkipLink(ctx context.Context, m *telego.Message, act actor, deliveryID string) { + d, err := b.store.GetDelivery(ctx, deliveryID) + if err != nil || d.UserID != act.user.ID { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil) + return + } + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil || job.Status != db.JobQueued || job.Lane != db.LaneFree { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "pay.skip_not_needed", nil), nil) + return + } + b.startPurchase(ctx, m.Chat.ID, act, billing.ProductSkipQueue, 0, purchaseContext{deliveryID: d.ID}) +} + +// sourceLabel names what paid for a download, for status lines. +func (b *Bot) sourceLabel(lang string, src entitle.Source) string { + return b.tr.T(lang, "source."+string(src), nil) +} diff --git a/internal/bot/ratelimit.go b/internal/bot/ratelimit.go new file mode 100644 index 0000000..62a747e --- /dev/null +++ b/internal/bot/ratelimit.go @@ -0,0 +1,60 @@ +package bot + +import ( + "crypto/sha256" + "encoding/hex" + "strings" + "sync" + "time" +) + +// rateLimiter is a sliding window counter per key. It lives in memory: a +// restart forgets it, which is fine for a limit measured in a minute. +type rateLimiter struct { + mu sync.Mutex + hits map[string][]time.Time + now func() time.Time +} + +func newRateLimiter() *rateLimiter { + return &rateLimiter{hits: map[string][]time.Time{}, now: time.Now} +} + +// allow records a hit for key and reports whether it stays within limit +// hits per window. A limit of 0 or less allows everything. +func (r *rateLimiter) allow(key string, limit int, window time.Duration) bool { + if limit <= 0 { + return true + } + now := r.now() + cut := now.Add(-window) + r.mu.Lock() + defer r.mu.Unlock() + kept := r.hits[key][:0] + for _, t := range r.hits[key] { + if t.After(cut) { + kept = append(kept, t) + } + } + if len(kept) >= limit { + r.hits[key] = kept + return false + } + r.hits[key] = append(kept, now) + // Keep the map from growing without bound. + if len(r.hits) > 50_000 { + for k, v := range r.hits { + if len(v) == 0 || !v[len(v)-1].After(cut) { + delete(r.hits, k) + } + } + } + return true +} + +// tokenDigest returns a stable fingerprint of a bearer token, so the token +// itself is never stored or logged. +func tokenDigest(token string) string { + sum := sha256.Sum256([]byte(strings.TrimSpace(token))) + return hex.EncodeToString(sum[:16]) +} diff --git a/internal/bot/status.go b/internal/bot/status.go index 2653adf..ee3e2e6 100644 --- a/internal/bot/status.go +++ b/internal/bot/status.go @@ -2,6 +2,7 @@ package bot import ( "context" + "strings" "time" "github.com/mymmrac/telego" @@ -16,9 +17,27 @@ import ( // statusState remembers what a status message shows, so edits that would // change nothing or come too fast are skipped. type statusState struct { - text string - phase string - at time.Time + text string + buttons string + phase string + at time.Time +} + +// keyboardSignature identifies a keyboard by the callback data and links +// of its buttons. +func keyboardSignature(kb *telego.InlineKeyboardMarkup) string { + if kb == nil { + return "" + } + var sb strings.Builder + for _, row := range kb.InlineKeyboard { + for _, btn := range row { + sb.WriteString(btn.CallbackData) + sb.WriteString(btn.URL) + sb.WriteByte('|') + } + } + return sb.String() } // eventLoop reacts to job events and periodically reconciles, which covers @@ -33,6 +52,8 @@ func (b *Bot) eventLoop(ctx context.Context) { return case ev := <-b.events: b.safely("event", func() { b.handleEvent(ctx, ev) }) + case ev := <-b.payEvents: + b.safely("payment", func() { b.handlePayEvent(ctx, ev) }) case <-t.C: b.safely("reconcile", func() { b.reconcile(ctx) }) } @@ -84,6 +105,10 @@ func (b *Bot) reconcile(ctx context.Context) { each(db.JobQueued, func(id string) { b.refreshStatus(ctx, id) }) each(db.JobRunning, func(id string) { b.refreshStatus(ctx, id) }) + // Refunds and paid follow-ups that an interruption left undone. + b.svc.ReleasePending(ctx) + b.fulfilPending(ctx) + // Jobs whose requesters were all served but that were never closed. delivering, err := b.store.JobsByStatus(ctx, db.JobDelivering, 200) if err != nil { @@ -128,6 +153,10 @@ func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (te cancel := b.cancelJobKeyboard(lang, d.ID) switch job.Status { case db.JobQueued: + kb := cancel + if job.Lane == db.LaneFree && b.bill.Enabled() && b.cfg.Prices.SkipQueue > 0 { + kb = b.queuedKeyboard(lang, d.ID) + } pos, err := b.sched.Position(ctx, job, b.slots()) if err != nil { b.log.Error("queue position", "job_id", job.ID, "err", err) @@ -135,7 +164,7 @@ func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (te return head + b.tr.HTML(lang, "status.queued", i18n.Args{ "Position": pos.Ahead + 1, "Wait": b.tr.Span(lang, pos.Wait), - }), cancel, "queued" + }), kb, "queued" case db.JobRunning: switch job.Stage { case ytdlp.StageProcessing: @@ -185,15 +214,19 @@ func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *te return } now := time.Now() + // What the message shows is its text and its buttons. A change in + // either is worth an edit, for example "Skip the queue" disappearing. + shown := text + "\x00" + keyboardSignature(kb) b.statusMu.Lock() st := b.statuses[d.ID] if st != nil { - if st.text == text || (!force && st.phase == phase && now.Sub(st.at) < b.statusMinGap) { + sameButtons := keyboardSignature(kb) == st.buttons + if st.text == shown || (!force && sameButtons && st.phase == phase && now.Sub(st.at) < b.statusMinGap) { b.statusMu.Unlock() return } } - b.statuses[d.ID] = &statusState{text: text, phase: phase, at: now} + b.statuses[d.ID] = &statusState{text: shown, buttons: keyboardSignature(kb), phase: phase, at: now} b.statusMu.Unlock() if err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, kb); err != nil { diff --git a/internal/config/config.go b/internal/config/config.go index 913e8e1..f6968a6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -43,8 +43,16 @@ type Config struct { Worker Worker `toml:"worker"` Queue Queue `toml:"queue"` Limits Limits `toml:"limits"` + LNbits LNbits `toml:"lnbits"` + Prices Prices `toml:"prices"` + Rate Rate `toml:"rate"` Log Log `toml:"log"` + // PublicURL is the HTTPS base URL this server is reachable at from the + // internet, without a trailing slash. It is used for payment webhooks, + // "open in wallet" links and the Mini App. + PublicURL string `toml:"public_url" env:"PUBLIC_URL"` + // Owners are the Telegram user IDs allowed to use owner commands. Owners []int64 `toml:"owners" env:"OWNER_IDS"` } @@ -113,16 +121,72 @@ type Queue struct { MaxAttempts int `toml:"max_attempts" env:"QUEUE_MAX_ATTEMPTS"` } -// Tier is one set of per-download limits. +// Tier is one set of limits. type Tier struct { MaxSizeMB int64 `toml:"max_size_mb"` MaxDuration Duration `toml:"max_duration"` ActiveJobs int `toml:"active_jobs"` + // DailyDownloads is the number of downloads per UTC day, 0 for no cap. + DailyDownloads int `toml:"daily_downloads"` + // DailyMB is the volume per UTC day in MB, 0 for no cap. It applies to + // paid users too, as a guard against abuse. + DailyMB int64 `toml:"daily_mb"` } -// Limits holds the per-tier limits. +// Limits holds the per-tier limits. Free applies to everyone without a +// paid entitlement. Paid applies to passes, credits and one-off payments. type Limits struct { Free Tier `toml:"free"` + Paid Tier `toml:"paid"` +} + +// LNbits holds the Lightning payment backend settings. Payments are +// enabled when both URL and InvoiceKey are set. +type LNbits struct { + URL string `toml:"url" env:"LNBITS_URL"` + // InvoiceKey is the wallet's invoice (read) key. The admin key is never + // needed and must not be given to the bot. + InvoiceKey string `toml:"invoice_key" env:"LNBITS_INVOICE_KEY"` + // WebhookSecret is a random string that becomes part of the webhook + // path, so only LNbits knows where to post. + WebhookSecret string `toml:"webhook_secret" env:"LNBITS_WEBHOOK_SECRET"` + // PollInterval is how often unsettled invoices are checked as a + // fallback for lost webhooks. + PollInterval Duration `toml:"poll_interval" env:"LNBITS_POLL_INTERVAL"` + // InvoiceExpiry is how long an invoice can be paid. + InvoiceExpiry Duration `toml:"invoice_expiry" env:"INVOICE_EXPIRY"` +} + +// Enabled reports whether payments are configured. +func (l LNbits) Enabled() bool { return l.URL != "" && l.InvoiceKey != "" } + +// Prices holds every price in sats. Nothing is hardcoded elsewhere. +type Prices struct { + PassDay int64 `toml:"pass_day" env:"PRICE_PASS_DAY"` + PassWeek int64 `toml:"pass_week" env:"PRICE_PASS_WEEK"` + PassMonth int64 `toml:"pass_month" env:"PRICE_PASS_MONTH"` + // CreditPerDownload is what one download costs when credits pay. + CreditPerDownload int64 `toml:"credit_per_download" env:"PRICE_CREDIT_DOWNLOAD"` + // OneOff is base plus a step per started 100 MB. + OneOffBase int64 `toml:"one_off_base" env:"PRICE_ONE_OFF_BASE"` + OneOffPer100MB int64 `toml:"one_off_per_100mb" env:"PRICE_ONE_OFF_PER_100MB"` + // SkipQueue moves one waiting free job to the paid lane. + SkipQueue int64 `toml:"skip_queue" env:"PRICE_SKIP_QUEUE"` + // CreditPacks are the top-up amounts offered. + CreditPacks []int64 `toml:"credit_packs" env:"CREDIT_PACKS"` + // DonationAmounts are the tip amounts offered by /donate. + DonationAmounts []int64 `toml:"donation_amounts" env:"DONATION_AMOUNTS"` + // ReferralReward is credited to the inviter when an invited user makes + // a first purchase. 0 turns the reward off. + ReferralReward int64 `toml:"referral_reward" env:"REFERRAL_REWARD"` +} + +// Rate holds the request rate limits. +type Rate struct { + // UserPerMinute is how many links one user may send per minute. + UserPerMinute int `toml:"user_per_minute" env:"RATE_USER_PER_MINUTE"` + // GroupPerMinute is how many links one group may send per minute. + GroupPerMinute int `toml:"group_per_minute" env:"RATE_GROUP_PER_MINUTE"` } // Log holds logging settings. @@ -162,9 +226,26 @@ func Default() Config { MaxAttempts: 2, }, Limits: Limits{ - Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1}, + Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1, + DailyDownloads: 5, DailyMB: 250}, + Paid: Tier{MaxSizeMB: 2000, MaxDuration: Duration(3 * time.Hour), ActiveJobs: 3, + DailyDownloads: 100, DailyMB: 20000}, }, - Log: Log{Level: "info", Format: "json"}, + LNbits: LNbits{ + PollInterval: Duration(5 * time.Second), + InvoiceExpiry: Duration(10 * time.Minute), + }, + Prices: Prices{ + PassDay: 700, PassWeek: 3000, PassMonth: 9000, + CreditPerDownload: 50, + OneOffBase: 100, OneOffPer100MB: 50, + SkipQueue: 50, + CreditPacks: []int64{1000, 5000, 20000}, + DonationAmounts: []int64{500, 2100, 10000}, + ReferralReward: 200, + }, + Rate: Rate{UserPerMinute: 10, GroupPerMinute: 30}, + Log: Log{Level: "info", Format: "json"}, } } @@ -199,6 +280,11 @@ func Load(path string) (Config, error) { if err := applyTierEnv("FREE", &cfg.Limits.Free, os.LookupEnv); err != nil { return cfg, err } + if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil { + return cfg, err + } + cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/") + cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/") return cfg, cfg.Validate() } @@ -236,6 +322,25 @@ func (c Config) Validate() error { if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() { errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE") } + if (c.LNbits.URL == "") != (c.LNbits.InvoiceKey == "") { + errs = append(errs, "LNBITS_URL and LNBITS_INVOICE_KEY must be set together") + } + if c.LNbits.Enabled() { + if c.LNbits.InvoiceExpiry.D() < time.Minute { + errs = append(errs, "INVOICE_EXPIRY must be at least 1m") + } + if c.LNbits.PollInterval.D() <= 0 { + errs = append(errs, "LNBITS_POLL_INTERVAL must be positive") + } + for name, v := range map[string]int64{ + "PRICE_PASS_DAY": c.Prices.PassDay, "PRICE_PASS_WEEK": c.Prices.PassWeek, + "PRICE_PASS_MONTH": c.Prices.PassMonth, "PRICE_CREDIT_DOWNLOAD": c.Prices.CreditPerDownload, + } { + if v <= 0 { + errs = append(errs, name+" must be positive") + } + } + } if len(errs) > 0 { return errors.New("config: " + strings.Join(errs, "; ")) } @@ -275,9 +380,47 @@ func applyTierEnv(prefix string, t *Tier, lookup func(string) (string, bool)) er } t.ActiveJobs = n } + if v, ok := lookup(prefix + "_DAILY_DOWNLOADS"); ok && v != "" { + n, err := strconv.Atoi(v) + if err != nil { + return fmt.Errorf("config: %s_DAILY_DOWNLOADS: %w", prefix, err) + } + t.DailyDownloads = n + } + if v, ok := lookup(prefix + "_DAILY_MB"); ok && v != "" { + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return fmt.Errorf("config: %s_DAILY_MB: %w", prefix, err) + } + t.DailyMB = n + } return nil } +// PassPrice returns the price of a pass kind ("day", "week", "month"). +func (p Prices) PassPrice(kind string) int64 { + switch kind { + case "day": + return p.PassDay + case "week": + return p.PassWeek + case "month": + return p.PassMonth + } + return 0 +} + +// OneOffPrice returns the price of a single download of the given size. +// An unknown size is priced as 200 MB. +func (p Prices) OneOffPrice(sizeBytes int64) int64 { + const step = 100 << 20 + if sizeBytes <= 0 { + sizeBytes = 2 * step + } + steps := (sizeBytes + step - 1) / step + return p.OneOffBase + steps*p.OneOffPer100MB +} + var durationType = reflect.TypeOf(Duration(0)) // applyEnv walks the struct and overrides every field that has an env tag diff --git a/internal/config/config_test.go b/internal/config/config_test.go index e09b18b..0fccd70 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -83,6 +83,81 @@ func TestApplyEnvRejectsBadValues(t *testing.T) { } } +func TestMoneyDefaultsAndValidation(t *testing.T) { + cfg := Default() + cfg.Telegram.Token = "x" + p := cfg.Prices + if p.PassDay != 700 || p.PassWeek != 3000 || p.PassMonth != 9000 { + t.Fatalf("pass prices changed: %+v", p) + } + if cfg.Limits.Free.DailyDownloads != 5 || cfg.Limits.Paid.MaxSizeMB != 2000 || + cfg.Limits.Paid.MaxDuration.D() != 3*time.Hour || cfg.Limits.Paid.ActiveJobs != 3 { + t.Fatalf("tier defaults changed: %+v", cfg.Limits) + } + if cfg.LNbits.Enabled() { + t.Fatal("payments must be off until LNbits is configured") + } + if err := cfg.Validate(); err != nil { + t.Fatalf("a config without payments must validate: %v", err) + } + + // One of the two LNbits settings alone is a mistake. + cfg.LNbits.URL = "https://lnbits.example.com" + if err := cfg.Validate(); err == nil { + t.Fatal("LNBITS_URL without a key must be rejected") + } + cfg.LNbits.InvoiceKey = "key" + if err := cfg.Validate(); err != nil || !cfg.LNbits.Enabled() { + t.Fatalf("complete LNbits settings: %v", err) + } + cfg.Prices.PassDay = 0 + if err := cfg.Validate(); err == nil { + t.Fatal("a zero pass price must be rejected when payments are on") + } + cfg.Prices.PassDay = 700 + cfg.LNbits.InvoiceExpiry = Duration(10 * time.Second) + if err := cfg.Validate(); err == nil { + t.Fatal("an invoice expiry under a minute must be rejected") + } + + // One-off pricing: base plus one step per started 100 MB. + prices := map[int64]int64{ + 0: 200, // unknown size is priced as 200 MB + 1: 150, + 100 << 20: 150, + 101 << 20: 200, + 1 << 30: 100 + 11*50, + } + for size, want := range prices { + if got := p.OneOffPrice(size); got != want { + t.Errorf("OneOffPrice(%d) = %d, want %d", size, got, want) + } + } + if p.PassPrice("week") != 3000 || p.PassPrice("decade") != 0 { + t.Fatal("PassPrice is wrong") + } +} + +func TestMoneyEnv(t *testing.T) { + cfg := Default() + env := map[string]string{ + "PRICE_PASS_DAY": "1000", "CREDIT_PACKS": "100, 200", "LNBITS_URL": "https://ln.example.com/", + "RATE_USER_PER_MINUTE": "3", "PUBLIC_URL": "https://bot.example.com/", + } + if err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(env)); err != nil { + t.Fatal(err) + } + if cfg.Prices.PassDay != 1000 || !reflect.DeepEqual(cfg.Prices.CreditPacks, []int64{100, 200}) || + cfg.Rate.UserPerMinute != 3 || cfg.LNbits.URL != "https://ln.example.com/" { + t.Fatalf("env not applied: %+v %+v", cfg.Prices, cfg.Rate) + } + if err := applyTierEnv("PAID", &cfg.Limits.Paid, lookup(map[string]string{ + "PAID_DAILY_DOWNLOADS": "7", "PAID_DAILY_MB": "9", + })); err != nil || cfg.Limits.Paid.DailyDownloads != 7 || cfg.Limits.Paid.DailyMB != 9 { + t.Fatalf("paid tier env: %+v, %v", cfg.Limits.Paid, err) + } +} + func TestValidate(t *testing.T) { bad := []func(*Config){ func(c *Config) { c.Telegram.Mode = "carrier-pigeon" }, diff --git a/internal/db/deliveries.go b/internal/db/deliveries.go index 8175829..99eed28 100644 --- a/internal/db/deliveries.go +++ b/internal/db/deliveries.go @@ -7,13 +7,13 @@ import ( const deliveryCols = `id, job_id, request_id, user_id, chat_id, chat_type, reply_to_message_id, status_message_id, status_is_photo, lang, status, attempts, error_code, tg_file_id, - tg_message_id, created_at, updated_at` + tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released` func scanDelivery(sc interface{ Scan(...any) error }) (*Delivery, error) { var d Delivery err := sc.Scan(&d.ID, &d.JobID, &d.RequestID, &d.UserID, &d.ChatID, &d.ChatType, &d.ReplyToMessageID, &d.StatusMessageID, &d.StatusIsPhoto, &d.Lang, &d.Status, &d.Attempts, &d.ErrorCode, &d.TgFileID, - &d.TgMessageID, &d.CreatedAt, &d.UpdatedAt) + &d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released) if err != nil { return nil, notFound(err) } @@ -42,11 +42,14 @@ func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error { d.CreatedAt = NowMilli() } d.UpdatedAt = d.CreatedAt + if d.Source == "" { + d.Source = "free" + } _, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, d.ID, d.JobID, d.RequestID, d.UserID, d.ChatID, d.ChatType, d.ReplyToMessageID, d.StatusMessageID, d.StatusIsPhoto, d.Lang, d.Status, d.Attempts, d.ErrorCode, d.TgFileID, - d.TgMessageID, d.CreatedAt, d.UpdatedAt) + d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released) return err } @@ -135,3 +138,27 @@ func (s *Store) PendingDeliveryJobIDs(ctx context.Context, jobStatus string, lim } return out, rows.Err() } + +// MarkDeliveryReleased flags a delivery as refunded and reports whether +// this call was the one that flagged it. It is the idempotency guard for +// giving back a charge and a quota slot. +func (s *Store) MarkDeliveryReleased(ctx context.Context, id string) (bool, error) { + n, err := s.exec(ctx, `UPDATE deliveries SET released = ?, updated_at = ? WHERE id = ? AND released = ?`, + true, NowMilli(), id, false) + return n == 1, err +} + +// UnreleasedDeliveries lists deliveries that ended without a file and have +// not been refunded yet. It is the safety net behind the refund events. +func (s *Store) UnreleasedDeliveries(ctx context.Context, limit int) ([]*Delivery, error) { + return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries + WHERE status IN ('failed', 'cancelled') AND released = ? + AND (charge_sats > 0 OR quota_day > 0) ORDER BY id LIMIT ?`, false, limit)) +} + +// CountDeliveriesForRequest counts the deliveries created from a request. +func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string) (int, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE request_id = ?`, requestID).Scan(&n) + return n, err +} diff --git a/internal/db/jobs.go b/internal/db/jobs.go index 920cdb6..8e40ac7 100644 --- a/internal/db/jobs.go +++ b/internal/db/jobs.go @@ -213,3 +213,30 @@ func (s *Store) CountRunning(ctx context.Context) (int, error) { err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'running'`).Scan(&n) return n, err } + +// CountRunningByLane counts running jobs, in total and in the free lane. +func (s *Store) CountRunningByLane(ctx context.Context) (total, free int, err error) { + rows, err := s.rows(ctx, `SELECT lane, COUNT(*) FROM jobs WHERE status = 'running' GROUP BY lane`) + if err != nil { + return 0, 0, err + } + defer rows.Close() + for rows.Next() { + var lane string + var n int + if err := rows.Scan(&lane, &n); err != nil { + return 0, 0, err + } + total += n + if lane == LaneFree { + free += n + } + } + return total, free, rows.Err() +} + +// PromoteJob moves a queued free job to the paid lane. +func (s *Store) PromoteJob(ctx context.Context, id string) (bool, error) { + n, err := s.exec(ctx, `UPDATE jobs SET lane = 'paid' WHERE id = ? AND status = 'queued' AND lane = 'free'`, id) + return n == 1, err +} diff --git a/internal/db/migrations/00002_money.sql b/internal/db/migrations/00002_money.sql new file mode 100644 index 0000000..7d4dd33 --- /dev/null +++ b/internal/db/migrations/00002_money.sql @@ -0,0 +1,114 @@ +-- +goose Up +-- Money. The ledger is append-only: rows are inserted, never updated or +-- deleted. wallets.balance is a cached sum that is updated in the same +-- transaction as each ledger row and can be checked against the ledger. + +CREATE TABLE wallets ( + id TEXT PRIMARY KEY, + owner_type TEXT NOT NULL, + owner_id BIGINT NOT NULL, + balance BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL, + UNIQUE (owner_type, owner_id) +); + +CREATE TABLE ledger ( + id TEXT PRIMARY KEY, + wallet_id TEXT NOT NULL REFERENCES wallets (id), + kind TEXT NOT NULL, + amount BIGINT NOT NULL, + balance_after BIGINT NOT NULL, + reason TEXT NOT NULL, + ref TEXT NOT NULL DEFAULT '', + dedupe_key TEXT NOT NULL UNIQUE, + actor_id BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL +); +CREATE INDEX ledger_wallet_idx ON ledger (wallet_id, created_at); + +CREATE TABLE passes ( + id TEXT PRIMARY KEY, + wallet_id TEXT NOT NULL REFERENCES wallets (id), + kind TEXT NOT NULL, + starts_at BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + source TEXT NOT NULL DEFAULT '', + created_at BIGINT NOT NULL +); +CREATE INDEX passes_wallet_idx ON passes (wallet_id, expires_at); + +-- A purchase is one invoice. payment_hash maps the Lightning payment back +-- to the purchase and through it to the wallet that gets credited. +CREATE TABLE purchases ( + id TEXT PRIMARY KEY, + user_id BIGINT NOT NULL, + wallet_id TEXT NOT NULL REFERENCES wallets (id), + product TEXT NOT NULL, + amount_sats BIGINT NOT NULL, + status TEXT NOT NULL, + payment_hash TEXT NOT NULL UNIQUE, + bolt11 TEXT NOT NULL, + chat_id BIGINT NOT NULL DEFAULT 0, + message_id BIGINT NOT NULL DEFAULT 0, + message_is_photo BOOLEAN NOT NULL DEFAULT FALSE, + lang TEXT NOT NULL DEFAULT 'en', + request_id TEXT NOT NULL DEFAULT '', + profile TEXT NOT NULL DEFAULT '', + delivery_id TEXT NOT NULL DEFAULT '', + fulfilled BOOLEAN NOT NULL DEFAULT FALSE, + created_at BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + paid_at BIGINT NOT NULL DEFAULT 0 +); +CREATE INDEX purchases_status_idx ON purchases (status, created_at); +CREATE INDEX purchases_user_idx ON purchases (user_id, status); + +CREATE TABLE usage_daily ( + user_id BIGINT NOT NULL, + day INTEGER NOT NULL, + downloads INTEGER NOT NULL DEFAULT 0, + bytes BIGINT NOT NULL DEFAULT 0, + PRIMARY KEY (user_id, day) +); + +CREATE TABLE gift_codes ( + code TEXT PRIMARY KEY, + kind TEXT NOT NULL, + amount BIGINT NOT NULL, + max_uses INTEGER NOT NULL DEFAULT 1, + uses INTEGER NOT NULL DEFAULT 0, + expires_at BIGINT NOT NULL DEFAULT 0, + created_by BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL +); + +CREATE TABLE gift_redemptions ( + code TEXT NOT NULL REFERENCES gift_codes (code), + user_id BIGINT NOT NULL, + created_at BIGINT NOT NULL, + PRIMARY KEY (code, user_id) +); + +ALTER TABLE users ADD COLUMN referred_by BIGINT NOT NULL DEFAULT 0; + +-- What paid for a delivery, so a failed download can be refunded exactly. +ALTER TABLE deliveries ADD COLUMN source TEXT NOT NULL DEFAULT 'free'; +ALTER TABLE deliveries ADD COLUMN wallet_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE deliveries ADD COLUMN charge_sats BIGINT NOT NULL DEFAULT 0; +ALTER TABLE deliveries ADD COLUMN quota_day INTEGER NOT NULL DEFAULT 0; +ALTER TABLE deliveries ADD COLUMN released BOOLEAN NOT NULL DEFAULT FALSE; + +-- +goose Down +ALTER TABLE deliveries DROP COLUMN released; +ALTER TABLE deliveries DROP COLUMN quota_day; +ALTER TABLE deliveries DROP COLUMN charge_sats; +ALTER TABLE deliveries DROP COLUMN wallet_id; +ALTER TABLE deliveries DROP COLUMN source; +ALTER TABLE users DROP COLUMN referred_by; +DROP TABLE gift_redemptions; +DROP TABLE gift_codes; +DROP TABLE usage_daily; +DROP TABLE purchases; +DROP TABLE passes; +DROP TABLE ledger; +DROP TABLE wallets; diff --git a/internal/db/models.go b/internal/db/models.go index 3d656c2..bb268e6 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -47,6 +47,9 @@ type User struct { Banned bool CreatedAt int64 LastSeenAt int64 + ReferredBy int64 // user who invited this one, 0 for none + // IsNew is set by UpsertUser when the row was just created. + IsNew bool } // Request is one link sent by a user. @@ -129,4 +132,115 @@ type Delivery struct { TgMessageID int64 CreatedAt int64 UpdatedAt int64 + // Source is the entitlement that paid: see package entitle. + Source string + // WalletID is the wallet that was charged, "" for free and passes. + WalletID string + // ChargeSats is what was debited (or prepaid) for this delivery. + ChargeSats int64 + // QuotaDay is the usage day (YYYYMMDD) the download was counted + // against, 0 when it was not counted. + QuotaDay int + // Released is true once charge and quota were given back. + Released bool +} + +// Wallet owner types. +const ( + OwnerUser = "user" + OwnerGroup = "group" +) + +// Ledger entry kinds. Amounts are always positive; the kind gives the sign. +const ( + LedgerCredit = "credit" + LedgerDebit = "debit" + LedgerRefund = "refund" +) + +// Purchase statuses. +const ( + PurchasePending = "pending" + PurchasePaid = "paid" + PurchaseExpired = "expired" + PurchaseCancelled = "cancelled" +) + +// Wallet holds credits for a user or a group. +type Wallet struct { + ID string + OwnerType string + OwnerID int64 + Balance int64 // sats, cached sum of the ledger + CreatedAt int64 +} + +// LedgerEntry is one append-only movement on a wallet. +type LedgerEntry struct { + ID string + WalletID string + Kind string + Amount int64 + BalanceAfter int64 + Reason string + Ref string + // DedupeKey makes an entry idempotent: a second insert with the same + // key is ignored. + DedupeKey string + ActorID int64 + CreatedAt int64 +} + +// Pass is a time window of paid limits on a wallet. +type Pass struct { + ID string + WalletID string + Kind string + StartsAt int64 + ExpiresAt int64 + Source string + CreatedAt int64 +} + +// Purchase is one invoice and what it buys. +type Purchase struct { + ID string + UserID int64 // the payer + WalletID string + Product string + AmountSats int64 + Status string + PaymentHash string + Bolt11 string + ChatID int64 + MessageID int64 + MessageIsPhoto bool + Lang string + // RequestID and Profile describe a download to start once paid. + RequestID string + Profile string + // DeliveryID is the waiting delivery a skip-the-queue payment is for. + DeliveryID string + Fulfilled bool + CreatedAt int64 + ExpiresAt int64 + PaidAt int64 +} + +// Usage is what a user consumed on one UTC day. +type Usage struct { + Downloads int + Bytes int64 +} + +// GiftCode is a redeemable code. +type GiftCode struct { + Code string + Kind string // "credits" or a pass kind + Amount int64 // sats for credits, ignored for passes + MaxUses int + Uses int + ExpiresAt int64 + CreatedBy int64 + CreatedAt int64 } diff --git a/internal/db/money.go b/internal/db/money.go new file mode 100644 index 0000000..eadf00b --- /dev/null +++ b/internal/db/money.go @@ -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 +} diff --git a/internal/db/users.go b/internal/db/users.go index 6a1e30b..5a1b8a1 100644 --- a/internal/db/users.go +++ b/internal/db/users.go @@ -2,11 +2,11 @@ package db import "context" -const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at` +const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at, referred_by` func scanUser(sc interface{ Scan(...any) error }) (*User, error) { var u User - err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt) + err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt, &u.ReferredBy) if err != nil { return nil, notFound(err) } @@ -29,10 +29,32 @@ func (s *Store) UpsertUser(ctx context.Context, id int64, username, firstName, l if err != nil { return nil, err } - return s.GetUser(ctx, id) + u, err := s.GetUser(ctx, id) + if err == nil { + u.IsNew = u.CreatedAt == now && u.LastSeenAt == now + } + return u, err } // GetUser loads a user by Telegram ID. func (s *Store) GetUser(ctx context.Context, id int64) (*User, error) { return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE id = ?`, id)) } + +// SetReferrer records who invited a user. It only works once, and never +// for a self-invite. It reports whether the referrer was stored. +func (s *Store) SetReferrer(ctx context.Context, userID, referrerID int64) (bool, error) { + if userID == referrerID || referrerID == 0 { + return false, nil + } + n, err := s.exec(ctx, `UPDATE users SET referred_by = ? WHERE id = ? AND referred_by = 0 + AND EXISTS (SELECT 1 FROM (SELECT id FROM users WHERE id = ?) r)`, referrerID, userID, referrerID) + return n == 1, err +} + +// CountReferrals counts the users invited by a user. +func (s *Store) CountReferrals(ctx context.Context, referrerID int64) (int, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM users WHERE referred_by = ?`, referrerID).Scan(&n) + return n, err +} diff --git a/internal/entitle/entitle.go b/internal/entitle/entitle.go new file mode 100644 index 0000000..2df0e55 --- /dev/null +++ b/internal/entitle/entitle.go @@ -0,0 +1,172 @@ +// Package entitle decides, for one download request, what pays for it and +// which limits apply. It is a pure function of its input: no database, no +// clock, no configuration lookups. Everything that matters is passed in, +// which is what makes the rules testable as a table. +package entitle + +// Source names what pays for a download. +type Source string + +// The sources, in resolution order. +const ( + // OneOff is an invoice paid for exactly this file. + OneOff Source = "one_off" + // OwnPass is the requester's own active pass. + OwnPass Source = "own_pass" + // GroupPass is the active pass of the group the request came from. + GroupPass Source = "group_pass" + // GroupCredits are sats from the group wallet. + GroupCredits Source = "group_credits" + // OwnCredits are sats from the requester's wallet. + OwnCredits Source = "own_credits" + // Free is the free tier. + Free Source = "free" +) + +// Paid reports whether the source is anything but the free tier. +func (s Source) Paid() bool { return s != Free && s != "" } + +// Queue lanes. They match the values stored with jobs. +const ( + LanePaid = "paid" + LaneFree = "free" +) + +// Limits are the rules one download runs under. Zero means "no cap" for +// every field. +type Limits struct { + MaxSize int64 // bytes + MaxDuration int64 // seconds + ActiveJobs int + DailyDownloads int + DailyBytes int64 +} + +// Wallet is the state of a wallet that matters for resolution. +type Wallet struct { + ID string + // PassUntil is the unix millisecond the pass coverage ends, 0 for none. + PassUntil int64 + // Credits is the balance in sats. + Credits int64 +} + +func (w Wallet) hasPass(now int64) bool { return w.PassUntil > now } + +// Group is the state of the group a request came from. +type Group struct { + Wallet Wallet + // CreditsAllowed says whether this requester may spend group credits + // right now. The caller evaluates the group's spending rule (anyone, + // admins only, capped per person per day) and its daily cap. + CreditsAllowed bool + // MaxSize and MaxDuration are caps set by the group admins. They can + // only lower what the group's pass or credits allow, never raise it. + MaxSize int64 + MaxDuration int64 +} + +// Input is everything the resolver looks at. +type Input struct { + // Now is the current time in unix milliseconds. + Now int64 + // User is the wallet of the person who pressed the button. Inside a + // group it is still that person's wallet, not the group's. + User Wallet + // Group is nil for private chats. + Group *Group + // OneOffPaid is true when an invoice for exactly this file was paid. + OneOffPaid bool + // Free and Paid are the configured tiers. + Free, Paid Limits + // CreditCost is what one download costs when credits pay. + CreditCost int64 + // UploadCap is the largest file the bot can send to Telegram. It caps + // MaxSize whatever the tier says. 0 means no cap. + UploadCap int64 +} + +// Decision is the outcome. +type Decision struct { + Source Source + // WalletID is the wallet to debit, set only when Charge is positive. + WalletID string + // Charge is the sats to debit before the job is queued. + Charge int64 + Limits Limits + // Lane and Priority are fixed when the job is queued. A pass that + // expires while the job waits does not demote it. + Lane string + Priority int +} + +// Resolve picks what pays, in this order: +// +// 1. a one-off payment for this file +// 2. the requester's own active pass +// 3. the group's active pass +// 4. group credits, when the group's spending rule allows this requester +// 5. the requester's own credits +// 6. the free tier +// +// The first one that applies wins. Credits apply when the balance covers +// the cost of one download. +func Resolve(in Input) Decision { + switch { + case in.OneOffPaid: + return in.paid(OneOff, "", 0, false) + case in.User.hasPass(in.Now): + return in.paid(OwnPass, "", 0, false) + case in.Group != nil && in.Group.Wallet.hasPass(in.Now): + return in.paid(GroupPass, "", 0, true) + case in.Group != nil && in.Group.CreditsAllowed && in.covers(in.Group.Wallet): + return in.paid(GroupCredits, in.Group.Wallet.ID, in.CreditCost, true) + case in.covers(in.User): + return in.paid(OwnCredits, in.User.ID, in.CreditCost, false) + } + return Decision{ + Source: Free, + Limits: in.capped(in.Free, false), + Lane: LaneFree, + } +} + +// covers reports whether a wallet can pay for one download with credits. +// A zero cost never selects credits: that would make everyone "paid". +func (in Input) covers(w Wallet) bool { + return in.CreditCost > 0 && w.ID != "" && w.Credits >= in.CreditCost +} + +func (in Input) paid(src Source, walletID string, charge int64, groupFunded bool) Decision { + return Decision{ + Source: src, + WalletID: walletID, + Charge: charge, + Limits: in.capped(in.Paid, groupFunded), + Lane: LanePaid, + } +} + +// capped applies the Telegram upload ceiling and, for downloads the group +// pays for, the caps set by the group admins. +func (in Input) capped(l Limits, groupFunded bool) Limits { + l.MaxSize = minCap(l.MaxSize, in.UploadCap) + if groupFunded && in.Group != nil { + l.MaxSize = minCap(l.MaxSize, in.Group.MaxSize) + l.MaxDuration = minCap(l.MaxDuration, in.Group.MaxDuration) + } + return l +} + +// minCap returns the tighter of two caps where 0 means "no cap". +func minCap(a, b int64) int64 { + switch { + case a == 0: + return b + case b == 0: + return a + case b < a: + return b + } + return a +} diff --git a/internal/entitle/entitle_test.go b/internal/entitle/entitle_test.go new file mode 100644 index 0000000..e5043f7 --- /dev/null +++ b/internal/entitle/entitle_test.go @@ -0,0 +1,350 @@ +package entitle + +import "testing" + +const ( + now = int64(1_800_000_000_000) + future = now + 3_600_000 + past = now - 1 + mb = int64(1 << 20) +) + +var ( + free = Limits{MaxSize: 50 * mb, MaxDuration: 600, ActiveJobs: 1, DailyDownloads: 5, DailyBytes: 250 * mb} + paid = Limits{MaxSize: 2000 * mb, MaxDuration: 10800, ActiveJobs: 3, DailyDownloads: 100, DailyBytes: 20000 * mb} +) + +func base() Input { + return Input{Now: now, User: Wallet{ID: "u"}, Free: free, Paid: paid, CreditCost: 50, UploadCap: 2000 * mb} +} + +func group(mut func(*Group)) *Group { + g := &Group{Wallet: Wallet{ID: "g"}} + if mut != nil { + mut(g) + } + return g +} + +func TestResolve(t *testing.T) { + tests := []struct { + name string + mut func(*Input) + want Decision + }{ + // --- private chat --------------------------------------------------- + { + name: "nothing: free tier", + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "own active pass", + mut: func(in *Input) { in.User.PassUntil = future }, + want: Decision{Source: OwnPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "own pass expired a millisecond ago: free", + mut: func(in *Input) { in.User.PassUntil = past }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "own pass expiring exactly now is not active", + mut: func(in *Input) { in.User.PassUntil = now }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "own credits cover the cost", + mut: func(in *Input) { in.User.Credits = 50 }, + want: Decision{Source: OwnCredits, WalletID: "u", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "own credits one sat short: free", + mut: func(in *Input) { in.User.Credits = 49 }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "own pass beats own credits and charges nothing", + mut: func(in *Input) { in.User.PassUntil = future; in.User.Credits = 10_000 }, + want: Decision{Source: OwnPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "one-off payment lifts a user with nothing", + mut: func(in *Input) { in.OneOffPaid = true }, + want: Decision{Source: OneOff, Limits: paid, Lane: LanePaid}, + }, + { + name: "one-off is not charged again even with credits", + mut: func(in *Input) { in.OneOffPaid = true; in.User.Credits = 10_000 }, + want: Decision{Source: OneOff, Limits: paid, Lane: LanePaid}, + }, + { + name: "zero credit cost never selects credits", + mut: func(in *Input) { in.CreditCost = 0; in.User.Credits = 10_000 }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "a user without a wallet is free", + mut: func(in *Input) { in.User = Wallet{Credits: 500} }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + + // --- Telegram upload ceiling ---------------------------------------- + { + name: "upload cap lowers the paid size", + mut: func(in *Input) { in.User.PassUntil = future; in.UploadCap = 50 * mb }, + want: Decision{Source: OwnPass, Limits: withSize(paid, 50*mb), Lane: LanePaid}, + }, + { + name: "upload cap lowers the free size too", + mut: func(in *Input) { in.UploadCap = 20 * mb }, + want: Decision{Source: Free, Limits: withSize(free, 20*mb), Lane: LaneFree}, + }, + { + name: "no upload cap leaves tiers alone", + mut: func(in *Input) { in.UploadCap = 0; in.User.PassUntil = future }, + want: Decision{Source: OwnPass, Limits: paid, Lane: LanePaid}, + }, + + // --- groups --------------------------------------------------------- + { + name: "group with nothing: free", + mut: func(in *Input) { in.Group = group(nil) }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "group pass covers a member with nothing", + mut: func(in *Input) { in.Group = group(func(g *Group) { g.Wallet.PassUntil = future }) }, + want: Decision{Source: GroupPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "expired group pass: free", + mut: func(in *Input) { in.Group = group(func(g *Group) { g.Wallet.PassUntil = past }) }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "own pass beats group pass", + mut: func(in *Input) { + in.User.PassUntil = future + in.Group = group(func(g *Group) { g.Wallet.PassUntil = future }) + }, + want: Decision{Source: OwnPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "own pass ignores the group's lower caps", + mut: func(in *Input) { + in.User.PassUntil = future + in.Group = group(func(g *Group) { g.Wallet.PassUntil = future; g.MaxSize = 100 * mb; g.MaxDuration = 900 }) + }, + want: Decision{Source: OwnPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "group pass beats group credits", + mut: func(in *Input) { + in.Group = group(func(g *Group) { g.Wallet.PassUntil = future; g.Wallet.Credits = 5000; g.CreditsAllowed = true }) + }, + want: Decision{Source: GroupPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "group credits when the rule allows this member", + mut: func(in *Input) { + in.Group = group(func(g *Group) { g.Wallet.Credits = 5000; g.CreditsAllowed = true }) + }, + want: Decision{Source: GroupCredits, WalletID: "g", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "group credits refused by the spending rule: falls to own credits", + mut: func(in *Input) { + in.User.Credits = 500 + in.Group = group(func(g *Group) { g.Wallet.Credits = 5000; g.CreditsAllowed = false }) + }, + want: Decision{Source: OwnCredits, WalletID: "u", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "group credits refused and no own credits: free", + mut: func(in *Input) { + in.Group = group(func(g *Group) { g.Wallet.Credits = 5000; g.CreditsAllowed = false }) + }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "group credits beat own credits: the group pays first", + mut: func(in *Input) { + in.User.Credits = 500 + in.Group = group(func(g *Group) { g.Wallet.Credits = 5000; g.CreditsAllowed = true }) + }, + want: Decision{Source: GroupCredits, WalletID: "g", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "group credits too low: own credits pay", + mut: func(in *Input) { + in.User.Credits = 500 + in.Group = group(func(g *Group) { g.Wallet.Credits = 49; g.CreditsAllowed = true }) + }, + want: Decision{Source: OwnCredits, WalletID: "u", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "own credits in a group charge the requester, not the group", + mut: func(in *Input) { + in.User.Credits = 500 + in.Group = group(nil) + }, + want: Decision{Source: OwnCredits, WalletID: "u", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "own credits ignore the group's lower caps", + mut: func(in *Input) { + in.User.Credits = 500 + in.Group = group(func(g *Group) { g.MaxSize = 100 * mb; g.MaxDuration = 900 }) + }, + want: Decision{Source: OwnCredits, WalletID: "u", Charge: 50, Limits: paid, Lane: LanePaid}, + }, + { + name: "group pass honors the admins' lower caps", + mut: func(in *Input) { + in.Group = group(func(g *Group) { g.Wallet.PassUntil = future; g.MaxSize = 100 * mb; g.MaxDuration = 900 }) + }, + want: Decision{Source: GroupPass, Limits: withSizeDur(paid, 100*mb, 900), Lane: LanePaid}, + }, + { + name: "group credits honor the admins' lower caps", + mut: func(in *Input) { + in.Group = group(func(g *Group) { + g.Wallet.Credits = 5000 + g.CreditsAllowed = true + g.MaxSize = 100 * mb + }) + }, + want: Decision{Source: GroupCredits, WalletID: "g", Charge: 50, Limits: withSize(paid, 100*mb), Lane: LanePaid}, + }, + { + name: "group caps cannot raise limits above the tier", + mut: func(in *Input) { + in.Group = group(func(g *Group) { g.Wallet.PassUntil = future; g.MaxSize = 9000 * mb; g.MaxDuration = 99999 }) + }, + want: Decision{Source: GroupPass, Limits: paid, Lane: LanePaid}, + }, + { + name: "group caps do not touch the free tier", + mut: func(in *Input) { + in.Group = group(func(g *Group) { g.MaxSize = 10 * mb; g.MaxDuration = 60 }) + }, + want: Decision{Source: Free, Limits: free, Lane: LaneFree}, + }, + { + name: "one-off beats everything in a group", + mut: func(in *Input) { + in.OneOffPaid = true + in.Group = group(func(g *Group) { g.Wallet.PassUntil = future; g.MaxSize = 100 * mb }) + }, + want: Decision{Source: OneOff, Limits: paid, Lane: LanePaid}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + in := base() + if tc.mut != nil { + tc.mut(&in) + } + got := Resolve(in) + if got != tc.want { + t.Fatalf("Resolve()\n got %+v\nwant %+v", got, tc.want) + } + }) + } +} + +func withSize(l Limits, size int64) Limits { + l.MaxSize = size + return l +} + +func withSizeDur(l Limits, size, dur int64) Limits { + l.MaxSize = size + l.MaxDuration = dur + return l +} + +// TestResolveInvariants checks properties that must hold for every input, +// by walking the whole space of on/off combinations. +func TestResolveInvariants(t *testing.T) { + bools := []bool{false, true} + for _, ownPass := range bools { + for _, ownCredits := range bools { + for _, inGroup := range bools { + for _, groupPass := range bools { + for _, groupCredits := range bools { + for _, allowed := range bools { + for _, oneOff := range bools { + in := base() + in.OneOffPaid = oneOff + if ownPass { + in.User.PassUntil = future + } + if ownCredits { + in.User.Credits = 1000 + } + if inGroup { + in.Group = group(func(g *Group) { + if groupPass { + g.Wallet.PassUntil = future + } + if groupCredits { + g.Wallet.Credits = 1000 + } + g.CreditsAllowed = allowed + }) + } + d := Resolve(in) + + // A charge always names a wallet, and only credits charge. + if (d.Charge > 0) != (d.WalletID != "") { + t.Fatalf("%+v: charge and wallet disagree: %+v", in, d) + } + if d.Charge > 0 && d.Source != OwnCredits && d.Source != GroupCredits { + t.Fatalf("%+v: source %s must not charge", in, d.Source) + } + // The group wallet is never charged outside a group or + // against its spending rule. + if d.Source == GroupCredits && (!inGroup || !allowed) { + t.Fatalf("%+v: group credits spent without permission", in) + } + if (d.Source == GroupPass || d.Source == GroupCredits) && !inGroup { + t.Fatalf("%+v: group source in a private chat", in) + } + // Lane follows the source, and paid limits are never + // tighter than free ones. + if d.Source.Paid() != (d.Lane == LanePaid) { + t.Fatalf("%+v: lane %s for source %s", in, d.Lane, d.Source) + } + if d.Source.Paid() && d.Limits.MaxSize < free.MaxSize { + t.Fatalf("%+v: paid limits below free", in) + } + // Whoever has their own pass is never charged. + if ownPass && d.Charge != 0 { + t.Fatalf("%+v: pass holder was charged", in) + } + // Free is only chosen when nothing else applies. + anything := oneOff || ownPass || ownCredits || + (inGroup && (groupPass || (groupCredits && allowed))) + if (d.Source == Free) == anything { + t.Fatalf("%+v: free=%v but anything=%v", in, d.Source == Free, anything) + } + } + } + } + } + } + } + } +} + +func TestMinCap(t *testing.T) { + tests := []struct{ a, b, want int64 }{ + {0, 0, 0}, {0, 5, 5}, {5, 0, 5}, {5, 9, 5}, {9, 5, 5}, {7, 7, 7}, + } + for _, tc := range tests { + if got := minCap(tc.a, tc.b); got != tc.want { + t.Errorf("minCap(%d, %d) = %d, want %d", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/internal/i18n/format.go b/internal/i18n/format.go index 95a86f9..14acfe4 100644 --- a/internal/i18n/format.go +++ b/internal/i18n/format.go @@ -65,3 +65,20 @@ func (b *Bundle) Percent(lang string, ratio float64) string { } return b.printer(lang).Sprintf("%d%%", int(ratio*100+0.5)) } + +// Number formats an integer with the digit grouping of the locale, such as +// "9,000" in English and "9.000" in Spanish and Dutch. +func (b *Bundle) Number(lang string, n int64) string { + return b.printer(lang).Sprintf("%d", n) +} + +// Sats formats an amount of sats with its unit, for example "1,000 sats". +func (b *Bundle) Sats(lang string, n int64) string { + return b.T(lang, "unit.sats", Args{"Count": n, "N": b.Number(lang, n)}) +} + +// DateTime formats a point in time. The numeric form reads the same in +// every language and always states the time zone. +func (b *Bundle) DateTime(_ string, t time.Time) string { + return t.UTC().Format("2006-01-02 15:04") + " UTC" +} diff --git a/internal/sched/sched.go b/internal/sched/sched.go index 4ffaf92..77e6775 100644 --- a/internal/sched/sched.go +++ b/internal/sched/sched.go @@ -64,8 +64,20 @@ type Scheduler struct { mu sync.Mutex listeners []func(Event) wake chan struct{} + workers map[string]workerSeen } +// workerSeen is what the scheduler remembers about a worker between +// claims. It is enough to know the total capacity of the fleet. +type workerSeen struct { + capacity int + at time.Time +} + +// workerTTL is how long a worker counts toward capacity after its last +// claim. Workers claim at least every 20 seconds while idle. +const workerTTL = 90 * time.Second + // New creates a scheduler on top of a store. func New(store *db.Store, cfg Config, log *slog.Logger) *Scheduler { if cfg.Lease <= 0 { @@ -80,7 +92,7 @@ func New(store *db.Store, cfg Config, log *slog.Logger) *Scheduler { if log == nil { log = slog.Default() } - return &Scheduler{store: store, cfg: cfg, log: log, wake: make(chan struct{})} + return &Scheduler{store: store, cfg: cfg, log: log, wake: make(chan struct{}), workers: map[string]workerSeen{}} } // Subscribe registers a listener for job events. Listeners are called @@ -149,12 +161,39 @@ type EnqueueParams struct { // ActiveLimit is the most active jobs the user may have, 0 for no limit. ActiveLimit int + + // What pays for the download. These are stored with the delivery so a + // failure can give back exactly what was taken. + Source string + WalletID string + ChargeSats int64 + QuotaDay int } -// Enqueue adds a job with one delivery. The per-user limit and the free -// queue cap are checked in the same transaction as the insert, so two fast -// button presses cannot both slip through. +// Enqueue adds a job with one delivery in its own transaction. func (s *Scheduler) Enqueue(ctx context.Context, p EnqueueParams) (*db.Job, *db.Delivery, error) { + var ( + job *db.Job + del *db.Delivery + ) + err := s.store.InTx(ctx, func(tx *db.Store) error { + var err error + job, del, err = s.EnqueueTx(ctx, tx, p) + return err + }) + if err != nil { + return nil, nil, err + } + s.Announce(job, del) + return job, del, nil +} + +// EnqueueTx adds a job with one delivery inside the caller's transaction, +// so that charging a wallet and queueing the job commit or fail together. +// The per-user limit and the free queue cap are checked in the same +// transaction as the insert, so two fast button presses cannot both slip +// through. The caller must call Announce after the transaction commits. +func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams) (*db.Job, *db.Delivery, error) { now := s.now() if p.Lane == "" { p.Lane = db.LaneFree @@ -190,57 +229,123 @@ func (s *Scheduler) Enqueue(ctx context.Context, p EnqueueParams) (*db.Job, *db. Lang: p.Lang, Status: db.DeliveryPending, CreatedAt: now, + Source: p.Source, + WalletID: p.WalletID, + ChargeSats: p.ChargeSats, + QuotaDay: p.QuotaDay, } - err := s.store.InTx(ctx, func(tx *db.Store) error { - if p.ActiveLimit > 0 { - n, err := tx.CountActiveDeliveries(ctx, p.UserID) - if err != nil { - return err - } - if n >= p.ActiveLimit { - return ErrTooManyActive - } + if p.ActiveLimit > 0 { + n, err := tx.CountActiveDeliveries(ctx, p.UserID) + if err != nil { + return nil, nil, err } - if p.Lane == db.LaneFree && s.cfg.FreeMaxLen > 0 { - n, err := tx.CountQueued(ctx, db.LaneFree) - if err != nil { - return err - } - if n >= s.cfg.FreeMaxLen { - return ErrQueueFull - } + if n >= p.ActiveLimit { + return nil, nil, ErrTooManyActive } - if err := tx.InsertJob(ctx, job); err != nil { - return err + } + if p.Lane == db.LaneFree && s.cfg.FreeMaxLen > 0 { + n, err := tx.CountQueued(ctx, db.LaneFree) + if err != nil { + return nil, nil, err } - return tx.InsertDelivery(ctx, del) - }) - if err != nil { + if n >= s.cfg.FreeMaxLen { + return nil, nil, ErrQueueFull + } + } + if err := tx.InsertJob(ctx, job); err != nil { + return nil, nil, err + } + if err := tx.InsertDelivery(ctx, del); err != nil { return nil, nil, err } - s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", p.UserID, - "profile", p.Profile, "lane", p.Lane) - s.emit(EventQueued, job.ID) - s.notifyWork() return job, del, nil } -// lanes is the claim order: paid jobs first, then free. -var lanes = []string{db.LanePaid, db.LaneFree} +// Announce tells listeners and waiting workers about a committed job. +func (s *Scheduler) Announce(job *db.Job, del *db.Delivery) { + s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID, + "profile", job.Profile, "lane", job.Lane, "source", del.Source) + s.emit(EventQueued, job.ID) + s.notifyWork() +} + +// Claim order: paid jobs first, then free. +var ( + allLanes = []string{db.LanePaid, db.LaneFree} + freeOnly = []string{db.LaneFree} +) + +// seen records a worker's capacity and returns the capacity of all +// workers that claimed recently. +func (s *Scheduler) seen(workerID string, capacity int) (total int) { + if capacity < 1 { + capacity = 1 + } + now := s.cfg.Now() + s.mu.Lock() + defer s.mu.Unlock() + s.workers[workerID] = workerSeen{capacity: capacity, at: now} + for id, w := range s.workers { + if now.Sub(w.at) > workerTTL { + delete(s.workers, id) + continue + } + total += w.capacity + } + return total +} + +// Capacity returns the number of download slots of all live workers. +func (s *Scheduler) Capacity() int { + now := s.cfg.Now() + s.mu.Lock() + defer s.mu.Unlock() + total := 0 + for _, w := range s.workers { + if now.Sub(w.at) <= workerTTL { + total += w.capacity + } + } + return total +} // Claim hands the next queued job to a worker, or returns nil when there // is nothing to do. +// +// Paid jobs go first. One slot of the fleet is reserved for the free lane +// so free users never starve behind a stream of paid jobs: when this claim +// would take the last idle slot and no free job is running, a waiting free +// job is served first. The reservation costs nothing when no free job +// waits, and it needs at least two slots, since a single slot cannot be +// both reserved and useful to paying users. func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) { + capacity := s.seen(req.WorkerID, req.Capacity) now := s.now() lease := now + s.cfg.Lease.Milliseconds() var job *db.Job err := s.store.InTx(ctx, func(tx *db.Store) error { - j, err := tx.NextQueuedJob(ctx, lanes) - if errors.Is(err, db.ErrNotFound) { - return nil + var j *db.Job + if capacity >= 2 { + total, free, err := tx.CountRunningByLane(ctx) + if err != nil { + return err + } + if idle := capacity - total; idle <= 1 && free == 0 { + j, err = tx.NextQueuedJob(ctx, freeOnly) + if err != nil && !errors.Is(err, db.ErrNotFound) { + return err + } + } } - if err != nil { - return err + if j == nil { + var err error + j, err = tx.NextQueuedJob(ctx, allLanes) + if errors.Is(err, db.ErrNotFound) { + return nil + } + if err != nil { + return err + } } ok, err := tx.MarkJobRunning(ctx, j.ID, req.WorkerID, lease, now) if err != nil || !ok { @@ -253,7 +358,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w if err != nil || job == nil { return nil, err } - s.log.Info("job claimed", "job_id", job.ID, "worker_id", req.WorkerID, "attempt", job.Attempts) + s.log.Info("job claimed", "job_id", job.ID, "worker_id", req.WorkerID, "attempt", job.Attempts, "lane", job.Lane) s.emit(EventStarted, job.ID) return &workerproto.Job{ ID: job.ID, @@ -268,6 +373,19 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w }, nil } +// Promote moves a waiting free job to the paid lane ("skip the queue"). +// It reports false when the job is no longer waiting in the free lane. +func (s *Scheduler) Promote(ctx context.Context, jobID string) (bool, error) { + ok, err := s.store.PromoteJob(ctx, jobID) + if err != nil || !ok { + return false, err + } + s.log.Info("job promoted to the paid lane", "job_id", jobID) + s.emit(EventRequeued, jobID) // refreshes the position shown to the user + s.notifyWork() + return true, nil +} + // UploadKey is the storage key a job result is written to. func UploadKey(jobID string) string { return "jobs/" + jobID + "/media" } diff --git a/internal/sched/sched_test.go b/internal/sched/sched_test.go index d7a7ded..25d6d0e 100644 --- a/internal/sched/sched_test.go +++ b/internal/sched/sched_test.go @@ -455,3 +455,167 @@ func TestWaitWorkWakesOnEnqueue(t *testing.T) { t.Fatal("WaitWork did not wake up on enqueue") } } + +// claimCap claims as a worker that advertises the given capacity. +func (f *fixture) claimCap(worker string, capacity int) *workerproto.Job { + f.t.Helper() + j, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker, Capacity: capacity}) + if err != nil { + f.t.Fatalf("claim: %v", err) + } + return j +} + +func (f *fixture) finish(worker, jobID string) { + f.t.Helper() + if err := f.s.Complete(context.Background(), workerproto.CompleteRequest{WorkerID: worker, JobID: jobID, StorageKey: "k"}); err != nil { + f.t.Fatalf("complete: %v", err) + } +} + +func wantClaim(t *testing.T, got *workerproto.Job, want *db.Job, what string) { + t.Helper() + switch { + case want == nil && got != nil: + t.Fatalf("%s: claimed %s, want nothing", what, got.ID) + case want != nil && got == nil: + t.Fatalf("%s: claimed nothing, want %s", what, want.ID) + case want != nil && got.ID != want.ID: + t.Fatalf("%s: claimed the wrong job", what) + } +} + +// Acceptance: correct priority ordering with the reserved free slot. +func TestPaidFirstWithOneSlotReservedForFree(t *testing.T) { + f := newFixture(t, sched.Config{}) + paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } + const w, slots = "w1", 3 + + free1, _ := f.enqueue(1) + free2, _ := f.enqueue(2) + paid1, _ := f.enqueue(11, paid) + paid2, _ := f.enqueue(12, paid) + paid3, _ := f.enqueue(13, paid) + paid4, _ := f.enqueue(14, paid) + + // Free jobs were queued first, yet paid jobs are served first. + wantClaim(t, f.claimCap(w, slots), paid1, "slot 1") + wantClaim(t, f.claimCap(w, slots), paid2, "slot 2") + // The last idle slot is the reserved one: a free job waits and none + // runs, so it goes to the free lane although paid jobs are waiting. + wantClaim(t, f.claimCap(w, slots), free1, "slot 3 (reserved)") + + // A paid job finishes. A free job is already running, so the + // reservation is satisfied and the slot goes to the next paid job. + f.finish(w, paid1.ID) + wantClaim(t, f.claimCap(w, slots), paid3, "after paid1") + + // The free job finishes. Its slot is again the last idle one with no + // free job running, so the second free job is served before paid4. + f.finish(w, free1.ID) + wantClaim(t, f.claimCap(w, slots), free2, "after free1 (reserved)") + + f.finish(w, paid2.ID) + wantClaim(t, f.claimCap(w, slots), paid4, "after paid2") + f.finish(w, paid3.ID) + wantClaim(t, f.claimCap(w, slots), nil, "queue drained") +} + +func TestReservationCostsNothingWhenNoFreeJobWaits(t *testing.T) { + f := newFixture(t, sched.Config{}) + paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } + a, _ := f.enqueue(1, paid) + b, _ := f.enqueue(2, paid) + c, _ := f.enqueue(3, paid) + // All three slots serve paid jobs, including the reserved one. + wantClaim(t, f.claimCap("w", 3), a, "slot 1") + wantClaim(t, f.claimCap("w", 3), b, "slot 2") + wantClaim(t, f.claimCap("w", 3), c, "slot 3") +} + +func TestSingleSlotHasNoReservation(t *testing.T) { + f := newFixture(t, sched.Config{}) + free1, _ := f.enqueue(1) + paid1, _ := f.enqueue(2, func(p *sched.EnqueueParams) { p.Lane = db.LanePaid }) + // With one slot in total, reserving it would lock paying users out. + wantClaim(t, f.claimCap("w", 1), paid1, "the only slot") + f.finish("w", paid1.ID) + wantClaim(t, f.claimCap("w", 1), free1, "then free") +} + +func TestReservationCountsTheWholeFleet(t *testing.T) { + f := newFixture(t, sched.Config{}) + paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } + free1, _ := f.enqueue(1) + paid1, _ := f.enqueue(2, paid) + paid2, _ := f.enqueue(3, paid) + + // Two workers with one slot each: the fleet has two slots. Worker a + // claims first; nobody knows about b yet, so capacity is 1 and paid + // goes first. When b claims, the fleet is 2, one slot is busy, and the + // last idle slot is reserved for the waiting free job. + wantClaim(t, f.claimCap("a", 1), paid1, "worker a") + wantClaim(t, f.claimCap("b", 1), free1, "worker b (reserved)") + if got := f.s.Capacity(); got != 2 { + t.Fatalf("fleet capacity = %d, want 2", got) + } + f.finish("a", paid1.ID) + wantClaim(t, f.claimCap("a", 1), paid2, "worker a again") + + // A worker that stopped claiming drops out of the capacity. + f.advance(2 * time.Minute) + f.claimCap("a", 1) + if got := f.s.Capacity(); got != 1 { + t.Fatalf("fleet capacity after b went away = %d, want 1", got) + } +} + +func TestPromoteSkipsTheQueue(t *testing.T) { + ctx := context.Background() + f := newFixture(t, sched.Config{}) + free1, _ := f.enqueue(1) + free2, _ := f.enqueue(2) + free3, _ := f.enqueue(3) + + ok, err := f.s.Promote(ctx, free3.ID) + if err != nil || !ok { + t.Fatalf("promote = %v, %v", ok, err) + } + if pos, _ := f.s.Position(ctx, f.job(free3.ID), 1); pos.Ahead != 0 { + t.Fatalf("promoted job has %d jobs ahead, want 0", pos.Ahead) + } + if pos, _ := f.s.Position(ctx, f.job(free1.ID), 1); pos.Ahead != 1 { + t.Fatalf("first free job has %d jobs ahead, want 1", pos.Ahead) + } + wantClaim(t, f.claim("w"), free3, "promoted job first") + wantClaim(t, f.claim("w"), free1, "then FIFO") + + // Promoting twice, or promoting a job that is no longer waiting, is a + // no-op that reports false. + if ok, _ := f.s.Promote(ctx, free3.ID); ok { + t.Fatal("a running job cannot be promoted") + } + if ok, _ := f.s.Promote(ctx, free2.ID); !ok { + t.Fatal("a waiting free job can be promoted") + } + if ok, _ := f.s.Promote(ctx, free2.ID); ok { + t.Fatal("a paid job cannot be promoted again") + } +} + +func TestPriorityIsFixedAtEnqueue(t *testing.T) { + // The lane is stored with the job. Whatever happens to the pass that + // paid for it while it waits, the job keeps its place. + f := newFixture(t, sched.Config{}) + free1, _ := f.enqueue(1) + paid1, _ := f.enqueue(2, func(p *sched.EnqueueParams) { + p.Lane = db.LanePaid + p.Source = "own_pass" + }) + f.advance(48 * time.Hour) // far past any pass + wantClaim(t, f.claim("w"), paid1, "paid job after its pass expired") + wantClaim(t, f.claim("w"), free1, "then the free job") + if d, _ := f.store.DeliveriesForJob(context.Background(), paid1.ID, db.DeliveryPending); len(d) != 1 || d[0].Source != "own_pass" { + t.Fatalf("the delivery must remember what paid: %+v", d) + } +} diff --git a/internal/service/service.go b/internal/service/service.go index f8d279a..d5c4c94 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -9,9 +9,12 @@ import ( "errors" "log/slog" "math" + "time" + "github.com/noderunners/dlbot/internal/billing" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/entitle" "github.com/noderunners/dlbot/internal/links" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/sched" @@ -80,31 +83,30 @@ func cardInfo(url string, info *ytdlp.Info) *CardInfo { return c } -// Limits are the rules one download runs under. -type Limits struct { - MaxSize int64 // bytes - MaxDuration int64 // seconds - ActiveJobs int - Lane string - Priority int -} - // LimitError is a refusal caused by a limit rather than by the source. // Code doubles as the message key suffix: "limit.". type LimitError struct { - Code string - Limits Limits + Code string + // Decision is the entitlement the request was judged under. + Decision entitle.Decision + // Upgradable is true when a paid entitlement would allow the download + // and payments are available, which is when the bot offers to sell. + Upgradable bool + // Size is the estimated size of the refused download, 0 when unknown. + Size int64 } func (e *LimitError) Error() string { return "service: limit: " + e.Code } // The limit refusal codes. const ( - LimitTooLarge = "too_large" - LimitTooLong = "too_long" - LimitLive = "live" - LimitActiveJobs = "active_jobs" - LimitQueueFull = "queue_full" + LimitTooLarge = "too_large" + LimitTooLong = "too_long" + LimitLive = "live" + LimitActiveJobs = "active_jobs" + LimitQueueFull = "queue_full" + LimitDailyDownloads = "daily_downloads" + LimitDailyVolume = "daily_volume" ) // ErrPlaylist is returned by Probe for links that resolve to a list. @@ -112,23 +114,31 @@ var ErrPlaylist = errors.New("service: link is a playlist") // Service implements the download rules. type Service struct { - cfg config.Config - store *db.Store - sched *sched.Scheduler - runner ytdlp.Runner - log *slog.Logger - probes chan struct{} + cfg config.Config + store *db.Store + sched *sched.Scheduler + billing *billing.Billing + runner ytdlp.Runner + log *slog.Logger + probes chan struct{} + now func() time.Time } // New creates the service. -func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, runner ytdlp.Runner, log *slog.Logger) *Service { +func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, runner ytdlp.Runner, log *slog.Logger) *Service { n := cfg.Worker.ProbeConcurrency if n < 1 { n = 1 } - return &Service{cfg: cfg, store: store, sched: sch, runner: runner, log: log, probes: make(chan struct{}, n)} + return &Service{ + cfg: cfg, store: store, sched: sch, billing: bill, runner: runner, log: log, + probes: make(chan struct{}, n), now: time.Now, + } } +// SetClock replaces the time source, for tests. +func (s *Service) SetClock(now func() time.Time) { s.now = now } + // Probe looks up the metadata of a link. Lookups are limited to a few at a // time so a burst of links cannot start dozens of yt-dlp processes. func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) { @@ -152,40 +162,121 @@ func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) { return cardInfo(url, info), nil } -// LimitsFor returns the limits that apply to a user. Until payments exist -// everyone is on the free tier. The Telegram upload ceiling always applies. -func (s *Service) LimitsFor(_ context.Context, _ int64) Limits { - free := s.cfg.Limits.Free - lim := Limits{ - MaxSize: free.MaxSizeMB << 20, - MaxDuration: int64(free.MaxDuration.D().Seconds()), - ActiveJobs: free.ActiveJobs, - Lane: db.LaneFree, +// tier converts a configured tier to resolver limits. +func tier(t config.Tier) entitle.Limits { + return entitle.Limits{ + MaxSize: t.MaxSizeMB << 20, + MaxDuration: int64(t.MaxDuration.D().Seconds()), + ActiveJobs: t.ActiveJobs, + DailyDownloads: t.DailyDownloads, + DailyBytes: t.DailyMB << 20, } - if up := s.cfg.MaxUploadBytes(); up > 0 && (lim.MaxSize == 0 || lim.MaxSize > up) { - lim.MaxSize = up +} + +// Day returns the usage day of a time as YYYYMMDD in UTC. +func Day(t time.Time) int { + y, m, d := t.UTC().Date() + return y*10000 + int(m)*100 + d +} + +// Who identifies the requester and where the request came from. +type Who struct { + UserID int64 + ChatID int64 + ChatType string +} + +// Entitlement resolves what pays for a download by this requester and +// which limits apply. oneOffPaid is true when an invoice for exactly this +// file was paid. +func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, error) { + in := entitle.Input{ + Now: s.now().UnixMilli(), + OneOffPaid: oneOffPaid, + Free: tier(s.cfg.Limits.Free), + Paid: tier(s.cfg.Limits.Paid), + CreditCost: s.cfg.Prices.CreditPerDownload, + UploadCap: s.cfg.MaxUploadBytes(), } - return lim + user, err := s.billing.State(ctx, db.OwnerUser, who.UserID) + if err != nil { + return entitle.Decision{}, err + } + in.User = user + return entitle.Resolve(in), nil +} + +// Usage returns what the user consumed today. +func (s *Service) Usage(ctx context.Context, userID int64) (db.Usage, error) { + return s.store.GetUsage(ctx, userID, Day(s.now())) } // Check applies the size, duration and live rules to known metadata. The // worker enforces the same caps again on the real file, because metadata // is often incomplete. -func Check(info *CardInfo, profile media.Profile, lim Limits) error { +func Check(info *CardInfo, profile media.Profile, lim entitle.Limits) string { if info.Live { - return &LimitError{Code: LimitLive, Limits: lim} + return LimitLive } kind := profile.Kind() if kind == media.KindThumb || kind == media.KindSubs { - return nil + return "" } if lim.MaxDuration > 0 && info.Duration > lim.MaxDuration { - return &LimitError{Code: LimitTooLong, Limits: lim} + return LimitTooLong } if size := info.Sizes[string(profile)]; lim.MaxSize > 0 && size > lim.MaxSize { - return &LimitError{Code: LimitTooLarge, Limits: lim} + return LimitTooLarge } - return nil + return "" +} + +// admit runs every rule that can refuse a download: size, duration, live, +// the daily download quota and the daily volume cap. It is the one gate +// for fresh downloads and, later, for cache hits alike. +func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile media.Profile, dec entitle.Decision) error { + code := Check(info, profile, dec.Limits) + if code == "" { + usage, err := s.Usage(ctx, who.UserID) + if err != nil { + return err + } + switch { + case dec.Limits.DailyDownloads > 0 && usage.Downloads >= dec.Limits.DailyDownloads: + code = LimitDailyDownloads + case dec.Limits.DailyBytes > 0 && usage.Bytes >= dec.Limits.DailyBytes: + code = LimitDailyVolume + } + } + if code == "" { + return nil + } + return s.limitError(code, info, profile, dec) +} + +func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError { + le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]} + if code == LimitLive || code == LimitQueueFull || dec.Source.Paid() || !s.billing.Enabled() { + return le + } + // Would the paid tier accept it? Only then is it worth offering. + paid := tier(s.cfg.Limits.Paid) + if up := s.cfg.MaxUploadBytes(); up > 0 && (paid.MaxSize == 0 || paid.MaxSize > up) { + paid.MaxSize = up + } + le.Upgradable = Check(info, profile, paid) == "" + return le +} + +// Preview reports whether a download would be accepted right now, without +// queueing or charging anything. It returns *LimitError when a rule would +// refuse it. +func (s *Service) Preview(ctx context.Context, who Who, info *CardInfo, profile media.Profile) error { + dec, err := s.Entitlement(ctx, who, false) + if err != nil { + return err + } + return s.admit(ctx, who, info, profile, dec) } // StartParams describes a download a requester asked for. @@ -196,26 +287,47 @@ type StartParams struct { StatusMessageID int64 StatusIsPhoto bool ReplyToMessageID int64 + // OneOff is the paid purchase for exactly this file, if any. + OneOff *db.Purchase } -// Start checks the limits and queues the download. It returns *LimitError -// when a rule refuses the request. +// Start resolves the entitlement, checks every limit, charges the wallet +// when credits pay, and queues the download. Charge, quota and job are +// written in one transaction. It returns *LimitError when a rule refuses. func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delivery, error) { - lim := s.LimitsFor(ctx, p.Request.UserID) - if err := Check(p.Info, p.Profile, lim); err != nil { + who := Who{UserID: p.Request.UserID, ChatID: p.Request.ChatID, ChatType: p.Request.ChatType} + // A wallet changing under us (two downloads racing for the last + // credits) makes the debit fail; resolving again then picks the next + // source in line. + for attempt := 0; ; attempt++ { + job, del, err := s.startOnce(ctx, who, p) + if errors.Is(err, db.ErrInsufficient) && attempt < 2 { + continue + } + return job, del, err + } +} + +func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Job, *db.Delivery, error) { + dec, err := s.Entitlement(ctx, who, p.OneOff != nil) + if err != nil { return nil, nil, err } - job, del, err := s.sched.Enqueue(ctx, sched.EnqueueParams{ + if err := s.admit(ctx, who, p.Info, p.Profile, dec); err != nil { + return nil, nil, err + } + day := Day(s.now()) + params := sched.EnqueueParams{ URL: p.Request.URL, Extractor: p.Info.Extractor, VideoID: p.Info.VideoID, Profile: string(p.Profile), Title: p.Info.Title, Uploader: p.Info.Uploader, - Lane: lim.Lane, - Priority: lim.Priority, - MaxSize: lim.MaxSize, - MaxDuration: lim.MaxDuration, + Lane: dec.Lane, + Priority: dec.Priority, + MaxSize: dec.Limits.MaxSize, + MaxDuration: dec.Limits.MaxDuration, RequestID: p.Request.ID, UserID: p.Request.UserID, ChatID: p.Request.ChatID, @@ -224,15 +336,116 @@ func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delive StatusMessageID: p.StatusMessageID, StatusIsPhoto: p.StatusIsPhoto, Lang: p.Request.Lang, - ActiveLimit: lim.ActiveJobs, + ActiveLimit: dec.Limits.ActiveJobs, + Source: string(dec.Source), + WalletID: dec.WalletID, + ChargeSats: dec.Charge, + QuotaDay: day, + } + if p.OneOff != nil { + // Prepaid by invoice. Remember the amount and the payer's wallet so + // a failed download can be refunded as credits. + w, err := s.billing.Wallet(ctx, db.OwnerUser, p.OneOff.UserID) + if err != nil { + return nil, nil, err + } + params.WalletID = w.ID + params.ChargeSats = p.OneOff.AmountSats + } + var ( + job *db.Job + del *db.Delivery + ) + err = s.store.InTx(ctx, func(tx *db.Store) error { + var err error + if job, del, err = s.sched.EnqueueTx(ctx, tx, params); err != nil { + return err + } + if dec.Charge > 0 { + if _, err := tx.AddLedger(ctx, &db.LedgerEntry{ + WalletID: dec.WalletID, Kind: db.LedgerDebit, Amount: dec.Charge, Reason: "download", + Ref: del.ID, DedupeKey: "download:" + del.ID, ActorID: who.UserID, CreatedAt: s.now().UnixMilli(), + }); err != nil { + return err + } + } + return tx.AddUsage(ctx, who.UserID, day, 1, 0) }) switch { case errors.Is(err, sched.ErrTooManyActive): - return nil, nil, &LimitError{Code: LimitActiveJobs, Limits: lim} + return nil, nil, s.limitError(LimitActiveJobs, p.Info, p.Profile, dec) case errors.Is(err, sched.ErrQueueFull): - return nil, nil, &LimitError{Code: LimitQueueFull, Limits: lim} + return nil, nil, s.limitError(LimitQueueFull, p.Info, p.Profile, dec) case err != nil: return nil, nil, err } + s.sched.Announce(job, del) return job, del, nil } + +// Release gives back what an undelivered download took: the sats that +// were charged and the slot in the daily quota. It is idempotent and +// returns the refunded sats, which is 0 on every call after the first. +func (s *Service) Release(ctx context.Context, deliveryID string) (refunded int64, err error) { + err = s.store.InTx(ctx, func(tx *db.Store) error { + d, err := tx.GetDelivery(ctx, deliveryID) + if err != nil { + return err + } + if d.Status == db.DeliverySent { + return nil // the file arrived, nothing to give back + } + won, err := tx.MarkDeliveryReleased(ctx, d.ID) + if err != nil || !won { + return err + } + if d.ChargeSats > 0 && d.WalletID != "" { + applied, err := tx.AddLedger(ctx, &db.LedgerEntry{ + WalletID: d.WalletID, Kind: db.LedgerRefund, Amount: d.ChargeSats, Reason: "refund", + Ref: d.ID, DedupeKey: "refund:" + d.ID, CreatedAt: s.now().UnixMilli(), + }) + if err != nil { + return err + } + if applied { + refunded = d.ChargeSats + } + } + if d.QuotaDay > 0 { + return tx.AddUsage(ctx, d.UserID, d.QuotaDay, -1, 0) + } + return nil + }) + if errors.Is(err, db.ErrDuplicate) { + return 0, nil + } + if err == nil && refunded > 0 { + s.log.Info("download refunded", "delivery_id", deliveryID, "sats", refunded) + } + return refunded, err +} + +// RecordDelivered adds the delivered bytes to the requester's daily volume. +func (s *Service) RecordDelivered(ctx context.Context, d *db.Delivery, bytes int64) error { + day := d.QuotaDay + if day == 0 { + day = Day(s.now()) + } + return s.store.AddUsage(ctx, d.UserID, day, 0, bytes) +} + +// ReleasePending refunds deliveries that ended without a file but were +// missed by the normal path, for example because the core stopped between +// the failure and the refund. +func (s *Service) ReleasePending(ctx context.Context) { + list, err := s.store.UnreleasedDeliveries(ctx, 200) + if err != nil { + s.log.Error("list unreleased deliveries", "err", err) + return + } + for _, d := range list { + if _, err := s.Release(ctx, d.ID); err != nil { + s.log.Error("release delivery", "delivery_id", d.ID, "err", err) + } + } +} diff --git a/internal/tg/fakeserver/server.go b/internal/tg/fakeserver/server.go index a959e3e..3ce9107 100644 --- a/internal/tg/fakeserver/server.go +++ b/internal/tg/fakeserver/server.go @@ -114,7 +114,10 @@ type Server struct { failures map[string][]scriptedError members map[string]string sent map[int]map[string]any // messages the bot sent, by message ID - closed bool + // confirmed is the highest update ID the bot acknowledged by asking for + // a later offset. Like Telegram, confirmed updates are never sent again. + confirmed int + closed bool } // New starts a fake server. @@ -386,10 +389,13 @@ func (s *Server) getUpdates(w http.ResponseWriter, params map[string]string) { defer timer.Stop() s.mu.Lock() defer s.mu.Unlock() + if offset-1 > s.confirmed { + s.confirmed = offset - 1 + } for { var out []map[string]any for _, u := range s.updates { - if u["update_id"].(int) >= offset { + if id := u["update_id"].(int); id > s.confirmed && id >= offset { out = append(out, u) } } diff --git a/locales/en.toml b/locales/en.toml index 084d9ce..e5d5cba 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -35,6 +35,15 @@ In a group, use /dl with a link, or reply /dl to a message that has a link. /queue - your running downloads /cancel - cancel your downloads +Account +/account - your pass, balance and usage +/limits - the limits that apply to you +/buy - get a pass or credits +/credits - your balance and top up +/redeem code - use a gift code +/referral - invite friends and earn sats +/donate - send a tip + Your limits Up to {{.MaxSize}} and {{.MaxDuration}} per download.""" @@ -49,6 +58,8 @@ thumb = "Get the thumbnail" info = "Show formats and sizes" queue = "Your downloads in progress" cancel = "Cancel your downloads" +account = "Your pass, balance and usage" +buy = "Get a pass or credits" help = "How to use the bot" [hint] @@ -90,6 +101,12 @@ thumb = "Thumbnail" subs = "Subtitles ({{.Lang}})" with_size = "{{.Label}} · {{.Size}}" cancel = "Cancel" +skip_queue = "Skip the queue" +open_private = "Open a private chat" +open_wallet = "Open in wallet" +check_payment = "Check payment" +this_file = "This file only" +buy_for_me = "Buy for me" [status] queued = "In the queue. Position {{.Position}}, about {{.Wait}}." @@ -101,6 +118,7 @@ uploading = "Sending it to Telegram…" done = "Done. Enjoy." cancelled = "Cancelled." failed = "That did not work. {{.Reason}}" +refunded = "{{.Amount}} went back to your balance." [notice] cancelled = "Cancelled." @@ -108,17 +126,34 @@ not_yours = "These buttons belong to the person who asked." too_late = "Too late to cancel that." expired = "This card has expired. Send the link again." already_chosen = "A download from this card is already running." +private_only = "This works in a private chat with me." +rate_limited = "That is a lot of links. Please wait a minute and try again." +paid = "Payment received." +not_paid_yet = "Not paid yet. It can take a few seconds after you pay." +invoice_closed = "This invoice is closed." +skipped = "Done. Your download moved to the front." +skip_too_late = "This download is not waiting in the queue anymore." +skip_private = "Open a private chat with me to pay for this." [limit] too_large = "This file is larger than your limit of {{.MaxSize}}. Try a lower quality." too_long = "This is longer than your limit of {{.MaxDuration}}." live = "Live streams cannot be downloaded." queue_full = "The queue is full right now. Please try again in a few minutes." +daily_volume = "You reached your daily volume of {{.MaxVolume}}. It resets at midnight UTC." + +[limit.daily_downloads] +one = "You used your {{.Count}} download for today. It resets at midnight UTC." +other = "You used your {{.Count}} downloads for today. It resets at midnight UTC." [limit.active_jobs] one = "You already have {{.Count}} download running. Wait for it to finish or use /cancel." other = "You already have {{.Count}} downloads running. Wait for one to finish or use /cancel." +[unit.sats] +one = "{{.N}} sat" +other = "{{.N}} sats" + [unit.seconds] one = "{{.Count}} second" other = "{{.Count}} seconds" @@ -156,3 +191,122 @@ internal = "Something went wrong on my side. Please try again." unknown = "The download failed. Please try again later." playlist = "That link is a playlist. Send the link of a single video for now." send_failed = "I could not send the file to Telegram. Please try again." + +# --- Money ------------------------------------------------------------------- + +[product] +pass_day = "Day pass" +pass_week = "Week pass" +pass_month = "Month pass" +credits = "Credits" +one_off = "Single download" +skip_queue = "Skip the queue" +donation = "Donation" + +# What pays for a download. +[source] +one_off = "Single download" +own_pass = "Your pass" +group_pass = "Group pass" +group_credits = "Group credits" +own_credits = "Your credits" +free = "Free" + +[buy] +intro = """ +Passes and credits + +A pass lifts your limits to {{.MaxSize}} and {{.MaxDuration}} per download and puts you in the priority queue for as long as it runs. + +Credits pay per download, {{.PerDownload}} each, with the same limits and priority. They never expire. + +You pay in sats over Lightning.""" +unavailable = "Payments are not set up on this bot yet." +backend_down = "I cannot reach the payment service right now. Please try again in a moment." +backend_down_short = "The payment service is not reachable right now. Please try again in a moment." +bad_amount = "That amount is not possible." + +[credits] +text = """ +Your balance: {{.Balance}} + +One download costs {{.PerDownload}}. Top up:""" + +[donate] +intro = "Thank you for supporting the bot. Pick an amount:" + +[account] +title = "Your account" +pass_active = "Pass: active until {{.Until}}" +pass_none = "Pass: none" +balance = "Balance: {{.Balance}}" +today = "Today" +usage_downloads = "Downloads: {{.Used}} of {{.Max}}" +usage_volume = "Volume: {{.Used}} of {{.Max}}" +unlimited = "unlimited" + +[limits] +text = """ +Your limits ({{.Tier}}) + +Size per download: {{.MaxSize}} +Length per download: {{.MaxDuration}} +Downloads at the same time: {{.ActiveJobs}} +Downloads per day: {{.DailyDownloads}} +Volume per day: {{.DailyVolume}}""" + +[referral.text] +one = """ +Invite friends + +Share your link. When somebody you invited makes a first purchase, you get {{.Reward}}. + +{{.Link}} + +You invited {{.Count}} person so far.""" +other = """ +Invite friends + +Share your link. When somebody you invited makes a first purchase, you get {{.Reward}}. + +{{.Link}} + +You invited {{.Count}} people so far.""" + +[redeem] +usage = "Send the code after the command.\nExample: /redeem NR-ABCD-EFGH-JKMN" +invalid = "That code is not valid." +used = "That code was already used or has expired." +credits = "Done. {{.Amount}} were added to your balance." +pass = "Done. Your pass is active until {{.Until}}." +cashu_off = "Cashu tokens are not accepted on this bot." +cashu_mint = "I do not accept tokens from that mint." + +[invoice] +memo = "The Noderunners Download Bot: {{.Title}}" +caption = """ +{{.Title}} · {{.Amount}} + +{{.Invoice}} + +Scan the code or tap the invoice to copy it. Valid for {{.Valid}}.""" +paid = "Paid. {{.Title}} · {{.Amount}}" +balance = "Your balance is now {{.Balance}}." +pass_until = "Your pass is active until {{.Until}}." +thanks = "Thank you for the support." +expired = "This invoice for {{.Title}} has expired. Nothing was charged." +cancelled = "Invoice cancelled." + +[pay] +title = "Pay with Lightning" +hint = "Your Lightning wallet should open now." +open = "Open in wallet" +gone = "This invoice is no longer open." +too_late_skip = "Your payment arrived, but the download had already left the queue. {{.Amount}} were added to your balance instead." +too_late_file = "Your payment arrived, but the download could not be started. {{.Amount}} were added to your balance instead." +not_started = "The download could not be started. {{.Reason}}" +skip_not_needed = "That download is not waiting in the queue anymore, so there is nothing to pay." + +[over] +options = "You can lift the limit:" +started = "Your limits allow it now. The download has started."