1 package billing
2 3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10 "time"
11 )
12 13 // Subscription is one gateway's paid-for access to a relay.
14 type Subscription struct {
15 Gateway string `json:"gateway"`
16 PaidUntil string `json:"paid_until"`
17 TotalSats int64 `json:"total_sats"`
18 LastPaymentAt string `json:"last_payment_at"`
19 }
20 21 // Ledger is the relay's record of who has paid for how long.
22 //
23 // Payments arrive by keysend with the gateway's own public key as the preimage, so the ledger needs
24 // no accounts and no reference field: the payment says who paid, and the amount divided by the
25 // daily rate says how long it buys. Preimages are remembered so replaying the same payment from a
26 // wallet's transaction list does not buy the same time twice.
27 type Ledger struct {
28 // Path is where the ledger is stored. Empty keeps it in memory.
29 Path string
30 // RateSatsPerDay is the price of one day of access.
31 RateSatsPerDay int64 `json:"rate_sats_per_day"`
32 33 Subscriptions map[string]Subscription `json:"subscriptions"`
34 // Watermarks remember, per gateway, the settle time of the newest payment already credited.
35 // Keysend payments from one gateway share a preimage (it is the gateway's key), so the wallet
36 // cannot tell two of them apart by preimage; the settle time is the only thing that can, and
37 // it is what makes rescanning the wallet idempotent.
38 Watermarks map[string]int64 `json:"watermarks"`
39 // Blocked is the operator's own decision, kept beside the payments rather than inside them:
40 // blocking a gateway does not erase what it paid.
41 Blocked map[string]bool `json:"blocked,omitempty"`
42 }
43 44 // OpenLedger loads the ledger at path. A missing file is an empty ledger.
45 func OpenLedger(path string, ratePerDay int64) (*Ledger, error) {
46 ledger := &Ledger{Path: path, RateSatsPerDay: ratePerDay}
47 48 body, err := os.ReadFile(path)
49 50 if errors.Is(err, os.ErrNotExist) {
51 return ledger.withMaps(), nil
52 }
53 54 if err != nil {
55 return nil, fmt.Errorf("billing: %w", err)
56 }
57 58 if err := json.Unmarshal(body, ledger); err != nil {
59 return nil, fmt.Errorf("billing: %s: %w", path, err)
60 }
61 62 ledger.Path = path
63 64 // The file's rate wins when it has one: the relay is the side that sets a price, and the
65 // billing sidecar is told to follow it.
66 if ledger.RateSatsPerDay == 0 {
67 ledger.RateSatsPerDay = ratePerDay
68 }
69 70 return ledger.withMaps(), nil
71 }
72 73 func (l *Ledger) withMaps() *Ledger {
74 if l.Subscriptions == nil {
75 l.Subscriptions = map[string]Subscription{}
76 }
77 78 if l.Watermarks == nil {
79 l.Watermarks = map[string]int64{}
80 }
81 82 return l
83 }
84 85 // Save writes the ledger atomically.
86 func (l *Ledger) Save() error {
87 if l.Path == "" {
88 return nil
89 }
90 91 body, err := json.MarshalIndent(l, "", " ")
92 93 if err != nil {
94 return fmt.Errorf("billing: %w", err)
95 }
96 97 if err := os.MkdirAll(filepath.Dir(l.Path), 0o700); err != nil {
98 return fmt.Errorf("billing: %w", err)
99 }
100 101 stage, err := os.CreateTemp(filepath.Dir(l.Path), ".ledger-*")
102 103 if err != nil {
104 return fmt.Errorf("billing: %w", err)
105 }
106 107 name := stage.Name()
108 109 if _, err := stage.Write(append(body, '\n')); err != nil {
110 stage.Close()
111 os.Remove(name)
112 113 return fmt.Errorf("billing: %w", err)
114 }
115 116 if err := stage.Sync(); err != nil {
117 stage.Close()
118 os.Remove(name)
119 120 return fmt.Errorf("billing: %w", err)
121 }
122 123 if err := stage.Close(); err != nil {
124 os.Remove(name)
125 126 return fmt.Errorf("billing: %w", err)
127 }
128 129 if err := os.Chmod(name, 0o600); err != nil {
130 os.Remove(name)
131 132 return fmt.Errorf("billing: %w", err)
133 }
134 135 if err := os.Rename(name, l.Path); err != nil {
136 os.Remove(name)
137 138 return fmt.Errorf("billing: %w", err)
139 }
140 141 return nil
142 }
143 144 // Credit records one payment. The preimage is the paying gateway's public key; the amount buys
145 // Amount/rate days of access from now, or from the end of the access already paid for, so a
146 // gateway that renews early does not lose the time it had.
147 func (l *Ledger) Credit(preimageHex string, amountSats int64, settledAt int64, now time.Time) (Subscription, error) {
148 gateway := strings.ToLower(strings.TrimSpace(preimageHex))
149 150 if len(gateway) != 64 || !isHex(gateway) {
151 return Subscription{}, fmt.Errorf("billing: preimage %q is not a gateway public key", preimageHex)
152 }
153 154 if amountSats <= 0 {
155 return Subscription{}, fmt.Errorf("billing: payment of %d sats credits nothing", amountSats)
156 }
157 158 if l.RateSatsPerDay <= 0 {
159 return Subscription{}, errors.New("billing: no daily rate is set, so a payment cannot be priced")
160 }
161 162 if settledAt > 0 && settledAt <= l.Watermarks[gateway] {
163 // Already counted: this is the same payment seen again in the wallet's list.
164 return l.Subscriptions[gateway], nil
165 }
166 167 // Time is bought in seconds of the day, which keeps small payments honest instead of
168 // rounding them to nothing or to a whole day.
169 seconds := amountSats * 86400 / l.RateSatsPerDay
170 171 if seconds <= 0 {
172 return Subscription{}, fmt.Errorf("billing: %d sats is less than one second at %d sats/day",
173 amountSats, l.RateSatsPerDay)
174 }
175 176 current := l.Subscriptions[gateway]
177 start := now
178 179 if parsed, err := time.Parse(time.RFC3339, current.PaidUntil); err == nil && parsed.After(now) {
180 start = parsed
181 }
182 183 next := Subscription{
184 Gateway: gateway,
185 PaidUntil: start.Add(time.Duration(seconds) * time.Second).UTC().Format(time.RFC3339),
186 TotalSats: current.TotalSats + amountSats,
187 LastPaymentAt: now.UTC().Format(time.RFC3339),
188 }
189 190 l.Subscriptions[gateway] = next
191 192 if settledAt > l.Watermarks[gateway] {
193 l.Watermarks[gateway] = settledAt
194 }
195 196 return next, nil
197 }
198 199 // Paid reports whether a gateway is paid up at now.
200 func (l *Ledger) Paid(gateway string, now time.Time) bool {
201 subscription, ok := l.Subscriptions[strings.ToLower(strings.TrimSpace(gateway))]
202 203 if !ok {
204 return false
205 }
206 207 until, err := time.Parse(time.RFC3339, subscription.PaidUntil)
208 209 if err != nil {
210 return false
211 }
212 213 return until.After(now)
214 }
215 216 // Remaining is how long a gateway's access runs for.
217 func (l *Ledger) Remaining(gateway string, now time.Time) time.Duration {
218 subscription, ok := l.Subscriptions[strings.ToLower(strings.TrimSpace(gateway))]
219 220 if !ok {
221 return 0
222 }
223 224 until, err := time.Parse(time.RFC3339, subscription.PaidUntil)
225 226 if err != nil || !until.After(now) {
227 return 0
228 }
229 230 return until.Sub(now)
231 }
232 233 // AmountForDays is what a period costs at the daily rate, rounded up to the second.
234 func (l *Ledger) AmountForDays(days float64) int64 {
235 if days <= 0 || l.RateSatsPerDay <= 0 {
236 return 0
237 }
238 239 return int64(days*float64(l.RateSatsPerDay) + 0.5)
240 }
241 242 func isHex(text string) bool {
243 for i := 0; i < len(text); i++ {
244 c := text[i]
245 246 if !(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') {
247 return false
248 }
249 }
250 251 return true
252 }
253