Files
Media-download-telegram-bot/internal/entitle/entitle.go
T
MichilisandClaude Fable 5.2 0d50f453a0 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>
2026-11-18 08:09:35 +00:00

173 lines
5.2 KiB
Go

// 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
}