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

board.gno

package gauntlet

import (
	"crypto/sha256"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"strconv"
	"strings"
	"time"

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

// Status of a challenge.
type Status int

const (
	Open   Status = iota // accepting commits until the deadline
	Won                  // paid out to the earliest passing commit
	Closed               // nobody passed; reward returned to the poster
)

func (s Status) String() string {
	switch s {
	case Open:
		return "open"
	case Won:
		return "won"
	case Closed:
		return "closed"
	}
	return "unknown"
}

// State of an attempt.
type State int

const (
	Pending State = iota // committed, not yet revealed
	Passed               // revealed and passed every test
	Failed               // revealed and failed a test
	Expired              // not revealed in time; bond forfeited
	Refunded             // challenge ended before it was revealed; bond returned
)

func (s State) String() string {
	switch s {
	case Pending:
		return "pending"
	case Passed:
		return "passed"
	case Failed:
		return "failed"
	case Expired:
		return "expired"
	case Refunded:
		return "refunded"
	}
	return "unknown"
}

// Attempt is one solver's commit, and its result once revealed.
type Attempt struct {
	Seq         uint64 // global order of commits on the board
	Solver      address
	Hash        string
	CommittedAt time.Time
	State       State
	PkgPath     string // the solution realm, set on reveal
	RevealedAt  time.Time
	Report      Report
}

// Challenge is one bounty.
type Challenge struct {
	ID       uint64
	Title    string
	Spec     string // markdown
	Poster   address
	Reward   int64 // escrowed by the hosting realm
	Bond     int64 // required with every commit, refunded on reveal
	Created  time.Time
	Deadline time.Time     // last moment to commit
	Window   time.Duration // time allowed between commit and reveal

	Cases     []Case // fixed tests, may be empty if Judge is set
	Judge     *Judge
	JudgePath string // package path of the judge's code, for display

	Status    Status
	Winner    *Attempt
	Attempts  []*Attempt
	Forfeited int64 // expired bonds, added to the reward
	Boosts    int64 // reward added after posting
}

// Pot is what the winner (or, if nobody wins, the poster) receives.
func (c *Challenge) Pot() int64 { return c.Reward + c.Forfeited }

// Payout is an instruction for the hosting realm to send coins.
type Payout struct {
	To     address
	Amount int64
	Reason string
}

// PostParams describes a new challenge.
type PostParams struct {
	Title     string
	Spec      string
	Poster    address
	Reward    int64
	Bond      int64
	Deadline  time.Time
	Window    time.Duration
	Cases     []Case
	Judge     *Judge
	JudgePath string
}

const (
	MaxTitleLen   = 120
	MaxSpecLen    = 8000
	MaxAttempts   = 256
	MinWindow     = time.Minute
	MaxWindow     = 7 * 24 * time.Hour
	MaxPostLength = 90 * 24 * time.Hour
)

var (
	ErrNotFound       = errors.New("gauntlet: challenge not found")
	ErrNotOpen        = errors.New("gauntlet: challenge is not open")
	ErrPastDeadline   = errors.New("gauntlet: commits are closed for this challenge")
	ErrBadTitle       = errors.New("gauntlet: title must be 1-120 characters")
	ErrBadSpec        = errors.New("gauntlet: spec is too long")
	ErrBadReward      = errors.New("gauntlet: reward must be positive")
	ErrBadBond        = errors.New("gauntlet: bond cannot be negative")
	ErrBadDeadline    = errors.New("gauntlet: deadline must be in the future and within 90 days")
	ErrBadWindow      = errors.New("gauntlet: reveal window must be between 1 minute and 7 days")
	ErrNoTests        = errors.New("gauntlet: a challenge needs test cases or a judge")
	ErrBadHash        = errors.New("gauntlet: hash must be 64 hex characters")
	ErrWrongBond      = errors.New("gauntlet: wrong bond amount")
	ErrHasPending     = errors.New("gauntlet: you already have a pending commit on this challenge")
	ErrDuplicateHash  = errors.New("gauntlet: this hash was already committed")
	ErrFull           = errors.New("gauntlet: too many attempts on this challenge")
	ErrNoCommit       = errors.New("gauntlet: no pending commit matches this package path and salt")
	ErrRevealTooLate  = errors.New("gauntlet: reveal window has passed for this commit")
	ErrNotRealm       = errors.New("gauntlet: solutions must be revealed from a deployed /r/ realm")
	ErrBadBoostAmount = errors.New("gauntlet: boost must be positive")
)

// Board is a set of challenges. The zero value is ready to use.
type Board struct {
	challenges avl.Tree // key(id) -> *Challenge
	lastID     uint64
	seq        uint64
}

func key(id uint64) string {
	s := strconv.FormatUint(id, 10)
	return strings.Repeat("0", 20-len(s)) + s
}

// HashSolution is the commitment a solver posts: sha256(pkgPath + ":" + salt)
// as lowercase hex.
func HashSolution(pkgPath, salt string) string {
	sum := sha256.Sum256([]byte(pkgPath + ":" + salt))
	return hex.EncodeToString(sum[:])
}

// Post adds a challenge. The caller must already hold p.Reward in escrow.
func (b *Board) Post(p PostParams, now time.Time) (*Challenge, error) {
	if len(p.Title) == 0 || len(p.Title) > MaxTitleLen {
		return nil, ErrBadTitle
	}
	if len(p.Spec) > MaxSpecLen {
		return nil, ErrBadSpec
	}
	if p.Reward <= 0 {
		return nil, ErrBadReward
	}
	if p.Bond < 0 {
		return nil, ErrBadBond
	}
	if !p.Deadline.After(now) || p.Deadline.Sub(now) > MaxPostLength {
		return nil, ErrBadDeadline
	}
	if p.Window < MinWindow || p.Window > MaxWindow {
		return nil, ErrBadWindow
	}
	if len(p.Cases) == 0 && p.Judge == nil {
		return nil, ErrNoTests
	}
	if len(p.Cases) > MaxCases {
		return nil, ErrTooManyCase
	}
	b.lastID++
	c := &Challenge{
		ID:        b.lastID,
		Title:     p.Title,
		Spec:      p.Spec,
		Poster:    p.Poster,
		Reward:    p.Reward,
		Bond:      p.Bond,
		Created:   now,
		Deadline:  p.Deadline,
		Window:    p.Window,
		Cases:     p.Cases,
		Judge:     p.Judge,
		JudgePath: p.JudgePath,
		Status:    Open,
	}
	b.challenges.Set(key(c.ID), c)
	return c, nil
}

// Get returns a challenge or nil.
func (b *Board) Get(id uint64) *Challenge {
	v := b.challenges.Get(key(id))
	if v == nil {
		return nil
	}
	return v.(*Challenge)
}

// Size is the number of challenges ever posted.
func (b *Board) Size() int { return b.challenges.Size() }

// Iterate visits challenges newest first. Return true to stop.
func (b *Board) Iterate(cb func(c *Challenge) bool) {
	b.challenges.ReverseIterate("", "", func(_ string, v any) bool {
		return cb(v.(*Challenge))
	})
}

// Commit records a solver's place in line.
func (b *Board) Commit(id uint64, solver address, hash string, bond int64, now time.Time) (*Attempt, error) {
	c := b.Get(id)
	if c == nil {
		return nil, ErrNotFound
	}
	if c.Status != Open {
		return nil, ErrNotOpen
	}
	if !now.Before(c.Deadline) {
		return nil, ErrPastDeadline
	}
	if bond != c.Bond {
		return nil, ErrWrongBond
	}
	if !isHexHash(hash) {
		return nil, ErrBadHash
	}
	if len(c.Attempts) >= MaxAttempts {
		return nil, ErrFull
	}
	for _, a := range c.Attempts {
		if a.Hash == hash {
			return nil, ErrDuplicateHash
		}
		if a.Solver == solver && a.State == Pending {
			return nil, ErrHasPending
		}
	}
	b.seq++
	a := &Attempt{
		Seq:         b.seq,
		Solver:      solver,
		Hash:        hash,
		CommittedAt: now,
		State:       Pending,
	}
	c.Attempts = append(c.Attempts, a)
	return a, nil
}

// Reveal grades a solution. pkgPath must be the package path of the realm
// that is calling, as reported by the runtime, never a value a user typed.
func (b *Board) Reveal(id uint64, pkgPath, salt string, solve Solver, now time.Time) (*Attempt, []Payout, error) {
	c := b.Get(id)
	if c == nil {
		return nil, nil, ErrNotFound
	}
	if !strings.Contains(pkgPath, "/r/") {
		return nil, nil, ErrNotRealm
	}
	hash := HashSolution(pkgPath, salt)
	var a *Attempt
	for _, x := range c.Attempts {
		if x.Hash == hash {
			a = x
			break
		}
	}
	if a == nil || a.State != Pending {
		return nil, nil, ErrNoCommit
	}
	if now.After(a.CommittedAt.Add(c.Window)) {
		return nil, nil, ErrRevealTooLate
	}

	a.PkgPath = pkgPath
	a.RevealedAt = now
	if c.Judge != nil {
		a.Report = GradeJudge(c.Judge, seedFor(hash, salt, now), solve)
	} else {
		a.Report = GradeCases(c.Cases, solve)
	}
	// A judged challenge with fixed cases runs both.
	if c.Judge != nil && len(c.Cases) > 0 && a.Report.OK() {
		fixed := GradeCases(c.Cases, solve)
		fixed.Passed += a.Report.Passed
		fixed.Total += a.Report.Total
		a.Report = fixed
	}
	if a.Report.OK() {
		a.State = Passed
	} else {
		a.State = Failed
	}

	var payouts []Payout
	if c.Bond > 0 {
		payouts = append(payouts, Payout{To: a.Solver, Amount: c.Bond, Reason: "bond refund"})
	}
	payouts = append(payouts, b.settle(c, now)...)
	return a, payouts, nil
}

// Settle moves a challenge forward: it expires late commits and, when the
// result is certain, pays the winner or returns the reward to the poster.
// Anyone may call it; it is also run after every reveal.
func (b *Board) Settle(id uint64, now time.Time) ([]Payout, error) {
	c := b.Get(id)
	if c == nil {
		return nil, ErrNotFound
	}
	return b.settle(c, now), nil
}

func (b *Board) settle(c *Challenge, now time.Time) []Payout {
	if c.Status != Open {
		return nil
	}
	var winner *Attempt
	for _, a := range c.Attempts { // already in commit order
		if a.State == Pending && now.After(a.CommittedAt.Add(c.Window)) {
			a.State = Expired
			c.Forfeited += c.Bond
		}
		switch a.State {
		case Pending:
			return nil // an earlier commit may still win; wait for it
		case Passed:
			winner = a
		}
		if winner != nil {
			break
		}
	}

	var payouts []Payout
	if winner != nil {
		c.Status = Won
		c.Winner = winner
		payouts = append(payouts, Payout{To: winner.Solver, Amount: c.Pot(), Reason: "bounty won"})
	} else if !now.Before(c.Deadline) {
		c.Status = Closed
		payouts = append(payouts, Payout{To: c.Poster, Amount: c.Pot(), Reason: "no winner, reward returned"})
	} else {
		return nil
	}
	// Later commits did nothing wrong: return their bonds.
	for _, a := range c.Attempts {
		if a.State == Pending {
			a.State = Refunded
			if c.Bond > 0 {
				payouts = append(payouts, Payout{To: a.Solver, Amount: c.Bond, Reason: "bond refund, challenge ended"})
			}
		}
	}
	return payouts
}

// Boost adds to the reward of an open challenge.
func (b *Board) Boost(id uint64, amount int64, now time.Time) error {
	c := b.Get(id)
	if c == nil {
		return ErrNotFound
	}
	if c.Status != Open || !now.Before(c.Deadline) {
		return ErrNotOpen
	}
	if amount <= 0 {
		return ErrBadBoostAmount
	}
	c.Reward += amount
	c.Boosts += amount
	return nil
}

func isHexHash(s string) bool {
	if len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		ch := s[i]
		if !(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f') {
			return false
		}
	}
	return true
}

