Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

challenge.gno

package flag

import (
	"errors"
	"strings"
)

// Difficulty grades a challenge. It sets the starting value of the
// challenge on the scoring curve.
type Difficulty int

// Difficulty levels, from a first evening in the cellar to a long night.
const (
	Easy Difficulty = iota + 1
	Medium
	Hard
)

// String returns the human name of d.
func (d Difficulty) String() string {
	switch d {
	case Easy:
		return "Easy"
	case Medium:
		return "Medium"
	case Hard:
		return "Hard"
	}
	return "Unknown"
}

// Valid reports whether d is one of the declared levels.
func (d Difficulty) Valid() bool { return d >= Easy && d <= Hard }

// Info describes a challenge to players and to the hall.
type Info struct {
	Slug       string     // unique, lowercase, 3 to 24 chars of [a-z0-9-]
	Title      string     // display name
	Difficulty Difficulty // starting value on the scoring curve
	Category   string     // the Gno semantic it teaches, e.g. "render"
	Brief      string     // the story a player reads first (markdown)
}

// Challenge is what a challenge realm hands to a hall.
//
// Implementations live in the challenge realm, so their methods run with
// that realm's storage. Captured must be a pure read.
type Challenge interface {
	Info() Info
	Captured(player address) bool
}

// Errors returned by Validate.
var (
	ErrBadSlug       = errors.New("flag: slug must be 3-24 chars of [a-z0-9-]")
	ErrNoTitle       = errors.New("flag: title is required")
	ErrBadDifficulty = errors.New("flag: unknown difficulty")
	ErrNoBrief       = errors.New("flag: brief is required")
)

// Validate checks that info can be listed in a hall.
func (info Info) Validate() error {
	if !validSlug(info.Slug) {
		return ErrBadSlug
	}
	if strings.TrimSpace(info.Title) == "" {
		return ErrNoTitle
	}
	if !info.Difficulty.Valid() {
		return ErrBadDifficulty
	}
	if strings.TrimSpace(info.Brief) == "" {
		return ErrNoBrief
	}
	return nil
}

func validSlug(s string) bool {
	if len(s) < 3 || len(s) > 24 {
		return false
	}
	for _, c := range s {
		if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
			return false
		}
	}
	return s[0] != '-' && s[len(s)-1] != '-'
}

challenge_test.gno

package flag

import "testing"

func TestDifficultyString(t *testing.T) {
	cases := map[Difficulty]string{Easy: "Easy", Medium: "Medium", Hard: "Hard", 0: "Unknown", 9: "Unknown"}
	for d, want := range cases {
		if got := d.String(); got != want {
			t.Errorf("Difficulty(%d).String() = %q, want %q", int(d), got, want)
		}
	}
}

func TestInfoValidate(t *testing.T) {
	good := Info{Slug: "open-rack", Title: "The Open Rack", Difficulty: Medium, Brief: "A rack."}
	if err := good.Validate(); err != nil {
		t.Fatalf("valid info rejected: %v", err)
	}
	cases := []struct {
		name string
		edit func(*Info)
		want error
	}{
		{"short slug", func(i *Info) { i.Slug = "ab" }, ErrBadSlug},
		{"upper slug", func(i *Info) { i.Slug = "Rack" }, ErrBadSlug},
		{"dash edge", func(i *Info) { i.Slug = "-rack" }, ErrBadSlug},
		{"no title", func(i *Info) { i.Title = "  " }, ErrNoTitle},
		{"bad grade", func(i *Info) { i.Difficulty = 7 }, ErrBadDifficulty},
		{"no brief", func(i *Info) { i.Brief = "" }, ErrNoBrief},
	}
	for _, tc := range cases {
		info := good
		tc.edit(&info)
		if err := info.Validate(); err != tc.want {
			t.Errorf("%s: got %v, want %v", tc.name, err, tc.want)
		}
	}
}

doc.gno

