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
+172
View File
@@ -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
}
+350
View File
@@ -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)
}
}
}