Playground
api.gno
package hall
import (
"strconv"
"strings"
"gno.land/p/nt/mux/v0"
)
// renderAPI answers api/<what> with JSON for the Cellar web client:
// challenges, board, board-<season>, feed, seasons, player-<address>.
func renderAPI(res *mux.ResponseWriter, req *mux.Request) {
what := req.GetVar("what")
switch {
case what == "challenges":
res.Write(challengesJSON())
case what == "board":
res.Write(boardJSON(0))
case strings.HasPrefix(what, "board-"):
n, err := strconv.Atoi(strings.TrimPrefix(what, "board-"))
if err != nil || n < 1 || n > len(seasons) {
res.Write(`{"error":"no such season"}`)
return
}
res.Write(boardJSON(n))
case what == "feed":
res.Write(feedJSON())
case what == "seasons":
res.Write(seasonsJSON())
case strings.HasPrefix(what, "player-"):
res.Write(playerJSON(strings.TrimPrefix(what, "player-")))
default:
res.Write(`{"error":"unknown endpoint"}`)
}
}
func challengesJSON() string {
var items []string
eachEntry(func(slug string, e *entry) {
first := ""
if len(e.solvers) > 0 {
first = e.solvers[0].String()
}
items = append(items, object(
"slug", quote(slug),
"title", quote(e.info.Title),
"difficulty", quote(e.info.Difficulty.String()),
"category", quote(e.info.Category),
"brief", quote(e.info.Brief),
"path", quote(e.path),
"official", strconv.FormatBool(e.official),
"status", quote(e.status.String()),
"solves", strconv.Itoa(len(e.solvers)),
"value", strconv.Itoa(e.value()),
"firstBloodBonus", strconv.Itoa(e.info.Difficulty.FirstBloodBonus()),
"firstBlood", quote(first),
"enlistedAt", strconv.FormatInt(e.enlistedAt, 10),
))
})
return array(items)
}
func boardJSON(season int) string {
var items []string
for _, r := range standings(season) {
items = append(items, object(
"player", quote(r.Player.String()),
"name", quote(DisplayName(r.Player)),
"points", strconv.Itoa(r.Points),
"solves", strconv.Itoa(r.Solves),
))
}
return array(items)
}
func feedJSON() string {
var items []string
for i := len(feed) - 1; i >= 0; i-- {
items = append(items, solveJSON(feed[i]))
}
return array(items)
}
func solveJSON(s Solve) string {
return object(
"player", quote(s.Player.String()),
"name", quote(DisplayName(s.Player)),
"slug", quote(s.Slug),
"height", strconv.FormatInt(s.Height, 10),
"season", strconv.Itoa(s.Season),
"firstBlood", strconv.FormatBool(s.FirstBlood),
"points", strconv.Itoa(solvePoints(s)),
)
}
func seasonsJSON() string {
var items []string
for _, s := range seasons {
var podium []string
for _, a := range s.Podium {
podium = append(podium, quote(a.String()))
}
items = append(items, object(
"number", strconv.Itoa(s.Number),
"name", quote(s.Name),
"openedAt", strconv.FormatInt(s.OpenedAt, 10),
"closedAt", strconv.FormatInt(s.ClosedAt, 10),
"claims", strconv.Itoa(s.Claims),
"podium", array(podium),
))
}
return array(items)
}
func playerJSON(who string) string {
addr, ok := resolvePlayer(who)
if !ok {
return `{"error":"unknown player"}`
}
p, found := findProfile(addr)
if !found {
p = &profile{addr: addr}
}
all, n, _ := p.score(0)
season, _, _ := p.score(currentSeason().Number)
var solves, badges []string
for _, s := range p.solves {
solves = append(solves, solveJSON(s))
}
for _, tid := range p.badges {
badges = append(badges, object("id", quote(tid), "uri", quote(BadgeURI(tid))))
}
return object(
"player", quote(addr.String()),
"name", quote(DisplayName(addr)),
"handle", quote(p.handle),
"points", strconv.Itoa(all),
"seasonPoints", strconv.Itoa(season),
"flags", strconv.Itoa(n),
"solves", array(solves),
"badges", array(badges),
)
}
// object renders alternating keys and raw JSON values as a JSON object.
func object(kv ...string) string {
var b strings.Builder
b.WriteByte('{')
for i := 0; i+1 < len(kv); i += 2 {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(quote(kv[i]) + ":" + kv[i+1])
}
b.WriteByte('}')
return b.String()
}
func array(items []string) string { return "[" + strings.Join(items, ",") + "]" }
// quote encodes s as a JSON string.
func quote(s string) string {
const hex = "0123456789abcdef"
var b strings.Builder
b.WriteByte('"')
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '"' || c == '\\':
b.WriteByte('\\')
b.WriteByte(c)
case c == '\n':
b.WriteString(`\n`)
case c < 0x20:
b.WriteString(`\u00`)
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&0xf])
default:
b.WriteByte(c)
}
}
b.WriteByte('"')
return b.String()
}
badge.gno
package hall
import (
"strconv"
"strings"
"gno.land/p/nt/grc721/v0"
)
// badgeArt is where the badge artwork lives. The artwork of a badge is
// derived from its token id, so nothing extra is stored per token.
const badgeArt = "https://akinbola247.github.io/cellar-ctf/badges/"
var (
badges *grc721.Token
badgeMint *grc721.PrivateLedger
)
func initBadges(cur realm) {
badges, badgeMint = grc721.NewToken("Cellar Badges", "CELLAR", 0, cur)
}
// Badges returns a read-only view of the badge collection (GRC721).
// Badges cannot be transferred: the hall exposes no transfer.
//
// Token ids:
//
// solve:<slug>:<address> broke a challenge
// blood:<slug> broke it first (replaces the solve badge)
// season:<n>:<rank> finished a season on the podium
func Badges() grc721.Teller { return badges.ReadonlyTeller() }
// BadgeURI returns the artwork URI of badge tid, or "" if it was never
// minted.
func BadgeURI(tid string) string {
if _, err := badges.OwnerOf(grc721.TokenID(tid)); err != nil {
return ""
}
parts := strings.Split(tid, ":")
switch parts[0] {
case "solve":
return badgeArt + parts[1] + ".svg"
case "blood":
return badgeArt + "blood-" + parts[1] + ".svg"
case "season":
return badgeArt + "season-" + parts[2] + ".svg"
}
return ""
}
// awardSolve mints the badge for a solve: first blood, or a plain solve.
func awardSolve(p *profile, s Solve) {
if s.FirstBlood {
mint(p, "blood:"+s.Slug)
return
}
mint(p, "solve:"+s.Slug+":"+s.Player.String())
}
// awardSeason mints a season podium badge.
func awardSeason(addr address, season, rank int) {
mint(profileOf(addr), "season:"+strconv.Itoa(season)+":"+strconv.Itoa(rank))
}
func mint(p *profile, tid string) {
if err := badgeMint.Mint(p.addr, grc721.TokenID(tid)); err != nil {
panic(err)
}
p.badges = append(p.badges, tid)
}
claim.gno
package hall
import (
"chain"
"chain/runtime"
"strconv"
"gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
)
// Solve is one claimed capture.
type Solve struct {
Player address
Slug string
Height int64
Season int
FirstBlood bool
}
// Claim records that the caller broke the challenge slug and returns the
// points it is now worth. The challenge realm is asked whether the player
// captured it; the hall never takes the player's word for it.
//
// Call it from your wallet, or from your solution realm right after the
// exploit: a realm at gno.land/r/<your-address>/... is credited to you.
func Claim(cur realm, slug string) int {
player := flag.MustPlayer(cur.Previous())
e := mustEntry(slug)
if e.status != Listed {
panic(ErrNotListed)
}
p := profileOf(player)
if p.solved(slug) {
panic(ErrAlreadyClaimed)
}
if !e.ch.Captured(player) {
panic(ErrNotCaptured)
}
s := Solve{
Player: player,
Slug: slug,
Height: runtime.ChainHeight(),
Season: currentSeason().Number,
FirstBlood: len(e.solvers) == 0,
}
e.solvers = append(e.solvers, player)
p.solves = append(p.solves, s)
currentSeason().Claims++
pushFeed(s)
awardSolve(p, s)
chain.Emit("Claimed",
"slug", slug,
"player", player.String(),
"firstBlood", strconv.FormatBool(s.FirstBlood),
"season", strconv.Itoa(s.Season),
)
return e.value()
}
func pushFeed(s Solve) {
feed = append(feed, s)
if len(feed) > feedSize {
feed = feed[len(feed)-feedSize:]
}
}
// solvePoints is what one solve is worth today, first blood included.
func solvePoints(s Solve) int {
e, ok := getEntry(s.Slug)
if !ok {
return 0
}
pts := e.value()
if s.FirstBlood {
pts += e.info.Difficulty.FirstBloodBonus()
}
return pts
}
entry.gno
package hall
import (
"chain"
"chain/runtime"
"strings"
"gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
)
// Status is where a challenge stands in the hall.
type Status int
// Challenge statuses.
const (
Pending Status = iota // enlisted by a community realm, awaiting review
Listed // open for claims
Retired // closed for claims; past solves still score
)
// String returns the human name of s.
func (s Status) String() string {
switch s {
case Pending:
return "pending"
case Listed:
return "listed"
case Retired:
return "retired"
}
return "unknown"
}
// entry is a challenge as the hall knows it.
type entry struct {
path string
ch flag.Challenge
info flag.Info
official bool
status Status
enlistedAt int64
solvers []address // claim order; solvers[0] drew first blood
}
// value is what the challenge is worth to each of its solvers right now.
func (e *entry) value() int { return flag.Value(e.info.Difficulty, len(e.solvers)) }
// Enlist registers the challenge ch for the realm that calls it. Call it
// from your challenge realm's init:
//
// func init(cur realm) { hall.Enlist(cross(cur), challenge{}) }
//
// Official challenges are listed at once; community ones wait for review.
func Enlist(cur realm, ch flag.Challenge) {
caller := cur.Previous()
path := caller.PkgPath()
if path == "" || caller.IsEphemeral() {
panic(ErrNotRealm)
}
if ch == nil {
panic(ErrNilChallenge)
}
info := ch.Info()
if err := info.Validate(); err != nil {
panic(err)
}
if paths.Has(path) {
panic(ErrAlreadyEnlisted)
}
if entries.Has(info.Slug) {
panic(ErrSlugTaken)
}
e := &entry{
path: path,
ch: ch,
info: info,
status: Pending,
enlistedAt: runtime.ChainHeight(),
}
if strings.HasPrefix(path, officialPrefix) {
e.official = true
e.status = Listed
}
entries.Set(info.Slug, e)
paths.Set(path, info.Slug)
order = append(order, info.Slug)
chain.Emit("Enlisted", "slug", info.Slug, "path", path, "status", e.status.String())
}
// Approve opens a pending community challenge for claims.
func Approve(cur realm, slug string) {
assertCurator(cur)
e := mustEntry(slug)
if e.status != Pending {
panic(ErrNotPending)
}
e.status = Listed
chain.Emit("Approved", "slug", slug)
}
// Retire closes a challenge for new claims. Existing solves keep scoring.
func Retire(cur realm, slug string) {
assertCurator(cur)
e := mustEntry(slug)
e.status = Retired
chain.Emit("Retired", "slug", slug)
}
func getEntry(slug string) (*entry, bool) {
v := entries.Get(slug)
if v == nil {
return nil, false
}
return v.(*entry), true
}
func mustEntry(slug string) *entry {
e, ok := getEntry(slug)
if !ok {
panic(ErrUnknownChallenge)
}
return e
}
// eachEntry calls fn for every challenge in enlistment order.
func eachEntry(fn func(slug string, e *entry)) {
for _, slug := range order {
e, _ := getEntry(slug)
fn(slug, e)
}
}
errors.gno
package hall
import "errors"
// Errors returned (as panics) by the hall's public functions.
var (
ErrNotCurator = errors.New("hall: only the curator may do this")
ErrBadAddress = errors.New("hall: invalid address")
ErrNotRealm = errors.New("hall: a challenge must enlist itself from its own realm")
ErrNilChallenge = errors.New("hall: nil challenge")
ErrAlreadyEnlisted = errors.New("hall: this realm already enlisted a challenge")
ErrSlugTaken = errors.New("hall: slug already taken")
ErrUnknownChallenge = errors.New("hall: no such challenge")
ErrNotListed = errors.New("hall: challenge is not open for claims")
ErrNotPending = errors.New("hall: challenge is not awaiting review")
ErrAlreadyClaimed = errors.New("hall: you already claimed this challenge")
ErrNotCaptured = errors.New("hall: the cellar has no record of your capture; break the challenge first")
ErrNotUser = errors.New("hall: handles belong to people; call SetHandle directly from your wallet")
ErrBadHandle = errors.New("hall: a handle is 3-20 chars of [a-z0-9_], starting with a letter")
ErrHandleTaken = errors.New("hall: handle already taken")
ErrBadSeasonName = errors.New("hall: a season name is 1-40 printable characters")
)
gnomod.toml
module = "gno.land/r/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/hall" gno = "0.9" [addpkg] creator = "g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf" height = 1457709 max_deposit = "100000000ugnot"
hall.gno
// Package hall is the scoreboard of Cellar, a capture-the-flag wargame
// played on gno.land.
//
// Challenge realms enlist themselves here from their init. Players break a
// challenge in its own realm, then Claim it here: the hall asks the
// challenge whether the player captured it, records the solve, awards a
// badge and updates the standings. Points follow the dynamic curve in
// package flag, so a challenge is worth less as more players solve it.
//
// Everything a player sees is in Render, so gnoweb is a complete client.
package hall
import (
"strings"
"gno.land/p/nt/avl/v0"
)
// officialPrefix marks the realms of the Cellar team. Challenges enlisted
// from below it are listed at once; everyone else waits for the curator.
const officialPrefix = "gno.land/r/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/"
// feedSize is how many recent solves the hall remembers for its feed.
const feedSize = 50
var (
curator = address("g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf")
selfPath string // web path of this realm, e.g. /r/<ns>/cellar/hall
entries = avl.NewTree() // slug -> *entry
paths = avl.NewTree() // challenge realm path -> slug
order []string // slugs in enlistment order
players = avl.NewTree() // address -> *profile
handles = avl.NewTree() // handle -> address
seasons []*season // the last one is open
feed []Solve // newest last, at most feedSize
)
func init(cur realm) {
selfPath = strings.TrimPrefix(cur.PkgPath(), "gno.land")
initBadges(cur)
seasons = append(seasons, newSeason(1, "First Pressing"))
}
// Curator returns the address allowed to curate the hall.
func Curator() address { return curator }
// TransferCuration hands the curator role to another address.
func TransferCuration(cur realm, to address) {
assertCurator(cur)
if !to.IsValid() {
panic(ErrBadAddress)
}
curator = to
}
func assertCurator(cur realm) {
if cur.Previous().Address() != curator {
panic(ErrNotCurator)
}
}
hall_test.gno
package hall
import (
"strings"
"testing"
"gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
"gno.land/p/nt/grc721/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const (
ash = address("g1zkzjmyveh7euq83h5zhnhj6mg0d7kr35nphzd2")
briar = address("g19cyxvfmzdnxlf4ul6328wqq4hy3ssqmqcgul0k")
cask = address("g1rh0vd3xzwjpcqehrf0tpjlqeq35079wf4zklar")
)
// fake is a challenge whose captures the test controls.
type fake struct {
info flag.Info
broken map[address]bool
}
func (f *fake) Info() flag.Info { return f.info }
func (f *fake) Captured(player address) bool { return f.broken[player] }
func newFake(slug string, d flag.Difficulty) *fake {
return &fake{
info: flag.Info{Slug: slug, Title: "Fake " + slug, Difficulty: d, Category: "testing", Brief: "A test."},
broken: map[address]bool{},
}
}
// enlistFrom enlists ch as if called from the realm at path.
func enlistFrom(cur realm, path string, ch flag.Challenge) {
testing.SetRealm(testing.NewCodeRealm(path))
Enlist(cross(cur), ch)
}
func claimAs(cur realm, player address, slug string) int {
testing.SetRealm(testing.NewUserRealm(player))
return Claim(cross(cur), slug)
}
func TestEnlistOfficialIsListed(cur realm, t *testing.T) {
enlistFrom(cur, officialPrefix+"one", newFake("one", flag.Easy))
e := mustEntry("one")
uassert.True(t, e.official)
uassert.Equal(t, "listed", e.status.String())
}
func TestEnlistCommunityWaitsForReview(cur realm, t *testing.T) {
enlistFrom(cur, "gno.land/r/"+string(ash)+"/riddle", newFake("riddle", flag.Medium))
e := mustEntry("riddle")
uassert.False(t, e.official)
uassert.Equal(t, "pending", e.status.String())
testing.SetRealm(testing.NewUserRealm(ash))
uassert.AbortsContains(t, cur, "not open for claims", func() { Claim(cross(cur), "riddle") })
uassert.AbortsContains(t, cur, "only the curator", func() { Approve(cross(cur), "riddle") })
testing.SetRealm(testing.NewUserRealm(curator))
Approve(cross(cur), "riddle")
uassert.Equal(t, "listed", e.status.String())
uassert.AbortsContains(t, cur, "not awaiting review", func() { Approve(cross(cur), "riddle") })
}
func TestEnlistRejects(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(ash))
uassert.AbortsContains(t, cur, "from its own realm", func() { Enlist(cross(cur), newFake("users", flag.Easy)) })
path := "gno.land/r/" + string(briar) + "/twice"
enlistFrom(cur, path, newFake("twice", flag.Easy))
uassert.AbortsContains(t, cur, "already enlisted", func() { Enlist(cross(cur), newFake("twice-b", flag.Easy)) })
testing.SetRealm(testing.NewCodeRealm("gno.land/r/" + string(cask) + "/copycat"))
uassert.AbortsContains(t, cur, "slug already taken", func() { Enlist(cross(cur), newFake("twice", flag.Easy)) })
uassert.AbortsContains(t, cur, "slug must be", func() { Enlist(cross(cur), newFake("X", flag.Easy)) })
uassert.AbortsContains(t, cur, "nil challenge", func() { Enlist(cross(cur), nil) })
}
func TestClaimFlow(cur realm, t *testing.T) {
ch := newFake("flow", flag.Hard)
enlistFrom(cur, officialPrefix+"flow", ch)
testing.SetRealm(testing.NewUserRealm(ash))
uassert.AbortsContains(t, cur, "no record of your capture", func() { Claim(cross(cur), "flow") })
uassert.AbortsContains(t, cur, "no such challenge", func() { Claim(cross(cur), "nope") })
ch.broken[ash] = true
uassert.Equal(t, 500, claimAs(cur, ash, "flow"))
uassert.AbortsContains(t, cur, "already claimed", func() { Claim(cross(cur), "flow") })
// The first solver keeps the full value plus first blood.
p, _ := findProfile(ash)
pts, n, _ := p.score(0)
uassert.Equal(t, 550, pts)
uassert.Equal(t, 1, n)
// A second solver lowers the value for both, retroactively.
ch.broken[briar] = true
second := claimAs(cur, briar, "flow")
uassert.Equal(t, flag.Value(flag.Hard, 2), second)
pts, _, _ = p.score(0)
uassert.Equal(t, second+50, pts)
// Badges: first blood for ash, a solve badge for briar.
owner, err := Badges().OwnerOf("blood:flow")
urequire.NoError(t, err)
uassert.Equal(t, ash, owner)
_, err = Badges().OwnerOf(grc721.TokenID("solve:flow:" + string(briar)))
uassert.NoError(t, err)
uassert.Equal(t, badgeArt+"blood-flow.svg", BadgeURI("blood:flow"))
uassert.Equal(t, badgeArt+"flow.svg", BadgeURI("solve:flow:"+string(briar)))
uassert.Equal(t, "", BadgeURI("solve:flow:"+string(ash)))
}
func TestClaimFromSolutionRealmCreditsNamespace(cur realm, t *testing.T) {
ch := newFake("relay", flag.Easy)
enlistFrom(cur, officialPrefix+"relay", ch)
ch.broken[cask] = true
testing.SetRealm(testing.NewCodeRealm("gno.land/r/" + string(cask) + "/solutions"))
Claim(cross(cur), "relay")
p, ok := findProfile(cask)
urequire.True(t, ok)
uassert.True(t, p.solved("relay"))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/moul/home"))
uassert.AbortsContains(t, cur, "your-g1-address", func() { Claim(cross(cur), "relay") })
}
func TestRetireKeepsPoints(cur realm, t *testing.T) {
ch := newFake("old", flag.Easy)
enlistFrom(cur, officialPrefix+"old", ch)
ch.broken[ash] = true
claimAs(cur, ash, "old")
before, _, _ := profileOf(ash).score(0)
testing.SetRealm(testing.NewUserRealm(curator))
Retire(cross(cur), "old")
after, _, _ := profileOf(ash).score(0)
uassert.Equal(t, before, after)
ch.broken[briar] = true
testing.SetRealm(testing.NewUserRealm(briar))
uassert.AbortsContains(t, cur, "not open for claims", func() { Claim(cross(cur), "old") })
}
func TestHandles(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(ash))
SetHandle(cross(cur), "ash")
uassert.Equal(t, "ash", DisplayName(ash))
SetHandle(cross(cur), "ash_two")
uassert.Equal(t, "ash_two", DisplayName(ash))
testing.SetRealm(testing.NewUserRealm(briar))
SetHandle(cross(cur), "ash") // released by ash, free again
uassert.AbortsContains(t, cur, "already taken", func() { SetHandle(cross(cur), "ash_two") })
for _, bad := range []string{"ab", "1abc", "Ash", "has space", strings.Repeat("a", 21)} {
uassert.AbortsContains(t, cur, "a handle is", func() { SetHandle(cross(cur), bad) })
}
testing.SetRealm(testing.NewCodeRealm("gno.land/r/" + string(cask) + "/bot"))
uassert.AbortsContains(t, cur, "belong to people", func() { SetHandle(cross(cur), "botty") })
uassert.Equal(t, "g1rh0vd3…klar", DisplayName(cask))
}
func TestSeasons(cur realm, t *testing.T) {
ch := newFake("season", flag.Medium)
enlistFrom(cur, officialPrefix+"season", ch)
ch.broken[cask] = true
claimAs(cur, cask, "season")
opened := currentSeason().Number
testing.SetRealm(testing.NewUserRealm(ash))
uassert.AbortsContains(t, cur, "only the curator", func() { OpenSeason(cross(cur), "Second Pressing") })
testing.SetRealm(testing.NewUserRealm(curator))
uassert.AbortsContains(t, cur, "season name", func() { OpenSeason(cross(cur), "") })
OpenSeason(cross(cur), "Second Pressing")
closed := seasons[opened-1]
uassert.True(t, closed.ClosedAt != 0)
urequire.True(t, len(closed.Podium) > 0)
_, err := Badges().OwnerOf(grc721.TokenID("season:" + itoa(opened) + ":1"))
uassert.NoError(t, err)
uassert.Equal(t, badgeArt+"season-1.svg", BadgeURI("season:"+itoa(opened)+":1"))
uassert.Equal(t, opened+1, currentSeason().Number)
uassert.Equal(t, 0, len(standings(currentSeason().Number)))
}
func TestCurationTransfer(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(ash))
uassert.AbortsContains(t, cur, "only the curator", func() { TransferCuration(cross(cur), ash) })
old := curator
testing.SetRealm(testing.NewUserRealm(old))
uassert.AbortsContains(t, cur, "invalid address", func() { TransferCuration(cross(cur), "nope") })
TransferCuration(cross(cur), briar)
uassert.Equal(t, briar, Curator())
testing.SetRealm(testing.NewUserRealm(briar))
TransferCuration(cross(cur), old)
}
player.gno
package hall
import (
"chain"
"sort"
"gno.land/r/sys/users"
)
// profile is a player as the hall knows them.
type profile struct {
addr address
handle string
solves []Solve // claim order
badges []string
}
func (p *profile) solved(slug string) bool {
for _, s := range p.solves {
if s.Slug == slug {
return true
}
}
return false
}
// score sums the player's solves; season 0 means all time.
func (p *profile) score(season int) (points, solves int, last int64) {
for _, s := range p.solves {
if season != 0 && s.Season != season {
continue
}
points += solvePoints(s)
solves++
last = s.Height
}
return points, solves, last
}
// profileOf returns the profile of addr, creating it on first use.
func profileOf(addr address) *profile {
if p, ok := findProfile(addr); ok {
return p
}
p := &profile{addr: addr}
players.Set(addr.String(), p)
return p
}
func findProfile(addr address) (*profile, bool) {
v := players.Get(addr.String())
if v == nil {
return nil, false
}
return v.(*profile), true
}
// SetHandle sets the caller's display name in the hall. Handles are
// unique; setting a new one releases the old one.
func SetHandle(cur realm, handle string) {
caller := cur.Previous()
if !caller.IsUserCall() {
panic(ErrNotUser)
}
if !validHandle(handle) {
panic(ErrBadHandle)
}
addr := caller.Address()
if owner := handles.Get(handle); owner != nil && owner.(address) != addr {
panic(ErrHandleTaken)
}
p := profileOf(addr)
if p.handle != "" {
handles.Remove(p.handle)
}
p.handle = handle
handles.Set(handle, addr)
chain.Emit("Handle", "player", addr.String(), "handle", handle)
}
func validHandle(h string) bool {
if len(h) < 3 || len(h) > 20 || h[0] < 'a' || h[0] > 'z' {
return false
}
for _, c := range h {
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_') {
return false
}
}
return true
}
// DisplayName returns the hall handle of addr, else its gno.land username,
// else a shortened address.
func DisplayName(addr address) string {
if p, ok := findProfile(addr); ok && p.handle != "" {
return p.handle
}
if u := users.ResolveAddress(addr); u != nil {
return u.Name()
}
s := addr.String()
if len(s) < 14 {
return s
}
return s[:8] + "…" + s[len(s)-4:]
}
// resolvePlayer finds an address from an address or a handle.
func resolvePlayer(who string) (address, bool) {
if addr := address(who); addr.IsValid() {
return addr, true
}
if v := handles.Get(who); v != nil {
return v.(address), true
}
return "", false
}
// Standing is a row of a leaderboard.
type Standing struct {
Player address
Points int
Solves int
Last int64 // height of the latest counted solve, for tie-breaks
}
// standings ranks every player with points; season 0 means all time.
// Ties go to whoever got there first.
func standings(season int) []Standing {
var rows []Standing
players.Iterate("", "", func(_ string, v any) bool {
p := v.(*profile)
pts, n, last := p.score(season)
if n > 0 {
rows = append(rows, Standing{Player: p.addr, Points: pts, Solves: n, Last: last})
}
return false
})
sort.Sort(byRank(rows))
return rows
}
type byRank []Standing
func (r byRank) Len() int { return len(r) }
func (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r byRank) Less(i, j int) bool {
if r[i].Points != r[j].Points {
return r[i].Points > r[j].Points
}
if r[i].Last != r[j].Last {
return r[i].Last < r[j].Last
}
return r[i].Player < r[j].Player
}
render.gno
package hall
import (
"strconv"
"strings"
"gno.land/p/moul/txlink/v0"
"gno.land/p/nt/markdown/sanitize/v0"
"gno.land/p/nt/mux/v0"
)
// boardSize is how many rows the lobby leaderboard shows.
const boardSize = 10
var router = newRouter()
func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("", renderLobby)
r.HandleFunc("c/{slug}", renderChallenge)
r.HandleFunc("p/{who}", renderPlayer)
r.HandleFunc("board", renderBoard)
r.HandleFunc("seasons", renderSeasons)
r.HandleFunc("community", renderCommunity)
r.HandleFunc("api/{what}", renderAPI)
r.SetNotFoundHandler(func(res *mux.ResponseWriter, _ *mux.Request) {
res.Write("# Nothing on this shelf\n\n[Back to the hall](" + selfPath + ")\n")
})
return r
}
// Render serves the hall's pages to gnoweb, and JSON under api/ for the
// Cellar web client.
func Render(path string) string { return router.Render(path) }
func renderLobby(res *mux.ResponseWriter, _ *mux.Request) {
s := currentSeason()
res.Write("# The Cellar\n\n")
res.Write("*A capture-the-flag wargame for Gno, played on-chain. Every challenge is a live realm with a flaw in it. Break it, then claim it here.*\n\n")
res.Write("**Season " + strconv.Itoa(s.Number) + ": " + s.Name + "** · opened at block " +
strconv.FormatInt(s.OpenedAt, 10) + " · " + strconv.Itoa(s.Claims) + " claims\n\n")
res.Write("## The racks\n\n")
res.Write(challengeTable(func(e *entry) bool { return e.status == Listed }))
res.Write("\n## Standings this season\n\n")
res.Write(boardTable(standings(s.Number), boardSize))
res.Write("\n## Last pours\n\n")
if len(feed) == 0 {
res.Write("*Nobody has claimed a flag yet. The first one draws first blood.*\n")
}
for i := len(feed) - 1; i >= 0 && i >= len(feed)-10; i-- {
res.Write("- " + feedLine(feed[i]) + "\n")
}
res.Write("\n---\n\n" + link("All-time board", "board") + " · " + link("Seasons", "seasons") +
" · " + link("Community cellar", "community") + "\n")
}
func renderChallenge(res *mux.ResponseWriter, req *mux.Request) {
e, ok := getEntry(req.GetVar("slug"))
if !ok {
res.Write("# No such challenge\n\n" + link("Back to the hall", "") + "\n")
return
}
info := e.info
res.Write("# " + sanitize.InlineText(info.Title) + "\n\n")
res.Write("**" + info.Difficulty.String() + "** · " + sanitize.InlineText(info.Category) +
" · " + e.status.String() + " · worth **" + strconv.Itoa(e.value()) + "** points to each of its " +
strconv.Itoa(len(e.solvers)) + " solvers\n\n")
res.Write(info.Brief + "\n\n")
web := strings.TrimPrefix(e.path, "gno.land")
res.Write("**Realm:** [" + e.path + "](" + web + ") · [read the source](" + web + "$source)\n\n")
if e.status == Listed {
res.Write("When you have broken it, [claim the flag](" + txlink.Call("Claim", "slug", info.Slug) + ").\n\n")
}
res.Write("## Solvers\n\n")
if len(e.solvers) == 0 {
res.Write("*Untouched. First blood is worth +" + strconv.Itoa(info.Difficulty.FirstBloodBonus()) + ".*\n")
}
for i, addr := range e.solvers {
line := strconv.Itoa(i+1) + ". " + playerLink(addr)
if i == 0 {
line += " · first blood"
}
res.Write(line + "\n")
}
}
func renderPlayer(res *mux.ResponseWriter, req *mux.Request) {
addr, ok := resolvePlayer(req.GetVar("who"))
p, found := findProfile(addr)
if !ok || !found {
res.Write("# Unknown player\n\nNobody by that name has claimed a flag yet.\n\n" + link("Back to the hall", "") + "\n")
return
}
all, n, _ := p.score(0)
season, _, _ := p.score(currentSeason().Number)
res.Write("# " + DisplayName(addr) + "\n\n`" + addr.String() + "`\n\n")
res.Write("**" + strconv.Itoa(all) + "** points all time · **" + strconv.Itoa(season) +
"** this season · " + strconv.Itoa(n) + " flags\n\n")
res.Write("## Flags\n\n")
if len(p.solves) == 0 {
res.Write("*No flags yet.*\n")
}
for _, s := range p.solves {
e, _ := getEntry(s.Slug)
line := "- " + link(sanitize.InlineText(e.info.Title), "c/"+s.Slug) + " · block " +
strconv.FormatInt(s.Height, 10) + " · season " + strconv.Itoa(s.Season) + " · " +
strconv.Itoa(solvePoints(s)) + " pts"
if s.FirstBlood {
line += " · first blood"
}
res.Write(line + "\n")
}
res.Write("\n## Badges\n\n")
if len(p.badges) == 0 {
res.Write("*No badges yet.*\n")
}
for _, tid := range p.badges {
res.Write("- `" + tid + "`\n")
}
}
func renderBoard(res *mux.ResponseWriter, _ *mux.Request) {
res.Write("# All-time board\n\n")
rows := standings(0)
res.Write(boardTable(rows, len(rows)))
res.Write("\n" + link("Back to the hall", "") + "\n")
}
func renderSeasons(res *mux.ResponseWriter, _ *mux.Request) {
res.Write("# Seasons\n\n")
for i := len(seasons) - 1; i >= 0; i-- {
s := seasons[i]
res.Write("## Season " + strconv.Itoa(s.Number) + ": " + s.Name + "\n\n")
span := "opened at block " + strconv.FormatInt(s.OpenedAt, 10)
if s.ClosedAt != 0 {
span += ", closed at block " + strconv.FormatInt(s.ClosedAt, 10)
} else {
span += ", still open"
}
res.Write(span + " · " + strconv.Itoa(s.Claims) + " claims\n\n")
for rank, addr := range s.Podium {
res.Write(strconv.Itoa(rank+1) + ". " + playerLink(addr) + "\n")
}
if s.ClosedAt == 0 {
res.Write(boardTable(standings(s.Number), boardSize))
}
res.Write("\n")
}
}
func renderCommunity(res *mux.ResponseWriter, _ *mux.Request) {
res.Write("# Community cellar\n\n")
res.Write("Anyone can build a challenge: import `gno.land/p/" + strings.TrimPrefix(officialPrefix, "gno.land/r/") +
"flag`, keep a `flag.Ledger`, and call `hall.Enlist(cross(cur), challenge{})` from your realm's `init`. " +
"The curator reviews it, then it opens for claims.\n\n")
res.Write("## Listed\n\n")
res.Write(challengeTable(func(e *entry) bool { return !e.official && e.status == Listed }))
res.Write("\n## Awaiting review\n\n")
res.Write(challengeTable(func(e *entry) bool { return e.status == Pending }))
}
func challengeTable(keep func(*entry) bool) string {
var b strings.Builder
b.WriteString("| Challenge | Grade | Teaches | Solves | Worth |\n|---|---|---|---:|---:|\n")
rows := 0
eachEntry(func(slug string, e *entry) {
if !keep(e) {
return
}
rows++
b.WriteString("| " + link(sanitize.TableCell(e.info.Title), "c/"+slug) + " | " + e.info.Difficulty.String() +
" | " + sanitize.TableCell(e.info.Category) + " | " + strconv.Itoa(len(e.solvers)) +
" | " + strconv.Itoa(e.value()) + " |\n")
})
if rows == 0 {
return "*Empty rack.*\n"
}
return b.String()
}
func boardTable(rows []Standing, limit int) string {
if len(rows) == 0 {
return "*No points on the board yet.*\n"
}
var b strings.Builder
b.WriteString("| # | Player | Points | Flags |\n|---:|---|---:|---:|\n")
for i, r := range rows {
if i == limit {
break
}
b.WriteString("| " + strconv.Itoa(i+1) + " | " + playerLink(r.Player) + " | " +
strconv.Itoa(r.Points) + " | " + strconv.Itoa(r.Solves) + " |\n")
}
return b.String()
}
func feedLine(s Solve) string {
title := s.Slug
if e, ok := getEntry(s.Slug); ok {
title = sanitize.InlineText(e.info.Title)
}
line := "block " + strconv.FormatInt(s.Height, 10) + ": " + playerLink(s.Player) + " broke " + link(title, "c/"+s.Slug)
if s.FirstBlood {
line += " (first blood)"
}
return line
}
func playerLink(addr address) string { return link(DisplayName(addr), "p/"+addr.String()) }
// link points at a page of this realm.
func link(text, page string) string {
if page == "" {
return "[" + text + "](" + selfPath + ")"
}
return "[" + text + "](" + selfPath + ":" + page + ")"
}
render_test.gno
package hall
import (
"strconv"
"strings"
"testing"
"gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
"gno.land/p/nt/uassert/v0"
)
func itoa(n int) string { return strconv.Itoa(n) }
func TestRenderPages(cur realm, t *testing.T) {
ch := newFake("pages", flag.Easy)
ch.info.Title = "Pages | <b>bold</b>"
enlistFrom(cur, officialPrefix+"pages", ch)
ch.broken[ash] = true
claimAs(cur, ash, "pages")
testing.SetRealm(testing.NewUserRealm(ash))
SetHandle(cross(cur), "ashen")
lobby := Render("")
for _, want := range []string{"# The Cellar", "## The racks", "## Standings this season", "## Last pours", "ashen", "(first blood)"} {
uassert.True(t, strings.Contains(lobby, want), "lobby lacks "+want)
}
uassert.False(t, strings.Contains(lobby, "| <b>"), "titles must be table-safe")
page := Render("c/pages")
uassert.True(t, strings.Contains(page, "first blood"))
uassert.True(t, strings.Contains(page, "$source"))
uassert.True(t, strings.Contains(Render("c/missing"), "No such challenge"))
uassert.True(t, strings.Contains(Render("p/ashen"), "`"+string(ash)+"`"))
uassert.True(t, strings.Contains(Render("p/"+string(ash)), "## Badges"))
uassert.True(t, strings.Contains(Render("p/<script>"), "Unknown player"))
uassert.True(t, strings.Contains(Render("board"), "# All-time board"))
uassert.True(t, strings.Contains(Render("seasons"), "## Season"))
uassert.True(t, strings.Contains(Render("community"), "hall.Enlist(cross(cur), challenge{})"))
uassert.True(t, strings.Contains(Render("no/such/page"), "Nothing on this shelf"))
}
func TestRenderAPI(cur realm, t *testing.T) {
ch := newFake("api", flag.Medium)
ch.info.Brief = "Line one\nsays \"hi\" \\ there"
enlistFrom(cur, officialPrefix+"api", ch)
out := Render("api/challenges")
uassert.True(t, strings.HasPrefix(out, "[{"))
uassert.True(t, strings.Contains(out, `"brief":"Line one\nsays \"hi\" \\ there"`))
uassert.True(t, strings.Contains(out, `"slug":"api","title":"Fake api","difficulty":"Medium"`))
uassert.True(t, strings.HasPrefix(Render("api/board"), "["))
uassert.True(t, strings.HasPrefix(Render("api/board-1"), "["))
uassert.Equal(t, `{"error":"no such season"}`, Render("api/board-99"))
uassert.True(t, strings.HasPrefix(Render("api/feed"), "["))
uassert.True(t, strings.Contains(Render("api/seasons"), `"name":"First Pressing"`))
uassert.True(t, strings.Contains(Render("api/player-"+string(cask)), `"player":"`+string(cask)+`"`))
uassert.Equal(t, `{"error":"unknown player"}`, Render("api/player-nobody"))
uassert.Equal(t, `{"error":"unknown endpoint"}`, Render("api/what"))
}
func TestQuote(t *testing.T) {
uassert.Equal(t, `"a\u0001b\u0009c"`, quote("a\x01b\tc"))
}
season.gno
package hall
import (
"chain"
"chain/runtime"
"strconv"
)
// podiumSize is how many players a closing season decorates.
const podiumSize = 3
// season is a stretch of play with its own standings. New challenges
// usually open with a new season.
type season struct {
Number int
Name string
OpenedAt int64
ClosedAt int64 // 0 while open
Claims int
Podium []address
}
func newSeason(n int, name string) *season {
return &season{Number: n, Name: name, OpenedAt: runtime.ChainHeight()}
}
func currentSeason() *season { return seasons[len(seasons)-1] }
// OpenSeason closes the current season, decorates its podium with season
// badges, and opens the next one under name.
func OpenSeason(cur realm, name string) {
assertCurator(cur)
if len(name) == 0 || len(name) > 40 {
panic(ErrBadSeasonName)
}
closing := currentSeason()
closing.ClosedAt = runtime.ChainHeight()
for i, row := range standings(closing.Number) {
if i == podiumSize {
break
}
closing.Podium = append(closing.Podium, row.Player)
awardSeason(row.Player, closing.Number, i+1)
}
next := newSeason(closing.Number+1, name)
seasons = append(seasons, next)
chain.Emit("SeasonOpened", "number", strconv.Itoa(next.Number), "name", name)
}