// Package flag is the shared vocabulary of Cellar, a capture-the-flag
// wargame played on gno.land.
//
// A challenge is a realm that holds a deliberate weakness. When a player
// exploits it, the realm records a capture in a Ledger. A hall (a
// scoreboard realm) learns about the challenge through the Challenge
// interface and asks it, on claim, whether a given player captured it.
//
// Anyone can author a challenge by importing this package:
//
//	package riddle
//
//	import (
//		"gno.land/p/<ns>/cellar/flag"
//		"gno.land/r/<ns>/cellar/hall"
//	)
//
//	var captures = flag.NewLedger()
//
//	type challenge struct{}
//
//	func (challenge) Info() flag.Info { return info }
//	func (challenge) Captured(p address) bool { return captures.Captured(p) }
//
//	func init(cur realm) { hall.Enlist(cross(cur), challenge{}) }
//
// The package also carries the scoring curve (Value) and the rule that
// maps a caller to the player who gets the credit (Player).
package flag

gnomod.toml

module = "gno.land/p/g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf/cellar/flag"
gno = "0.9"

[addpkg]
  creator = "g15c02s5hhdny9uvr9za3xsyn9sw8p0klptrh6kf"
  height = 1457699
  max_deposit = "100000000ugnot"

ledger.gno

package flag

import (
	"chain/runtime"

	"gno.land/p/nt/avl/v0"
)

// Capture is the proof that a player broke a challenge.
type Capture struct {
	Player address
	Height int64 // block height of the capture
	Order  int   // 1 for the first capture of this challenge
}

// Ledger records captures for one challenge.
//
// Keep a Ledger in an unexported variable of your realm and never return a
// pointer to it: its methods mutate, and a method call on a leaked pointer
// commits under your realm's authority. (Challenge "rack" is about
// exactly that.)
type Ledger struct {
	captures *avl.Tree // address -> Capture
	order    []address // players in capture order
}

// NewLedger returns an empty Ledger.
func NewLedger() *Ledger {
	return &Ledger{captures: avl.NewTree()}
}

// Record stores a capture for player at the current height. It returns
// the stored capture and true, or the earlier capture and false if the
// player had already captured.
func (l *Ledger) Record(player address) (Capture, bool) {
	if prev, ok := l.Get(player); ok {
		return prev, false
	}
	c := Capture{
		Player: player,
		Height: runtime.ChainHeight(),
		Order:  len(l.order) + 1,
	}
	l.captures.Set(player.String(), c)
	l.order = append(l.order, player)
	return c, true
}

// Captured reports whether player has captured.
func (l *Ledger) Captured(player address) bool {
	return l.captures.Has(player.String())
}

// Get returns the capture of player, if any.
func (l *Ledger) Get(player address) (Capture, bool) {
	v := l.captures.Get(player.String())
	if v == nil {
		return Capture{}, false
	}
	return v.(Capture), true
}

// Count returns the number of distinct players who captured.
func (l *Ledger) Count() int { return len(l.order) }

// Recent returns up to n captures, newest first.
func (l *Ledger) Recent(n int) []Capture {
	if n > len(l.order) {
		n = len(l.order)
	}
	out := make([]Capture, 0, n)
	for i := len(l.order) - 1; i >= len(l.order)-n; i-- {
		c, _ := l.Get(l.order[i])
		out = append(out, c)
	}
	return out
}

ledger_test.gno

package flag

import "testing"

const (
	ash   = address("g1zkzjmyveh7euq83h5zhnhj6mg0d7kr35nphzd2")
	briar = address("g19cyxvfmzdnxlf4ul6328wqq4hy3ssqmqcgul0k")
	cask  = address("g1rh0vd3xzwjpcqehrf0tpjlqeq35079wf4zklar")
)

func TestLedgerRecord(t *testing.T) {
	l := NewLedger()
	if l.Captured(ash) {
		t.Fatal("empty ledger reports a capture")
	}
	c, fresh := l.Record(ash)
	if !fresh || c.Order != 1 || c.Player != ash {
		t.Fatalf("first record = %+v, fresh=%v", c, fresh)
	}
	testing.SkipHeights(3)
	again, fresh := l.Record(ash)
	if fresh || again != c {
		t.Fatalf("second record of same player should return the first: %+v", again)
	}
	c2, _ := l.Record(briar)
	if c2.Order != 2 || c2.Height != c.Height+3 {
		t.Fatalf("second player capture = %+v", c2)
	}
	if l.Count() != 2 || !l.Captured(briar) || l.Captured(cask) {
		t.Fatal("count or membership wrong")
	}
}

