Playground
escape.gno
package mandate
import (
"strings"
"gno.land/p/nt/markdown/sanitize/v0"
)
// Escaping. Plan titles are the only text users choose; every title that
// reaches a page goes through esc (headings, link text) or escCell (table
// cells). They wrap p/nt/markdown/sanitize/v0, so a title cannot produce a
// heading, list, table break, link, image, HTML tag or code, plus the
// gnoweb-specific steps in gnowebSafe:
// - "@name" and " g1..." (an address after a space) become profile links
// in gnoweb: "@" becomes "\@", the space before "g1" becomes " ", and
// a "g1" at the very start becomes "g1" (the realm often puts a space
// right before a title).
// - "$...$" becomes math: every "$" becomes "\$".
// Everything else on the pages is generated by the realm from validated
// values (addresses, numbers, a bech32 key checked by the chain).
func esc(s string) string { return gnowebSafe(sanitize.InlineText(s)) }
func escCell(s string) string { return gnowebSafe(sanitize.TableCell(s)) }
func gnowebSafe(s string) string {
s = strings.ReplaceAll(s, "@", `\@`)
s = strings.ReplaceAll(s, "$", `\$`)
s = strings.ReplaceAll(s, " g1", " g1")
if strings.HasPrefix(s, "g1") {
s = "g1" + s[2:]
}
return s
}
gnomod.toml
module = "gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate" gno = "0.9" [addpkg] creator = "g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8" height = 1366932 max_deposit = "30000000ugnot"
mandate.gno
// Package mandate is capped, revocable direct debit on native GNOT, built on
// Gno session keys.
//
// A payee publishes a plan ("1 GNOT every 7 days"). A payer subscribes with
// two things signed by the payer's own key:
//
// 1. a session on chain for the payee's collector key, scoped to this realm
// only, with a spend limit of the plan's amount plus a small fee
// allowance per period, and an expiry;
// 2. Subscribe here, which records the terms for that session.
//
// The payee's collector then calls Pull once per period, signed with the
// session key on behalf of the payer and sending exactly the plan's amount.
// The realm is the rulebook: it checks who, how much and when, then forwards
// the coins to the payee in the same transaction. It never keeps funds.
//
// Honest limits, also shown on the home page:
// - It is direct debit, not escrow. A payer can revoke the session, cancel,
// or empty the account at any time; the payee is then not paid.
// - The chain caps what the payer can lose per period at the session's
// spend limit: amount plus fee allowance. A hostile payee can burn the
// allowance as gas fees (it goes to the network, not to the payee).
// - The chain allows at most 16 sessions per account, so a wallet can have
// at most 16 mandates at a time.
// - A realm cannot see an on-chain session revoke. A service deciding
// whether someone has paid reads PaidThrough, which moves only when a
// payment succeeds; HasMandate is only the realm's view (recorded, not
// cancelled, not expired), and the chain's own view of the session is
// the free query auth/accounts/<payer>/session/<session address>.
// - A session scoped to vm/exec:<this realm> also allows every realm under
// this path (the chain's scope match is prefix-based). Nothing must ever
// be deployed under a sub-path of this realm. Pull also refuses any
// session whose allow list is not exactly this realm, but that cannot
// protect a payer from a sub-realm called directly.
//
// There is no admin, owner, pause, upgrade or sweep.
package mandate
import (
"chain"
"chain/banker"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"gno.land/p/nt/avl/v0"
)
// Denom is the only coin a plan can be paid in.
const Denom = "ugnot"
// Limits. See docs/design.md for the reasoning behind each value.
const (
// MinAmount is the smallest plan amount, 0.1 GNOT. A Pull uses about
// 8-9M gas on a local chain, and the chain charges the whole fee the
// signer sets, not the gas used: the pages set 20,000 ugnot for 20M gas
// wanted (Onyx's minimum price of 1 ugnot per 1,000 gas). At 0.1 GNOT that
// fee is already a fifth of the payment; below it, fees would dominate.
MinAmount int64 = 100_000
// MaxAmount is 1,000,000 GNOT per period: far above any real plan, and
// low enough that totals cannot overflow int64 for millions of pulls.
MaxAmount int64 = 1_000_000_000_000
// MinPeriod is one minute: block times are a few seconds, and the
// chain's spend period is counted in seconds. Short periods exist for
// demos and tests; pages flag any period under a day.
MinPeriod int64 = 60
// MaxPeriod is 30 days, exactly the chain's limit on a session's spend
// period (tm2 std.MaxSpendPeriod). The session's spend period is always
// the plan's period, so the cap the pages promise ("at most price +
// allowance per period") is exactly what the chain enforces. No yearly
// plans: the chain refuses a session whose spend period is longer.
MaxPeriod int64 = 30 * 24 * 60 * 60
// MaxTerm is the longest a mandate may run from the moment it is
// created: 366 days. A payer renews once a year at most; the chain's own
// cap on a session's expiry is 4 x 365 days (tm2 std.MaxSessionDuration).
MaxTerm int64 = 366 * 24 * 60 * 60
// FeeAllowance is what the pages add to the session's spend limit for
// fees and storage (0.1 GNOT). The chain accepts a fee when fee / gas
// wanted is at least the current gas price (1 ugnot per 1,000 gas on
// Onyx, raised by the chain when blocks are full), and counts the Pull's
// storage deposit against the same limit. With the pages' 20M gas wanted
// the minimum fee is 20,000 ugnot. A Pull creates no object: a first
// payment adds at most 78 bytes measured (7,800 ugnot at 100 ugnot per
// byte), later ones nothing. So the worst pull costs about 28,000 ugnot
// and the allowance covers a gas price up to about 4.5x Onyx's current
// one (docs/design.md, "Pull's budget").
FeeAllowance int64 = 100_000
// MaxTitleLen is the longest plan title, in characters.
MaxTitleLen = 80
// PageSize is the number of rows per list page and per read call.
PageSize = 20
// MaxSessionsPerWallet is the chain's limit (tm2 std.MaxSessionsPerAccount).
MaxSessionsPerWallet = 16
)
// Plan is published by a payee and never changes. New terms mean a new plan.
type Plan struct {
ID uint64
Payee address
Title string
Amount int64 // ugnot per period
Period int64 // seconds
CreatedAt int64 // unix seconds
Supporters fixedList // every mandate for this plan, oldest first (see encodeEntry)
Cancelled int // how many of them were cancelled
Pulls int64 // successful pulls (paid = Pulls * Amount)
LastPullAt int64 // unix seconds, 0 = never
// Payments per period window: window k is [k*Period, (k+1)*Period). A
// mandate pays at most once in a window, and paid time carries over to a
// payer's next mandate for the plan, so a payer is not charged twice for
// one period (except when 16 kept periods are already held, see
// MaxCreditsPerPayer); but these count payments, not distinct people (a creator
// can pay its own plan from a second wallet). Read with paidWindows, which
// turns them into counts for the window containing "now" and the one
// before it, so they are true at any time without a transaction.
payWindow int64 // index of the window of the last payment
paidThis int // payments in window payWindow
paidPrev int // payments in window payWindow-1
payee *Payee // direct link, so Pull needs no lookup
}
// Mandate is one payer's permission for one session key on one plan. It
// keeps only what cannot be derived: the amount paid is Pulls * the plan's
// amount, and the last pull was one period before NextPullAt.
type Mandate struct {
ID uint64
Payer address
Session address // address of the session key the payee holds
CreatedAt int64
ExpiresAt int64 // unix seconds; pulls are refused from this time on
NextPullAt int64 // unix seconds; the first pull is due at once
Pulls int64
Index int // position in the plan's supporter list
CancelledAt int64 // 0 = not cancelled
CancelledBy address
plan *Plan // direct link, so Pull needs no lookup
prevOfPayer *Mandate // the payer's previous mandate (history, newest first)
}
// Payee holds a payee's plans, totals and published collector key.
type Payee struct {
Addr address
Plans int
planIDs fixedList // the payee's plan ids, padded (values, not pointers)
Pulls int64
Paid int64
LastPullAt int64
CollectorKey string // bech32 public key (gpub1...), empty if not set
CollectorAddr address // address derived from CollectorKey by the chain
}
// State. Storage is paid per byte (100 ugnot) and gas mostly per object
// read or written, so the layout keeps both small, and nothing one address
// does can grow what another payer's calls read (docs/design.md):
// - plans, payees and payers live in avl trees: an attacker can only add
// depth (log2 of the number of entries);
// - each payer's lookups live in that payer's own record (Payer, stored
// by value in the tree), capped at MaxActivePerPayer active mandates
// and MaxCreditsPerPayer kept credits;
// - each plan's supporter list holds small values in chunks (see
// fixedList), so adding one costs the same however long it is;
// - a payer's history is a linked list through the mandates, walked only
// by free reads.
var (
realmPath string // this realm's package path, captured at init
nextPlanID uint64
nextMandateID uint64
plans = avl.NewTree() // pad(planID) -> *Plan
payees = avl.NewTree() // payee -> *Payee
payers = avl.NewTree() // payer -> Payer (a value, not a pointer)
totalPulls int64
totalPaid int64
)
func init() {
realmPath = unsafe.CurrentRealm().PkgPath()
}
// Offer publishes a plan: amountUgnot every periodSeconds, paid to the
// caller. Signed with the payee's own key; no session, no coins.
func Offer(cur realm, title string, amountUgnot, periodSeconds int64) uint64 {
caller := directCaller(cur)
if err := validateTitle(title); err != "" {
panic(err)
}
if amountUgnot < MinAmount {
panic("mandate: amount is below the minimum of " + formatUgnot(MinAmount))
}
if amountUgnot > MaxAmount {
panic("mandate: amount is above the maximum of " + formatUgnot(MaxAmount))
}
if periodSeconds < MinPeriod {
panic("mandate: period is below the minimum of " + itoa(MinPeriod) + " seconds")
}
if periodSeconds > MaxPeriod {
panic("mandate: period is above the maximum of " + itoa(MaxPeriod) + " seconds")
}
nextPlanID++
p := &Plan{
ID: nextPlanID,
Payee: caller,
Title: title,
Amount: amountUgnot,
Period: periodSeconds,
CreatedAt: time.Now().Unix(),
}
pe := payeeOf(caller)
if pe == nil {
pe = &Payee{Addr: caller}
payees.Set(caller.String(), pe)
}
p.payee = pe
plans.Set(pad(p.ID), p)
pe.Plans++
pe.planIDs.add(pad(p.ID))
chain.Emit("PlanOffered",
"plan", utoa(p.ID),
"payee", caller.String(),
"title", p.Title,
"amount", itoa(p.Amount),
"period", itoa(p.Period),
)
return p.ID
}
// SetCollectorKey publishes the public key (bech32, gpub1...) of the key the
// payee's collector signs pulls with. Plan pages show it in the copy-ready
// commands, so payers create their session for the right key. Signed with
// the payee's own key. It does not change existing mandates.
func SetCollectorKey(cur realm, pubKey string) {
caller := directCaller(cur)
if len(pubKey) > 200 || !strings.HasPrefix(pubKey, "gpub1") {
panic("mandate: collector key must be a bech32 public key starting with gpub1")
}
addr, err := chain.PubKeyAddress(pubKey)
if err != nil || !addr.IsValid() {
panic("mandate: collector key is not a valid public key")
}
if addr == caller {
panic("mandate: use a dedicated key for collecting, not your main key")
}
if collectorFunded(addr) {
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")
}
pe := payeeOf(caller)
if pe == nil {
pe = &Payee{Addr: caller}
payees.Set(caller.String(), pe)
}
pe.CollectorKey = pubKey
pe.CollectorAddr = addr
chain.Emit("CollectorKeySet", "payee", caller.String(), "pubkey", pubKey, "address", addr.String())
}
// Subscribe records the terms for one session: the payer allows the holder
// of sessionAddr to pull the plan's amount once per period until
// expiresAtUnix, through this realm only. Signed with the payer's own key
// (never a session), no coins. Create the session on chain in the same
// transaction or just before (see the plan page for the exact command).
//
// The first payment is collected by the first Pull, which is due at once
// (billing in advance: each period is paid at its start).
func Subscribe(cur realm, planID uint64, sessionAddr address, expiresAtUnix int64) uint64 {
payer := directCaller(cur)
p := planOf(planID)
if p == nil {
panic("mandate: no such plan")
}
if payer == p.Payee {
panic("mandate: you cannot subscribe to your own plan")
}
if !sessionAddr.IsValid() {
panic("mandate: invalid session address")
}
if sessionAddr == payer || sessionAddr == p.Payee {
panic("mandate: the session address must be a dedicated session key, not a wallet")
}
now := time.Now().Unix()
if expiresAtUnix <= now {
panic("mandate: expiry must be in the future")
}
if expiresAtUnix > now+MaxTerm {
panic("mandate: expiry is more than " + itoa(MaxTerm/86400) + " days away")
}
pr := payerOf(payer)
if pr == nil {
pr = &Payer{}
}
// Time already paid for on this plan carries over. Take this plan's
// credit before pruning, so the prune can never evict the credit about
// to be used; then take the one the prune may have made from an expired
// mandate for this plan (at most one of the two exists).
until := pr.takeCredit(planID, now)
// An expired mandate's lookups go when its payer subscribes again; the
// paid time of an expired mandate for this plan comes back directly.
if u := pr.pruneExpired(payer, planID, now); u > until {
until = u
}
for _, r := range pr.Active {
if r.Session == sessionAddr {
panic("mandate: this session already has an active mandate; cancel it first or use another session key")
}
if r.PlanID == planID {
panic("mandate: you already have an active mandate for this plan")
}
}
if len(pr.Active) >= MaxActivePerPayer {
panic("mandate: at most " + strconv.Itoa(MaxActivePerPayer) + " active mandates per wallet (the chain allows " + strconv.Itoa(MaxSessionsPerWallet) + " sessions); cancel one first")
}
// The first pull of the new mandate is due when the paid time ends. The
// new mandate must outlive it: otherwise it would be listed as paid,
// expire without ever paying, and hand the credit back, again and again.
first := now
carried := int64(0) // paid time carried over: until when, or 0
status := byte(statusUnpaid)
if until > now {
if expiresAtUnix <= until {
panic("mandate: this plan is already paid for until " + formatTime(until) + " (unix " + itoa(until) + "); choose an expiry after that")
}
first, carried = until, until
status = statusPaid // covered now, so listed as a supporter
}
nextMandateID++
m := &Mandate{
ID: nextMandateID,
Payer: payer,
Session: sessionAddr,
CreatedAt: now,
ExpiresAt: expiresAtUnix,
NextPullAt: first,
Index: p.Supporters.N,
plan: p,
prevOfPayer: pr.Head,
}
pr.Head = m
pr.Active = append(pr.Active, activeRef{Session: sessionAddr, PlanID: planID, ID: m.ID, M: m})
pr.save(payer)
p.Supporters.add(encodeEntry(payer, m.ID, status))
chain.Emit("Subscribed",
"mandate", utoa(m.ID),
"plan", utoa(planID),
"payer", payer.String(),
"payee", p.Payee.String(),
"session", sessionAddr.String(),
"expires", itoa(expiresAtUnix),
"first", itoa(first),
"carried", itoa(carried),
)
return m.ID
}
// Pull collects one period's payment. It must be signed with the mandate's
// session key on behalf of the payer (gnokey ... -master <payer>
// <session key>), as a direct call, sending exactly the plan's amount. The
// realm forwards the coins to the plan's payee in the same transaction.
// At most one pull per period; the next one is due one period after this
// one, the same rule the chain applies to the session's spend period.
func Pull(cur realm) {
if !cur.Previous().IsUserCall() {
panic("mandate: Pull must be a direct call")
}
sess, _, paths, isSession := runtime.GetSessionInfo()
now := time.Now().Unix()
m, p := checkPull(isSession, sess, paths, unsafe.OriginCaller(), unsafe.OriginSend(), now)
recordPull(m, p, now) // state and event first, then the transfer
b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
b.SendCoins(cur.Address(), p.Payee, chain.Coins{chain.NewCoin(Denom, p.Amount)})
}
// checkPull applies every rule of Pull to the transaction's session info,
// signer and coins, and returns the mandate and plan to pay, or panics.
// It is separate from Pull so the rules can be unit-tested: `gno test`
// cannot sign with a session key.
func checkPull(isSession bool, sess address, paths []string, payer address, sent chain.Coins, now int64) (*Mandate, *Plan) {
if !isSession {
panic("mandate: Pull must be signed with the mandate's session key")
}
if len(paths) != 1 || paths[0] != "vm/exec:"+realmPath {
panic("mandate: the session must be scoped to exactly vm/exec:" + realmPath)
}
m := activeBySession(payer, sess)
if m == nil {
panic("mandate: no active mandate for this session (never recorded, cancelled or replaced)")
}
if now >= m.ExpiresAt {
panic("mandate: expired")
}
if now < m.NextPullAt {
panic("mandate: too early, next pull from " + itoa(m.NextPullAt))
}
p := m.plan
if len(sent) != 1 || sent[0].Denom != Denom || sent[0].Amount != p.Amount {
panic("mandate: send exactly " + itoa(p.Amount) + Denom)
}
return m, p
}
// recordPull updates the mandate, plan, payee and totals for one payment
// and emits the event. It never creates an object: Pull runs under the
// payer's session budget, which also pays its storage deposit. A first pull
// flips the mandate's entry in the plan's list from unpaid to paid in place
// (same width) and sets fields that were zero (amino omits zero values), a
// few dozen bytes at most; later pulls add nothing.
func recordPull(m *Mandate, p *Plan, now int64) {
m.NextPullAt = now + p.Period
if m.Pulls == 0 {
p.Supporters.setStatus(m.Index, statusPaid)
}
m.Pulls++
p.Pulls++
p.LastPullAt = now
p.countPayment(now)
pe := p.payee
pe.Pulls++
pe.Paid += p.Amount
pe.LastPullAt = now
totalPulls++
totalPaid += p.Amount
chain.Emit("Pulled",
"mandate", utoa(m.ID),
"plan", utoa(p.ID),
"payer", m.Payer.String(),
"payee", p.Payee.String(),
"amount", itoa(p.Amount),
"next", itoa(m.NextPullAt),
)
}
// Cancel ends a mandate in the realm. The payer or the payee may cancel,
// each with their own key (never a session). A payer should also revoke the
// session on chain (the payer page shows the command); cancelling alone
// already makes every later Pull fail.
func Cancel(cur realm, payer address, sessionAddr address) {
caller := directCaller(cur)
m := activeBySession(payer, sessionAddr)
if m == nil {
panic("mandate: no active mandate for this payer and session (never recorded, already cancelled or replaced)")
}
p := m.plan
if caller != m.Payer && caller != p.Payee {
panic("mandate: only the payer or the payee can cancel")
}
now := time.Now().Unix()
pr := payerOf(payer)
pr.removeActive(m)
// Paid time stays the payer's. A payee's Cancel never evicts another
// credit the payer holds: if the record is full, this one is not kept.
kept := pr.keepCredit(payer, p.ID, m.paidThrough(), now, caller == m.Payer)
pr.save(payer)
m.CancelledAt = now
m.CancelledBy = caller
p.Cancelled++
p.Supporters.setStatus(m.Index, statusCancelled)
chain.Emit("Cancelled",
"mandate", utoa(m.ID),
"plan", utoa(p.ID),
"payer", m.Payer.String(),
"by", caller.String(),
"kept", itoa(kept),
)
}
// countPayment counts one payment at time now in its period window.
func (p *Plan) countPayment(now int64) {
w := now / p.Period
switch w {
case p.payWindow:
p.paidThis++
case p.payWindow + 1:
p.paidPrev, p.paidThis = p.paidThis, 1
default:
p.paidPrev, p.paidThis = 0, 1
}
p.payWindow = w
}
// paidWindows returns how many payments were made in the period window that
// contains now, and in the window before it.
func (p *Plan) paidWindows(now int64) (current, previous int) {
switch now / p.Period {
case p.payWindow:
return p.paidThis, p.paidPrev
case p.payWindow + 1:
return 0, p.paidThis
}
return 0, 0
}
// directCaller is the guard shared by every crossing function except Pull:
// a direct call from a user, signed with the user's own key (never a
// session key, or the payee could rewrite terms through the session), with
// no coins attached (the realm never holds funds).
func directCaller(cur realm) address {
if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
panic("mandate: this function cannot be called with a session key")
}
prev := cur.Previous()
if !prev.IsUserCall() {
panic("mandate: direct calls only")
}
if len(unsafe.OriginSend()) != 0 {
panic("mandate: do not send coins with this call")
}
return prev.Address()
}
func (m *Mandate) isActive(now int64) bool {
return m.CancelledAt == 0 && now < m.ExpiresAt
}
// paidThrough returns until when this mandate's payments cover its payer:
// its next pull time once it has paid, or when it started with paid time
// carried over from an earlier mandate (its first pull is then after its
// creation). 0 when it has never paid and carried nothing.
func (m *Mandate) paidThrough() int64 {
if m.Pulls > 0 || m.NextPullAt > m.CreatedAt {
return m.NextPullAt
}
return 0
}
// status is the realm's view of a mandate: cancelled, expired or active.
func (m *Mandate) status(now int64) string {
switch {
case m.CancelledAt != 0:
return "cancelled"
case now >= m.ExpiresAt:
return "expired"
default:
return "active"
}
}
func planOf(id uint64) *Plan {
v := plans.Get(pad(id))
if v == nil {
return nil
}
return v.(*Plan)
}
func payeeOf(a address) *Payee {
v := payees.Get(a.String())
if v == nil {
return nil
}
return v.(*Payee)
}
// validateTitle returns "" or the reason the title is refused: blank, too
// long, not UTF-8, or containing control characters or line separators.
func validateTitle(s string) string {
if !utf8.ValidString(s) {
return "mandate: title is not valid UTF-8"
}
if strings.TrimSpace(s) == "" {
return "mandate: title is empty"
}
if utf8.RuneCountInString(s) > MaxTitleLen {
return "mandate: title is longer than " + strconv.Itoa(MaxTitleLen) + " characters"
}
for _, r := range s {
if unicode.IsControl(r) || r == '\u2028' || r == '\u2029' {
return "mandate: title must be a single line without control characters"
}
if unicode.Is(unicode.Cf, r) {
// format characters: bidi controls (U+202A-U+202E, U+2066-U+2069),
// zero-width ones (U+200B-U+200F, U+FEFF) and the like, which can make
// a title display differently from what it says
return "mandate: title must not contain invisible formatting characters"
}
}
return ""
}
// pad formats an id with a fixed width so tree keys sort numerically.
func pad(id uint64) string {
s := strconv.FormatUint(id, 10)
if len(s) < 10 {
s = strings.Repeat("0", 10-len(s)) + s
}
return s
}
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
func utoa(n uint64) string { return strconv.FormatUint(n, 10) }
// collectorFunded reports whether a collector key's address holds coins.
// Receiving any coin makes an address an account for good, and the chain
// refuses to create a session for a key whose address is an account
// (tm2/pkg/sdk/auth/handler.go:63-65): no new supporter could join. A
// balance cannot see an account that received coins and was emptied; the
// free query auth/accounts/<address> can, and the collector runs it.
func collectorFunded(addr address) bool {
return len(banker.NewReadonlyBanker().GetCoins(addr)) > 0
}
mandate_test.gno
package mandate
import (
"chain"
"chain/banker"
"strings"
"testing"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// Test notes
//
// Sessions: `gno test` cannot sign with a session key, so
// runtime.GetSessionInfo() always reports "not a session" here. Pull's rules
// live in checkPull and recordPull, which take the session info as plain
// arguments and are tested directly below. The real session path (signing,
// spend limits, revoke, expiry, the transfer) is proven on a real chain by
// scripts/local-flow.sh.
//
// Reverts: the test harness does not roll back realm state when a call
// panics; on chain the whole transaction reverts. So every refused call is
// checked to leave all state and the realm balance unchanged, which holds
// because every check runs before the first write.
//
// Time: testing.SkipHeights(n) moves the block time by 5*n seconds.
var (
payee = testutils.TestAddress("md_payee")
payee2 = testutils.TestAddress("md_payee2")
payer = testutils.TestAddress("md_payer")
payer2 = testutils.TestAddress("md_payer2")
stranger = testutils.TestAddress("md_stranger")
realmAddr = chain.PackageAddress("gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate")
)
// Two real session keys and the addresses the chain derives from them
// (taken from a local chain: gnokey list).
const (
gpubA = "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqfp0696ldln2nm7kd33zfpgypg6u0e7upl03hyeexa6mccn4ce8mkswg65c"
sessA = address("g1psdsf789f4xw3qrpjue54g2h28syd09yfkrxdh")
gpubB = "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqtwu0rahac8cw2fw7fmlan472nfyprlgdp4c034vmwyumy4yksl67587x7p"
sessB = address("g1valkxsym77y3qlj5fq9h4p64y73l3masvuxav0")
selfPaths = "vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate"
gnot = int64(1_000_000)
day = int64(86400)
)
func ugnot(n int64) chain.Coins { return chain.Coins{{Denom: "ugnot", Amount: n}} }
func bal(a address) int64 { return banker.NewReadonlyBanker().GetCoin(a, "ugnot") }
func now() int64 { return time.Now().Unix() }
func resetState() {
nextPlanID, nextMandateID = 0, 0
plans, payees, payers = avl.NewTree(), avl.NewTree(), avl.NewTree()
pullLog = nil
totalPulls, totalPaid = 0, 0
}
// testing.SetRealm changes the realm of the frame that calls it, so it is
// called inline right before each cross(cur) call it is meant for.
func offer(cur realm, who address, title string, amount, period int64) uint64 {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(who))
return Offer(cross(cur), title, amount, period)
}
func setKey(cur realm, who address, gpub string) {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(who))
SetCollectorKey(cross(cur), gpub)
}
func subscribe(cur realm, who address, planID uint64, sess address, expires int64) uint64 {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(who))
return Subscribe(cross(cur), planID, sess, expires)
}
func cancel(cur realm, who, p, sess address) {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(who))
Cancel(cross(cur), p, sess)
}
// pullOK runs Pull's rules and state update as the chain would for a
// correct session-signed call (the transfer itself is proven by the local
// flow script).
func pullOK(p address, sess address, amount int64) {
m, pl := checkPull(true, sess, []string{selfPaths}, p, ugnot(amount), now())
recordPull(m, pl, now())
pullLog = append(pullLog, pulled{plan: pl.ID, at: now()})
}
// pullLog records every payment the tests make, so expected per-period
// counts are computed independently of the realm's counters.
type pulled struct {
plan uint64
at int64
}
var pullLog []pulled
// expectedWindows counts the logged payments of a plan in the period window
// containing now and in the one before.
func expectedWindows(planID uint64, period int64) (current, previous int) {
w := now() / period
for _, x := range pullLog {
if x.plan != planID {
continue
}
switch x.at / period {
case w:
current++
case w - 1:
previous++
}
}
return
}
// snapshot is everything a refused call must leave unchanged.
func snapshot() string {
var b strings.Builder
n1, n2, pulls, paid := Totals()
b.WriteString(itoa(int64(n1)) + "/" + itoa(int64(n2)) + "/" + itoa(pulls) + "/" + itoa(paid) + "/" + itoa(bal(realmAddr)) + "\n")
mandate := func(m *Mandate) {
b.WriteString(utoa(m.ID) + m.Payer.String() + m.Session.String() + itoa(m.ExpiresAt) + itoa(m.NextPullAt) +
itoa(m.Pulls) + itoa(m.CancelledAt) + m.CancelledBy.String() + "\n")
}
plans.Iterate("", "", func(_ string, v any) bool {
p := v.(*Plan)
b.WriteString(p.Title + itoa(p.Amount) + itoa(p.Period) + itoa(int64(p.Supporters.N)) + "c" + itoa(int64(p.Cancelled)) + "w" + itoa(p.payWindow) + "/" + itoa(int64(p.paidThis)) + "/" + itoa(int64(p.paidPrev)) +
itoa(p.Pulls) + itoa(p.LastPullAt) + "\n")
for i := 0; i < p.Supporters.N; i++ {
b.WriteString(p.Supporters.at(i) + ",")
}
return false
})
payees.Iterate("", "", func(k string, v any) bool {
pe := v.(*Payee)
b.WriteString(k + itoa(int64(pe.Plans)) + itoa(pe.Pulls) + itoa(pe.Paid) + pe.CollectorKey + pe.CollectorAddr.String() + "\n")
return false
})
payers.Iterate("", "", func(k string, v any) bool {
pr := v.(Payer)
b.WriteString("\npayer " + k + " active:")
for _, r := range pr.Active {
b.WriteString(" " + r.Session.String() + "/" + utoa(r.PlanID) + "=" + utoa(r.M.ID))
}
if pr.Head != nil {
b.WriteString(" head=" + utoa(pr.Head.ID))
}
for m := pr.Head; m != nil; m = m.prevOfPayer {
mandate(m)
}
return false
})
for _, t := range []*avl.Tree{plans, payees, payers} {
b.WriteString(itoa(int64(t.Size())) + ",")
}
return b.String()
}
// fails asserts fn aborts with a message containing substr and changes nothing.
func fails(t *testing.T, rlm realm, substr string, fn func(), what string) {
t.Helper()
before := snapshot()
uassert.AbortsContains(t, rlm, substr, fn, what)
if after := snapshot(); after != before {
t.Fatalf("%s: state changed by a refused call\nbefore:\n%s\nafter:\n%s", what, before, after)
}
}
// panicsLocal is fails for non-crossing helpers (checkPull).
func panicsLocal(t *testing.T, rlm realm, substr string, fn func(), what string) {
t.Helper()
before := snapshot()
uassert.PanicsContains(t, rlm, substr, fn, what)
if after := snapshot(); after != before {
t.Fatalf("%s: state changed by a refused pull", what)
}
}
func TestOffer(cur realm, t *testing.T) {
resetState()
id := offer(cur, payee, "Weekly supporter", gnot, 7*day)
uassert.Equal(t, uint64(1), id)
p, ok := GetPlan(id)
uassert.True(t, ok)
uassert.Equal(t, payee.String(), p.Payee.String())
uassert.Equal(t, "Weekly supporter", p.Title)
uassert.Equal(t, gnot, p.Amount)
uassert.Equal(t, 7*day, p.Period)
uassert.Equal(t, now(), p.CreatedAt)
pe, ok := GetPayee(payee)
uassert.True(t, ok)
uassert.Equal(t, 1, pe.Plans)
uassert.Equal(t, int64(0), bal(realmAddr))
// Boundaries are accepted.
offer(cur, payee, "min", MinAmount, MinPeriod)
offer(cur, payee, "max", MaxAmount, MaxPeriod)
offer(cur, payee, strings.Repeat("é", MaxTitleLen), gnot, day)
uassert.Equal(t, uint64(4), nextPlanID)
uassert.Equal(t, 4, payeeOf(payee).Plans)
}
func TestOfferRefusals(cur realm, t *testing.T) {
resetState()
offer(cur, payee, "existing", gnot, day)
cases := []struct {
title string
amount, period int64
want string
}{
{"", gnot, day, "title is empty"},
{" ", gnot, day, "title is empty"},
{strings.Repeat("a", MaxTitleLen+1), gnot, day, "longer than 80"},
{"two\nlines", gnot, day, "single line"},
{"tab\there", gnot, day, "single line"},
{"cr\rhere", gnot, day, "single line"},
{"nul\x00here", gnot, day, "single line"},
{"sep\u2028here", gnot, day, "single line"},
{"sep\u2029here", gnot, day, "single line"},
{"del\x7fhere", gnot, day, "single line"},
{"zero\u200bwidth", gnot, day, "invisible formatting"},
{"Fluxen\u202egnp.exe", gnot, day, "invisible formatting"},
{"\ufeffbom", gnot, day, "invisible formatting"},
{"iso\u2066late\u2069", gnot, day, "invisible formatting"},
{"soft\u00adhyphen", gnot, day, "invisible formatting"},
{"joiner\u200d", gnot, day, "invisible formatting"},
{"bad\xffutf8", gnot, day, "not valid UTF-8"},
{"ok", MinAmount - 1, day, "below the minimum"},
{"ok", 0, day, "below the minimum"},
{"ok", -gnot, day, "below the minimum"},
{"ok", MaxAmount + 1, day, "above the maximum"},
{"ok", gnot, MinPeriod - 1, "period is below"},
{"ok", gnot, 0, "period is below"},
{"ok", gnot, -1, "period is below"},
{"ok", gnot, MaxPeriod + 1, "period is above"},
}
for _, c := range cases {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payee))
fails(t, cur, c.want, func() { Offer(cross(cur), c.title, c.amount, c.period) }, "Offer "+c.want)
}
// Coins attached are refused (the realm never holds funds).
testing.SetRealm(testing.NewUserRealm(payee))
testing.SetOriginSend(ugnot(gnot))
fails(t, cur, "do not send coins", func() { Offer(cross(cur), "ok", gnot, day) }, "Offer with coins")
testing.SetOriginSend(nil)
// Only direct calls from a user.
testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/proxy"))
fails(t, cur, "direct calls only", func() { Offer(cross(cur), "ok", gnot, day) }, "Offer from a realm")
}
func TestTitleCharacters(cur realm, t *testing.T) {
resetState()
// Visible non-ASCII text is fine; only invisible formatting is refused.
for _, title := range []string{"Café ☕ für alle", "Support Fluxen's work", "日本語のプラン", "Ünïcödé — dash"} {
id := offer(cur, payee, title, gnot, day)
p, _ := GetPlan(id)
uassert.Equal(t, title, p.Title)
}
}
// PaidThrough moves only with a successful payment: never before the first
// one, payment time + period after each, and the paid time is kept after a
// cancel until it runs out. IsPaidUp is now < PaidThrough, exclusive at the boundary.
func TestPaidThrough(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
uassert.Equal(t, int64(0), PaidThrough(payer, pid))
subscribe(cur, payer, pid, sessA, now()+600)
uassert.True(t, HasMandate(payer, pid))
uassert.Equal(t, int64(0), PaidThrough(payer, pid), "recorded, not paid")
uassert.False(t, IsPaidUp(payer, pid))
t0 := now()
pullOK(payer, sessA, gnot)
uassert.Equal(t, t0+MinPeriod, PaidThrough(payer, pid))
uassert.True(t, IsPaidUp(payer, pid))
uassert.Equal(t, int64(0), PaidThrough(payer2, pid), "another payer")
uassert.Equal(t, int64(0), PaidThrough(payer, pid+1), "another plan")
testing.SkipHeights(MinPeriod/5 - 1) // one block before the period ends
uassert.True(t, IsPaidUp(payer, pid))
testing.SkipHeights(1) // now == PaidThrough
uassert.False(t, IsPaidUp(payer, pid), "exclusive at the boundary")
uassert.Equal(t, t0+MinPeriod, PaidThrough(payer, pid), "unchanged without a payment")
uassert.True(t, HasMandate(payer, pid), "a mandate is not a payment")
t1 := now()
pullOK(payer, sessA, gnot)
uassert.Equal(t, t1+MinPeriod, PaidThrough(payer, pid))
cancel(cur, payer, payer, sessA)
uassert.Equal(t, t1+MinPeriod, PaidThrough(payer, pid), "cancelled: the paid period is still the payer's")
uassert.True(t, IsPaidUp(payer, pid))
uassert.False(t, HasMandate(payer, pid))
testing.SkipHeights(MinPeriod / 5)
uassert.False(t, IsPaidUp(payer, pid), "the kept time runs out")
}
func TestSetCollectorKey(cur realm, t *testing.T) {
resetState()
// Allowed before any plan: it creates the payee record.
setKey(cur, payee, gpubA)
pe, ok := GetPayee(payee)
uassert.True(t, ok)
uassert.Equal(t, gpubA, pe.CollectorKey)
uassert.Equal(t, sessA.String(), pe.CollectorAddr.String())
uassert.Equal(t, 0, pe.Plans)
// Replace it.
setKey(cur, payee, gpubB)
uassert.Equal(t, sessB.String(), payeeOf(payee).CollectorAddr.String())
for _, c := range []struct{ key, want string }{
{"", "must be a bech32 public key"},
{"g1psdsf789f4xw3qrpjue54g2h28syd09yfkrxdh", "must be a bech32 public key"},
{"gpub1" + strings.Repeat("q", 200), "must be a bech32 public key"},
{gpubA[:len(gpubA)-1] + "q", "not a valid public key"}, // bad checksum
{"gpub1mdgqmw", "not a valid public key"},
{"gpub1qqqqqq", "not a valid public key"},
} {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payee))
fails(t, cur, c.want, func() { SetCollectorKey(cross(cur), c.key) }, "SetCollectorKey "+c.key)
}
// The payee's own main key is refused.
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(sessA))
fails(t, cur, "dedicated key", func() { SetCollectorKey(cross(cur), gpubA) }, "own key as collector")
testing.SetRealm(testing.NewUserRealm(payee))
testing.SetOriginSend(ugnot(1))
fails(t, cur, "do not send coins", func() { SetCollectorKey(cross(cur), gpubA) }, "collector key with coins")
testing.SetOriginSend(nil)
}
func TestSubscribe(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, day)
setKey(cur, payee, gpubA)
exp := now() + 30*day
mid := subscribe(cur, payer, pid, sessA, exp)
uassert.Equal(t, uint64(1), mid)
m, ok := MandateOf(payer, sessA)
uassert.True(t, ok)
uassert.Equal(t, payer.String(), m.Payer.String())
uassert.Equal(t, payee.String(), m.Payee.String())
uassert.Equal(t, sessA.String(), m.Session.String())
uassert.Equal(t, gpubA, m.SessionPubKey) // the payee's published key
uassert.Equal(t, exp, m.ExpiresAt)
uassert.Equal(t, now(), m.NextPullAt) // first payment due at once
uassert.Equal(t, "active", m.Status)
uassert.True(t, m.Due)
uassert.Equal(t, "auth/accounts/"+payer.String()+"/session/"+sessA.String(), m.SessionQuery)
uassert.True(t, HasMandate(payer, pid))
uassert.Equal(t, now(), NextPullAt(payer, pid))
uassert.Equal(t, 1, planOf(pid).Supporters.N)
uassert.Equal(t, int64(0), bal(realmAddr))
// A session key that is not the published collector key: no public key recorded.
subscribe(cur, payer2, pid, sessB, exp)
m2, _ := MandateOf(payer2, sessB)
uassert.Equal(t, "", m2.SessionPubKey)
// Expiry exactly at the maximum term is accepted.
pid2 := offer(cur, payee2, "Other", gnot, day)
subscribe(cur, payer, pid2, sessB, now()+MaxTerm)
}
func TestSubscribeRefusals(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, day)
pid2 := offer(cur, payee, "Plan 2", gnot, day)
subscribe(cur, payer, pid, sessA, now()+day)
cases := []struct {
who address
plan uint64
sess address
expires int64
want string
}{
{payer2, 99, sessA, now() + day, "no such plan"},
{payer2, 0, sessA, now() + day, "no such plan"},
{payee, pid, sessA, now() + day, "your own plan"},
{payer2, pid, address(""), now() + day, "invalid session address"},
{payer2, pid, address("g1notanaddress"), now() + day, "invalid session address"},
{payer2, pid, payer2, now() + day, "dedicated session key"},
{payer2, pid, payee, now() + day, "dedicated session key"},
{payer2, pid, sessA, now(), "in the future"},
{payer2, pid, sessA, now() - 1, "in the future"},
{payer2, pid, sessA, 0, "in the future"},
{payer2, pid, sessA, now() + MaxTerm + 1, "days away"},
{payer, pid2, sessA, now() + day, "already has an active mandate"}, // same session, other plan
{payer, pid, sessB, now() + day, "already have an active mandate for this plan"},
}
for _, c := range cases {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(c.who))
fails(t, cur, c.want, func() { Subscribe(cross(cur), c.plan, c.sess, c.expires) }, "Subscribe "+c.want)
}
testing.SetRealm(testing.NewUserRealm(payer2))
testing.SetOriginSend(ugnot(gnot))
fails(t, cur, "do not send coins", func() { Subscribe(cross(cur), pid, sessA, now()+day) }, "Subscribe with coins")
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/proxy"))
fails(t, cur, "direct calls only", func() { Subscribe(cross(cur), pid, sessA, now()+day) }, "Subscribe from a realm")
}
func TestResubscribeAfterCancelOrExpiry(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
first := subscribe(cur, payer, pid, sessA, now()+day)
cancel(cur, payer, payer, sessA)
uassert.False(t, HasMandate(payer, pid))
second := subscribe(cur, payer, pid, sessA, now()+120)
uassert.True(t, second != first)
uassert.True(t, HasMandate(payer, pid))
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, second, m.ID)
old := MandatesOf(payer, 1)[1] // newest first
uassert.Equal(t, first, old.ID)
uassert.Equal(t, "cancelled", old.Status)
// Let it expire, then subscribe again with the same session.
testing.SkipHeights(24) // 120 s
uassert.False(t, HasMandate(payer, pid))
uassert.Equal(t, int64(0), NextPullAt(payer, pid))
third := subscribe(cur, payer, pid, sessA, now()+day)
uassert.True(t, HasMandate(payer, pid))
uassert.Equal(t, 3, len(MandatesOf(payer, 1)))
uassert.Equal(t, 1, len(SupportersOf(pid, 1))) // active ones only
m, _ = MandateOf(payer, sessA)
uassert.Equal(t, third, m.ID)
}
func TestPullRules(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", 2*gnot, MinPeriod)
exp := now() + 600
subscribe(cur, payer, pid, sessA, exp)
paths := []string{selfPaths}
// Not a session, or a session with the wrong scope.
panicsLocal(t, cur, "signed with the mandate's session key", func() { checkPull(false, sessA, paths, payer, ugnot(2*gnot), now()) }, "no session")
for _, bad := range [][]string{
nil,
{},
{"*"},
{"vm/exec"},
{"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8"},
{"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandat"},
{"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate/sub"},
{"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate", "bank/send"},
{"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate", "vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate"},
{"bank/send"},
} {
panicsLocal(t, cur, "scoped to exactly", func() { checkPull(true, sessA, bad, payer, ugnot(2*gnot), now()) }, "paths "+strings.Join(bad, ","))
}
// No mandate for this payer and session.
panicsLocal(t, cur, "no active mandate", func() { checkPull(true, sessB, paths, payer, ugnot(2*gnot), now()) }, "other session")
panicsLocal(t, cur, "no active mandate", func() { checkPull(true, sessA, paths, payer2, ugnot(2*gnot), now()) }, "other payer")
// Wrong coins.
for _, c := range []chain.Coins{
nil,
ugnot(2*gnot - 1),
ugnot(2*gnot + 1),
ugnot(gnot),
{{Denom: "ufoo", Amount: 2 * gnot}},
{{Denom: "ufoo", Amount: 1}, {Denom: "ugnot", Amount: 2 * gnot}},
{{Denom: "ugnot", Amount: 2 * gnot}, {Denom: "uzzz", Amount: 1}},
{{Denom: "ugnot", Amount: 2 * gnot}, {Denom: "ugnot", Amount: 2 * gnot}},
} {
panicsLocal(t, cur, "send exactly 2000000ugnot", func() { checkPull(true, sessA, paths, payer, c, now()) }, "coins "+c.String())
}
// First pull: allowed at once.
t0 := now()
pullOK(payer, sessA, 2*gnot)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, int64(1), m.Pulls)
uassert.Equal(t, 2*gnot, m.Paid)
uassert.Equal(t, t0, m.LastPullAt)
uassert.Equal(t, t0+MinPeriod, m.NextPullAt)
uassert.False(t, m.Due)
p, _ := GetPlan(pid)
uassert.Equal(t, int64(1), p.Pulls)
uassert.Equal(t, 2*gnot, p.Paid)
pe, _ := GetPayee(payee)
uassert.Equal(t, int64(1), pe.Pulls)
uassert.Equal(t, 2*gnot, pe.Paid)
_, _, pulls, paid := Totals()
uassert.Equal(t, int64(1), pulls)
uassert.Equal(t, 2*gnot, paid)
// Too early: right after, and one block before the period ends.
panicsLocal(t, cur, "too early, next pull from "+itoa(t0+MinPeriod), func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), now()) }, "second pull at once")
testing.SkipHeights(11) // +55 s
panicsLocal(t, cur, "too early", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), now()) }, "pull at +55 s")
uassert.Equal(t, int64(55), now()-t0)
// The rule at the exact second: allowed at next, refused at next-1.
panicsLocal(t, cur, "too early", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), t0+MinPeriod-1) }, "pull at next-1")
checkPull(true, sessA, paths, payer, ugnot(2*gnot), t0+MinPeriod)
testing.SkipHeights(1) // +60 s: due
m, _ = MandateOf(payer, sessA)
uassert.True(t, m.Due)
pullOK(payer, sessA, 2*gnot)
m, _ = MandateOf(payer, sessA)
uassert.Equal(t, int64(2), m.Pulls)
uassert.Equal(t, now()+MinPeriod, m.NextPullAt)
// A late pull: the next one is one period after it (no catch-up).
testing.SkipHeights(60) // +300 s, four periods missed
pullOK(payer, sessA, 2*gnot)
m, _ = MandateOf(payer, sessA)
uassert.Equal(t, int64(3), m.Pulls)
uassert.Equal(t, now()+MinPeriod, m.NextPullAt)
panicsLocal(t, cur, "too early", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), now()) }, "no catch-up")
// Expiry: exactly at ExpiresAt is refused, one second before is allowed.
testing.SkipHeights(12)
checkPull(true, sessA, paths, payer, ugnot(2*gnot), exp-1)
panicsLocal(t, cur, "expired", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), exp) }, "pull at expiry")
uassert.Equal(t, int64(0), bal(realmAddr))
}
func TestPullCancelled(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day)
subscribe(cur, payer2, pid, sessA, now()+day)
cancel(cur, payee, payer, sessA) // the payee may cancel too
panicsLocal(t, cur, "cancelled", func() { checkPull(true, sessA, []string{selfPaths}, payer, ugnot(gnot), now()) }, "pull after cancel")
// The other payer's mandate on the same key is untouched.
pullOK(payer2, sessA, gnot)
uassert.False(t, HasMandate(payer, pid))
uassert.True(t, HasMandate(payer2, pid))
}
func TestPullEntryPoint(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day)
// Without a session (all that gno test can do) Pull refuses before anything else.
testing.SetRealm(testing.NewUserRealm(payer))
testing.SetOriginSend(ugnot(gnot))
fails(t, cur, "signed with the mandate's session key", func() { Pull(cross(cur)) }, "Pull without session")
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/proxy"))
fails(t, cur, "must be a direct call", func() { Pull(cross(cur)) }, "Pull from a realm")
}
func TestCancel(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, day)
subscribe(cur, payer, pid, sessA, now()+day)
for _, c := range []struct {
who, p, s address
want string
}{
{stranger, payer, sessA, "only the payer or the payee"},
{payee2, payer, sessA, "only the payer or the payee"},
{sessA, payer, sessA, "only the payer or the payee"},
{payer, payer, sessB, "no active mandate"},
{payer, payer2, sessA, "no active mandate"},
} {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(c.who))
fails(t, cur, c.want, func() { Cancel(cross(cur), c.p, c.s) }, "Cancel "+c.want)
}
testing.SetRealm(testing.NewUserRealm(payer))
testing.SetOriginSend(ugnot(1))
fails(t, cur, "do not send coins", func() { Cancel(cross(cur), payer, sessA) }, "Cancel with coins")
testing.SetOriginSend(nil)
cancel(cur, payer, payer, sessA)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, "cancelled", m.Status)
uassert.Equal(t, now(), m.CancelledAt)
uassert.Equal(t, payer.String(), m.CancelledBy.String())
uassert.False(t, m.Due)
testing.SetRealm(testing.NewUserRealm(payer))
fails(t, cur, "already cancelled", func() { Cancel(cross(cur), payer, sessA) }, "cancel twice")
}
func TestReadsArePlainCopies(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Original", gnot, day)
subscribe(cur, payer, pid, sessA, now()+day)
p, _ := GetPlan(pid)
p.Title = "changed"
p.Amount = 1
list := Plans(1)
list[0].Payee = stranger
m, _ := MandateOf(payer, sessA)
m.ExpiresAt = 0
ms := MandatesOf(payer, 1)
ms[0].Status = "cancelled"
p2, _ := GetPlan(pid)
uassert.Equal(t, "Original", p2.Title)
uassert.Equal(t, gnot, p2.Amount)
uassert.Equal(t, payee.String(), Plans(1)[0].Payee.String())
uassert.True(t, HasMandate(payer, pid))
_, ok := GetPlan(99)
uassert.False(t, ok)
_, ok = MandateOf(stranger, sessA)
uassert.False(t, ok)
_, ok = GetPayee(stranger)
uassert.False(t, ok)
uassert.False(t, HasMandate(stranger, pid))
uassert.False(t, HasMandate(payer, 99))
}
func TestPaging(cur realm, t *testing.T) {
resetState()
for i := 0; i < 25; i++ {
offer(cur, payee, "Plan "+itoa(int64(i+1)), gnot, day)
}
offer(cur, payee2, "Other creator", gnot, day)
uassert.Equal(t, PageSize, len(Plans(1)))
uassert.Equal(t, 6, len(Plans(2)))
uassert.Equal(t, 0, len(Plans(3)))
uassert.Equal(t, PageSize, len(Plans(0))) // clamped to page 1
uassert.Equal(t, PageSize, len(Plans(-5)))
uassert.Equal(t, 0, len(Plans(1<<30)))
uassert.Equal(t, "Other creator", Plans(1)[0].Title) // newest first
uassert.Equal(t, uint64(1), Plans(2)[5].ID)
uassert.Equal(t, PageSize, len(PlansOf(payee, 1)))
uassert.Equal(t, 5, len(PlansOf(payee, 2)))
uassert.Equal(t, uint64(1), PlansOf(payee, 1)[0].ID) // oldest first
uassert.Equal(t, 1, len(PlansOf(payee2, 1)))
uassert.Equal(t, 0, len(PlansOf(stranger, 1)))
// 23 payers on plan 1, all with the same collector key.
for i := 0; i < 23; i++ {
who := testutils.TestAddress("md_p" + itoa(int64(i)))
subscribe(cur, who, 1, sessA, now()+day)
}
uassert.Equal(t, PageSize, len(SupportersOf(1, 1)))
uassert.Equal(t, 3, len(SupportersOf(1, 2)))
uassert.Equal(t, 0, len(SupportersOf(2, 1)))
// CollectorScan: plan 1's supporter list, filtered to one key, in
// windows of ScanLimit entries with a cursor.
first := testutils.TestAddress("md_p0")
lines := strings.Split(strings.TrimSuffix(CollectorScan(1, sessA, 0), "\n"), "\n")
uassert.Equal(t, 24, len(lines))
uassert.Equal(t, "end", lines[23])
uassert.Equal(t, "0 1 "+first.String()+" 1000000 "+itoa(now())+" due 0 0", lines[0])
uassert.Equal(t, "end\n", CollectorScan(1, sessB, 0))
uassert.Equal(t, "end\n", CollectorScan(99, sessA, 0))
uassert.Equal(t, "end\n", CollectorScan(1, sessA, 23))
// after a pull and a cancel: the paid one waits and shows its pulls, the cancelled one is gone
pullOK(first, sessA, gnot)
second := testutils.TestAddress("md_p1")
cancel(cur, second, second, sessA)
lines = strings.Split(strings.TrimSuffix(CollectorScan(1, sessA, 0), "\n"), "\n")
uassert.Equal(t, 23, len(lines))
uassert.Equal(t, "0 1 "+first.String()+" 1000000 "+itoa(now()+day)+" wait 1 1", lines[0])
uassert.True(t, strings.HasPrefix(lines[1], "2 3 "))
// CollectorPlans
pl := strings.Split(strings.TrimSuffix(CollectorPlans(payee, 1), "\n"), "\n")
uassert.Equal(t, PageSize+1, len(pl))
uassert.Equal(t, "1 1000000 86400 23", pl[0])
uassert.Equal(t, "more", pl[PageSize])
uassert.Equal(t, "end\n", CollectorPlans(stranger, 1))
_, nMandates, _, _ := Totals()
uassert.Equal(t, 23, nMandates)
}
func TestFormat(t *testing.T) {
uassert.Equal(t, "1 GNOT", formatUgnot(1_000_000))
uassert.Equal(t, "0.1 GNOT", formatUgnot(100_000))
uassert.Equal(t, "0.05 GNOT", formatUgnot(50_000))
uassert.Equal(t, "1.000001 GNOT", formatUgnot(1_000_001))
uassert.Equal(t, "0 GNOT", formatUgnot(0))
uassert.Equal(t, "1000000 GNOT", formatUgnot(MaxAmount))
uassert.Equal(t, "minute", formatPeriod(60))
uassert.Equal(t, "90 seconds", formatPeriod(90))
uassert.Equal(t, "2 hours", formatPeriod(7200))
uassert.Equal(t, "day", formatPeriod(86400))
uassert.Equal(t, "week", formatPeriod(604800))
uassert.Equal(t, "30 days", formatPeriod(30*86400))
uassert.Equal(t, "30 days", formatPeriod(MaxPeriod))
uassert.Equal(t, "0000000001", pad(1))
uassert.Equal(t, "18446744073709551615", pad(18446744073709551615))
uassert.True(t, pad(9) < pad(10))
uassert.Equal(t, 1, pageParam(""))
uassert.Equal(t, 3, pageParam("page=3"))
uassert.Equal(t, 3, pageParam("x=1&page=3"))
uassert.Equal(t, 1, pageParam("page=0"))
uassert.Equal(t, 1, pageParam("page=-2"))
uassert.Equal(t, 1, pageParam("page=abc"))
uassert.Equal(t, 1, pageParam("page=99999999999"))
uassert.Equal(t, "1970-01-01 00:00 UTC", formatTime(0))
uassert.Equal(t, "never", formatTimeOrNever(0))
}
reads.gno
package mandate
import (
"strconv"
"strings"
"time"
)
// Free reads. Each returns plain values (copies), never pointers into the
// realm's state, so callers and vm/qeval cannot change anything.
// PlanInfo is a copy of a plan.
type PlanInfo struct {
ID uint64
Payee address
Title string
Amount int64
Period int64
CreatedAt int64
Mandates int // mandates ever created for this plan
Cancelled int // how many of them were cancelled
// PaidThisPeriod and PaidLastPeriod count the payments in the plan's
// current period window, which started at PeriodStart, and in the window
// before it. Windows are [k*Period, (k+1)*Period) in unix time. They count
// payments, not distinct people (a creator can pay its own plan from a
// second wallet). Historical facts, true at any time, whatever has
// expired or been cancelled since.
PaidThisPeriod int
PaidLastPeriod int
PeriodStart int64
Pulls int64
Paid int64
LastPullAt int64
}
// MandateInfo is a copy of a mandate with the realm's view of it.
type MandateInfo struct {
ID uint64
PlanID uint64
Payer address
Payee address
Session address
SessionPubKey string
Amount int64
Period int64
CreatedAt int64
ExpiresAt int64
NextPullAt int64
LastPullAt int64
// PaidThrough is until when this mandate's payments, or paid time
// carried over from the payer's earlier mandate for the plan, cover the
// payer (0 if neither). A mandate that starts with carried time has its
// first pull at that time.
PaidThrough int64
Pulls int64
Paid int64
CancelledAt int64
CancelledBy address
// Status is "active", "expired" or "cancelled": the realm's view only.
Status string
// Due is true when the mandate is active and a pull is allowed now.
Due bool
// SessionPubKey is the session key's public key when it is the payee's
// current collector key, "" otherwise.
//
// SessionQuery is the free query an off-chain checker must also run:
// the realm cannot see a session revoked or expired on chain.
SessionQuery string
}
// PayeeInfo is a copy of a payee's totals and collector key.
type PayeeInfo struct {
Addr address
Plans int
Pulls int64
Paid int64
LastPullAt int64
CollectorKey string
CollectorAddr address
// CollectorFunded is true when the collector key's address holds coins:
// the chain then refuses every new session for that key, so nobody can
// subscribe until the creator publishes a new key. (An address that
// received coins and was emptied is also refused by the chain; only the
// free query auth/accounts/<CollectorAddr> shows that.)
CollectorFunded bool
}
// GetPlan returns the plan with this id.
func GetPlan(id uint64) (PlanInfo, bool) {
p := planOf(id)
if p == nil {
return PlanInfo{}, false
}
return p.info(), true
}
// MandateOf returns the latest mandate of payer for this session address.
func MandateOf(payer, sessionAddr address) (MandateInfo, bool) {
m := latestBySession(payer, sessionAddr)
if m == nil {
return MandateInfo{}, false
}
return m.info(time.Now().Unix()), true
}
// PaidThrough is the read for services that deliver something to paying
// supporters. It returns the unix time until which the payer's payments for
// the plan cover them: the latest payment's time plus one period. Paid time
// stays the payer's when a mandate is cancelled (by either side) or
// expires, and a new mandate for the same plan starts when it ends, so it
// is not charged twice. The one exception: a payer who already holds 16
// kept periods (MaxCreditsPerPayer). 0 when they never paid for the plan.
// Deliver while now < PaidThrough.
//
// It turns false at the due time and moves on only when the payee's
// collector pulls the next payment: allow a grace equal to how often the
// collector runs (an hour, say) before treating a supporter as lapsed.
//
// A payment is proof; a mandate is not: anyone can record a mandate
// without creating a session and without paying. A realm also cannot see a
// session revoked on chain: a revoked supporter simply stops paying, so
// PaidThrough stops moving and runs out within one period.
func PaidThrough(payer address, planID uint64) int64 {
pr := payerOf(payer)
if pr == nil {
return 0
}
now := time.Now().Unix()
until := pr.creditFor(planID, now)
for _, r := range pr.Active {
if r.PlanID == planID {
if t := r.M.paidThrough(); t > until {
until = t
}
}
}
return until
}
// IsPaidUp reports whether payer's latest payment for the plan still covers
// now (now < PaidThrough). See PaidThrough.
func IsPaidUp(payer address, planID uint64) bool {
return time.Now().Unix() < PaidThrough(payer, planID)
}
// HasMandate reports whether payer has a mandate for the plan that is
// neither cancelled nor expired in the realm. It says nothing about payment
// (a mandate costs only a storage deposit to record) and cannot see a
// session revoked on chain: do not grant anything on it; use PaidThrough.
func HasMandate(payer address, planID uint64) bool {
m := activeByPlan(payer, planID)
return m != nil && m.isActive(time.Now().Unix())
}
// NextPullAt returns when the next pull of payer's active mandate for the
// plan is allowed (unix seconds), or 0 if there is no active mandate.
func NextPullAt(payer address, planID uint64) int64 {
m := activeByPlan(payer, planID)
if m == nil || !m.isActive(time.Now().Unix()) {
return 0
}
return m.NextPullAt
}
// GetPayee returns a payee's totals and collector key.
func GetPayee(payee address) (PayeeInfo, bool) {
pe := payeeOf(payee)
if pe == nil {
return PayeeInfo{}, false
}
return PayeeInfo{
Addr: pe.Addr,
Plans: pe.Plans,
Pulls: pe.Pulls,
Paid: pe.Paid,
LastPullAt: pe.LastPullAt,
CollectorKey: pe.CollectorKey,
CollectorAddr: pe.CollectorAddr,
CollectorFunded: pe.CollectorKey != "" && collectorFunded(pe.CollectorAddr),
}, true
}
// Totals returns the number of plans and mandates, and all pulls so far.
func Totals() (plansCount, mandatesCount int, pulls, paid int64) {
return plans.Size(), int(nextMandateID), totalPulls, totalPaid
}
// Plans lists all plans, newest first, PageSize per page (page 1 first).
func Plans(page int) []PlanInfo {
out := []PlanInfo{}
plans.ReverseIterateByOffset(offset(page), PageSize, func(_ string, v any) bool {
out = append(out, v.(*Plan).info())
return false
})
return out
}
// PlansOf lists a payee's plans, oldest first.
func PlansOf(payee address, page int) []PlanInfo {
out := []PlanInfo{}
plans, _ := payeePlans(payee, page)
for _, p := range plans {
out = append(out, p.info())
}
return out
}
// payeePlans returns page `page` of a payee's plans and whether more follow.
func payeePlans(payee address, page int) ([]*Plan, bool) {
pe := payeeOf(payee)
if pe == nil {
return nil, false
}
lo, hi, more := pageBounds(pe.planIDs.N, page)
out := make([]*Plan, 0, hi-lo)
for i := lo; i < hi; i++ {
id, _ := strconv.ParseUint(pe.planIDs.at(i), 10, 64)
out = append(out, planOf(id))
}
return out, more
}
// MandatesOf lists a payer's mandates (all states), newest first.
func MandatesOf(payer address, page int) []MandateInfo {
list, _ := payerPage(payer, page)
return infos(list)
}
// payerPage returns page `page` of the payer's mandates, newest first, and
// whether another page follows. It walks the payer's history, which only
// free reads do.
func payerPage(payer address, page int) ([]*Mandate, bool) {
skip := offset(page)
out := []*Mandate{}
for m := payerHead(payer); m != nil; m = m.prevOfPayer {
if skip > 0 {
skip--
continue
}
if len(out) == PageSize {
return out, true
}
out = append(out, m)
}
return out, false
}
// SupportersOf lists a plan's active mandates (not cancelled, replaced or
// expired), oldest first. Page n covers entries (n-1)*PageSize to
// n*PageSize-1 of the plan's list, so a page may hold fewer rows than
// PageSize; inactive ones are on the payers' own pages.
func SupportersOf(planID uint64, page int) []MandateInfo {
p := planOf(planID)
if p == nil {
return []MandateInfo{}
}
now := time.Now().Unix()
out := []MandateInfo{}
lo, hi, _ := pageBounds(p.Supporters.N, page)
for i := lo; i < hi; i++ {
e := decodeEntry(p.Supporters.at(i))
if e.Status == statusCancelled {
continue
}
if m := activeMandate(e); m != nil && m.isActive(now) {
out = append(out, m.info(now))
}
}
return out
}
// ScanLimit is the most supporter-list entries one free read resolves
// (looks up in its payer's record); WalkLimit is the most it reads at all.
// Entries carry their status, so cancelled ones, and for some reads unpaid
// ones, are skipped without a lookup. Reads that filter return a cursor to
// continue from, so junk can delay but never hide a real entry.
const (
ScanLimit = 200
WalkLimit = 1000
)
// CollectorPlans lists a payee's plans for a collector script, one per line:
//
// <plan id> <amount ugnot> <period seconds> <mandates>
//
// PageSize per page; the last line is "more" or "end".
func CollectorPlans(payee address, page int) string {
var b strings.Builder
more := false
if list, m := payeePlans(payee, page); list != nil {
more = m
for _, p := range list {
b.WriteString(utoa(p.ID) + " " + itoa(p.Amount) + " " + itoa(p.Period) + " " + strconv.Itoa(p.Supporters.N) + "\n")
}
}
if more {
b.WriteString("more\n")
} else {
b.WriteString("end\n")
}
return b.String()
}
// CollectorScan walks at most ScanLimit entries of a plan's supporter list,
// from index `from` (0 = oldest), and returns the active mandates whose
// session key is sessionAddr, one per line:
//
// <index> <mandate id> <payer> <amount ugnot> <next pull unix> <due|wait> <pulls> <paid>
//
// <paid> is 1 when the payer has paid for this plan (this mandate pulled, or
// it started with paid time carried over from an earlier one), 0 when it
// never has. The last line is "next <index>" when more entries follow,
// "end" otherwise. Cancelled and expired mandates, and mandates for other
// keys, are skipped here, so a collector never needs to read them. Anyone
// can record a mandate without a session, so a collector should check on
// chain that the session exists, at least before the first pull of a
// mandate whose payer never paid.
func CollectorScan(planID uint64, sessionAddr address, from int) string {
p := planOf(planID)
if p == nil {
return "end\n"
}
if from < 0 {
from = 0
}
if from > p.Supporters.N {
from = p.Supporters.N // also keeps from+ScanLimit from overflowing
}
now := time.Now().Unix()
var b strings.Builder
end := from + ScanLimit
if end > p.Supporters.N {
end = p.Supporters.N
}
for i := from; i < end; i++ {
e := decodeEntry(p.Supporters.at(i))
if e.Status == statusCancelled {
continue
}
pr := payerOf(e.Payer)
if pr == nil {
continue
}
var m *Mandate
for _, r := range pr.Active {
if r.ID == e.ID && r.Session == sessionAddr {
m = r.M
}
}
if m == nil || !m.isActive(now) {
continue
}
due := "wait"
if now >= m.NextPullAt {
due = "due"
}
b.WriteString(strconv.Itoa(i) + " " + utoa(m.ID) + " " + m.Payer.String() + " " + itoa(p.Amount) + " " +
itoa(m.NextPullAt) + " " + due + " " + itoa(m.Pulls) + " " + paidFlag(m) + "\n")
}
if end < p.Supporters.N {
b.WriteString("next " + strconv.Itoa(end) + "\n")
} else {
b.WriteString("end\n")
}
return b.String()
}
// payingFrom lists a plan's supporters: mandates that have paid at least
// once and are active now, newest first, up to PageSize, starting at list
// index `from` (or the newest when from < 0). It reads at most WalkLimit
// entries and resolves at most ScanLimit of them (only entries marked paid
// are resolved), and returns the index to continue from (-1 when the list is
// exhausted).
func payingFrom(p *Plan, from int, now int64) ([]*Mandate, int) {
if from < 0 || from >= p.Supporters.N {
from = p.Supporters.N - 1
}
out := []*Mandate{}
i, walked, resolved := from, 0, 0
for ; i >= 0 && walked < WalkLimit && resolved < ScanLimit && len(out) < PageSize; i, walked = i-1, walked+1 {
e := decodeEntry(p.Supporters.at(i))
if e.Status != statusPaid {
continue
}
resolved++
if m := activeMandate(e); m != nil && m.isActive(now) {
out = append(out, m)
}
}
return out, i
}
// PayingSupporters lists a plan's supporters the way its gnoweb page does:
// mandates that have paid at least once and are active now, newest first,
// at most PageSize per call. Pass from = -1 for the newest; the second
// result is where to continue. A client must stop when it is -1 (the list
// is exhausted): -1 passed back in starts again from the newest, so a
// client that feeds the cursor back unchecked loops for ever. Each call
// walks at most WalkLimit entries and looks up at most ScanLimit of them,
// so a call may return fewer than PageSize (even none) and still a cursor.
func PayingSupporters(planID uint64, from int) ([]MandateInfo, int) {
p := planOf(planID)
if p == nil {
return []MandateInfo{}, -1
}
now := time.Now().Unix()
list, next := payingFrom(p, from, now)
out := make([]MandateInfo, 0, len(list))
for _, m := range list {
out = append(out, m.info(now))
}
return out, next
}
// PlanCounts returns the numbers the gnoweb plan page shows: how many
// supporters paid in the plan's current period window and in the one
// before (as in GetPlan), and how many active mandates have never paid,
// among the latest ScanLimit entries (unpaidExact is false when there were
// more entries than that).
func PlanCounts(planID uint64) (paidThisPeriod, paidLastPeriod, unpaid int, unpaidExact bool) {
p := planOf(planID)
if p == nil {
return 0, 0, 0, true
}
now := time.Now().Unix()
paidThisPeriod, paidLastPeriod = p.paidWindows(now)
unpaid, unpaidExact = countUnpaid(p, now)
return
}
// countUnpaid counts active mandates that have never paid, among the
// plan's latest ScanLimit mandates, and says whether that covered them all.
func countUnpaid(p *Plan, now int64) (int, bool) {
n := 0
lo := p.Supporters.N - ScanLimit
if lo < 0 {
lo = 0
}
for i := p.Supporters.N - 1; i >= lo; i-- {
e := decodeEntry(p.Supporters.at(i))
if e.Status != statusUnpaid {
continue
}
if m := activeMandate(e); m != nil && m.isActive(now) {
n++
}
}
return n, lo == 0
}
func infos(list []*Mandate) []MandateInfo {
now := time.Now().Unix()
out := []MandateInfo{}
for _, m := range list {
out = append(out, m.info(now))
}
return out
}
func (p *Plan) info() PlanInfo {
now := time.Now().Unix()
current, previous := p.paidWindows(now)
return PlanInfo{
ID: p.ID,
Payee: p.Payee,
Title: p.Title,
Amount: p.Amount,
Period: p.Period,
CreatedAt: p.CreatedAt,
Mandates: p.Supporters.N,
Cancelled: p.Cancelled,
PaidThisPeriod: current,
PaidLastPeriod: previous,
PeriodStart: now / p.Period * p.Period,
Pulls: p.Pulls,
Paid: p.Pulls * p.Amount,
LastPullAt: p.LastPullAt,
}
}
func (m *Mandate) info(now int64) MandateInfo {
p := m.plan
st := m.status(now)
return MandateInfo{
ID: m.ID,
PlanID: p.ID,
Payer: m.Payer,
Payee: p.Payee,
Session: m.Session,
SessionPubKey: m.sessionPubKey(),
Amount: p.Amount,
Period: p.Period,
CreatedAt: m.CreatedAt,
ExpiresAt: m.ExpiresAt,
NextPullAt: m.NextPullAt,
LastPullAt: m.lastPullAt(),
PaidThrough: m.paidThrough(),
Pulls: m.Pulls,
Paid: m.Pulls * p.Amount,
CancelledAt: m.CancelledAt,
CancelledBy: m.CancelledBy,
Status: st,
Due: st == "active" && now >= m.NextPullAt,
SessionQuery: "auth/accounts/" + m.Payer.String() + "/session/" + m.Session.String(),
}
}
// lastPullAt is when the last pull happened (0 = never): each pull sets
// NextPullAt to its own time plus one period.
func (m *Mandate) lastPullAt() int64 {
if m.Pulls == 0 {
return 0
}
return m.NextPullAt - m.plan.Period
}
// sessionPubKey returns the session key's public key when it is the payee's
// current collector key, "" otherwise (the realm then does not know it).
func (m *Mandate) sessionPubKey() string {
if pe := m.plan.payee; pe.CollectorAddr == m.Session {
return pe.CollectorKey
}
return ""
}
// offset turns a 1-based page number into a row offset; pages below 1 and
// absurdly large pages are clamped.
func offset(page int) int {
if page < 1 {
page = 1
}
if page > 1_000_000 {
page = 1_000_000
}
return (page - 1) * PageSize
}
// pageBounds returns the slice bounds of page `page` (1-based, PageSize
// rows) in a list of n rows, and whether another page follows.
func pageBounds(n, page int) (lo, hi int, more bool) {
lo = offset(page)
if lo > n {
lo = n
}
hi = lo + PageSize
if hi > n {
hi = n
}
return lo, hi, hi < n
}
// paidFlag is CollectorScan's last column: "1" once the payer has paid for
// the plan through this mandate or carried paid time into it, else "0".
func paidFlag(m *Mandate) string {
if m.paidThrough() > 0 {
return "1"
}
return "0"
}
render.gno
package mandate
import (
"strconv"
"strings"
"time"
)
// SourceRepo is where the source code is published, shown in the footer of
// every page.
const SourceRepo = "https://github.com/elangrr/mandate"
// Network the copy-ready commands are pinned to.
const (
ChainID = "onyx-1"
Remote = "https://rpc.onyx.testnets.gno.land:443"
)
// Gas settings used in the commands. The chain charges the whole fee set,
// whatever gas is used, and accepts it when fee / gas wanted is at least
// the current gas price (1 ugnot per 1,000 gas on Onyx). Measured on a local
// chain: Offer and Subscribe use 7M to 10M gas, Pull 8M to 9M. Reads on
// Onyx cost more per object (the chain prices a read by its store's depth,
// and Onyx's store is far larger), so gas wanted keeps about 2x headroom.
// The Pull fee counts against the session's spend limit (see FeeAllowance).
const (
callGas = "-gas-fee 100000ugnot -gas-wanted 60000000"
pullGas = "-gas-fee 20000ugnot -gas-wanted 20000000"
)
// Render returns the gnoweb page for path, with the footer.
func Render(path string) string {
return renderPage(path) + footer()
}
func footer() string {
return "\n---\n\nBuilt on [gno.land](https://gno.land) · source code: [" + strings.TrimPrefix(SourceRepo, "https://") + "](" + SourceRepo + ")\n"
}
func renderPage(raw string) string {
path, query := raw, ""
if i := strings.Index(raw, "?"); i >= 0 {
path, query = raw[:i], raw[i+1:]
}
page := pageParam(query)
from := intParam(query, "from", -1)
parts := strings.Split(path, "/")
switch {
case path == "":
return renderHome(from)
case path == "plans":
return renderAllPlans(page)
case path == "help":
return renderHelp()
case len(parts) == 2 && parts[0] == "plan":
id, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return renderNotFound()
}
return renderPlan(id, from)
case len(parts) == 2 && parts[0] == "payer":
a := address(parts[1])
if !a.IsValid() {
return renderNotFound()
}
return renderPayer(a, page)
case len(parts) == 2 && parts[0] == "payee":
a := address(parts[1])
if !a.IsValid() {
return renderNotFound()
}
return renderPayee(a, page)
}
return renderNotFound()
}
func renderHome(from int) string {
nPlans, nMandates, pulls, paid := Totals()
var b strings.Builder
b.WriteString("# Mandate\n\n")
b.WriteString("**Subscriptions and direct debit on native GNOT.** A creator publishes a plan, such as 1 GNOT every week. ")
b.WriteString("A supporter signs one permission from their own wallet: *at most this much, every period, through this realm only, until I cancel or it expires*. ")
b.WriteString("The creator's collector then pulls each payment at the start of the period, and this realm checks who, how much and when before it forwards the coins.\n\n")
b.WriteString("## The honest limits\n\n")
b.WriteString("- **It is direct debit, not escrow.** Nothing is locked up front. A supporter can stop at any time, and a creator is only paid when a pull succeeds.\n")
b.WriteString("- **A hard cap the supporter sets.** The chain never lets a pull take more than the session's spend limit per period: the plan's amount plus a fee allowance of " + formatUgnot(FeeAllowance) + ". ")
b.WriteString("A dishonest creator could at worst burn that allowance as network fees; they can never take more, or pull more often.\n")
b.WriteString("- **At most " + strconv.Itoa(MaxSessionsPerWallet) + " mandates per wallet**, because the chain allows " + strconv.Itoa(MaxSessionsPerWallet) + " session keys per account.\n")
b.WriteString("- **Revoke any time.** Revoking the session on chain stops every pull at once. The realm cannot see a revoke, so a mandate still shows here as active until it is cancelled or expires: [how to stop a mandate](" + link("help") + ").\n")
b.WriteString("- **One realm, nothing under it.** A session for this realm also covers any realm deployed under its path, so nothing will ever be deployed there.\n")
b.WriteString("- No admin, no pause, no upgrade. The realm never holds funds: each payment goes straight to the creator in the same transaction.\n\n")
b.WriteString("[How to use it, with every command](" + link("help") + ")\n\n")
b.WriteString("## Numbers\n\n")
b.WriteString("| Plans | Mandates ever recorded | Payments | Paid out |\n|---|---|---|---|\n")
b.WriteString("| " + strconv.Itoa(nPlans) + " | " + strconv.Itoa(nMandates) + " | " + itoa(pulls) + " | " + formatUgnot(paid) + " |\n\n")
b.WriteString("## Supporter pages\n\n")
b.WriteString(plansWithSupporters(from))
return b.String()
}
// homeScanPlans is how many plans one home page walks. Each check reads only
// the plan itself (its payment counters), never its supporters.
const homeScanPlans = ScanLimit
// plansWithSupporters lists, newest first, the plans that someone paid in
// the current or the previous period, walking at most homeScanPlans plans
// per page: plans nobody pays for (spam included) never fill this list, and
// a "more" link continues the walk. A plan someone keeps paying for stays,
// whatever the churn of its supporter list.
func plansWithSupporters(from int) string {
var b strings.Builder
n := plans.Size()
if from < 0 || from >= n {
from = n - 1
}
rows := 0
i := from
now := time.Now().Unix()
var t strings.Builder
for walked := 0; i >= 0 && walked < homeScanPlans && rows < PageSize; i, walked = i-1, walked+1 {
_, v := plans.GetByIndex(i)
p := v.(*Plan)
if current, previous := p.paidWindows(now); current+previous == 0 {
continue
}
t.WriteString("| [#" + utoa(p.ID) + " " + escCell(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ") | " + price(p.Amount, p.Period) +
" | [" + short(p.Payee) + "](" + link("payee/"+p.Payee.String()) + ") | " + payingCell(p, now) +
" | " + itoa(p.Pulls) + " |\n")
rows++
}
if rows == 0 {
b.WriteString("No plan has been paid for in its current or last period")
if i >= 0 {
b.WriteString(" among those looked at")
}
b.WriteString(".\n\n")
} else {
b.WriteString("| Plan | Price | Creator | Payments this / last period | All payments |\n|---|---|---|---|---|\n")
b.WriteString(t.String() + "\n")
}
if i >= 0 {
b.WriteString("[More plans with supporters](" + link("") + "?from=" + strconv.Itoa(i) + ")\n\n")
}
b.WriteString("Only plans that someone has paid for are listed here. [All plans, newest first](" + link("plans") + ")\n")
return b.String()
}
func renderAllPlans(page int) string {
var b strings.Builder
b.WriteString("# All plans\n\nNewest first, including plans nobody has paid for yet. [Back to Mandate](" + link("") + ")\n\n")
list := Plans(page)
if len(list) == 0 {
b.WriteString("No plans on this page.\n")
return b.String()
}
b.WriteString("| Plan | Price | Creator | Payments this / last period | All payments |\n|---|---|---|---|---|\n")
for _, p := range list {
b.WriteString("| [#" + utoa(p.ID) + " " + escCell(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ") | " + price(p.Amount, p.Period) +
" | [" + short(p.Payee) + "](" + link("payee/"+p.Payee.String()) + ") | " + infoPayingCell(p) +
" | " + itoa(p.Pulls) + " |\n")
}
b.WriteString(pager("plans", page, len(list) == PageSize))
return b.String()
}
func renderPlan(id uint64, from int) string {
p := planOf(id)
if p == nil {
return renderNotFound()
}
now := time.Now().Unix()
pe := payeeOf(p.Payee)
var b strings.Builder
b.WriteString("# Plan #" + utoa(p.ID) + ": " + esc(p.Title) + "\n\n")
b.WriteString("**" + price(p.Amount, p.Period) + "** to [" + p.Payee.String() + "](" + link("payee/"+p.Payee.String()) + ")")
if p.Period < 86400 {
b.WriteString(" (a test plan: the period is under a day)")
}
b.WriteString("\n\n")
b.WriteString("Plan " + utoa(p.ID) + " · published " + formatTime(p.CreatedAt) + " · " + payingText(p, now) + " · " +
plural(int(p.Pulls), "payment", "payments") + ", " + formatUgnot(p.Pulls*p.Amount) + " in total · last payment: " + formatTimeOrNever(p.LastPullAt) + "\n\n")
b.WriteString("Plans never change. New terms are published as a new plan.\n\n")
b.WriteString("## Supporters\n\n")
list, next := payingFrom(p, from, now)
if len(list) == 0 {
b.WriteString("No paying supporters")
if next >= 0 {
b.WriteString(" in this part of the list")
}
b.WriteString(".\n\n")
} else {
b.WriteString("| Supporter | Since | Payments | Last payment |\n|---|---|---|---|\n")
for _, m := range list {
b.WriteString("| [" + short(m.Payer) + "](" + link("payer/"+m.Payer.String()) + ") | " + formatTime(m.CreatedAt) + " | " + itoa(m.Pulls) +
" | " + formatTimeOrNever(m.lastPullAt()) + " |\n")
}
b.WriteString("\n")
}
if next >= 0 {
b.WriteString("[More supporters](" + link("plan/"+utoa(id)) + "?from=" + strconv.Itoa(next) + ")\n\n")
}
unpaid, exact := countUnpaid(p, now)
b.WriteString("Supporters are listed and counted from their first payment on, newest first, while their mandate is active. ")
b.WriteString("Cancelled and expired mandates are not listed or counted; a supporter who revoked the session on chain stays listed until the mandate is cancelled or expires. ")
b.WriteString(plural(unpaid, "active mandate has", "active mandates have") + " not paid yet (not listed)")
if !exact {
b.WriteString(", among the latest " + strconv.Itoa(ScanLimit))
}
b.WriteString(".\n\n")
b.WriteString("## Support this plan\n\n")
spend := p.Amount + FeeAllowance
expires := now + 365*86400
if pe == nil || pe.CollectorKey == "" {
b.WriteString("The creator has not published a collector key yet, so there is nothing to subscribe to. Ask them to run `SetCollectorKey`.\n\n")
return b.String()
}
if collectorFunded(pe.CollectorAddr) {
b.WriteString("**New supporters cannot join right now.** The creator's collector key (`" + pe.CollectorAddr.String() + "`) has received coins, so its address is an account, and the chain refuses a session for a key whose address is an account. " +
"This creator must publish a new collector key before new supporters can join. Existing mandates keep working until they expire; renewing needs the new key. " +
"A creator can also hand you a fresh session key privately: `Subscribe` accepts any session key, not only the published one.\n\n")
return b.String()
}
b.WriteString("You need [gnokey](https://docs.gno.land) and a key with some GNOT on " + ChainID + ". Replace `YOUR_KEY` with your key's name. " +
"You can support one plan of each creator at a time: every plan of a creator is collected by the same key, and the chain allows one session per key. To switch plans, cancel and revoke first (time you paid for carries over to the same plan only). ")
b.WriteString("These two commands give the creator's collector key (`" + pe.CollectorAddr.String() + "`) the right to take **at most " +
formatUgnot(spend) + " every " + formatPeriod(p.Period) + "** (the price plus a fee allowance), through this realm only, for one year.\n\n")
b.WriteString("1. Create the session (your own key; it cannot be done with a session). If the chain answers `session key address collides with existing account`, this collector key can no longer be used for new sessions: ask the creator to publish a new one.\n\n")
b.WriteString("```\ngnokey maketx session create -pubkey " + pe.CollectorKey + " -allow-paths vm/exec:" + realmPath +
" -spend-limit " + itoa(spend) + "ugnot -spend-period " + itoa(p.Period) + " -expires-at " + itoa(expires) + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
b.WriteString("2. Record the terms here:\n\n")
b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Subscribe -args " + utoa(p.ID) + " -args " + pe.CollectorAddr.String() +
" -args " + itoa(expires) + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
b.WriteString("The first payment is collected right after, then one every " + formatPeriod(p.Period) + ". If you paid for this plan before and that period has not ended " +
"(you cancelled, the creator cancelled, or your mandate expired), the new mandate's first payment waits until it ends, so time you paid for is not charged twice. " +
"The one exception: a wallet keeps paid time for at most " + strconv.Itoa(MaxCreditsPerPayer) + " plans it has left; beyond that, a creator's cancel keeps nothing for that creator's plan, and your own cancel or expiry lets the period that ends soonest go. Your page at `" + link("payer/<your address>") +
"` shows how to stop.\n")
return b.String()
}
func renderPayer(payer address, page int) string {
var b strings.Builder
b.WriteString("# Mandates of " + payer.String() + "\n\n")
b.WriteString("Each mandate lets one creator's collector key pull a fixed amount once per period. To stop one completely, run both commands shown under it: ")
b.WriteString("**revoke** removes the session on chain (no pull can be signed any more) and **cancel** ends the mandate here. Revoke alone already stops every payment.\n\n")
list := MandatesOf(payer, page)
if len(list) == 0 {
b.WriteString("No mandates on this page.\n")
return b.String()
}
now := time.Now().Unix()
for _, m := range list {
p := planOf(m.PlanID)
b.WriteString("## Mandate " + utoa(m.ID) + ": [plan #" + utoa(p.ID) + " " + esc(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ")\n\n")
b.WriteString("- Status here: **" + m.Status + "**")
if m.Status == "active" {
b.WriteString(" (if you revoked the session on chain, no payment can be taken)")
}
b.WriteString("\n- Price: " + price(m.Amount, m.Period) + " to [" + short(m.Payee) + "](" + link("payee/"+m.Payee.String()) + ")\n")
b.WriteString("- Session key: `" + m.Session.String() + "`\n")
b.WriteString("- Payments: " + itoa(m.Pulls) + ", " + formatUgnot(m.Paid) + " in total, last: " + formatTimeOrNever(m.LastPullAt) + "\n")
if m.Status == "active" {
if m.Pulls == 0 && m.PaidThrough > 0 {
b.WriteString("- First payment on " + formatTime(m.NextPullAt) + ": your current period is already paid (time carried over from your earlier mandate for this plan) · ends: " + formatTime(m.ExpiresAt) + "\n")
} else {
b.WriteString("- Next payment allowed from: " + formatTime(m.NextPullAt) + " · ends: " + formatTime(m.ExpiresAt) + "\n")
}
} else if m.PaidThrough > now {
if PaidThrough(payer, m.PlanID) >= m.PaidThrough {
b.WriteString("- Paid through " + formatTime(m.PaidThrough) + ": that time stays yours. A new mandate for this plan starts its payments then.\n")
} else {
b.WriteString("- Paid through " + formatTime(m.PaidThrough) + ", but that time could not be kept: a wallet keeps paid time for at most " +
strconv.Itoa(MaxCreditsPerPayer) + " plans it has left, and a creator's cancel never pushes another one out. A new mandate for this plan would pay at once.\n")
}
}
b.WriteString("\n")
if m.Status != "cancelled" {
b.WriteString("Revoke the session (your own key):\n\n")
if m.SessionPubKey != "" {
b.WriteString("```\ngnokey maketx session revoke -pubkey " + m.SessionPubKey + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
} else {
b.WriteString("This session's public key is not recorded here. List your sessions to find it, then run `gnokey maketx session revoke -pubkey <its gpub1 key> ... YOUR_KEY`:\n\n")
b.WriteString("```\ngnokey query auth/accounts/" + payer.String() + "/sessions -remote " + Remote + "\n```\n\n")
}
b.WriteString("Cancel the mandate (your own key):\n\n")
b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Cancel -args " + payer.String() + " -args " + m.Session.String() + " " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
}
}
b.WriteString(pager("payer/"+payer.String(), page, len(list) == PageSize))
return b.String()
}
func renderPayee(payee address, page int) string {
var b strings.Builder
b.WriteString("# Creator " + payee.String() + "\n\n")
pe := payeeOf(payee)
if pe == nil {
b.WriteString("No plans from this address.\n")
return b.String()
}
b.WriteString("| Plans | Payments | Received | Last payment |\n|---|---|---|---|\n")
b.WriteString("| " + strconv.Itoa(pe.Plans) + " | " + itoa(pe.Pulls) + " | " + formatUgnot(pe.Paid) + " | " + formatTimeOrNever(pe.LastPullAt) + " |\n\n")
if pe.CollectorKey == "" {
b.WriteString("Collector key: **not published**. Supporters cannot subscribe until it is (see [help](" + link("help") + ")).\n\n")
} else {
b.WriteString("Collector key: `" + pe.CollectorAddr.String() + "` (`" + pe.CollectorKey + "`)\n\n")
if collectorFunded(pe.CollectorAddr) {
b.WriteString("**This collector key's address has received coins, so the chain refuses new sessions for it: nobody new can subscribe.** The creator must publish a new collector key; existing mandates keep being collected with this one until they expire, and renewing needs the new key.\n\n")
}
}
b.WriteString("## Plans\n\n")
list := PlansOf(payee, page)
if len(list) == 0 {
b.WriteString("No plans on this page.\n")
return b.String()
}
b.WriteString("| Plan | Price | Payments this / last period | All payments | Last payment |\n|---|---|---|---|---|\n")
for _, p := range list {
b.WriteString("| [#" + utoa(p.ID) + " " + escCell(p.Title) + "](" + link("plan/"+utoa(p.ID)) + ") | " + price(p.Amount, p.Period) + " | " +
infoPayingCell(p) + " | " + itoa(p.Pulls) + " | " + formatTimeOrNever(p.LastPullAt) + " |\n")
}
b.WriteString(pager("payee/"+payee.String(), page, len(list) == PageSize))
return b.String()
}
func renderHelp() string {
var b strings.Builder
b.WriteString("# How to use Mandate\n\n")
b.WriteString("Every command is for the **" + ChainID + "** test network and uses test GNOT. Replace the words in capitals. ")
b.WriteString("Amounts are in ugnot (1 GNOT = 1,000,000 ugnot); periods and times are in seconds and unix seconds.\n\n")
b.WriteString("## For creators\n\n")
b.WriteString("1. Publish a plan with your own key: a title (one line, at most " + strconv.Itoa(MaxTitleLen) + " characters, no invisible formatting characters: direction controls and zero-width characters, the joiner included, are refused, so emoji joined into one, such as families, cannot be used), the amount (at least " +
formatUgnot(MinAmount) + ") and the period (" + itoa(MinPeriod) + " seconds to " + itoa(MaxPeriod/86400) + " days). Plans cannot be changed.\n\n")
b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Offer -args \"TITLE\" -args 1000000 -args 604800 " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
b.WriteString("2. Make a separate key for collecting (`gnokey add COLLECTOR_KEY`) and publish its public key (the `gpub1...` value `gnokey list` shows), signed with your own key. " +
"**Never send coins to the collector key's address**, not even for fees (the supporter pays every fee): an address that has received coins is an account, and the chain refuses to create a session for it, so nobody new could subscribe. " +
"Anyone can do this to a published key with a 1 ugnot send, and a realm can even make the address an account that holds nothing. In most cases the plan page then says so; in every case supporters get the chain error `session key address collides with existing account` when they create the session, and the collector script warns. " +
"Then the key can no longer be used for new sessions: make a new key and publish it (this command again). New supporters then use the new key, and existing mandates keep being collected with the old one: run one collector per key. " +
"`Subscribe` accepts any session key you hand out, so you can also give supporters a fresh key privately:\n\n")
b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func SetCollectorKey -args GPUB_OF_COLLECTOR_KEY " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
b.WriteString("3. Collect each payment when it is due, signed with the collector key on behalf of the supporter. Only the exact price is accepted, at most once per period. The fee counts against the supporter's fee allowance, so keep it small. " +
"The command below uses today's minimum fee on " + ChainID + " (1 ugnot per 1,000 gas); when the chain raises its gas price, raise `-gas-fee` with it (`gnokey query auth/gasprice`), within the allowance. The collector script does this itself:\n\n")
b.WriteString("```\ngnokey maketx call -pkgpath " + realmPath + " -func Pull -send AMOUNTugnot -master SUPPORTER_ADDRESS " + pullGas + " " + netFlags() + " COLLECTOR_KEY\n```\n\n")
b.WriteString("The repository has a collector script that finds what is due through free queries and pulls it.\n\n")
b.WriteString("## For supporters\n\n")
b.WriteString("Open a plan's page: it shows the two exact commands, with the creator's collector key, the spend limit (price plus " + formatUgnot(FeeAllowance) +
" for fees) and the period filled in. The general form:\n\n")
b.WriteString("```\ngnokey maketx session create -pubkey COLLECTOR_GPUB -allow-paths vm/exec:" + realmPath + " -spend-limit PRICE_PLUS_" + itoa(FeeAllowance) +
"ugnot -spend-period PERIOD_SECONDS -expires-at UNIX_TIME " + callGas + " " + netFlags() + " YOUR_KEY\n")
b.WriteString("gnokey maketx call -pkgpath " + realmPath + " -func Subscribe -args PLAN_ID -args COLLECTOR_ADDRESS -args UNIX_TIME " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
b.WriteString("Use the same UNIX_TIME for both, at most " + itoa(MaxTerm/86400) + " days ahead. The session must allow exactly `vm/exec:" + realmPath +
"` and nothing else, or Pull refuses it. PERIOD_SECONDS is the plan's period, at most " + itoa(MaxPeriod/86400) + " days (the chain's limit on a spend period). " +
"You can support one plan of each creator at a time: all of a creator's plans are collected by one key, and the chain allows one session per key.\n\n")
b.WriteString("### Stop a mandate\n\n")
b.WriteString("Do both, with your own key. Your page (`" + link("payer/YOUR_ADDRESS") + "`) shows them filled in.\n\n")
b.WriteString("```\ngnokey maketx session revoke -pubkey COLLECTOR_GPUB " + callGas + " " + netFlags() + " YOUR_KEY\n")
b.WriteString("gnokey maketx call -pkgpath " + realmPath + " -func Cancel -args YOUR_ADDRESS -args COLLECTOR_ADDRESS " + callGas + " " + netFlags() + " YOUR_KEY\n```\n\n")
b.WriteString("## Checking a supporter (free)\n\n")
b.WriteString("To decide whether to deliver something to a supporter, ask how long their latest payment covers them: `PaidThrough` returns a unix time (0 if they never paid); deliver while now is before it. Paid time stays the supporter's after a cancel or an expiry. ")
b.WriteString("Do not rely on a mandate merely existing: anyone can record one without paying. A realm cannot see a session revoked on chain either, but a revoked supporter stops paying, so `PaidThrough` stops moving and runs out within one period. It runs out at the due time and moves on only when the creator's collector takes the next payment, so allow a grace equal to how often the collector runs (an hour, say) before treating someone as lapsed. The second query shows the chain's view of the session.\n\n")
b.WriteString("```\ngnokey query vm/qeval -data '" + realmPath + ".PaidThrough(address(\"PAYER\"), PLAN_ID)' -remote " + Remote + "\n")
b.WriteString("gnokey query auth/accounts/PAYER/session/COLLECTOR_ADDRESS -remote " + Remote + "\n```\n\n")
b.WriteString("## Rules the realm enforces\n\n")
b.WriteString("- Pull: signed with a session key as a direct call; the session allows exactly this realm; a recorded, active mandate for that payer and key; exactly the price in ugnot; at most once per period (the next one is due one period after the last); not after the expiry.\n")
b.WriteString("- Every other function refuses session keys and coins.\n")
b.WriteString("- The first payment can be pulled as soon as the mandate is recorded (billing in advance). A missed period is never collected later.\n")
b.WriteString("- A wallet can have at most " + strconv.Itoa(MaxSessionsPerWallet) + " sessions, so at most " + strconv.Itoa(MaxSessionsPerWallet) + " mandates at a time.\n")
return b.String()
}
func renderNotFound() string {
return "# Not found\n\nThere is no such page. [Back to Mandate](" + link("") + ")\n"
}
// payingText is the plan headline's count of payments per period. It
// counts payments, not distinct people: a creator paying its own plan from
// a second wallet counts too.
func payingText(p *Plan, now int64) string {
current, previous := p.paidWindows(now)
start := now / p.Period * p.Period
return plural(current, "payment", "payments") + " in the current period (since " + formatTime(start) + "), " +
strconv.Itoa(previous) + " in the one before"
}
// payingCell is the count in tables: paid this period / the one before.
func payingCell(p *Plan, now int64) string {
current, previous := p.paidWindows(now)
return strconv.Itoa(current) + " / " + strconv.Itoa(previous)
}
func infoPayingCell(p PlanInfo) string {
return strconv.Itoa(p.PaidThisPeriod) + " / " + strconv.Itoa(p.PaidLastPeriod)
}
// intParam returns the integer value of key in the query, or def.
func intParam(query, key string, def int) int {
for _, kv := range strings.Split(query, "&") {
if strings.HasPrefix(kv, key+"=") {
n, err := strconv.Atoi(kv[len(key)+1:])
if err == nil && n >= 0 && n <= 1_000_000_000 {
return n
}
}
}
return def
}
// link returns the gnoweb link to a page of this realm.
func link(page string) string {
p := strings.TrimPrefix(realmPath, "gno.land")
if page == "" {
return p
}
return p + ":" + page
}
func pager(page string, n int, more bool) string {
s := ""
if n > 1 {
s += "[Previous page](" + link(page) + "?page=" + strconv.Itoa(n-1) + ") "
}
if more {
s += "[Next page](" + link(page) + "?page=" + strconv.Itoa(n+1) + ")"
}
if s == "" {
return ""
}
return s + "\n\n"
}
func pageParam(query string) int {
for _, kv := range strings.Split(query, "&") {
if strings.HasPrefix(kv, "page=") {
n, err := strconv.Atoi(kv[5:])
if err == nil && n >= 1 && n <= 1_000_000 {
return n
}
}
}
return 1
}
func plural(n int, one, many string) string {
if n == 1 {
return "1 " + one
}
return strconv.Itoa(n) + " " + many
}
func netFlags() string {
return "-broadcast -chainid " + ChainID + " -remote " + Remote
}
func price(amount, period int64) string {
return formatUgnot(amount) + " every " + formatPeriod(period)
}
// formatUgnot shows an amount in GNOT with up to six decimals.
func formatUgnot(n int64) string {
whole := n / 1_000_000
frac := n % 1_000_000
s := itoa(whole)
if frac != 0 {
f := strconv.FormatInt(frac+1_000_000, 10)[1:]
s += "." + strings.TrimRight(f, "0")
}
return s + " GNOT"
}
// formatPeriod shows a number of seconds in the largest exact unit.
func formatPeriod(sec int64) string {
unit := func(n int64, one, many string) string {
if n == 1 {
return one
}
return itoa(n) + " " + many
}
switch {
case sec%604800 == 0:
return unit(sec/604800, "week", "weeks")
case sec%86400 == 0:
return unit(sec/86400, "day", "days")
case sec%3600 == 0:
return unit(sec/3600, "hour", "hours")
case sec%60 == 0:
return unit(sec/60, "minute", "minutes")
}
return unit(sec, "second", "seconds")
}
func formatTime(unix int64) string {
return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04 UTC")
}
func formatTimeOrNever(unix int64) string {
if unix == 0 {
return "never"
}
return formatTime(unix)
}
func short(a address) string {
s := a.String()
if len(s) < 14 {
return s
}
return s[:8] + "…" + s[len(s)-4:]
}
render_test.gno
package mandate
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
const base = "/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate"
func has(t *testing.T, page, want, what string) {
t.Helper()
if !strings.Contains(page, want) {
t.Fatalf("%s: page does not contain %q\n--- page ---\n%s", what, want, page)
}
}
func hasNot(t *testing.T, page, bad, what string) {
t.Helper()
if strings.Contains(page, bad) {
t.Fatalf("%s: page must not contain %q\n--- page ---\n%s", what, bad, page)
}
}
// renders calls Render and fails the test (instead of crashing) on a panic.
func renders(t *testing.T, path string) string {
t.Helper()
var out string
if r := revive(func() { out = Render(path) }); r != nil {
t.Fatalf("Render(%q) panicked: %v", path, r)
}
return out
}
func TestRenderEmpty(cur realm, t *testing.T) {
resetState()
home := renders(t, "")
has(t, home, "# Mandate", "title")
has(t, home, "It is direct debit, not escrow.", "honest limit: not escrow")
has(t, home, "0.1 GNOT", "fee allowance")
has(t, home, "At most 16 mandates per wallet", "16 sessions")
has(t, home, "Revoke any time.", "revoke")
has(t, home, "nothing will ever be deployed there", "sub-path rule")
has(t, home, "| 0 | 0 | 0 | 0 GNOT |", "empty totals")
has(t, home, "No plan has been paid for in its current or last period.", "empty list")
has(t, home, "Built on [gno.land](https://gno.land)", "footer")
has(t, renders(t, "plans"), "No plans on this page.", "empty all-plans page")
for _, p := range []string{
"x", "plan", "plan/", "plan/1", "plan/abc", "plan/-1", "plan/1/2", "payer/", "payer/g1bad", "payee/xyz",
"help/x", "../help", "plan/18446744073709551616",
} {
has(t, renders(t, p), "# Not found", "not found: "+p)
}
has(t, renders(t, "payer/"+payer.String()), "No mandates on this page.", "empty payer")
has(t, renders(t, "payee/"+payee.String()), "No plans from this address.", "empty payee")
}
func TestRenderHelp(cur realm, t *testing.T) {
resetState()
h := renders(t, "help")
net := "-broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443"
has(t, h, "gnokey maketx call -pkgpath gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate -func Offer -args \"TITLE\" -args 1000000 -args 604800 -gas-fee 100000ugnot -gas-wanted 60000000 "+net+" YOUR_KEY", "offer command")
has(t, h, "the joiner included, are refused", "format characters explained")
has(t, h, "-func SetCollectorKey -args GPUB_OF_COLLECTOR_KEY", "collector key command")
has(t, h, "-func Pull -send AMOUNTugnot -master SUPPORTER_ADDRESS -gas-fee 20000ugnot -gas-wanted 20000000 "+net+" COLLECTOR_KEY", "pull command")
has(t, h, "gnokey maketx session create -pubkey COLLECTOR_GPUB -allow-paths vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate -spend-limit PRICE_PLUS_100000ugnot -spend-period PERIOD_SECONDS -expires-at UNIX_TIME", "session command")
has(t, h, "gnokey maketx session revoke -pubkey COLLECTOR_GPUB", "revoke")
has(t, h, "-func Cancel -args YOUR_ADDRESS -args COLLECTOR_ADDRESS", "cancel")
has(t, h, "gnokey query auth/accounts/PAYER/session/COLLECTOR_ADDRESS -remote https://rpc.onyx.testnets.gno.land:443", "session check")
has(t, h, "PaidThrough(address(\"PAYER\"), PLAN_ID)", "qeval check")
hasNot(t, h, "127.0.0.1", "no local node")
hasNot(t, h, "-chainid dev", "no dev chain")
// Every gnokey line that talks to a node names onyx-1 or the Onyx RPC.
for _, line := range strings.Split(h, "\n") {
if strings.HasPrefix(line, "gnokey maketx") {
has(t, line, net, "pinned: "+line)
}
if strings.HasPrefix(line, "gnokey query") {
has(t, line, "-remote https://rpc.onyx.testnets.gno.land:443", "pinned: "+line)
}
}
}
func TestRenderPages(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Weekly coffee", gnot, 7*day)
demo := offer(cur, payee, "Demo plan", gnot, 60)
p, _ := GetPlan(pid)
// No collector key yet: no subscribe commands.
pp := renders(t, "plan/1")
has(t, pp, "# Plan #1: Weekly coffee", "plan title")
has(t, pp, "**1 GNOT every week** to ["+payee.String()+"]("+base+":payee/"+payee.String()+")", "price line")
has(t, pp, "has not published a collector key", "no key")
hasNot(t, pp, "session create", "no command without key")
has(t, renders(t, "plan/2"), "a test plan: the period is under a day", "short period flagged")
hasNot(t, pp, "a test plan", "week plan not flagged")
setKey(cur, payee, gpubA)
subscribe(cur, payer, pid, sessA, now()+30*day)
subscribe(cur, payer2, pid, sessB, now()+30*day)
pullOK(payer, sessA, gnot)
cancel(cur, payer2, payer2, sessB)
pp = renders(t, "plan/1")
exp := itoa(now() + 365*day)
has(t, pp, "gnokey maketx session create -pubkey "+gpubA+" -allow-paths vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate -spend-limit 1100000ugnot -spend-period 604800 -expires-at "+exp+" -gas-fee 100000ugnot -gas-wanted 60000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY", "session create")
has(t, pp, "gnokey maketx call -pkgpath gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate -func Subscribe -args 1 -args "+sessA.String()+" -args "+exp+" -gas-fee 100000ugnot", "subscribe command")
has(t, pp, "at most 1.1 GNOT every week", "cap in words")
has(t, pp, "1 payment in the current period", "paid count")
has(t, pp, "0 active mandates have not paid yet", "unpaid count")
has(t, pp, "| ["+short(payer)+"]("+base+":payer/"+payer.String()+") |", "active supporter listed")
hasNot(t, pp, short(payer2), "cancelled supporter not listed")
has(t, pp, "1 payment, 1 GNOT in total", "plan totals")
uassert.Equal(t, uint64(2), demo)
_ = p
pr := renders(t, "payer/"+payer.String())
has(t, pr, "## Mandate 1: [plan #1 Weekly coffee]("+base+":plan/1)", "mandate heading")
has(t, pr, "Status here: **active**", "status")
has(t, pr, "gnokey maketx session revoke -pubkey "+gpubA+" -gas-fee 100000ugnot -gas-wanted 60000000 -broadcast -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY", "revoke command")
has(t, pr, "-func Cancel -args "+payer.String()+" -args "+sessA.String()+" -gas-fee", "cancel command")
has(t, pr, "Payments: 1, 1 GNOT in total", "payer totals")
// Unknown session public key: show how to find it.
setKey(cur, payee, gpubB)
subscribe(cur, payer2, demo, sessA, now()+day)
p2 := renders(t, "payer/"+payer2.String())
has(t, p2, "Status here: **cancelled**", "cancelled mandate")
has(t, p2, "gnokey query auth/accounts/"+payer2.String()+"/sessions -remote https://rpc.onyx.testnets.gno.land:443", "list sessions")
pe := renders(t, "payee/"+payee.String())
has(t, pe, "| 2 | 1 | 1 GNOT |", "payee totals")
has(t, pe, "Collector key: `"+sessB.String()+"` (`"+gpubB+"`)", "collector key shown")
has(t, pe, "| [#1 Weekly coffee]("+base+":plan/1) | 1 GNOT every week | 1 / 0 | 1 |", "plan row")
home := renders(t, "")
has(t, home, "| 2 | 3 | 1 | 1 GNOT |", "home totals")
has(t, renders(t, "plans"), "| [#2 Demo plan]("+base+":plan/2) | 1 GNOT every minute |", "all plans list")
}
// Titles cannot inject Markdown, HTML, links, mentions or math anywhere they
// are shown (plan page heading, payer heading, home and payee tables).
func TestRenderInjection(cur realm, t *testing.T) {
resetState()
setKey(cur, payee, gpubA)
evil := []string{
"# heading",
"[click](https://evil.example)",
"",
"<script>alert(1)</script>",
"a | b | c",
"$x^2$ and $$y$$",
"@moul look",
"g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 leading address",
"pay g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 now",
"`code` and ```fence",
"*bold* _it_ ~~s~~",
"> quote",
"<https://auto.link>",
"& A",
}
for _, title := range evil {
pid := offer(cur, payee, title, gnot, day)
subscribe(cur, payer, pid, sessA, now()+day)
cancel(cur, payer, payer, sessA)
pages := map[string]string{
"plan": renders(t, "plan/"+utoa(pid)),
"payer": renders(t, "payer/"+payer.String()),
"payee": renders(t, "payee/"+payee.String()),
"home": renders(t, ""),
"plans": renders(t, "plans"),
}
for name, pg := range pages {
what := name + " " + title
hasNot(t, pg, "](https://evil", what)
hasNot(t, pg, "<script>", what)
hasNot(t, pg, "\n# heading", what)
hasNot(t, strings.ReplaceAll(pg, `\$`, ""), "$", what) // every $ escaped
hasNot(t, strings.ReplaceAll(pg, `\@`, ""), "@", what) // every @ escaped
hasNot(t, pg, " g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5", what)
hasNot(t, stripKnown(pg), "<", what) // no raw "<": no HTML, no autolink
hasNot(t, pg, "& A", what)
if name == "plans" || name == "payee" { // tables: a "|" must not split the cell
hasNot(t, pg, "| b |", what)
}
}
has(t, pages["plan"], ": "+esc(title)+"\n", "escaped heading")
}
uassert.Equal(t, "\\# heading", esc("# heading"))
uassert.Equal(t, "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5", esc("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"))
uassert.Equal(t, "a g1x", gnowebSafe("a g1x"))
uassert.Equal(t, `\$1`, gnowebSafe("$1"))
uassert.Equal(t, `\@x`, gnowebSafe("@x"))
}
// stripKnown removes escaped "<" and the realm's own placeholders in code
// spans, so any "<" left would come from a title.
func stripKnown(pg string) string {
for _, k := range []string{`\<`, "`/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate:payer/<your address>`", "`gnokey maketx session revoke -pubkey <its gpub1 key> ... YOUR_KEY`"} {
pg = strings.ReplaceAll(pg, k, "")
}
return pg
}
func TestRenderPaging(cur realm, t *testing.T) {
resetState()
setKey(cur, payee, gpubA)
for i := 0; i < 21; i++ {
offer(cur, payee, "Plan "+itoa(int64(i+1)), gnot, day)
}
for i := 0; i < 21; i++ {
who := testutils.TestAddress("md_r" + itoa(int64(i)))
subscribe(cur, who, 1, sessA, now()+day)
}
// all subscribers pay once; plan 1's supporters then span two pages of 20
for i := 0; i < 21; i++ {
pullOK(testutils.TestAddress("md_r"+itoa(int64(i))), sessA, gnot)
}
all := renders(t, "plans")
has(t, all, "[Next page]("+base+":plans?page=2)", "all plans next")
h2 := renders(t, "plans?page=2")
has(t, h2, "[Previous page]("+base+":plans?page=1)", "all plans previous")
has(t, h2, "[#1 Plan 1]("+base+":plan/1)", "oldest on page 2")
has(t, renders(t, ""), "[#1 Plan 1]("+base+":plan/1) | 1 GNOT every day |", "paid plan on home")
plan := renders(t, "plan/1")
has(t, plan, "21 payments in the current period", "count")
has(t, plan, "| ["+short(testutils.TestAddress("md_r20"))+"]", "newest first")
has(t, plan, "[More supporters]("+base+":plan/1?from=0)", "plan cursor")
has(t, renders(t, "plan/1?from=0"), "| ["+short(testutils.TestAddress("md_r0"))+"]", "oldest on the next page")
// PayingSupporters pages the same way: 20 newest, then the oldest one
ps, next := PayingSupporters(1, -1)
uassert.Equal(t, PageSize, len(ps))
uassert.Equal(t, testutils.TestAddress("md_r20").String(), ps[0].Payer.String())
uassert.Equal(t, 0, next)
ps, next = PayingSupporters(1, next)
uassert.Equal(t, 1, len(ps))
uassert.Equal(t, testutils.TestAddress("md_r0").String(), ps[0].Payer.String())
uassert.Equal(t, -1, next)
has(t, renders(t, "payee/"+payee.String()), "[Next page]("+base+":payee/"+payee.String()+"?page=2)", "payee next")
}
store.gno
package mandate
import (
"chain"
"strconv"
)
// fanout is the number of entries per chunk, and of chunks per super-chunk.
const fanout = 32
// fixedList is an append-only list of strings of one fixed width, in two
// levels of chunks. It holds values, never pointers to shared objects (on
// chain, rewriting an array costs about 0.37M gas for every pointer to a
// shared object it holds; docs/notes.md), and no array in it grows with the
// list's length except supers, by one entry per fanout*fanout appends:
// - tail: the newest N % fanout entries, inside the owner object;
// - when tail is full it becomes a chunk, appended to the last
// super-chunk (at most fanout chunks each);
// - supers: the list of super-chunks.
//
// So an append rewrites the owner and its tail; every fanout appends it also
// creates a chunk and rewrites one super-chunk (at most fanout pointers to
// objects that only it holds); every fanout*fanout appends it rewrites
// supers. set replaces an entry in place with one of the same width, so it
// never changes the storage size. Appends happen only in transactions signed
// with someone's own key (Subscribe, Offer), never under a session budget.
type fixedList struct {
N int
tail []string // the newest N % fanout entries
supers []*superChunk // full chunks, fanout per super-chunk, oldest first
}
type superChunk struct {
chunks []*strChunk
}
type strChunk struct {
items []string
}
func (l *fixedList) add(s string) {
l.tail = append(l.tail, s)
l.N++
if len(l.tail) < fanout {
return
}
c := &strChunk{items: l.tail}
l.tail = nil
if n := len(l.supers); n == 0 || len(l.supers[n-1].chunks) == fanout {
l.supers = append(l.supers, &superChunk{chunks: []*strChunk{c}})
return
}
sc := l.supers[len(l.supers)-1]
sc.chunks = append(sc.chunks, c)
}
// at returns entry i (0 = oldest).
func (l *fixedList) at(i int) string {
c := i / fanout
if c < l.N/fanout {
return l.supers[c/fanout].chunks[c%fanout].items[i%fanout]
}
return l.tail[i%fanout]
}
// set replaces entry i with s, which must have the same width.
func (l *fixedList) set(i int, s string) {
c := i / fanout
if c < l.N/fanout {
l.supers[c/fanout].chunks[c%fanout].items[i%fanout] = s
return
}
l.tail[i%fanout] = s
}
// Supporter entries: the payer's 40-character address, the mandate id
// padded to 10 digits, and one status character. Pull flips '0' to '1' at
// a mandate's first payment and Cancel sets 'x', both in place.
const (
statusUnpaid = '0'
statusPaid = '1'
statusCancelled = 'x'
entryWidth = 40 + 10 + 1
)
// entry is a decoded supporter entry.
type entry struct {
Payer address
ID uint64 // mandate id
Status byte
}
func encodeEntry(payer address, id uint64, status byte) string {
return payer.String() + pad(id) + string(status)
}
func decodeEntry(s string) entry {
id, _ := strconv.ParseUint(s[40:50], 10, 64)
return entry{Payer: address(s[:40]), ID: id, Status: s[50]}
}
// setStatus rewrites the status character of entry i (same width).
func (l *fixedList) setStatus(i int, status byte) {
s := l.at(i)
l.set(i, s[:50]+string(status))
}
// activeMandate returns the mandate an entry names if it is still in its
// payer's active list (cancelled and replaced ones are not), or nil. It may
// have expired: callers check isActive.
func activeMandate(e entry) *Mandate {
if pr := payerOf(e.Payer); pr != nil {
for _, r := range pr.Active {
if r.ID == e.ID {
return r.M
}
}
}
return nil
}
// MaxActivePerPayer is how many active mandates one payer may hold: the
// chain allows 16 sessions per account (tm2 std.MaxSessionsPerAccount), and
// each active mandate needs its own session key.
const MaxActivePerPayer = MaxSessionsPerWallet
// Payer holds one payer's own lookups and nothing of anyone else's, so no
// address can make another payer's Pull, Subscribe or Cancel read or write
// more than the payer tree's depth.
// - Active: the payer's current mandates, at most MaxActivePerPayer that
// are not expired. Cancel removes an entry at once; an expired entry is
// removed at the payer's next Subscribe. Each entry carries the session
// address and plan id inline, so finding a mandate reads one small array
// and loads only the mandate found.
// - Head: the payer's newest mandate; older ones follow through
// prevOfPayer (history, walked only by free reads).
// - Credits: time the payer has paid for on a plan where they no longer
// have an active mandate (cancelled by either side, or expired and
// pruned), at most MaxCreditsPerPayer, each still in the future. A new
// mandate for that plan starts when the credit ends, so paid time is
// not lost or charged twice, unless 16 credits are already held (see
// MaxCreditsPerPayer for who can then lose what).
type Payer struct {
Active []activeRef
Head *Mandate
Credits []credit
}
// credit is paid time kept for a plan: the payer is covered until Until.
type credit struct {
PlanID uint64
Until int64
}
// MaxCreditsPerPayer bounds a payer's kept credits: 16 plans left while
// each is still paid ahead. At the bound, the payer's own Cancel or expiry
// lets the credit ending soonest give way to a later one (that plan's time
// is lost); a payee's Cancel never evicts: its new credit is not kept.
const MaxCreditsPerPayer = 16
type activeRef struct {
Session address
PlanID uint64
ID uint64 // mandate id, so a supporter entry resolves without loading mandates
M *Mandate
}
// payerOf returns a copy of the payer's record, or nil. Records are stored
// by value (no heap item, about 400 bytes less per payer); after changing
// one, write it back with save.
func payerOf(a address) *Payer {
v := payers.Get(a.String())
if v == nil {
return nil
}
pr := v.(Payer)
return &pr
}
func (pr *Payer) save(a address) { payers.Set(a.String(), *pr) }
// activeBySession returns the payer's active-list mandate for this session
// key (it may have expired but not been pruned yet), or nil.
func activeBySession(payer, sess address) *Mandate {
if pr := payerOf(payer); pr != nil {
for _, r := range pr.Active {
if r.Session == sess {
return r.M
}
}
}
return nil
}
// activeByPlan returns the payer's active-list mandate for the plan, or nil.
func activeByPlan(payer address, planID uint64) *Mandate {
if pr := payerOf(payer); pr != nil {
for _, r := range pr.Active {
if r.PlanID == planID {
return r.M
}
}
}
return nil
}
// removeActive drops m's entry from the payer's active list.
func (pr *Payer) removeActive(m *Mandate) {
out := make([]activeRef, 0, len(pr.Active))
for _, r := range pr.Active {
if r.M != m {
out = append(out, r)
}
}
pr.Active = out
}
// pruneExpired drops expired entries from the active list (payer is the
// record's owner, for events). The paid time of an expired mandate for
// planID, the plan being subscribed to, is returned directly, so nothing in
// the same prune can evict it; every other expired mandate's paid time is
// kept as a credit for its plan.
func (pr *Payer) pruneExpired(payer address, planID uint64, now int64) int64 {
keep := 0
for _, r := range pr.Active {
if r.M.isActive(now) {
keep++
}
}
if keep == len(pr.Active) {
return 0
}
var own int64
out := make([]activeRef, 0, keep)
for _, r := range pr.Active {
if r.M.isActive(now) {
out = append(out, r)
continue
}
var kept int64
if r.PlanID == planID {
if t := r.M.paidThrough(); t > now {
own, kept = t, t
}
} else {
kept = pr.keepCredit(payer, r.PlanID, r.M.paidThrough(), now, true)
}
chain.Emit("MandatePruned",
"mandate", utoa(r.ID),
"plan", utoa(r.PlanID),
"payer", payer.String(),
"kept", itoa(kept),
)
}
pr.Active = out
return own
}
// pruneCredits drops credits that have run out.
func (pr *Payer) pruneCredits(now int64) {
keep := 0
for _, c := range pr.Credits {
if c.Until > now {
keep++
}
}
if keep == len(pr.Credits) {
return
}
out := make([]credit, 0, keep)
for _, c := range pr.Credits {
if c.Until > now {
out = append(out, c)
}
}
pr.Credits = out
}
// keepCredit records that the payer is paid on the plan until `until`
// (nothing if that is not in the future). One credit per plan, the later
// time wins. At MaxCreditsPerPayer: with evict (the payer's own Cancel, or
// the expiry prune at the payer's own Subscribe), the credit ending soonest
// gives way if this one ends later; without evict (a payee's Cancel), this
// one is not kept, so no third party can remove a credit the payer holds.
//
// It returns the time kept (0 if none) and emits CreditDropped for a credit
// it pushes out.
func (pr *Payer) keepCredit(payer address, planID uint64, until, now int64, evict bool) int64 {
if until <= now {
return 0
}
pr.pruneCredits(now)
// A plan has a credit only while the payer has no active mandate for it
// (Subscribe uses it up), so this is a guard, not a path taken today.
for i := range pr.Credits {
if pr.Credits[i].PlanID == planID {
if until > pr.Credits[i].Until {
pr.Credits[i] = credit{PlanID: planID, Until: until}
}
return pr.Credits[i].Until
}
}
if len(pr.Credits) < MaxCreditsPerPayer {
pr.Credits = append(pr.Credits, credit{PlanID: planID, Until: until})
return until
}
if !evict {
return 0
}
soonest := 0
for i := range pr.Credits {
if pr.Credits[i].Until < pr.Credits[soonest].Until {
soonest = i
}
}
if until <= pr.Credits[soonest].Until {
return 0
}
chain.Emit("CreditDropped",
"payer", payer.String(),
"plan", utoa(pr.Credits[soonest].PlanID),
"until", itoa(pr.Credits[soonest].Until),
)
pr.Credits[soonest] = credit{PlanID: planID, Until: until}
return until
}
// creditFor returns until when a kept credit covers the payer on the plan,
// or 0. For reads; it changes nothing.
func (pr *Payer) creditFor(planID uint64, now int64) int64 {
for _, c := range pr.Credits {
if c.PlanID == planID && c.Until > now {
return c.Until
}
}
return 0
}
// takeCredit removes the plan's credit and returns until when it covered
// the payer, or 0 if there was none still in the future.
func (pr *Payer) takeCredit(planID uint64, now int64) int64 {
pr.pruneCredits(now)
for i, c := range pr.Credits {
if c.PlanID == planID {
out := make([]credit, 0, len(pr.Credits)-1)
out = append(out, pr.Credits[:i]...)
pr.Credits = append(out, pr.Credits[i+1:]...)
return c.Until
}
}
return 0
}
// latestBySession returns the payer's newest mandate for this session key,
// active or not, walking the history when it is no longer active. For free
// reads only.
func latestBySession(payer, sess address) *Mandate {
if m := activeBySession(payer, sess); m != nil {
return m
}
if pr := payerOf(payer); pr != nil {
for m := pr.Head; m != nil; m = m.prevOfPayer {
if m.Session == sess {
return m
}
}
}
return nil
}
// payerHead returns the payer's newest mandate.
func payerHead(payer address) *Mandate {
if pr := payerOf(payer); pr != nil {
return pr.Head
}
return nil
}
store_test.gno
package mandate
import (
"chain"
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// fixedList keeps the newest entries in tail, full chunks of fanout, and
// fanout chunks per super-chunk; every index maps to the right entry across
// the boundaries, and set rewrites in place.
func TestFixedList(t *testing.T) {
var l fixedList
n := fanout*fanout + 3*fanout + 5 // past the first super-chunk
for i := 0; i < n; i++ {
l.add(encodeEntry(payer, uint64(i), statusUnpaid))
uassert.Equal(t, i+1, l.N)
for _, j := range []int{0, i / 2, i} {
uassert.Equal(t, uint64(j), decodeEntry(l.at(j)).ID)
}
uassert.Equal(t, (i+1)%fanout, len(l.tail))
full := (i + 1) / fanout
uassert.Equal(t, (full+fanout-1)/fanout, len(l.supers))
}
uassert.Equal(t, fanout, len(l.supers[0].chunks))
uassert.Equal(t, 3, len(l.supers[1].chunks))
for _, j := range []int{0, 31, 32, 33, fanout*fanout - 1, fanout * fanout, n - 1} {
l.setStatus(j, statusPaid)
e := decodeEntry(l.at(j))
uassert.Equal(t, uint64(j), e.ID)
uassert.True(t, e.Status == statusPaid)
uassert.Equal(t, entryWidth, len(l.at(j)))
uassert.Equal(t, payer.String(), e.Payer.String())
}
// No preallocation: a slot costs storage even when empty.
var small fixedList
small.add("x")
uassert.Equal(t, 1, cap(small.tail))
}
// Supporter lists keep their order across chunks.
func TestLongLists(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, day)
n := 2*fanout + 3
for i := 0; i < n; i++ {
subscribe(cur, testutils.TestAddress("md_l"+itoa(int64(i))), pid, sessA, now()+day)
}
uassert.Equal(t, n, planOf(pid).Supporters.N)
seen := 0
for page := 1; ; page++ {
list := SupportersOf(pid, page)
for _, m := range list {
uassert.Equal(t, uint64(seen+1), m.ID)
uassert.Equal(t, testutils.TestAddress("md_l"+itoa(int64(seen))).String(), m.Payer.String())
seen++
}
if len(list) < PageSize {
break
}
}
uassert.Equal(t, n, seen)
}
// A payer's history is newest first and paged; lookups by session and by
// plan return the latest mandate.
func TestPayerHistory(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, day)
pid2 := offer(cur, payee, "Plan 2", gnot, day)
var ids []uint64
for i := 0; i < 25; i++ {
ids = append(ids, subscribe(cur, payer, pid, sessA, now()+day))
cancel(cur, payer, payer, sessA)
}
last := subscribe(cur, payer, pid2, sessA, now()+day)
p1 := MandatesOf(payer, 1)
p2 := MandatesOf(payer, 2)
uassert.Equal(t, PageSize, len(p1))
uassert.Equal(t, 6, len(p2))
uassert.Equal(t, 0, len(MandatesOf(payer, 3)))
uassert.Equal(t, last, p1[0].ID)
uassert.Equal(t, ids[24], p1[1].ID)
uassert.Equal(t, ids[0], p2[5].ID)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, last, m.ID)
uassert.True(t, HasMandate(payer, pid2))
uassert.False(t, HasMandate(payer, pid))
pl, _ := GetPlan(pid)
uassert.Equal(t, 25, pl.Mandates)
uassert.Equal(t, 25, pl.Cancelled)
// The payer page pages the same way.
has(t, renders(t, "payer/"+payer.String()), "## Mandate "+utoa(last)+":", "newest first")
has(t, renders(t, "payer/"+payer.String()+"?page=2"), "## Mandate "+utoa(ids[0])+":", "oldest on page 2")
}
// Free reads never create storage: looking up an unknown payer creates no
// payer record.
func TestReadsDoNotWrite(cur realm, t *testing.T) {
resetState()
MandateOf(payer, sessA)
HasMandate(payer, 1)
NextPullAt(payer, 1)
MandatesOf(payer, 1)
renders(t, "payer/"+payer.String())
uassert.Equal(t, 0, payers.Size())
}
// Paid, LastPullAt and SessionPubKey are derived, not stored.
func TestDerivedFields(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", 2*gnot, MinPeriod)
setKey(cur, payee, gpubA)
subscribe(cur, payer, pid, sessA, now()+day)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, int64(0), m.LastPullAt)
uassert.Equal(t, int64(0), m.Paid)
uassert.Equal(t, gpubA, m.SessionPubKey)
t0 := now()
pullOK(payer, sessA, 2*gnot)
testing.SkipHeights(13)
t1 := now()
pullOK(payer, sessA, 2*gnot)
m, _ = MandateOf(payer, sessA)
uassert.Equal(t, t1, m.LastPullAt)
uassert.True(t, t1 > t0)
uassert.Equal(t, int64(2), m.Pulls)
uassert.Equal(t, 4*gnot, m.Paid)
p, _ := GetPlan(pid)
uassert.Equal(t, 4*gnot, p.Paid)
uassert.Equal(t, t1, p.LastPullAt)
// The payee moves to another collector key: the realm no longer knows
// this session's public key, and the payer page says how to find it.
setKey(cur, payee, gpubB)
m, _ = MandateOf(payer, sessA)
uassert.Equal(t, "", m.SessionPubKey)
has(t, renders(t, "payer/"+payer.String()), "/sessions -remote", "lookup command")
}
// Supporters are listed only once they have paid. Junk mandates that never
// pay are skipped by their status character, without a lookup, so they
// cannot hide a real supporter; payment counts come from the plan's own
// counters and junk cannot move them.
func TestPayingSupporters(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Real plan", gnot, MinPeriod)
offer(cur, payee, "Nobody pays", gnot, MinPeriod)
real := testutils.TestAddress("md_real")
subscribe(cur, real, pid, sessA, now()+day)
pullOK(real, sessA, gnot)
// 2*ScanLimit junk mandates after the real one, none of them ever pays
for i := 0; i < 2*ScanLimit; i++ {
subscribe(cur, testutils.TestAddress("md_j"+itoa(int64(i))), pid, sessA, now()+day)
}
p, _ := GetPlan(pid)
uassert.Equal(t, 1, p.PaidThisPeriod)
// the collector scan resolves at most ScanLimit entries per call and says where to go on
scan := CollectorScan(pid, sessA, 0)
uassert.True(t, strings.HasSuffix(scan, "\nnext 200\n"), "scan cursor")
uassert.Equal(t, ScanLimit+1, len(strings.Split(strings.TrimSuffix(scan, "\n"), "\n")))
uassert.True(t, strings.HasSuffix(CollectorScan(pid, sessA, 400), "end\n"))
uassert.Equal(t, "end\n", CollectorScan(pid, sessA, 1<<62))
uassert.Equal(t, "end\n", CollectorScan(pid, sessA, int(^uint(0)>>1))) // clamped: from+ScanLimit would overflow
page := renders(t, "plan/"+utoa(pid))
has(t, page, "1 payment in the current period", "count")
has(t, page, "200 active mandates have not paid yet (not listed), among the latest 200", "unpaid count, bounded")
hasNot(t, page, short(testutils.TestAddress("md_j0")), "junk not listed")
has(t, page, "| ["+short(real)+"]", "real supporter found past 400 junk entries in one walk")
hasNot(t, page, "More supporters", "nothing more to walk")
// a cancel takes the supporter off the list; the payment stays in the counts
cancel(cur, real, real, sessA)
p, _ = GetPlan(pid)
uassert.Equal(t, 1, p.PaidThisPeriod)
uassert.Equal(t, 1, p.Cancelled)
list, _ := payingFrom(planOf(pid), -1, now())
uassert.Equal(t, 0, len(list))
// the home page lists only plans somebody paid for in this or the last period
home := renders(t, "")
has(t, home, "[#"+utoa(pid)+" Real plan]("+base+":plan/"+utoa(pid)+")", "paid plan on home")
hasNot(t, home, "Nobody pays", "unpaid plan not on home")
has(t, renders(t, "plans"), "Nobody pays", "all plans page")
// two periods without payments: off the home page
testing.SkipHeights(25)
hasNot(t, renders(t, ""), "Real plan]", "no payment for two periods")
}
// The supporter list walks at most WalkLimit entries per page, and the
// next page continues where it stopped: a real supporter behind more than
// WalkLimit never-paid entries is on a later page, never lost.
func TestPayingWalkBounded(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
real := testutils.TestAddress("md_real")
subscribe(cur, real, pid, sessA, now()+day)
pullOK(real, sessA, gnot)
for i := 0; i < WalkLimit+10; i++ {
subscribe(cur, testutils.TestAddress("md_w"+itoa(int64(i))), pid, sessA, now()+day)
}
p := planOf(pid)
list, next := payingFrom(p, -1, now())
uassert.Equal(t, 0, len(list), "first walk stops after WalkLimit entries")
uassert.Equal(t, p.Supporters.N-1-WalkLimit, next, "cursor where the walk stopped")
list, next = payingFrom(p, next, now())
uassert.Equal(t, 1, len(list), "found on the next walk")
uassert.Equal(t, real.String(), list[0].Payer.String())
uassert.Equal(t, -1, next)
}
// The payment counters read against the current time: a payment counts in
// its own period window, then in "the one before", then not at all.
func TestPaymentWindows(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
toNextWindow := func() {
need := (now()/MinPeriod+1)*MinPeriod - now()
testing.SkipHeights((need + 4) / 5)
}
windows := func(cur, prev int, what string) {
p, _ := GetPlan(pid)
uassert.Equal(t, cur, p.PaidThisPeriod, what+": this period")
uassert.Equal(t, prev, p.PaidLastPeriod, what+": last period")
}
toNextWindow()
subscribe(cur, payer, pid, sessA, now()+day)
subscribe(cur, payer2, pid, sessB, now()+day)
windows(0, 0, "nothing paid")
pullOK(payer, sessA, gnot)
pullOK(payer2, sessB, gnot)
windows(2, 0, "two payments")
toNextWindow()
windows(0, 2, "next window, no payment yet")
testing.SkipHeights(1) // a full period after the first payment
pullOK(payer, sessA, gnot)
windows(1, 2, "one payment in the next window")
toNextWindow()
toNextWindow()
windows(0, 0, "two windows later")
pullOK(payer, sessA, gnot)
windows(1, 0, "after a gap")
}
// Churn cannot hide a plan someone keeps paying for (audit LOW-1): one
// steady supporter, and 300 others who subscribe, pay once and cancel.
func TestHomeSurvivesChurn(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Steady", gnot, MinPeriod)
steady := testutils.TestAddress("md_steady")
subscribe(cur, steady, pid, sessA, now()+day)
for round := 0; round < 3; round++ {
pullOK(steady, sessA, gnot)
for i := 0; i < 100; i++ {
who := testutils.TestAddress("md_c" + itoa(int64(round*100+i)))
subscribe(cur, who, pid, sessB, now()+day)
pullOK(who, sessB, gnot)
cancel(cur, who, who, sessB)
}
has(t, renders(t, ""), "[#"+utoa(pid)+" Steady]("+base+":plan/"+utoa(pid)+")", "steady plan stays on home")
list, _ := payingFrom(planOf(pid), -1, now())
uassert.Equal(t, 1, len(list), "the steady supporter is listed")
uassert.Equal(t, steady.String(), list[0].Payer.String())
testing.SkipHeights(13)
}
}
// Offer spam cannot push paid plans off the home page: it walks ScanLimit
// plans and links onwards.
func TestOfferSpam(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Real plan", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day)
pullOK(payer, sessA, gnot)
for i := 0; i < ScanLimit+5; i++ {
offer(cur, stranger, "spam "+itoa(int64(i)), MinAmount, MinPeriod)
}
home := renders(t, "")
hasNot(t, home, "spam", "no spam on home")
has(t, home, "No plan has been paid for in its current or last period among those looked at.", "first window empty")
has(t, home, "[More plans with supporters]("+base+"?from=5)", "cursor")
has(t, renders(t, "?from=5"), " Real plan]", "paid plan reached")
}
// At most MaxActivePerPayer active mandates; a cancelled or expired one
// frees its slot.
func TestActiveCap(cur realm, t *testing.T) {
resetState()
var pids []uint64
for i := 0; i < MaxActivePerPayer+2; i++ {
pids = append(pids, offer(cur, payee, "Plan "+itoa(int64(i)), gnot, MinPeriod))
}
sess := func(i int) address { return testutils.TestAddress("md_cap" + itoa(int64(i))) }
for i := 0; i < MaxActivePerPayer; i++ {
subscribe(cur, payer, pids[i], sess(i), now()+day)
}
uassert.Equal(t, MaxActivePerPayer, len(payerOf(payer).Active))
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payer))
fails(t, cur, "at most 16 active mandates", func() { Subscribe(cross(cur), pids[16], sess(16), now()+day) }, "17th mandate")
// a cancel frees a slot
cancel(cur, payer, payer, sess(0))
uassert.Equal(t, MaxActivePerPayer-1, len(payerOf(payer).Active))
subscribe(cur, payer, pids[16], sess(16), now()+day)
// an expired mandate frees its slot at the next Subscribe
resetState()
pids = nil
for i := 0; i < MaxActivePerPayer+1; i++ {
pids = append(pids, offer(cur, payee, "Plan "+itoa(int64(i)), gnot, MinPeriod))
}
subscribe(cur, payer, pids[0], sess(0), now()+120)
for i := 1; i < MaxActivePerPayer; i++ {
subscribe(cur, payer, pids[i], sess(i), now()+day)
}
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payer))
fails(t, cur, "at most 16 active", func() { Subscribe(cross(cur), pids[16], sess(16), now()+day) }, "17th before expiry")
testing.SkipHeights(24) // 120 s: mandate 1 expires
subscribe(cur, payer, pids[16], sess(16), now()+day)
uassert.Equal(t, MaxActivePerPayer, len(payerOf(payer).Active))
for _, r := range payerOf(payer).Active {
uassert.True(t, r.Session != sess(0), "expired entry pruned")
}
}
// What the reads return for cancelled and expired mandates (documented in
// docs/design.md): MandateOf still returns the newest mandate for that payer
// and session with its status; IsActive is false; NextPullAt is 0; Pull and
// Cancel find no active mandate.
func TestInactiveReads(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
pid2 := offer(cur, payee, "Plan 2", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day)
subscribe(cur, payer, pid2, sessB, now()+120)
cancel(cur, payer, payer, sessA)
m, ok := MandateOf(payer, sessA)
uassert.True(t, ok)
uassert.Equal(t, "cancelled", m.Status)
uassert.False(t, HasMandate(payer, pid))
uassert.Equal(t, int64(0), NextPullAt(payer, pid))
panicsLocal(t, cur, "no active mandate", func() { checkPull(true, sessA, []string{selfPaths}, payer, ugnot(gnot), now()) }, "pull cancelled")
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payer))
fails(t, cur, "no active mandate", func() { Cancel(cross(cur), payer, sessA) }, "cancel twice")
uassert.Equal(t, 1, len(payerOf(payer).Active)) // the cancel removed its entry
// expired: entry kept until the next Subscribe; reads say expired
testing.SkipHeights(24)
m, _ = MandateOf(payer, sessB)
uassert.Equal(t, "expired", m.Status)
uassert.Equal(t, 0, len(SupportersOf(pid2, 1))) // only active mandates are listed
uassert.Equal(t, 0, len(SupportersOf(pid, 1))) // the cancelled one neither
uassert.False(t, HasMandate(payer, pid2))
uassert.Equal(t, int64(0), NextPullAt(payer, pid2))
panicsLocal(t, cur, "mandate: expired", func() { checkPull(true, sessB, []string{selfPaths}, payer, ugnot(gnot), now()) }, "pull expired")
subscribe(cur, payer, pid, sessA, now()+day) // prunes the expired entry
uassert.Equal(t, 1, len(payerOf(payer).Active))
m, _ = MandateOf(payer, sessB) // still found through the history
uassert.Equal(t, "expired", m.Status)
uassert.Equal(t, 3, len(MandatesOf(payer, 1)))
}
// Nothing another address does changes a payer's own record: an attacker's
// subscribe/cancel loop leaves the victim's Payer exactly as it was.
func TestPayerIsolation(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
pid2 := offer(cur, payee, "Plan 2", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day)
victim := func() string {
pr := payerOf(payer)
s := utoa(pr.Head.ID) + ":"
for _, r := range pr.Active {
s += r.Session.String() + "/" + utoa(r.PlanID) + "=" + utoa(r.M.ID) + ","
}
return s
}
before := victim()
for i := 0; i < 40; i++ {
s := testutils.TestAddress("md_junk" + itoa(int64(i)))
subscribe(cur, stranger, pid2, s, now()+day)
cancel(cur, stranger, stranger, s)
}
uassert.Equal(t, before, victim())
uassert.Equal(t, 0, len(payerOf(stranger).Active)) // cancels left nothing behind
uassert.Equal(t, 40, len(MandatesOf(stranger, 1))+len(MandatesOf(stranger, 2)))
}
// Counts true at read time. "Supporters" (listed) are mandates that have
// paid and are active now: an expired or cancelled one is not, and is not
// "not yet paid" either; a payer who comes back counts once. The per-period
// payment counts are history (who paid in this period window and the one
// before) and are checked against the tests' own log of payments. Every view
// must agree: GetPlan, the plan headline, the supporter list, SupportersOf,
// the home page and the payee table.
func checkCounts(t *testing.T, pid uint64, listed, unpaid int, what string) {
t.Helper()
p, _ := GetPlan(pid)
cur, prev := expectedWindows(pid, p.Period)
uassert.Equal(t, cur, p.PaidThisPeriod, what+": GetPlan this period")
uassert.Equal(t, prev, p.PaidLastPeriod, what+": GetPlan last period")
uassert.Equal(t, now()/p.Period*p.Period, p.PeriodStart, what+": period start")
pp := renders(t, "plan/"+utoa(pid))
has(t, pp, plural(cur, "payment", "payments")+" in the current period", what+": headline")
has(t, pp, ", "+itoa(int64(prev))+" in the one before", what+": headline previous")
list, _ := payingFrom(planOf(pid), -1, now())
uassert.Equal(t, listed, len(list), what+": listed")
ps, _ := PayingSupporters(pid, -1)
uassert.Equal(t, listed, len(ps), what+": PayingSupporters")
c1, c2, un, exact := PlanCounts(pid)
uassert.Equal(t, cur, c1, what+": PlanCounts this period")
uassert.Equal(t, prev, c2, what+": PlanCounts last period")
uassert.Equal(t, unpaid, un, what+": PlanCounts unpaid")
uassert.True(t, exact, what+": PlanCounts exact")
active := len(SupportersOf(pid, 1))
uassert.Equal(t, listed+unpaid, active, what+": SupportersOf")
if unpaid == 1 {
has(t, pp, "1 active mandate has not paid yet", what+": unpaid")
} else {
has(t, pp, itoa(int64(unpaid))+" active mandates have not paid yet", what+": unpaid")
}
home := renders(t, "")
pe := renders(t, "payee/"+payee.String())
row := "| [#" + utoa(pid) + " Plan](" + base + ":plan/" + utoa(pid) + ") | 1 GNOT every minute | "
if cur+prev > 0 {
has(t, home, "[#"+utoa(pid)+" Plan]("+base+":plan/"+utoa(pid)+")", what+": on home")
} else {
hasNot(t, home, "[#"+utoa(pid)+" Plan]("+base+":plan/"+utoa(pid)+")", what+": not on home")
}
has(t, pe, row+itoa(int64(cur))+" / "+itoa(int64(prev))+" |", what+": payee table")
}
func TestExpirySequences(cur realm, t *testing.T) {
period := MinPeriod
short := func() int64 { return now() + 2*period } // expires in 2 minutes
expire := func() { testing.SkipHeights(25) } // 125 s
// 1. pay, expire: not a supporter any more, not "unpaid" either
resetState()
pid := offer(cur, payee, "Plan", gnot, period)
subscribe(cur, payer, pid, sessA, short())
checkCounts(t, pid, 0, 1, "subscribed, not paid")
pullOK(payer, sessA, gnot)
checkCounts(t, pid, 1, 0, "paid")
expire()
checkCounts(t, pid, 0, 0, "expired")
// 2. come back after expiry and pay: counted once
subscribe(cur, payer, pid, sessA, now()+day)
checkCounts(t, pid, 0, 1, "re-subscribed after expiry")
pullOK(payer, sessA, gnot)
checkCounts(t, pid, 1, 0, "paid again after expiry")
// 3. expire, then cancel the expired (unpruned) mandate, then come back
resetState()
pid = offer(cur, payee, "Plan", gnot, period)
subscribe(cur, payer, pid, sessA, short())
pullOK(payer, sessA, gnot)
expire()
cancel(cur, payer, payer, sessA)
checkCounts(t, pid, 0, 0, "expired then cancelled")
subscribe(cur, payer, pid, sessA, now()+day)
pullOK(payer, sessA, gnot)
checkCounts(t, pid, 1, 0, "back after expire+cancel")
// 4. expire, re-subscribe (prunes), cancel, come back again
resetState()
pid = offer(cur, payee, "Plan", gnot, period)
subscribe(cur, payer, pid, sessA, short())
pullOK(payer, sessA, gnot)
expire()
subscribe(cur, payer, pid, sessB, now()+day)
pullOK(payer, sessB, gnot)
checkCounts(t, pid, 1, 0, "expired, re-subscribed with another key, paid")
cancel(cur, payer, payer, sessB)
checkCounts(t, pid, 0, 0, "then cancelled")
subscribe(cur, payer, pid, sessA, now()+day)
checkCounts(t, pid, 1, 0, "back once more within the paid period: covered")
testing.SkipHeights(13)
pullOK(payer, sessA, gnot)
checkCounts(t, pid, 1, 0, "and paid when it ended")
// 5. cancel a paying mandate, come back within the paid period: the new
// mandate is covered (listed, not "unpaid") and first pays when the
// paid period ends; counted once per payment
resetState()
pid = offer(cur, payee, "Plan", gnot, period)
subscribe(cur, payer, pid, sessA, now()+day)
pullOK(payer, sessA, gnot)
paid := PaidThrough(payer, pid)
cancel(cur, payer, payer, sessA)
checkCounts(t, pid, 0, 0, "cancelled")
uassert.Equal(t, paid, PaidThrough(payer, pid), "paid time kept after the cancel")
subscribe(cur, payer, pid, sessA, now()+day)
checkCounts(t, pid, 1, 0, "back within the paid period: covered")
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, paid, m.NextPullAt, "first pull when the paid period ends")
testing.SkipHeights((paid - now() + 4) / 5)
pullOK(payer, sessA, gnot)
checkCounts(t, pid, 1, 0, "back and paid")
testing.SkipHeights(13) // next period: a second payment adds nothing to the lists
pullOK(payer, sessA, gnot)
checkCounts(t, pid, 1, 0, "paid twice")
// 5b. never paid, then expired: not "not yet paid" any more
resetState()
pid = offer(cur, payee, "Plan", gnot, period)
subscribe(cur, payer, pid, sessA, short())
checkCounts(t, pid, 0, 1, "unpaid")
expire()
checkCounts(t, pid, 0, 0, "unpaid, expired")
// 6. two payers, one expires: the other still counts
resetState()
pid = offer(cur, payee, "Plan", gnot, period)
subscribe(cur, payer, pid, sessA, short())
subscribe(cur, payer2, pid, sessA, now()+day)
pullOK(payer, sessA, gnot)
pullOK(payer2, sessA, gnot)
checkCounts(t, pid, 2, 0, "two paying")
expire()
checkCounts(t, pid, 1, 0, "one expired")
}
// Paid time is never lost and never charged twice for the same payer and
// plan (audit 2, MEDIUM-A), whoever cancels, after an expiry, a key
// rotation or a yearly renewal of a monthly plan, with another session
// key, across plans.
func TestNoDoubleCharge(cur realm, t *testing.T) {
month := 30 * day
status := func(pid uint64, payer, sess address) byte {
return decodeEntry(planOf(pid).Supporters.at(latestBySession(payer, sess).Index)).Status
}
due := func(payer, sess address) int64 {
m, _ := MandateOf(payer, sess)
return m.NextPullAt
}
tooEarly := func(sess address, what string) {
panicsLocal(t, cur, "too early", func() { checkPull(true, sess, []string{selfPaths}, payer, ugnot(gnot), now()) }, what)
}
// 1. the payer cancels and comes back two days later
resetState()
pid := offer(cur, payee, "Monthly", gnot, month)
subscribe(cur, payer, pid, sessA, now()+300*day)
t0 := now()
pullOK(payer, sessA, gnot)
testing.SkipHeights(2 * day / 5)
cancel(cur, payer, payer, sessA)
uassert.True(t, status(pid, payer, sessA) == statusCancelled, "old entry cancelled")
uassert.Equal(t, t0+month, PaidThrough(payer, pid), "kept after the payer's cancel")
subscribe(cur, payer, pid, sessA, now()+300*day)
uassert.Equal(t, t0+month, due(payer, sessA), "first pull of the new mandate when the paid month ends")
uassert.True(t, status(pid, payer, sessA) == statusPaid, "new entry covered")
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, t0+month, m.PaidThrough)
uassert.False(t, m.Due)
tooEarly(sessA, "no second charge in the paid month")
scan := strings.Split(CollectorScan(pid, sessA, 0), "\n")[0]
uassert.True(t, strings.HasSuffix(scan, " wait 0 1"), "the collector sees a paid payer, not a new one: "+scan)
p, _ := GetPlan(pid)
uassert.Equal(t, 1, p.PaidThisPeriod+p.PaidLastPeriod, "one payment")
has(t, renders(t, "payer/"+payer.String()), "your current period is already paid", "payer page")
list, _ := payingFrom(planOf(pid), -1, now())
uassert.Equal(t, 1, len(list), "listed once, as the new mandate")
testing.SkipHeights((t0 + month - now() + 4) / 5)
pullOK(payer, sessA, gnot)
uassert.Equal(t, now()+month, PaidThrough(payer, pid))
uassert.Equal(t, 0, len(payerOf(payer).Credits), "the credit was used up")
// 2. the payee cancels; the payer comes back
resetState()
pid = offer(cur, payee, "Monthly", gnot, month)
subscribe(cur, payer, pid, sessA, now()+300*day)
t0 = now()
pullOK(payer, sessA, gnot)
cancel(cur, payee, payer, sessA)
uassert.Equal(t, t0+month, PaidThrough(payer, pid), "kept after the payee's cancel")
uassert.True(t, IsPaidUp(payer, pid))
has(t, renders(t, "payer/"+payer.String()), "that time stays yours", "payer page after a cancel")
subscribe(cur, payer, pid, sessA, now()+300*day)
uassert.Equal(t, t0+month, due(payer, sessA))
// 3. the payee rotates its collector key: cancel, subscribe with the new key
resetState()
pid = offer(cur, payee, "Monthly", gnot, month)
setKey(cur, payee, gpubA)
subscribe(cur, payer, pid, sessA, now()+300*day)
t0 = now()
pullOK(payer, sessA, gnot)
testing.SkipHeights(day / 5)
setKey(cur, payee, gpubB)
cancel(cur, payer, payer, sessA)
subscribe(cur, payer, pid, sessB, now()+300*day)
uassert.Equal(t, t0+month, due(payer, sessB), "new key, same paid month")
tooEarly(sessB, "no charge with the new key in the paid month")
// 4. yearly renewal of a 30-day plan: 13 pulls (day 0 to 360) on a 365-day mandate,
// renewed on day 364 (cancel first) or on day 366 (after expiry)
for _, renewDay := range []int64{364, 366} {
resetState()
pid = offer(cur, payee, "Monthly", gnot, month)
start := now()
subscribe(cur, payer, pid, sessA, start+365*day)
for k := 0; k < 13; k++ {
if k > 0 {
testing.SkipHeights(month / 5)
}
pullOK(payer, sessA, gnot)
}
paid := now() + month // day 390
testing.SkipHeights((start + renewDay*day - now()) / 5)
uassert.Equal(t, paid, PaidThrough(payer, pid), "paid through day 390 on day "+itoa(renewDay))
sess := sessA
if renewDay < 365 {
cancel(cur, payer, payer, sessA)
} else {
sess = sessB // the old key's mandate expired; either key works, try the other
}
subscribe(cur, payer, pid, sess, now()+365*day)
uassert.Equal(t, paid, due(payer, sess), "renewal on day "+itoa(renewDay)+" first pays on day 390")
tooEarly(sess, "no charge at renewal on day "+itoa(renewDay))
}
// 5. a credit that has run out: the new mandate is due at once
resetState()
pid = offer(cur, payee, "Per minute", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day)
pullOK(payer, sessA, gnot)
cancel(cur, payer, payer, sessA)
testing.SkipHeights(MinPeriod/5 + 1)
uassert.False(t, IsPaidUp(payer, pid))
subscribe(cur, payer, pid, sessB, now()+day)
uassert.Equal(t, now(), due(payer, sessB), "nothing carried")
uassert.True(t, status(pid, payer, sessB) == statusUnpaid, "new entry unpaid")
uassert.Equal(t, 0, len(payerOf(payer).Credits), "the stale credit was pruned")
// 6. several plans: each keeps its own paid time
resetState()
a := offer(cur, payee, "A", gnot, month)
b := offer(cur, payee, "B", gnot, month-day)
subscribe(cur, payer, a, sessA, now()+300*day)
subscribe(cur, payer, b, sessB, now()+300*day)
t0 = now()
pullOK(payer, sessA, gnot)
pullOK(payer, sessB, gnot)
cancel(cur, payer, payer, sessA)
cancel(cur, payer, payer, sessB)
subscribe(cur, payer, b, sessA, now()+300*day)
subscribe(cur, payer, a, sessB, now()+300*day)
uassert.Equal(t, t0+month-day, due(payer, sessA), "plan B's time on B")
uassert.Equal(t, t0+month, due(payer, sessB), "plan A's time on A")
// a never-paid mandate cancelled keeps nothing; another payer is untouched
subscribe(cur, payer2, a, sessA, now()+300*day)
cancel(cur, payer2, payer2, sessA)
uassert.Equal(t, int64(0), PaidThrough(payer2, a))
uassert.True(t, payerOf(payer2).Credits == nil || len(payerOf(payer2).Credits) == 0)
}
// Credits are bounded: a payer who leaves 17 plans while each is paid ahead
// keeps 16; the one that ends soonest gives way.
func TestCreditBound(cur realm, t *testing.T) {
resetState()
var pids []uint64
for i := 0; i < MaxCreditsPerPayer+1; i++ {
pid := offer(cur, payee, "Plan "+itoa(int64(i)), gnot, 30*day)
pids = append(pids, pid)
subscribe(cur, payer, pid, sessA, now()+300*day)
pullOK(payer, sessA, gnot)
cancel(cur, payer, payer, sessA)
testing.SkipHeights(1) // each later credit ends 5 s later
}
uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
uassert.Equal(t, int64(0), PaidThrough(payer, pids[0]), "the soonest-ending credit gave way")
for _, pid := range pids[1:] {
uassert.True(t, PaidThrough(payer, pid) > now(), "kept: plan "+utoa(pid))
}
// paying the first plan again works and is due at once
subscribe(cur, payer, pids[0], sessA, now()+300*day)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, now(), m.NextPullAt)
cancel(cur, payer, payer, sessA)
// at the bound, a credit that ends sooner than all kept ones is dropped
short := offer(cur, payee, "Short", gnot, MinPeriod)
subscribe(cur, payer, short, sessA, now()+300*day)
pullOK(payer, sessA, gnot)
before := PaidThrough(payer, pids[1])
cancel(cur, payer, payer, sessA)
uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
uassert.Equal(t, int64(0), PaidThrough(payer, short), "the shorter credit was not kept")
uassert.Equal(t, before, PaidThrough(payer, pids[1]), "the soonest of the longer ones stayed")
}
// A credit that has run out reads as nothing, and the next write to the
// payer's record drops it.
func TestCreditRunsOut(cur realm, t *testing.T) {
resetState()
a := offer(cur, payee, "A", gnot, MinPeriod)
b := offer(cur, payee, "B", gnot, 30*day)
subscribe(cur, payer, a, sessA, now()+day)
pullOK(payer, sessA, gnot)
cancel(cur, payer, payer, sessA)
uassert.Equal(t, 1, len(payerOf(payer).Credits))
testing.SkipHeights(MinPeriod/5 + 1)
uassert.Equal(t, int64(0), PaidThrough(payer, a), "a run-out credit reads as 0")
uassert.Equal(t, 1, len(payerOf(payer).Credits), "still stored until the next write")
subscribe(cur, payer, b, sessB, now()+day)
pullOK(payer, sessB, gnot)
cancel(cur, payer, payer, sessB) // keeps B's credit, drops A's
cr := payerOf(payer).Credits
uassert.Equal(t, 1, len(cr), "the run-out credit was dropped")
uassert.Equal(t, b, cr[0].PlanID)
}
// Cancel marks the mandate's list entry cancelled, whether it never paid
// or paid, and leaves the other entries alone; reads then skip it without
// a lookup.
func TestCancelMarksEntry(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
subscribe(cur, payer, pid, sessA, now()+day) // entry 0, never pays
subscribe(cur, payer2, pid, sessA, now()+day) // entry 1, pays
subscribe(cur, stranger, pid, sessA, now()+day)
pullOK(payer2, sessA, gnot)
at := func(i int) byte { return decodeEntry(planOf(pid).Supporters.at(i)).Status }
uassert.True(t, at(0) == statusUnpaid && at(1) == statusPaid && at(2) == statusUnpaid, "before")
cancel(cur, payer, payer, sessA)
uassert.True(t, at(0) == statusCancelled, "never-paid entry cancelled")
cancel(cur, payee, payer2, sessA)
uassert.True(t, at(1) == statusCancelled, "paid entry cancelled by the payee")
uassert.True(t, at(2) == statusUnpaid, "the other entry untouched")
uassert.Equal(t, 1, len(SupportersOf(pid, 1)), "only the stranger is active")
}
// A new mandate must outlive the paid time it carries; otherwise anyone
// could mint "paid" entries from one payment by subscribing with a short
// expiry again and again (third audit, LOW-1).
func TestCarriedMandateMustOutliveCredit(cur realm, t *testing.T) {
resetState()
month := 30 * day
pid := offer(cur, payee, "Monthly", gnot, month)
subscribe(cur, payer, pid, sessA, now()+300*day)
pullOK(payer, sessA, gnot)
paid := PaidThrough(payer, pid)
cancel(cur, payer, payer, sessA)
paidEntries := func() int {
n := 0
l := planOf(pid).Supporters
for i := 0; i < l.N; i++ {
if decodeEntry(l.at(i)).Status == statusPaid {
n++
}
}
return n
}
before := paidEntries()
for i := 0; i < 20; i++ {
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payer))
fails(t, cur, "already paid for until", func() { Subscribe(cross(cur), pid, sessA, now()+1) }, "short expiry "+itoa(int64(i)))
testing.SkipHeights(1)
}
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payer))
fails(t, cur, "already paid for until", func() { Subscribe(cross(cur), pid, sessA, paid) }, "expiry exactly at the paid time")
uassert.Equal(t, before, paidEntries(), "no paid entry minted")
uassert.Equal(t, paid, PaidThrough(payer, pid), "the credit is still there")
subscribe(cur, payer, pid, sessA, paid+1)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, paid, m.NextPullAt, "a mandate that outlives the credit takes it")
}
// Subscribe takes the plan's own credit before pruning, so the prune of an
// expired mandate on another plan cannot evict it (third audit, LOW-2).
func TestSubscribeKeepsItsOwnCredit(cur realm, t *testing.T) {
resetState()
month := 30 * day
var pids []uint64
for i := 0; i < MaxCreditsPerPayer; i++ {
pid := offer(cur, payee, "P"+itoa(int64(i)), gnot, month)
pids = append(pids, pid)
subscribe(cur, payer, pid, sessA, now()+300*day)
pullOK(payer, sessA, gnot)
cancel(cur, payer, payer, sessA)
testing.SkipHeights(1)
}
p0 := PaidThrough(payer, pids[0]) // ends soonest
x := offer(cur, payee, "X", gnot, month)
subscribe(cur, payer, x, sessB, now()+120)
pullOK(payer, sessB, gnot)
testing.SkipHeights(30) // X has expired, unpruned, still paid ahead
uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
subscribe(cur, payer, pids[0], sessA, now()+300*day)
m, _ := MandateOf(payer, sessA)
uassert.Equal(t, p0, m.NextPullAt, "the plan's own credit was used, not evicted")
uassert.True(t, PaidThrough(payer, x) > now(), "X's paid time kept by the prune")
}
// A payee's Cancel never evicts a credit the payer holds for another plan:
// with a full record its own credit is not kept (third audit, LOW-3).
func TestPayeeCancelNeverEvicts(cur realm, t *testing.T) {
resetState()
month := 30 * day
a := offer(cur, payee2, "A", 100*gnot, month)
subscribe(cur, payer, a, sessA, now()+300*day)
pullOK(payer, sessA, 100*gnot)
cancel(cur, payer, payer, sessA)
paidA := PaidThrough(payer, a)
testing.SkipHeights(1) // every later credit ends after A's, so an eviction would take A's
var bs []uint64
for i := 0; i < MaxActivePerPayer; i++ {
b := offer(cur, payee, "B"+itoa(int64(i)), MinAmount, month)
bs = append(bs, b)
sess := testutils.TestAddress("md_s" + itoa(int64(i)))
subscribe(cur, payer, b, sess, now()+300*day)
pullOK(payer, sess, MinAmount)
}
testing.SkipHeights(1)
for i, b := range bs { // the payee cancels every one of them, later ones ending later
cancel(cur, payee, payer, testutils.TestAddress("md_s"+itoa(int64(i))))
_ = b
}
uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
uassert.Equal(t, paidA, PaidThrough(payer, a), "the payer's credit with another creator survives")
last := bs[len(bs)-1]
uassert.Equal(t, int64(0), PaidThrough(payer, last), "the payee's 16th cancel kept nothing")
has(t, renders(t, "payer/"+payer.String()), "but that time could not be kept", "payer page says so")
// the payer's own cancel still lets the soonest give way
c := offer(cur, payee2, "C", gnot, month)
subscribe(cur, payer, c, sessB, now()+300*day)
pullOK(payer, sessB, gnot)
cancel(cur, payer, payer, sessB)
uassert.True(t, PaidThrough(payer, c) > now(), "own cancel keeps its credit by evicting the soonest")
}
// A collector key whose address holds coins is an account, and the chain
// then refuses every new session for it (audit 4, MEDIUM-1): SetCollectorKey
// refuses such a key, and the pages and GetPayee say so when it happens to a
// published key.
func TestFundedCollectorKey(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
setKey(cur, payee, gpubA)
pe, _ := GetPayee(payee)
uassert.False(t, pe.CollectorFunded)
has(t, renders(t, "plan/"+utoa(pid)), "gnokey maketx session create", "commands shown")
has(t, renders(t, "plan/"+utoa(pid)), "`session key address collides with existing account`", "the chain's error, where a supporter looks")
has(t, renders(t, "help"), "a realm can even make the address an account that holds nothing", "help is true when the notice cannot fire")
// a key whose address already received coins is refused
testing.IssueCoins(sessB, chain.Coins{{Denom: "ugnot", Amount: 1}})
testing.SetOriginSend(nil)
testing.SetRealm(testing.NewUserRealm(payee))
fails(t, cur, "has received coins", func() { SetCollectorKey(cross(cur), gpubB) }, "funded key")
pe, _ = GetPayee(payee)
uassert.Equal(t, sessA.String(), pe.CollectorAddr.String(), "the old key stays")
// someone sends 1 ugnot to the published key's address
testing.IssueCoins(sessA, chain.Coins{{Denom: "ugnot", Amount: 1}})
pe, _ = GetPayee(payee)
uassert.True(t, pe.CollectorFunded)
pp := renders(t, "plan/"+utoa(pid))
has(t, pp, "New supporters cannot join right now", "plan page notice")
has(t, pp, "must publish a new collector key", "what to do")
has(t, pp, "Existing mandates keep working until they expire; renewing needs the new key", "honest about renewals")
hasNot(t, pp, "gnokey maketx session create", "no command the chain would refuse")
has(t, renders(t, "payee/"+payee.String()), "nobody new can subscribe", "payee page notice")
has(t, renders(t, "help"), "Never send coins to the collector key", "help says so")
// an existing mandate for the old key is untouched by the realm
subscribe(cur, payer, pid, sessA, now()+day) // the realm does not block it; the chain's session create would
pullOK(payer, sessA, gnot)
uassert.True(t, IsPaidUp(payer, pid))
// a fresh, unfunded key can be published
fresh := "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqtrmge0d5wdx9cqxw7fpdrj7n4zwmuj6jh0gknykufehl20ng5drcwhzezy"
setKey(cur, payee, fresh)
pe, _ = GetPayee(payee)
uassert.False(t, pe.CollectorFunded)
has(t, renders(t, "plan/"+utoa(pid)), "gnokey maketx session create", "commands back with the new key")
}
// The paid time of an expired mandate for the plan being subscribed to
// comes back directly from the prune, so a later expired mandate in the same
// prune cannot evict it (audit 4, LOW-A).
func TestPruneReturnsOwnPlanTime(cur realm, t *testing.T) {
resetState()
month := 30 * day
credit := func(i int) uint64 {
c := offer(cur, payee, "C"+itoa(int64(i)), gnot, month)
subscribe(cur, payer, c, sessA, now()+300*day)
pullOK(payer, sessA, gnot)
cancel(cur, payer, payer, sessA)
testing.SkipHeights(1)
return c
}
credit(0)
p := offer(cur, payee, "P", gnot, month)
subscribe(cur, payer, p, testutils.TestAddress("md_p1"), now()+120)
pullOK(payer, testutils.TestAddress("md_p1"), gnot)
pUntil := PaidThrough(payer, p) // after C0's, before every later credit
testing.SkipHeights(1)
for i := 1; i < MaxCreditsPerPayer; i++ {
credit(i)
}
x := offer(cur, payee, "X", gnot, month)
subscribe(cur, payer, x, testutils.TestAddress("md_x"), now()+120)
pullOK(payer, testutils.TestAddress("md_x"), gnot) // ends after everything else
testing.SkipHeights(30) // P and X have expired, unpruned, paid ahead
uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
subscribe(cur, payer, p, testutils.TestAddress("md_p2"), now()+300*day)
m, _ := MandateOf(payer, testutils.TestAddress("md_p2"))
uassert.Equal(t, pUntil, m.NextPullAt, "P's paid time came back from the prune, not evicted by X's")
uassert.True(t, PaidThrough(payer, x) > now(), "X's paid time kept")
}
// PlanCounts and PayingSupporters agree with the page past the read limits,
// and say when a count is not exact.
func TestPlanCountsBeyondLimit(cur realm, t *testing.T) {
resetState()
pid := offer(cur, payee, "Plan", gnot, MinPeriod)
real := testutils.TestAddress("md_real")
subscribe(cur, real, pid, sessA, now()+day)
pullOK(real, sessA, gnot)
for i := 0; i < ScanLimit+5; i++ {
subscribe(cur, testutils.TestAddress("md_b"+itoa(int64(i))), pid, sessA, now()+day)
}
c1, c2, un, exact := PlanCounts(pid)
uassert.Equal(t, 1, c1)
uassert.Equal(t, 0, c2)
uassert.Equal(t, ScanLimit, un, "unpaid counted among the latest ScanLimit")
uassert.False(t, exact, "more entries than that")
has(t, renders(t, "plan/"+utoa(pid)), itoa(int64(ScanLimit))+" active mandates have not paid yet (not listed), among the latest", "page agrees")
ps, next := PayingSupporters(pid, -1)
uassert.Equal(t, 1, len(ps), "the real supporter behind the junk")
uassert.Equal(t, real.String(), ps[0].Payer.String())
uassert.Equal(t, -1, next)
a, b, u, e := PlanCounts(pid + 1)
uassert.True(t, a == 0 && b == 0 && u == 0 && e, "missing plan")
ps, next = PayingSupporters(pid+1, -1)
uassert.True(t, len(ps) == 0 && next == -1, "missing plan list")
}