// seedFor derives the judge seed from values fixed only at reveal time.
func seedFor(hash, salt string, now time.Time) uint64 {
	sum := sha256.Sum256([]byte(hash + ":" + salt + ":" + strconv.FormatInt(now.UnixNano(), 10)))
	return binary.BigEndian.Uint64(sum[:8])
}

cases.gno

package gauntlet

import (
	"errors"
	"strings"
)

// Case is one fixed test: Solve(In) must return exactly Want.
type Case struct {
	In   string
	Want string
}

// Solver is the function a solution exposes.
type Solver func(in string) string

// Judge lets a poster define correctness with code instead of fixed answers.
// Inputs returns fresh inputs for a seed; Check reports whether out is a
// correct answer for in. Checking is usually far cheaper than solving.
type Judge struct {
	Inputs func(seed uint64) []string
	Check  func(in, out string) bool
}

const (
	MaxCases    = 64
	MaxFieldLen = 2048
)

var (
	ErrNoCases     = errors.New("gauntlet: no test cases")
	ErrTooManyCase = errors.New("gauntlet: too many test cases")
	ErrBadCaseLine = errors.New("gauntlet: each case line must be `input => want`")
	ErrFieldTooBig = errors.New("gauntlet: test case too large")
)

// ParseCases reads one case per line in the form `input => want`.
// Inside a field, `\n` is a newline, `\t` a tab and `\\` a backslash.
// Blank lines and lines starting with `#` are ignored.
func ParseCases(src string) ([]Case, error) {
	var out []Case
	for _, line := range strings.Split(src, "\n") {
		line = strings.TrimRight(line, "\r")
		if strings.TrimSpace(line) == "" || strings.HasPrefix(strings.TrimSpace(line), "#") {
			continue
		}
		idx := strings.Index(line, " => ")
		if idx < 0 {
			return nil, ErrBadCaseLine
		}
		c := Case{In: Unescape(line[:idx]), Want: Unescape(line[idx+4:])}
		if len(c.In) > MaxFieldLen || len(c.Want) > MaxFieldLen {
			return nil, ErrFieldTooBig
		}
		out = append(out, c)
		if len(out) > MaxCases {
			return nil, ErrTooManyCase
		}
	}
	if len(out) == 0 {
		return nil, ErrNoCases
	}
	return out, nil
}

