Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

store_test.gno

39.59 Kb · 938 lines
  1package mandate
  2
  3import (
  4	"chain"
  5	"strings"
  6	"testing"
  7
  8	"gno.land/p/nt/testutils/v0"
  9	"gno.land/p/nt/uassert/v0"
 10)
 11
 12// fixedList keeps the newest entries in tail, full chunks of fanout, and
 13// fanout chunks per super-chunk; every index maps to the right entry across
 14// the boundaries, and set rewrites in place.
 15func TestFixedList(t *testing.T) {
 16	var l fixedList
 17	n := fanout*fanout + 3*fanout + 5 // past the first super-chunk
 18	for i := 0; i < n; i++ {
 19		l.add(encodeEntry(payer, uint64(i), statusUnpaid))
 20		uassert.Equal(t, i+1, l.N)
 21		for _, j := range []int{0, i / 2, i} {
 22			uassert.Equal(t, uint64(j), decodeEntry(l.at(j)).ID)
 23		}
 24		uassert.Equal(t, (i+1)%fanout, len(l.tail))
 25		full := (i + 1) / fanout
 26		uassert.Equal(t, (full+fanout-1)/fanout, len(l.supers))
 27	}
 28	uassert.Equal(t, fanout, len(l.supers[0].chunks))
 29	uassert.Equal(t, 3, len(l.supers[1].chunks))
 30	for _, j := range []int{0, 31, 32, 33, fanout*fanout - 1, fanout * fanout, n - 1} {
 31		l.setStatus(j, statusPaid)
 32		e := decodeEntry(l.at(j))
 33		uassert.Equal(t, uint64(j), e.ID)
 34		uassert.True(t, e.Status == statusPaid)
 35		uassert.Equal(t, entryWidth, len(l.at(j)))
 36		uassert.Equal(t, payer.String(), e.Payer.String())
 37	}
 38	// No preallocation: a slot costs storage even when empty.
 39	var small fixedList
 40	small.add("x")
 41	uassert.Equal(t, 1, cap(small.tail))
 42}
 43
 44// Supporter lists keep their order across chunks.
 45func TestLongLists(cur realm, t *testing.T) {
 46	resetState()
 47	pid := offer(cur, payee, "Plan", gnot, day)
 48	n := 2*fanout + 3
 49	for i := 0; i < n; i++ {
 50		subscribe(cur, testutils.TestAddress("md_l"+itoa(int64(i))), pid, sessA, now()+day)
 51	}
 52	uassert.Equal(t, n, planOf(pid).Supporters.N)
 53	seen := 0
 54	for page := 1; ; page++ {
 55		list := SupportersOf(pid, page)
 56		for _, m := range list {
 57			uassert.Equal(t, uint64(seen+1), m.ID)
 58			uassert.Equal(t, testutils.TestAddress("md_l"+itoa(int64(seen))).String(), m.Payer.String())
 59			seen++
 60		}
 61		if len(list) < PageSize {
 62			break
 63		}
 64	}
 65	uassert.Equal(t, n, seen)
 66}
 67
 68// A payer's history is newest first and paged; lookups by session and by
 69// plan return the latest mandate.
 70func TestPayerHistory(cur realm, t *testing.T) {
 71	resetState()
 72	pid := offer(cur, payee, "Plan", gnot, day)
 73	pid2 := offer(cur, payee, "Plan 2", gnot, day)
 74	var ids []uint64
 75	for i := 0; i < 25; i++ {
 76		ids = append(ids, subscribe(cur, payer, pid, sessA, now()+day))
 77		cancel(cur, payer, payer, sessA)
 78	}
 79	last := subscribe(cur, payer, pid2, sessA, now()+day)
 80	p1 := MandatesOf(payer, 1)
 81	p2 := MandatesOf(payer, 2)
 82	uassert.Equal(t, PageSize, len(p1))
 83	uassert.Equal(t, 6, len(p2))
 84	uassert.Equal(t, 0, len(MandatesOf(payer, 3)))
 85	uassert.Equal(t, last, p1[0].ID)
 86	uassert.Equal(t, ids[24], p1[1].ID)
 87	uassert.Equal(t, ids[0], p2[5].ID)
 88	m, _ := MandateOf(payer, sessA)
 89	uassert.Equal(t, last, m.ID)
 90	uassert.True(t, HasMandate(payer, pid2))
 91	uassert.False(t, HasMandate(payer, pid))
 92	pl, _ := GetPlan(pid)
 93	uassert.Equal(t, 25, pl.Mandates)
 94	uassert.Equal(t, 25, pl.Cancelled)
 95	// The payer page pages the same way.
 96	has(t, renders(t, "payer/"+payer.String()), "## Mandate "+utoa(last)+":", "newest first")
 97	has(t, renders(t, "payer/"+payer.String()+"?page=2"), "## Mandate "+utoa(ids[0])+":", "oldest on page 2")
 98}
 99
