mandate.gno
22.43 Kb · 608 lines
1// Package mandate is capped, revocable direct debit on native GNOT, built on
2// Gno session keys.
3//
4// A payee publishes a plan ("1 GNOT every 7 days"). A payer subscribes with
5// two things signed by the payer's own key:
6//
7// 1. a session on chain for the payee's collector key, scoped to this realm
8// only, with a spend limit of the plan's amount plus a small fee
9// allowance per period, and an expiry;
10// 2. Subscribe here, which records the terms for that session.
11//
12// The payee's collector then calls Pull once per period, signed with the
13// session key on behalf of the payer and sending exactly the plan's amount.
14// The realm is the rulebook: it checks who, how much and when, then forwards
15// the coins to the payee in the same transaction. It never keeps funds.
16//
17// Honest limits, also shown on the home page:
18// - It is direct debit, not escrow. A payer can revoke the session, cancel,
19// or empty the account at any time; the payee is then not paid.
20// - The chain caps what the payer can lose per period at the session's
21// spend limit: amount plus fee allowance. A hostile payee can burn the
22// allowance as gas fees (it goes to the network, not to the payee).
23// - The chain allows at most 16 sessions per account, so a wallet can have
24// at most 16 mandates at a time.
25// - A realm cannot see an on-chain session revoke. A service deciding
26// whether someone has paid reads PaidThrough, which moves only when a
27// payment succeeds; HasMandate is only the realm's view (recorded, not
28// cancelled, not expired), and the chain's own view of the session is
29// the free query auth/accounts/<payer>/session/<session address>.
30// - A session scoped to vm/exec:<this realm> also allows every realm under
31// this path (the chain's scope match is prefix-based). Nothing must ever
32// be deployed under a sub-path of this realm. Pull also refuses any
33// session whose allow list is not exactly this realm, but that cannot
34// protect a payer from a sub-realm called directly.
35//
36// There is no admin, owner, pause, upgrade or sweep.
37package mandate
38
39import (
40 "chain"
41 "chain/banker"
42 "chain/runtime"
43 "chain/runtime/unsafe"
44 "strconv"
45 "strings"
46 "time"
47 "unicode"
48 "unicode/utf8"
49
50 "gno.land/p/nt/avl/v0"
51)
52
53// Denom is the only coin a plan can be paid in.
54const Denom = "ugnot"
55
56// Limits. See docs/design.md for the reasoning behind each value.
57const (
58 // MinAmount is the smallest plan amount, 0.1 GNOT. A Pull uses about
59 // 8-9M gas on a local chain, and the chain charges the whole fee the
60 // signer sets, not the gas used: the pages set 20,000 ugnot for 20M gas
61 // wanted (Onyx's minimum price of 1 ugnot per 1,000 gas). At 0.1 GNOT that
62 // fee is already a fifth of the payment; below it, fees would dominate.
63 MinAmount int64 = 100_000
64 // MaxAmount is 1,000,000 GNOT per period: far above any real plan, and
65 // low enough that totals cannot overflow int64 for millions of pulls.
66 MaxAmount int64 = 1_000_000_000_000
67 // MinPeriod is one minute: block times are a few seconds, and the
68 // chain's spend period is counted in seconds. Short periods exist for
69 // demos and tests; pages flag any period under a day.
70 MinPeriod int64 = 60
71 // MaxPeriod is 30 days, exactly the chain's limit on a session's spend
72 // period (tm2 std.MaxSpendPeriod). The session's spend period is always
73 // the plan's period, so the cap the pages promise ("at most price +
74 // allowance per period") is exactly what the chain enforces. No yearly
75 // plans: the chain refuses a session whose spend period is longer.
76 MaxPeriod int64 = 30 * 24 * 60 * 60
77 // MaxTerm is the longest a mandate may run from the moment it is
78 // created: 366 days. A payer renews once a year at most; the chain's own
79 // cap on a session's expiry is 4 x 365 days (tm2 std.MaxSessionDuration).
80 MaxTerm int64 = 366 * 24 * 60 * 60
81 // FeeAllowance is what the pages add to the session's spend limit for
82 // fees and storage (0.1 GNOT). The chain accepts a fee when fee / gas
83 // wanted is at least the current gas price (1 ugnot per 1,000 gas on
84 // Onyx, raised by the chain when blocks are full), and counts the Pull's
85 // storage deposit against the same limit. With the pages' 20M gas wanted
86 // the minimum fee is 20,000 ugnot. A Pull creates no object: a first
87 // payment adds at most 78 bytes measured (7,800 ugnot at 100 ugnot per
88 // byte), later ones nothing. So the worst pull costs about 28,000 ugnot
89 // and the allowance covers a gas price up to about 4.5x Onyx's current
90 // one (docs/design.md, "Pull's budget").
91 FeeAllowance int64 = 100_000
92 // MaxTitleLen is the longest plan title, in characters.
93 MaxTitleLen = 80
94 // PageSize is the number of rows per list page and per read call.
95 PageSize = 20
96 // MaxSessionsPerWallet is the chain's limit (tm2 std.MaxSessionsPerAccount).
97 MaxSessionsPerWallet = 16
98)
99
100// Plan is published by a payee and never changes. New terms mean a new plan.
101type Plan struct {
102 ID uint64
103 Payee address
104 Title string
105 Amount int64 // ugnot per period
106 Period int64 // seconds
107 CreatedAt int64 // unix seconds
108
109 Supporters fixedList // every mandate for this plan, oldest first (see encodeEntry)
110 Cancelled int // how many of them were cancelled
111 Pulls int64 // successful pulls (paid = Pulls * Amount)
112 LastPullAt int64 // unix seconds, 0 = never
113
114 // Payments per period window: window k is [k*Period, (k+1)*Period). A
115 // mandate pays at most once in a window, and paid time carries over to a
116 // payer's next mandate for the plan, so a payer is not charged twice for
117 // one period (except when 16 kept periods are already held, see
118 // MaxCreditsPerPayer); but these count payments, not distinct people (a creator
119 // can pay its own plan from a second wallet). Read with paidWindows, which
120 // turns them into counts for the window containing "now" and the one
121 // before it, so they are true at any time without a transaction.
122 payWindow int64 // index of the window of the last payment
123 paidThis int // payments in window payWindow
124 paidPrev int // payments in window payWindow-1
125
126 payee *Payee // direct link, so Pull needs no lookup
127}
128
129// Mandate is one payer's permission for one session key on one plan. It
130// keeps only what cannot be derived: the amount paid is Pulls * the plan's
131// amount, and the last pull was one period before NextPullAt.
132type Mandate struct {
133 ID uint64
134 Payer address
135 Session address // address of the session key the payee holds
136 CreatedAt int64
137 ExpiresAt int64 // unix seconds; pulls are refused from this time on
138 NextPullAt int64 // unix seconds; the first pull is due at once
139 Pulls int64
140 Index int // position in the plan's supporter list
141
142 CancelledAt int64 // 0 = not cancelled
143 CancelledBy address
144
145 plan *Plan // direct link, so Pull needs no lookup
146 prevOfPayer *Mandate // the payer's previous mandate (history, newest first)
147}
148
149// Payee holds a payee's plans, totals and published collector key.
150type Payee struct {
151 Addr address
152 Plans int
153 planIDs fixedList // the payee's plan ids, padded (values, not pointers)
154 Pulls int64
155 Paid int64
156 LastPullAt int64
157 CollectorKey string // bech32 public key (gpub1...), empty if not set
158 CollectorAddr address // address derived from CollectorKey by the chain
159}
160
161// State. Storage is paid per byte (100 ugnot) and gas mostly per object
162// read or written, so the layout keeps both small, and nothing one address
163// does can grow what another payer's calls read (docs/design.md):
164// - plans, payees and payers live in avl trees: an attacker can only add
165// depth (log2 of the number of entries);
166// - each payer's lookups live in that payer's own record (Payer, stored
167// by value in the tree), capped at MaxActivePerPayer active mandates
168// and MaxCreditsPerPayer kept credits;
169// - each plan's supporter list holds small values in chunks (see
170// fixedList), so adding one costs the same however long it is;
171// - a payer's history is a linked list through the mandates, walked only
172// by free reads.
173var (
174 realmPath string // this realm's package path, captured at init
175
176 nextPlanID uint64
177 nextMandateID uint64
178
179 plans = avl.NewTree() // pad(planID) -> *Plan
180 payees = avl.NewTree() // payee -> *Payee
181 payers = avl.NewTree() // payer -> Payer (a value, not a pointer)
182
183 totalPulls int64
184 totalPaid int64
185)
186
187func init() {
188 realmPath = unsafe.CurrentRealm().PkgPath()
189}
190
191// Offer publishes a plan: amountUgnot every periodSeconds, paid to the
192// caller. Signed with the payee's own key; no session, no coins.
193func Offer(cur realm, title string, amountUgnot, periodSeconds int64) uint64 {
194 caller := directCaller(cur)
195 if err := validateTitle(title); err != "" {
196 panic(err)
197 }
198 if amountUgnot < MinAmount {
199 panic("mandate: amount is below the minimum of " + formatUgnot(MinAmount))
200 }
201 if amountUgnot > MaxAmount {
202 panic("mandate: amount is above the maximum of " + formatUgnot(MaxAmount))
203 }
204 if periodSeconds < MinPeriod {
205 panic("mandate: period is below the minimum of " + itoa(MinPeriod) + " seconds")
206 }
207 if periodSeconds > MaxPeriod {
208 panic("mandate: period is above the maximum of " + itoa(MaxPeriod) + " seconds")
209 }
210 nextPlanID++
211 p := &Plan{
212 ID: nextPlanID,
213 Payee: caller,
214 Title: title,
215 Amount: amountUgnot,
216 Period: periodSeconds,
217 CreatedAt: time.Now().Unix(),
218 }
219 pe := payeeOf(caller)
220 if pe == nil {
221 pe = &Payee{Addr: caller}
222 payees.Set(caller.String(), pe)
223 }
224 p.payee = pe
225 plans.Set(pad(p.ID), p)
226 pe.Plans++
227 pe.planIDs.add(pad(p.ID))
228 chain.Emit("PlanOffered",
229 "plan", utoa(p.ID),
230 "payee", caller.String(),
231 "title", p.Title,
232 "amount", itoa(p.Amount),
233 "period", itoa(p.Period),
234 )
235 return p.ID
236}
237
238// SetCollectorKey publishes the public key (bech32, gpub1...) of the key the
239// payee's collector signs pulls with. Plan pages show it in the copy-ready
240// commands, so payers create their session for the right key. Signed with
241// the payee's own key. It does not change existing mandates.
242func SetCollectorKey(cur realm, pubKey string) {
243 caller := directCaller(cur)
244 if len(pubKey) > 200 || !strings.HasPrefix(pubKey, "gpub1") {
245 panic("mandate: collector key must be a bech32 public key starting with gpub1")
246 }
247 addr, err := chain.PubKeyAddress(pubKey)
248 if err != nil || !addr.IsValid() {
249 panic("mandate: collector key is not a valid public key")
250 }
251 if addr == caller {
252 panic("mandate: use a dedicated key for collecting, not your main key")
253 }
254 if collectorFunded(addr) {
255 panic("mandate: this key's address " + addr.String() + " has received coins, so it is an account and the chain will refuse every new session for it; make a new key and never send coins to it")
256 }
257 pe := payeeOf(caller)
258 if pe == nil {
259 pe = &Payee{Addr: caller}
260 payees.Set(caller.String(), pe)
261 }
262 pe.CollectorKey = pubKey
263 pe.CollectorAddr = addr
264 chain.Emit("CollectorKeySet", "payee", caller.String(), "pubkey", pubKey, "address", addr.String())
265}
266
267// Subscribe records the terms for one session: the payer allows the holder
268// of sessionAddr to pull the plan's amount once per period until
269// expiresAtUnix, through this realm only. Signed with the payer's own key
270// (never a session), no coins. Create the session on chain in the same
271// transaction or just before (see the plan page for the exact command).
272//
273// The first payment is collected by the first Pull, which is due at once
274// (billing in advance: each period is paid at its start).
275func Subscribe(cur realm, planID uint64, sessionAddr address, expiresAtUnix int64) uint64 {
276 payer := directCaller(cur)
277 p := planOf(planID)
278 if p == nil {
279 panic("mandate: no such plan")
280 }
281 if payer == p.Payee {
282 panic("mandate: you cannot subscribe to your own plan")
283 }
284 if !sessionAddr.IsValid() {
285 panic("mandate: invalid session address")
286 }
287 if sessionAddr == payer || sessionAddr == p.Payee {
288 panic("mandate: the session address must be a dedicated session key, not a wallet")
289 }
290 now := time.Now().Unix()
291 if expiresAtUnix <= now {
292 panic("mandate: expiry must be in the future")
293 }
294 if expiresAtUnix > now+MaxTerm {
295 panic("mandate: expiry is more than " + itoa(MaxTerm/86400) + " days away")
296 }
297 pr := payerOf(payer)
298 if pr == nil {
299 pr = &Payer{}
300 }
301 // Time already paid for on this plan carries over. Take this plan's
302 // credit before pruning, so the prune can never evict the credit about
303 // to be used; then take the one the prune may have made from an expired
304 // mandate for this plan (at most one of the two exists).
305 until := pr.takeCredit(planID, now)
306 // An expired mandate's lookups go when its payer subscribes again; the
307 // paid time of an expired mandate for this plan comes back directly.
308 if u := pr.pruneExpired(payer, planID, now); u > until {
309 until = u
310 }
311 for _, r := range pr.Active {
312 if r.Session == sessionAddr {
313 panic("mandate: this session already has an active mandate; cancel it first or use another session key")
314 }
315 if r.PlanID == planID {
316 panic("mandate: you already have an active mandate for this plan")
317 }
318 }
319 if len(pr.Active) >= MaxActivePerPayer {
320 panic("mandate: at most " + strconv.Itoa(MaxActivePerPayer) + " active mandates per wallet (the chain allows " + strconv.Itoa(MaxSessionsPerWallet) + " sessions); cancel one first")
321 }
322 // The first pull of the new mandate is due when the paid time ends. The
323 // new mandate must outlive it: otherwise it would be listed as paid,
324 // expire without ever paying, and hand the credit back, again and again.
325 first := now
326 carried := int64(0) // paid time carried over: until when, or 0
327 status := byte(statusUnpaid)
328 if until > now {
329 if expiresAtUnix <= until {
330 panic("mandate: this plan is already paid for until " + formatTime(until) + " (unix " + itoa(until) + "); choose an expiry after that")
331 }
332 first, carried = until, until
333 status = statusPaid // covered now, so listed as a supporter
334 }
335 nextMandateID++
336 m := &Mandate{
337 ID: nextMandateID,
338 Payer: payer,
339 Session: sessionAddr,
340 CreatedAt: now,
341 ExpiresAt: expiresAtUnix,
342 NextPullAt: first,
343 Index: p.Supporters.N,
344 plan: p,
345 prevOfPayer: pr.Head,
346 }
347 pr.Head = m
348 pr.Active = append(pr.Active, activeRef{Session: sessionAddr, PlanID: planID, ID: m.ID, M: m})
349 pr.save(payer)
350 p.Supporters.add(encodeEntry(payer, m.ID, status))
351 chain.Emit("Subscribed",
352 "mandate", utoa(m.ID),
353 "plan", utoa(planID),
354 "payer", payer.String(),
355 "payee", p.Payee.String(),
356 "session", sessionAddr.String(),
357 "expires", itoa(expiresAtUnix),
358 "first", itoa(first),
359 "carried", itoa(carried),
360 )
361 return m.ID
362}
363
364// Pull collects one period's payment. It must be signed with the mandate's
365// session key on behalf of the payer (gnokey ... -master <payer>
366// <session key>), as a direct call, sending exactly the plan's amount. The
367// realm forwards the coins to the plan's payee in the same transaction.
368// At most one pull per period; the next one is due one period after this
369// one, the same rule the chain applies to the session's spend period.
370func Pull(cur realm) {
371 if !cur.Previous().IsUserCall() {
372 panic("mandate: Pull must be a direct call")
373 }
374 sess, _, paths, isSession := runtime.GetSessionInfo()
375 now := time.Now().Unix()
376 m, p := checkPull(isSession, sess, paths, unsafe.OriginCaller(), unsafe.OriginSend(), now)
377 recordPull(m, p, now) // state and event first, then the transfer
378 b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
379 b.SendCoins(cur.Address(), p.Payee, chain.Coins{chain.NewCoin(Denom, p.Amount)})
380}
381
382// checkPull applies every rule of Pull to the transaction's session info,
383// signer and coins, and returns the mandate and plan to pay, or panics.
384// It is separate from Pull so the rules can be unit-tested: `gno test`
385// cannot sign with a session key.
386func checkPull(isSession bool, sess address, paths []string, payer address, sent chain.Coins, now int64) (*Mandate, *Plan) {
387 if !isSession {
388 panic("mandate: Pull must be signed with the mandate's session key")
389 }
390 if len(paths) != 1 || paths[0] != "vm/exec:"+realmPath {
391 panic("mandate: the session must be scoped to exactly vm/exec:" + realmPath)
392 }
393 m := activeBySession(payer, sess)
394 if m == nil {
395 panic("mandate: no active mandate for this session (never recorded, cancelled or replaced)")
396 }
397 if now >= m.ExpiresAt {
398 panic("mandate: expired")
399 }
400 if now < m.NextPullAt {
401 panic("mandate: too early, next pull from " + itoa(m.NextPullAt))
402 }
403 p := m.plan
404 if len(sent) != 1 || sent[0].Denom != Denom || sent[0].Amount != p.Amount {
405 panic("mandate: send exactly " + itoa(p.Amount) + Denom)
406 }
407 return m, p
408}
409
410// recordPull updates the mandate, plan, payee and totals for one payment
411// and emits the event. It never creates an object: Pull runs under the
412// payer's session budget, which also pays its storage deposit. A first pull
413// flips the mandate's entry in the plan's list from unpaid to paid in place
414// (same width) and sets fields that were zero (amino omits zero values), a
415// few dozen bytes at most; later pulls add nothing.
416func recordPull(m *Mandate, p *Plan, now int64) {
417 m.NextPullAt = now + p.Period
418 if m.Pulls == 0 {
419 p.Supporters.setStatus(m.Index, statusPaid)
420 }
421 m.Pulls++
422 p.Pulls++
423 p.LastPullAt = now
424 p.countPayment(now)
425 pe := p.payee
426 pe.Pulls++
427 pe.Paid += p.Amount
428 pe.LastPullAt = now
429 totalPulls++
430 totalPaid += p.Amount
431 chain.Emit("Pulled",
432 "mandate", utoa(m.ID),
433 "plan", utoa(p.ID),
434 "payer", m.Payer.String(),
435 "payee", p.Payee.String(),
436 "amount", itoa(p.Amount),
437 "next", itoa(m.NextPullAt),
438 )
439}
440
441// Cancel ends a mandate in the realm. The payer or the payee may cancel,
442// each with their own key (never a session). A payer should also revoke the
443// session on chain (the payer page shows the command); cancelling alone
444// already makes every later Pull fail.
445func Cancel(cur realm, payer address, sessionAddr address) {
446 caller := directCaller(cur)
447 m := activeBySession(payer, sessionAddr)
448 if m == nil {
449 panic("mandate: no active mandate for this payer and session (never recorded, already cancelled or replaced)")
450 }
451 p := m.plan
452 if caller != m.Payer && caller != p.Payee {
453 panic("mandate: only the payer or the payee can cancel")
454 }
455 now := time.Now().Unix()
456 pr := payerOf(payer)
457 pr.removeActive(m)
458 // Paid time stays the payer's. A payee's Cancel never evicts another
459 // credit the payer holds: if the record is full, this one is not kept.
460 kept := pr.keepCredit(payer, p.ID, m.paidThrough(), now, caller == m.Payer)
461 pr.save(payer)
462 m.CancelledAt = now
463 m.CancelledBy = caller
464 p.Cancelled++
465 p.Supporters.setStatus(m.Index, statusCancelled)
466 chain.Emit("Cancelled",
467 "mandate", utoa(m.ID),
468 "plan", utoa(p.ID),
469 "payer", m.Payer.String(),
470 "by", caller.String(),
471 "kept", itoa(kept),
472 )
473}
474
475// countPayment counts one payment at time now in its period window.
476func (p *Plan) countPayment(now int64) {
477 w := now / p.Period
478 switch w {
479 case p.payWindow:
480 p.paidThis++
481 case p.payWindow + 1:
482 p.paidPrev, p.paidThis = p.paidThis, 1
483 default:
484 p.paidPrev, p.paidThis = 0, 1
485 }
486 p.payWindow = w
487}
488
489// paidWindows returns how many payments were made in the period window that
490// contains now, and in the window before it.
491func (p *Plan) paidWindows(now int64) (current, previous int) {
492 switch now / p.Period {
493 case p.payWindow:
494 return p.paidThis, p.paidPrev
495 case p.payWindow + 1:
496 return 0, p.paidThis
497 }
498 return 0, 0
499}
500
501// directCaller is the guard shared by every crossing function except Pull:
502// a direct call from a user, signed with the user's own key (never a
503// session key, or the payee could rewrite terms through the session), with
504// no coins attached (the realm never holds funds).
505func directCaller(cur realm) address {
506 if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
507 panic("mandate: this function cannot be called with a session key")
508 }
509 prev := cur.Previous()
510 if !prev.IsUserCall() {
511 panic("mandate: direct calls only")
512 }
513 if len(unsafe.OriginSend()) != 0 {
514 panic("mandate: do not send coins with this call")
515 }
516 return prev.Address()
517}
518
519func (m *Mandate) isActive(now int64) bool {
520 return m.CancelledAt == 0 && now < m.ExpiresAt
521}
522
523// paidThrough returns until when this mandate's payments cover its payer:
524// its next pull time once it has paid, or when it started with paid time
525// carried over from an earlier mandate (its first pull is then after its
526// creation). 0 when it has never paid and carried nothing.
527func (m *Mandate) paidThrough() int64 {
528 if m.Pulls > 0 || m.NextPullAt > m.CreatedAt {
529 return m.NextPullAt
530 }
531 return 0
532}
533
534// status is the realm's view of a mandate: cancelled, expired or active.
535func (m *Mandate) status(now int64) string {
536 switch {
537 case m.CancelledAt != 0:
538 return "cancelled"
539 case now >= m.ExpiresAt:
540 return "expired"
541 default:
542 return "active"
543 }
544}
545
546func planOf(id uint64) *Plan {
547 v := plans.Get(pad(id))
548 if v == nil {
549 return nil
550 }
551 return v.(*Plan)
552}
553
554func payeeOf(a address) *Payee {
555 v := payees.Get(a.String())
556 if v == nil {
557 return nil
558 }
559 return v.(*Payee)
560}
561
562// validateTitle returns "" or the reason the title is refused: blank, too
563// long, not UTF-8, or containing control characters or line separators.
564func validateTitle(s string) string {
565 if !utf8.ValidString(s) {
566 return "mandate: title is not valid UTF-8"
567 }
568 if strings.TrimSpace(s) == "" {
569 return "mandate: title is empty"
570 }
571 if utf8.RuneCountInString(s) > MaxTitleLen {
572 return "mandate: title is longer than " + strconv.Itoa(MaxTitleLen) + " characters"
573 }
574 for _, r := range s {
575 if unicode.IsControl(r) || r == '\u2028' || r == '\u2029' {
576 return "mandate: title must be a single line without control characters"
577 }
578 if unicode.Is(unicode.Cf, r) {
579 // format characters: bidi controls (U+202A-U+202E, U+2066-U+2069),
580 // zero-width ones (U+200B-U+200F, U+FEFF) and the like, which can make
581 // a title display differently from what it says
582 return "mandate: title must not contain invisible formatting characters"
583 }
584 }
585 return ""
586}
587
588// pad formats an id with a fixed width so tree keys sort numerically.
589func pad(id uint64) string {
590 s := strconv.FormatUint(id, 10)
591 if len(s) < 10 {
592 s = strings.Repeat("0", 10-len(s)) + s
593 }
594 return s
595}
596
597func itoa(n int64) string { return strconv.FormatInt(n, 10) }
598func utoa(n uint64) string { return strconv.FormatUint(n, 10) }
599
600// collectorFunded reports whether a collector key's address holds coins.
601// Receiving any coin makes an address an account for good, and the chain
602// refuses to create a session for a key whose address is an account
603// (tm2/pkg/sdk/auth/handler.go:63-65): no new supporter could join. A
604// balance cannot see an account that received coins and was emptied; the
605// free query auth/accounts/<address> can, and the collector runs it.
606func collectorFunded(addr address) bool {
607 return len(banker.NewReadonlyBanker().GetCoins(addr)) > 0
608}