Phase 2: money

Lightning payments through LNbits, wallets, passes, credits, the
entitlement resolver and priority lanes.

- internal/entitle: pure resolver (one-off, own pass, group pass, group
  credits, own credits, free) with a table-driven suite and an invariant
  check over every input combination
- internal/billing: wallets, append-only ledger with dedupe keys, stacking
  passes, purchases, gift codes, referral reward
- LNbits client verified against v0.12.12 and v1.7.1 source
- Settlement by one conditional UPDATE: idempotent under any mix of
  webhooks, polls and the check button. Webhooks are unsigned, so every
  payment is confirmed with LNbits before it is credited
- Polling fallback, reconciliation of all unsettled invoices at startup,
  late payments still honored, no expiry while LNbits is unreachable
- Charge, quota and job are written in one transaction; failed, cancelled
  and undeliverable downloads are refunded exactly once
- Paid lane first with one slot of the fleet reserved for free users
- Daily download quota and daily volume cap, per-user and per-group rate
  limits
- Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice
  message that flips to paid, over-limit offer (passes or this file only),
  deep links from groups, skip the queue
- Fake LNbits server for tests; end-to-end money flows including a payment
  made while the core was down

Cashu redemption is behind an interface and not implemented.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 08:09:35 +00:00
co-authored by Claude Fable 5.2
parent 3b361c17a1
commit 0d50f453a0
42 changed files with 7040 additions and 140 deletions
+96 -1
View File
@@ -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:<id>`, charging a download `download:<delivery>`,
refunding it `refund:<delivery>`. 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/<secret> --- (once, unsigned)
| <--- poll GET /api/v1/payments/<hash> (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.
+122
View File
@@ -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/<bot>?start=ref_<user id>`. 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).