reads.gno
16.89 Kb · 559 lines
1package mandate
2
3import (
4 "strconv"
5 "strings"
6 "time"
7)
8
9// Free reads. Each returns plain values (copies), never pointers into the
10// realm's state, so callers and vm/qeval cannot change anything.
11
12// PlanInfo is a copy of a plan.
13type PlanInfo struct {
14 ID uint64
15 Payee address
16 Title string
17 Amount int64
18 Period int64
19 CreatedAt int64
20 Mandates int // mandates ever created for this plan
21 Cancelled int // how many of them were cancelled
22 // PaidThisPeriod and PaidLastPeriod count the payments in the plan's
23 // current period window, which started at PeriodStart, and in the window
24 // before it. Windows are [k*Period, (k+1)*Period) in unix time. They count
25 // payments, not distinct people (a creator can pay its own plan from a
26 // second wallet). Historical facts, true at any time, whatever has
27 // expired or been cancelled since.
28 PaidThisPeriod int
29 PaidLastPeriod int
30 PeriodStart int64
31 Pulls int64
32 Paid int64
33 LastPullAt int64
34}
35
36// MandateInfo is a copy of a mandate with the realm's view of it.
37type MandateInfo struct {
38 ID uint64
39 PlanID uint64
40 Payer address
41 Payee address
42 Session address
43 SessionPubKey string
44 Amount int64
45 Period int64
46 CreatedAt int64
47 ExpiresAt int64
48 NextPullAt int64
49 LastPullAt int64
50 // PaidThrough is until when this mandate's payments, or paid time
51 // carried over from the payer's earlier mandate for the plan, cover the
52 // payer (0 if neither). A mandate that starts with carried time has its
53 // first pull at that time.
54 PaidThrough int64
55 Pulls int64
56 Paid int64
57 CancelledAt int64
58 CancelledBy address
59 // Status is "active", "expired" or "cancelled": the realm's view only.
60 Status string
61 // Due is true when the mandate is active and a pull is allowed now.
62 Due bool
63 // SessionPubKey is the session key's public key when it is the payee's
64 // current collector key, "" otherwise.
65 //
66 // SessionQuery is the free query an off-chain checker must also run:
67 // the realm cannot see a session revoked or expired on chain.
68 SessionQuery string
69}
70
71// PayeeInfo is a copy of a payee's totals and collector key.
72type PayeeInfo struct {
73 Addr address
74 Plans int
75 Pulls int64
76 Paid int64
77 LastPullAt int64
78 CollectorKey string
79 CollectorAddr address
80 // CollectorFunded is true when the collector key's address holds coins:
81 // the chain then refuses every new session for that key, so nobody can
82 // subscribe until the creator publishes a new key. (An address that
83 // received coins and was emptied is also refused by the chain; only the
84 // free query auth/accounts/<CollectorAddr> shows that.)
85 CollectorFunded bool
86}
87
88// GetPlan returns the plan with this id.
89func GetPlan(id uint64) (PlanInfo, bool) {
90 p := planOf(id)
91 if p == nil {
92 return PlanInfo{}, false
93 }
94 return p.info(), true
95}
96
97// MandateOf returns the latest mandate of payer for this session address.
98func MandateOf(payer, sessionAddr address) (MandateInfo, bool) {
99 m := latestBySession(payer, sessionAddr)
100 if m == nil {
101 return MandateInfo{}, false
102 }
103 return m.info(time.Now().Unix()), true
104}
105
106// PaidThrough is the read for services that deliver something to paying
107// supporters. It returns the unix time until which the payer's payments for
108// the plan cover them: the latest payment's time plus one period. Paid time
109// stays the payer's when a mandate is cancelled (by either side) or
110// expires, and a new mandate for the same plan starts when it ends, so it
111// is not charged twice. The one exception: a payer who already holds 16
112// kept periods (MaxCreditsPerPayer). 0 when they never paid for the plan.
113// Deliver while now < PaidThrough.
114//
115// It turns false at the due time and moves on only when the payee's
116// collector pulls the next payment: allow a grace equal to how often the
117// collector runs (an hour, say) before treating a supporter as lapsed.
118//
119// A payment is proof; a mandate is not: anyone can record a mandate
120// without creating a session and without paying. A realm also cannot see a
121// session revoked on chain: a revoked supporter simply stops paying, so
122// PaidThrough stops moving and runs out within one period.
123func PaidThrough(payer address, planID uint64) int64 {
124 pr := payerOf(payer)
125 if pr == nil {
126 return 0
127 }
128 now := time.Now().Unix()
129 until := pr.creditFor(planID, now)
130 for _, r := range pr.Active {
131 if r.PlanID == planID {
132 if t := r.M.paidThrough(); t > until {
133 until = t
134 }
135 }
136 }
137 return until
138}
139
140// IsPaidUp reports whether payer's latest payment for the plan still covers
141// now (now < PaidThrough). See PaidThrough.
142func IsPaidUp(payer address, planID uint64) bool {
143 return time.Now().Unix() < PaidThrough(payer, planID)
144}
145
146// HasMandate reports whether payer has a mandate for the plan that is
147// neither cancelled nor expired in the realm. It says nothing about payment
148// (a mandate costs only a storage deposit to record) and cannot see a
149// session revoked on chain: do not grant anything on it; use PaidThrough.
150func HasMandate(payer address, planID uint64) bool {
151 m := activeByPlan(payer, planID)
152 return m != nil && m.isActive(time.Now().Unix())
153}
154
155// NextPullAt returns when the next pull of payer's active mandate for the
156// plan is allowed (unix seconds), or 0 if there is no active mandate.
157func NextPullAt(payer address, planID uint64) int64 {
158 m := activeByPlan(payer, planID)
159 if m == nil || !m.isActive(time.Now().Unix()) {
160 return 0
161 }
162 return m.NextPullAt
163}
164
165// GetPayee returns a payee's totals and collector key.
166func GetPayee(payee address) (PayeeInfo, bool) {
167 pe := payeeOf(payee)
168 if pe == nil {
169 return PayeeInfo{}, false
170 }
171 return PayeeInfo{
172 Addr: pe.Addr,
173 Plans: pe.Plans,
174 Pulls: pe.Pulls,
175 Paid: pe.Paid,
176 LastPullAt: pe.LastPullAt,
177 CollectorKey: pe.CollectorKey,
178 CollectorAddr: pe.CollectorAddr,
179 CollectorFunded: pe.CollectorKey != "" && collectorFunded(pe.CollectorAddr),
180 }, true
181}
182
183// Totals returns the number of plans and mandates, and all pulls so far.
184func Totals() (plansCount, mandatesCount int, pulls, paid int64) {
185 return plans.Size(), int(nextMandateID), totalPulls, totalPaid
186}
187
188// Plans lists all plans, newest first, PageSize per page (page 1 first).
189func Plans(page int) []PlanInfo {
190 out := []PlanInfo{}
191 plans.ReverseIterateByOffset(offset(page), PageSize, func(_ string, v any) bool {
192 out = append(out, v.(*Plan).info())
193 return false
194 })
195 return out
196}
197
198// PlansOf lists a payee's plans, oldest first.
199func PlansOf(payee address, page int) []PlanInfo {
200 out := []PlanInfo{}
201 plans, _ := payeePlans(payee, page)
202 for _, p := range plans {
203 out = append(out, p.info())
204 }
205 return out
206}
207
208// payeePlans returns page `page` of a payee's plans and whether more follow.
209func payeePlans(payee address, page int) ([]*Plan, bool) {
210 pe := payeeOf(payee)
211 if pe == nil {
212 return nil, false
213 }
214 lo, hi, more := pageBounds(pe.planIDs.N, page)
215 out := make([]*Plan, 0, hi-lo)
216 for i := lo; i < hi; i++ {
217 id, _ := strconv.ParseUint(pe.planIDs.at(i), 10, 64)
218 out = append(out, planOf(id))
219 }
220 return out, more
221}
222
223// MandatesOf lists a payer's mandates (all states), newest first.
224func MandatesOf(payer address, page int) []MandateInfo {
225 list, _ := payerPage(payer, page)
226 return infos(list)
227}
228
229// payerPage returns page `page` of the payer's mandates, newest first, and
230// whether another page follows. It walks the payer's history, which only
231// free reads do.
232func payerPage(payer address, page int) ([]*Mandate, bool) {
233 skip := offset(page)
234 out := []*Mandate{}
235 for m := payerHead(payer); m != nil; m = m.prevOfPayer {
236 if skip > 0 {
237 skip--
238 continue
239 }
240 if len(out) == PageSize {
241 return out, true
242 }
243 out = append(out, m)
244 }
245 return out, false
246}
247
248// SupportersOf lists a plan's active mandates (not cancelled, replaced or
249// expired), oldest first. Page n covers entries (n-1)*PageSize to
250// n*PageSize-1 of the plan's list, so a page may hold fewer rows than
251// PageSize; inactive ones are on the payers' own pages.
252func SupportersOf(planID uint64, page int) []MandateInfo {
253 p := planOf(planID)
254 if p == nil {
255 return []MandateInfo{}
256 }
257 now := time.Now().Unix()
258 out := []MandateInfo{}
259 lo, hi, _ := pageBounds(p.Supporters.N, page)
260 for i := lo; i < hi; i++ {
261 e := decodeEntry(p.Supporters.at(i))
262 if e.Status == statusCancelled {
263 continue
264 }
265 if m := activeMandate(e); m != nil && m.isActive(now) {
266 out = append(out, m.info(now))
267 }
268 }
269 return out
270}
271
272// ScanLimit is the most supporter-list entries one free read resolves
273// (looks up in its payer's record); WalkLimit is the most it reads at all.
274// Entries carry their status, so cancelled ones, and for some reads unpaid
275// ones, are skipped without a lookup. Reads that filter return a cursor to
276// continue from, so junk can delay but never hide a real entry.
277const (
278 ScanLimit = 200
279 WalkLimit = 1000
280)
281
282// CollectorPlans lists a payee's plans for a collector script, one per line:
283//
284// <plan id> <amount ugnot> <period seconds> <mandates>
285//
286// PageSize per page; the last line is "more" or "end".
287func CollectorPlans(payee address, page int) string {
288 var b strings.Builder
289 more := false
290 if list, m := payeePlans(payee, page); list != nil {
291 more = m
292 for _, p := range list {
293 b.WriteString(utoa(p.ID) + " " + itoa(p.Amount) + " " + itoa(p.Period) + " " + strconv.Itoa(p.Supporters.N) + "\n")
294 }
295 }
296 if more {
297 b.WriteString("more\n")
298 } else {
299 b.WriteString("end\n")
300 }
301 return b.String()
302}
303
304// CollectorScan walks at most ScanLimit entries of a plan's supporter list,
305// from index `from` (0 = oldest), and returns the active mandates whose
306// session key is sessionAddr, one per line:
307//
308// <index> <mandate id> <payer> <amount ugnot> <next pull unix> <due|wait> <pulls> <paid>
309//
310// <paid> is 1 when the payer has paid for this plan (this mandate pulled, or
311// it started with paid time carried over from an earlier one), 0 when it
312// never has. The last line is "next <index>" when more entries follow,
313// "end" otherwise. Cancelled and expired mandates, and mandates for other
314// keys, are skipped here, so a collector never needs to read them. Anyone
315// can record a mandate without a session, so a collector should check on
316// chain that the session exists, at least before the first pull of a
317// mandate whose payer never paid.
318func CollectorScan(planID uint64, sessionAddr address, from int) string {
319 p := planOf(planID)
320 if p == nil {
321 return "end\n"
322 }
323 if from < 0 {
324 from = 0
325 }
326 if from > p.Supporters.N {
327 from = p.Supporters.N // also keeps from+ScanLimit from overflowing
328 }
329 now := time.Now().Unix()
330 var b strings.Builder
331 end := from + ScanLimit
332 if end > p.Supporters.N {
333 end = p.Supporters.N
334 }
335 for i := from; i < end; i++ {
336 e := decodeEntry(p.Supporters.at(i))
337 if e.Status == statusCancelled {
338 continue
339 }
340 pr := payerOf(e.Payer)
341 if pr == nil {
342 continue
343 }
344 var m *Mandate
345 for _, r := range pr.Active {
346 if r.ID == e.ID && r.Session == sessionAddr {
347 m = r.M
348 }
349 }
350 if m == nil || !m.isActive(now) {
351 continue
352 }
353 due := "wait"
354 if now >= m.NextPullAt {
355 due = "due"
356 }
357 b.WriteString(strconv.Itoa(i) + " " + utoa(m.ID) + " " + m.Payer.String() + " " + itoa(p.Amount) + " " +
358 itoa(m.NextPullAt) + " " + due + " " + itoa(m.Pulls) + " " + paidFlag(m) + "\n")
359 }
360 if end < p.Supporters.N {
361 b.WriteString("next " + strconv.Itoa(end) + "\n")
362 } else {
363 b.WriteString("end\n")
364 }
365 return b.String()
366}
367
368// payingFrom lists a plan's supporters: mandates that have paid at least
369// once and are active now, newest first, up to PageSize, starting at list
370// index `from` (or the newest when from < 0). It reads at most WalkLimit
371// entries and resolves at most ScanLimit of them (only entries marked paid
372// are resolved), and returns the index to continue from (-1 when the list is
373// exhausted).
374func payingFrom(p *Plan, from int, now int64) ([]*Mandate, int) {
375 if from < 0 || from >= p.Supporters.N {
376 from = p.Supporters.N - 1
377 }
378 out := []*Mandate{}
379 i, walked, resolved := from, 0, 0
380 for ; i >= 0 && walked < WalkLimit && resolved < ScanLimit && len(out) < PageSize; i, walked = i-1, walked+1 {
381 e := decodeEntry(p.Supporters.at(i))
382 if e.Status != statusPaid {
383 continue
384 }
385 resolved++
386 if m := activeMandate(e); m != nil && m.isActive(now) {
387 out = append(out, m)
388 }
389 }
390 return out, i
391}
392
393// PayingSupporters lists a plan's supporters the way its gnoweb page does:
394// mandates that have paid at least once and are active now, newest first,
395// at most PageSize per call. Pass from = -1 for the newest; the second
396// result is where to continue. A client must stop when it is -1 (the list
397// is exhausted): -1 passed back in starts again from the newest, so a
398// client that feeds the cursor back unchecked loops for ever. Each call
399// walks at most WalkLimit entries and looks up at most ScanLimit of them,
400// so a call may return fewer than PageSize (even none) and still a cursor.
401func PayingSupporters(planID uint64, from int) ([]MandateInfo, int) {
402 p := planOf(planID)
403 if p == nil {
404 return []MandateInfo{}, -1
405 }
406 now := time.Now().Unix()
407 list, next := payingFrom(p, from, now)
408 out := make([]MandateInfo, 0, len(list))
409 for _, m := range list {
410 out = append(out, m.info(now))
411 }
412 return out, next
413}
414
415// PlanCounts returns the numbers the gnoweb plan page shows: how many
416// supporters paid in the plan's current period window and in the one
417// before (as in GetPlan), and how many active mandates have never paid,
418// among the latest ScanLimit entries (unpaidExact is false when there were
419// more entries than that).
420func PlanCounts(planID uint64) (paidThisPeriod, paidLastPeriod, unpaid int, unpaidExact bool) {
421 p := planOf(planID)
422 if p == nil {
423 return 0, 0, 0, true
424 }
425 now := time.Now().Unix()
426 paidThisPeriod, paidLastPeriod = p.paidWindows(now)
427 unpaid, unpaidExact = countUnpaid(p, now)
428 return
429}
430
431// countUnpaid counts active mandates that have never paid, among the
432// plan's latest ScanLimit mandates, and says whether that covered them all.
433func countUnpaid(p *Plan, now int64) (int, bool) {
434 n := 0
435 lo := p.Supporters.N - ScanLimit
436 if lo < 0 {
437 lo = 0
438 }
439 for i := p.Supporters.N - 1; i >= lo; i-- {
440 e := decodeEntry(p.Supporters.at(i))
441 if e.Status != statusUnpaid {
442 continue
443 }
444 if m := activeMandate(e); m != nil && m.isActive(now) {
445 n++
446 }
447 }
448 return n, lo == 0
449}
450
451func infos(list []*Mandate) []MandateInfo {
452 now := time.Now().Unix()
453 out := []MandateInfo{}
454 for _, m := range list {
455 out = append(out, m.info(now))
456 }
457 return out
458}
459
460func (p *Plan) info() PlanInfo {
461 now := time.Now().Unix()
462 current, previous := p.paidWindows(now)
463 return PlanInfo{
464 ID: p.ID,
465 Payee: p.Payee,
466 Title: p.Title,
467 Amount: p.Amount,
468 Period: p.Period,
469 CreatedAt: p.CreatedAt,
470 Mandates: p.Supporters.N,
471 Cancelled: p.Cancelled,
472 PaidThisPeriod: current,
473 PaidLastPeriod: previous,
474 PeriodStart: now / p.Period * p.Period,
475 Pulls: p.Pulls,
476 Paid: p.Pulls * p.Amount,
477 LastPullAt: p.LastPullAt,
478 }
479}
480
481func (m *Mandate) info(now int64) MandateInfo {
482 p := m.plan
483 st := m.status(now)
484 return MandateInfo{
485 ID: m.ID,
486 PlanID: p.ID,
487 Payer: m.Payer,
488 Payee: p.Payee,
489 Session: m.Session,
490 SessionPubKey: m.sessionPubKey(),
491 Amount: p.Amount,
492 Period: p.Period,
493 CreatedAt: m.CreatedAt,
494 ExpiresAt: m.ExpiresAt,
495 NextPullAt: m.NextPullAt,
496 LastPullAt: m.lastPullAt(),
497 PaidThrough: m.paidThrough(),
498 Pulls: m.Pulls,
499 Paid: m.Pulls * p.Amount,
500 CancelledAt: m.CancelledAt,
501 CancelledBy: m.CancelledBy,
502 Status: st,
503 Due: st == "active" && now >= m.NextPullAt,
504 SessionQuery: "auth/accounts/" + m.Payer.String() + "/session/" + m.Session.String(),
505 }
506}
507
508// lastPullAt is when the last pull happened (0 = never): each pull sets
509// NextPullAt to its own time plus one period.
510func (m *Mandate) lastPullAt() int64 {
511 if m.Pulls == 0 {
512 return 0
513 }
514 return m.NextPullAt - m.plan.Period
515}
516
517// sessionPubKey returns the session key's public key when it is the payee's
518// current collector key, "" otherwise (the realm then does not know it).
519func (m *Mandate) sessionPubKey() string {
520 if pe := m.plan.payee; pe.CollectorAddr == m.Session {
521 return pe.CollectorKey
522 }
523 return ""
524}
525
526// offset turns a 1-based page number into a row offset; pages below 1 and
527// absurdly large pages are clamped.
528func offset(page int) int {
529 if page < 1 {
530 page = 1
531 }
532 if page > 1_000_000 {
533 page = 1_000_000
534 }
535 return (page - 1) * PageSize
536}
537
538// pageBounds returns the slice bounds of page `page` (1-based, PageSize
539// rows) in a list of n rows, and whether another page follows.
540func pageBounds(n, page int) (lo, hi int, more bool) {
541 lo = offset(page)
542 if lo > n {
543 lo = n
544 }
545 hi = lo + PageSize
546 if hi > n {
547 hi = n
548 }
549 return lo, hi, hi < n
550}
551
552// paidFlag is CollectorScan's last column: "1" once the payer has paid for
553// the plan through this mandate or carried paid time into it, else "0".
554func paidFlag(m *Mandate) string {
555 if m.paidThrough() > 0 {
556 return "1"
557 }
558 return "0"
559}