render.gno
18.87 Kb · 501 lines
1package fairdrop
2
3// gnoweb pages. Every page is derived from on-chain state alone, so the same
4// URL renders the same thing for every visitor.
5
6import (
7 "chain/runtime"
8 "strconv"
9 "strings"
10 "time"
11
12 "gno.land/p/g1k6cl2huxpps9fxls8tqyxknvl7fgq9hua3f2yt/fairness"
13)
14
15// gnowebURL turns a package path into the path part of its gnoweb URL by
16// dropping the chain domain: gno.land/r/x/y -> /r/x/y.
17func gnowebURL(pkgPath string) string {
18 i := strings.Index(pkgPath, "/")
19 if i < 0 {
20 return "/" + pkgPath
21 }
22 return pkgPath[i:]
23}
24
25// Render dispatches gnoweb paths:
26//
27// "" board home: open and past draws
28// "event/<id>" one draw, with the actions it accepts right now
29// "event/<id>/verify" the seed's inputs and how to recompute it
30// "event/<id>/receipt/<rank>"
31// "create" how to open a draw
32func Render(path string) string {
33 parts := strings.Split(path, "/")
34
35 switch {
36 case path == "":
37 return renderHome()
38 case parts[0] == "create" && len(parts) == 1:
39 return renderCreate()
40 case parts[0] == "event" && len(parts) == 2:
41 id, ok := parseUint(parts[1])
42 if !ok {
43 return renderNotFound(path)
44 }
45 return renderEvent(id)
46 case parts[0] == "event" && len(parts) == 3 && parts[2] == "verify":
47 id, ok := parseUint(parts[1])
48 if !ok {
49 return renderNotFound(path)
50 }
51 return renderVerify(id)
52 case parts[0] == "event" && len(parts) == 4 && parts[2] == "receipt":
53 id, ok := parseUint(parts[1])
54 if !ok {
55 return renderNotFound(path)
56 }
57 rank, ok := parseUint(parts[3])
58 if !ok {
59 return renderNotFound(path)
60 }
61 return renderReceipt(id, int(rank))
62 }
63 return renderNotFound(path)
64}
65
66// ------------------------------------------------------------------- home
67
68func renderHome() string {
69 var b strings.Builder
70
71 b.WriteString("# FairDrop\n\n")
72 b.WriteString("Raffles whose result anyone can check.\n\n")
73 b.WriteString("An organizer opens a draw with a prize and a number of winners. Entrants ")
74 b.WriteString("seal a ticket by publishing only a hash of a secret they generated locally. ")
75 b.WriteString("Once entries close they reveal the secret, this realm re-hashes it against the ")
76 b.WriteString("seal, and when the reveal window ends **anyone** can press the draw. The winners ")
77 b.WriteString("come from a seed folded out of the revealed secrets in address order, so every ")
78 b.WriteString("result can be recomputed from public data — the page for each draw ends with the ")
79 b.WriteString("exact inputs to do it.\n\n")
80
81 b.WriteString("### Why it is fair\n\n")
82 b.WriteString("| Step | Who acts | What is fixed at that moment |\n")
83 b.WriteString("|---|---|---|\n")
84 b.WriteString("| 1. Seal | each entrant | their secret and ticket weight, as a hash — unreadable until later |\n")
85 b.WriteString("| 2. Close | nobody (block time) | the roster and every seal; nothing can be added or changed |\n")
86 b.WriteString("| 3. Reveal | each entrant | the preimage; a reveal that does not open its own seal is rejected |\n")
87 b.WriteString("| 4. Draw | anyone | the winners are a pure function of the revealed secrets |\n\n")
88 b.WriteString("The organizer cannot add, drop or re-weight an entry after it is sealed, cannot ")
89 b.WriteString("read the secrets before the close, and cannot see or influence the seed before ")
90 b.WriteString("the reveal window. An entrant who never reveals forfeits their own ticket — it ")
91 b.WriteString("cannot promote anyone else.\n\n")
92
93 b.WriteString("## Draws\n\n")
94 if len(events) == 0 {
95 b.WriteString("No draw has been opened yet. ")
96 b.WriteString("[Open the first one](" + gnowebURL(RealmPath) + ":create) — it takes one transaction.\n")
97 return b.String()
98 }
99
100 b.WriteString("| draw | prize | entries | winners | phase | closes |\n")
101 b.WriteString("|---|---|---|---|---|---|\n")
102 now := nowUnix()
103 for i := len(events) - 1; i >= 0; i-- {
104 e := events[i]
105 b.WriteString("| [#" + e.IDString() + " " + cell(e.Title) + "](" + gnowebURL(RealmPath) + ":event/" + e.IDString() + ") ")
106 b.WriteString("| " + cell(e.Prize) + " ")
107 b.WriteString("| " + strconv.Itoa(e.Entries()) + " sealed / " + strconv.Itoa(e.Revealed()) + " revealed ")
108 b.WriteString("| " + strconv.Itoa(e.Slots) + " ")
109 b.WriteString("| " + phaseBadge(e.phase(now)) + " ")
110 b.WriteString("| " + closeLine(e, now) + " |\n")
111 }
112
113 b.WriteString("\n[Open a draw](" + gnowebURL(RealmPath) + ":create) · ")
114 b.WriteString("the reusable engine is [" + PackagePath + "](" + gnowebURL(PackagePath) + ")\n")
115 return b.String()
116}
117
118// ------------------------------------------------------------------ event
119
120func renderEvent(id uint64) string {
121 e := GetEvent(id)
122 if e == nil {
123 return renderNotFound("event/" + uitoa(id))
124 }
125 now := nowUnix()
126 ph := e.phase(now)
127
128 var b strings.Builder
129
130 b.WriteString("# Draw #" + e.IDString() + " — " + e.Title + "\n\n")
131 b.WriteString("**Prize:** " + e.Prize + "\n\n")
132 b.WriteString("**Organizer:** `" + e.Creator.String() + "`\n\n")
133 b.WriteString("**Winners:** " + strconv.Itoa(e.Slots) +
134 " · **Max weight per ticket:** " + uitoa(e.MaxWeight) +
135 " · **Phase:** " + phaseBadge(ph) + "\n\n")
136
137 b.WriteString("### Timeline\n\n")
138 b.WriteString("| phase | starts (UTC / KST) | ends (UTC / KST) | now |\n")
139 b.WriteString("|---|---|---|---|\n")
140 b.WriteString("| entries | " + stamp(e.OpensAt) + " | " + stamp(e.ClosesAt) + " | " + phaseTick(ph == PhaseOpen) + " |\n")
141 b.WriteString("| reveal | " + stamp(e.ClosesAt) + " | " + stamp(e.RevealEndsAt) + " | " + phaseTick(ph == PhaseReveal) + " |\n")
142 b.WriteString("| draw | " + stamp(e.RevealEndsAt) + " | anyone may trigger | " + phaseTick(ph == PhaseDrawn) + " |\n\n")
143
144 if ph == PhaseOpen {
145 b.WriteString("Entries close in **" + left(e.ClosesAt, now) + "**")
146 if e.Entries() > 0 {
147 b.WriteString(", with " + strconv.Itoa(e.Entries()) + " sealed ticket(s) so far")
148 }
149 b.WriteString(".\n\n")
150 }
151 if ph == PhaseReveal {
152 b.WriteString("Reveals close in **" + left(e.RevealEndsAt, now) + "** — " +
153 strconv.Itoa(e.Revealed()) + " of " + strconv.Itoa(e.Entries()) + " sealed tickets revealed.\n\n")
154 }
155 if ph == PhaseDrawable {
156 b.WriteString("The reveal window is over. The result is fixed by the revealed secrets — ")
157 b.WriteString("anyone can write it down with `Draw(" + e.IDString() + ")`.\n\n")
158 }
159
160 renderActions(&b, e, ph)
161 renderRoster(&b, e, ph)
162 if e.Seed != "" {
163 renderResult(&b, e)
164 }
165 return b.String()
166}
167
168func renderActions(b *strings.Builder, e *Event, ph string) {
169 b.WriteString("### Actions\n\n")
170 if ph == PhaseOpen {
171 b.WriteString("**Enter.** Generate a secret locally and publish only its seal:\n\n")
172 b.WriteString("```sh\n")
173 b.WriteString("# 1. a secret only you know (32 random bytes, hex)\n")
174 b.WriteString("SECRET=$(openssl rand -hex 32)\n\n")
175 b.WriteString("# 2. its seal = sha256(\"fairdrop/seal/v1|" + e.Domain() + "|<your g1 address>|<weight>|$SECRET\")\n")
176 b.WriteString("SEAL=$(printf 'fairdrop/seal/v1|" + e.Domain() + "|%s|1|%s' \\\n")
177 b.WriteString(" g1youraddress... \"$SECRET\" | sha256sum | cut -d' ' -f1)\n\n")
178 b.WriteString("# 3. seal the ticket (weight 1 unless the organizer vouched for more)\n")
179 b.WriteString("gnokey maketx call -pkgpath " + RealmPath + " -func Register \\\n")
180 b.WriteString(" -args " + e.IDString() + " -args \"$SEAL\" -args 1 \\\n")
181 b.WriteString(" -gas-fee 1000000ugnot -gas-wanted 5000000 -broadcast \\\n")
182 b.WriteString(" -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY\n\n")
183 b.WriteString("# keep $SECRET until the reveal window\n")
184 b.WriteString("```\n\n")
185 b.WriteString("Read the seal back on chain before the window closes: it is listed below. ")
186 b.WriteString("If it is wrong, that ticket cannot be revealed and does not count.\n\n")
187 } else if ph == PhaseReveal {
188 b.WriteString("**Reveal.** Publish the secret behind your seal:\n\n")
189 b.WriteString("```sh\n")
190 b.WriteString("gnokey maketx call -pkgpath " + RealmPath + " -func Reveal \\\n")
191 b.WriteString(" -args " + e.IDString() + " -args \"$SECRET\" \\\n")
192 b.WriteString(" -gas-fee 1000000ugnot -gas-wanted 5000000 -broadcast \\\n")
193 b.WriteString(" -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY\n")
194 b.WriteString("```\n\n")
195 } else if ph == PhaseDrawable {
196 b.WriteString("**Draw.** Write the determined result on chain — anyone can do it:\n\n")
197 b.WriteString("```sh\n")
198 b.WriteString("gnokey maketx call -pkgpath " + RealmPath + " -func Draw \\\n")
199 b.WriteString(" -args " + e.IDString() + " \\\n")
200 b.WriteString(" -gas-fee 1000000ugnot -gas-wanted 5000000 -broadcast \\\n")
201 b.WriteString(" -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY\n")
202 b.WriteString("```\n\n")
203 } else if ph == PhaseDrawn {
204 b.WriteString("This draw is settled. [Verify it](" + gnowebURL(RealmPath) + ":event/" + e.IDString() + "/verify).\n\n")
205 } else {
206 b.WriteString("This draw was cancelled by its organizer before entries closed.\n\n")
207 }
208}
209
210func renderRoster(b *strings.Builder, e *Event, ph string) {
211 b.WriteString("### Tickets (" + strconv.Itoa(e.Entries()) + ")\n\n")
212 if len(e.Roster) == 0 {
213 b.WriteString("No ticket sealed yet.\n\n")
214 return
215 }
216 b.WriteString("| # | entrant | weight | seal | status |\n")
217 b.WriteString("|---|---|---|---|---|\n")
218 for i := 0; i < len(e.Roster); i++ {
219 t := e.Roster[i]
220 status := "sealed"
221 if t.Secret != "" {
222 status = "revealed"
223 } else if e.phase(nowUnix()) == PhaseDrawable && e.Seed == "" {
224 status = "forfeited (no reveal)"
225 } else if e.Seed != "" && t.Secret == "" {
226 status = "forfeited (no reveal)"
227 }
228 if t.Rank > 0 {
229 status = "**winner #" + strconv.Itoa(t.Rank) + "**"
230 }
231 b.WriteString("| " + strconv.Itoa(i+1) + " | `" + t.ID + "` | " + uitoa(t.Weight) +
232 " | `" + short(t.Commit) + "` | " + status + " |\n")
233 }
234 b.WriteString("\n")
235}
236
237func renderResult(b *strings.Builder, e *Event) {
238 b.WriteString("### Result\n\n")
239 winners := e.Winners()
240 if len(winners) == 0 {
241 b.WriteString("No eligible ticket: nobody revealed, so the draw settled with no winner.\n\n")
242 } else {
243 b.WriteString("| rank | winner | weight | receipt |\n")
244 b.WriteString("|---|---|---|---|\n")
245 for i := 0; i < len(winners); i++ {
246 w := winners[i]
247 b.WriteString("| " + strconv.Itoa(w.Rank) + " | `" + w.Entrant + "` | " + uitoa(w.Weight) +
248 " | [receipt](" + gnowebURL(RealmPath) + ":event/" + e.IDString() + "/receipt/" + strconv.Itoa(w.Rank) + ") |\n")
249 }
250 b.WriteString("\n")
251 }
252 b.WriteString("**Seed:** `" + e.Seed + "`\n\n")
253 b.WriteString("Drawn at " + stamp(e.DrawnAt) + " at block " + strconv.FormatInt(e.DrawnHeight, 10) + ". ")
254 b.WriteString("[Every input of the seed](" + gnowebURL(RealmPath) + ":event/" + e.IDString() + "/verify) is on chain.\n\n")
255}
256
257func renderVerify(id uint64) string {
258 e := GetEvent(id)
259 if e == nil {
260 return renderNotFound("event/" + uitoa(id))
261 }
262 leaves := e.AcceptedLeaves()
263
264 var b strings.Builder
265 b.WriteString("# Verify draw #" + e.IDString() + "\n\n")
266 b.WriteString("**Draw:** #" + e.IDString() + " · **Domain:** `" + e.Domain() + "` · **Chain:** `" + runtime.ChainID() + "`\n\n")
267
268 if e.Seed == "" {
269 b.WriteString("Not drawn yet — there is no seed to verify.\n")
270 return b.String()
271 }
272
273 b.WriteString("**Seed:**\n\n```\n" + e.Seed + "\n```\n\n")
274 b.WriteString("The seed is folded from these inputs, in this exact order (ascending entrant address, ")
275 b.WriteString("revealed tickets only). Each leaf is `seal:secret`.\n\n")
276
277 if len(leaves) == 0 {
278 b.WriteString("_No revealed ticket, so the fold had no leaf._\n\n")
279 } else {
280 b.WriteString("| # | entrant | leaf |\n|---|---|---|\n")
281 n := 0
282 for i := 0; i < len(e.Roster); i++ {
283 if e.Roster[i].Secret == "" {
284 continue
285 }
286 n++
287 b.WriteString("| " + strconv.Itoa(n) + " | `" + e.Roster[i].ID + "` | `" +
288 e.Roster[i].Commit + ":" + e.Roster[i].Secret + "` |\n")
289 }
290 b.WriteString("\n")
291 }
292
293 b.WriteString("### Recompute it yourself\n\n")
294 b.WriteString("The realm hashes this string (one trailing `|` per leaf is included):\n\n")
295 b.WriteString("```\nfairdrop/seed/v1|" + e.Domain() + "|" + runtime.ChainID() + "|" + e.IDString() + "|" + strings.Join(leaves, "|") + "|\n```\n\n")
296 b.WriteString("```python\nimport hashlib\n")
297 b.WriteString("leaves = [" + quoteList(leaves) + "]\n")
298 b.WriteString("payload = \"fairdrop/seed/v1|" + e.Domain() + "|" + runtime.ChainID() + "|" + e.IDString() + "|\" + \"\".join(l + \"|\" for l in leaves)\n")
299 b.WriteString("print(hashlib.sha256(payload.encode()).hexdigest())\n")
300 b.WriteString("# compare with the seed above\n")
301 b.WriteString("```\n\n")
302
303 b.WriteString("The winners are then taken from that seed by [the draw in ")
304 b.WriteString("gno.land/p/fairdrop/fairness](/p/fairdrop/fairness): a SHA-256 counter-mode stream ")
305 b.WriteString("walks the revealed roster in the same order, drawing weighted tickets without ")
306 b.WriteString("replacement until " + strconv.Itoa(e.Slots) + " winner(s) are chosen. ")
307 b.WriteString("`scripts/verify.py` in the project repository reproduces both steps.\n")
308 return b.String()
309}
310
311func renderReceipt(id uint64, rank int) string {
312 e := GetEvent(id)
313 if e == nil {
314 return renderNotFound("event/" + uitoa(id))
315 }
316 if e.Seed == "" {
317 return "# Draw #" + e.IDString() + " has not been drawn yet\n"
318 }
319
320 found := false
321 w := Winner{}
322 all := e.Winners()
323 for i := 0; i < len(all); i++ {
324 if all[i].Rank == rank {
325 w = all[i]
326 found = true
327 break
328 }
329 }
330 if !found {
331 return "# No winner at rank " + strconv.Itoa(rank) + " in draw #" + e.IDString() + "\n"
332 }
333
334 var b strings.Builder
335 b.WriteString("# Receipt — draw #" + e.IDString() + ", rank " + strconv.Itoa(w.Rank) + "\n\n")
336 b.WriteString("**Prize:** " + e.Prize + "\n\n")
337 b.WriteString("**Winner:** `" + w.Entrant + "`\n\n")
338 b.WriteString("**Ticket weight:** " + uitoa(w.Weight) + "\n\n")
339 b.WriteString("**Seal:** `" + w.Commit + "`\n\n")
340 b.WriteString("**Revealed secret:** `" + w.Secret + "`\n\n")
341 b.WriteString("**Seed:** `" + e.Seed + "`\n\n")
342 b.WriteString("**Drawn:** " + stamp(e.DrawnAt) + " · block " + strconv.FormatInt(e.DrawnHeight, 10) + "\n\n")
343 b.WriteString("This ticket took rank " + strconv.Itoa(w.Rank) + " of " +
344 strconv.Itoa(len(e.Winners())) + ", drawn from " + strconv.Itoa(e.Revealed()) +
345 " revealed ticket(s) carrying " + uitoa(fairness.TotalWeight(e.Roster)) + " weight in total. ")
346 b.WriteString("The receipt is checkable twice over: the secret re-hashes to the seal that was ")
347 b.WriteString("on chain before entries closed, and the seed that produced this rank is the fold ")
348 b.WriteString("of every revealed ticket — see [verify](" + gnowebURL(RealmPath) + ":event/" + e.IDString() + "/verify).\n")
349 return b.String()
350}
351
352// ----------------------------------------------------------------- create
353
354func renderCreate() string {
355 var b strings.Builder
356 b.WriteString("# Open a draw\n\n")
357 b.WriteString("One transaction opens a draw. Nothing is escrowed: FairDrop records the draw and ")
358 b.WriteString("its result, it does not hold the prize.\n\n")
359 b.WriteString("```sh\n")
360 b.WriteString("gnokey maketx call -pkgpath " + RealmPath + " -func Create \\\n")
361 b.WriteString(" -args \"Friday community raffle\" \\\n")
362 b.WriteString(" -args \"1 limited edition mug\" \\\n")
363 b.WriteString(" -args 3 \\\n")
364 b.WriteString(" -args 5 \\\n")
365 b.WriteString(" -args 600 \\\n")
366 b.WriteString(" -args 300 \\\n")
367 b.WriteString(" -gas-fee 1000000ugnot -gas-wanted 5000000 -broadcast \\\n")
368 b.WriteString(" -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY\n")
369 b.WriteString("```\n\n")
370 b.WriteString("Arguments: `title`, `prize`, `winners`, `max weight per ticket`, ")
371 b.WriteString("`entry window (seconds)`, `reveal window (seconds)`.\n\n")
372 b.WriteString("Then, optionally, give a known guest more weight **before** they seal:\n\n")
373 b.WriteString("```sh\n")
374 b.WriteString("gnokey maketx call -pkgpath " + RealmPath + " -func Vouch \\\n")
375 b.WriteString(" -args <draw id> -args g1guestaddress... -args 3 \\\n")
376 b.WriteString(" -gas-fee 1000000ugnot -gas-wanted 5000000 -broadcast \\\n")
377 b.WriteString(" -chainid onyx-1 -remote https://rpc.onyx.testnets.gno.land:443 YOUR_KEY\n")
378 b.WriteString("```\n\n")
379 b.WriteString("Rules the realm enforces, not just documents:\n\n")
380 b.WriteString("- one ticket per address; a vouch changes its weight, never the number of entries\n")
381 b.WriteString("- a ticket's weight is sealed into its digest, so it cannot change after sealing\n")
382 b.WriteString("- entries close on block time, not on the organizer's word\n")
383 b.WriteString("- the draw is permissionless and the seed is public\n")
384 return b.String()
385}
386
387func renderNotFound(path string) string {
388 return "# Not found\n\n`" + path + "` is not a page of this realm.\n\n[Back to the board](" + gnowebURL(RealmPath) + ")\n"
389}
390
391// ----------------------------------------------------------------- helpers
392
393func phaseBadge(ph string) string {
394 switch ph {
395 case PhaseOpen:
396 return "**open** — sealing"
397 case PhaseReveal:
398 return "**reveal** — secrets being opened"
399 case PhaseDrawable:
400 return "**drawable** — waiting for a draw"
401 case PhaseDrawn:
402 return "**drawn**"
403 case PhaseCancelled:
404 return "cancelled"
405 }
406 return ph
407}
408
409func phaseTick(active bool) string {
410 if active {
411 return "←"
412 }
413 return ""
414}
415
416func closeLine(e *Event, now int64) string {
417 switch e.phase(now) {
418 case PhaseOpen:
419 return "in " + left(e.ClosesAt, now)
420 case PhaseReveal:
421 return "closed " + left(now, e.ClosesAt) + " ago"
422 case PhaseDrawable:
423 return "closed " + left(now, e.ClosesAt) + " ago"
424 case PhaseDrawn:
425 return "drawn " + left(now, e.DrawnAt) + " ago"
426 case PhaseCancelled:
427 return "cancelled"
428 }
429 return ""
430}
431
432// left renders a positive duration in seconds as "2d 3h", "4h 12m", "3m 40s".
433func left(until int64, from int64) string {
434 d := until - from
435 if d < 0 {
436 d = 0
437 }
438 if d >= 86400 {
439 return strconv.FormatInt(d/86400, 10) + "d " + strconv.FormatInt((d%86400)/3600, 10) + "h"
440 }
441 if d >= 3600 {
442 return strconv.FormatInt(d/3600, 10) + "h " + strconv.FormatInt((d%3600)/60, 10) + "m"
443 }
444 if d >= 60 {
445 return strconv.FormatInt(d/60, 10) + "m " + strconv.FormatInt(d%60, 10) + "s"
446 }
447 return strconv.FormatInt(d, 10) + "s"
448}
449
450// stamp renders a unix second in both UTC and KST, the two clocks this board's
451// audience reads.
452func stamp(unix int64) string {
453 t := time.Unix(unix, 0).UTC()
454 k := time.Unix(unix+9*3600, 0).UTC()
455 return t.Format("2006-01-02 15:04") + " / " + k.Format("01-02 15:04") + " KST"
456}
457
458func short(s string) string {
459 if len(s) <= 12 {
460 return s
461 }
462 return s[:6] + "…" + s[len(s)-6:]
463}
464
465// cell keeps a free-text field from breaking a markdown table.
466func cell(s string) string {
467 out := ""
468 for i := 0; i < len(s); i++ {
469 c := s[i]
470 if c == '|' {
471 out += "\\|"
472 } else if c == '\n' || c == '\r' {
473 out += " "
474 } else {
475 out += string(c)
476 }
477 }
478 return out
479}
480
481func quoteList(items []string) string {
482 out := ""
483 for i := 0; i < len(items); i++ {
484 if i > 0 {
485 out += ", "
486 }
487 out += "\"" + items[i] + "\""
488 }
489 return out
490}
491
492func parseUint(s string) (uint64, bool) {
493 if s == "" {
494 return 0, false
495 }
496 v, err := strconv.ParseUint(s, 10, 64)
497 if err != nil {
498 return 0, false
499 }
500 return v, true
501}