advent.gno
8.42 Kb · 346 lines
1// Package advent is Gnoël, an on-chain advent calendar with sealed guesses.
2package advent
3
4import (
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "strconv"
9 "strings"
10 "time"
11
12 "chain/runtime"
13 "chain/runtime/unsafe"
14
15 "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/tally/v0"
16 "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
17 "gno.land/p/nt/bptree/v0"
18)
19
20const (
21 Days = 24
22 ReviewLimit = 16
23 PageLimit = 32
24 homeAdmin = address("g1manfred47kzduec920z88wfr64ylksmdcedlf5")
25 onyxAgent = address("g1f4k94fjje9tpeekkrnyv2qc7stwxdqp9vcfjg8")
26)
27
28const (
29 pending = iota + 1
30 missed
31 solved
32)
33
34type attempt struct {
35 player string
36 commitment string
37 sealedSalt string
38 origin string
39 status int
40}
41
42type challenge struct {
43 title, clue, publicKey string
44 reviewFrom int64
45 submitted, reviewed int
46 solves int
47 attempts, latest *bptree.BPTree
48}
49
50var (
51 self = unsafe.CurrentRealm().PkgPath()
52 days [Days]*challenge
53 organizer = organizerForChain()
54 publisher = organizer
55 oracle = organizer
56 board = tally.NewBoard()
57 carryingOver bool
58)
59
60func organizerForChain() address {
61 if runtime.ChainID() == "onyx-1" {
62 return onyxAgent
63 }
64 return homeAdmin
65}
66
67// Publisher returns the address that publishes and edits the doors.
68func Publisher() address {
69 return publisher
70}
71
72// SetPublisher delegates publishing and clue corrections to another account.
73func SetPublisher(cur realm, signer address) {
74 if caller(cur) != organizer {
75 panic("organizer only")
76 }
77 if signer.String() == "" {
78 panic("missing publisher address")
79 }
80 publisher = signer
81}
82
83func caller(cur realm) address {
84 if !cur.IsCurrent() {
85 panic("spoofed realm")
86 }
87 return cur.Previous().Address()
88}
89
90func SetOracle(cur realm, signer address) {
91 if caller(cur) != organizer {
92 panic("organizer only")
93 }
94 if signer.String() == "" {
95 panic("missing oracle address")
96 }
97 oracle = signer
98}
99
100// Publish opens a case. The RSA-2048 SPKI public key is pinned for
101// that case so that rotating the key for a new door leaves old doors playable.
102func Publish(cur realm, day int, title, clue, publicKey string, reviewFrom int64) {
103 if caller(cur) != publisher {
104 panic("publisher only")
105 }
106 openDoor(day, title, clue, publicKey, reviewFrom)
107}
108
109func openDoor(day int, title, clue, publicKey string, reviewFrom int64) {
110 if day < 1 || day > Days || doors(day) != nil {
111 panic("invalid or already open door")
112 }
113 if len(title) > 100 || strings.TrimSpace(ui.Inline(title)) == "" {
114 panic("invalid title")
115 }
116 assertClue(clue)
117 if !lowerHex(publicKey, 588) {
118 panic("expected a hex RSA-2048 public key")
119 }
120 now := time.Now().Unix()
121 if reviewFrom <= now || reviewFrom > now+26*60*60 {
122 panic("review must begin in the next 26 hours")
123 }
124 days[day-1] = &challenge{
125 title: title, clue: clue, publicKey: publicKey, reviewFrom: reviewFrom,
126 attempts: bptree.NewBPTreeN(128), latest: bptree.NewBPTreeN(128),
127 }
128}
129
130// UpdateClue corrects the text of an open door while keeping its review
131// schedule, oracle key and submissions intact.
132func UpdateClue(cur realm, day int, clue string) {
133 if caller(cur) != publisher {
134 panic("publisher only")
135 }
136 d := requireDoor(day)
137 assertClue(clue)
138 d.clue = clue
139}
140
141func assertClue(clue string) {
142 if len(clue) > 2500 || strings.TrimSpace(ui.Inline(clue)) == "" {
143 panic("invalid clue")
144 }
145}
146
147// Submit publicly records the commitment and its encrypted random salt.
148func Submit(cur realm, day int, commitment, sealedSalt string) int {
149 player := caller(cur).String()
150 assertReady()
151 d := requireDoor(day)
152 assertSeal(commitment, sealedSalt)
153 if status := d.status(player); status == pending || status == solved {
154 panic("you already have a pending guess or a solve")
155 }
156 return d.record(player, commitment, sealedSalt, "")
157}
158
159// ReplaceGuess reseals the caller's current guess while it awaits review.
160func ReplaceGuess(cur realm, day int, commitment, sealedSalt string) int {
161 player := caller(cur).String()
162 assertReady()
163 d := requireDoor(day)
164 assertSeal(commitment, sealedSalt)
165 id, ok := d.latest.Get(player).(int)
166 if !ok || d.attempt(id).status != pending {
167 panic("only a pending guess can be replaced")
168 }
169 a := d.attempt(id)
170 a.commitment = commitment
171 a.sealedSalt = sealedSalt
172 a.origin = ""
173 return id
174}
175
176func (d *challenge) record(player, commitment, sealedSalt, origin string) int {
177 d.submitted++
178 d.attempts.Set(strconv.Itoa(d.submitted), &attempt{
179 player: player, commitment: commitment, sealedSalt: sealedSalt, origin: origin, status: pending,
180 })
181 d.latest.Set(player, d.submitted)
182 return d.submitted
183}
184
185func assertSeal(commitment, sealedSalt string) {
186 if !lowerHex(commitment, 64) || !lowerHex(sealedSalt, 512) {
187 panic("invalid sealed guess")
188 }
189}
190
191func assertReady() {
192 if carryingOver {
193 panic("the original seals are being carried over")
194 }
195}
196
197// Review records one verdict per consecutive attempt, starting at the first
198// pending ID. A stale batch fails before it can apply verdicts to other guesses.
199func Review(cur realm, day, start int, verdicts, snapshot string) {
200 if caller(cur) != oracle {
201 panic("oracle only")
202 }
203 assertReady()
204 d := requireDoor(day)
205 if time.Now().Unix() < d.reviewFrom {
206 panic("this case is still under seal")
207 }
208 if start != d.reviewed+1 || len(verdicts) == 0 || len(verdicts) > ReviewLimit || len(verdicts) > d.submitted-d.reviewed {
209 panic("invalid review range")
210 }
211 for i := 0; i < len(verdicts); i++ {
212 if verdicts[i] != '0' && verdicts[i] != '1' {
213 panic("verdict must be 0 or 1")
214 }
215 }
216 if d.snapshot(start, len(verdicts)) != snapshot {
217 panic("a seal changed; read the attempts again")
218 }
219 for i := 0; i < len(verdicts); i++ {
220 a := d.attempt(start + i)
221 if verdicts[i] == '1' {
222 a.status = solved
223 d.solves++
224 board.Add(a.player, 1)
225 } else {
226 a.status = missed
227 }
228 }
229 d.reviewed += len(verdicts)
230}
231
232func doors(day int) *challenge {
233 if day < 1 || day > Days {
234 return nil
235 }
236 return days[day-1]
237}
238
239func requireDoor(day int) *challenge {
240 d := doors(day)
241 if d == nil {
242 panic("this door is still locked")
243 }
244 return d
245}
246
247func (d *challenge) attempt(id int) *attempt {
248 return d.attempts.Get(strconv.Itoa(id)).(*attempt)
249}
250
251func (d *challenge) status(player string) int {
252 if id := d.latest.Get(player); id != nil {
253 return d.attempt(id.(int)).status
254 }
255 return 0
256}
257
258func lowerHex(s string, size int) bool {
259 if len(s) != size {
260 return false
261 }
262 for i := 0; i < len(s); i++ {
263 b := s[i]
264 if !(b >= '0' && b <= '9' || b >= 'a' && b <= 'f') {
265 return false
266 }
267 }
268 return true
269}
270
271// Calendar returns tab-separated rows for open doors, with title and clue in base64.
272func Calendar() string {
273 var out strings.Builder
274 for i, d := range days {
275 if d == nil {
276 continue
277 }
278 out.WriteString(strings.Join([]string{
279 strconv.Itoa(i + 1), strconv.Itoa(d.submitted), strconv.Itoa(d.reviewed), strconv.Itoa(d.solves),
280 strconv.FormatInt(d.reviewFrom, 10), d.publicKey,
281 base64.StdEncoding.EncodeToString([]byte(d.title)), base64.StdEncoding.EncodeToString([]byte(d.clue)),
282 }, "\t"))
283 out.WriteByte('\n')
284 }
285 return out.String()
286}
287
288// Attempts returns one bounded page of the public record, starting at a 1-based ID.
289func Attempts(day, start int) string {
290 d := requireDoor(day)
291 if start < 1 || start > d.submitted {
292 return ""
293 }
294 count := d.submitted - start + 1
295 if count > PageLimit {
296 count = PageLimit
297 }
298 return d.rows(start, count)
299}
300
301func (d *challenge) rows(start, count int) string {
302 var out strings.Builder
303 for id := start; id-start < count; id++ {
304 a := d.attempt(id)
305 out.WriteString(strings.Join([]string{
306 strconv.Itoa(id), a.player, a.commitment, a.sealedSalt, strconv.Itoa(a.status), a.origin,
307 }, "\t"))
308 out.WriteByte('\n')
309 }
310 return out.String()
311}
312
313func (d *challenge) snapshot(start, count int) string {
314 sum := sha256.Sum256([]byte(d.rows(start, count)))
315 return hex.EncodeToString(sum[:])
316}
317
318// Progress lists the latest status of an address across all 24 doors.
319func Progress(player string) string {
320 var out strings.Builder
321 for _, d := range days {
322 status := 0
323 if d != nil {
324 status = d.status(player)
325 }
326 out.WriteByte(byte('0' + status))
327 }
328 return out.String()
329}
330
331// Leaders returns the top 24 addresses with their confirmed solves.
332func Leaders() string {
333 var out strings.Builder
334 for _, e := range leaders() {
335 out.WriteString(e.Key + "\t" + strconv.FormatInt(e.Score, 10) + "\n")
336 }
337 return out.String()
338}
339
340func leaders() []tally.Entry {
341 entries := board.Entries()
342 if len(entries) > Days {
343 return entries[:Days]
344 }
345 return entries
346}