// Package advent is Gnoƫl, an on-chain advent calendar with sealed guesses. package advent import ( "crypto/sha256" "encoding/base64" "encoding/hex" "strconv" "strings" "time" "chain/runtime" "chain/runtime/unsafe" "gno.land/p/moul/kit/tally/v0" "gno.land/p/moul/kit/ui/v0" "gno.land/p/nt/bptree/v0" ) const ( Days = 24 ReviewLimit = 16 PageLimit = 32 homeAdmin = address("g1manfred47kzduec920z88wfr64ylksmdcedlf5") onyxAgent = address("g1f4k94fjje9tpeekkrnyv2qc7stwxdqp9vcfjg8") ) const ( pending = iota + 1 missed solved ) type attempt struct { player string commitment string sealedSalt string origin string status int } type challenge struct { title, clue, publicKey string reviewFrom int64 submitted, reviewed int solves int attempts, latest *bptree.BPTree } var ( self = unsafe.CurrentRealm().PkgPath() days [Days]*challenge organizer = organizerForChain() publisher = organizer oracle = organizer board = tally.NewBoard() carryingOver bool ) func organizerForChain() address { if runtime.ChainID() == "onyx-1" || runtime.ChainID() == "moulstaging-1" { return onyxAgent } return homeAdmin } // Publisher returns the address that publishes and edits the doors. func Publisher() address { return publisher } // SetPublisher delegates publishing and clue corrections to another account. func SetPublisher(cur realm, signer address) { if caller(cur) != organizer { panic("organizer only") } if signer.String() == "" { panic("missing publisher address") } publisher = signer } func caller(cur realm) address { if !cur.IsCurrent() { panic("spoofed realm") } return cur.Previous().Address() } func SetOracle(cur realm, signer address) { if caller(cur) != organizer { panic("organizer only") } if signer.String() == "" { panic("missing oracle address") } oracle = signer } // Publish opens a case. The RSA-2048 SPKI public key is pinned for // that case so that rotating the key for a new door leaves old doors playable. func Publish(cur realm, day int, title, clue, publicKey string, reviewFrom int64) { if caller(cur) != publisher { panic("publisher only") } openDoor(day, title, clue, publicKey, reviewFrom) } func openDoor(day int, title, clue, publicKey string, reviewFrom int64) { if day < 1 || day > Days || doors(day) != nil { panic("invalid or already open door") } if len(title) > 100 || strings.TrimSpace(ui.Inline(title)) == "" { panic("invalid title") } assertClue(clue) if !lowerHex(publicKey, 588) { panic("expected a hex RSA-2048 public key") } now := time.Now().Unix() if reviewFrom <= now || reviewFrom > now+26*60*60 { panic("review must begin in the next 26 hours") } days[day-1] = &challenge{ title: title, clue: clue, publicKey: publicKey, reviewFrom: reviewFrom, attempts: bptree.NewBPTreeN(128), latest: bptree.NewBPTreeN(128), } } // UpdateClue corrects the text of an open door while keeping its review // schedule, oracle key and submissions intact. func UpdateClue(cur realm, day int, clue string) { if caller(cur) != publisher { panic("publisher only") } d := requireDoor(day) assertClue(clue) d.clue = clue } func assertClue(clue string) { if len(clue) > 2500 || strings.TrimSpace(ui.Inline(clue)) == "" { panic("invalid clue") } } // Submit publicly records the commitment and its encrypted random salt. func Submit(cur realm, day int, commitment, sealedSalt string) int { player := caller(cur).String() assertReady() d := requireDoor(day) assertSeal(commitment, sealedSalt) if status := d.status(player); status == pending || status == solved { panic("you already have a pending guess or a solve") } return d.record(player, commitment, sealedSalt, "") } // ReplaceGuess reseals the caller's current guess while it awaits review. func ReplaceGuess(cur realm, day int, commitment, sealedSalt string) int { player := caller(cur).String() assertReady() d := requireDoor(day) assertSeal(commitment, sealedSalt) id, ok := d.latest.Get(player).(int) if !ok || d.attempt(id).status != pending { panic("only a pending guess can be replaced") } a := d.attempt(id) a.commitment = commitment a.sealedSalt = sealedSalt a.origin = "" return id } func (d *challenge) record(player, commitment, sealedSalt, origin string) int { d.submitted++ d.attempts.Set(strconv.Itoa(d.submitted), &attempt{ player: player, commitment: commitment, sealedSalt: sealedSalt, origin: origin, status: pending, }) d.latest.Set(player, d.submitted) return d.submitted } func assertSeal(commitment, sealedSalt string) { if !lowerHex(commitment, 64) || !lowerHex(sealedSalt, 512) { panic("invalid sealed guess") } } func assertReady() { if carryingOver { panic("the original seals are being carried over") } } // Review records one verdict per consecutive attempt, starting at the first // pending ID. A stale batch fails before it can apply verdicts to other guesses. func Review(cur realm, day, start int, verdicts, snapshot string) { if caller(cur) != oracle { panic("oracle only") } assertReady() d := requireDoor(day) if time.Now().Unix() < d.reviewFrom { panic("this case is still under seal") } if start != d.reviewed+1 || len(verdicts) == 0 || len(verdicts) > ReviewLimit || len(verdicts) > d.submitted-d.reviewed { panic("invalid review range") } for i := 0; i < len(verdicts); i++ { if verdicts[i] != '0' && verdicts[i] != '1' { panic("verdict must be 0 or 1") } } if d.snapshot(start, len(verdicts)) != snapshot { panic("a seal changed; read the attempts again") } for i := 0; i < len(verdicts); i++ { a := d.attempt(start + i) if verdicts[i] == '1' { a.status = solved d.solves++ board.Add(a.player, 1) } else { a.status = missed } } d.reviewed += len(verdicts) } func doors(day int) *challenge { if day < 1 || day > Days { return nil } return days[day-1] } func requireDoor(day int) *challenge { d := doors(day) if d == nil { panic("this door is still locked") } return d } func (d *challenge) attempt(id int) *attempt { return d.attempts.Get(strconv.Itoa(id)).(*attempt) } func (d *challenge) status(player string) int { if id := d.latest.Get(player); id != nil { return d.attempt(id.(int)).status } return 0 } func lowerHex(s string, size int) bool { if len(s) != size { return false } for i := 0; i < len(s); i++ { b := s[i] if !(b >= '0' && b <= '9' || b >= 'a' && b <= 'f') { return false } } return true } // Calendar returns tab-separated rows for open doors, with title and clue in base64. func Calendar() string { var out strings.Builder for i, d := range days { if d == nil { continue } out.WriteString(strings.Join([]string{ strconv.Itoa(i + 1), strconv.Itoa(d.submitted), strconv.Itoa(d.reviewed), strconv.Itoa(d.solves), strconv.FormatInt(d.reviewFrom, 10), d.publicKey, base64.StdEncoding.EncodeToString([]byte(d.title)), base64.StdEncoding.EncodeToString([]byte(d.clue)), }, "\t")) out.WriteByte('\n') } return out.String() } // Attempts returns one bounded page of the public record, starting at a 1-based ID. func Attempts(day, start int) string { d := requireDoor(day) if start < 1 || start > d.submitted { return "" } count := d.submitted - start + 1 if count > PageLimit { count = PageLimit } return d.rows(start, count) } func (d *challenge) rows(start, count int) string { var out strings.Builder for id := start; id-start < count; id++ { a := d.attempt(id) out.WriteString(strings.Join([]string{ strconv.Itoa(id), a.player, a.commitment, a.sealedSalt, strconv.Itoa(a.status), a.origin, }, "\t")) out.WriteByte('\n') } return out.String() } func (d *challenge) snapshot(start, count int) string { sum := sha256.Sum256([]byte(d.rows(start, count))) return hex.EncodeToString(sum[:]) } // Progress lists the latest status of an address across all 24 doors. func Progress(player string) string { var out strings.Builder for _, d := range days { status := 0 if d != nil { status = d.status(player) } out.WriteByte(byte('0' + status)) } return out.String() } // Leaders returns the top 24 addresses with their confirmed solves. func Leaders() string { var out strings.Builder for _, e := range leaders() { out.WriteString(e.Key + "\t" + strconv.FormatInt(e.Score, 10) + "\n") } return out.String() } func leaders() []tally.Entry { entries := board.Entries() if len(entries) > Days { return entries[:Days] } return entries }