func TestLedgerRecent(t *testing.T) {
	l := NewLedger()
	if got := l.Recent(5); len(got) != 0 {
		t.Fatalf("Recent on empty ledger = %v", got)
	}
	l.Record(ash)
	l.Record(briar)
	l.Record(cask)
	got := l.Recent(2)
	if len(got) != 2 || got[0].Player != cask || got[1].Player != briar {
		t.Fatalf("Recent(2) = %+v", got)
	}
	if len(l.Recent(10)) != 3 {
		t.Fatal("Recent should clamp to the ledger size")
	}
}

player.gno

package flag

import (
	"errors"
	"strings"
)

// ErrNoPlayer is returned when a caller cannot be tied to a player.
var ErrNoPlayer = errors.New("flag: deploy your solution under gno.land/r/<your-g1-address>/ so the hall knows who you are")

// Caller is the part of a realm value Player needs. Pass cur.Previous().
type Caller interface {
	Address() address
	PkgPath() string
}

// Player returns the player credited for a call made by caller, which must
// be the previous realm of the challenge's crossing function
// (cur.Previous()).
//
// A user calling directly is credited as themselves. A realm is credited
// to the owner of its namespace, so a solution deployed at
// gno.land/r/<g1address>/... earns points for <g1address>. Namespaces are
// enforced by the chain, so nobody can deploy under your address.
func Player(caller Caller) (address, error) {
	path := caller.PkgPath()
	if path == "" {
		return caller.Address(), nil
	}
	return namespaceOwner(path)
}

// namespaceOwner extracts the address from "<domain>/<r|e>/<g1...>/...".
func namespaceOwner(path string) (address, error) {
	parts := strings.Split(path, "/")
	if len(parts) < 4 || (parts[1] != "r" && parts[1] != "e") {
		return "", ErrNoPlayer
	}
	addr := address(parts[2])
	if !addr.IsValid() {
		return "", ErrNoPlayer
	}
	return addr, nil
}

// MustPlayer is Player that panics with ErrNoPlayer.
func MustPlayer(caller Caller) address {
	p, err := Player(caller)
	if err != nil {
		panic(err)
	}
	return p
}

player_test.gno

package flag

import (
	"chain"
	"testing"
)

func TestPlayerUser(t *testing.T) {
	user := testing.MakeRealm(ash, "", testing.OriginRealm())
	got, err := Player(user)
	if err != nil || got != ash {
		t.Fatalf("Player(user) = %s, %v", got, err)
	}
}

func TestPlayerNamespace(t *testing.T) {
	path := "gno.land/r/" + string(briar) + "/solutions/rack"
	code := testing.MakeRealm(chain.PackageAddress(path), path, testing.OriginRealm())
	got, err := Player(code)
	if err != nil || got != briar {
		t.Fatalf("Player(code) = %s, %v", got, err)
	}
}

func TestPlayerRejectsNamedNamespace(t *testing.T) {
	for _, path := range []string{"gno.land/r/moul/home", "gno.land/r/x", "gno.land/p/" + string(ash) + "/lib"} {
		code := testing.MakeRealm(chain.PackageAddress(path), path, testing.OriginRealm())
		if _, err := Player(code); err != ErrNoPlayer {
			t.Errorf("Player(%q) err = %v, want ErrNoPlayer", path, err)
		}
	}
}

func TestMustPlayerPanics(t *testing.T) {
	defer func() {
		if recover() == nil {
			t.Fatal("MustPlayer should panic for an unknown namespace")
		}
	}()
	path := "gno.land/r/moul/home"
	MustPlayer(testing.MakeRealm(chain.PackageAddress(path), path, testing.OriginRealm()))
}

render.gno

package flag

import (
	"strconv"
	"strings"
)

// Card renders the standard header of a challenge page: title, grade,
// category, number of captures and the brief. Authors use it at the top of
// their Render so every challenge in the cellar reads the same way.
func Card(info Info, l *Ledger) string {
	var b strings.Builder
	b.WriteString("# " + info.Title + "\n\n")
	b.WriteString("**" + info.Difficulty.String() + "** · " + info.Category)
	b.WriteString(" · " + strconv.Itoa(l.Count()) + " captured")
	b.WriteString(" · worth " + strconv.Itoa(Value(info.Difficulty, l.Count())) + " points\n\n")
	b.WriteString(info.Brief + "\n")
	return b.String()
}

