questmaster_test.gno
36.09 Kb · 951 lines
1package questmaster
2
3import (
4 "chain"
5 "chain/banker"
6 "chain/runtime"
7 "strings"
8 "testing"
9
10 "gno.land/p/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/escrow"
11 "gno.land/p/nt/avl/v0"
12 "gno.land/p/nt/testutils/v0"
13 "gno.land/p/nt/uassert/v0"
14)
15
16// Test notes
17//
18// Coins: in `gno test`, testing.SetOriginSend only sets what
19// unsafe.OriginSend() reports; it does not move coins. On chain, a MsgCall
20// with -send credits the realm before the call runs. post() below does the
21// same by issuing the reward to the realm address just before PostQuest.
22// Failing posts get no coins issued, matching a reverted transaction.
23//
24// Reverts: the test harness does NOT roll back realm state when a call
25// panics (checked: a test-only crossing function that changed a variable and
26// then panicked left the change in place). On chain the whole transaction
27// reverts. So the tests below snapshot all quests, totals and the realm
28// balance before every failing call and check they are identical after it.
29// This passes because every check (caller, coins, escrow rule) runs before
30// the first write.
31
32var (
33 alice = testutils.TestAddress("qb_alice")
34 bob = testutils.TestAddress("qb_bob")
35 carol = testutils.TestAddress("qb_carol")
36 dave = testutils.TestAddress("qb_dave")
37
38 realmAddr = chain.PackageAddress("gno.land/r/g1llc3lq3zmjtjdk29dk52munrzxt5ne746cl7r8/questmaster")
39)
40
41const (
42 gnot = int64(1_000_000)
43 link = "https://github.com/example/repo/pull/1"
44)
45
46func ugnot(n int64) chain.Coins { return chain.Coins{{Denom: "ugnot", Amount: n}} }
47
48func bal(addr address) int64 {
49 return banker.NewReadonlyBanker().GetCoin(addr, "ugnot")
50}
51
52// resetState gives each test an empty board. The test harness keeps realm
53// variables between tests but resets bank balances, so every test starts
54// from scratch to keep the balance invariants exact.
55func resetState() {
56 quests = avl.Tree{}
57 byPoster = avl.Tree{}
58 byBuilder = avl.Tree{}
59 openIDs = avl.Tree{}
60 paidIDs = avl.Tree{}
61 lastID = 0
62 totalPosted, totalLocked, totalPaid, totalRefunded = 0, 0, 0, 0
63}
64
65// testing.SetRealm changes the realm of the frame that calls it, so it is
66// called inline in each crossing function (test or helper) right before the
67// cross(cur) call it is meant for, not from a shared helper.
68
69// post posts a quest from u with reward ugnot, simulating the MsgCall deposit.
70func post(cur realm, u address, reward int64, title string) uint64 {
71 return postD(cur, u, reward, title, "details")
72}
73
74// postD is post with chosen details.
75func postD(cur realm, u address, reward int64, title, details string) uint64 {
76 testing.SetRealm(testing.NewUserRealm(u))
77 testing.SetOriginSend(nil)
78 testing.SetOriginSend(ugnot(reward))
79 testing.IssueCoins(realmAddr, ugnot(reward))
80 id := PostQuest(cross(cur), title, details, 2_000)
81 testing.SetOriginSend(nil)
82 return id
83}
84
85// claimed / submitted set up a quest from alice taken by bob.
86func claimed(cur realm, reward int64) uint64 {
87 id := post(cur, alice, reward, "claimed quest")
88 testing.SetRealm(testing.NewUserRealm(bob))
89 testing.SetOriginSend(nil)
90 ClaimQuest(cross(cur), id)
91 return id
92}
93
94func submitted(cur realm, reward int64) uint64 {
95 id := claimed(cur, reward)
96 testing.SetRealm(testing.NewUserRealm(bob))
97 testing.SetOriginSend(nil)
98 SubmitWork(cross(cur), id, link)
99 return id
100}
101
102// snapshot is everything a failed call must leave unchanged.
103type snapshot struct {
104 totals Totals
105 quests []QuestView
106 realm int64
107 open string
108 paid string
109}
110
111func takeSnapshot() snapshot {
112 s := snapshot{totals: GetTotals(), realm: bal(realmAddr)}
113 for id := uint64(1); id <= s.totals.Quests; id++ {
114 s.quests = append(s.quests, GetQuest(id))
115 }
116 s.open = idsString(allPages(OpenQuestIDs))
117 s.paid = idsString(allPages(PaidQuestIDs))
118 return s
119}
120
121func sameSnapshot(t *testing.T, a, b snapshot, what string) {
122 t.Helper()
123 if a.totals != b.totals {
124 t.Fatalf("%s: totals changed: %v -> %v", what, a.totals, b.totals)
125 }
126 if a.realm != b.realm {
127 t.Fatalf("%s: realm balance changed: %d -> %d", what, a.realm, b.realm)
128 }
129 if len(a.quests) != len(b.quests) {
130 t.Fatalf("%s: quest count changed", what)
131 }
132 for i := range a.quests {
133 if a.quests[i] != b.quests[i] {
134 t.Fatalf("%s: quest %d changed", what, i+1)
135 }
136 }
137 if a.open != b.open || a.paid != b.paid {
138 t.Fatalf("%s: open/paid lists changed", what)
139 }
140}
141
142// fails asserts fn aborts with a message containing substr and changes nothing.
143func fails(t *testing.T, rlm realm, substr string, fn func(), what string) {
144 t.Helper()
145 before := takeSnapshot()
146 uassert.AbortsContains(t, rlm, substr, fn, what)
147 sameSnapshot(t, before, takeSnapshot(), what)
148}
149
150func allPages(list func(offset, limit int) []uint64) []uint64 {
151 var out []uint64
152 for off := 0; ; off += MaxPageSize {
153 p := list(off, MaxPageSize)
154 out = append(out, p...)
155 if len(p) < MaxPageSize {
156 return out
157 }
158 }
159}
160
161func idsString(ids []uint64) string {
162 var sb strings.Builder
163 for _, id := range ids {
164 sb.WriteString(idStr(id))
165 sb.WriteString(",")
166 }
167 return sb.String()
168}
169
170// checkInvariants: rule 12 and the totals identities.
171func checkInvariants(t *testing.T, what string) {
172 t.Helper()
173 tot := GetTotals()
174 var held int64
175 open, paid := 0, 0
176 for id := uint64(1); id <= tot.Quests; id++ {
177 q := GetQuest(id)
178 if !q.State.IsFinal() {
179 held += q.Reward
180 }
181 if q.State == escrow.Open {
182 open++
183 }
184 if q.State == escrow.Paid {
185 paid++
186 }
187 }
188 if b := bal(realmAddr); b != held || held != tot.Locked {
189 t.Fatalf("%s: realm balance %d, sum of held rewards %d, locked total %d", what, b, held, tot.Locked)
190 }
191 if tot.Posted != tot.Locked+tot.Paid+tot.Refunded {
192 t.Fatalf("%s: posted %d != locked %d + paid %d + refunded %d", what, tot.Posted, tot.Locked, tot.Paid, tot.Refunded)
193 }
194 if tot.OpenQuests != open || tot.PaidQuests != paid {
195 t.Fatalf("%s: open %d/%d paid %d/%d", what, tot.OpenQuests, open, tot.PaidQuests, paid)
196 }
197}
198
199// ---------------------------------------------------------------------------
200// Plan section 10, case 1: happy path with balances.
201
202func TestHappyPath(cur realm, t *testing.T) {
203 resetState()
204 before := GetTotals()
205 id := post(cur, alice, 5*gnot, "Write a tutorial")
206 q := GetQuest(id)
207 uassert.Equal(t, escrow.Open.String(), q.State.String())
208 uassert.Equal(t, alice.String(), q.Poster.String())
209 uassert.Equal(t, 5*gnot, q.Reward)
210 uassert.Equal(t, runtime.ChainHeight(), q.CreatedAt)
211
212 testing.SetRealm(testing.NewUserRealm(bob))
213 testing.SetOriginSend(nil)
214 ClaimQuest(cross(cur), id)
215 uassert.Equal(t, escrow.Claimed.String(), GetQuest(id).State.String())
216 uassert.Equal(t, bob.String(), GetQuest(id).Builder.String())
217 SubmitWork(cross(cur), id, link)
218 uassert.Equal(t, escrow.Submitted.String(), GetQuest(id).State.String())
219 uassert.Equal(t, link, GetQuest(id).WorkLink)
220
221 bobBefore, realmBefore := bal(bob), bal(realmAddr)
222 testing.SetRealm(testing.NewUserRealm(alice))
223 testing.SetOriginSend(nil)
224 ApproveWork(cross(cur), id)
225 uassert.Equal(t, bobBefore+5*gnot, bal(bob), "builder gets exactly the reward")
226 uassert.Equal(t, realmBefore-5*gnot, bal(realmAddr), "realm pays exactly the reward")
227 uassert.Equal(t, escrow.Paid.String(), GetQuest(id).State.String())
228
229 after := GetTotals()
230 uassert.Equal(t, before.Posted+5*gnot, after.Posted)
231 uassert.Equal(t, before.Paid+5*gnot, after.Paid)
232 uassert.Equal(t, before.Locked, after.Locked)
233 uassert.Equal(t, before.PaidQuests+1, after.PaidQuests)
234 checkInvariants(t, "happy path")
235}
236
237// Case 2: cancel an open quest refunds the poster.
238func TestCancelRefund(cur realm, t *testing.T) {
239 resetState()
240 id := post(cur, alice, 3*gnot, "To be cancelled")
241 before := GetTotals()
242 aliceBefore, realmBefore := bal(alice), bal(realmAddr)
243 testing.SetRealm(testing.NewUserRealm(alice))
244 testing.SetOriginSend(nil)
245 CancelQuest(cross(cur), id)
246 uassert.Equal(t, aliceBefore+3*gnot, bal(alice))
247 uassert.Equal(t, realmBefore-3*gnot, bal(realmAddr))
248 uassert.Equal(t, escrow.Cancelled.String(), GetQuest(id).State.String())
249 after := GetTotals()
250 uassert.Equal(t, before.Refunded+3*gnot, after.Refunded)
251 uassert.Equal(t, before.Locked-3*gnot, after.Locked)
252 uassert.Equal(t, before.OpenQuests-1, after.OpenQuests)
253 checkInvariants(t, "cancel")
254}
255
256// Case 3: reject reopens, clears the builder, counts; builder history kept.
257func TestReject(cur realm, t *testing.T) {
258 resetState()
259 id := submitted(cur, 2*gnot)
260 realmBefore := bal(realmAddr)
261 testing.SetRealm(testing.NewUserRealm(alice))
262 testing.SetOriginSend(nil)
263 RejectWork(cross(cur), id, "Tests are missing")
264 q := GetQuest(id)
265 uassert.Equal(t, escrow.Open.String(), q.State.String())
266 uassert.Equal(t, address("").String(), q.Builder.String())
267 uassert.Equal(t, "", q.WorkLink)
268 uassert.Equal(t, 1, q.RejectCount)
269 uassert.Equal(t, "Tests are missing", q.LastRejectReason)
270 uassert.Equal(t, realmBefore, bal(realmAddr), "no coins move on reject")
271 uassert.True(t, containsID(allPages(OpenQuestIDs), id), "back in the open list")
272 uassert.True(t, containsID(QuestIDsByBuilder(bob, 0, MaxPageSize), id), "builder history kept")
273
274 // a second builder can take it; both stay in their own history
275 testing.SetRealm(testing.NewUserRealm(carol))
276 testing.SetOriginSend(nil)
277 ClaimQuest(cross(cur), id)
278 uassert.True(t, containsID(QuestIDsByBuilder(carol, 0, MaxPageSize), id))
279 uassert.True(t, containsID(QuestIDsByBuilder(bob, 0, MaxPageSize), id))
280 uassert.Equal(t, carol.String(), GetQuest(id).Builder.String())
281 checkInvariants(t, "reject")
282}
283
284// Case 4: ClaimPayout fails up to and including the review deadline, pays after.
285func TestClaimPayoutTimeout(cur realm, t *testing.T) {
286 resetState()
287 id := submitted(cur, 4*gnot)
288 q := GetQuest(id)
289 uassert.Equal(t, q.SubmittedAt+escrow.ReviewBlocks, q.ReviewDeadline)
290
291 testing.SetRealm(testing.NewUserRealm(bob))
292 testing.SetOriginSend(nil)
293 fails(t, cur, "review deadline has not passed", func() { ClaimPayout(cross(cur), id) }, "payout right after submit")
294 testing.SkipHeights(q.ReviewDeadline - runtime.ChainHeight() - 1) // deadline - 1
295 fails(t, cur, "review deadline has not passed", func() { ClaimPayout(cross(cur), id) }, "payout at deadline-1")
296 testing.SkipHeights(1) // exactly at the deadline
297 uassert.Equal(t, q.ReviewDeadline, runtime.ChainHeight())
298 uassert.False(t, GetQuest(id).CanClaimPayout)
299 fails(t, cur, "review deadline has not passed", func() { ClaimPayout(cross(cur), id) }, "payout at deadline")
300
301 testing.SkipHeights(1) // deadline + 1
302 uassert.True(t, GetQuest(id).CanClaimPayout)
303 bobBefore, realmBefore := bal(bob), bal(realmAddr)
304 ClaimPayout(cross(cur), id)
305 uassert.Equal(t, bobBefore+4*gnot, bal(bob))
306 uassert.Equal(t, realmBefore-4*gnot, bal(realmAddr))
307 uassert.Equal(t, escrow.Paid.String(), GetQuest(id).State.String())
308 checkInvariants(t, "timeout payout")
309}
310
311// Reject is allowed at the review deadline and refused one block after.
312func TestRejectAfterReviewDeadline(cur realm, t *testing.T) {
313 resetState()
314 id := submitted(cur, gnot)
315 d := GetQuest(id).ReviewDeadline
316 testing.SkipHeights(d - runtime.ChainHeight() + 1)
317 testing.SetRealm(testing.NewUserRealm(alice))
318 testing.SetOriginSend(nil)
319 fails(t, cur, "review deadline has passed", func() { RejectWork(cross(cur), id, "late") }, "late reject")
320 // approving late still works and pays the builder
321 bobBefore := bal(bob)
322 ApproveWork(cross(cur), id)
323 uassert.Equal(t, bobBefore+gnot, bal(bob))
324}
325
326// Case 5: ReleaseQuest fails up to and including the work deadline, works after.
327func TestReleaseDeadline(cur realm, t *testing.T) {
328 resetState()
329 id := claimed(cur, gnot)
330 q := GetQuest(id)
331 uassert.Equal(t, q.ClaimedAt+2_000, q.WorkDeadline)
332 testing.SetRealm(testing.NewUserRealm(dave))
333 testing.SetOriginSend(nil)
334 fails(t, cur, "work deadline has not passed", func() { ReleaseQuest(cross(cur), id) }, "release right after claim")
335 testing.SkipHeights(q.WorkDeadline - runtime.ChainHeight())
336 uassert.Equal(t, q.WorkDeadline, runtime.ChainHeight())
337 fails(t, cur, "work deadline has not passed", func() { ReleaseQuest(cross(cur), id) }, "release at deadline")
338 // the builder may still submit at the deadline block; check on a copy quest instead
339 testing.SkipHeights(1)
340 uassert.True(t, GetQuest(id).CanRelease)
341 testing.SetRealm(testing.NewUserRealm(bob))
342 testing.SetOriginSend(nil)
343 fails(t, cur, "work deadline has passed", func() { SubmitWork(cross(cur), id, link) }, "submit after deadline")
344 testing.SetRealm(testing.NewUserRealm(dave))
345 testing.SetOriginSend(nil)
346 ReleaseQuest(cross(cur), id)
347 uassert.Equal(t, escrow.Open.String(), GetQuest(id).State.String())
348 uassert.Equal(t, address("").String(), GetQuest(id).Builder.String())
349 uassert.True(t, containsID(allPages(OpenQuestIDs), id))
350 checkInvariants(t, "release")
351}
352
353// Unclaim by the builder reopens the quest.
354func TestUnclaim(cur realm, t *testing.T) {
355 resetState()
356 id := claimed(cur, gnot)
357 testing.SetRealm(testing.NewUserRealm(bob))
358 testing.SetOriginSend(nil)
359 UnclaimQuest(cross(cur), id)
360 uassert.Equal(t, escrow.Open.String(), GetQuest(id).State.String())
361 uassert.True(t, containsID(allPages(OpenQuestIDs), id))
362 uassert.True(t, containsID(QuestIDsByBuilder(bob, 0, MaxPageSize), id), "history kept after unclaim")
363 checkInvariants(t, "unclaim")
364}
365
366// Case 6: a stranger cannot approve, reject, cancel, submit, unclaim or claim payout.
367func TestStranger(cur realm, t *testing.T) {
368 resetState()
369 open := post(cur, alice, gnot, "open")
370 cl := claimed(cur, gnot)
371 sub := submitted(cur, gnot)
372 testing.SetRealm(testing.NewUserRealm(carol))
373 testing.SetOriginSend(nil)
374 fails(t, cur, "only the poster", func() { CancelQuest(cross(cur), open) }, "stranger cancel")
375 fails(t, cur, "only the builder", func() { SubmitWork(cross(cur), cl, link) }, "stranger submit")
376 fails(t, cur, "only the builder", func() { UnclaimQuest(cross(cur), cl) }, "stranger unclaim")
377 fails(t, cur, "only the poster", func() { ApproveWork(cross(cur), sub) }, "stranger approve")
378 fails(t, cur, "only the poster", func() { RejectWork(cross(cur), sub, "no") }, "stranger reject")
379 testing.SkipHeights(escrow.ReviewBlocks + 1)
380 fails(t, cur, "only the builder", func() { ClaimPayout(cross(cur), sub) }, "stranger claim payout")
381 // roles do not cross either
382 testing.SetRealm(testing.NewUserRealm(bob))
383 testing.SetOriginSend(nil)
384 fails(t, cur, "only the poster", func() { ApproveWork(cross(cur), sub) }, "builder approve")
385 testing.SetRealm(testing.NewUserRealm(alice))
386 testing.SetOriginSend(nil)
387 fails(t, cur, "only the builder", func() { ClaimPayout(cross(cur), sub) }, "poster claim payout")
388 fails(t, cur, "only the builder", func() { SubmitWork(cross(cur), cl, link) }, "poster submit")
389}
390
391// Case 7: the poster cannot claim their own quest.
392func TestPosterCannotClaim(cur realm, t *testing.T) {
393 resetState()
394 id := post(cur, alice, gnot, "mine")
395 testing.SetRealm(testing.NewUserRealm(alice))
396 testing.SetOriginSend(nil)
397 fails(t, cur, "cannot claim their own quest", func() { ClaimQuest(cross(cur), id) }, "poster claim")
398}
399
400// Case 8: post with a wrong coin, several coins, no coins or too small a reward.
401func TestPostCoins(cur realm, t *testing.T) {
402 resetState()
403 testing.SetRealm(testing.NewUserRealm(alice))
404 testing.SetOriginSend(nil)
405 cases := []struct {
406 name string
407 sent chain.Coins
408 want string
409 }{
410 {"no coins", nil, ErrNoCoins},
411 {"wrong denom", chain.Coins{{Denom: "uatom", Amount: 5 * gnot}}, ErrWrongDenom},
412 {"two coins", chain.Coins{{Denom: "ugnot", Amount: 5 * gnot}, {Denom: "uatom", Amount: 1}}, ErrSeveralCoins},
413 {"two ugnot entries", chain.Coins{{Denom: "ugnot", Amount: gnot}, {Denom: "ugnot", Amount: gnot}}, ErrSeveralCoins},
414 {"below minimum", ugnot(MinReward - 1), ErrRewardTooLow},
415 {"zero", ugnot(0), ErrRewardTooLow},
416 }
417 for _, c := range cases {
418 testing.SetOriginSend(c.sent)
419 fails(t, cur, c.want, func() { PostQuest(cross(cur), "title", "", 2_000) }, c.name)
420 }
421 testing.SetOriginSend(nil)
422
423 // exactly the minimum works, and the stored reward is the amount sent
424 id := post(cur, alice, MinReward, "minimum")
425 uassert.Equal(t, MinReward, GetQuest(id).Reward)
426 checkInvariants(t, "post coins")
427}
428
429// Rule 3: every function that does not take money refuses coins, even when the
430// call would otherwise succeed.
431func TestNoCoinsOnOtherCalls(cur realm, t *testing.T) {
432 resetState()
433 open := post(cur, alice, gnot, "open")
434 cl := claimed(cur, gnot)
435 sub := submitted(cur, gnot)
436 one := ugnot(1)
437 type call struct {
438 who address
439 name string
440 fn func()
441 }
442 calls := []call{
443 {bob, "ClaimQuest", func() { ClaimQuest(cross(cur), open) }},
444 {alice, "CancelQuest", func() { CancelQuest(cross(cur), open) }},
445 {bob, "SubmitWork", func() { SubmitWork(cross(cur), cl, link) }},
446 {bob, "UnclaimQuest", func() { UnclaimQuest(cross(cur), cl) }},
447 {alice, "ApproveWork", func() { ApproveWork(cross(cur), sub) }},
448 {alice, "RejectWork", func() { RejectWork(cross(cur), sub, "no") }},
449 }
450 for _, c := range calls {
451 testing.SetRealm(testing.NewUserRealm(c.who))
452 testing.SetOriginSend(nil)
453 testing.SetOriginSend(one)
454 fails(t, cur, ErrCoinsNotTaken, c.fn, c.name+" with coins")
455 }
456 // the two time-gated moves, past their deadlines
457 testing.SkipHeights(escrow.ReviewBlocks + 2_001)
458 testing.SetRealm(testing.NewUserRealm(dave))
459 testing.SetOriginSend(nil)
460 testing.SetOriginSend(one)
461 fails(t, cur, ErrCoinsNotTaken, func() { ReleaseQuest(cross(cur), cl) }, "ReleaseQuest with coins")
462 testing.SetRealm(testing.NewUserRealm(bob))
463 testing.SetOriginSend(nil)
464 testing.SetOriginSend(one)
465 fails(t, cur, ErrCoinsNotTaken, func() { ClaimPayout(cross(cur), sub) }, "ClaimPayout with coins")
466 testing.SetOriginSend(nil)
467
468 // without coins the same calls succeed
469 ClaimPayout(cross(cur), sub)
470 testing.SetRealm(testing.NewUserRealm(dave))
471 testing.SetOriginSend(nil)
472 ReleaseQuest(cross(cur), cl)
473 checkInvariants(t, "no coins")
474}
475
476// Case 9: a payout cannot happen twice.
477func TestNoDoublePayout(cur realm, t *testing.T) {
478 resetState()
479 // approve twice, then approve -> claim payout
480 a := submitted(cur, gnot)
481 testing.SetRealm(testing.NewUserRealm(alice))
482 testing.SetOriginSend(nil)
483 ApproveWork(cross(cur), a)
484 fails(t, cur, "not allowed in the quest's current state", func() { ApproveWork(cross(cur), a) }, "approve twice")
485 testing.SkipHeights(escrow.ReviewBlocks + 1)
486 testing.SetRealm(testing.NewUserRealm(bob))
487 testing.SetOriginSend(nil)
488 fails(t, cur, "not allowed in the quest's current state", func() { ClaimPayout(cross(cur), a) }, "approve then claim payout")
489
490 // claim payout twice, then claim payout -> approve
491 b := submitted(cur, gnot)
492 testing.SkipHeights(escrow.ReviewBlocks + 1)
493 testing.SetRealm(testing.NewUserRealm(bob))
494 testing.SetOriginSend(nil)
495 ClaimPayout(cross(cur), b)
496 fails(t, cur, "not allowed in the quest's current state", func() { ClaimPayout(cross(cur), b) }, "claim payout twice")
497 testing.SetRealm(testing.NewUserRealm(alice))
498 testing.SetOriginSend(nil)
499 fails(t, cur, "not allowed in the quest's current state", func() { ApproveWork(cross(cur), b) }, "claim payout then approve")
500
501 // cancel twice
502 c := post(cur, alice, gnot, "cancel twice")
503 testing.SetRealm(testing.NewUserRealm(alice))
504 testing.SetOriginSend(nil)
505 CancelQuest(cross(cur), c)
506 fails(t, cur, "not allowed in the quest's current state", func() { CancelQuest(cross(cur), c) }, "cancel twice")
507 checkInvariants(t, "double payout")
508}
509
510// Case 10: cancel after Claimed (or Submitted) fails.
511// Case 10: cancelling a Claimed or Submitted quest refunds nothing: it only
512// marks the quest as closing.
513func TestCancelAfterClaimOnlyCloses(cur realm, t *testing.T) {
514 resetState()
515 cl := claimed(cur, gnot)
516 sub := submitted(cur, gnot)
517 before := takeSnapshot()
518 aliceBefore := bal(alice)
519 testing.SetRealm(testing.NewUserRealm(alice))
520 testing.SetOriginSend(nil)
521 CancelQuest(cross(cur), cl)
522 CancelQuest(cross(cur), sub)
523 after := takeSnapshot()
524 uassert.Equal(t, before.realm, after.realm, "no coins move on close")
525 uassert.Equal(t, aliceBefore, bal(alice))
526 uassert.True(t, before.totals == after.totals, "totals unchanged on close")
527 uassert.True(t, GetQuest(cl).Closing)
528 uassert.True(t, GetQuest(sub).Closing)
529 uassert.Equal(t, escrow.Claimed.String(), GetQuest(cl).State.String())
530 fails(t, cur, "already closing", func() { CancelQuest(cross(cur), cl) }, "close twice")
531 testing.SetRealm(testing.NewUserRealm(carol))
532 testing.SetOriginSend(nil)
533 fails(t, cur, "only the poster", func() { CancelQuest(cross(cur), sub) }, "stranger close")
534 checkInvariants(t, "close")
535}
536
537// The squatting attack from the security review: a squatter claims, the
538// poster closes, the squatter holds until the work deadline; then anyone can
539// end it, the poster is refunded exactly once and nobody can claim again.
540func TestCloseStopsSquatting(cur realm, t *testing.T) {
541 resetState()
542 eve := testutils.TestAddress("qb_eve")
543 mal := testutils.TestAddress("qb_mal")
544 id := post(cur, alice, 5*gnot, "real task")
545 testing.SetRealm(testing.NewUserRealm(eve))
546 testing.SetOriginSend(nil)
547 ClaimQuest(cross(cur), id)
548
549 testing.SetRealm(testing.NewUserRealm(alice))
550 testing.SetOriginSend(nil)
551 CancelQuest(cross(cur), id)
552 uassert.False(t, containsID(allPages(OpenQuestIDs), id), "closing quest is not open")
553 checkInvariants(t, "closed")
554
555 d := GetQuest(id).WorkDeadline
556 testing.SkipHeights(d - runtime.ChainHeight())
557 testing.SetRealm(testing.NewUserRealm(mal))
558 testing.SetOriginSend(nil)
559 fails(t, cur, "work deadline has not passed", func() { ReleaseQuest(cross(cur), id) }, "release at the deadline")
560 testing.SkipHeights(1)
561
562 aliceBefore, malBefore, realmBefore := bal(alice), bal(mal), bal(realmAddr)
563 totBefore := GetTotals()
564 ReleaseQuest(cross(cur), id)
565 uassert.Equal(t, aliceBefore+5*gnot, bal(alice), "poster refunded once")
566 uassert.Equal(t, malBefore, bal(mal), "the caller gets nothing")
567 uassert.Equal(t, realmBefore-5*gnot, bal(realmAddr))
568 uassert.Equal(t, escrow.Cancelled.String(), GetQuest(id).State.String())
569 uassert.Equal(t, totBefore.Refunded+5*gnot, GetTotals().Refunded)
570 uassert.Equal(t, totBefore.OpenQuests, GetTotals().OpenQuests)
571 uassert.False(t, containsID(allPages(OpenQuestIDs), id))
572 fails(t, cur, "not allowed in the quest's current state", func() { ClaimQuest(cross(cur), id) }, "re-claim after close")
573 fails(t, cur, "not allowed in the quest's current state", func() { ReleaseQuest(cross(cur), id) }, "release twice")
574 testing.SetRealm(testing.NewUserRealm(alice))
575 testing.SetOriginSend(nil)
576 fails(t, cur, "not allowed in the quest's current state", func() { CancelQuest(cross(cur), id) }, "cancel after refund")
577 checkInvariants(t, "squat released")
578}
579
580func TestCloseThenUnclaim(cur realm, t *testing.T) {
581 resetState()
582 id := claimed(cur, 3*gnot)
583 testing.SetRealm(testing.NewUserRealm(alice))
584 testing.SetOriginSend(nil)
585 CancelQuest(cross(cur), id)
586 aliceBefore := bal(alice)
587 testing.SetRealm(testing.NewUserRealm(bob))
588 testing.SetOriginSend(nil)
589 UnclaimQuest(cross(cur), id)
590 uassert.Equal(t, aliceBefore+3*gnot, bal(alice))
591 uassert.Equal(t, escrow.Cancelled.String(), GetQuest(id).State.String())
592 uassert.False(t, containsID(allPages(OpenQuestIDs), id))
593 checkInvariants(t, "close then unclaim")
594}
595
596func TestCloseThenReject(cur realm, t *testing.T) {
597 resetState()
598 id := submitted(cur, 4*gnot)
599 testing.SetRealm(testing.NewUserRealm(alice))
600 testing.SetOriginSend(nil)
601 CancelQuest(cross(cur), id)
602 aliceBefore, bobBefore := bal(alice), bal(bob)
603 RejectWork(cross(cur), id, "not what I asked")
604 uassert.Equal(t, aliceBefore+4*gnot, bal(alice))
605 uassert.Equal(t, bobBefore, bal(bob))
606 q := GetQuest(id)
607 uassert.Equal(t, escrow.Cancelled.String(), q.State.String())
608 uassert.Equal(t, 1, q.RejectCount)
609 uassert.False(t, containsID(allPages(OpenQuestIDs), id))
610 checkInvariants(t, "close then reject")
611}
612
613// While closing, the builder keeps every right.
614func TestCloseStillPaysBuilder(cur realm, t *testing.T) {
615 resetState()
616 a := claimed(cur, 2*gnot)
617 testing.SetRealm(testing.NewUserRealm(alice))
618 testing.SetOriginSend(nil)
619 CancelQuest(cross(cur), a)
620 testing.SetRealm(testing.NewUserRealm(bob))
621 testing.SetOriginSend(nil)
622 SubmitWork(cross(cur), a, link)
623 bobBefore := bal(bob)
624 testing.SetRealm(testing.NewUserRealm(alice))
625 testing.SetOriginSend(nil)
626 ApproveWork(cross(cur), a)
627 uassert.Equal(t, bobBefore+2*gnot, bal(bob), "approve while closing pays the builder")
628
629 b := submitted(cur, 3*gnot)
630 testing.SetRealm(testing.NewUserRealm(alice))
631 testing.SetOriginSend(nil)
632 CancelQuest(cross(cur), b)
633 testing.SkipHeights(escrow.ReviewBlocks + 1)
634 bobBefore = bal(bob)
635 testing.SetRealm(testing.NewUserRealm(bob))
636 testing.SetOriginSend(nil)
637 ClaimPayout(cross(cur), b)
638 uassert.Equal(t, bobBefore+3*gnot, bal(bob), "timeout payout while closing pays the builder")
639 checkInvariants(t, "close still pays")
640}
641
642// The timeout rule, documented: a builder who submits anything is paid after
643// the review window if the poster does nothing; a reject at the last block of
644// the window prevents it.
645func TestJunkSubmissionTimeout(cur realm, t *testing.T) {
646 resetState()
647 id := claimed(cur, 5*gnot)
648 testing.SetRealm(testing.NewUserRealm(bob))
649 testing.SetOriginSend(nil)
650 SubmitWork(cross(cur), id, "https://x")
651 testing.SkipHeights(GetQuest(id).ReviewDeadline - runtime.ChainHeight() + 1)
652 bobBefore := bal(bob)
653 ClaimPayout(cross(cur), id)
654 uassert.Equal(t, bobBefore+5*gnot, bal(bob), "silent poster: builder paid")
655
656 id2 := claimed(cur, 5*gnot)
657 testing.SetRealm(testing.NewUserRealm(bob))
658 testing.SetOriginSend(nil)
659 SubmitWork(cross(cur), id2, "https://x")
660 testing.SkipHeights(GetQuest(id2).ReviewDeadline - runtime.ChainHeight())
661 testing.SetRealm(testing.NewUserRealm(alice))
662 testing.SetOriginSend(nil)
663 RejectWork(cross(cur), id2, "junk")
664 testing.SkipHeights(1)
665 testing.SetRealm(testing.NewUserRealm(bob))
666 testing.SetOriginSend(nil)
667 fails(t, cur, "not allowed in the quest's current state", func() { ClaimPayout(cross(cur), id2) }, "payout after reject")
668 checkInvariants(t, "junk timeout")
669}
670
671// Case 11: text over the limits and bad links fail at realm level.
672func TestTextLimits(cur realm, t *testing.T) {
673 resetState()
674 testing.SetRealm(testing.NewUserRealm(alice))
675 testing.SetOriginSend(nil)
676 bad := []struct{ title, details, want string }{
677 {"", "", "title is empty"},
678 {strings.Repeat("a", escrow.MaxTitleLen+1), "", "title is too long"},
679 {"two\nlines", "", "control characters"},
680 {"ok", strings.Repeat("d", escrow.MaxDetailsLen+1), "details are too long"},
681 }
682 for _, c := range bad {
683 testing.SetOriginSend(ugnot(gnot))
684 fails(t, cur, c.want, func() { PostQuest(cross(cur), c.title, c.details, 2_000) }, "post: "+c.want)
685 }
686 testing.SetOriginSend(ugnot(gnot))
687 fails(t, cur, "work window is below", func() { PostQuest(cross(cur), "t", "", escrow.MinWorkBlocks-1) }, "work window low")
688 fails(t, cur, "work window is above", func() { PostQuest(cross(cur), "t", "", escrow.MaxWorkBlocks+1) }, "work window high")
689 testing.SetOriginSend(nil)
690
691 cl := claimed(cur, gnot)
692 testing.SetRealm(testing.NewUserRealm(bob))
693 testing.SetOriginSend(nil)
694 for _, l := range []string{"http://example.com", "example.com", "https://", "https://a b", "https://" + strings.Repeat("a", escrow.MaxLinkLen)} {
695 fails(t, cur, "escrow: work link", func() { SubmitWork(cross(cur), cl, l) }, "link "+l)
696 }
697 SubmitWork(cross(cur), cl, link)
698 testing.SetRealm(testing.NewUserRealm(alice))
699 testing.SetOriginSend(nil)
700 fails(t, cur, "reject reason is too long", func() { RejectWork(cross(cur), cl, strings.Repeat("r", escrow.MaxReasonLen+1)) }, "long reason")
701 fails(t, cur, "reject reason is empty", func() { RejectWork(cross(cur), cl, "") }, "empty reason")
702}
703
704// Non-user callers (other realms, maketx run scripts) are refused everywhere.
705func TestCodeRealmRefused(cur realm, t *testing.T) {
706 resetState()
707 open := post(cur, alice, gnot, "open")
708 cl := claimed(cur, gnot)
709 sub := submitted(cur, gnot)
710 callers := []runtime.Realm{
711 testing.NewCodeRealm("gno.land/r/evil/proxy"),
712 // a `gnokey maketx run` script runs as an ephemeral realm
713 runtime.NewRealm(alice, "gno.land/e/"+alice.String()+"/run"),
714 }
715 for _, c := range callers {
716 testing.SetRealm(c)
717 testing.SetOriginSend(ugnot(gnot))
718 fails(t, cur, ErrNotUserCall, func() { PostQuest(cross(cur), "t", "", 2_000) }, "PostQuest")
719 testing.SetOriginSend(nil)
720 fails(t, cur, ErrNotUserCall, func() { ClaimQuest(cross(cur), open) }, "ClaimQuest")
721 fails(t, cur, ErrNotUserCall, func() { CancelQuest(cross(cur), open) }, "CancelQuest")
722 fails(t, cur, ErrNotUserCall, func() { SubmitWork(cross(cur), cl, link) }, "SubmitWork")
723 fails(t, cur, ErrNotUserCall, func() { UnclaimQuest(cross(cur), cl) }, "UnclaimQuest")
724 fails(t, cur, ErrNotUserCall, func() { ReleaseQuest(cross(cur), cl) }, "ReleaseQuest")
725 fails(t, cur, ErrNotUserCall, func() { ApproveWork(cross(cur), sub) }, "ApproveWork")
726 fails(t, cur, ErrNotUserCall, func() { RejectWork(cross(cur), sub, "no") }, "RejectWork")
727 fails(t, cur, ErrNotUserCall, func() { ClaimPayout(cross(cur), sub) }, "ClaimPayout")
728 }
729}
730
731// An unknown quest id panics cleanly on every function that takes an id.
732func TestUnknownID(cur realm, t *testing.T) {
733 resetState()
734 missing := GetTotals().Quests + 1000
735 testing.SetRealm(testing.NewUserRealm(alice))
736 testing.SetOriginSend(nil)
737 fails(t, cur, ErrUnknownQuest, func() { ClaimQuest(cross(cur), missing) }, "ClaimQuest")
738 fails(t, cur, ErrUnknownQuest, func() { UnclaimQuest(cross(cur), missing) }, "UnclaimQuest")
739 fails(t, cur, ErrUnknownQuest, func() { ReleaseQuest(cross(cur), missing) }, "ReleaseQuest")
740 fails(t, cur, ErrUnknownQuest, func() { SubmitWork(cross(cur), missing, link) }, "SubmitWork")
741 fails(t, cur, ErrUnknownQuest, func() { ApproveWork(cross(cur), missing) }, "ApproveWork")
742 fails(t, cur, ErrUnknownQuest, func() { RejectWork(cross(cur), missing, "no") }, "RejectWork")
743 fails(t, cur, ErrUnknownQuest, func() { CancelQuest(cross(cur), missing) }, "CancelQuest")
744 fails(t, cur, ErrUnknownQuest, func() { ClaimPayout(cross(cur), missing) }, "ClaimPayout")
745 uassert.PanicsContains(t, cur, ErrUnknownQuest, func() { GetQuest(missing) }, "GetQuest")
746 uassert.PanicsContains(t, cur, ErrUnknownQuest, func() { GetQuest(0) }, "GetQuest(0)")
747}
748
749// Read functions return copies: changing a returned value or slice does not
750// change stored state. The exported API (see questmaster.gno) has no function
751// or variable that returns *escrow.Quest or an avl tree; package variables
752// are all unexported.
753func TestNoPointerLeak(cur realm, t *testing.T) {
754 resetState()
755 id := post(cur, alice, gnot, "original title")
756 v := GetQuest(id)
757 v.Title = "changed"
758 v.Reward = 1
759 v.State = escrow.Paid
760 uassert.Equal(t, "original title", GetQuest(id).Title)
761 uassert.Equal(t, gnot, GetQuest(id).Reward)
762 uassert.Equal(t, escrow.Open.String(), GetQuest(id).State.String())
763
764 ids := QuestIDsByPoster(alice, 0, 1)
765 ids[0] = 999999
766 uassert.Equal(t, id, QuestIDsByPoster(alice, 0, 1)[0])
767
768 tot := GetTotals()
769 tot.Locked = 0
770 uassert.NotEqual(t, int64(0), GetTotals().Locked)
771}
772
773// Lists: newest first, offset, and a hard cap of MaxPageSize per call.
774func TestLists(cur realm, t *testing.T) {
775 resetState()
776 var mine []uint64
777 for i := 0; i < MaxPageSize+5; i++ {
778 mine = append(mine, post(cur, dave, gnot, "bulk"))
779 }
780 first := QuestIDsByPoster(dave, 0, 1000)
781 uassert.Equal(t, MaxPageSize, len(first), "capped")
782 uassert.Equal(t, mine[len(mine)-1], first[0], "newest first")
783 second := QuestIDsByPoster(dave, MaxPageSize, 1000)
784 uassert.Equal(t, 5, len(second))
785 uassert.Equal(t, mine[0], second[4], "oldest last")
786 uassert.Equal(t, 3, len(QuestIDsByPoster(dave, 0, 3)))
787 uassert.Equal(t, MaxPageSize, len(QuestIDsByPoster(dave, -5, 0)), "bad offset/limit fall back to defaults")
788 uassert.Equal(t, 0, len(QuestIDsByPoster(dave, 10_000, 10)))
789 uassert.Equal(t, MaxPageSize+5, CountByPoster(dave))
790 uassert.Equal(t, 0, len(QuestIDsByBuilder(testutils.TestAddress("nobody"), 0, 10)))
791 uassert.Equal(t, 0, CountByBuilder(testutils.TestAddress("nobody")))
792 uassert.Equal(t, MaxPageSize, len(AllQuestIDs(0, 0)))
793 uassert.Equal(t, GetTotals().Quests, AllQuestIDs(0, 1)[0])
794
795 // tidy up so later tests see fewer open quests
796 testing.SetRealm(testing.NewUserRealm(dave))
797 testing.SetOriginSend(nil)
798 for _, id := range mine {
799 CancelQuest(cross(cur), id)
800 }
801 checkInvariants(t, "lists")
802}
803
804// Case 12: a long mixed run over many quests and users. After every step the
805// realm balance equals the sum of rewards still held, equals the locked
806// total, and posted == locked + paid + refunded. Coins are conserved across
807// users and the realm.
808func TestMixedRunInvariant(cur realm, t *testing.T) {
809 resetState()
810 users := []address{alice, bob, carol, dave}
811 start := int64(0)
812 for _, u := range users {
813 start += bal(u)
814 }
815 start += bal(realmAddr)
816 issued := int64(0)
817
818 seed := uint64(42)
819 rnd := func(n int) int {
820 seed = seed*6364136223846793005 + 1442695040888963407
821 return int((seed >> 33) % uint64(n))
822 }
823 var ids []uint64
824 done := map[string]int{}
825
826 for step := 0; step < 300; step++ {
827 var id uint64
828 var active []uint64
829 for _, x := range ids {
830 if !GetQuest(x).State.IsFinal() {
831 active = append(active, x)
832 }
833 }
834 if len(active) > 0 && rnd(8) != 0 {
835 id = active[rnd(len(active))] // mostly quests still in play
836 } else if len(ids) > 0 {
837 id = ids[rnd(len(ids))] // sometimes a finished one (must fail)
838 }
839 action := rnd(10)
840 if len(active) < 3 || action == 0 {
841 reward := gnot + int64(rnd(5))*250_000
842 ids = append(ids, post(cur, users[rnd(len(users))], reward, "mixed"))
843 issued += reward
844 done["post"]++
845 checkInvariants(t, "mixed post")
846 continue
847 }
848 q := GetQuest(id)
849 // pick a legal actor most of the time, a random one otherwise
850 poster, builder := q.Poster, q.Builder
851 pick := func(want address) address {
852 if rnd(8) == 0 || want == "" {
853 return users[rnd(len(users))]
854 }
855 return want
856 }
857 var name string
858 var fn func()
859 switch q.State {
860 case escrow.Open:
861 if rnd(4) == 0 {
862 testing.SetRealm(testing.NewUserRealm(pick(poster)))
863 testing.SetOriginSend(nil)
864 name, fn = "cancel", func() { CancelQuest(cross(cur), id) }
865 } else {
866 testing.SetRealm(testing.NewUserRealm(users[rnd(len(users))]))
867 testing.SetOriginSend(nil)
868 name, fn = "claim", func() { ClaimQuest(cross(cur), id) }
869 }
870 case escrow.Claimed:
871 switch rnd(5) {
872 case 4:
873 testing.SetRealm(testing.NewUserRealm(pick(poster)))
874 testing.SetOriginSend(nil)
875 name, fn = "close", func() { CancelQuest(cross(cur), id) }
876 case 0:
877 testing.SetRealm(testing.NewUserRealm(pick(builder)))
878 testing.SetOriginSend(nil)
879 name, fn = "unclaim", func() { UnclaimQuest(cross(cur), id) }
880 case 1:
881 testing.SkipHeights(q.WorkDeadline - runtime.ChainHeight() + 1)
882 testing.SetRealm(testing.NewUserRealm(users[rnd(len(users))]))
883 testing.SetOriginSend(nil)
884 name, fn = "release", func() { ReleaseQuest(cross(cur), id) }
885 default:
886 testing.SetRealm(testing.NewUserRealm(pick(builder)))
887 testing.SetOriginSend(nil)
888 name, fn = "submit", func() { SubmitWork(cross(cur), id, link) }
889 }
890 case escrow.Submitted:
891 switch k := rnd(5); {
892 case k == 4:
893 testing.SetRealm(testing.NewUserRealm(pick(poster)))
894 testing.SetOriginSend(nil)
895 name, fn = "close", func() { CancelQuest(cross(cur), id) }
896 case k == 0 || (k < 3 && runtime.ChainHeight() > q.ReviewDeadline):
897 testing.SetRealm(testing.NewUserRealm(pick(poster)))
898 testing.SetOriginSend(nil)
899 name, fn = "approve", func() { ApproveWork(cross(cur), id) }
900 case k < 3:
901 testing.SetRealm(testing.NewUserRealm(pick(poster)))
902 testing.SetOriginSend(nil)
903 name, fn = "reject", func() { RejectWork(cross(cur), id, "again") }
904 default:
905 testing.SkipHeights(q.ReviewDeadline - runtime.ChainHeight() + 1)
906 testing.SetRealm(testing.NewUserRealm(pick(builder)))
907 testing.SetOriginSend(nil)
908 name, fn = "timeout", func() { ClaimPayout(cross(cur), id) }
909 }
910 default:
911 testing.SetRealm(testing.NewUserRealm(pick(poster)))
912 testing.SetOriginSend(nil)
913 name, fn = "final-cancel", func() { CancelQuest(cross(cur), id) }
914 }
915 before := takeSnapshot()
916 r := revive(fn)
917 if r != nil {
918 sameSnapshot(t, before, takeSnapshot(), "failed "+name)
919 done["failed"]++
920 } else {
921 done[name]++
922 if q.Closing && (name == "unclaim" || name == "release" || name == "reject") {
923 done["closed-refund"]++
924 }
925 }
926 checkInvariants(t, name)
927
928 total := bal(realmAddr)
929 for _, u := range users {
930 total += bal(u)
931 }
932 if total != start+issued {
933 t.Fatalf("step %d %s: coins not conserved: %d != %d", step, name, total, start+issued)
934 }
935 }
936 for _, k := range []string{"post", "claim", "cancel", "unclaim", "release", "submit", "approve", "reject", "timeout", "failed", "close", "closed-refund"} {
937 if done[k] == 0 {
938 t.Errorf("mixed run never did %q: %v", k, done)
939 }
940 }
941 println("mixed run moves:", done)
942}
943
944func containsID(ids []uint64, id uint64) bool {
945 for _, x := range ids {
946 if x == id {
947 return true
948 }
949 }
950 return false
951}