100// Free reads never create storage: looking up an unknown payer creates no
101// payer record.
102func TestReadsDoNotWrite(cur realm, t *testing.T) {
103	resetState()
104	MandateOf(payer, sessA)
105	HasMandate(payer, 1)
106	NextPullAt(payer, 1)
107	MandatesOf(payer, 1)
108	renders(t, "payer/"+payer.String())
109	uassert.Equal(t, 0, payers.Size())
110}
111
112// Paid, LastPullAt and SessionPubKey are derived, not stored.
113func TestDerivedFields(cur realm, t *testing.T) {
114	resetState()
115	pid := offer(cur, payee, "Plan", 2*gnot, MinPeriod)
116	setKey(cur, payee, gpubA)
117	subscribe(cur, payer, pid, sessA, now()+day)
118	m, _ := MandateOf(payer, sessA)
119	uassert.Equal(t, int64(0), m.LastPullAt)
120	uassert.Equal(t, int64(0), m.Paid)
121	uassert.Equal(t, gpubA, m.SessionPubKey)
122	t0 := now()
123	pullOK(payer, sessA, 2*gnot)
124	testing.SkipHeights(13)
125	t1 := now()
126	pullOK(payer, sessA, 2*gnot)
127	m, _ = MandateOf(payer, sessA)
128	uassert.Equal(t, t1, m.LastPullAt)
129	uassert.True(t, t1 > t0)
130	uassert.Equal(t, int64(2), m.Pulls)
131	uassert.Equal(t, 4*gnot, m.Paid)
132	p, _ := GetPlan(pid)
133	uassert.Equal(t, 4*gnot, p.Paid)
134	uassert.Equal(t, t1, p.LastPullAt)
135	// The payee moves to another collector key: the realm no longer knows
136	// this session's public key, and the payer page says how to find it.
137	setKey(cur, payee, gpubB)
138	m, _ = MandateOf(payer, sessA)
139	uassert.Equal(t, "", m.SessionPubKey)
140	has(t, renders(t, "payer/"+payer.String()), "/sessions -remote", "lookup command")
141}
142
143// Supporters are listed only once they have paid. Junk mandates that never
144// pay are skipped by their status character, without a lookup, so they
145// cannot hide a real supporter; payment counts come from the plan's own
146// counters and junk cannot move them.
147func TestPayingSupporters(cur realm, t *testing.T) {
148	resetState()
149	pid := offer(cur, payee, "Real plan", gnot, MinPeriod)
150	offer(cur, payee, "Nobody pays", gnot, MinPeriod)
151	real := testutils.TestAddress("md_real")
152	subscribe(cur, real, pid, sessA, now()+day)
153	pullOK(real, sessA, gnot)
154	// 2*ScanLimit junk mandates after the real one, none of them ever pays
155	for i := 0; i < 2*ScanLimit; i++ {
156		subscribe(cur, testutils.TestAddress("md_j"+itoa(int64(i))), pid, sessA, now()+day)
157	}
158	p, _ := GetPlan(pid)
159	uassert.Equal(t, 1, p.PaidThisPeriod)
160	// the collector scan resolves at most ScanLimit entries per call and says where to go on
161	scan := CollectorScan(pid, sessA, 0)
162	uassert.True(t, strings.HasSuffix(scan, "\nnext 200\n"), "scan cursor")
163	uassert.Equal(t, ScanLimit+1, len(strings.Split(strings.TrimSuffix(scan, "\n"), "\n")))
164	uassert.True(t, strings.HasSuffix(CollectorScan(pid, sessA, 400), "end\n"))
165	uassert.Equal(t, "end\n", CollectorScan(pid, sessA, 1<<62))
166	uassert.Equal(t, "end\n", CollectorScan(pid, sessA, int(^uint(0)>>1))) // clamped: from+ScanLimit would overflow
167	page := renders(t, "plan/"+utoa(pid))
168	has(t, page, "1 payment in the current period", "count")
169	has(t, page, "200 active mandates have not paid yet (not listed), among the latest 200", "unpaid count, bounded")
170	hasNot(t, page, short(testutils.TestAddress("md_j0")), "junk not listed")
171	has(t, page, "| ["+short(real)+"]", "real supporter found past 400 junk entries in one walk")
172	hasNot(t, page, "More supporters", "nothing more to walk")
173	// a cancel takes the supporter off the list; the payment stays in the counts
174	cancel(cur, real, real, sessA)
175	p, _ = GetPlan(pid)
176	uassert.Equal(t, 1, p.PaidThisPeriod)
177	uassert.Equal(t, 1, p.Cancelled)
178	list, _ := payingFrom(planOf(pid), -1, now())
179	uassert.Equal(t, 0, len(list))
180	// the home page lists only plans somebody paid for in this or the last period
181	home := renders(t, "")
182	has(t, home, "[#"+utoa(pid)+" Real plan]("+base+":plan/"+utoa(pid)+")", "paid plan on home")
183	hasNot(t, home, "Nobody pays", "unpaid plan not on home")
184	has(t, renders(t, "plans"), "Nobody pays", "all plans page")
185	// two periods without payments: off the home page
186	testing.SkipHeights(25)
187	hasNot(t, renders(t, ""), "Real plan]", "no payment for two periods")
188}
189
190// The supporter list walks at most WalkLimit entries per page, and the
191// next page continues where it stopped: a real supporter behind more than
192// WalkLimit never-paid entries is on a later page, never lost.
193func TestPayingWalkBounded(cur realm, t *testing.T) {
194	resetState()
195	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
196	real := testutils.TestAddress("md_real")
197	subscribe(cur, real, pid, sessA, now()+day)
198	pullOK(real, sessA, gnot)
199	for i := 0; i < WalkLimit+10; i++ {
200		subscribe(cur, testutils.TestAddress("md_w"+itoa(int64(i))), pid, sessA, now()+day)
201	}
202	p := planOf(pid)
203	list, next := payingFrom(p, -1, now())
204	uassert.Equal(t, 0, len(list), "first walk stops after WalkLimit entries")
205	uassert.Equal(t, p.Supporters.N-1-WalkLimit, next, "cursor where the walk stopped")
206	list, next = payingFrom(p, next, now())
207	uassert.Equal(t, 1, len(list), "found on the next walk")
208	uassert.Equal(t, real.String(), list[0].Payer.String())
209	uassert.Equal(t, -1, next)
210}
211
212// The payment counters read against the current time: a payment counts in
213// its own period window, then in "the one before", then not at all.
214func TestPaymentWindows(cur realm, t *testing.T) {
215	resetState()
216	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
217	toNextWindow := func() {
218		need := (now()/MinPeriod+1)*MinPeriod - now()
219		testing.SkipHeights((need + 4) / 5)
220	}
221	windows := func(cur, prev int, what string) {
222		p, _ := GetPlan(pid)
223		uassert.Equal(t, cur, p.PaidThisPeriod, what+": this period")
224		uassert.Equal(t, prev, p.PaidLastPeriod, what+": last period")
225	}
226	toNextWindow()
227	subscribe(cur, payer, pid, sessA, now()+day)
228	subscribe(cur, payer2, pid, sessB, now()+day)
229	windows(0, 0, "nothing paid")
230	pullOK(payer, sessA, gnot)
231	pullOK(payer2, sessB, gnot)
232	windows(2, 0, "two payments")
233	toNextWindow()
234	windows(0, 2, "next window, no payment yet")
235	testing.SkipHeights(1) // a full period after the first payment
236	pullOK(payer, sessA, gnot)
237	windows(1, 2, "one payment in the next window")
238	toNextWindow()
239	toNextWindow()
240	windows(0, 0, "two windows later")
241	pullOK(payer, sessA, gnot)
242	windows(1, 0, "after a gap")
243}
244
245// Churn cannot hide a plan someone keeps paying for (audit LOW-1): one
246// steady supporter, and 300 others who subscribe, pay once and cancel.
247func TestHomeSurvivesChurn(cur realm, t *testing.T) {
248	resetState()
249	pid := offer(cur, payee, "Steady", gnot, MinPeriod)
250	steady := testutils.TestAddress("md_steady")
251	subscribe(cur, steady, pid, sessA, now()+day)
252	for round := 0; round < 3; round++ {
253		pullOK(steady, sessA, gnot)
254		for i := 0; i < 100; i++ {
255			who := testutils.TestAddress("md_c" + itoa(int64(round*100+i)))
256			subscribe(cur, who, pid, sessB, now()+day)
257			pullOK(who, sessB, gnot)
258			cancel(cur, who, who, sessB)
259		}
260		has(t, renders(t, ""), "[#"+utoa(pid)+" Steady]("+base+":plan/"+utoa(pid)+")", "steady plan stays on home")
261		list, _ := payingFrom(planOf(pid), -1, now())
262		uassert.Equal(t, 1, len(list), "the steady supporter is listed")
263		uassert.Equal(t, steady.String(), list[0].Payer.String())
264		testing.SkipHeights(13)
265	}
266}
267
268// Offer spam cannot push paid plans off the home page: it walks ScanLimit
269// plans and links onwards.
270func TestOfferSpam(cur realm, t *testing.T) {
271	resetState()
272	pid := offer(cur, payee, "Real plan", gnot, MinPeriod)
273	subscribe(cur, payer, pid, sessA, now()+day)
274	pullOK(payer, sessA, gnot)
275	for i := 0; i < ScanLimit+5; i++ {
276		offer(cur, stranger, "spam "+itoa(int64(i)), MinAmount, MinPeriod)
277	}
278	home := renders(t, "")
279	hasNot(t, home, "spam", "no spam on home")
280	has(t, home, "No plan has been paid for in its current or last period among those looked at.", "first window empty")
281	has(t, home, "[More plans with supporters]("+base+"?from=5)", "cursor")
282	has(t, renders(t, "?from=5"), " Real plan]", "paid plan reached")
283}
284
285// At most MaxActivePerPayer active mandates; a cancelled or expired one
286// frees its slot.
287func TestActiveCap(cur realm, t *testing.T) {
288	resetState()
289	var pids []uint64
290	for i := 0; i < MaxActivePerPayer+2; i++ {
291		pids = append(pids, offer(cur, payee, "Plan "+itoa(int64(i)), gnot, MinPeriod))
292	}
293	sess := func(i int) address { return testutils.TestAddress("md_cap" + itoa(int64(i))) }
294	for i := 0; i < MaxActivePerPayer; i++ {
295		subscribe(cur, payer, pids[i], sess(i), now()+day)
296	}
297	uassert.Equal(t, MaxActivePerPayer, len(payerOf(payer).Active))
298	testing.SetOriginSend(nil)
299	testing.SetRealm(testing.NewUserRealm(payer))
300	fails(t, cur, "at most 16 active mandates", func() { Subscribe(cross(cur), pids[16], sess(16), now()+day) }, "17th mandate")
301	// a cancel frees a slot
302	cancel(cur, payer, payer, sess(0))
303	uassert.Equal(t, MaxActivePerPayer-1, len(payerOf(payer).Active))
304	subscribe(cur, payer, pids[16], sess(16), now()+day)
305	// an expired mandate frees its slot at the next Subscribe
306	resetState()
307	pids = nil
308	for i := 0; i < MaxActivePerPayer+1; i++ {
309		pids = append(pids, offer(cur, payee, "Plan "+itoa(int64(i)), gnot, MinPeriod))
310	}
311	subscribe(cur, payer, pids[0], sess(0), now()+120)
312	for i := 1; i < MaxActivePerPayer; i++ {
313		subscribe(cur, payer, pids[i], sess(i), now()+day)
314	}
315	testing.SetOriginSend(nil)
316	testing.SetRealm(testing.NewUserRealm(payer))
317	fails(t, cur, "at most 16 active", func() { Subscribe(cross(cur), pids[16], sess(16), now()+day) }, "17th before expiry")
318	testing.SkipHeights(24) // 120 s: mandate 1 expires
319	subscribe(cur, payer, pids[16], sess(16), now()+day)
320	uassert.Equal(t, MaxActivePerPayer, len(payerOf(payer).Active))
321	for _, r := range payerOf(payer).Active {
322		uassert.True(t, r.Session != sess(0), "expired entry pruned")
323	}
324}
325
326// What the reads return for cancelled and expired mandates (documented in
327// docs/design.md): MandateOf still returns the newest mandate for that payer
328// and session with its status; IsActive is false; NextPullAt is 0; Pull and
329// Cancel find no active mandate.
330func TestInactiveReads(cur realm, t *testing.T) {
331	resetState()
332	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
333	pid2 := offer(cur, payee, "Plan 2", gnot, MinPeriod)
334	subscribe(cur, payer, pid, sessA, now()+day)
335	subscribe(cur, payer, pid2, sessB, now()+120)
336	cancel(cur, payer, payer, sessA)
337	m, ok := MandateOf(payer, sessA)
338	uassert.True(t, ok)
339	uassert.Equal(t, "cancelled", m.Status)
340	uassert.False(t, HasMandate(payer, pid))
341	uassert.Equal(t, int64(0), NextPullAt(payer, pid))
342	panicsLocal(t, cur, "no active mandate", func() { checkPull(true, sessA, []string{selfPaths}, payer, ugnot(gnot), now()) }, "pull cancelled")
343	testing.SetOriginSend(nil)
344	testing.SetRealm(testing.NewUserRealm(payer))
345	fails(t, cur, "no active mandate", func() { Cancel(cross(cur), payer, sessA) }, "cancel twice")
346	uassert.Equal(t, 1, len(payerOf(payer).Active)) // the cancel removed its entry
347	// expired: entry kept until the next Subscribe; reads say expired
348	testing.SkipHeights(24)
349	m, _ = MandateOf(payer, sessB)
350	uassert.Equal(t, "expired", m.Status)
351	uassert.Equal(t, 0, len(SupportersOf(pid2, 1))) // only active mandates are listed
352	uassert.Equal(t, 0, len(SupportersOf(pid, 1)))  // the cancelled one neither
353	uassert.False(t, HasMandate(payer, pid2))
354	uassert.Equal(t, int64(0), NextPullAt(payer, pid2))
355	panicsLocal(t, cur, "mandate: expired", func() { checkPull(true, sessB, []string{selfPaths}, payer, ugnot(gnot), now()) }, "pull expired")
356	subscribe(cur, payer, pid, sessA, now()+day) // prunes the expired entry
357	uassert.Equal(t, 1, len(payerOf(payer).Active))
358	m, _ = MandateOf(payer, sessB) // still found through the history
359	uassert.Equal(t, "expired", m.Status)
360	uassert.Equal(t, 3, len(MandatesOf(payer, 1)))
361}
362
363// Nothing another address does changes a payer's own record: an attacker's
364// subscribe/cancel loop leaves the victim's Payer exactly as it was.
365func TestPayerIsolation(cur realm, t *testing.T) {
366	resetState()
367	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
368	pid2 := offer(cur, payee, "Plan 2", gnot, MinPeriod)
369	subscribe(cur, payer, pid, sessA, now()+day)
370	victim := func() string {
371		pr := payerOf(payer)
372		s := utoa(pr.Head.ID) + ":"
373		for _, r := range pr.Active {
374			s += r.Session.String() + "/" + utoa(r.PlanID) + "=" + utoa(r.M.ID) + ","
375		}
376		return s
377	}
378	before := victim()
379	for i := 0; i < 40; i++ {
380		s := testutils.TestAddress("md_junk" + itoa(int64(i)))
381		subscribe(cur, stranger, pid2, s, now()+day)
382		cancel(cur, stranger, stranger, s)
383	}
384	uassert.Equal(t, before, victim())
385	uassert.Equal(t, 0, len(payerOf(stranger).Active)) // cancels left nothing behind
386	uassert.Equal(t, 40, len(MandatesOf(stranger, 1))+len(MandatesOf(stranger, 2)))
387}
388
389// Counts true at read time. "Supporters" (listed) are mandates that have
390// paid and are active now: an expired or cancelled one is not, and is not
391// "not yet paid" either; a payer who comes back counts once. The per-period
392// payment counts are history (who paid in this period window and the one
393// before) and are checked against the tests' own log of payments. Every view
394// must agree: GetPlan, the plan headline, the supporter list, SupportersOf,
395// the home page and the payee table.
396func checkCounts(t *testing.T, pid uint64, listed, unpaid int, what string) {
397	t.Helper()
398	p, _ := GetPlan(pid)
399	cur, prev := expectedWindows(pid, p.Period)
400	uassert.Equal(t, cur, p.PaidThisPeriod, what+": GetPlan this period")
401	uassert.Equal(t, prev, p.PaidLastPeriod, what+": GetPlan last period")
402	uassert.Equal(t, now()/p.Period*p.Period, p.PeriodStart, what+": period start")
403	pp := renders(t, "plan/"+utoa(pid))
404	has(t, pp, plural(cur, "payment", "payments")+" in the current period", what+": headline")
405	has(t, pp, ", "+itoa(int64(prev))+" in the one before", what+": headline previous")
406	list, _ := payingFrom(planOf(pid), -1, now())
407	uassert.Equal(t, listed, len(list), what+": listed")
408	ps, _ := PayingSupporters(pid, -1)
409	uassert.Equal(t, listed, len(ps), what+": PayingSupporters")
410	c1, c2, un, exact := PlanCounts(pid)
411	uassert.Equal(t, cur, c1, what+": PlanCounts this period")
412	uassert.Equal(t, prev, c2, what+": PlanCounts last period")
413	uassert.Equal(t, unpaid, un, what+": PlanCounts unpaid")
414	uassert.True(t, exact, what+": PlanCounts exact")
415	active := len(SupportersOf(pid, 1))
416	uassert.Equal(t, listed+unpaid, active, what+": SupportersOf")
417	if unpaid == 1 {
418		has(t, pp, "1 active mandate has not paid yet", what+": unpaid")
419	} else {
420		has(t, pp, itoa(int64(unpaid))+" active mandates have not paid yet", what+": unpaid")
421	}
422	home := renders(t, "")
423	pe := renders(t, "payee/"+payee.String())
424	row := "| [#" + utoa(pid) + " Plan](" + base + ":plan/" + utoa(pid) + ") | 1 GNOT every minute | "
425	if cur+prev > 0 {
426		has(t, home, "[#"+utoa(pid)+" Plan]("+base+":plan/"+utoa(pid)+")", what+": on home")
427	} else {
428		hasNot(t, home, "[#"+utoa(pid)+" Plan]("+base+":plan/"+utoa(pid)+")", what+": not on home")
429	}
430	has(t, pe, row+itoa(int64(cur))+" / "+itoa(int64(prev))+" |", what+": payee table")
431}
432
433func TestExpirySequences(cur realm, t *testing.T) {
434	period := MinPeriod
435	short := func() int64 { return now() + 2*period } // expires in 2 minutes
436	expire := func() { testing.SkipHeights(25) }      // 125 s
437
438	// 1. pay, expire: not a supporter any more, not "unpaid" either
439	resetState()
440	pid := offer(cur, payee, "Plan", gnot, period)
441	subscribe(cur, payer, pid, sessA, short())
442	checkCounts(t, pid, 0, 1, "subscribed, not paid")
443	pullOK(payer, sessA, gnot)
444	checkCounts(t, pid, 1, 0, "paid")
445	expire()
446	checkCounts(t, pid, 0, 0, "expired")
447	// 2. come back after expiry and pay: counted once
448	subscribe(cur, payer, pid, sessA, now()+day)
449	checkCounts(t, pid, 0, 1, "re-subscribed after expiry")
450	pullOK(payer, sessA, gnot)
451	checkCounts(t, pid, 1, 0, "paid again after expiry")
452
453	// 3. expire, then cancel the expired (unpruned) mandate, then come back
454	resetState()
455	pid = offer(cur, payee, "Plan", gnot, period)
456	subscribe(cur, payer, pid, sessA, short())
457	pullOK(payer, sessA, gnot)
458	expire()
459	cancel(cur, payer, payer, sessA)
460	checkCounts(t, pid, 0, 0, "expired then cancelled")
461	subscribe(cur, payer, pid, sessA, now()+day)
462	pullOK(payer, sessA, gnot)
463	checkCounts(t, pid, 1, 0, "back after expire+cancel")
464
465	// 4. expire, re-subscribe (prunes), cancel, come back again
466	resetState()
467	pid = offer(cur, payee, "Plan", gnot, period)
468	subscribe(cur, payer, pid, sessA, short())
469	pullOK(payer, sessA, gnot)
470	expire()
471	subscribe(cur, payer, pid, sessB, now()+day)
472	pullOK(payer, sessB, gnot)
473	checkCounts(t, pid, 1, 0, "expired, re-subscribed with another key, paid")
474	cancel(cur, payer, payer, sessB)
475	checkCounts(t, pid, 0, 0, "then cancelled")
476	subscribe(cur, payer, pid, sessA, now()+day)
477	checkCounts(t, pid, 1, 0, "back once more within the paid period: covered")
478	testing.SkipHeights(13)
479	pullOK(payer, sessA, gnot)
480	checkCounts(t, pid, 1, 0, "and paid when it ended")
481
482	// 5. cancel a paying mandate, come back within the paid period: the new
483	// mandate is covered (listed, not "unpaid") and first pays when the
484	// paid period ends; counted once per payment
485	resetState()
486	pid = offer(cur, payee, "Plan", gnot, period)
487	subscribe(cur, payer, pid, sessA, now()+day)
488	pullOK(payer, sessA, gnot)
489	paid := PaidThrough(payer, pid)
490	cancel(cur, payer, payer, sessA)
491	checkCounts(t, pid, 0, 0, "cancelled")
492	uassert.Equal(t, paid, PaidThrough(payer, pid), "paid time kept after the cancel")
493	subscribe(cur, payer, pid, sessA, now()+day)
494	checkCounts(t, pid, 1, 0, "back within the paid period: covered")
495	m, _ := MandateOf(payer, sessA)
496	uassert.Equal(t, paid, m.NextPullAt, "first pull when the paid period ends")
497	testing.SkipHeights((paid - now() + 4) / 5)
498	pullOK(payer, sessA, gnot)
499	checkCounts(t, pid, 1, 0, "back and paid")
500	testing.SkipHeights(13) // next period: a second payment adds nothing to the lists
501	pullOK(payer, sessA, gnot)
502	checkCounts(t, pid, 1, 0, "paid twice")
503
504	// 5b. never paid, then expired: not "not yet paid" any more
505	resetState()
506	pid = offer(cur, payee, "Plan", gnot, period)
507	subscribe(cur, payer, pid, sessA, short())
508	checkCounts(t, pid, 0, 1, "unpaid")
509	expire()
510	checkCounts(t, pid, 0, 0, "unpaid, expired")
511
512	// 6. two payers, one expires: the other still counts
513	resetState()
514	pid = offer(cur, payee, "Plan", gnot, period)
515	subscribe(cur, payer, pid, sessA, short())
516	subscribe(cur, payer2, pid, sessA, now()+day)
517	pullOK(payer, sessA, gnot)
518	pullOK(payer2, sessA, gnot)
519	checkCounts(t, pid, 2, 0, "two paying")
520	expire()
521	checkCounts(t, pid, 1, 0, "one expired")
522}
523
524// Paid time is never lost and never charged twice for the same payer and
525// plan (audit 2, MEDIUM-A), whoever cancels, after an expiry, a key
526// rotation or a yearly renewal of a monthly plan, with another session
527// key, across plans.
528func TestNoDoubleCharge(cur realm, t *testing.T) {
529	month := 30 * day
530	status := func(pid uint64, payer, sess address) byte {
531		return decodeEntry(planOf(pid).Supporters.at(latestBySession(payer, sess).Index)).Status
532	}
533	due := func(payer, sess address) int64 {
534		m, _ := MandateOf(payer, sess)
535		return m.NextPullAt
536	}
537	tooEarly := func(sess address, what string) {
538		panicsLocal(t, cur, "too early", func() { checkPull(true, sess, []string{selfPaths}, payer, ugnot(gnot), now()) }, what)
539	}
540
541	// 1. the payer cancels and comes back two days later
542	resetState()
543	pid := offer(cur, payee, "Monthly", gnot, month)
544	subscribe(cur, payer, pid, sessA, now()+300*day)
545	t0 := now()
546	pullOK(payer, sessA, gnot)
547	testing.SkipHeights(2 * day / 5)
548	cancel(cur, payer, payer, sessA)
549	uassert.True(t, status(pid, payer, sessA) == statusCancelled, "old entry cancelled")
550	uassert.Equal(t, t0+month, PaidThrough(payer, pid), "kept after the payer's cancel")
551	subscribe(cur, payer, pid, sessA, now()+300*day)
552	uassert.Equal(t, t0+month, due(payer, sessA), "first pull of the new mandate when the paid month ends")
553	uassert.True(t, status(pid, payer, sessA) == statusPaid, "new entry covered")
554	m, _ := MandateOf(payer, sessA)
555	uassert.Equal(t, t0+month, m.PaidThrough)
556	uassert.False(t, m.Due)
557	tooEarly(sessA, "no second charge in the paid month")
558	scan := strings.Split(CollectorScan(pid, sessA, 0), "\n")[0]
559	uassert.True(t, strings.HasSuffix(scan, " wait 0 1"), "the collector sees a paid payer, not a new one: "+scan)
560	p, _ := GetPlan(pid)
561	uassert.Equal(t, 1, p.PaidThisPeriod+p.PaidLastPeriod, "one payment")
562	has(t, renders(t, "payer/"+payer.String()), "your current period is already paid", "payer page")
563	list, _ := payingFrom(planOf(pid), -1, now())
564	uassert.Equal(t, 1, len(list), "listed once, as the new mandate")
565	testing.SkipHeights((t0 + month - now() + 4) / 5)
566	pullOK(payer, sessA, gnot)
567	uassert.Equal(t, now()+month, PaidThrough(payer, pid))
568	uassert.Equal(t, 0, len(payerOf(payer).Credits), "the credit was used up")
569
570	// 2. the payee cancels; the payer comes back
571	resetState()
572	pid = offer(cur, payee, "Monthly", gnot, month)
573	subscribe(cur, payer, pid, sessA, now()+300*day)
574	t0 = now()
575	pullOK(payer, sessA, gnot)
576	cancel(cur, payee, payer, sessA)
577	uassert.Equal(t, t0+month, PaidThrough(payer, pid), "kept after the payee's cancel")
578	uassert.True(t, IsPaidUp(payer, pid))
579	has(t, renders(t, "payer/"+payer.String()), "that time stays yours", "payer page after a cancel")
580	subscribe(cur, payer, pid, sessA, now()+300*day)
581	uassert.Equal(t, t0+month, due(payer, sessA))
582
583	// 3. the payee rotates its collector key: cancel, subscribe with the new key
584	resetState()
585	pid = offer(cur, payee, "Monthly", gnot, month)
586	setKey(cur, payee, gpubA)
587	subscribe(cur, payer, pid, sessA, now()+300*day)
588	t0 = now()
589	pullOK(payer, sessA, gnot)
590	testing.SkipHeights(day / 5)
591	setKey(cur, payee, gpubB)
592	cancel(cur, payer, payer, sessA)
593	subscribe(cur, payer, pid, sessB, now()+300*day)
594	uassert.Equal(t, t0+month, due(payer, sessB), "new key, same paid month")
595	tooEarly(sessB, "no charge with the new key in the paid month")
596
597	// 4. yearly renewal of a 30-day plan: 13 pulls (day 0 to 360) on a 365-day mandate,
598	// renewed on day 364 (cancel first) or on day 366 (after expiry)
599	for _, renewDay := range []int64{364, 366} {
600		resetState()
601		pid = offer(cur, payee, "Monthly", gnot, month)
602		start := now()
603		subscribe(cur, payer, pid, sessA, start+365*day)
604		for k := 0; k < 13; k++ {
605			if k > 0 {
606				testing.SkipHeights(month / 5)
607			}
608			pullOK(payer, sessA, gnot)
609		}
610		paid := now() + month // day 390
611		testing.SkipHeights((start + renewDay*day - now()) / 5)
612		uassert.Equal(t, paid, PaidThrough(payer, pid), "paid through day 390 on day "+itoa(renewDay))
613		sess := sessA
614		if renewDay < 365 {
615			cancel(cur, payer, payer, sessA)
616		} else {
617			sess = sessB // the old key's mandate expired; either key works, try the other
618		}
619		subscribe(cur, payer, pid, sess, now()+365*day)
620		uassert.Equal(t, paid, due(payer, sess), "renewal on day "+itoa(renewDay)+" first pays on day 390")
621		tooEarly(sess, "no charge at renewal on day "+itoa(renewDay))
622	}
623
624	// 5. a credit that has run out: the new mandate is due at once
625	resetState()
626	pid = offer(cur, payee, "Per minute", gnot, MinPeriod)
627	subscribe(cur, payer, pid, sessA, now()+day)
628	pullOK(payer, sessA, gnot)
629	cancel(cur, payer, payer, sessA)
630	testing.SkipHeights(MinPeriod/5 + 1)
631	uassert.False(t, IsPaidUp(payer, pid))
632	subscribe(cur, payer, pid, sessB, now()+day)
633	uassert.Equal(t, now(), due(payer, sessB), "nothing carried")
634	uassert.True(t, status(pid, payer, sessB) == statusUnpaid, "new entry unpaid")
635	uassert.Equal(t, 0, len(payerOf(payer).Credits), "the stale credit was pruned")
636
637	// 6. several plans: each keeps its own paid time
638	resetState()
639	a := offer(cur, payee, "A", gnot, month)
640	b := offer(cur, payee, "B", gnot, month-day)
641	subscribe(cur, payer, a, sessA, now()+300*day)
642	subscribe(cur, payer, b, sessB, now()+300*day)
643	t0 = now()
644	pullOK(payer, sessA, gnot)
645	pullOK(payer, sessB, gnot)
646	cancel(cur, payer, payer, sessA)
647	cancel(cur, payer, payer, sessB)
648	subscribe(cur, payer, b, sessA, now()+300*day)
649	subscribe(cur, payer, a, sessB, now()+300*day)
650	uassert.Equal(t, t0+month-day, due(payer, sessA), "plan B's time on B")
651	uassert.Equal(t, t0+month, due(payer, sessB), "plan A's time on A")
652	// a never-paid mandate cancelled keeps nothing; another payer is untouched
653	subscribe(cur, payer2, a, sessA, now()+300*day)
654	cancel(cur, payer2, payer2, sessA)
655	uassert.Equal(t, int64(0), PaidThrough(payer2, a))
656	uassert.True(t, payerOf(payer2).Credits == nil || len(payerOf(payer2).Credits) == 0)
657}
658
659// Credits are bounded: a payer who leaves 17 plans while each is paid ahead
660// keeps 16; the one that ends soonest gives way.
661func TestCreditBound(cur realm, t *testing.T) {
662	resetState()
663	var pids []uint64
664	for i := 0; i < MaxCreditsPerPayer+1; i++ {
665		pid := offer(cur, payee, "Plan "+itoa(int64(i)), gnot, 30*day)
666		pids = append(pids, pid)
667		subscribe(cur, payer, pid, sessA, now()+300*day)
668		pullOK(payer, sessA, gnot)
669		cancel(cur, payer, payer, sessA)
670		testing.SkipHeights(1) // each later credit ends 5 s later
671	}
672	uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
673	uassert.Equal(t, int64(0), PaidThrough(payer, pids[0]), "the soonest-ending credit gave way")
674	for _, pid := range pids[1:] {
675		uassert.True(t, PaidThrough(payer, pid) > now(), "kept: plan "+utoa(pid))
676	}
677	// paying the first plan again works and is due at once
678	subscribe(cur, payer, pids[0], sessA, now()+300*day)
679	m, _ := MandateOf(payer, sessA)
680	uassert.Equal(t, now(), m.NextPullAt)
681	cancel(cur, payer, payer, sessA)
682
683	// at the bound, a credit that ends sooner than all kept ones is dropped
684	short := offer(cur, payee, "Short", gnot, MinPeriod)
685	subscribe(cur, payer, short, sessA, now()+300*day)
686	pullOK(payer, sessA, gnot)
687	before := PaidThrough(payer, pids[1])
688	cancel(cur, payer, payer, sessA)
689	uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
690	uassert.Equal(t, int64(0), PaidThrough(payer, short), "the shorter credit was not kept")
691	uassert.Equal(t, before, PaidThrough(payer, pids[1]), "the soonest of the longer ones stayed")
692}
693
694// A credit that has run out reads as nothing, and the next write to the
695// payer's record drops it.
696func TestCreditRunsOut(cur realm, t *testing.T) {
697	resetState()
698	a := offer(cur, payee, "A", gnot, MinPeriod)
699	b := offer(cur, payee, "B", gnot, 30*day)
700	subscribe(cur, payer, a, sessA, now()+day)
701	pullOK(payer, sessA, gnot)
702	cancel(cur, payer, payer, sessA)
703	uassert.Equal(t, 1, len(payerOf(payer).Credits))
704	testing.SkipHeights(MinPeriod/5 + 1)
705	uassert.Equal(t, int64(0), PaidThrough(payer, a), "a run-out credit reads as 0")
706	uassert.Equal(t, 1, len(payerOf(payer).Credits), "still stored until the next write")
707	subscribe(cur, payer, b, sessB, now()+day)
708	pullOK(payer, sessB, gnot)
709	cancel(cur, payer, payer, sessB) // keeps B's credit, drops A's
710	cr := payerOf(payer).Credits
711	uassert.Equal(t, 1, len(cr), "the run-out credit was dropped")
712	uassert.Equal(t, b, cr[0].PlanID)
713}
714
715// Cancel marks the mandate's list entry cancelled, whether it never paid
716// or paid, and leaves the other entries alone; reads then skip it without
717// a lookup.
718func TestCancelMarksEntry(cur realm, t *testing.T) {
719	resetState()
720	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
721	subscribe(cur, payer, pid, sessA, now()+day)  // entry 0, never pays
722	subscribe(cur, payer2, pid, sessA, now()+day) // entry 1, pays
723	subscribe(cur, stranger, pid, sessA, now()+day)
724	pullOK(payer2, sessA, gnot)
725	at := func(i int) byte { return decodeEntry(planOf(pid).Supporters.at(i)).Status }
726	uassert.True(t, at(0) == statusUnpaid && at(1) == statusPaid && at(2) == statusUnpaid, "before")
727	cancel(cur, payer, payer, sessA)
728	uassert.True(t, at(0) == statusCancelled, "never-paid entry cancelled")
729	cancel(cur, payee, payer2, sessA)
730	uassert.True(t, at(1) == statusCancelled, "paid entry cancelled by the payee")
731	uassert.True(t, at(2) == statusUnpaid, "the other entry untouched")
732	uassert.Equal(t, 1, len(SupportersOf(pid, 1)), "only the stranger is active")
733}
734
735// A new mandate must outlive the paid time it carries; otherwise anyone
736// could mint "paid" entries from one payment by subscribing with a short
737// expiry again and again (third audit, LOW-1).
738func TestCarriedMandateMustOutliveCredit(cur realm, t *testing.T) {
739	resetState()
740	month := 30 * day
741	pid := offer(cur, payee, "Monthly", gnot, month)
742	subscribe(cur, payer, pid, sessA, now()+300*day)
743	pullOK(payer, sessA, gnot)
744	paid := PaidThrough(payer, pid)
745	cancel(cur, payer, payer, sessA)
746	paidEntries := func() int {
747		n := 0
748		l := planOf(pid).Supporters
749		for i := 0; i < l.N; i++ {
750			if decodeEntry(l.at(i)).Status == statusPaid {
751				n++
752			}
753		}
754		return n
755	}
756	before := paidEntries()
757	for i := 0; i < 20; i++ {
758		testing.SetOriginSend(nil)
759		testing.SetRealm(testing.NewUserRealm(payer))
760		fails(t, cur, "already paid for until", func() { Subscribe(cross(cur), pid, sessA, now()+1) }, "short expiry "+itoa(int64(i)))
761		testing.SkipHeights(1)
762	}
763	testing.SetOriginSend(nil)
764	testing.SetRealm(testing.NewUserRealm(payer))
765	fails(t, cur, "already paid for until", func() { Subscribe(cross(cur), pid, sessA, paid) }, "expiry exactly at the paid time")
766	uassert.Equal(t, before, paidEntries(), "no paid entry minted")
767	uassert.Equal(t, paid, PaidThrough(payer, pid), "the credit is still there")
768	subscribe(cur, payer, pid, sessA, paid+1)
769	m, _ := MandateOf(payer, sessA)
770	uassert.Equal(t, paid, m.NextPullAt, "a mandate that outlives the credit takes it")
771}
772
773// Subscribe takes the plan's own credit before pruning, so the prune of an
774// expired mandate on another plan cannot evict it (third audit, LOW-2).
775func TestSubscribeKeepsItsOwnCredit(cur realm, t *testing.T) {
776	resetState()
777	month := 30 * day
778	var pids []uint64
779	for i := 0; i < MaxCreditsPerPayer; i++ {
780		pid := offer(cur, payee, "P"+itoa(int64(i)), gnot, month)
781		pids = append(pids, pid)
782		subscribe(cur, payer, pid, sessA, now()+300*day)
783		pullOK(payer, sessA, gnot)
784		cancel(cur, payer, payer, sessA)
785		testing.SkipHeights(1)
786	}
787	p0 := PaidThrough(payer, pids[0]) // ends soonest
788	x := offer(cur, payee, "X", gnot, month)
789	subscribe(cur, payer, x, sessB, now()+120)
790	pullOK(payer, sessB, gnot)
791	testing.SkipHeights(30) // X has expired, unpruned, still paid ahead
792	uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
793	subscribe(cur, payer, pids[0], sessA, now()+300*day)
794	m, _ := MandateOf(payer, sessA)
795	uassert.Equal(t, p0, m.NextPullAt, "the plan's own credit was used, not evicted")
796	uassert.True(t, PaidThrough(payer, x) > now(), "X's paid time kept by the prune")
797}
798
799// A payee's Cancel never evicts a credit the payer holds for another plan:
800// with a full record its own credit is not kept (third audit, LOW-3).
801func TestPayeeCancelNeverEvicts(cur realm, t *testing.T) {
802	resetState()
803	month := 30 * day
804	a := offer(cur, payee2, "A", 100*gnot, month)
805	subscribe(cur, payer, a, sessA, now()+300*day)
806	pullOK(payer, sessA, 100*gnot)
807	cancel(cur, payer, payer, sessA)
808	paidA := PaidThrough(payer, a)
809	testing.SkipHeights(1) // every later credit ends after A's, so an eviction would take A's
810	var bs []uint64
811	for i := 0; i < MaxActivePerPayer; i++ {
812		b := offer(cur, payee, "B"+itoa(int64(i)), MinAmount, month)
813		bs = append(bs, b)
814		sess := testutils.TestAddress("md_s" + itoa(int64(i)))
815		subscribe(cur, payer, b, sess, now()+300*day)
816		pullOK(payer, sess, MinAmount)
817	}
818	testing.SkipHeights(1)
819	for i, b := range bs { // the payee cancels every one of them, later ones ending later
820		cancel(cur, payee, payer, testutils.TestAddress("md_s"+itoa(int64(i))))
821		_ = b
822	}
823	uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
824	uassert.Equal(t, paidA, PaidThrough(payer, a), "the payer's credit with another creator survives")
825	last := bs[len(bs)-1]
826	uassert.Equal(t, int64(0), PaidThrough(payer, last), "the payee's 16th cancel kept nothing")
827	has(t, renders(t, "payer/"+payer.String()), "but that time could not be kept", "payer page says so")
828	// the payer's own cancel still lets the soonest give way
829	c := offer(cur, payee2, "C", gnot, month)
830	subscribe(cur, payer, c, sessB, now()+300*day)
831	pullOK(payer, sessB, gnot)
832	cancel(cur, payer, payer, sessB)
833	uassert.True(t, PaidThrough(payer, c) > now(), "own cancel keeps its credit by evicting the soonest")
834}
835
836// A collector key whose address holds coins is an account, and the chain
837// then refuses every new session for it (audit 4, MEDIUM-1): SetCollectorKey
838// refuses such a key, and the pages and GetPayee say so when it happens to a
839// published key.
840func TestFundedCollectorKey(cur realm, t *testing.T) {
841	resetState()
842	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
843	setKey(cur, payee, gpubA)
844	pe, _ := GetPayee(payee)
845	uassert.False(t, pe.CollectorFunded)
846	has(t, renders(t, "plan/"+utoa(pid)), "gnokey maketx session create", "commands shown")
847	has(t, renders(t, "plan/"+utoa(pid)), "`session key address collides with existing account`", "the chain's error, where a supporter looks")
848	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")
849	// a key whose address already received coins is refused
850	testing.IssueCoins(sessB, chain.Coins{{Denom: "ugnot", Amount: 1}})
851	testing.SetOriginSend(nil)
852	testing.SetRealm(testing.NewUserRealm(payee))
853	fails(t, cur, "has received coins", func() { SetCollectorKey(cross(cur), gpubB) }, "funded key")
854	pe, _ = GetPayee(payee)
855	uassert.Equal(t, sessA.String(), pe.CollectorAddr.String(), "the old key stays")
856	// someone sends 1 ugnot to the published key's address
857	testing.IssueCoins(sessA, chain.Coins{{Denom: "ugnot", Amount: 1}})
858	pe, _ = GetPayee(payee)
859	uassert.True(t, pe.CollectorFunded)
860	pp := renders(t, "plan/"+utoa(pid))
861	has(t, pp, "New supporters cannot join right now", "plan page notice")
862	has(t, pp, "must publish a new collector key", "what to do")
863	has(t, pp, "Existing mandates keep working until they expire; renewing needs the new key", "honest about renewals")
864	hasNot(t, pp, "gnokey maketx session create", "no command the chain would refuse")
865	has(t, renders(t, "payee/"+payee.String()), "nobody new can subscribe", "payee page notice")
866	has(t, renders(t, "help"), "Never send coins to the collector key", "help says so")
867	// an existing mandate for the old key is untouched by the realm
868	subscribe(cur, payer, pid, sessA, now()+day) // the realm does not block it; the chain's session create would
869	pullOK(payer, sessA, gnot)
870	uassert.True(t, IsPaidUp(payer, pid))
871	// a fresh, unfunded key can be published
872	fresh := "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqtrmge0d5wdx9cqxw7fpdrj7n4zwmuj6jh0gknykufehl20ng5drcwhzezy"
873	setKey(cur, payee, fresh)
874	pe, _ = GetPayee(payee)
875	uassert.False(t, pe.CollectorFunded)
876	has(t, renders(t, "plan/"+utoa(pid)), "gnokey maketx session create", "commands back with the new key")
877}
878
879// The paid time of an expired mandate for the plan being subscribed to
880// comes back directly from the prune, so a later expired mandate in the same
881// prune cannot evict it (audit 4, LOW-A).
882func TestPruneReturnsOwnPlanTime(cur realm, t *testing.T) {
883	resetState()
884	month := 30 * day
885	credit := func(i int) uint64 {
886		c := offer(cur, payee, "C"+itoa(int64(i)), gnot, month)
887		subscribe(cur, payer, c, sessA, now()+300*day)
888		pullOK(payer, sessA, gnot)
889		cancel(cur, payer, payer, sessA)
890		testing.SkipHeights(1)
891		return c
892	}
893	credit(0)
894	p := offer(cur, payee, "P", gnot, month)
895	subscribe(cur, payer, p, testutils.TestAddress("md_p1"), now()+120)
896	pullOK(payer, testutils.TestAddress("md_p1"), gnot)
897	pUntil := PaidThrough(payer, p) // after C0's, before every later credit
898	testing.SkipHeights(1)
899	for i := 1; i < MaxCreditsPerPayer; i++ {
900		credit(i)
901	}
902	x := offer(cur, payee, "X", gnot, month)
903	subscribe(cur, payer, x, testutils.TestAddress("md_x"), now()+120)
904	pullOK(payer, testutils.TestAddress("md_x"), gnot) // ends after everything else
905	testing.SkipHeights(30)                            // P and X have expired, unpruned, paid ahead
906	uassert.Equal(t, MaxCreditsPerPayer, len(payerOf(payer).Credits))
907	subscribe(cur, payer, p, testutils.TestAddress("md_p2"), now()+300*day)
908	m, _ := MandateOf(payer, testutils.TestAddress("md_p2"))
909	uassert.Equal(t, pUntil, m.NextPullAt, "P's paid time came back from the prune, not evicted by X's")
910	uassert.True(t, PaidThrough(payer, x) > now(), "X's paid time kept")
911}
912
913// PlanCounts and PayingSupporters agree with the page past the read limits,
914// and say when a count is not exact.
915func TestPlanCountsBeyondLimit(cur realm, t *testing.T) {
916	resetState()
917	pid := offer(cur, payee, "Plan", gnot, MinPeriod)
918	real := testutils.TestAddress("md_real")
919	subscribe(cur, real, pid, sessA, now()+day)
920	pullOK(real, sessA, gnot)
921	for i := 0; i < ScanLimit+5; i++ {
922		subscribe(cur, testutils.TestAddress("md_b"+itoa(int64(i))), pid, sessA, now()+day)
923	}
924	c1, c2, un, exact := PlanCounts(pid)
925	uassert.Equal(t, 1, c1)
926	uassert.Equal(t, 0, c2)
927	uassert.Equal(t, ScanLimit, un, "unpaid counted among the latest ScanLimit")
928	uassert.False(t, exact, "more entries than that")
929	has(t, renders(t, "plan/"+utoa(pid)), itoa(int64(ScanLimit))+" active mandates have not paid yet (not listed), among the latest", "page agrees")
930	ps, next := PayingSupporters(pid, -1)
931	uassert.Equal(t, 1, len(ps), "the real supporter behind the junk")
932	uassert.Equal(t, real.String(), ps[0].Payer.String())
933	uassert.Equal(t, -1, next)
934	a, b, u, e := PlanCounts(pid + 1)
935	uassert.True(t, a == 0 && b == 0 && u == 0 && e, "missing plan")
936	ps, next = PayingSupporters(pid+1, -1)
937	uassert.True(t, len(ps) == 0 && next == -1, "missing plan list")
938}