fairdrop.gno
14.77 Kb · 480 lines
1package fairdrop
2
3// FairDrop — a commit–reveal raffle board for gno.land.
4//
5// An organizer opens a draw with a prize and a number of winners. Entrants
6// seal a ticket by submitting only a hash of a secret they generated locally;
7// once entries close they reveal the secret, the realm re-hashes it against
8// the seal, and when the reveal window ends anyone can trigger the draw. The
9// seed is folded from the revealed secrets in address order, so every winner
10// can be recomputed from public on-chain data — see Render("event/<id>/verify").
11//
12// The pure mechanics live in gno.land/p/fairdrop/fairness and are imported
13// here; this realm owns the lifecycle, the storage and the pages.
14
15import (
16 "chain"
17 "chain/runtime"
18 "chain/runtime/unsafe"
19 "strconv"
20 "time"
21
22 "gno.land/p/g1k6cl2huxpps9fxls8tqyxknvl7fgq9hua3f2yt/fairness"
23)
24
25const (
26 // RealmPath is this realm's own path and must equal the module line in
27 // gnomod.toml (scripts/check.sh verifies that). It is part of every seal's
28 // domain, so a seal made for this board cannot be replayed against another.
29 RealmPath = "gno.land/r/g1k6cl2huxpps9fxls8tqyxknvl7fgq9hua3f2yt/fairdrop"
30
31 // PackagePath is the reusable engine this realm imports.
32 PackagePath = "gno.land/p/g1k6cl2huxpps9fxls8tqyxknvl7fgq9hua3f2yt/fairness"
33
34 PhaseOpen = "open" // entries are being sealed
35 PhaseReveal = "reveal" // entries closed, secrets being revealed
36 PhaseDrawable = "drawable" // reveal window over, waiting for Draw
37 PhaseDrawn = "drawn" // winners recorded
38 PhaseCancelled = "cancelled" // voided by the organizer before entries closed
39
40 // MaxSlots caps winners per event so a draw stays cheap to compute.
41 MaxSlots = 100
42 // MaxWeightCap caps organizer-granted ticket weight per address.
43 MaxWeightCap = 100
44 // MinWindowSeconds is the shortest window an event may open or reveal for.
45 MinWindowSeconds = 30
46 // MaxWindowSeconds is the longest window (30 days).
47 MaxWindowSeconds = 30 * 24 * 60 * 60
48
49 MaxTitleLen = 80
50 MaxPrizeLen = 240
51)
52
53// Event is one draw.
54type Event struct {
55 ID uint64
56 Creator address
57 Title string
58 Prize string
59 Slots int
60 MaxWeight uint64
61 OpensAt int64
62 ClosesAt int64
63 RevealEndsAt int64
64
65 // Roster holds the sealed tickets in canonical (ascending address) order;
66 // fairness.Insert maintains that order and refuses a second ticket per
67 // address. Secrets are filled in by Reveal and are public by design — they
68 // are what makes the seed checkable.
69 Roster []fairness.Ticket
70
71 // vouches are organizer-granted ticket weights, address string -> weight.
72 // A voucher must land before that address seals its ticket.
73 vouches map[string]uint64
74
75 Seed string
76 DrawnAt int64
77 DrawnHeight int64
78 Cancelled bool
79}
80
81var (
82 events = []*Event{}
83 byID = map[uint64]*Event{}
84 nextID uint64
85)
86
87// ---------------------------------------------------------------- lifecycle
88
89// Create opens a draw and returns its id. The organizer pays nothing: FairDrop
90// never holds funds, it only records the draw.
91func Create(cur realm, title string, prize string, slots int, maxWeight int, regSeconds int, revealSeconds int) uint64 {
92 runtime.AssertOriginCall()
93 creator := unsafe.OriginCaller()
94
95 title = trimSpace(title)
96 prize = trimSpace(prize)
97 require(title != "", "title is required")
98 require(len(title) <= MaxTitleLen, "title is too long (max "+strconv.Itoa(MaxTitleLen)+" bytes)")
99 require(prize != "", "prize is required")
100 require(len(prize) <= MaxPrizeLen, "prize is too long (max "+strconv.Itoa(MaxPrizeLen)+" bytes)")
101 require(slots >= 1 && slots <= MaxSlots, "winners must be between 1 and "+strconv.Itoa(MaxSlots))
102 require(maxWeight >= 1 && maxWeight <= MaxWeightCap, "max weight must be between 1 and "+strconv.Itoa(MaxWeightCap))
103 require(regSeconds >= MinWindowSeconds && regSeconds <= MaxWindowSeconds,
104 "entry window must be between "+strconv.Itoa(MinWindowSeconds)+"s and "+strconv.Itoa(MaxWindowSeconds)+"s")
105 require(revealSeconds >= MinWindowSeconds && revealSeconds <= MaxWindowSeconds,
106 "reveal window must be between "+strconv.Itoa(MinWindowSeconds)+"s and "+strconv.Itoa(MaxWindowSeconds)+"s")
107
108 now := time.Now().Unix()
109 nextID++
110 e := &Event{
111 ID: nextID,
112 Creator: creator,
113 Title: title,
114 Prize: prize,
115 Slots: slots,
116 MaxWeight: uint64(maxWeight),
117 OpensAt: now,
118 ClosesAt: now + int64(regSeconds),
119 RevealEndsAt: now + int64(regSeconds) + int64(revealSeconds),
120 Roster: []fairness.Ticket{},
121 vouches: map[string]uint64{},
122 }
123 events = append(events, e)
124 byID[e.ID] = e
125
126 chain.Emit("EventCreated", "id", uitoa(e.ID), "creator", creator.String(), "slots", strconv.Itoa(slots))
127 println("FairDrop event #" + uitoa(e.ID) + " opened: " + title)
128 return e.ID
129}
130
131// Vouch grants an address extra ticket weight before it seals its ticket. One
132// ticket per address is the floor; a vouch is how an organizer recognises a
133// member who should carry more weight (a role holder, an allowlisted guest).
134// Weight cannot be granted after the address has sealed, because the sealed
135// digest commits to the weight.
136func Vouch(cur realm, eventID uint64, who string, weight int) {
137 runtime.AssertOriginCall()
138 caller := unsafe.OriginCaller()
139 e := mustEvent(eventID)
140
141 require(!e.Cancelled, "event is cancelled")
142 require(e.phase(nowUnix()) == PhaseOpen, "event is not open for entries")
143 require(caller == e.Creator, "only the organizer can vouch")
144
145 id := normalizeAddress(who)
146 require(id != "", "address is required")
147 require(weight >= 1 && uint64(weight) <= e.MaxWeight, "weight must be between 1 and "+uitoa(e.MaxWeight))
148 require(fairness.Find(e.Roster, id) < 0, "address already sealed a ticket; weight is now fixed")
149
150 e.vouches[id] = uint64(weight)
151 chain.Emit("Vouched", "id", uitoa(e.ID), "who", id, "weight", strconv.Itoa(weight))
152}
153
154// Register seals a ticket: commit is the hex SHA-256 of the entrant's secret
155// bound to their address, this event and their weight. Weight must be 1 unless
156// the organizer vouched for more.
157func Register(cur realm, eventID uint64, commit string, weight int) {
158 runtime.AssertOriginCall()
159 caller := unsafe.OriginCaller()
160 e := mustEvent(eventID)
161
162 require(!e.Cancelled, "event is cancelled")
163 require(e.phase(nowUnix()) == PhaseOpen, "entries are closed")
164
165 id := caller.String()
166 commit = fairness.NormalizeDigest(commit)
167 require(fairness.IsDigest(commit), "commit must be a 64-character hex sha256 digest")
168 require(weight >= 1, "weight must be at least 1")
169
170 w := uint64(weight)
171 require(w <= e.MaxWeight, "weight exceeds this event's cap of "+uitoa(e.MaxWeight))
172 if v, ok := e.vouches[id]; ok {
173 require(w <= v, "weight exceeds the organizer's vouch of "+uitoa(v))
174 } else {
175 require(w == 1, "one ticket per address unless the organizer vouched for more")
176 }
177
178 roster, err := fairness.Insert(e.Roster, fairness.Ticket{
179 ID: id,
180 Weight: w,
181 Commit: commit,
182 })
183 require(err == nil, errString(err))
184 e.Roster = roster
185
186 chain.Emit("TicketSealed", "id", uitoa(e.ID), "entrant", id, "weight", uitoa(w))
187 println("ticket sealed for event #" + uitoa(e.ID) + " by " + id)
188}
189
190// Reveal opens a seal. It is accepted only inside the reveal window and only
191// when the secret re-hashes to the seal already on chain.
192func Reveal(cur realm, eventID uint64, secret string) {
193 runtime.AssertOriginCall()
194 caller := unsafe.OriginCaller()
195 e := mustEvent(eventID)
196
197 require(!e.Cancelled, "event is cancelled")
198 require(e.phase(nowUnix()) == PhaseReveal, "reveal window is not open")
199
200 idx := fairness.Find(e.Roster, caller.String())
201 require(idx >= 0, "no sealed ticket for this address")
202
203 t := e.Roster[idx]
204 require(t.Secret == "", "ticket already revealed")
205 require(fairness.ValidSecret(secret), "secret must be printable ASCII, "+
206 strconv.Itoa(fairness.MinSecretLen)+"-"+strconv.Itoa(fairness.MaxSecretLen)+" bytes")
207
208 require(fairness.VerifySeal(t.Commit, e.Domain(), t.ID, int64(t.Weight), secret),
209 "secret does not open this ticket's seal")
210
211 e.Roster[idx].Secret = secret
212 chain.Emit("TicketRevealed", "id", uitoa(e.ID), "entrant", t.ID)
213 println("ticket revealed for event #" + uitoa(e.ID) + " by " + t.ID)
214}
215
216// Draw records the winners. It is permissionless on purpose: once the reveal
217// window is over the result is already determined by public data, so anyone —
218// entrant, organizer or passer-by — may pay the gas to write it down.
219func Draw(cur realm, eventID uint64) {
220 runtime.AssertOriginCall()
221 e := mustEvent(eventID)
222
223 require(!e.Cancelled, "event is cancelled")
224 require(e.Seed == "", "event already drawn")
225
226 now := nowUnix()
227 ph := e.phase(now)
228 // The result is fixed as soon as everyone who sealed has revealed; waiting
229 // for the deadline then would only delay a foregone conclusion.
230 allRevealed := len(e.Roster) > 0 && revealedCount(e) == len(e.Roster)
231 require(ph == PhaseDrawable || (ph == PhaseReveal && allRevealed),
232 "draw opens after the reveal window (or once every sealed ticket has revealed)")
233
234 eligible := make([]fairness.Ticket, 0, len(e.Roster))
235 leaves := make([]string, 0, len(e.Roster))
236 for i := 0; i < len(e.Roster); i++ {
237 t := e.Roster[i]
238 if t.Secret == "" {
239 continue
240 }
241 eligible = append(eligible, t)
242 leaves = append(leaves, fairness.Leaf(t.Commit, t.Secret))
243 }
244
245 seed := fairness.Seed(e.Domain(), runtime.ChainID(), e.ID, leaves)
246 winners := fairness.Draw(seed, eligible, e.Slots)
247
248 for rank := 0; rank < len(winners); rank++ {
249 idx := fairness.Find(e.Roster, winners[rank])
250 if idx >= 0 {
251 e.Roster[idx].Rank = rank + 1
252 }
253 }
254
255 e.Seed = seed
256 e.DrawnAt = now
257 e.DrawnHeight = runtime.ChainHeight()
258
259 chain.Emit("Drawn", "id", uitoa(e.ID), "seed", seed, "winners", strconv.Itoa(len(winners)))
260 println("event #" + uitoa(e.ID) + " drawn, seed " + seed)
261}
262
263// Cancel voids a draw before entries close. After close the entries are
264// committed and only the draw can settle them.
265func Cancel(cur realm, eventID uint64) {
266 runtime.AssertOriginCall()
267 caller := unsafe.OriginCaller()
268 e := mustEvent(eventID)
269
270 require(caller == e.Creator, "only the organizer can cancel")
271 require(!e.Cancelled, "event already cancelled")
272 require(e.Seed == "", "event already drawn")
273 require(e.phase(nowUnix()) == PhaseOpen, "entries are closed; the draw must settle this event")
274
275 e.Cancelled = true
276 chain.Emit("EventCancelled", "id", uitoa(e.ID))
277}
278
279// ------------------------------------------------------------------- reads
280
281// EventCount is the number of events ever opened.
282func EventCount() int {
283 return len(events)
284}
285
286// Domain is this event's seal domain. It is stamped into every seal, so a seal
287// cannot be moved between events, and into the seed, so a seed cannot either.
288func (e *Event) Domain() string {
289 return RealmPath + "#" + uitoa(e.ID)
290}
291
292// IDString renders the event id.
293func (e *Event) IDString() string {
294 return uitoa(e.ID)
295}
296
297// Phase returns the lifecycle phase at the given unix time.
298func (e *Event) Phase(now int64) string {
299 return e.phase(now)
300}
301
302func (e *Event) phase(now int64) string {
303 if e.Cancelled {
304 return PhaseCancelled
305 }
306 if e.Seed != "" {
307 return PhaseDrawn
308 }
309 if now < e.ClosesAt {
310 return PhaseOpen
311 }
312 if now < e.RevealEndsAt {
313 return PhaseReveal
314 }
315 return PhaseDrawable
316}
317
318// Revealed returns how many sealed tickets have been revealed.
319func (e *Event) Revealed() int {
320 return revealedCount(e)
321}
322
323// Entries returns the number of sealed tickets.
324func (e *Event) Entries() int {
325 return len(e.Roster)
326}
327
328// Winner is one recorded winner, resolved from the roster at render time.
329type Winner struct {
330 Rank int
331 Entrant string
332 Weight uint64
333 Commit string
334 Secret string
335}
336
337// Winners returns the recorded winners in rank order.
338func (e *Event) Winners() []Winner {
339 out := []Winner{}
340 for i := 0; i < len(e.Roster); i++ {
341 t := e.Roster[i]
342 if t.Rank > 0 {
343 out = append(out, Winner{
344 Rank: t.Rank,
345 Entrant: t.ID,
346 Weight: t.Weight,
347 Commit: t.Commit,
348 Secret: t.Secret,
349 })
350 }
351 }
352 // Rank order: insertion sort, rosters are small and ranks are unique.
353 for i := 1; i < len(out); i++ {
354 for j := i; j > 0 && out[j].Rank < out[j-1].Rank; j-- {
355 out[j], out[j-1] = out[j-1], out[j]
356 }
357 }
358 return out
359}
360
361// Proof returns the draw's verifiable inputs as a JSON object, so an
362// off-chain checker can recompute the seed and the winners from chain state
363// without trusting this realm's pages. Every value is an address, a hex
364// digest or a printable-ASCII secret, so the JSON needs no escaping.
365func Proof(id uint64) string {
366 e := mustEvent(id)
367
368 out := "{\"event\":" + uitoa(e.ID)
369 out += ",\"domain\":\"" + e.Domain() + "\""
370 out += ",\"chain_id\":\"" + runtime.ChainID() + "\""
371 out += ",\"slots\":" + strconv.Itoa(e.Slots)
372 out += ",\"seed\":\"" + e.Seed + "\""
373 out += ",\"entrants\":["
374 for i := 0; i < len(e.Roster); i++ {
375 t := e.Roster[i]
376 if i > 0 {
377 out += ","
378 }
379 out += "{\"address\":\"" + t.ID + "\""
380 out += ",\"weight\":" + uitoa(t.Weight)
381 out += ",\"seal\":\"" + t.Commit + "\""
382 out += ",\"secret\":\"" + t.Secret + "\""
383 out += ",\"rank\":" + strconv.Itoa(t.Rank) + "}"
384 }
385 out += "]}"
386 return out
387}
388
389// AcceptedLeaves returns the seed inputs in fold order, for verification.
390func (e *Event) AcceptedLeaves() []string {
391 out := []string{}
392 for i := 0; i < len(e.Roster); i++ {
393 t := e.Roster[i]
394 if t.Secret != "" {
395 out = append(out, fairness.Leaf(t.Commit, t.Secret))
396 }
397 }
398 return out
399}
400
401// GetEvent looks an event up by id, or nil.
402func GetEvent(id uint64) *Event {
403 e, ok := byID[id]
404 if !ok {
405 return nil
406 }
407 return e
408}
409
410// ---------------------------------------------------------------- internals
411
412func revealedCount(e *Event) int {
413 n := 0
414 for i := 0; i < len(e.Roster); i++ {
415 if e.Roster[i].Secret != "" {
416 n++
417 }
418 }
419 return n
420}
421
422func mustEvent(id uint64) *Event {
423 e, ok := byID[id]
424 if !ok {
425 panic("event #" + uitoa(id) + " does not exist")
426 }
427 return e
428}
429
430func nowUnix() int64 {
431 return time.Now().Unix()
432}
433
434func require(ok bool, msg string) {
435 if !ok {
436 panic(msg)
437 }
438}
439
440func errString(err error) string {
441 if err == nil {
442 return ""
443 }
444 return err.Error()
445}
446
447func uitoa(u uint64) string {
448 return strconv.FormatUint(u, 10)
449}
450
451func trimSpace(s string) string {
452 start := 0
453 end := len(s)
454 for start < end && (s[start] == ' ' || s[start] == '\t' || s[start] == '\n' || s[start] == '\r') {
455 start++
456 }
457 for end > start && (s[end-1] == ' ' || s[end-1] == '\t' || s[end-1] == '\n' || s[end-1] == '\r') {
458 end--
459 }
460 return s[start:end]
461}
462
463// normalizeAddress accepts the shape of a bech32 gno address (g1 + 38
464// lower-case alphanumerics) as typed. It deliberately does not convert through
465// the address type: a bad checksum would panic, and vouching for an address
466// nobody holds is harmless — the vouch just never matches a ticket.
467func normalizeAddress(s string) string {
468 s = trimSpace(s)
469 if len(s) != 40 || s[0] != 'g' || s[1] != '1' {
470 return ""
471 }
472 for i := 0; i < len(s); i++ {
473 c := s[i]
474 if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') {
475 continue
476 }
477 return ""
478 }
479 return s
480}