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