package billing import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "time" ) // Subscription is one gateway's paid-for access to a relay. type Subscription struct { Gateway string `json:"gateway"` PaidUntil string `json:"paid_until"` TotalSats int64 `json:"total_sats"` LastPaymentAt string `json:"last_payment_at"` } // Ledger is the relay's record of who has paid for how long. // // Payments arrive by keysend with the gateway's own public key as the preimage, so the ledger needs // no accounts and no reference field: the payment says who paid, and the amount divided by the // daily rate says how long it buys. Preimages are remembered so replaying the same payment from a // wallet's transaction list does not buy the same time twice. type Ledger struct { // Path is where the ledger is stored. Empty keeps it in memory. Path string // RateSatsPerDay is the price of one day of access. RateSatsPerDay int64 `json:"rate_sats_per_day"` Subscriptions map[string]Subscription `json:"subscriptions"` // Watermarks remember, per gateway, the settle time of the newest payment already credited. // Keysend payments from one gateway share a preimage (it is the gateway's key), so the wallet // cannot tell two of them apart by preimage; the settle time is the only thing that can, and // it is what makes rescanning the wallet idempotent. Watermarks map[string]int64 `json:"watermarks"` // Blocked is the operator's own decision, kept beside the payments rather than inside them: // blocking a gateway does not erase what it paid. Blocked map[string]bool `json:"blocked,omitempty"` } // OpenLedger loads the ledger at path. A missing file is an empty ledger. func OpenLedger(path string, ratePerDay int64) (*Ledger, error) { ledger := &Ledger{Path: path, RateSatsPerDay: ratePerDay} body, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return ledger.withMaps(), nil } if err != nil { return nil, fmt.Errorf("billing: %w", err) } if err := json.Unmarshal(body, ledger); err != nil { return nil, fmt.Errorf("billing: %s: %w", path, err) } ledger.Path = path // The file's rate wins when it has one: the relay is the side that sets a price, and the // billing sidecar is told to follow it. if ledger.RateSatsPerDay == 0 { ledger.RateSatsPerDay = ratePerDay } return ledger.withMaps(), nil } func (l *Ledger) withMaps() *Ledger { if l.Subscriptions == nil { l.Subscriptions = map[string]Subscription{} } if l.Watermarks == nil { l.Watermarks = map[string]int64{} } return l } // Save writes the ledger atomically. func (l *Ledger) Save() error { if l.Path == "" { return nil } body, err := json.MarshalIndent(l, "", " ") if err != nil { return fmt.Errorf("billing: %w", err) } if err := os.MkdirAll(filepath.Dir(l.Path), 0o700); err != nil { return fmt.Errorf("billing: %w", err) } stage, err := os.CreateTemp(filepath.Dir(l.Path), ".ledger-*") if err != nil { return fmt.Errorf("billing: %w", err) } name := stage.Name() if _, err := stage.Write(append(body, '\n')); err != nil { stage.Close() os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := stage.Sync(); err != nil { stage.Close() os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := stage.Close(); err != nil { os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := os.Chmod(name, 0o600); err != nil { os.Remove(name) return fmt.Errorf("billing: %w", err) } if err := os.Rename(name, l.Path); err != nil { os.Remove(name) return fmt.Errorf("billing: %w", err) } return nil } // Credit records one payment. The preimage is the paying gateway's public key; the amount buys // Amount/rate days of access from now, or from the end of the access already paid for, so a // gateway that renews early does not lose the time it had. func (l *Ledger) Credit(preimageHex string, amountSats int64, settledAt int64, now time.Time) (Subscription, error) { gateway := strings.ToLower(strings.TrimSpace(preimageHex)) if len(gateway) != 64 || !isHex(gateway) { return Subscription{}, fmt.Errorf("billing: preimage %q is not a gateway public key", preimageHex) } if amountSats <= 0 { return Subscription{}, fmt.Errorf("billing: payment of %d sats credits nothing", amountSats) } if l.RateSatsPerDay <= 0 { return Subscription{}, errors.New("billing: no daily rate is set, so a payment cannot be priced") } if settledAt > 0 && settledAt <= l.Watermarks[gateway] { // Already counted: this is the same payment seen again in the wallet's list. return l.Subscriptions[gateway], nil } // Time is bought in seconds of the day, which keeps small payments honest instead of // rounding them to nothing or to a whole day. seconds := amountSats * 86400 / l.RateSatsPerDay if seconds <= 0 { return Subscription{}, fmt.Errorf("billing: %d sats is less than one second at %d sats/day", amountSats, l.RateSatsPerDay) } current := l.Subscriptions[gateway] start := now if parsed, err := time.Parse(time.RFC3339, current.PaidUntil); err == nil && parsed.After(now) { start = parsed } next := Subscription{ Gateway: gateway, PaidUntil: start.Add(time.Duration(seconds) * time.Second).UTC().Format(time.RFC3339), TotalSats: current.TotalSats + amountSats, LastPaymentAt: now.UTC().Format(time.RFC3339), } l.Subscriptions[gateway] = next if settledAt > l.Watermarks[gateway] { l.Watermarks[gateway] = settledAt } return next, nil } // Paid reports whether a gateway is paid up at now. func (l *Ledger) Paid(gateway string, now time.Time) bool { subscription, ok := l.Subscriptions[strings.ToLower(strings.TrimSpace(gateway))] if !ok { return false } until, err := time.Parse(time.RFC3339, subscription.PaidUntil) if err != nil { return false } return until.After(now) } // Remaining is how long a gateway's access runs for. func (l *Ledger) Remaining(gateway string, now time.Time) time.Duration { subscription, ok := l.Subscriptions[strings.ToLower(strings.TrimSpace(gateway))] if !ok { return 0 } until, err := time.Parse(time.RFC3339, subscription.PaidUntil) if err != nil || !until.After(now) { return 0 } return until.Sub(now) } // AmountForDays is what a period costs at the daily rate, rounded up to the second. func (l *Ledger) AmountForDays(days float64) int64 { if days <= 0 || l.RateSatsPerDay <= 0 { return 0 } return int64(days*float64(l.RateSatsPerDay) + 0.5) } func isHex(text string) bool { for i := 0; i < len(text); i++ { c := text[i] if !(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') { return false } } return true }