mandate_test.gno
27.66 Kb · 709 lines
1package mandate
2
3import (
4 "chain"
5 "chain/banker"
6 "strings"
7 "testing"
8 "time"
9
10 "gno.land/p/nt/avl/v0"
11 "gno.land/p/nt/testutils/v0"
12 "gno.land/p/nt/uassert/v0"
13)
14
15// Test notes
16//
17// Sessions: `gno test` cannot sign with a session key, so
18// runtime.GetSessionInfo() always reports "not a session" here. Pull's rules
19// live in checkPull and recordPull, which take the session info as plain
20// arguments and are tested directly below. The real session path (signing,
21// spend limits, revoke, expiry, the transfer) is proven on a real chain by
22// scripts/local-flow.sh.
23//
24// Reverts: the test harness does not roll back realm state when a call
25// panics; on chain the whole transaction reverts. So every refused call is
26// checked to leave all state and the realm balance unchanged, which holds
27// because every check runs before the first write.
28//
29// Time: testing.SkipHeights(n) moves the block time by 5*n seconds.
30
31var (
32 payee = testutils.TestAddress("md_payee")
33 payee2 = testutils.TestAddress("md_payee2")
34 payer = testutils.TestAddress("md_payer")
35 payer2 = testutils.TestAddress("md_payer2")
36 stranger = testutils.TestAddress("md_stranger")
37
38 realmAddr = chain.PackageAddress("gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate")
39)
40
41// Two real session keys and the addresses the chain derives from them
42// (taken from a local chain: gnokey list).
43const (
44 gpubA = "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqfp0696ldln2nm7kd33zfpgypg6u0e7upl03hyeexa6mccn4ce8mkswg65c"
45 sessA = address("g1psdsf789f4xw3qrpjue54g2h28syd09yfkrxdh")
46 gpubB = "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqtwu0rahac8cw2fw7fmlan472nfyprlgdp4c034vmwyumy4yksl67587x7p"
47 sessB = address("g1valkxsym77y3qlj5fq9h4p64y73l3masvuxav0")
48
49 selfPaths = "vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate"
50 gnot = int64(1_000_000)
51 day = int64(86400)
52)
53
54func ugnot(n int64) chain.Coins { return chain.Coins{{Denom: "ugnot", Amount: n}} }
55
56func bal(a address) int64 { return banker.NewReadonlyBanker().GetCoin(a, "ugnot") }
57
58func now() int64 { return time.Now().Unix() }
59
60func resetState() {
61 nextPlanID, nextMandateID = 0, 0
62 plans, payees, payers = avl.NewTree(), avl.NewTree(), avl.NewTree()
63 pullLog = nil
64 totalPulls, totalPaid = 0, 0
65}
66
67// testing.SetRealm changes the realm of the frame that calls it, so it is
68// called inline right before each cross(cur) call it is meant for.
69
70func offer(cur realm, who address, title string, amount, period int64) uint64 {
71 testing.SetOriginSend(nil)
72 testing.SetRealm(testing.NewUserRealm(who))
73 return Offer(cross(cur), title, amount, period)
74}
75
76func setKey(cur realm, who address, gpub string) {
77 testing.SetOriginSend(nil)
78 testing.SetRealm(testing.NewUserRealm(who))
79 SetCollectorKey(cross(cur), gpub)
80}
81
82func subscribe(cur realm, who address, planID uint64, sess address, expires int64) uint64 {
83 testing.SetOriginSend(nil)
84 testing.SetRealm(testing.NewUserRealm(who))
85 return Subscribe(cross(cur), planID, sess, expires)
86}
87
88func cancel(cur realm, who, p, sess address) {
89 testing.SetOriginSend(nil)
90 testing.SetRealm(testing.NewUserRealm(who))
91 Cancel(cross(cur), p, sess)
92}
93
94// pullOK runs Pull's rules and state update as the chain would for a
95// correct session-signed call (the transfer itself is proven by the local
96// flow script).
97func pullOK(p address, sess address, amount int64) {
98 m, pl := checkPull(true, sess, []string{selfPaths}, p, ugnot(amount), now())
99 recordPull(m, pl, now())
100 pullLog = append(pullLog, pulled{plan: pl.ID, at: now()})
101}
102
103// pullLog records every payment the tests make, so expected per-period
104// counts are computed independently of the realm's counters.
105type pulled struct {
106 plan uint64
107 at int64
108}
109
110var pullLog []pulled
111
112// expectedWindows counts the logged payments of a plan in the period window
113// containing now and in the one before.
114func expectedWindows(planID uint64, period int64) (current, previous int) {
115 w := now() / period
116 for _, x := range pullLog {
117 if x.plan != planID {
118 continue
119 }
120 switch x.at / period {
121 case w:
122 current++
123 case w - 1:
124 previous++
125 }
126 }
127 return
128}
129
130// snapshot is everything a refused call must leave unchanged.
131func snapshot() string {
132 var b strings.Builder
133 n1, n2, pulls, paid := Totals()
134 b.WriteString(itoa(int64(n1)) + "/" + itoa(int64(n2)) + "/" + itoa(pulls) + "/" + itoa(paid) + "/" + itoa(bal(realmAddr)) + "\n")
135 mandate := func(m *Mandate) {
136 b.WriteString(utoa(m.ID) + m.Payer.String() + m.Session.String() + itoa(m.ExpiresAt) + itoa(m.NextPullAt) +
137 itoa(m.Pulls) + itoa(m.CancelledAt) + m.CancelledBy.String() + "\n")
138 }
139 plans.Iterate("", "", func(_ string, v any) bool {
140 p := v.(*Plan)
141 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)) +
142 itoa(p.Pulls) + itoa(p.LastPullAt) + "\n")
143 for i := 0; i < p.Supporters.N; i++ {
144 b.WriteString(p.Supporters.at(i) + ",")
145 }
146 return false
147 })
148 payees.Iterate("", "", func(k string, v any) bool {
149 pe := v.(*Payee)
150 b.WriteString(k + itoa(int64(pe.Plans)) + itoa(pe.Pulls) + itoa(pe.Paid) + pe.CollectorKey + pe.CollectorAddr.String() + "\n")
151 return false
152 })
153 payers.Iterate("", "", func(k string, v any) bool {
154 pr := v.(Payer)
155 b.WriteString("\npayer " + k + " active:")
156 for _, r := range pr.Active {
157 b.WriteString(" " + r.Session.String() + "/" + utoa(r.PlanID) + "=" + utoa(r.M.ID))
158 }
159 if pr.Head != nil {
160 b.WriteString(" head=" + utoa(pr.Head.ID))
161 }
162 for m := pr.Head; m != nil; m = m.prevOfPayer {
163 mandate(m)
164 }
165 return false
166 })
167 for _, t := range []*avl.Tree{plans, payees, payers} {
168 b.WriteString(itoa(int64(t.Size())) + ",")
169 }
170 return b.String()
171}
172
173// fails asserts fn aborts with a message containing substr and changes nothing.
174func fails(t *testing.T, rlm realm, substr string, fn func(), what string) {
175 t.Helper()
176 before := snapshot()
177 uassert.AbortsContains(t, rlm, substr, fn, what)
178 if after := snapshot(); after != before {
179 t.Fatalf("%s: state changed by a refused call\nbefore:\n%s\nafter:\n%s", what, before, after)
180 }
181}
182
183// panicsLocal is fails for non-crossing helpers (checkPull).
184func panicsLocal(t *testing.T, rlm realm, substr string, fn func(), what string) {
185 t.Helper()
186 before := snapshot()
187 uassert.PanicsContains(t, rlm, substr, fn, what)
188 if after := snapshot(); after != before {
189 t.Fatalf("%s: state changed by a refused pull", what)
190 }
191}
192
193func TestOffer(cur realm, t *testing.T) {
194 resetState()
195 id := offer(cur, payee, "Weekly supporter", gnot, 7*day)
196 uassert.Equal(t, uint64(1), id)
197 p, ok := GetPlan(id)
198 uassert.True(t, ok)
199 uassert.Equal(t, payee.String(), p.Payee.String())
200 uassert.Equal(t, "Weekly supporter", p.Title)
201 uassert.Equal(t, gnot, p.Amount)
202 uassert.Equal(t, 7*day, p.Period)
203 uassert.Equal(t, now(), p.CreatedAt)
204 pe, ok := GetPayee(payee)
205 uassert.True(t, ok)
206 uassert.Equal(t, 1, pe.Plans)
207 uassert.Equal(t, int64(0), bal(realmAddr))
208
209 // Boundaries are accepted.
210 offer(cur, payee, "min", MinAmount, MinPeriod)
211 offer(cur, payee, "max", MaxAmount, MaxPeriod)
212 offer(cur, payee, strings.Repeat("é", MaxTitleLen), gnot, day)
213 uassert.Equal(t, uint64(4), nextPlanID)
214 uassert.Equal(t, 4, payeeOf(payee).Plans)
215}
216
217func TestOfferRefusals(cur realm, t *testing.T) {
218 resetState()
219 offer(cur, payee, "existing", gnot, day)
220 cases := []struct {
221 title string
222 amount, period int64
223 want string
224 }{
225 {"", gnot, day, "title is empty"},
226 {" ", gnot, day, "title is empty"},
227 {strings.Repeat("a", MaxTitleLen+1), gnot, day, "longer than 80"},
228 {"two\nlines", gnot, day, "single line"},
229 {"tab\there", gnot, day, "single line"},
230 {"cr\rhere", gnot, day, "single line"},
231 {"nul\x00here", gnot, day, "single line"},
232 {"sep\u2028here", gnot, day, "single line"},
233 {"sep\u2029here", gnot, day, "single line"},
234 {"del\x7fhere", gnot, day, "single line"},
235 {"zero\u200bwidth", gnot, day, "invisible formatting"},
236 {"Fluxen\u202egnp.exe", gnot, day, "invisible formatting"},
237 {"\ufeffbom", gnot, day, "invisible formatting"},
238 {"iso\u2066late\u2069", gnot, day, "invisible formatting"},
239 {"soft\u00adhyphen", gnot, day, "invisible formatting"},
240 {"joiner\u200d", gnot, day, "invisible formatting"},
241 {"bad\xffutf8", gnot, day, "not valid UTF-8"},
242 {"ok", MinAmount - 1, day, "below the minimum"},
243 {"ok", 0, day, "below the minimum"},
244 {"ok", -gnot, day, "below the minimum"},
245 {"ok", MaxAmount + 1, day, "above the maximum"},
246 {"ok", gnot, MinPeriod - 1, "period is below"},
247 {"ok", gnot, 0, "period is below"},
248 {"ok", gnot, -1, "period is below"},
249 {"ok", gnot, MaxPeriod + 1, "period is above"},
250 }
251 for _, c := range cases {
252 testing.SetOriginSend(nil)
253 testing.SetRealm(testing.NewUserRealm(payee))
254 fails(t, cur, c.want, func() { Offer(cross(cur), c.title, c.amount, c.period) }, "Offer "+c.want)
255 }
256
257 // Coins attached are refused (the realm never holds funds).
258 testing.SetRealm(testing.NewUserRealm(payee))
259 testing.SetOriginSend(ugnot(gnot))
260 fails(t, cur, "do not send coins", func() { Offer(cross(cur), "ok", gnot, day) }, "Offer with coins")
261 testing.SetOriginSend(nil)
262
263 // Only direct calls from a user.
264 testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/proxy"))
265 fails(t, cur, "direct calls only", func() { Offer(cross(cur), "ok", gnot, day) }, "Offer from a realm")
266}
267
268func TestTitleCharacters(cur realm, t *testing.T) {
269 resetState()
270 // Visible non-ASCII text is fine; only invisible formatting is refused.
271 for _, title := range []string{"Café ☕ für alle", "Support Fluxen's work", "日本語のプラン", "Ünïcödé — dash"} {
272 id := offer(cur, payee, title, gnot, day)
273 p, _ := GetPlan(id)
274 uassert.Equal(t, title, p.Title)
275 }
276}
277
278// PaidThrough moves only with a successful payment: never before the first
279// one, payment time + period after each, and the paid time is kept after a
280// cancel until it runs out. IsPaidUp is now < PaidThrough, exclusive at the boundary.
281func TestPaidThrough(cur realm, t *testing.T) {
282 resetState()
283 pid := offer(cur, payee, "Plan", gnot, MinPeriod)
284 uassert.Equal(t, int64(0), PaidThrough(payer, pid))
285 subscribe(cur, payer, pid, sessA, now()+600)
286 uassert.True(t, HasMandate(payer, pid))
287 uassert.Equal(t, int64(0), PaidThrough(payer, pid), "recorded, not paid")
288 uassert.False(t, IsPaidUp(payer, pid))
289
290 t0 := now()
291 pullOK(payer, sessA, gnot)
292 uassert.Equal(t, t0+MinPeriod, PaidThrough(payer, pid))
293 uassert.True(t, IsPaidUp(payer, pid))
294 uassert.Equal(t, int64(0), PaidThrough(payer2, pid), "another payer")
295 uassert.Equal(t, int64(0), PaidThrough(payer, pid+1), "another plan")
296
297 testing.SkipHeights(MinPeriod/5 - 1) // one block before the period ends
298 uassert.True(t, IsPaidUp(payer, pid))
299 testing.SkipHeights(1) // now == PaidThrough
300 uassert.False(t, IsPaidUp(payer, pid), "exclusive at the boundary")
301 uassert.Equal(t, t0+MinPeriod, PaidThrough(payer, pid), "unchanged without a payment")
302 uassert.True(t, HasMandate(payer, pid), "a mandate is not a payment")
303
304 t1 := now()
305 pullOK(payer, sessA, gnot)
306 uassert.Equal(t, t1+MinPeriod, PaidThrough(payer, pid))
307
308 cancel(cur, payer, payer, sessA)
309 uassert.Equal(t, t1+MinPeriod, PaidThrough(payer, pid), "cancelled: the paid period is still the payer's")
310 uassert.True(t, IsPaidUp(payer, pid))
311 uassert.False(t, HasMandate(payer, pid))
312 testing.SkipHeights(MinPeriod / 5)
313 uassert.False(t, IsPaidUp(payer, pid), "the kept time runs out")
314}
315
316func TestSetCollectorKey(cur realm, t *testing.T) {
317 resetState()
318 // Allowed before any plan: it creates the payee record.
319 setKey(cur, payee, gpubA)
320 pe, ok := GetPayee(payee)
321 uassert.True(t, ok)
322 uassert.Equal(t, gpubA, pe.CollectorKey)
323 uassert.Equal(t, sessA.String(), pe.CollectorAddr.String())
324 uassert.Equal(t, 0, pe.Plans)
325 // Replace it.
326 setKey(cur, payee, gpubB)
327 uassert.Equal(t, sessB.String(), payeeOf(payee).CollectorAddr.String())
328
329 for _, c := range []struct{ key, want string }{
330 {"", "must be a bech32 public key"},
331 {"g1psdsf789f4xw3qrpjue54g2h28syd09yfkrxdh", "must be a bech32 public key"},
332 {"gpub1" + strings.Repeat("q", 200), "must be a bech32 public key"},
333 {gpubA[:len(gpubA)-1] + "q", "not a valid public key"}, // bad checksum
334 {"gpub1mdgqmw", "not a valid public key"},
335 {"gpub1qqqqqq", "not a valid public key"},
336 } {
337 testing.SetOriginSend(nil)
338 testing.SetRealm(testing.NewUserRealm(payee))
339 fails(t, cur, c.want, func() { SetCollectorKey(cross(cur), c.key) }, "SetCollectorKey "+c.key)
340 }
341 // The payee's own main key is refused.
342 testing.SetOriginSend(nil)
343 testing.SetRealm(testing.NewUserRealm(sessA))
344 fails(t, cur, "dedicated key", func() { SetCollectorKey(cross(cur), gpubA) }, "own key as collector")
345 testing.SetRealm(testing.NewUserRealm(payee))
346 testing.SetOriginSend(ugnot(1))
347 fails(t, cur, "do not send coins", func() { SetCollectorKey(cross(cur), gpubA) }, "collector key with coins")
348 testing.SetOriginSend(nil)
349}
350
351func TestSubscribe(cur realm, t *testing.T) {
352 resetState()
353 pid := offer(cur, payee, "Plan", gnot, day)
354 setKey(cur, payee, gpubA)
355 exp := now() + 30*day
356 mid := subscribe(cur, payer, pid, sessA, exp)
357 uassert.Equal(t, uint64(1), mid)
358 m, ok := MandateOf(payer, sessA)
359 uassert.True(t, ok)
360 uassert.Equal(t, payer.String(), m.Payer.String())
361 uassert.Equal(t, payee.String(), m.Payee.String())
362 uassert.Equal(t, sessA.String(), m.Session.String())
363 uassert.Equal(t, gpubA, m.SessionPubKey) // the payee's published key
364 uassert.Equal(t, exp, m.ExpiresAt)
365 uassert.Equal(t, now(), m.NextPullAt) // first payment due at once
366 uassert.Equal(t, "active", m.Status)
367 uassert.True(t, m.Due)
368 uassert.Equal(t, "auth/accounts/"+payer.String()+"/session/"+sessA.String(), m.SessionQuery)
369 uassert.True(t, HasMandate(payer, pid))
370 uassert.Equal(t, now(), NextPullAt(payer, pid))
371 uassert.Equal(t, 1, planOf(pid).Supporters.N)
372 uassert.Equal(t, int64(0), bal(realmAddr))
373
374 // A session key that is not the published collector key: no public key recorded.
375 subscribe(cur, payer2, pid, sessB, exp)
376 m2, _ := MandateOf(payer2, sessB)
377 uassert.Equal(t, "", m2.SessionPubKey)
378
379 // Expiry exactly at the maximum term is accepted.
380 pid2 := offer(cur, payee2, "Other", gnot, day)
381 subscribe(cur, payer, pid2, sessB, now()+MaxTerm)
382}
383
384func TestSubscribeRefusals(cur realm, t *testing.T) {
385 resetState()
386 pid := offer(cur, payee, "Plan", gnot, day)
387 pid2 := offer(cur, payee, "Plan 2", gnot, day)
388 subscribe(cur, payer, pid, sessA, now()+day)
389 cases := []struct {
390 who address
391 plan uint64
392 sess address
393 expires int64
394 want string
395 }{
396 {payer2, 99, sessA, now() + day, "no such plan"},
397 {payer2, 0, sessA, now() + day, "no such plan"},
398 {payee, pid, sessA, now() + day, "your own plan"},
399 {payer2, pid, address(""), now() + day, "invalid session address"},
400 {payer2, pid, address("g1notanaddress"), now() + day, "invalid session address"},
401 {payer2, pid, payer2, now() + day, "dedicated session key"},
402 {payer2, pid, payee, now() + day, "dedicated session key"},
403 {payer2, pid, sessA, now(), "in the future"},
404 {payer2, pid, sessA, now() - 1, "in the future"},
405 {payer2, pid, sessA, 0, "in the future"},
406 {payer2, pid, sessA, now() + MaxTerm + 1, "days away"},
407 {payer, pid2, sessA, now() + day, "already has an active mandate"}, // same session, other plan
408 {payer, pid, sessB, now() + day, "already have an active mandate for this plan"},
409 }
410 for _, c := range cases {
411 testing.SetOriginSend(nil)
412 testing.SetRealm(testing.NewUserRealm(c.who))
413 fails(t, cur, c.want, func() { Subscribe(cross(cur), c.plan, c.sess, c.expires) }, "Subscribe "+c.want)
414 }
415 testing.SetRealm(testing.NewUserRealm(payer2))
416 testing.SetOriginSend(ugnot(gnot))
417 fails(t, cur, "do not send coins", func() { Subscribe(cross(cur), pid, sessA, now()+day) }, "Subscribe with coins")
418 testing.SetOriginSend(nil)
419 testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/proxy"))
420 fails(t, cur, "direct calls only", func() { Subscribe(cross(cur), pid, sessA, now()+day) }, "Subscribe from a realm")
421}
422
423func TestResubscribeAfterCancelOrExpiry(cur realm, t *testing.T) {
424 resetState()
425 pid := offer(cur, payee, "Plan", gnot, MinPeriod)
426 first := subscribe(cur, payer, pid, sessA, now()+day)
427 cancel(cur, payer, payer, sessA)
428 uassert.False(t, HasMandate(payer, pid))
429 second := subscribe(cur, payer, pid, sessA, now()+120)
430 uassert.True(t, second != first)
431 uassert.True(t, HasMandate(payer, pid))
432 m, _ := MandateOf(payer, sessA)
433 uassert.Equal(t, second, m.ID)
434 old := MandatesOf(payer, 1)[1] // newest first
435 uassert.Equal(t, first, old.ID)
436 uassert.Equal(t, "cancelled", old.Status)
437 // Let it expire, then subscribe again with the same session.
438 testing.SkipHeights(24) // 120 s
439 uassert.False(t, HasMandate(payer, pid))
440 uassert.Equal(t, int64(0), NextPullAt(payer, pid))
441 third := subscribe(cur, payer, pid, sessA, now()+day)
442 uassert.True(t, HasMandate(payer, pid))
443 uassert.Equal(t, 3, len(MandatesOf(payer, 1)))
444 uassert.Equal(t, 1, len(SupportersOf(pid, 1))) // active ones only
445 m, _ = MandateOf(payer, sessA)
446 uassert.Equal(t, third, m.ID)
447}
448
449func TestPullRules(cur realm, t *testing.T) {
450 resetState()
451 pid := offer(cur, payee, "Plan", 2*gnot, MinPeriod)
452 exp := now() + 600
453 subscribe(cur, payer, pid, sessA, exp)
454 paths := []string{selfPaths}
455
456 // Not a session, or a session with the wrong scope.
457 panicsLocal(t, cur, "signed with the mandate's session key", func() { checkPull(false, sessA, paths, payer, ugnot(2*gnot), now()) }, "no session")
458 for _, bad := range [][]string{
459 nil,
460 {},
461 {"*"},
462 {"vm/exec"},
463 {"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8"},
464 {"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandat"},
465 {"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate/sub"},
466 {"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate", "bank/send"},
467 {"vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate", "vm/exec:gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/mandate"},
468 {"bank/send"},
469 } {
470 panicsLocal(t, cur, "scoped to exactly", func() { checkPull(true, sessA, bad, payer, ugnot(2*gnot), now()) }, "paths "+strings.Join(bad, ","))
471 }
472 // No mandate for this payer and session.
473 panicsLocal(t, cur, "no active mandate", func() { checkPull(true, sessB, paths, payer, ugnot(2*gnot), now()) }, "other session")
474 panicsLocal(t, cur, "no active mandate", func() { checkPull(true, sessA, paths, payer2, ugnot(2*gnot), now()) }, "other payer")
475 // Wrong coins.
476 for _, c := range []chain.Coins{
477 nil,
478 ugnot(2*gnot - 1),
479 ugnot(2*gnot + 1),
480 ugnot(gnot),
481 {{Denom: "ufoo", Amount: 2 * gnot}},
482 {{Denom: "ufoo", Amount: 1}, {Denom: "ugnot", Amount: 2 * gnot}},
483 {{Denom: "ugnot", Amount: 2 * gnot}, {Denom: "uzzz", Amount: 1}},
484 {{Denom: "ugnot", Amount: 2 * gnot}, {Denom: "ugnot", Amount: 2 * gnot}},
485 } {
486 panicsLocal(t, cur, "send exactly 2000000ugnot", func() { checkPull(true, sessA, paths, payer, c, now()) }, "coins "+c.String())
487 }
488
489 // First pull: allowed at once.
490 t0 := now()
491 pullOK(payer, sessA, 2*gnot)
492 m, _ := MandateOf(payer, sessA)
493 uassert.Equal(t, int64(1), m.Pulls)
494 uassert.Equal(t, 2*gnot, m.Paid)
495 uassert.Equal(t, t0, m.LastPullAt)
496 uassert.Equal(t, t0+MinPeriod, m.NextPullAt)
497 uassert.False(t, m.Due)
498 p, _ := GetPlan(pid)
499 uassert.Equal(t, int64(1), p.Pulls)
500 uassert.Equal(t, 2*gnot, p.Paid)
501 pe, _ := GetPayee(payee)
502 uassert.Equal(t, int64(1), pe.Pulls)
503 uassert.Equal(t, 2*gnot, pe.Paid)
504 _, _, pulls, paid := Totals()
505 uassert.Equal(t, int64(1), pulls)
506 uassert.Equal(t, 2*gnot, paid)
507
508 // Too early: right after, and one block before the period ends.
509 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")
510 testing.SkipHeights(11) // +55 s
511 panicsLocal(t, cur, "too early", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), now()) }, "pull at +55 s")
512 uassert.Equal(t, int64(55), now()-t0)
513 // The rule at the exact second: allowed at next, refused at next-1.
514 panicsLocal(t, cur, "too early", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), t0+MinPeriod-1) }, "pull at next-1")
515 checkPull(true, sessA, paths, payer, ugnot(2*gnot), t0+MinPeriod)
516 testing.SkipHeights(1) // +60 s: due
517 m, _ = MandateOf(payer, sessA)
518 uassert.True(t, m.Due)
519 pullOK(payer, sessA, 2*gnot)
520 m, _ = MandateOf(payer, sessA)
521 uassert.Equal(t, int64(2), m.Pulls)
522 uassert.Equal(t, now()+MinPeriod, m.NextPullAt)
523
524 // A late pull: the next one is one period after it (no catch-up).
525 testing.SkipHeights(60) // +300 s, four periods missed
526 pullOK(payer, sessA, 2*gnot)
527 m, _ = MandateOf(payer, sessA)
528 uassert.Equal(t, int64(3), m.Pulls)
529 uassert.Equal(t, now()+MinPeriod, m.NextPullAt)
530 panicsLocal(t, cur, "too early", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), now()) }, "no catch-up")
531
532 // Expiry: exactly at ExpiresAt is refused, one second before is allowed.
533 testing.SkipHeights(12)
534 checkPull(true, sessA, paths, payer, ugnot(2*gnot), exp-1)
535 panicsLocal(t, cur, "expired", func() { checkPull(true, sessA, paths, payer, ugnot(2*gnot), exp) }, "pull at expiry")
536 uassert.Equal(t, int64(0), bal(realmAddr))
537}
538
539func TestPullCancelled(cur realm, t *testing.T) {
540 resetState()
541 pid := offer(cur, payee, "Plan", gnot, MinPeriod)
542 subscribe(cur, payer, pid, sessA, now()+day)
543 subscribe(cur, payer2, pid, sessA, now()+day)
544 cancel(cur, payee, payer, sessA) // the payee may cancel too
545 panicsLocal(t, cur, "cancelled", func() { checkPull(true, sessA, []string{selfPaths}, payer, ugnot(gnot), now()) }, "pull after cancel")
546 // The other payer's mandate on the same key is untouched.
547 pullOK(payer2, sessA, gnot)
548 uassert.False(t, HasMandate(payer, pid))
549 uassert.True(t, HasMandate(payer2, pid))
550}
551
552func TestPullEntryPoint(cur realm, t *testing.T) {
553 resetState()
554 pid := offer(cur, payee, "Plan", gnot, MinPeriod)
555 subscribe(cur, payer, pid, sessA, now()+day)
556 // Without a session (all that gno test can do) Pull refuses before anything else.
557 testing.SetRealm(testing.NewUserRealm(payer))
558 testing.SetOriginSend(ugnot(gnot))
559 fails(t, cur, "signed with the mandate's session key", func() { Pull(cross(cur)) }, "Pull without session")
560 testing.SetOriginSend(nil)
561 testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/proxy"))
562 fails(t, cur, "must be a direct call", func() { Pull(cross(cur)) }, "Pull from a realm")
563}
564
565func TestCancel(cur realm, t *testing.T) {
566 resetState()
567 pid := offer(cur, payee, "Plan", gnot, day)
568 subscribe(cur, payer, pid, sessA, now()+day)
569 for _, c := range []struct {
570 who, p, s address
571 want string
572 }{
573 {stranger, payer, sessA, "only the payer or the payee"},
574 {payee2, payer, sessA, "only the payer or the payee"},
575 {sessA, payer, sessA, "only the payer or the payee"},
576 {payer, payer, sessB, "no active mandate"},
577 {payer, payer2, sessA, "no active mandate"},
578 } {
579 testing.SetOriginSend(nil)
580 testing.SetRealm(testing.NewUserRealm(c.who))
581 fails(t, cur, c.want, func() { Cancel(cross(cur), c.p, c.s) }, "Cancel "+c.want)
582 }
583 testing.SetRealm(testing.NewUserRealm(payer))
584 testing.SetOriginSend(ugnot(1))
585 fails(t, cur, "do not send coins", func() { Cancel(cross(cur), payer, sessA) }, "Cancel with coins")
586 testing.SetOriginSend(nil)
587
588 cancel(cur, payer, payer, sessA)
589 m, _ := MandateOf(payer, sessA)
590 uassert.Equal(t, "cancelled", m.Status)
591 uassert.Equal(t, now(), m.CancelledAt)
592 uassert.Equal(t, payer.String(), m.CancelledBy.String())
593 uassert.False(t, m.Due)
594 testing.SetRealm(testing.NewUserRealm(payer))
595 fails(t, cur, "already cancelled", func() { Cancel(cross(cur), payer, sessA) }, "cancel twice")
596}
597
598func TestReadsArePlainCopies(cur realm, t *testing.T) {
599 resetState()
600 pid := offer(cur, payee, "Original", gnot, day)
601 subscribe(cur, payer, pid, sessA, now()+day)
602 p, _ := GetPlan(pid)
603 p.Title = "changed"
604 p.Amount = 1
605 list := Plans(1)
606 list[0].Payee = stranger
607 m, _ := MandateOf(payer, sessA)
608 m.ExpiresAt = 0
609 ms := MandatesOf(payer, 1)
610 ms[0].Status = "cancelled"
611 p2, _ := GetPlan(pid)
612 uassert.Equal(t, "Original", p2.Title)
613 uassert.Equal(t, gnot, p2.Amount)
614 uassert.Equal(t, payee.String(), Plans(1)[0].Payee.String())
615 uassert.True(t, HasMandate(payer, pid))
616 _, ok := GetPlan(99)
617 uassert.False(t, ok)
618 _, ok = MandateOf(stranger, sessA)
619 uassert.False(t, ok)
620 _, ok = GetPayee(stranger)
621 uassert.False(t, ok)
622 uassert.False(t, HasMandate(stranger, pid))
623 uassert.False(t, HasMandate(payer, 99))
624}
625
626func TestPaging(cur realm, t *testing.T) {
627 resetState()
628 for i := 0; i < 25; i++ {
629 offer(cur, payee, "Plan "+itoa(int64(i+1)), gnot, day)
630 }
631 offer(cur, payee2, "Other creator", gnot, day)
632 uassert.Equal(t, PageSize, len(Plans(1)))
633 uassert.Equal(t, 6, len(Plans(2)))
634 uassert.Equal(t, 0, len(Plans(3)))
635 uassert.Equal(t, PageSize, len(Plans(0))) // clamped to page 1
636 uassert.Equal(t, PageSize, len(Plans(-5)))
637 uassert.Equal(t, 0, len(Plans(1<<30)))
638 uassert.Equal(t, "Other creator", Plans(1)[0].Title) // newest first
639 uassert.Equal(t, uint64(1), Plans(2)[5].ID)
640 uassert.Equal(t, PageSize, len(PlansOf(payee, 1)))
641 uassert.Equal(t, 5, len(PlansOf(payee, 2)))
642 uassert.Equal(t, uint64(1), PlansOf(payee, 1)[0].ID) // oldest first
643 uassert.Equal(t, 1, len(PlansOf(payee2, 1)))
644 uassert.Equal(t, 0, len(PlansOf(stranger, 1)))
645
646 // 23 payers on plan 1, all with the same collector key.
647 for i := 0; i < 23; i++ {
648 who := testutils.TestAddress("md_p" + itoa(int64(i)))
649 subscribe(cur, who, 1, sessA, now()+day)
650 }
651 uassert.Equal(t, PageSize, len(SupportersOf(1, 1)))
652 uassert.Equal(t, 3, len(SupportersOf(1, 2)))
653 uassert.Equal(t, 0, len(SupportersOf(2, 1)))
654
655 // CollectorScan: plan 1's supporter list, filtered to one key, in
656 // windows of ScanLimit entries with a cursor.
657 first := testutils.TestAddress("md_p0")
658 lines := strings.Split(strings.TrimSuffix(CollectorScan(1, sessA, 0), "\n"), "\n")
659 uassert.Equal(t, 24, len(lines))
660 uassert.Equal(t, "end", lines[23])
661 uassert.Equal(t, "0 1 "+first.String()+" 1000000 "+itoa(now())+" due 0 0", lines[0])
662 uassert.Equal(t, "end\n", CollectorScan(1, sessB, 0))
663 uassert.Equal(t, "end\n", CollectorScan(99, sessA, 0))
664 uassert.Equal(t, "end\n", CollectorScan(1, sessA, 23))
665 // after a pull and a cancel: the paid one waits and shows its pulls, the cancelled one is gone
666 pullOK(first, sessA, gnot)
667 second := testutils.TestAddress("md_p1")
668 cancel(cur, second, second, sessA)
669 lines = strings.Split(strings.TrimSuffix(CollectorScan(1, sessA, 0), "\n"), "\n")
670 uassert.Equal(t, 23, len(lines))
671 uassert.Equal(t, "0 1 "+first.String()+" 1000000 "+itoa(now()+day)+" wait 1 1", lines[0])
672 uassert.True(t, strings.HasPrefix(lines[1], "2 3 "))
673 // CollectorPlans
674 pl := strings.Split(strings.TrimSuffix(CollectorPlans(payee, 1), "\n"), "\n")
675 uassert.Equal(t, PageSize+1, len(pl))
676 uassert.Equal(t, "1 1000000 86400 23", pl[0])
677 uassert.Equal(t, "more", pl[PageSize])
678 uassert.Equal(t, "end\n", CollectorPlans(stranger, 1))
679 _, nMandates, _, _ := Totals()
680 uassert.Equal(t, 23, nMandates)
681}
682
683func TestFormat(t *testing.T) {
684 uassert.Equal(t, "1 GNOT", formatUgnot(1_000_000))
685 uassert.Equal(t, "0.1 GNOT", formatUgnot(100_000))
686 uassert.Equal(t, "0.05 GNOT", formatUgnot(50_000))
687 uassert.Equal(t, "1.000001 GNOT", formatUgnot(1_000_001))
688 uassert.Equal(t, "0 GNOT", formatUgnot(0))
689 uassert.Equal(t, "1000000 GNOT", formatUgnot(MaxAmount))
690 uassert.Equal(t, "minute", formatPeriod(60))
691 uassert.Equal(t, "90 seconds", formatPeriod(90))
692 uassert.Equal(t, "2 hours", formatPeriod(7200))
693 uassert.Equal(t, "day", formatPeriod(86400))
694 uassert.Equal(t, "week", formatPeriod(604800))
695 uassert.Equal(t, "30 days", formatPeriod(30*86400))
696 uassert.Equal(t, "30 days", formatPeriod(MaxPeriod))
697 uassert.Equal(t, "0000000001", pad(1))
698 uassert.Equal(t, "18446744073709551615", pad(18446744073709551615))
699 uassert.True(t, pad(9) < pad(10))
700 uassert.Equal(t, 1, pageParam(""))
701 uassert.Equal(t, 3, pageParam("page=3"))
702 uassert.Equal(t, 3, pageParam("x=1&page=3"))
703 uassert.Equal(t, 1, pageParam("page=0"))
704 uassert.Equal(t, 1, pageParam("page=-2"))
705 uassert.Equal(t, 1, pageParam("page=abc"))
706 uassert.Equal(t, 1, pageParam("page=99999999999"))
707 uassert.Equal(t, "1970-01-01 00:00 UTC", formatTime(0))
708 uassert.Equal(t, "never", formatTimeOrNever(0))
709}