Playground
advent.gno
// Package advent is Gnoël, an on-chain advent calendar with sealed guesses.
package advent
import (
"encoding/base64"
"strconv"
"strings"
"time"
"chain/runtime/unsafe"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/tally/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/nt/bptree/v0"
)
const (
Days = 24
ReviewLimit = 16
PageLimit = 32
organizer = address("g1manfred47kzduec920z88wfr64ylksmdcedlf5")
)
const (
pending = iota + 1
missed
solved
)
type attempt struct {
player string
commitment string
sealedSalt 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
oracle = organizer
board = tally.NewBoard()
)
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) != organizer {
panic("organizer 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) != organizer {
panic("organizer 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()
d := requireDoor(day)
if !lowerHex(commitment, 64) || !lowerHex(sealedSalt, 512) {
panic("invalid sealed guess")
}
if status := d.status(player); status == pending || status == solved {
panic("you already have a pending guess or a solve")
}
d.submitted++
d.attempts.Set(strconv.Itoa(d.submitted), &attempt{player: player, commitment: commitment, sealedSalt: sealedSalt, status: pending})
d.latest.Set(player, d.submitted)
return d.submitted
}
// 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 string) {
if caller(cur) != oracle {
panic("oracle only")
}
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")
}
}
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 ""
}
var out strings.Builder
for id := start; id <= d.submitted && id-start < PageLimit; id++ {
a := d.attempt(id)
out.WriteString(strings.Join([]string{strconv.Itoa(id), a.player, a.commitment, a.sealedSalt, strconv.Itoa(a.status)}, "\t"))
out.WriteByte('\n')
}
return out.String()
}
// 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
}
advent_test.gno
package advent
import (
"strings"
"testing"
"time"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/tally/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
func reset() {
days = [Days]*challenge{}
board = tally.NewBoard()
oracle = organizer
}
func TestCalendarAndReviews(cur realm, t *testing.T) {
reset()
defer reset()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
checker := testutils.TestAddress("oracle")
hash, ciphertext := strings.Repeat("a", 64), strings.Repeat("b", 512)
key := strings.Repeat("a", 588)
next := time.Now().Unix() + 3600
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsWithMessage(t, cur, "organizer only", func() {
Publish(cross(cur), 1, "First clue", "Follow the gnome.", key, next)
})
uassert.AbortsWithMessage(t, cur, "this door is still locked", func() {
Submit(cross(cur), 1, hash, ciphertext)
})
testing.SetRealm(testing.NewUserRealm(organizer))
Publish(cross(cur), 1, "The [hidden] seal", "One line\nTwo lines", key, next)
Publish(cross(cur), 3, "Snow", "Third clue", key, next)
SetOracle(cross(cur), checker)
uassert.AbortsWithMessage(t, cur, "invalid or already open door", func() {
Publish(cross(cur), 1, "New clue", "Follow the gnome.", key, next)
})
uassert.True(t, strings.Contains(Render(""), "2 / 24 doors open"), "calendar shows all opened doors")
uassert.True(t, strings.Contains(Render("door/1"), `The \[hidden\] seal`), "title is escaped")
uassert.True(t, strings.Contains(Render("door/1"), "> One line\n> Two lines"), "clue keeps line breaks")
uassert.True(t, strings.Contains(Render("door/2"), "Still snowed in"), "unpublished doors stay closed")
testing.SetRealm(testing.NewUserRealm(alice))
uassert.Equal(t, 1, Submit(cross(cur), 1, hash, ciphertext))
uassert.AbortsWithMessage(t, cur, "you already have a pending guess or a solve", func() {
Submit(cross(cur), 1, hash, ciphertext)
})
uassert.AbortsWithMessage(t, cur, "oracle only", func() {
Review(cross(cur), 1, 1, "1")
})
testing.SetRealm(testing.NewUserRealm(bob))
uassert.Equal(t, 2, Submit(cross(cur), 1, hash, ciphertext))
testing.SetRealm(testing.NewUserRealm(checker))
uassert.AbortsWithMessage(t, cur, "this case is still under seal", func() {
Review(cross(cur), 1, 1, "01")
})
doors(1).reviewFrom = time.Now().Unix()
uassert.AbortsWithMessage(t, cur, "verdict must be 0 or 1", func() {
Review(cross(cur), 1, 1, "1x")
})
uassert.Equal(t, "1", Progress(alice.String())[:1])
Review(cross(cur), 1, 1, "01")
uassert.AbortsWithMessage(t, cur, "invalid review range", func() {
Review(cross(cur), 1, 1, "11")
})
uassert.Equal(t, "2", Progress(alice.String())[:1])
uassert.Equal(t, "3", Progress(bob.String())[:1])
uassert.Equal(t, bob.String()+"\t1\n", Leaders())
uassert.True(t, strings.Contains(Attempts(1, 2), "2\t"+bob.String()+"\t"+hash+"\t"+ciphertext+"\t3"), "sealed guess is publicly readable")
uassert.True(t, strings.Contains(Render("seal/1/2"), hash), "individual proof shows full commitment")
testing.SetRealm(testing.NewUserRealm(alice))
uassert.Equal(t, 3, Submit(cross(cur), 1, hash, ciphertext))
testing.SetRealm(testing.NewUserRealm(checker))
Review(cross(cur), 1, 3, "1")
uassert.Equal(t, 2, doors(1).solves)
uassert.True(t, strings.Contains(Render("scores"), alice.String()), "late solve updates the board")
uassert.True(t, strings.Contains(Render("door/1"), "2 solves"), "late solve updates the stats")
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsWithMessage(t, cur, "you already have a pending guess or a solve", func() {
Submit(cross(cur), 1, hash, ciphertext)
})
}
func TestUpdateClue(cur realm, t *testing.T) {
reset()
defer reset()
player := testutils.TestAddress("clue-player")
key := strings.Repeat("a", 588)
now := time.Now().Unix()
testing.SetRealm(testing.NewUserRealm(organizer))
Publish(cross(cur), 1, "The original title", "Original body", key, now+3600)
uassert.AbortsWithMessage(t, cur, "this door is still locked", func() {
UpdateClue(cross(cur), 2, "Corrected body")
})
testing.SetRealm(testing.NewUserRealm(player))
Submit(cross(cur), 1, strings.Repeat("a", 64), strings.Repeat("b", 512))
uassert.AbortsWithMessage(t, cur, "organizer only", func() {
UpdateClue(cross(cur), 1, "Wrong organizer")
})
testing.SetRealm(testing.NewUserRealm(organizer))
d := doors(1)
d.reviewFrom = now
Review(cross(cur), 1, 1, "1")
before := Attempts(1, 1)
uassert.AbortsWithMessage(t, cur, "invalid clue", func() {
UpdateClue(cross(cur), 1, strings.Repeat("a", 2501))
})
uassert.Equal(t, "Original body", d.clue)
UpdateClue(cross(cur), 1, "The corrected body")
uassert.Equal(t, "The corrected body", d.clue)
uassert.True(t, strings.Contains(Render("door/1"), "> The corrected body"), "GnoWeb renders the corrected clue")
uassert.True(t, strings.Contains(Calendar(), "VGhlIGNvcnJlY3RlZCBib2R5"), "the rich app reads the corrected clue")
uassert.Equal(t, "The original title", d.title)
uassert.Equal(t, key, d.publicKey)
uassert.Equal(t, now, d.reviewFrom)
uassert.Equal(t, before, Attempts(1, 1))
uassert.Equal(t, player.String()+"\t1\n", Leaders())
}
func ExampleRender_scores() {
reset()
print(Render("scores"))
// Output:
// [Gnoël calendar](/r/moul/advent/v0)
//
// ## 🏆 The Nice List
//
// _Nobody has thawed the scoreboard yet._
}
gnomod.toml
module = "gno.land/r/g1f4k94fjje9tpeekkrnyv2qc7stwxdqp9vcfjg8/advent/v0" gno = "0.9" private = true [addpkg] creator = "g1f4k94fjje9tpeekkrnyv2qc7stwxdqp9vcfjg8" height = 1570072 max_deposit = "10000000ugnot"
launch.gno
package advent
import (
"time"
"chain/runtime"
)
// Launch the approved first door on the empty Onyx realm. The cutoff keeps
// this one-day seed out of later installs and leaves daily publishing
// and clue edits with the organizer.
func init() {
const cutoff = 1796252400 // Midnight on 3 December 2026 in Paris.
if runtime.ChainID() != "onyx-1" || time.Now().Unix() >= cutoff {
return
}
openDoor(1, "There’s Gno Place Like Home", `The Gno-mes moved their workshop onto Gno.land. It has an address but no mailbox. You can visit it in a browser, and a transaction can change what’s inside. Close the tab and the workshop remembers exactly where you left things.
Its address starts with gno.land/r/. What kind of place is it?
Five letters, all caps.`,
"30820122300d06092a864886f70d01010105000382010f003082010a0282010100c4331b8d8af127ae0c5a1c751b4d007903fb274acf2ce12d851c8ad0c9884ee7316c3e411a22befc1186abb185c942fa95573bf321e485ee29e88b96cef918f3631596538601404cc5d7b9fc10bb592ba12d3c46a95d116fb74ed66fae9853dcbefd98c5d9aa2d4a0885bcc64f30808945d1dc9708ddf819fdd980ed766fa2fe3ecd3ac593b5f1e35c67cd2af7d28f6e60bba3e2abd15a00c44186df3706191217ff213271cd5803c92447e584b6539c992db46f3abb9a6ecb0320ea9b1932b378ae58f008b12029be8e3786a958f9863e9908bcecc9cd7f079e0230bf72e1949ef5ae088dbaf9f4d5b2a5d8a15bcb9dce3fdaacf6236ab8f1306afde435baf50203010001", cutoff)
}
render.gno
package advent
import (
"strconv"
"strings"
"time"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
)
const app = "https://moul.github.io/gno-contracts/advent/"
func webLinks() (string, string) {
if runtime.ChainID() == "moulstaging-1" {
return app + "?net=moul-dev", "https://gno-staging.moul.p2p.team/faucet"
}
return app, "https://onyx.testnets.gno.land/faucet"
}
func Render(path string) string {
req := realmpath.Parse(path)
switch req.PathPart(0) {
case "":
return renderCalendar()
case "scores":
return calendarLink() + "\n\n" + renderScores()
case "door":
day, _ := strconv.Atoi(req.PathPart(1))
return renderDoor(day)
case "seal":
day, _ := strconv.Atoi(req.PathPart(1))
id, _ := strconv.Atoi(req.PathPart(2))
return renderSeal(day, id)
default:
return "## Lost in the snow\n\n" + calendarLink()
}
}
func renderCalendar() string {
play, faucet := webLinks()
var out strings.Builder
out.WriteString("# ✷ Gnoël\n\n")
out.WriteString("**The North Pole, one realm over.**\n\n")
out.WriteString("\n\n")
out.WriteString("The Gno-mes hid 24 riddles in the VM. Open a door, follow the clues, and send a sealed guess. Every opened door stays playable.\n\n")
out.WriteString("[Play Gnoël](" + play + ") · [Get test GNOT](" + faucet + ") · [🏆 Leaderboard](" + route("scores") + ")\n\n")
out.WriteString("## Advent calendar\n\n")
table := ui.NewTable("First door", "Second door", "Third door", "Fourth door", "Fifth door", "Sixth door")
open, solves := 0, 0
for week := 0; week < 4; week++ {
row := make([]string, 0, 6)
for j := 1; j <= 6; j++ {
day := week*6 + j
n := dayNumber(day)
d := doors(day)
if d == nil {
row = append(row, "🔒 **"+n+"**")
continue
}
open++
solves += d.solves
row = append(row, "**["+n+"]("+doorURL(day)+")** · "+solveCount(d.solves))
}
table.Row(row...)
}
out.WriteString("**" + strconv.Itoa(open) + " / 24 doors open** · **" + solveCount(solves) + "**\n\n")
out.WriteString(table.String() + "\n")
out.WriteString("A right guess earns one point after the oracle checks the seals. The public ledger shows each commitment and verdict.\n\n")
out.WriteString(renderScores())
return out.String()
}
func renderDoor(day int) string {
play, faucet := webLinks()
d := doors(day)
if d == nil {
return "## 🔒 Still snowed in\n\nThis door opens when the organizer posts its riddle.\n\n" + calendarLink()
}
var out strings.Builder
out.WriteString(calendarLink() + "\n\n")
out.WriteString("# Door " + dayNumber(day) + " · " + ui.Inline(d.title) + "\n\n")
for _, line := range strings.Split(d.clue, "\n") {
out.WriteString("> " + ui.Inline(line) + "\n")
}
out.WriteString("\n**" + solveCount(d.solves) + "** · " + strconv.Itoa(d.submitted) + " sealed guesses · " + strconv.Itoa(d.submitted-d.reviewed) + " awaiting review\n\n")
out.WriteString("First review from **" + time.Unix(d.reviewFrom, 0).UTC().Format("2 Jan 2006, 15:04 UTC") + "**. This door stays open for late arrivals.\n\n")
out.WriteString("[Seal a guess](" + play + "#door-" + strconv.Itoa(day) + ") · [Get test GNOT](" + faucet + ")\n\n")
out.WriteString("## Public seals\n\n")
if d.submitted == 0 {
return out.String() + "_The snow is still fresh here. Send the first guess._\n"
}
table := ui.NewTable("Seal", "Gnome", "Commitment", "Verdict")
for id := d.submitted; id > 0 && id > d.submitted-8; id-- {
a := d.attempt(id)
n := strconv.Itoa(id)
table.Row("[#"+n+"]("+route("seal/"+strconv.Itoa(day)+"/"+n)+")", ui.AddrOf(a.player), "`"+ui.ShortN(a.commitment, 10, 4)+"`", verdict(a.status))
}
out.WriteString(table.String())
return out.String()
}
func renderSeal(day, id int) string {
d := doors(day)
if d == nil || id < 1 || id > d.submitted {
return "## Seal not found\n\n" + calendarLink()
}
a := d.attempt(id)
return "# Seal #" + strconv.Itoa(id) + "\n\n[Back to door " + dayNumber(day) + "](" + doorURL(day) + ")\n\n" +
"**Gnome** " + a.player + "\n\n**Verdict** " + verdict(a.status) +
"\n\n**Public SHA-256 commitment**\n\n`" + a.commitment + "`\n"
}
func renderScores() string {
const heading = "## 🏆 The Nice List\n\n"
rows := leaders()
if len(rows) == 0 {
return heading + "_Nobody has thawed the scoreboard yet._\n"
}
table := ui.NewTable("Rank", "Gnome", "Solves")
for i, e := range rows {
table.Row(strings.TrimSpace(strconv.Itoa(i+1)+" "+ui.Podium(i)), "`"+e.Key+"`", strconv.FormatInt(e.Score, 10))
}
return heading + table.String()
}
func verdict(status int) string {
switch status {
case solved:
return "✅ Solved"
case missed:
return "↩ Try again"
default:
return "✉️ Sealed"
}
}
func dayNumber(day int) string {
n := strconv.Itoa(day)
if day < 10 {
return "0" + n
}
return n
}
func solveCount(n int) string {
if n == 1 {
return "1 solve"
}
return strconv.Itoa(n) + " solves"
}
func route(path string) string {
return strings.TrimPrefix(self, "gno.land") + ":" + path
}
func doorURL(day int) string {
return route("door/" + strconv.Itoa(day))
}
func calendarLink() string {
return "[Gnoël calendar](" + strings.TrimPrefix(self, "gno.land") + ")"
}