// Captures renders the n most recent captures of l as a markdown list.
func Captures(l *Ledger, n int) string {
	recent := l.Recent(n)
	if len(recent) == 0 {
		return "*Nobody has broken it yet.*\n"
	}
	var b strings.Builder
	for _, c := range recent {
		b.WriteString("- `" + c.Player.String() + "` at block " + strconv.FormatInt(c.Height, 10))
		if c.Order == 1 {
			b.WriteString(" (first)")
		}
		b.WriteString("\n")
	}
	return b.String()
}

score.gno

package flag

// Points a challenge starts at, by difficulty.
const (
	EasyPoints   = 100
	MediumPoints = 250
	HardPoints   = 500
)

// DecaySolves is the number of solves after which a challenge settles at
// its floor value.
const DecaySolves = 20

// Initial returns the value of a challenge nobody has solved yet.
func (d Difficulty) Initial() int {
	switch d {
	case Easy:
		return EasyPoints
	case Medium:
		return MediumPoints
	case Hard:
		return HardPoints
	}
	return 0
}

// Floor returns the lowest value a challenge of difficulty d decays to:
// two fifths of its initial value.
func (d Difficulty) Floor() int { return d.Initial() * 2 / 5 }

// Value returns what a challenge of difficulty d is worth to every one of
// its solvers once it has solves solvers. It follows the CTFd dynamic
// curve: the value falls with the square of the solve count and settles at
// the floor after DecaySolves solves. A lone solver keeps the full value,
// and the value applies retroactively to all solvers.
func Value(d Difficulty, solves int) int {
	initial, floor := d.Initial(), d.Floor()
	n := solves - 1
	if n <= 0 {
		return initial
	}
	if n >= DecaySolves {
		return floor
	}
	v := initial - (initial-floor)*n*n/(DecaySolves*DecaySolves)
	if v < floor {
		return floor
	}
	return v
}

// FirstBloodBonus returns the one-time bonus for the first solver.
func (d Difficulty) FirstBloodBonus() int { return d.Initial() / 10 }

score_test.gno

package flag

import "testing"

func TestValueCurve(t *testing.T) {
	cases := []struct {
		d      Difficulty
		solves int
		want   int
	}{
		{Easy, 0, 100},
		{Easy, 1, 100},
		{Easy, 2, 100 - 60*1/400},
		{Medium, 11, 250 - 150*100/400},
		{Hard, 21, 200},
		{Hard, 500, 200},
	}
	for _, tc := range cases {
		if got := Value(tc.d, tc.solves); got != tc.want {
			t.Errorf("Value(%s, %d) = %d, want %d", tc.d, tc.solves, got, tc.want)
		}
	}
}

func TestValueMonotonic(t *testing.T) {
	for _, d := range []Difficulty{Easy, Medium, Hard} {
		prev := Value(d, 0)
		for n := 1; n <= 40; n++ {
			v := Value(d, n)
			if v > prev || v < d.Floor() {
				t.Fatalf("%s: value %d at %d solves breaks the curve", d, v, n)
			}
			prev = v
		}
	}
}

func TestFirstBlood(t *testing.T) {
	if Hard.FirstBloodBonus() != 50 || Easy.FirstBloodBonus() != 10 {
		t.Fatal("first blood bonus should be a tenth of the initial value")
	}
}

func TestCard(t *testing.T) {
	l := NewLedger()
	l.Record(ash)
	out := Card(Info{Slug: "label", Title: "The Forged Label", Difficulty: Easy, Category: "render", Brief: "Brief."}, l)
	want := "# The Forged Label\n\n**Easy** · render · 1 captured · worth 100 points\n\nBrief.\n"
	if out != want {
		t.Fatalf("Card =\n%q\nwant\n%q", out, want)
	}
}

func TestCaptures(t *testing.T) {
	l := NewLedger()
	if Captures(l, 3) != "*Nobody has broken it yet.*\n" {
		t.Fatal("empty ledger should say so")
	}
	l.Record(ash)
	out := Captures(l, 3)
	if out != "- `"+ash.String()+"` at block 123 (first)\n" {
		t.Fatalf("Captures = %q", out)
	}
}