// Escape makes a value safe to place on one case line.
func Escape(s string) string {
	s = strings.ReplaceAll(s, `\`, `\\`)
	s = strings.ReplaceAll(s, "\n", `\n`)
	s = strings.ReplaceAll(s, "\t", `\t`)
	return s
}

// Unescape reverses Escape.
func Unescape(s string) string {
	var b strings.Builder
	for i := 0; i < len(s); i++ {
		if s[i] == '\\' && i+1 < len(s) {
			switch s[i+1] {
			case 'n':
				b.WriteByte('\n')
				i++
				continue
			case 't':
				b.WriteByte('\t')
				i++
				continue
			case '\\':
				b.WriteByte('\\')
				i++
				continue
			}
		}
		b.WriteByte(s[i])
	}
	return b.String()
}

doc.gno

// Package gauntlet is a library for coding bounties that are graded by code,
// on-chain, instead of by people.
//
// A Board holds challenges. A challenge is either a set of fixed test cases
// (input -> exact expected output) or a Judge: two functions written by the
// poster, one that generates fresh inputs from a seed and one that checks an
// answer. Judged challenges cannot be gamed with a lookup table, because the
// inputs are only known at the moment of grading.
//
// Solvers compete with a commit-reveal scheme:
//
//  1. Commit: the solver posts sha256(solutionPkgPath + ":" + salt). This fixes
//     their place in the queue before anyone can see their code.
//  2. Deploy: the solver deploys their solution realm.
//  3. Reveal: the solution realm calls the board with the salt and its Solve
//     function. The board recomputes the hash from the caller's package path,
//     grades the function, and records pass or fail.
//
// The winner is the earliest commit that passes. A later commit can never
// overtake an earlier one, so copying someone's deployed code does not pay.
// A commit that is not revealed within the reveal window expires, and its bond
// is added to the reward.
//
// This package moves no coins. It returns Payouts that the hosting realm sends
// with its banker, so any realm can import it and run bounties in any token.
package gauntlet

gauntlet_test.gno

package gauntlet

import (
	"strings"
	"testing"
	"time"
)

var (
	alice  = address("g1alice000000000000000000000000000000000")
	bob    = address("g1bob00000000000000000000000000000000000")
	carol  = address("g1carol00000000000000000000000000000000")
	poster = address("g1poster0000000000000000000000000000000")
	t0     = time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
)

func reverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

func wrong(s string) string { return s }

func hardcoded(s string) string {
	if s == "abc" {
		return "cba"
	}
	return s
}

func newBoard(t *testing.T) (*Board, *Challenge) {
	b := &Board{}
	cases, err := ParseCases("abc => cba\nhello => olleh\n# comment\n\na\\nb => b\\na")
	if err != nil {
		t.Fatal(err)
	}
	c, err := b.Post(PostParams{
		Title: "Reverse", Poster: poster, Reward: 1000, Bond: 10,
		Deadline: t0.Add(24 * time.Hour), Window: time.Hour, Cases: cases,
	}, t0)
	if err != nil {
		t.Fatal(err)
	}
	return b, c
}

func TestParseCases(t *testing.T) {
	cs, err := ParseCases("a\\tb => x\\\\y")
	if err != nil {
		t.Fatal(err)
	}
	if cs[0].In != "a\tb" || cs[0].Want != `x\y` {
		t.Fatalf("got %q %q", cs[0].In, cs[0].Want)
	}
	if _, err := ParseCases("no arrow"); err != ErrBadCaseLine {
		t.Fatalf("want ErrBadCaseLine, got %v", err)
	}
	if _, err := ParseCases("  \n# x"); err != ErrNoCases {
		t.Fatalf("want ErrNoCases, got %v", err)
	}
	if Unescape(Escape("a\n\tb\\")) != "a\n\tb\\" {
		t.Fatal("escape roundtrip")
	}
}

func TestPostValidation(t *testing.T) {
	b := &Board{}
	base := PostParams{Title: "x", Poster: poster, Reward: 1, Deadline: t0.Add(time.Hour), Window: time.Hour, Cases: []Case{{"a", "b"}}}
	bad := []struct {
		mut  func(p *PostParams)
		want error
	}{
		{func(p *PostParams) { p.Title = "" }, ErrBadTitle},
		{func(p *PostParams) { p.Reward = 0 }, ErrBadReward},
		{func(p *PostParams) { p.Bond = -1 }, ErrBadBond},
		{func(p *PostParams) { p.Deadline = t0 }, ErrBadDeadline},
		{func(p *PostParams) { p.Window = time.Second }, ErrBadWindow},
		{func(p *PostParams) { p.Cases = nil }, ErrNoTests},
	}
	for i, tc := range bad {
		p := base
		tc.mut(&p)
		if _, err := b.Post(p, t0); err != tc.want {
			t.Fatalf("case %d: want %v, got %v", i, tc.want, err)
		}
	}
	if b.Size() != 0 {
		t.Fatal("nothing should be posted")
	}
}

func TestHappyPath(t *testing.T) {
	b, c := newBoard(t)
	path := "gno.land/r/g1alice/rev"
	if _, err := b.Commit(c.ID, alice, HashSolution(path, "s1"), 10, t0.Add(time.Minute)); err != nil {
		t.Fatal(err)
	}
	a, pay, err := b.Reveal(c.ID, path, "s1", reverse, t0.Add(2*time.Minute))
	if err != nil {
		t.Fatal(err)
	}
	if a.State != Passed || a.Report.Passed != 3 {
		t.Fatalf("state %v report %+v", a.State, a.Report)
	}
	if c.Status != Won || c.Winner != a {
		t.Fatal("alice should have won")
	}
	if len(pay) != 2 || pay[0].Amount != 10 || pay[1].To != alice || pay[1].Amount != 1000 {
		t.Fatalf("payouts %+v", pay)
	}
}

func TestFailingSolutionKeepsChallengeOpen(t *testing.T) {
	b, c := newBoard(t)
	path := "gno.land/r/g1bob/rev"
	b.Commit(c.ID, bob, HashSolution(path, "x"), 10, t0)
	a, pay, err := b.Reveal(c.ID, path, "x", hardcoded, t0.Add(time.Minute))
	if err != nil {
		t.Fatal(err)
	}
	if a.State != Failed || a.Report.Passed != 1 || a.Report.FailIn != "hello" {
		t.Fatalf("report %+v", a.Report)
	}
	if c.Status != Open || len(pay) != 1 {
		t.Fatalf("status %v payouts %+v", c.Status, pay)
	}
	// Bob can commit again after a failure.
	if _, err := b.Commit(c.ID, bob, HashSolution(path+"2", "y"), 10, t0.Add(2*time.Minute)); err != nil {
		t.Fatal(err)
	}
}

// The core fairness property: a copier who commits later never wins, even
// if they reveal first.
func TestEarlierCommitWinsOverFasterCopier(t *testing.T) {
	b, c := newBoard(t)
	honest := "gno.land/r/g1alice/rev"
	copier := "gno.land/r/g1carol/rev"
	b.Commit(c.ID, alice, HashSolution(honest, "a"), 10, t0)
	b.Commit(c.ID, carol, HashSolution(copier, "c"), 10, t0.Add(time.Minute))

	// Carol reveals first and passes, but Alice is earlier in line.
	_, pay, err := b.Reveal(c.ID, copier, "c", reverse, t0.Add(2*time.Minute))
	if err != nil {
		t.Fatal(err)
	}
	if c.Status != Open || len(pay) != 1 {
		t.Fatalf("must wait for alice: status %v payouts %+v", c.Status, pay)
	}
	_, pay, _ = b.Reveal(c.ID, honest, "a", reverse, t0.Add(3*time.Minute))
	if c.Status != Won || c.Winner.Solver != alice {
		t.Fatal("alice should win")
	}
	if pay[1].To != alice || pay[1].Amount != 1000 {
		t.Fatalf("payouts %+v", pay)
	}
}

func TestExpiredCommitForfeitsBondAndUnblocks(t *testing.T) {
	b, c := newBoard(t)
	slow := "gno.land/r/g1bob/rev"
	fast := "gno.land/r/g1alice/rev"
	b.Commit(c.ID, bob, HashSolution(slow, "b"), 10, t0)
	b.Commit(c.ID, alice, HashSolution(fast, "a"), 10, t0.Add(time.Minute))
	b.Reveal(c.ID, fast, "a", reverse, t0.Add(2*time.Minute))
	if c.Status != Open {
		t.Fatal("bob's commit is still in its window")
	}
	// After bob's window, anyone can settle.
	pay, _ := b.Settle(c.ID, t0.Add(61*time.Minute))
	if c.Status != Won || c.Winner.Solver != alice {
		t.Fatal("alice should win after bob expires")
	}
	if c.Attempts[0].State != Expired || c.Forfeited != 10 || pay[0].Amount != 1010 {
		t.Fatalf("forfeit not applied: %+v", pay)
	}
	// Bob is too late to reveal now.
	if _, _, err := b.Reveal(c.ID, slow, "b", reverse, t0.Add(62*time.Minute)); err != ErrNoCommit {
		t.Fatalf("want ErrNoCommit, got %v", err)
	}
}

func TestLaterPendingCommitsAreRefundedWhenWon(t *testing.T) {
	b, c := newBoard(t)
	b.Commit(c.ID, alice, HashSolution("gno.land/r/a/x", "1"), 10, t0)
	b.Commit(c.ID, bob, HashSolution("gno.land/r/b/x", "2"), 10, t0)
	_, pay, _ := b.Reveal(c.ID, "gno.land/r/a/x", "1", reverse, t0)
	if c.Attempts[1].State != Refunded {
		t.Fatal("bob should be refunded")
	}
	last := pay[len(pay)-1]
	if last.To != bob || last.Amount != 10 {
		t.Fatalf("payouts %+v", pay)
	}
}

func TestNoWinnerReturnsRewardToPoster(t *testing.T) {
	b, c := newBoard(t)
	b.Commit(c.ID, bob, HashSolution("gno.land/r/b/x", "1"), 10, t0)
	b.Reveal(c.ID, "gno.land/r/b/x", "1", wrong, t0.Add(time.Minute))
	if pay, _ := b.Settle(c.ID, t0.Add(time.Hour)); pay != nil {
		t.Fatal("too early to close")
	}
	pay, _ := b.Settle(c.ID, t0.Add(25*time.Hour))
	if c.Status != Closed || len(pay) != 1 || pay[0].To != poster || pay[0].Amount != 1000 {
		t.Fatalf("status %v payouts %+v", c.Status, pay)
	}
	if _, err := b.Commit(c.ID, alice, HashSolution("gno.land/r/a/x", "1"), 10, t0.Add(26*time.Hour)); err != ErrNotOpen {
		t.Fatalf("want ErrNotOpen, got %v", err)
	}
}

func TestCommitRules(t *testing.T) {
	b, c := newBoard(t)
	h := HashSolution("gno.land/r/a/x", "1")
	if _, err := b.Commit(c.ID, alice, h, 9, t0); err != ErrWrongBond {
		t.Fatalf("want ErrWrongBond, got %v", err)
	}
	if _, err := b.Commit(c.ID, alice, "zz", 10, t0); err != ErrBadHash {
		t.Fatalf("want ErrBadHash, got %v", err)
	}
	if _, err := b.Commit(c.ID, alice, strings.ToUpper(h), 10, t0); err != ErrBadHash {
		t.Fatalf("uppercase hash should be rejected, got %v", err)
	}
	b.Commit(c.ID, alice, h, 10, t0)
	if _, err := b.Commit(c.ID, bob, h, 10, t0); err != ErrDuplicateHash {
		t.Fatalf("want ErrDuplicateHash, got %v", err)
	}
	if _, err := b.Commit(c.ID, alice, HashSolution("gno.land/r/a/y", "1"), 10, t0); err != ErrHasPending {
		t.Fatalf("want ErrHasPending, got %v", err)
	}
	if _, err := b.Commit(c.ID, bob, HashSolution("gno.land/r/b/x", "1"), 10, t0.Add(24*time.Hour)); err != ErrPastDeadline {
		t.Fatalf("want ErrPastDeadline, got %v", err)
	}
	if _, err := b.Commit(99, bob, h, 10, t0); err != ErrNotFound {
		t.Fatalf("want ErrNotFound, got %v", err)
	}
}

func TestRevealRules(t *testing.T) {
	b, c := newBoard(t)
	b.Commit(c.ID, alice, HashSolution("gno.land/r/a/x", "1"), 10, t0)
	if _, _, err := b.Reveal(c.ID, "gno.land/e/a/run", "1", reverse, t0); err != ErrNotRealm {
		t.Fatalf("want ErrNotRealm, got %v", err)
	}
	if _, _, err := b.Reveal(c.ID, "gno.land/r/a/x", "wrong-salt", reverse, t0); err != ErrNoCommit {
		t.Fatalf("want ErrNoCommit, got %v", err)
	}
	// Someone else's realm cannot claim Alice's commit.
	if _, _, err := b.Reveal(c.ID, "gno.land/r/c/x", "1", reverse, t0); err != ErrNoCommit {
		t.Fatalf("want ErrNoCommit, got %v", err)
	}
	if _, _, err := b.Reveal(c.ID, "gno.land/r/a/x", "1", reverse, t0.Add(2*time.Hour)); err != ErrRevealTooLate {
		t.Fatalf("want ErrRevealTooLate, got %v", err)
	}
}

func TestJudgeDefeatsLookupTables(t *testing.T) {
	b := &Board{}
	judge := &Judge{
		Inputs: func(seed uint64) []string {
			out := []string{}
			for i := 0; i < 5; i++ {
				out = append(out, "x"+string(rune('a'+int((seed>>(i*8))%26))))
			}
			return out
		},
		Check: func(in, out string) bool { return out == reverse(in) },
	}
	c, err := b.Post(PostParams{
		Title: "Judged reverse", Poster: poster, Reward: 50, Deadline: t0.Add(time.Hour),
		Window: time.Hour, Judge: judge, Cases: []Case{{"ab", "ba"}},
	}, t0)
	if err != nil {
		t.Fatal(err)
	}
	b.Commit(c.ID, bob, HashSolution("gno.land/r/b/x", "1"), 0, t0)
	a, _, _ := b.Reveal(c.ID, "gno.land/r/b/x", "1", hardcoded, t0)
	if a.State != Failed {
		t.Fatal("lookup table must fail generated inputs")
	}
	b.Commit(c.ID, alice, HashSolution("gno.land/r/a/x", "1"), 0, t0)
	a, pay, _ := b.Reveal(c.ID, "gno.land/r/a/x", "1", reverse, t0)
	if a.State != Passed || a.Report.Total != 6 || c.Winner != a {
		t.Fatalf("state %v report %+v", a.State, a.Report)
	}
	if len(pay) != 1 || pay[0].Amount != 50 {
		t.Fatalf("no bond, only the prize: %+v", pay)
	}
}

func TestBoost(t *testing.T) {
	b, c := newBoard(t)
	if err := b.Boost(c.ID, 500, t0); err != nil {
		t.Fatal(err)
	}
	if c.Reward != 1500 || c.Boosts != 500 {
		t.Fatal("boost not applied")
	}
	if err := b.Boost(c.ID, 0, t0); err != ErrBadBoostAmount {
		t.Fatal("zero boost should fail")
	}
	if err := b.Boost(c.ID, 1, t0.Add(48*time.Hour)); err != ErrNotOpen {
		t.Fatal("boost after deadline should fail")
	}
}

func TestIterateNewestFirst(t *testing.T) {
	b := &Board{}
	for i := 0; i < 3; i++ {
		b.Post(PostParams{Title: "c", Poster: poster, Reward: 1, Deadline: t0.Add(time.Hour), Window: time.Hour, Cases: []Case{{"a", "a"}}}, t0)
	}
	var ids []uint64
	b.Iterate(func(c *Challenge) bool { ids = append(ids, c.ID); return false })
	if len(ids) != 3 || ids[0] != 3 || ids[2] != 1 {
		t.Fatalf("ids %v", ids)
	}
}

gnomod.toml

module = "gno.land/p/g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x/gauntlet"
gno = "0.9"

[addpkg]
  creator = "g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x"
  height = 1373012
  max_deposit = "100000000ugnot"

grade.gno

package gauntlet

// Report is the result of grading one solution.
type Report struct {
	Passed int
	Total  int
	// Details of the first failing test, if any.
	FailIn   string
	FailGot  string
	FailWant string
}

// OK reports whether every test passed.
func (r Report) OK() bool { return r.Total > 0 && r.Passed == r.Total }

// GradeCases runs solve against fixed cases. It stops at the first failure:
// a solution either passes everything or it does not.
func GradeCases(cases []Case, solve Solver) Report {
	r := Report{Total: len(cases)}
	for _, c := range cases {
		got := solve(c.In)
		if got != c.Want {
			r.FailIn, r.FailGot, r.FailWant = c.In, got, c.Want
			return r
		}
		r.Passed++
	}
	return r
}

// GradeJudge runs solve against inputs generated from seed and checked by the
// judge.
func GradeJudge(j *Judge, seed uint64, solve Solver) Report {
	ins := j.Inputs(seed)
	if len(ins) > MaxCases {
		ins = ins[:MaxCases]
	}
	r := Report{Total: len(ins)}
	for _, in := range ins {
		got := solve(in)
		if !j.Check(in, got) {
			r.FailIn, r.FailGot = in, got
			return r
		}
		r.Passed++
	}
	return r
}