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

arena.gno

// Package arena holds Gnomepit's online matches. A challenger posts a sealed deck and
// round-1 plan; an acceptor answers face up; the challenger reveals each round with the
// seal of the next, and the shared duel engine checks and resolves every move. A session
// key is bound to the match of the first call it signs: it then acts in no other match and
// posts or accepts nothing more. Calls the wallet signs are never bound.
package arena

import (
	"encoding/base64"
	"strconv"
	"strings"
	"time"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
)

const (
	moveWindow = 24 * 60 * 60     // seconds a player has for each move
	openWindow = 7 * 24 * 60 * 60 // seconds an open challenge stays on the board
	maxBox     = 104              // bytes
	maxPage    = 50
	maxCleared = 8 // expired challenges one Challenge deletes at most
	idDigits   = 10
)

const (
	phaseOpen    = "open"
	phaseReveal  = "reveal"
	phasePlay    = "play"
	phaseEnded   = "ended"
	phaseExpired = "expired" // reported for an open match past its expiry, never stored
)

var lastID int

// OpenChallenge is an open challenge as the board lists it.
type OpenChallenge struct {
	ID, Challenger, Clan, Opponent string
	Posted, Expires                int64
}

// Challenge posts a challenge for clan with the seals of the challenger's deck and
// round-1 plan, the box holding both, and an opponent who alone may accept, or none.
// It returns the new match's id. It first deletes up to 8 expired challenges, whoever
// posted them.
func Challenge(cur realm, clan, deckSeal, planSeal, box string, opponent address) string {
	mustBeOpen()
	rules := engine.ProofOfConcept()
	c := clanNumber(rules, clan)
	if c == 0 {
		panic("unknown clan")
	}
	if !validSeal(deckSeal) || !validSeal(planSeal) {
		panic("invalid seal")
	}
	raw := boxBytes(box)
	if opponent != "" && !canonical(opponent) {
		panic("invalid opponent")
	}
	now := time.Now().Unix()
	for _, id := range openClear(now, maxCleared) {
		if m, ok := loadMatch(rules, id); ok {
			forget(id, m.challenger)
		}
	}

	lastID++
	m := record{
		phase:      phaseOpen,
		deadline:   now + openWindow,
		challenger: cur.Previous().Address(),
		opponent:   opponent,
		deckSeal:   deckSeal,
		seal:       planSeal,
		box:        raw,
	}
	m.clans[0] = c
	join(cur.Previous().IsUser(), m.challenger, lastID)
	saveMatch(rules, lastID, m)
	openAdd(lastID, m.deadline)
	tellBoard(lastID, clan+" posted a challenge.")
	return strconv.Itoa(lastID)
}

// Open lists open, unexpired challenges, newest first: limit of them after skipping
// offset. limit is 1 to 50.
func Open(offset, limit int) []OpenChallenge {
	checkPage(offset, limit)
	rules := engine.ProofOfConcept()
	list := []OpenChallenge{}
	for _, id := range openNewest(time.Now().Unix(), offset, limit) {
		m, ok := loadMatch(rules, id)
		if !ok {
			continue
		}
		list = append(list, OpenChallenge{
			ID:         strconv.Itoa(id),
			Challenger: m.challenger.String(),
			Clan:       clanName(rules, m.clans[0]),
			Opponent:   m.opponent.String(),
			Posted:     m.deadline - openWindow,
			Expires:    m.deadline,
		})
	}
	return list
}

// forget deletes open challenge id and its place among its challenger's matches. Its
// entry on the open list is the caller's to remove.
func forget(id int, challenger address) {
	dropMatch(id)
	p := loadPlayer(challenger)
	p.remove(id)
	savePlayer(challenger, p)
}

func (m record) expired(now int64) bool {
	return m.phase == phaseOpen && now > m.deadline
}

func checkPage(offset, limit int) {
	if offset < 0 {
		panic("offset must not be negative")
	}
	if limit < 1 || limit > maxPage {
		panic("limit must be 1 to 50")
	}
}

// boxBytes decodes a box argument: the standard base64 of 1 to maxBox bytes, in the one
// form that encodes them, so Match returns every box exactly as it was sent.
func boxBytes(text string) string {
	if len(text) == 0 || len(text) > base64.StdEncoding.EncodedLen(maxBox) {
		panic("invalid box")
	}
	raw, err := base64.StdEncoding.DecodeString(text)
	if err != nil || len(raw) > maxBox || base64.StdEncoding.EncodeToString(raw) != text {
		panic("invalid box")
	}
	return string(raw)
}

// canonical accepts a valid address in the lowercase form callers carry. bech32 also
// allows uppercase, which would never equal a caller's address.
func canonical(a address) bool {
	return a.IsValid() && string(a) == strings.ToLower(string(a))
}

// validSeal accepts a sha256 sum in lowercase hex.
func validSeal(s string) bool {
	if len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
			return false
		}
	}
	return true
}

arena_test.gno

package arena

import (
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
	carol = testutils.TestAddress("carol")
)

const (
	saltA = "0101010101010101010101010101010101010101010101010101010101010101"
	saltB = "0202020202020202020202020202020202020202020202020202020202020202"
)

// reset empties the realm's state between tests; t.Run shares package globals.
func reset() {
	lastID = 0
	chunks = avl.Tree{}
	players = avl.Tree{}
	openList = ""
	retired = false
}

func sealOf(salt, text string) string {
	b, err := hex.DecodeString(salt)
	if err != nil {
		panic(err)
	}
	sum := sha256.Sum256(append(b, text...))
	return hex.EncodeToString(sum[:])
}

// boxOf is s as a box argument, which the page sends in base64.
func boxOf(s string) string {
	return base64.StdEncoding.EncodeToString([]byte(s))
}

func TestChallengeOpensAMatch(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, "deck"), sealOf(saltB, "plan"), boxOf("box"), "")
	uassert.Equal(t, "1", id)

	list := Open(0, 50)
	urequire.Equal(t, 1, len(list))
	c := list[0]
	uassert.Equal(t, "1", c.ID)
	uassert.Equal(t, alice.String(), c.Challenger)
	uassert.Equal(t, "Pickers", c.Clan)
	uassert.Equal(t, "", c.Opponent)
	uassert.Equal(t, c.Posted+604800, c.Expires)
}

func TestChallengeNamesAnOpponent(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	Challenge(cross(cur), "Ironhide", sealOf(saltA, "deck"), sealOf(saltB, "plan"), boxOf("box"), bob)
	uassert.Equal(t, bob.String(), Open(0, 50)[0].Opponent)
	uassert.Equal(t, bob.String(), Matches(alice, 0, 50)[0].Opponent)
}

func TestChallengeRejects(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	seal := sealOf(saltA, "deck")
	cases := []struct {
		name, clan, deckSeal, planSeal, box string
		opponent                            address
		want                                string
	}{
		{"unknown clan", "Elves", seal, seal, boxOf("box"), "", "unknown clan"},
		{"short seal", "Pickers", seal[1:], seal, boxOf("box"), "", "invalid seal"},
		{"uppercase seal", "Pickers", strings.ToUpper(seal), seal, boxOf("box"), "", "invalid seal"},
		{"non-hex seal", "Pickers", seal, "z" + seal[1:], boxOf("box"), "", "invalid seal"},
		{"empty box", "Pickers", seal, seal, "", "", "invalid box"},
		{"long box", "Pickers", seal, seal, boxOf(strings.Repeat("x", 1025)), "", "invalid box"},
		{"bad opponent", "Pickers", seal, seal, boxOf("box"), address("g1nope"), "invalid opponent"},
		{"uppercase opponent", "Pickers", seal, seal, boxOf("box"), address(strings.ToUpper(bob.String())), "invalid opponent"},
	}
	for _, c := range cases {
		uassert.AbortsWithMessage(t, cur, c.want, func() {
			Challenge(cross(cur), c.clan, c.deckSeal, c.planSeal, c.box, c.opponent)
		}, c.name)
	}
	uassert.Equal(t, 0, len(Open(0, 50)))
}

func TestOpenNewestFirstAndUnexpired(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	seal := sealOf(saltA, "deck")
	Challenge(cross(cur), "Pickers", seal, seal, boxOf("box"), "")
	Challenge(cross(cur), "Pickers", seal, seal, boxOf("box"), "")
	testing.SkipHeights(120000) // 600,000 s
	Challenge(cross(cur), "Ironhide", seal, seal, boxOf("box"), "")

	ids := func(list []OpenChallenge) string {
		var out []string
		for _, c := range list {
			out = append(out, c.ID)
		}
		return strings.Join(out, ",")
	}
	uassert.Equal(t, "3,2,1", ids(Open(0, 50)))
	uassert.Equal(t, "2", ids(Open(1, 1)))

	testing.SkipHeights(1000) // the first two are now 605,000 s old
	uassert.Equal(t, "3", ids(Open(0, 50)))
}

func TestOpenLimit(t *testing.T) {
	uassert.PanicsWithMessage(t, nil, "limit must be 1 to 50", func() { Open(0, 0) })
	uassert.PanicsWithMessage(t, nil, "limit must be 1 to 50", func() { Open(0, 51) })
	uassert.PanicsWithMessage(t, nil, "offset must not be negative", func() { Open(-1, 10) })
}

func TestExpiredChallengeLeavesTheBoardBeforeClearing(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SkipHeights(7 * day)
	uassert.Equal(t, 1, len(Open(0, 50)), "a challenge is open until the end of its expiry second")

	testing.SkipHeights(1)
	uassert.Equal(t, 0, len(Open(0, 50)))
	uassert.Equal(t, phaseExpired, Match(id).Phase)
	list := Matches(alice, 0, 50)
	urequire.Equal(t, 1, len(list))
	uassert.Equal(t, phaseExpired, list[0].Phase)
}

func TestClearingAtMostEight(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	for i := 0; i < 10; i++ {
		Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	}
	testing.SkipHeights(7*day + 1)

	Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	uassert.Equal(t, "11,10,9", summaryIDs(Matches(alice, 0, 50)))
	uassert.Equal(t, "[9 10 11]", showIDs(loadPlayer(alice).ids))
	uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match("8") })
	uassert.Equal(t, phaseExpired, Match("9").Phase)

	Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	uassert.Equal(t, "12,11", summaryIDs(Matches(alice, 0, 50)))
	uassert.Equal(t, "[11 12]", showIDs(loadPlayer(alice).ids))
	uassert.Equal(t, 2, len(Open(0, 50)))
}

// A challenge whose match is gone must not block the clearing, or every later Challenge.
func TestClearingSkipsMissingMatch(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	dropMatch(1)
	testing.SkipHeights(7*day + 1)

	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	entries := openEntries(openList)
	urequire.Equal(t, 1, len(entries))
	uassert.Equal(t, id, strconv.Itoa(entries[0].id))
}

func TestBoxText(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	seal := sealOf(saltA, deckA)
	full := boxOf(strings.Repeat("\x00\xff\x07\x80", 26))
	urequire.Equal(t, 140, len(full))
	cases := []struct{ name, box string }{
		{"over 140 characters", strings.Repeat("A", 144)},
		{"141 characters of 104 bytes", full + "\n"},
		{"140 characters of 105 bytes", strings.Repeat("A", 140)},
		{"unpadded", "box"},
		{"outside the alphabet", "b*x1"},
		{"with a newline", "Ym94\n"},
		{"stray low bits", "YR=="},
	}
	for _, c := range cases {
		uassert.AbortsWithMessage(t, cur, "invalid box", func() {
			Challenge(cross(cur), "Pickers", seal, seal, c.box, "")
		}, c.name)
	}

	for _, box := range []string{boxOf("box"), full} {
		id := Challenge(cross(cur), "Pickers", seal, seal, box, "")
		uassert.Equal(t, box, Match(id).Box)
	}
}

codec.gno

package arena

import (
	"encoding/binary"
	"encoding/hex"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
)

// Everything stored by the arena is a byte string laid out here, big-endian. This file
// is the only code that reads or writes those bytes.

const (
	chunkSize   = 64 // match ids per chunk
	addressSize = 40 // bytes in an address's text
	sealSize    = 32 // bytes in a raw sha256 seal
	lockSize    = addressSize + 4 + 4
	openSize    = 4 + 4

	planBits   = 20 // bits per round in a side's plans: 2 for the length, 6 per card
	cardBits   = 6
	maxPlanLen = 3
	maxRound   = 3
	maxPool    = 16 // cards in a clan's pool; a deck is one bit per pool card
)

// ---- Bit fields

// bitsAt returns the width bits of v starting at bit at.
func bitsAt(v uint64, at, width uint) uint64 {
	return (v >> at) & mask(width)
}

// withBits returns v with the width bits at bit at replaced by x.
func withBits(v uint64, at, width uint, x uint64) uint64 {
	if x&^mask(width) != 0 {
		panic("value does not fit")
	}
	return v&^(mask(width)<<at) | x<<at
}

func mask(width uint) uint64 {
	if width >= 64 {
		return ^uint64(0)
	}
	return 1<<width - 1
}

// ---- Plans

// planAt returns the plan made for round, or nil when it is not yet made.
func planAt(plans uint64, round int) engine.Plan {
	at := planOffset(round)
	n := int(bitsAt(plans, at, 2))
	if n == 0 {
		return nil
	}
	p := make(engine.Plan, n)
	for i := range p {
		p[i] = engine.CardID(bitsAt(plans, at+2+uint(i)*cardBits, cardBits))
	}
	return p
}

// withPlan returns plans with round's plan set to p.
func withPlan(plans uint64, round int, p engine.Plan) uint64 {
	if len(p) < 1 || len(p) > maxPlanLen {
		panic("invalid plan")
	}
	at := planOffset(round)
	v := withBits(0, 0, 2, uint64(len(p)))
	for i, id := range p {
		if id < 0 || id >= 1<<cardBits {
			panic("invalid plan")
		}
		v = withBits(v, 2+uint(i)*cardBits, cardBits, uint64(id))
	}
	return withBits(plans, at, planBits, 0) | v<<at
}

// plansMade counts the rounds from the first that have a plan.
func plansMade(plans uint64) int {
	n := 0
	for n < maxRound && bitsAt(plans, planOffset(n+1), 2) != 0 {
		n++
	}
	return n
}

func planOffset(round int) uint {
	if round < 1 || round > maxRound {
		panic("invalid plan")
	}
	return uint(round-1) * planBits
}

// ---- Decks

// deckOnPool returns deck, a set of card ids, as one bit per card of pool in id order.
func deckOnPool(pool, deck uint64) uint16 {
	if cardsIn(pool) > maxPool {
		panic("pool holds more than 16 cards")
	}
	if deck&^pool != 0 {
		panic("deck outside the pool")
	}
	var bits uint16
	k := uint(0)
	for id := uint(0); id < 64; id++ {
		if pool&(1<<id) == 0 {
			continue
		}
		if deck&(1<<id) != 0 {
			bits |= 1 << k
		}
		k++
	}
	return bits
}

// deckFromPool is the inverse of deckOnPool.
func deckFromPool(pool uint64, bits uint16) uint64 {
	if cardsIn(pool) > maxPool {
		panic("pool holds more than 16 cards")
	}
	var deck uint64
	k := uint(0)
	for id := uint(0); id < 64; id++ {
		if pool&(1<<id) == 0 {
			continue
		}
		if bits&(1<<k) != 0 {
			deck |= 1 << id
		}
		k++
	}
	if uint64(bits)>>k != 0 {
		panic("deck outside the pool")
	}
	return deck
}

func cardsIn(pool uint64) uint {
	n := uint(0)
	for ; pool != 0; pool &= pool - 1 {
		n++
	}
	return n
}

// ---- Byte reading and writing

type writer struct{ b []byte }

func (w *writer) u8(x uint64)   { w.b = append(w.b, byte(x)) }
func (w *writer) text(s string) { w.b = append(w.b, s...) }

func (w *writer) u16(x uint64) {
	var t [2]byte
	binary.BigEndian.PutUint16(t[:], uint16(x))
	w.b = append(w.b, t[:]...)
}

func (w *writer) u32(x uint64) {
	var t [4]byte
	binary.BigEndian.PutUint32(t[:], uint32(x))
	w.b = append(w.b, t[:]...)
}

func (w *writer) u64(x uint64) {
	var t [8]byte
	binary.BigEndian.PutUint64(t[:], x)
	w.b = append(w.b, t[:]...)
}

// addr writes a's 40 characters.
func (w *writer) addr(a address) {
	if len(a) != addressSize {
		panic("invalid address")
	}
	w.text(string(a))
}

// seal writes a seal, 64 hex characters, as 32 raw bytes.
func (w *writer) seal(s string) {
	raw, err := hex.DecodeString(s)
	if err != nil || len(raw) != sealSize {
		panic("invalid seal")
	}
	w.b = append(w.b, raw...)
}

func (w *writer) String() string { return string(w.b) }

type reader struct {
	s  string
	at int
}

func (r *reader) left() int { return len(r.s) - r.at }

func (r *reader) text(n int) string {
	if r.left() < n {
		panic("truncated record")
	}
	s := r.s[r.at : r.at+n]
	r.at += n
	return s
}

func (r *reader) u8() uint64    { return uint64(r.text(1)[0]) }
func (r *reader) u16() uint64   { return uint64(binary.BigEndian.Uint16([]byte(r.text(2)))) }
func (r *reader) u32() uint64   { return uint64(binary.BigEndian.Uint32([]byte(r.text(4)))) }
func (r *reader) u64() uint64   { return binary.BigEndian.Uint64([]byte(r.text(8))) }
func (r *reader) addr() address { return address(r.text(addressSize)) }

// seal reads 32 raw bytes as 64 hex characters.
func (r *reader) seal() string { return hex.EncodeToString([]byte(r.text(sealSize))) }

// ---- Match record

// record is a match as the arena works on it, decoded from its stored bytes. clans holds
// each side's index in the ruleset plus one, 0 for none; decks and plans are the engine's
// card sets and the packed plans of withPlan; hp is the HP after each round, per side;
// carried holds only the Vulnerable and Strength left after the last resolved round.
// deckSeal and seal are 64 hex characters; box is the raw bytes, up to maxBox, stored with a 2-byte length.
type record struct {
	phase, result, reason string
	clans                 [2]int
	deadline              int64
	decks                 [2]uint64
	plans                 [2]uint64
	hp                    [3][2]int
	carried               [2]engine.Vitals
	challenger, acceptor  address
	opponent              address
	deckSeal, seal, box   string
}

const (
	flagOpponent = 1 << iota
	flagDeckSeal
	flagSealBox
)

// The value of each name is its index; 0 of result and reason is none.
var (
	phaseNames  = []string{phaseOpen, phaseReveal, phasePlay, phaseEnded}
	resultNames = []string{"", "a", "b", "draw"}
	reasonNames = []string{"", "hp", "knockout", "forfeit", "resign"}
)

func nameIndex(names []string, s, what string) uint64 {
	for i, n := range names {
		if n == s {
			return uint64(i)
		}
	}
	panic("unknown " + what)
}

func nameAt(names []string, i uint64, what string) string {
	if i >= uint64(len(names)) {
		panic("unknown " + what)
	}
	return names[i]
}

func encodeMatch(rules *engine.Ruleset, m record) string {
	var flags uint64
	if m.opponent != "" {
		flags |= flagOpponent
	}
	if m.deckSeal != "" {
		flags |= flagDeckSeal
	}
	if m.seal != "" || m.box != "" {
		flags |= flagSealBox
	}

	w := &writer{}
	w.u8(nameIndex(phaseNames, m.phase, "phase") |
		nameIndex(resultNames, m.result, "result")<<3 |
		nameIndex(reasonNames, m.reason, "reason")<<5)
	w.u8(clanNibble(rules, m.clans[0])<<4 | clanNibble(rules, m.clans[1]))
	w.u8(flags)
	w.u32(uint64(m.deadline))
	for side := 0; side < 2; side++ {
		w.u16(uint64(deckOnPool(poolOf(rules, m.clans[side]), m.decks[side])))
	}
	w.u64(m.plans[0])
	w.u64(m.plans[1])
	for _, round := range m.hp {
		for _, hp := range round {
			if hp < -128 || hp > 127 {
				panic("hp does not fit a byte")
			}
			w.u8(uint64(int8(hp)))
		}
	}
	for _, v := range m.carried {
		if v.Vulnerable < 0 || v.Vulnerable > 15 || v.Strength < 0 || v.Strength > 15 {
			panic("carried state does not fit")
		}
		w.u8(uint64(v.Vulnerable)<<4 | uint64(v.Strength))
	}
	w.addr(m.challenger)
	if m.phase != phaseOpen {
		w.addr(m.acceptor)
	}
	if flags&flagOpponent != 0 {
		w.addr(m.opponent)
	}
	if flags&flagDeckSeal != 0 {
		w.seal(m.deckSeal)
	}
	if flags&flagSealBox != 0 {
		if len(m.box) > maxBox {
			panic("box too long")
		}
		w.seal(m.seal)
		w.u16(uint64(len(m.box)))
		w.text(m.box)
	}
	return w.String()
}

func decodeMatch(rules *engine.Ruleset, b string) record {
	var m record
	r := &reader{s: b}
	first := r.u8()
	m.phase = nameAt(phaseNames, first&7, "phase")
	m.result = nameAt(resultNames, first>>3&3, "result")
	m.reason = nameAt(reasonNames, first>>5, "reason")
	clans := r.u8()
	m.clans = [2]int{int(clans >> 4), int(clans & 15)}
	flags := r.u8()
	m.deadline = int64(r.u32())
	for side := 0; side < 2; side++ {
		m.decks[side] = deckFromPool(poolOf(rules, m.clans[side]), uint16(r.u16()))
	}
	m.plans[0] = r.u64()
	m.plans[1] = r.u64()
	for round := range m.hp {
		for side := range m.hp[round] {
			m.hp[round][side] = int(int8(r.u8()))
		}
	}
	for side := range m.carried {
		v := r.u8()
		m.carried[side] = engine.Vitals{Vulnerable: int(v >> 4), Strength: int(v & 15)}
	}
	m.challenger = r.addr()
	if m.phase != phaseOpen {
		m.acceptor = r.addr()
	}
	if flags&flagOpponent != 0 {
		m.opponent = r.addr()
	}
	if flags&flagDeckSeal != 0 {
		m.deckSeal = r.seal()
	}
	if flags&flagSealBox != 0 {
		m.seal = r.seal()
		m.box = r.text(int(r.u16()))
	}
	if r.left() != 0 {
		panic("trailing bytes in record")
	}
	return m
}

// clanNibble is a clan's stored form, its ruleset index plus one, checked against rules.
func clanNibble(rules *engine.Ruleset, clan int) uint64 {
	poolOf(rules, clan)
	return uint64(clan)
}

// poolOf returns the card pool of clan, 0 for no clan.
func poolOf(rules *engine.Ruleset, clan int) uint64 {
	if clan == 0 {
		return 0
	}
	if clan < 0 || clan > len(rules.Clans) {
		panic("unknown clan")
	}
	return rules.Clans[clan-1].Pool
}

// ---- Chunks

// A chunk holds, for each match id in order, a 2-byte record length and the record. A
// removed match keeps its place with length 0.

// chunkRecord returns the record in slot, or "" when it is removed or beyond the chunk.
func chunkRecord(chunk string, slot int) string {
	r := &reader{s: chunk}
	for i := 0; r.left() > 0; i++ {
		rec := r.text(int(r.u16()))
		if i == slot {
			return rec
		}
	}
	return ""
}

// withChunkRecord returns chunk with slot's record set to rec, adding empty slots up to it.
func withChunkRecord(chunk string, slot int, rec string) string {
	if slot < 0 || slot >= chunkSize {
		panic("slot outside the chunk")
	}
	if len(rec) > 0xFFFF {
		panic("record too long")
	}
	r := &reader{s: chunk}
	w := &writer{}
	for i := 0; i <= slot || r.left() > 0; i++ {
		var old string
		if r.left() > 0 {
			old = r.text(int(r.u16()))
		}
		if i == slot {
			old = rec
		}
		w.u16(uint64(len(old)))
		w.text(old)
	}
	return w.String()
}

// ---- Players

// playerRecord is what the arena keeps per player: the ids of their matches, oldest
// first, and the session locks that bind a session key to one match.
type playerRecord struct {
	ids   []int
	locks []sessionLock
}

type sessionLock struct {
	session address
	id      int
	expires int64
}

// decodePlayer reads a player's bytes: a 2-byte id count, the ids at 4 bytes each, then the
// locks.
// ceiling: joining a match or changing a lock rewrites all of a player's ids, up to 65,535, so
// gas grows with their matches; an avl index of ids per player if some play thousands.
func decodePlayer(s string) playerRecord {
	var p playerRecord
	if s == "" {
		return p
	}
	r := &reader{s: s}
	for n := r.u16(); n > 0; n-- {
		p.ids = append(p.ids, int(r.u32()))
	}
	if r.left()%lockSize != 0 {
		panic("malformed player")
	}
	for r.left() > 0 {
		p.locks = append(p.locks, sessionLock{session: r.addr(), id: int(r.u32()), expires: int64(r.u32())})
	}
	return p
}

func encodePlayer(p playerRecord) string {
	if len(p.ids) > 0xFFFF {
		panic("too many matches")
	}
	w := &writer{}
	w.u16(uint64(len(p.ids)))
	for _, id := range p.ids {
		w.u32(uint64(id))
	}
	for _, l := range p.locks {
		w.addr(l.session)
		w.u32(uint64(l.id))
		w.u32(uint64(l.expires))
	}
	return w.String()
}

// ---- Open challenges

// openEntry is a challenge on the board: its match id and expiry in Unix seconds.
type openEntry struct {
	id      int
	expires int64
}

func openEntries(s string) []openEntry {
	if len(s)%openSize != 0 {
		panic("malformed open list")
	}
	r := &reader{s: s}
	var entries []openEntry
	for r.left() > 0 {
		entries = append(entries, openEntry{id: int(r.u32()), expires: int64(r.u32())})
	}
	return entries
}

func encodeOpen(entries []openEntry) string {
	w := &writer{}
	for _, e := range entries {
		w.u32(uint64(e.id))
		w.u32(uint64(e.expires))
	}
	return w.String()
}

codec_test.gno

package arena

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

// panicsWith fails unless f panics with exactly want.
func panicsWith(t *testing.T, want string, f func()) {
	t.Helper()
	got := "no panic"
	func() {
		defer func() {
			if r := recover(); r != nil {
				got, _ = r.(string)
			}
		}()
		f()
	}()
	uassert.Equal(t, want, got)
}

func TestBits(cur realm, t *testing.T) {
	uassert.Equal(t, uint64(0xB), bitsAt(0xAB, 0, 4))
	uassert.Equal(t, uint64(0xA), bitsAt(0xAB, 4, 4))
	uassert.Equal(t, uint64(0xA5), withBits(0xA0, 0, 4, 5))
	uassert.Equal(t, uint64(1)<<63, withBits(0, 63, 1, 1))
	uassert.Equal(t, uint64(0), withBits(^uint64(0), 0, 64, 0))
	panicsWith(t, "value does not fit", func() {
		withBits(0, 0, 4, 16)
	})
}

func TestWorkedExamplePlans(cur realm, t *testing.T) {
	uassert.Equal(t, uint64(0x71A), withPlan(0, 1, engine.Plan{6, 7}))
	uassert.Equal(t, uint64(0x4107)<<20, withPlan(0, 2, engine.Plan{1, 1, 1}))
	uassert.Equal(t, uint64(0x103A), withPlan(0, 1, engine.Plan{14, 16}))
}

func TestPlansRoundTrip(cur realm, t *testing.T) {
	rules := engine.ProofOfConcept()
	for _, clan := range rules.Clans {
		for _, p := range rules.LegalPlans(rules.Start(), engine.SideA, clan.Pool) {
			for round := 1; round <= 3; round++ {
				got := planAt(withPlan(0, round, p), round)
				urequire.True(t, samePlan(p, got), "plan lost in round "+string(rune('0'+round)))
			}
		}
	}
}

func TestPlanSlotsDoNotOverlap(cur realm, t *testing.T) {
	var plans uint64
	for round := 1; round <= 3; round++ {
		plans = withPlan(plans, round, engine.Plan{63, 63, 63})
	}
	uassert.Equal(t, 3, plansMade(plans))
	plans = withPlan(plans, 2, engine.Plan{1})
	uassert.True(t, samePlan(engine.Plan{1}, planAt(plans, 2)))
	uassert.True(t, samePlan(engine.Plan{63, 63, 63}, planAt(plans, 1)))
	uassert.True(t, samePlan(engine.Plan{63, 63, 63}, planAt(plans, 3)))

	plans = withPlan(0, 1, engine.Plan{63, 63, 63})
	uassert.Equal(t, 1, plansMade(plans))
	uassert.Equal(t, 0, plansMade(0))
	uassert.True(t, planAt(plans, 2) == nil)
}

func TestPlanLimits(cur realm, t *testing.T) {
	for _, c := range []struct {
		round int
		plan  engine.Plan
	}{
		{0, engine.Plan{1}},
		{4, engine.Plan{1}},
		{1, nil},
		{1, engine.Plan{1, 1, 1, 1}},
		{1, engine.Plan{64}},
	} {
		panicsWith(t, "invalid plan", func() {
			withPlan(0, c.round, c.plan)
		})
	}
}

func TestDeckOnPool(cur realm, t *testing.T) {
	rules := engine.ProofOfConcept()
	for _, clan := range rules.Clans {
		n := 0
		for i := 0; i < 64; i++ {
			if clan.Pool&(1<<uint(i)) != 0 {
				n++
			}
		}
		uassert.True(t, n <= 16, clan.Name+" pool holds more than 16 cards")
	}

	for i, deck := range []string{deckA, deckB} {
		pool := rules.Clans[i].Pool
		bits := deckBits(rules, rules.Clans[i], deck)
		uassert.Equal(t, bits, deckFromPool(pool, deckOnPool(pool, bits)))
	}

	panicsWith(t, "deck outside the pool", func() {
		deckOnPool(rules.Clans[1].Pool, deckBits(rules, rules.Clans[0], deckA))
	})
	panicsWith(t, "pool holds more than 16 cards", func() {
		deckOnPool(^uint64(0), 1)
	})
}

func TestMatchRecordRoundTrip(cur realm, t *testing.T) {
	rules := engine.ProofOfConcept()
	deckBitsA := deckBits(rules, rules.Clans[0], deckA)
	deckBitsB := deckBits(rules, rules.Clans[1], deckB)

	box := make([]byte, 104)
	for i := range box {
		box[i] = byte(i * 3)
	}

	open := record{
		phase:      phaseOpen,
		clans:      [2]int{1, 0},
		deadline:   1_790_000_000,
		challenger: alice,
		opponent:   bob,
		deckSeal:   sealOf(saltA, deckA),
		seal:       sealOf(salt1, "Chalk Dust,Double Tap"),
		box:        "box1",
	}
	running := record{
		phase:      phasePlay,
		clans:      [2]int{1, 2},
		deadline:   1_790_086_400,
		decks:      [2]uint64{deckBitsA, deckBitsB},
		plans:      [2]uint64{withPlan(0, 1, engine.Plan{6, 7}), withPlan(0, 1, engine.Plan{14, 16})},
		hp:         [3][2]int{{10, 7}},
		carried:    [2]engine.Vitals{{Vulnerable: 1}, {Strength: 2}},
		challenger: alice,
		acceptor:   bob,
		seal:       sealOf(salt2, picks),
		box:        string(box),
	}
	finished := record{
		phase:      phaseEnded,
		result:     "b",
		reason:     "knockout",
		clans:      [2]int{2, 1},
		deadline:   1_790_172_800,
		decks:      [2]uint64{deckBitsB, deckBitsA},
		plans:      [2]uint64{withPlan(withPlan(0, 1, engine.Plan{1}), 2, engine.Plan{0, 0, 0}), withPlan(0, 3, engine.Plan{63, 63, 63})},
		hp:         [3][2]int{{10, 7}, {4, 0}, {-3, 0}},
		carried:    [2]engine.Vitals{{Vulnerable: 3, Strength: 8}, {Vulnerable: 3, Strength: 8}},
		challenger: alice,
		acceptor:   bob,
	}

	for name, want := range map[string]record{"open": open, "running": running, "finished": finished} {
		b := encodeMatch(rules, want)
		got := decodeMatch(rules, b)
		uassert.True(t, want == got, name+" record changed in a round trip")
	}
	uassert.Equal(t, 115, len(encodeMatch(rules, finished)))
}

func TestMatchRecordLimits(cur realm, t *testing.T) {
	rules := engine.ProofOfConcept()
	base := record{phase: phaseEnded, result: "a", reason: "hp", clans: [2]int{1, 2}, challenger: alice, acceptor: bob}

	hp := base
	hp.hp[0][0] = 128
	panicsWith(t, "hp does not fit a byte", func() { encodeMatch(rules, hp) })

	vuln := base
	vuln.carried[0].Vulnerable = 16
	panicsWith(t, "carried state does not fit", func() { encodeMatch(rules, vuln) })

	phase := base
	phase.phase = "lost"
	panicsWith(t, "unknown phase", func() { encodeMatch(rules, phase) })
}

func TestMatchRecordBox(cur realm, t *testing.T) {
	rules := engine.ProofOfConcept()
	base := record{
		phase: phasePlay, clans: [2]int{1, 2}, challenger: alice, acceptor: bob,
		seal: sealOf(salt2, picks),
	}

	for _, n := range []int{1, 64, maxBox} {
		m := base
		m.box = strings.Repeat("\x00\xff\x07", n)[:n]
		b := encodeMatch(rules, m)
		uassert.Equal(t, 115+32+2+n, len(b))
		uassert.True(t, decodeMatch(rules, b) == m, "box of "+strconv.Itoa(n)+" bytes changed")
	}

	over := base
	over.box = strings.Repeat("x", maxBox+1)
	panicsWith(t, "box too long", func() { encodeMatch(rules, over) })
}

func TestChunkSlots(cur realm, t *testing.T) {
	var chunk string
	chunk = withChunkRecord(chunk, 0, "zero")
	chunk = withChunkRecord(chunk, 5, "five")
	chunk = withChunkRecord(chunk, 63, "sixty-three")
	uassert.Equal(t, "zero", chunkRecord(chunk, 0))
	uassert.Equal(t, "five", chunkRecord(chunk, 5))
	uassert.Equal(t, "sixty-three", chunkRecord(chunk, 63))
	uassert.Equal(t, "", chunkRecord(chunk, 3))
	uassert.Equal(t, "", chunkRecord(chunk, 64))

	chunk = withChunkRecord(chunk, 5, "")
	uassert.Equal(t, "", chunkRecord(chunk, 5))
	uassert.Equal(t, "sixty-three", chunkRecord(chunk, 63))

	chunk = withChunkRecord(chunk, 0, "longer than before")
	uassert.Equal(t, "longer than before", chunkRecord(chunk, 0))
	uassert.Equal(t, "sixty-three", chunkRecord(chunk, 63))

	rec := "abc"
	uassert.Equal(t, 2+2+2+len(rec), len(withChunkRecord("", 2, rec)))
	uassert.Equal(t, "", chunkRecord("", 0))
}

func TestPlayerRecordRoundTrip(cur realm, t *testing.T) {
	locks := []sessionLock{
		{session: bob, id: 7, expires: 1_790_000_000},
		{session: carol, id: 9, expires: 1_790_086_400},
	}
	for _, p := range []playerRecord{
		{},
		{ids: []int{1, 70000, 3}},
		{locks: locks},
		{ids: []int{4, 5, 6}, locks: locks},
	} {
		s := encodePlayer(p)
		got := decodePlayer(s)
		urequire.Equal(t, len(p.ids), len(got.ids))
		urequire.Equal(t, len(p.locks), len(got.locks))
		for i := range p.ids {
			uassert.Equal(t, p.ids[i], got.ids[i])
		}
		for i := range p.locks {
			uassert.True(t, p.locks[i] == got.locks[i])
		}
		uassert.Equal(t, 2+4*len(p.ids)+48*len(p.locks), len(s))
	}
	got := decodePlayer("")
	uassert.Equal(t, 0, len(got.ids)+len(got.locks))
}

func TestOpenListRoundTrip(cur realm, t *testing.T) {
	entries := []openEntry{{1, 1_790_000_000}, {2, 1_790_000_100}, {300000, 1_790_000_200}}
	s := encodeOpen(entries)
	uassert.Equal(t, 8*len(entries), len(s))
	got := openEntries(s)
	urequire.Equal(t, len(entries), len(got))
	for i := range entries {
		uassert.True(t, entries[i] == got[i])
	}
	uassert.Equal(t, 0, len(openEntries("")))
	panicsWith(t, "malformed open list", func() {
		openEntries("short")
	})
}

func TestMalformedPlayer(cur realm, t *testing.T) {
	panicsWith(t, "malformed player", func() { decodePlayer("\x00\x00" + strings.Repeat("\x00", 10)) })
}

gnomod.toml

module = "gno.land/r/nym-gfanton001/gnomepit/arena/v0"
gno = "0.9"

[addpkg]
  creator = "g18me5p9kqqxyswd8ytrmlv3q8kvy7uacx2v90ne"
  height = 865699
  max_deposit = "47000000ugnot"

lock.gno

package arena

import (
	"chain/runtime"
	"strconv"
	"time"
)

// guard binds the session that signed the transaction to match id, held in m, saving the
// caller's record only when its locks change.
func guard(fromUser bool, caller address, m record, id int) {
	session, expires, ok := signingSession(fromUser)
	if !ok {
		return
	}
	if caller != m.challenger && caller != m.acceptor {
		panic("not a player")
	}
	p := loadPlayer(caller)
	if p.lock(session, expires, id, false, time.Now().Unix()) {
		savePlayer(caller, p)
	}
}

// join adds match id to the caller's record and binds the session that signed the
// transaction to it, refused when that session is bound to a match already.
func join(fromUser bool, caller address, id int) {
	p := loadPlayer(caller)
	if session, expires, ok := signingSession(fromUser); ok {
		p.lock(session, expires, id, true, time.Now().Unix())
	}
	p.add(id)
	savePlayer(caller, p)
}

// signingSession returns the signing session key and its expiry when fromUser: a session
// signs the whole transaction, so a call through another realm is left unchecked.
func signingSession(fromUser bool) (address, int64, bool) {
	if !fromUser {
		return "", 0, false
	}
	session, expires, _, ok := runtime.GetSessionInfo()
	return session, expires, ok
}

// lock binds session to match id in p's locks, panicking when it is refused, and reports
// whether the locks changed.
func (p *playerRecord) lock(session address, expires int64, id int, opening bool, now int64) bool {
	locks, changed, refusal := lockSession(p.locks, session, expires, id, opening, now)
	if refusal != "" {
		panic(refusal)
	}
	p.locks = locks
	return changed
}

// lockSession binds session to match id, refused when bound to another, or any when opening.
// It drops expired locks and any lock its key holds under another expiry (Unix seconds, 0 never).
func lockSession(locks []sessionLock, session address, expires int64, id int, opening bool, now int64) (kept []sessionLock, changed bool, refusal string) {
	for _, l := range locks {
		expired := l.expires != 0 && l.expires <= now
		stale := l.session == session && l.expires != expires
		if !expired && !stale {
			kept = append(kept, l)
		}
	}
	changed = len(kept) != len(locks)
	for _, l := range kept {
		if l.session != session {
			continue
		}
		if opening || l.id != id {
			return kept, changed, "session locked to match " + strconv.Itoa(l.id)
		}
		return kept, changed, ""
	}
	return append(kept, sessionLock{session: session, id: id, expires: expires}), true, ""
}

lock_test.gno

package arena

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

var (
	keyOne   = testutils.TestAddress("key one")
	keyTwo   = testutils.TestAddress("key two")
	keyThree = testutils.TestAddress("key three")
)

// showLocks lists locks as key:match:expiry, naming the test keys.
func showLocks(locks []sessionLock) string {
	names := map[address]string{keyOne: "one", keyTwo: "two", keyThree: "three"}
	var out []string
	for _, l := range locks {
		out = append(out, names[l.session]+":"+strconv.Itoa(l.id)+":"+strconv.FormatInt(l.expires, 10))
	}
	return strings.Join(out, " ")
}

func TestUnlockedSessionLocks(t *testing.T) {
	for _, opening := range []bool{true, false} {
		locks, changed, refusal := lockSession(nil, keyOne, 2000, 3, opening, 1000)
		uassert.Equal(t, "", refusal)
		uassert.True(t, changed)
		uassert.Equal(t, "one:3:2000", showLocks(locks))
	}
	locks, changed, refusal := lockSession([]sessionLock{{keyTwo, 4, 2000}}, keyOne, 2000, 3, false, 1000)
	uassert.Equal(t, "", refusal)
	uassert.True(t, changed)
	uassert.Equal(t, "two:4:2000 one:3:2000", showLocks(locks))
}

func TestLockedSessionRefusedElsewhere(t *testing.T) {
	locked := []sessionLock{{keyOne, 3, 2000}}
	_, _, refusal := lockSession(locked, keyOne, 2000, 5, false, 1000)
	uassert.Equal(t, "session locked to match 3", refusal)

	locks, changed, refusal := lockSession(locked, keyOne, 2000, 3, false, 1000)
	uassert.Equal(t, "", refusal)
	uassert.False(t, changed)
	uassert.Equal(t, "one:3:2000", showLocks(locks))
}

func TestLockedSessionCannotOpen(t *testing.T) {
	locked := []sessionLock{{keyOne, 3, 2000}}
	// Match 3 itself is refused too: a session cannot accept the challenge it posted.
	for _, id := range []int{3, 7} {
		_, _, refusal := lockSession(locked, keyOne, 2000, id, true, 1000)
		uassert.Equal(t, "session locked to match 3", refusal, strconv.Itoa(id))
	}
}

func TestExpiredLockDropped(t *testing.T) {
	locks := []sessionLock{{keyOne, 3, 1000}, {keyTwo, 4, 1001}}
	got, changed, refusal := lockSession(locks, keyThree, 2000, 5, true, 1000)
	uassert.Equal(t, "", refusal)
	// One lock dropped and one added keep the count, and still change the list.
	uassert.True(t, changed)
	uassert.Equal(t, "two:4:1001 three:5:2000", showLocks(got))

	got, changed, refusal = lockSession(locks, keyTwo, 1001, 4, false, 1000)
	uassert.Equal(t, "", refusal)
	uassert.True(t, changed)
	uassert.Equal(t, "two:4:1001", showLocks(got))
}

func TestLockWithoutExpiry(t *testing.T) {
	const later = int64(2_000_000_000)
	locks := []sessionLock{{keyOne, 3, 0}}
	got, _, refusal := lockSession(locks, keyTwo, 0, 4, true, later)
	uassert.Equal(t, "", refusal)
	uassert.Equal(t, "one:3:0 two:4:0", showLocks(got))

	_, _, refusal = lockSession(got, keyOne, 0, 5, false, later)
	uassert.Equal(t, "session locked to match 3", refusal)
}

func TestReusedKeyStartsUnlocked(t *testing.T) {
	locks := []sessionLock{{keyOne, 3, 2000}, {keyTwo, 4, 2000}}
	got, changed, refusal := lockSession(locks, keyOne, 2500, 5, true, 1000)
	uassert.Equal(t, "", refusal)
	uassert.True(t, changed)
	uassert.Equal(t, "two:4:2000 one:5:2500", showLocks(got))
}

// This pins the flag guard saves the player record on: a move in the session's own match
// changes nothing, so it writes nothing.
func TestLockReportsNoChangeInOwnMatch(t *testing.T) {
	p := playerRecord{ids: []int{3, 4}, locks: []sessionLock{{keyOne, 3, 2000}, {keyTwo, 4, 2000}}}
	uassert.False(t, p.lock(keyOne, 2000, 3, false, 1000))
	uassert.Equal(t, "one:3:2000 two:4:2000", showLocks(p.locks))

	uassert.True(t, p.lock(keyThree, 2000, 5, true, 1000))
	uassert.Equal(t, "one:3:2000 two:4:2000 three:5:2000", showLocks(p.locks))

	uassert.PanicsWithMessage(t, nil, "session locked to match 3", func() { p.lock(keyOne, 2000, 4, false, 1000) })
}

func TestLocksQuery(cur realm, t *testing.T) {
	reset()
	p := loadPlayer(alice)
	p.add(3)
	p.locks = []sessionLock{{keyOne, 3, 2000}, {keyTwo, 12, 0}}
	savePlayer(alice, p)

	got := Locks(alice)
	urequire.Equal(t, 2, len(got))
	uassert.Equal(t, keyOne.String(), got[0].Session)
	uassert.Equal(t, "3", got[0].Match)
	uassert.Equal(t, int64(2000), got[0].Expires)
	uassert.Equal(t, keyTwo.String(), got[1].Session)
	uassert.Equal(t, "12", got[1].Match)
	uassert.Equal(t, int64(0), got[1].Expires)
	uassert.Equal(t, 0, len(Locks(bob)))
}

notify.gno

package arena

import (
	"chain"
	"strconv"

	"gno.land/r/nym-gfanton001/gnotif/v1"
)

// self is the arena's package path; a deploy under another path changes it.
var self string

// pagePath is where the page lives on its origin, the start of every trigger's link; the
// registry accepts only a link that starts with "/".
const pagePath = "/gnomepit/"

// init sets the arena's three gnotif triggers and keeps no handle, so they stay as set
// for this deploy. A Turn or Ended event carries the address it notifies in "to", so a
// browser opts in with its wallet's address; a Board event notifies every browser that
// opted in.
func init(cur realm) {
	self = cur.PkgPath()
	me := cur.Sub(gnotif.Subpath)
	h := gnotif.Open(cross(me))
	h.Set(cross(me), "turn", gnotif.Trigger{Event: "Turn", Param: "to", Title: "Your move in Gnomepit", Body: "{text}", Link: pagePath + "#match={match}"})
	h.Set(cross(me), "ended", gnotif.Trigger{Event: "Ended", Param: "to", Title: "Match over", Body: "{text}", Link: pagePath + "#match={match}"})
	h.Set(cross(me), "board", gnotif.Trigger{Event: "Board", Title: "Gnomepit challenges", Body: "{text}", Link: pagePath})
}

// tell emits kind to player about match id. It emits nothing when player made the call,
// so an event never names its caller.
func tell(kind string, player, caller address, id int, text string) {
	if player == caller {
		return
	}
	chain.Emit(kind, "to", player.String(), "match", strconv.Itoa(id), "text", text)
}

// tellBoard emits Board about match id, whose change altered the open-challenge list. It
// names no address, so a caller cannot aim it at one player's browser.
func tellBoard(id int, text string) {
	chain.Emit("Board", "match", strconv.Itoa(id), "text", text)
}

// tellEnded sends Ended to each player of the finished match m, numbered id, but caller,
// one event each, since gnotif reads only the first value of a repeated attribute.
func tellEnded(m record, id int, caller address) {
	tell("Ended", m.challenger, caller, id, endText(m, 0))
	if m.acceptor != m.challenger {
		tell("Ended", m.acceptor, caller, id, endText(m, 1))
	}
}

// endText says how m ended to the player on side.
func endText(m record, side int) string {
	won := m.result == "a" && side == 0 || m.result == "b" && side == 1
	switch m.reason {
	case "hp":
		last := m.hp[plansMade(m.plans[0])-1]
		score := strconv.Itoa(last[side]) + " to " + strconv.Itoa(last[1-side]) + "."
		switch {
		case m.result == "draw":
			return "Draw on HP, " + score
		case won:
			return "You won on HP, " + score
		}
		return "You lost on HP, " + score
	case "knockout":
		switch {
		case m.result == "draw":
			return "Both gnomes fell: a draw."
		case won:
			return "You won by knockout."
		}
		return "You lost by knockout."
	case "resign":
		if won {
			return "Your opponent resigned. You won."
		}
		return "You resigned."
	}
	if won {
		return "You won by forfeit."
	}
	return "You lost by forfeit."
}

notify_test.gno

package arena

import (
	"strings"
	"testing"

	"gno.land/p/nt/markdown/sanitize/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
	"gno.land/r/nym-gfanton001/gnotif/v1"
)

func TestInitSetsTriggers(cur realm, t *testing.T) {
	ids := strings.Split(gnotif.Active(self), ",")
	urequire.Equal(t, 3, len(ids))
	want := [][6]string{ // name, event, param, title, body, link
		// The page opens the match a #match= fragment names.
		{"turn", "Turn", "to", "Your move in Gnomepit", "{text}", pagePath + "#match={match}"},
		{"ended", "Ended", "to", "Match over", "{text}", pagePath + "#match={match}"},
		{"board", "Board", "", "Gnomepit challenges", "{text}", pagePath},
	}
	for i, w := range want {
		page := gnotif.Render("trigger/" + ids[i])
		for j, label := range []string{"Name", "Event", "Param", "Title", "Body", "Link"} {
			// The registry renders each field through the same sanitizer.
			line := "- " + label + ": " + sanitize.InlineText(w[j]) + "\n"
			uassert.True(t, strings.Contains(page, line), ids[i]+" lacks "+line)
		}
	}
}

owner.gno

package arena

import (
	"chain/runtime"

	"gno.land/p/nt/ownable/v0"
	"gno.land/r/nym-gfanton001/gnomepit/standings/v0"
)

var (
	owner   *ownable.Ownable
	retired bool
)

func init(cur realm) {
	owner = ownable.NewWithAddress(cur.Previous().Address())
}

// Retire closes the arena to new challenges and acceptances, for good. Matches already
// running play out and are rated, and an open challenge can still be withdrawn. Owner
// only.
func Retire(cur realm) {
	refuseSession()
	owner.AssertOwnedBy(cur.Previous().Address())
	retired = true
}

// TransferOwnership makes newOwner the owner. Owner only.
func TransferOwnership(cur realm, newOwner address) {
	refuseSession()
	if err := owner.TransferOwnership(0, cur, newOwner); err != nil {
		panic(err.Error())
	}
}

// Retired reports whether the owner has retired the arena.
func Retired() bool {
	return retired
}

// Owner is the address that may retire the arena.
func Owner() address {
	return owner.Owner()
}

// refuseSession refuses a call signed with a session key: the page signs a match's moves
// with one, so an owner who plays from the owner's wallet must not hand it the owner's calls.
func refuseSession() {
	if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
		panic("sign with the owner's own key, not a session key")
	}
}

// mustBeOpen refuses a new match on a retired arena, or on one the standings realm takes no
// results from.
func mustBeOpen() {
	if retired {
		panic("arena retired")
	}
	if !standings.IsWriter(self) {
		panic("arena not open")
	}
}

owner_test.gno

package arena

import (
	"testing"

	"gno.land/p/nt/ownable/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/r/nym-gfanton001/gnomepit/standings/v0"
)

// Under gno test, init's deployer address is empty, so each test sets the owner itself.

func TestRetireIsOwnerOnly(cur realm, t *testing.T) {
	reset()
	owner = ownable.NewWithAddress(alice)

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "ownable: caller is not owner", func() { Retire(cross(cur)) })
	uassert.AbortsWithMessage(t, cur, "ownable: caller is not owner", func() { TransferOwnership(cross(cur), bob) })
	uassert.False(t, Retired())
	uassert.Equal(t, alice, Owner())

	testing.SetRealm(testing.NewUserRealm(alice))
	Retire(cross(cur))
	uassert.True(t, Retired())
	TransferOwnership(cross(cur), bob)
	uassert.Equal(t, bob, Owner())
}

func TestRetiredArenaRefusesNewMatches(cur realm, t *testing.T) {
	reset()
	owner = ownable.NewWithAddress(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	Retire(cross(cur))

	uassert.AbortsWithMessage(t, cur, "arena retired", func() {
		Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	})
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "arena retired", func() { Accept(cross(cur), id, "Ironhide", deckB, braces) })
}

func TestRetiredArenaFinishesItsMatches(cur realm, t *testing.T) {
	reset()
	owner = ownable.NewWithAddress(alice)
	a1, b1 := "Chalk Dust,Double Tap", "Hammer Blow,Spiked Shield"
	testing.SetRealm(testing.NewUserRealm(alice))
	open := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	running := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, a1), boxOf("box1"), "")
	stalled := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), running, "Ironhide", deckB, b1)
	Accept(cross(cur), stalled, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), running, deckA, saltA, a1, salt1, sealOf(salt2, picks), boxOf("box2"))
	Retire(cross(cur))

	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), running, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), running, "", "", picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	uassert.Equal(t, "play", Match(running).Phase)
	testing.SetRealm(testing.NewUserRealm(bob))
	Resign(cross(cur), running)
	uassert.Equal(t, "resign", Match(running).Reason)

	testing.SkipHeights(day + 1)
	testing.SetRealm(testing.NewUserRealm(carol))
	ClaimForfeit(cross(cur), stalled)
	uassert.Equal(t, "forfeit", Match(stalled).Reason)

	testing.SetRealm(testing.NewUserRealm(alice))
	Resign(cross(cur), open)
	uassert.Equal(t, 0, len(Open(0, 50)), "the open challenge is withdrawn")
}

func TestRetiredArenaStillRates(cur realm, t *testing.T) {
	reset()
	owner = ownable.NewWithAddress(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Retire(cross(cur))

	before := standings.ResultCount()
	testing.SetRealm(testing.NewUserRealm(bob))
	Resign(cross(cur), id)
	uassert.Equal(t, before+1, standings.ResultCount())
}

play.gno

package arena

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

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
)

// Accept answers open challenge id as clan, with deck and the round-1 plan in plain
// text. When the challenge names an opponent, only that address may accept.
func Accept(cur realm, id, clan, deck, plan string) {
	mustBeOpen()
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	now := time.Now().Unix()
	if m.phase != phaseOpen {
		panic("wrong phase")
	}
	if m.expired(now) {
		panic("challenge expired")
	}
	caller := cur.Previous().Address()
	if m.opponent != "" && caller != m.opponent {
		panic("not the named opponent")
	}
	c := clanNumber(rules, clan)
	if c == 0 {
		panic("unknown clan")
	}
	bits := deckBits(rules, rules.Clans[c-1], deck)
	b := planOf(rules, plan)
	if !legal(rules, stateOf(rules, m), engine.SideB, bits, b) {
		panic("illegal plan")
	}

	m.acceptor = caller
	m.opponent = ""
	join(cur.Previous().IsUser(), caller, n)
	m.clans[1] = c
	m.decks[1] = bits
	m.plans[1] = withPlan(m.plans[1], 1, b)
	m.phase = phaseReveal
	m.deadline = now + moveWindow
	saveMatch(rules, n, m)
	openRemove(n)
	tellBoard(n, "Challenge "+strconv.Itoa(n)+" was taken.")
	tell("Turn", m.challenger, caller, n, clan+" accepted your challenge. Your move within 24 hours.")
}

// Reveal opens the challenger's sealed plan for the round being played, and on the
// first reveal the sealed deck, then resolves the round. A match that goes on needs
// nextSeal and nextBox for the challenger's next plan; one that ends takes neither.
func Reveal(cur realm, id, deck, deckSalt, plan, planSalt, nextSeal, nextBox string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	now := time.Now().Unix()
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	m.checkMove(caller, phaseReveal, m.challenger, now)

	s := stateOf(rules, m)
	first := s.Round == 1
	bits := m.decks[0]
	if first {
		if deck == "" {
			panic("deck required")
		}
		checkSeal(m.deckSeal, deckSalt, deck)
		bits = deckBits(rules, rules.Clans[m.clans[0]-1], deck)
	} else if deck != "" || deckSalt != "" {
		panic("deck already revealed")
	}
	checkSeal(m.seal, planSalt, plan)
	a := planOf(rules, plan)
	if !legal(rules, s, engine.SideA, bits, a) {
		panic("illegal plan")
	}
	o := rules.Resolve(s, a, planAt(m.plans[1], s.Round))
	var box string
	if o.Result == engine.Ongoing {
		if nextSeal == "" {
			panic("next seal required")
		}
		if !validSeal(nextSeal) {
			panic("invalid seal")
		}
		box = boxBytes(nextBox)
	} else if nextSeal != "" || nextBox != "" {
		panic("unexpected next seal")
	}

	if first {
		m.decks[0] = bits
		m.deckSeal = ""
	}
	m.plans[0] = withPlan(m.plans[0], s.Round, a)
	for side, g := range o.State.Gnomes {
		m.hp[s.Round-1][side] = g.HP
		m.carried[side] = engine.Vitals{Vulnerable: g.Vulnerable, Strength: g.Strength}
	}
	m.seal, m.box = nextSeal, box
	if o.Result != engine.Ongoing {
		m.end(resultName(o.Result), reasonOf(o.State))
		saveMatch(rules, n, m)
		report(cur, rules, m)
		tellEnded(m, n, caller)
		return
	}
	m.phase = phasePlay
	m.deadline = now + moveWindow
	saveMatch(rules, n, m)
	hp := m.hp[s.Round-1]
	tell("Turn", m.acceptor, caller, n, "Round "+strconv.Itoa(s.Round)+" is over: you "+strconv.Itoa(hp[1])+
		" HP, them "+strconv.Itoa(hp[0])+". Your move within 24 hours.")
}

// Play records the acceptor's plan for the round being played.
func Play(cur realm, id, plan string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	now := time.Now().Unix()
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	m.checkMove(caller, phasePlay, m.acceptor, now)
	s := stateOf(rules, m)
	b := planOf(rules, plan)
	if !legal(rules, s, engine.SideB, m.decks[1], b) {
		panic("illegal plan")
	}
	m.plans[1] = withPlan(m.plans[1], s.Round, b)
	m.phase = phaseReveal
	m.deadline = now + moveWindow
	saveMatch(rules, n, m)
	tell("Turn", m.challenger, caller, n, clanName(rules, m.clans[1])+" played round "+strconv.Itoa(s.Round)+". Your move within 24 hours.")
}

// Resign withdraws the caller's open challenge, expired or not, deleting it, or concedes
// a running match.
func Resign(cur realm, id string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	switch m.phase {
	case phaseOpen:
		if caller != m.challenger {
			panic("not your challenge")
		}
		openRemove(n)
		forget(n, m.challenger)
		tellBoard(n, "Challenge "+strconv.Itoa(n)+" was withdrawn.")
	case phaseReveal, phasePlay:
		switch caller {
		case m.challenger:
			m.end("b", "resign")
		case m.acceptor:
			m.end("a", "resign")
		default:
			panic("not a player")
		}
		saveMatch(rules, n, m)
		report(cur, rules, m)
		tellEnded(m, n, caller)
	default:
		panic("wrong phase")
	}
}

// ClaimForfeit ends a running match whose deadline has passed: the player who had to
// move loses. Any wallet may claim it; a session may claim only a match its wallet plays.
func ClaimForfeit(cur realm, id string) {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	caller := cur.Previous().Address()
	guard(cur.Previous().IsUser(), caller, m, n)
	var result string
	switch m.phase {
	case phaseReveal:
		result = "b"
	case phasePlay:
		result = "a"
	default:
		panic("wrong phase")
	}
	if time.Now().Unix() <= m.deadline {
		panic("deadline not passed")
	}
	m.end(result, "forfeit")
	saveMatch(rules, n, m)
	report(cur, rules, m)
	tellEnded(m, n, caller)
}

func find(rules *engine.Ruleset, id string) (int, record) {
	n, m, ok := lookup(rules, id)
	if !ok {
		panic("unknown match")
	}
	return n, m
}

// lookup returns the match id names, false when there is none. Only an id's own decimal
// text names it, never "01" or "+1".
func lookup(rules *engine.Ruleset, id string) (int, record, bool) {
	if len(id) == 0 || len(id) > idDigits {
		return 0, record{}, false
	}
	n, err := strconv.Atoi(id)
	if err != nil || strconv.Itoa(n) != id {
		return 0, record{}, false
	}
	m, ok := loadMatch(rules, n)
	return n, m, ok
}

func (m record) checkMove(caller address, phase string, mover address, now int64) {
	if m.phase != phase {
		panic("wrong phase")
	}
	if caller != mover {
		panic("not your move")
	}
	if now > m.deadline {
		panic("deadline passed")
	}
}

func (m *record) end(result, reason string) {
	m.phase = phaseEnded
	m.result = result
	m.reason = reason
	m.deckSeal, m.seal, m.box = "", "", ""
}

// stateOf rebuilds the engine state the next round of m starts from. A round is resolved
// once the challenger's plan for it is stored; the specials of resolved rounds are spent.
func stateOf(rules *engine.Ruleset, m record) engine.State {
	resolved := plansMade(m.plans[0])
	s := rules.Start()
	s.Round = resolved + 1
	for side := range s.Gnomes {
		g := &s.Gnomes[side]
		if resolved > 0 {
			g.HP = m.hp[resolved-1][side]
		}
		g.Vulnerable = m.carried[side].Vulnerable
		g.Strength = m.carried[side].Strength
		for round := 1; round <= resolved; round++ {
			for _, id := range planAt(m.plans[side], round) {
				if rules.Cards[id].Special {
					g.Spent |= uint64(1) << uint(id)
				}
			}
		}
	}
	return s
}

// checkSeal panics unless seal is the sha256 of salt's bytes followed by text.
func checkSeal(seal, salt, text string) {
	if !validSeal(salt) {
		panic("invalid salt")
	}
	b, _ := hex.DecodeString(salt)
	sum := sha256.Sum256(append(b, text...))
	if hex.EncodeToString(sum[:]) != seal {
		panic("seal mismatch")
	}
}

// clanNumber is clan's index in rules plus one, as a record stores it, or 0 when no clan
// has that name.
func clanNumber(rules *engine.Ruleset, clan string) int {
	for i, c := range rules.Clans {
		if c.Name == clan {
			return i + 1
		}
	}
	return 0
}

// clanName is the name of the clan a record stores as n, "" for none.
func clanName(rules *engine.Ruleset, n int) string {
	if n == 0 {
		return ""
	}
	return rules.Clans[n-1].Name
}

// planOf maps comma-separated card names to the engine's ids.
func planOf(rules *engine.Ruleset, text string) engine.Plan {
	p, ok := rules.PlanOf(strings.Split(text, ",")...)
	if !ok {
		panic("unknown card")
	}
	return p
}

// deckBits returns deck as the engine's bit set, panicking unless it is legal for c. A
// card named twice is illegal, so a legal deck text holds exactly the deck's names.
func deckBits(rules *engine.Ruleset, c engine.Clan, deck string) uint64 {
	var bits uint64
	for _, id := range planOf(rules, deck) {
		bit := uint64(1) << uint(id)
		if bits&bit != 0 {
			panic("illegal deck")
		}
		bits |= bit
	}
	if !rules.LegalDeck(c, bits) {
		panic("illegal deck")
	}
	return bits
}

func legal(rules *engine.Ruleset, s engine.State, side engine.Side, deck uint64, p engine.Plan) bool {
	for _, q := range rules.LegalPlans(s, side, deck) {
		if samePlan(p, q) {
			return true
		}
	}
	return false
}

func samePlan(p, q engine.Plan) bool {
	if len(p) != len(q) {
		return false
	}
	for i := range p {
		if p[i] != q[i] {
			return false
		}
	}
	return true
}

func resultName(r engine.Result) string {
	switch r {
	case engine.AWins:
		return "a"
	case engine.BWins:
		return "b"
	case engine.Draw:
		return "draw"
	}
	return ""
}

// reasonOf says why a finished match ended: a gnome at 0 HP or less is a knockout.
func reasonOf(s engine.State) string {
	if s.Gnomes[0].HP <= 0 || s.Gnomes[1].HP <= 0 {
		return "knockout"
	}
	return "hp"
}

play_test.gno

package arena

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

const (
	deckA = "Pickaxe Flurry,Kneecap,Sling Stone,Dodge Roll,Chalk Dust,Double Tap,Momentum,Undermine"
	deckB = "Stone Guard,Bulwark,Hammer Blow,Cobble Throw,Spiked Shield,Anvil Stomp,Feint,Avalanche"

	salt1 = "1111111111111111111111111111111111111111111111111111111111111111"
	salt2 = "2222222222222222222222222222222222222222222222222222222222222222"
	salt3 = "3333333333333333333333333333333333333333333333333333333333333333"

	picks  = "Pick,Pick,Pick"
	braces = "Brace,Brace,Brace"

	day = 86400 / 5 // block heights in 24 hours at the test chain's 5 s per block
)

// recordOf loads match id as the realm stores it.
func recordOf(t *testing.T, id string) record {
	n, err := strconv.Atoi(id)
	urequire.NoError(t, err)
	m, ok := loadMatch(engine.ProofOfConcept(), n)
	urequire.True(t, ok, "match "+id+" is not stored")
	return m
}

// resolveAll plays rounds of [A plan, B plan] with the engine directly.
func resolveAll(rounds ...[2]string) engine.Outcome {
	rules := engine.ProofOfConcept()
	s := rules.Start()
	var o engine.Outcome
	for _, r := range rounds {
		a, _ := rules.PlanOf(strings.Split(r[0], ",")...)
		b, _ := rules.PlanOf(strings.Split(r[1], ",")...)
		o = rules.Resolve(s, a, b)
		s = o.State
	}
	return o
}

func TestWorkedExample(cur realm, t *testing.T) {
	reset()
	a1, b1 := "Chalk Dust,Double Tap", "Hammer Blow,Spiked Shield"

	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, a1), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, b1)
	uassert.Equal(t, phaseReveal, Match(id).Phase)
	uassert.Equal(t, 0, len(Open(0, 50)))

	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, a1, salt1, sealOf(salt2, picks), boxOf("box2"))
	uassert.Equal(t, phasePlay, Match(id).Phase)
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", picks, salt3, "", "")

	want := resolveAll([2]string{a1, b1}, [2]string{picks, braces}, [2]string{picks, braces})
	v := Match(id)
	uassert.Equal(t, phaseEnded, v.Phase)
	uassert.Equal(t, resultName(want.Result), v.Result)
	uassert.Equal(t, "hp", v.Reason)
	urequire.Equal(t, 3, len(v.HP))
	uassert.Equal(t, want.State.Gnomes[0].HP, v.HP[2][0])
	uassert.Equal(t, want.State.Gnomes[1].HP, v.HP[2][1])
	uassert.Equal(t, deckA, v.ChallengerDeck)
	uassert.Equal(t, a1, v.Plans[0][0])
	uassert.Equal(t, b1, v.Plans[0][1])
}

func TestKnockoutEndsTheMatchEarly(cur realm, t *testing.T) {
	reset()
	b1, b2 := "Pick,Anvil Stomp", "Hammer Blow,Cobble Throw"

	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, b1)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, b2)

	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "unexpected next seal", func() {
		Reveal(cross(cur), id, "", "", picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	})
	Reveal(cross(cur), id, "", "", picks, salt2, "", "")

	v := Match(id)
	uassert.Equal(t, phaseEnded, v.Phase)
	uassert.Equal(t, "b", v.Result)
	uassert.Equal(t, "knockout", v.Reason)
	uassert.Equal(t, 2, len(v.HP))
}

func TestDrawOnHP(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, braces), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, braces, salt1, sealOf(salt2, braces), boxOf("box2"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", braces, salt2, sealOf(salt3, braces), boxOf("box3"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", braces, salt3, "", "")

	v := Match(id)
	uassert.Equal(t, "draw", v.Result)
	uassert.Equal(t, "hp", v.Reason)
}

func TestSelfPlay(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	Play(cross(cur), id, braces)
	Reveal(cross(cur), id, "", "", picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	Play(cross(cur), id, braces)
	Reveal(cross(cur), id, "", "", picks, salt3, "", "")
	uassert.Equal(t, phaseEnded, Match(id).Phase)
	uassert.Equal(t, id, summaryIDs(Matches(alice, 0, 50)), "a match the player posted and accepted is listed once")
}

func TestAcceptRejects(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	openID := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	namedID := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), bob)

	testing.SetRealm(testing.NewUserRealm(carol))
	cases := []struct {
		name, id, clan, deck, plan, want string
	}{
		{"unknown match", "99", "Ironhide", deckB, braces, "unknown match"},
		{"not the named opponent", namedID, "Ironhide", deckB, braces, "not the named opponent"},
		{"unknown clan", openID, "Elves", deckB, braces, "unknown clan"},
		{"a card twice", openID, "Ironhide", strings.Replace(deckB, "Bulwark", "Stone Guard", 1), braces, "illegal deck"},
		{"a ninth name repeating a card", openID, "Ironhide", deckB + ",Stone Guard", braces, "illegal deck"},
		{"another clan's card", openID, "Ironhide", strings.Replace(deckB, "Bulwark", "Kneecap", 1), braces, "illegal deck"},
		{"unknown card", openID, "Ironhide", strings.Replace(deckB, "Bulwark", "Bulwerk", 1), braces, "unknown card"},
		{"two beats", openID, "Ironhide", deckB, "Pick,Pick", "illegal plan"},
		{"a card outside the deck", openID, "Ironhide", deckB, "Shield Catch,Pick", "illegal plan"},
	}
	for _, c := range cases {
		uassert.AbortsWithMessage(t, cur, c.want, func() {
			Accept(cross(cur), c.id, c.clan, c.deck, c.plan)
		}, c.name)
	}

	Accept(cross(cur), openID, "Ironhide", deckB, braces)
	uassert.AbortsWithMessage(t, cur, "wrong phase", func() {
		Accept(cross(cur), openID, "Ironhide", deckB, braces)
	})

	testing.SkipHeights(7*day + 1)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "challenge expired", func() {
		Accept(cross(cur), namedID, "Ironhide", deckB, braces)
	})
}

// The named opponent is the only one who can accept, and the acceptor then names them, so a
// copy would keep 40 bytes for good.
func TestAcceptForgetsTheNamedOpponent(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	named := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), bob)
	open := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	uassert.Equal(t, bob.String(), Match(named).Opponent)

	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), named, "Ironhide", deckB, braces)
	Accept(cross(cur), open, "Ironhide", deckB, braces)

	uassert.Equal(t, "", recordOf(t, named).opponent.String())
	stored := func(id string) string {
		n, _ := strconv.Atoi(id)
		return chunkRecord(stringAt(&chunks, chunkKey(n)), (n-1)%chunkSize)
	}
	uassert.Equal(t, len(stored(open)), len(stored(named)), "an accepted reserved match stores what an accepted open one does")
	v := Match(named)
	uassert.Equal(t, "", v.Opponent)
	uassert.Equal(t, bob.String(), v.Acceptor)
}

func TestRevealRejects(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	badPlan := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, "Pick,Pick"), boxOf("box1"), "")
	badDeck := Challenge(cross(cur), "Pickers", sealOf(saltA, "Pick"), sealOf(salt1, picks), boxOf("box1"), "")
	longDeck := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA+",Kneecap"), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	Accept(cross(cur), badPlan, "Ironhide", deckB, braces)
	Accept(cross(cur), badDeck, "Ironhide", deckB, braces)
	Accept(cross(cur), longDeck, "Ironhide", deckB, braces)
	next := sealOf(salt2, picks)

	uassert.AbortsWithMessage(t, cur, "not your move", func() {
		Reveal(cross(cur), id, deckA, saltA, picks, salt1, next, boxOf("box2"))
	})

	testing.SetRealm(testing.NewUserRealm(alice))
	cases := []struct {
		name, id, deck, deckSalt, plan, planSalt, nextSeal, nextBox, want string
	}{
		{"no deck", id, "", "", picks, salt1, next, boxOf("box2"), "deck required"},
		{"wrong deck salt", id, deckA, saltB, picks, salt1, next, boxOf("box2"), "seal mismatch"},
		{"wrong plan salt", id, deckA, saltA, picks, salt2, next, boxOf("box2"), "seal mismatch"},
		{"short salt", id, deckA, saltA[2:], picks, salt1, next, boxOf("box2"), "invalid salt"},
		{"illegal plan", badPlan, deckA, saltA, "Pick,Pick", salt1, next, boxOf("box2"), "illegal plan"},
		{"illegal deck", badDeck, "Pick", saltA, picks, salt1, next, boxOf("box2"), "illegal deck"},
		{"a ninth name repeating a card", longDeck, deckA + ",Kneecap", saltA, picks, salt1, next, boxOf("box2"), "illegal deck"},
		{"no next seal", id, deckA, saltA, picks, salt1, "", "", "next seal required"},
		{"bad next seal", id, deckA, saltA, picks, salt1, "abc", boxOf("box2"), "invalid seal"},
		{"no next box", id, deckA, saltA, picks, salt1, next, "", "invalid box"},
		{"next box not base64", id, deckA, saltA, picks, salt1, next, "box", "invalid box"},
	}
	for _, c := range cases {
		uassert.AbortsWithMessage(t, cur, c.want, func() {
			Reveal(cross(cur), c.id, c.deck, c.deckSalt, c.plan, c.planSalt, c.nextSeal, c.nextBox)
		}, c.name)
	}

	Reveal(cross(cur), id, deckA, saltA, picks, salt1, next, boxOf("box2"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "deck already revealed", func() {
		Reveal(cross(cur), id, deckA, saltA, picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	})

	testing.SkipHeights(day + 1)
	uassert.AbortsWithMessage(t, cur, "deadline passed", func() {
		Reveal(cross(cur), id, "", "", picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	})
}

func TestPlayRejects(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	uassert.AbortsWithMessage(t, cur, "wrong phase", func() { Play(cross(cur), id, braces) })

	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	uassert.AbortsWithMessage(t, cur, "not your move", func() { Play(cross(cur), id, braces) })

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "illegal plan", func() { Play(cross(cur), id, "Kneecap,Pick,Pick") })
	testing.SkipHeights(day + 1)
	uassert.AbortsWithMessage(t, cur, "deadline passed", func() { Play(cross(cur), id, braces) })
}

func TestEndClearsSealAndBox(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	resigned := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	forfeited := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), resigned, "Ironhide", deckB, braces)
	Accept(cross(cur), forfeited, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Resign(cross(cur), resigned)
	Reveal(cross(cur), forfeited, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	testing.SkipHeights(day + 1)
	ClaimForfeit(cross(cur), forfeited)

	for _, id := range []string{resigned, forfeited} {
		uassert.Equal(t, "", Match(id).Box, id)
		m := recordOf(t, id)
		uassert.Equal(t, "", m.deckSeal, id+": a deck seal resigned before its reveal is never checked")
		uassert.Equal(t, "", m.seal, id)
		uassert.Equal(t, "", m.box, id)
	}
}

func showState(s engine.State) string {
	out := "round " + strconv.Itoa(s.Round)
	for _, g := range s.Gnomes {
		out += " | hp " + strconv.Itoa(g.HP) + " vulnerable " + strconv.Itoa(g.Vulnerable) +
			" strength " + strconv.Itoa(g.Strength) + " spent " + strconv.FormatUint(g.Spent, 2)
	}
	return out
}

// After every round of whole matches, the state the realm rebuilds is the engine's own.
func TestStateMatchesEngine(cur realm, t *testing.T) {
	rules := engine.ProofOfConcept()
	salts := []string{salt1, salt2, salt3}
	cases := []struct {
		name   string
		rounds [][2]string
	}{
		{"worked example", [][2]string{{"Chalk Dust,Double Tap", "Hammer Blow,Spiked Shield"}, {picks, braces}, {picks, braces}}},
		{"knockout", [][2]string{{picks, "Pick,Anvil Stomp"}, {picks, "Hammer Blow,Cobble Throw"}}},
		{"draw", [][2]string{{braces, braces}, {braces, braces}, {braces, braces}}},
	}
	for _, c := range cases {
		reset()
		testing.SetRealm(testing.NewUserRealm(alice))
		id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salts[0], c.rounds[0][0]), boxOf("box1"), "")
		testing.SetRealm(testing.NewUserRealm(bob))
		Accept(cross(cur), id, "Ironhide", deckB, c.rounds[0][1])
		uassert.Equal(t, showState(rules.Start()), showState(stateOf(rules, recordOf(t, id))), c.name+" before round 1")

		for r, plans := range c.rounds {
			deck, deckSalt, next, nextBox := "", "", "", ""
			if r == 0 {
				deck, deckSalt = deckA, saltA
			}
			if r+1 < len(c.rounds) {
				next, nextBox = sealOf(salts[r+1], c.rounds[r+1][0]), boxOf("next")
			}
			testing.SetRealm(testing.NewUserRealm(alice))
			Reveal(cross(cur), id, deck, deckSalt, plans[0], salts[r], next, nextBox)

			at := c.name + " after round " + strconv.Itoa(r+1)
			want := resolveAll(c.rounds[:r+1]...).State
			uassert.Equal(t, showState(want), showState(stateOf(rules, recordOf(t, id))), at)
			hp := Match(id).HP
			urequire.Equal(t, r+1, len(hp), at)
			uassert.Equal(t, want.Gnomes[0].HP, hp[r][0], at)
			uassert.Equal(t, want.Gnomes[1].HP, hp[r][1], at)

			if next != "" {
				testing.SetRealm(testing.NewUserRealm(bob))
				Play(cross(cur), id, c.rounds[r+1][1])
			}
		}
	}
}

func TestFirstRevealDropsDeckSeal(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	uassert.Equal(t, sealOf(saltA, deckA), recordOf(t, id).deckSeal)
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	uassert.Equal(t, sealOf(saltA, deckA), recordOf(t, id).deckSeal)

	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	uassert.Equal(t, "", recordOf(t, id).deckSeal)
	uassert.Equal(t, deckA, Match(id).ChallengerDeck)
}

query.gno

package arena

import (
	"encoding/base64"
	"strconv"
	"strings"
	"time"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
)

// MatchSummary is one match as a player's list shows it. Round is the round being
// played, or the last one resolved once the match is over. ToMove is the address that
// must move next, empty when none. Deadline is the end of the current move's 24 hours,
// or the expiry of an open challenge, in Unix seconds. Opponent is the address an open
// challenge is reserved for, "" when anyone can accept it and once accepted.
type MatchSummary struct {
	ID, Phase                    string
	Round                        int
	Challenger, Acceptor         string
	ChallengerClan, AcceptorClan string
	ToMove                       string
	Deadline                     int64
	Result, Reason               string
	Opponent                     string
}

// MatchView is everything one match screen needs. Plans holds [challenger, acceptor]
// for each resolved round, and for the round being played while the match runs, ""
// while a plan is sealed or not yet made; HP holds both sides' HP after each resolved
// round; Box is the challenger's encrypted pending plan, in base64.
type MatchView struct {
	MatchSummary
	ChallengerDeck, AcceptorDeck string
	Plans                        [][]string
	Box                          string
	HP                           [][]int
	DeadlinePassed               bool
}

// SessionLock binds the session key at address Session to the match whose id is Match.
// Expires is the session's expiry in Unix seconds, 0 for none.
type SessionLock struct {
	Session, Match string
	Expires        int64
}

// Locks lists player's session locks. It can include locks whose session has expired.
func Locks(player address) []SessionLock {
	list := []SessionLock{}
	for _, l := range loadPlayer(player).locks {
		list = append(list, SessionLock{Session: l.session.String(), Match: strconv.Itoa(l.id), Expires: l.expires})
	}
	return list
}

// Matches lists player's matches, newest first: limit of them after skipping offset.
func Matches(player address, offset, limit int) []MatchSummary {
	checkPage(offset, limit)
	rules := engine.ProofOfConcept()
	now := time.Now().Unix()
	list := []MatchSummary{}
	for _, id := range loadPlayer(player).newest(offset, limit) {
		m, ok := loadMatch(rules, id)
		if !ok {
			continue
		}
		list = append(list, m.summary(rules, id, now))
	}
	return list
}

// Match returns the view of match id.
func Match(id string) MatchView {
	rules := engine.ProofOfConcept()
	n, m := find(rules, id)
	return m.view(rules, n, time.Now().Unix())
}

func (m record) view(rules *engine.Ruleset, id int, now int64) MatchView {
	v := MatchView{
		MatchSummary:   m.summary(rules, id, now),
		ChallengerDeck: deckText(rules, m.decks[0]),
		AcceptorDeck:   deckText(rules, m.decks[1]),
		Plans:          [][]string{},
		Box:            base64.StdEncoding.EncodeToString([]byte(m.box)),
		HP:             [][]int{},
		DeadlinePassed: m.running() && now > m.deadline,
	}
	resolved := plansMade(m.plans[0])
	rounds := resolved
	if m.running() {
		rounds++
	}
	for r := 1; r <= rounds; r++ {
		a := planText(rules, planAt(m.plans[0], r))
		b := planText(rules, planAt(m.plans[1], r))
		v.Plans = append(v.Plans, []string{a, b})
	}
	for r := 0; r < resolved; r++ {
		v.HP = append(v.HP, []int{m.hp[r][0], m.hp[r][1]})
	}
	return v
}

func (m record) summary(rules *engine.Ruleset, id int, now int64) MatchSummary {
	resolved := plansMade(m.plans[0])
	s := MatchSummary{
		ID:             strconv.Itoa(id),
		Phase:          m.phase,
		Round:          resolved + 1,
		Challenger:     m.challenger.String(),
		Acceptor:       m.acceptor.String(),
		ChallengerClan: clanName(rules, m.clans[0]),
		AcceptorClan:   clanName(rules, m.clans[1]),
		Result:         m.result,
		Reason:         m.reason,
		Opponent:       m.opponent.String(),
	}
	switch m.phase {
	case phaseOpen:
		s.Deadline = m.deadline
		if m.expired(now) {
			s.Phase = phaseExpired
		}
	case phaseReveal:
		s.ToMove = s.Challenger
		s.Deadline = m.deadline
	case phasePlay:
		s.ToMove = s.Acceptor
		s.Deadline = m.deadline
	case phaseEnded:
		if resolved > 0 {
			s.Round = resolved
		}
	}
	return s
}

func (m record) running() bool {
	return m.phase == phaseReveal || m.phase == phasePlay
}

// deckText names the cards of deck in card id order.
func deckText(rules *engine.Ruleset, deck uint64) string {
	var names []string
	for i := range rules.Cards {
		if deck&(uint64(1)<<uint(i)) != 0 {
			names = append(names, rules.Cards[i].Name)
		}
	}
	return strings.Join(names, ",")
}

// planText names the cards of p in play order.
func planText(rules *engine.Ruleset, p engine.Plan) string {
	names := make([]string, len(p))
	for i, id := range p {
		names[i] = rules.Cards[id].Name
	}
	return strings.Join(names, ",")
}

query_test.gno

package arena

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

func summaryIDs(list []MatchSummary) string {
	var out []string
	for _, s := range list {
		out = append(out, s.ID)
	}
	return strings.Join(out, ",")
}

func TestWithdraw(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "not your challenge", func() { Resign(cross(cur), id) })

	testing.SetRealm(testing.NewUserRealm(alice))
	Resign(cross(cur), id)
	uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match(id) })
	uassert.Equal(t, 0, len(Matches(alice, 0, 50)))
	uassert.Equal(t, "[]", showIDs(loadPlayer(alice).ids))
	uassert.Equal(t, 0, len(Open(0, 50)))
	uassert.AbortsWithMessage(t, cur, "unknown match", func() { Resign(cross(cur), id) })
}

func TestWithdrawExpired(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SkipHeights(7*day + 1)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "not your challenge", func() { Resign(cross(cur), id) })

	testing.SetRealm(testing.NewUserRealm(alice))
	Resign(cross(cur), id)
	uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match(id) })
	uassert.Equal(t, 0, len(Matches(alice, 0, 50)))
	uassert.Equal(t, "[]", showIDs(loadPlayer(alice).ids))
	uassert.Equal(t, "", openList)
}

func TestResign(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))

	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsWithMessage(t, cur, "not a player", func() { Resign(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(bob))
	Resign(cross(cur), id)

	v := Match(id)
	uassert.Equal(t, phaseEnded, v.Phase)
	uassert.Equal(t, "a", v.Result)
	uassert.Equal(t, "resign", v.Reason)
	uassert.Equal(t, "", v.ToMove)
	uassert.Equal(t, 1, v.Round)
}

func TestClaimForfeitInReveal(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsWithMessage(t, cur, "wrong phase", func() { ClaimForfeit(cross(cur), id) })
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)

	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsWithMessage(t, cur, "deadline not passed", func() { ClaimForfeit(cross(cur), id) })
	testing.SkipHeights(day + 1)
	ClaimForfeit(cross(cur), id)

	v := Match(id)
	uassert.Equal(t, "b", v.Result)
	uassert.Equal(t, "forfeit", v.Reason)
	uassert.False(t, v.DeadlinePassed)
}

func TestClaimForfeitInPlay(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	testing.SkipHeights(day + 1)
	ClaimForfeit(cross(cur), id)

	v := Match(id)
	uassert.Equal(t, "a", v.Result)
	uassert.Equal(t, "forfeit", v.Reason)
}

func TestMatchesNewestFirst(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	seal := sealOf(saltA, deckA)
	Challenge(cross(cur), "Pickers", seal, sealOf(salt1, picks), boxOf("box1"), "")
	id := Challenge(cross(cur), "Pickers", seal, sealOf(salt1, picks), boxOf("box1"), "")
	Challenge(cross(cur), "Pickers", seal, sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)

	uassert.Equal(t, "3,2,1", summaryIDs(Matches(alice, 0, 50)))
	uassert.Equal(t, "2", summaryIDs(Matches(alice, 1, 1)))
	uassert.Equal(t, "2", summaryIDs(Matches(bob, 0, 50)))
	uassert.Equal(t, 0, len(Matches(carol, 0, 50)))

	s := Matches(bob, 0, 50)[0]
	uassert.Equal(t, phaseReveal, s.Phase)
	uassert.Equal(t, 1, s.Round)
	uassert.Equal(t, alice.String(), s.Challenger)
	uassert.Equal(t, bob.String(), s.Acceptor)
	uassert.Equal(t, "Pickers", s.ChallengerClan)
	uassert.Equal(t, "Ironhide", s.AcceptorClan)
	uassert.Equal(t, alice.String(), s.ToMove)

	open := Matches(alice, 0, 50)[0]
	uassert.Equal(t, phaseOpen, open.Phase)
	uassert.Equal(t, "", open.ToMove)
	uassert.Equal(t, Open(0, 1)[0].Expires, open.Deadline)
}

func TestMatchViewKeepsTheSealHidden(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)

	v := Match(id)
	uassert.Equal(t, "", v.Opponent)
	uassert.Equal(t, "", v.ChallengerDeck)
	uassert.Equal(t, deckB, v.AcceptorDeck)
	urequire.Equal(t, 1, len(v.Plans))
	uassert.Equal(t, "", v.Plans[0][0])
	uassert.Equal(t, braces, v.Plans[0][1])
	uassert.Equal(t, boxOf("box1"), v.Box)
	uassert.Equal(t, 0, len(v.HP))

	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	v = Match(id)
	want := resolveAll([2]string{picks, braces})
	uassert.Equal(t, phasePlay, v.Phase)
	uassert.Equal(t, 2, v.Round)
	uassert.Equal(t, bob.String(), v.ToMove)
	uassert.Equal(t, deckA, v.ChallengerDeck)
	urequire.Equal(t, 2, len(v.Plans))
	uassert.Equal(t, picks, v.Plans[0][0])
	uassert.Equal(t, "", v.Plans[1][0])
	uassert.Equal(t, "", v.Plans[1][1])
	uassert.Equal(t, boxOf("box2"), v.Box)
	urequire.Equal(t, 1, len(v.HP))
	uassert.Equal(t, want.State.Gnomes[0].HP, v.HP[0][0])
	uassert.Equal(t, want.State.Gnomes[1].HP, v.HP[0][1])

	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	v = Match(id)
	uassert.Equal(t, "", v.Plans[1][0])
	uassert.Equal(t, braces, v.Plans[1][1])
	uassert.Equal(t, alice.String(), v.ToMove)
}

func TestMatchViewDeadlinePassed(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	uassert.False(t, Match(id).DeadlinePassed)
	testing.SkipHeights(day + 1)
	uassert.True(t, Match(id).DeadlinePassed)
}

func TestMatchViewExpired(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SkipHeights(7*day + 1)
	uassert.Equal(t, phaseExpired, Match(id).Phase)
}

func TestUnknownMatch(t *testing.T) {
	reset()
	uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match("99") })
	uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match("12345678901") })
	uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match("") })
}

// Only an id's own decimal text names its match.
func TestMatchIDsAreExact(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	uassert.Equal(t, "1", Match(id).ID)
	for _, other := range []string{"01", "+1", "-1", " 1", "1 ", "0", "1.0", "0x1", "0000000001"} {
		uassert.PanicsWithMessage(t, nil, "unknown match", func() { Match(other) }, other)
		uassert.AbortsWithMessage(t, cur, "unknown match", func() { Resign(cross(cur), other) }, other)
		uassert.True(t, strings.Contains(Render("match/"+other), "Not found"), other)
	}
}

render.gno

package arena

import (
	"strconv"
	"strings"
	"time"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
)

const notFound = "# Not found\n\nThe arena has no page at this path.\n"

// Render serves the board of open challenges at "", one player's matches at
// "player/<address>", and one match at "match/<id>".
func Render(path string) string {
	switch {
	case path == "":
		return renderBoard()
	case strings.HasPrefix(path, "player/"):
		player := address(strings.TrimPrefix(path, "player/"))
		if !canonical(player) {
			return notFound
		}
		return renderPlayer(player)
	case strings.HasPrefix(path, "match/"):
		rules := engine.ProofOfConcept()
		n, m, ok := lookup(rules, strings.TrimPrefix(path, "match/"))
		if !ok {
			return notFound
		}
		return renderMatch(m.view(rules, n, time.Now().Unix()))
	}
	return notFound
}

func renderBoard() string {
	var b strings.Builder
	b.WriteString("# Gnomepit arena\n\nOpen challenges, newest first.\n\n")
	list := Open(0, maxPage)
	if len(list) == 0 {
		b.WriteString("No open challenge.\n")
	}
	for _, c := range list {
		who := "open to anyone"
		if c.Opponent != "" {
			who = "reserved for " + c.Opponent
		}
		b.WriteString("- " + matchLink(c.ID) + ": " + c.Clan + ", posted by " + c.Challenger + ", " + who + ", expires " + date(c.Expires) + "\n")
	}
	return b.String()
}

func renderPlayer(player address) string {
	var b strings.Builder
	b.WriteString("# Matches of " + player.String() + "\n\n")
	list := Matches(player, 0, maxPage)
	if len(list) == 0 {
		b.WriteString("No match.\n")
	}
	for _, s := range list {
		b.WriteString("- " + matchLink(s.ID) + ": " + s.ChallengerClan + " against " + orNone(s.AcceptorClan) + ", " + s.Phase + "\n")
	}
	return b.String()
}

func renderMatch(v MatchView) string {
	var b strings.Builder
	b.WriteString("# Match " + v.ID + "\n\n")
	b.WriteString(v.ChallengerClan + " (" + v.Challenger + ") against " + orNone(v.AcceptorClan))
	if v.Acceptor != "" {
		b.WriteString(" (" + v.Acceptor + ")")
	}
	b.WriteString("\n\n")
	switch v.Phase {
	case phaseOpen:
		who := "open to anyone"
		if v.Opponent != "" {
			who = "reserved for " + v.Opponent
		}
		b.WriteString("Open challenge, " + who + ", until " + date(v.Deadline) + ".\n")
	case phaseReveal, phasePlay:
		b.WriteString("Round " + strconv.Itoa(v.Round) + ", waiting for " + v.ToMove + " until " + date(v.Deadline) + ".\n")
	case phaseEnded:
		b.WriteString("Over: " + outcome(v.Result, v.Reason) + ".\n")
	default:
		b.WriteString(strings.ToUpper(v.Phase[:1]) + v.Phase[1:] + ".\n")
	}
	if len(v.HP) > 0 {
		b.WriteString("\n| HP after | Challenger | Acceptor |\n|---|---|---|\n")
		for i, hp := range v.HP {
			b.WriteString("| Round " + strconv.Itoa(i+1) + " | " + strconv.Itoa(hp[0]) + " | " + strconv.Itoa(hp[1]) + " |\n")
		}
	}
	return b.String()
}

func outcome(result, reason string) string {
	winner := "the challenger won"
	switch result {
	case "b":
		winner = "the acceptor won"
	case "draw":
		winner = "a draw"
	}
	switch reason {
	case "hp":
		return winner + " on HP"
	case "knockout":
		return winner + " by knockout"
	case "resign":
		return winner + " by resignation"
	}
	return winner + " by forfeit"
}

func matchLink(id string) string {
	return "[Match " + id + "](" + strings.TrimPrefix(self, "gno.land") + ":match/" + id + ")"
}

func date(unix int64) string {
	return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04 UTC")
}

func orNone(s string) string {
	if s == "" {
		return "nobody yet"
	}
	return s
}

render_test.gno

package arena

import (
	"strconv"
	"strings"
	"testing"

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

func TestRenderBoard(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), bob)

	out := Render("")
	uassert.True(t, strings.Contains(out, "[Match 1](/r/nym-gfanton001/gnomepit/arena/v0:match/1)"), out)
	uassert.True(t, strings.Contains(out, "Pickers"), out)
	uassert.True(t, strings.Contains(out, "reserved for "+bob.String()), out)
}

func TestRenderMatch(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))

	v := Match(id)
	out := Render("match/" + id)
	uassert.True(t, strings.Contains(out, "# Match 1"), out)
	uassert.True(t, strings.Contains(out, "Round 2, waiting for "+bob.String()), out)
	uassert.True(t, strings.Contains(out, "| Round 1 | "+strconv.Itoa(v.HP[0][0])+" | "+strconv.Itoa(v.HP[0][1])+" |"), out)
}

func TestRenderPlayer(cur realm, t *testing.T) {
	reset()
	testing.SetRealm(testing.NewUserRealm(alice))
	Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	out := Render("player/" + alice.String())
	uassert.True(t, strings.Contains(out, "[Match 1](/r/nym-gfanton001/gnomepit/arena/v0:match/1)"), out)
}

func TestRenderNotFound(t *testing.T) {
	reset()
	for _, path := range []string{"match/99", "match/", "player/nope", "player/" + strings.ToUpper(alice.String()), "elsewhere"} {
		uassert.True(t, strings.Contains(Render(path), "Not found"), path)
	}
}

report.gno

package arena

import (
	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
	"gno.land/r/nym-gfanton001/gnomepit/standings/v0"
)

// report sends match m, which has just ended, to the standings realm to be rated. A match
// its challenger accepted is not reported. Neither is any match while the arena is off the
// writer list, where Record would abort the ending.
func report(cur realm, rules *engine.Ruleset, m record) {
	if m.challenger == m.acceptor || !standings.IsWriter(self) {
		return
	}
	standings.Record(cross(cur), m.challenger, m.acceptor, clanName(rules, m.clans[0]), clanName(rules, m.clans[1]), m.result)
}

report_test.gno

package arena

import (
	"testing"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
	"gno.land/r/nym-gfanton001/gnomepit/standings/v0"
)

// checkReported checks that the standings realm holds one result more than before, from this
// arena, for alice as Pickers against bob as Ironhide, ending in result. The standings realm
// keeps its state across tests, which reset cannot reach.
func checkReported(t *testing.T, before int, result string) {
	t.Helper()
	urequire.Equal(t, before+1, standings.ResultCount())
	page := standings.Results(before, 1)
	urequire.Equal(t, 1, len(page))
	r := page[0]
	uassert.Equal(t, "gno.land/r/nym-gfanton001/gnomepit/arena/v0", r.Writer)
	uassert.Equal(t, alice.String(), r.Challenger)
	uassert.Equal(t, bob.String(), r.Acceptor)
	uassert.Equal(t, "Pickers", r.ChallengerClan)
	uassert.Equal(t, "Ironhide", r.AcceptorClan)
	uassert.Equal(t, result, r.Result)
}

func TestEndingsReport(cur realm, t *testing.T) {
	// The worked match ends on HP with the challenger's last Reveal.
	reset()
	before := standings.ResultCount()
	a1, b1 := "Chalk Dust,Double Tap", "Hammer Blow,Spiked Shield"
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, a1), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, b1)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, a1, salt1, sealOf(salt2, picks), boxOf("box2"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", picks, salt2, sealOf(salt3, picks), boxOf("box3"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, braces)
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", picks, salt3, "", "")
	uassert.Equal(t, "hp", Match(id).Reason)
	checkReported(t, before, Match(id).Result)

	// A knockout ends it with the second Reveal.
	reset()
	before = standings.ResultCount()
	testing.SetRealm(testing.NewUserRealm(alice))
	id = Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, "Pick,Anvil Stomp")
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, deckA, saltA, picks, salt1, sealOf(salt2, picks), boxOf("box2"))
	testing.SetRealm(testing.NewUserRealm(bob))
	Play(cross(cur), id, "Hammer Blow,Cobble Throw")
	testing.SetRealm(testing.NewUserRealm(alice))
	Reveal(cross(cur), id, "", "", picks, salt2, "", "")
	uassert.Equal(t, "knockout", Match(id).Reason)
	checkReported(t, before, "b")

	// A resignation.
	reset()
	before = standings.ResultCount()
	testing.SetRealm(testing.NewUserRealm(alice))
	id = Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	Resign(cross(cur), id)
	checkReported(t, before, "a")

	// A forfeit claimed by a third wallet.
	reset()
	before = standings.ResultCount()
	testing.SetRealm(testing.NewUserRealm(alice))
	id = Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	testing.SetRealm(testing.NewUserRealm(bob))
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	testing.SkipHeights(day + 1)
	testing.SetRealm(testing.NewUserRealm(carol))
	ClaimForfeit(cross(cur), id)
	checkReported(t, before, "b")
}

func TestSelfAcceptedMatchUnreported(cur realm, t *testing.T) {
	reset()
	before := standings.ResultCount()
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "Pickers", sealOf(saltA, deckA), sealOf(salt1, picks), boxOf("box1"), "")
	Accept(cross(cur), id, "Ironhide", deckB, braces)
	Resign(cross(cur), id)
	uassert.Equal(t, "ended", Match(id).Phase)
	uassert.Equal(t, before, standings.ResultCount(), "a self-match is never reported")
}

// TestEveryClanNamePassesTheStore checks that the standings realm takes every clan name: one
// it refuses would abort every ending.
func TestEveryClanNamePassesTheStore(t *testing.T) {
	for _, c := range engine.ProofOfConcept().Clans {
		uassert.True(t, len(c.Name) >= 1 && len(c.Name) <= 32, c.Name)
	}
}

store.gno

package arena

import (
	"encoding/binary"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
	"gno.land/p/nt/avl/v0"
)

var (
	chunks   avl.Tree // 4-byte chunk number → chunk string
	players  avl.Tree // address → player string
	openList string
)

func chunkKey(id int) string {
	var k [4]byte
	binary.BigEndian.PutUint32(k[:], uint32((id-1)/chunkSize))
	return string(k[:])
}

// loadMatch returns match id, or false when it does not exist or was removed.
func loadMatch(rules *engine.Ruleset, id int) (record, bool) {
	if id < 1 || id > lastID {
		return record{}, false
	}
	rec := chunkRecord(stringAt(&chunks, chunkKey(id)), (id-1)%chunkSize)
	if rec == "" {
		return record{}, false
	}
	return decodeMatch(rules, rec), true
}

func saveMatch(rules *engine.Ruleset, id int, m record) {
	putRecord(id, encodeMatch(rules, m))
}

// dropMatch removes match id; an absent id is left alone.
func dropMatch(id int) {
	if id < 1 {
		return
	}
	if chunkRecord(stringAt(&chunks, chunkKey(id)), (id-1)%chunkSize) != "" {
		putRecord(id, "")
	}
}

func putRecord(id int, rec string) {
	chunks.Set(chunkKey(id), withChunkRecord(stringAt(&chunks, chunkKey(id)), (id-1)%chunkSize, rec))
}

// stringAt returns the string under key, "" when there is none.
func stringAt(t *avl.Tree, key string) string {
	v := t.Get(key)
	if v == nil {
		return ""
	}
	return v.(string)
}

func loadPlayer(a address) playerRecord {
	return decodePlayer(stringAt(&players, string(a)))
}

func savePlayer(a address, p playerRecord) {
	players.Set(string(a), encodePlayer(p))
}

// add appends id unless the player already has it.
func (p *playerRecord) add(id int) {
	for _, have := range p.ids {
		if have == id {
			return
		}
	}
	p.ids = append(p.ids, id)
}

func (p *playerRecord) remove(id int) {
	for i, have := range p.ids {
		if have == id {
			p.ids = append(p.ids[:i:i], p.ids[i+1:]...)
			return
		}
	}
}

// newest returns up to limit ids, newest first, after skipping offset of them.
func (p playerRecord) newest(offset, limit int) []int {
	var out []int
	for i := len(p.ids) - 1 - offset; i >= 0 && len(out) < limit; i-- {
		out = append(out, p.ids[i])
	}
	return out
}

// ceiling: each change rewrites the whole open list, 8 bytes per open challenge, so its gas
// grows with the board; an avl index keyed by expiry and id if the board holds thousands.
func openAdd(id int, expires int64) {
	openList += encodeOpen([]openEntry{{id: id, expires: expires}})
}

func openRemove(id int) {
	entries := openEntries(openList)
	for i, e := range entries {
		if e.id == id {
			openList = encodeOpen(append(entries[:i:i], entries[i+1:]...))
			return
		}
	}
}

// openNewest returns up to limit unexpired ids, newest first, after skipping offset of them.
func openNewest(now int64, offset, limit int) []int {
	entries := openEntries(openList)
	var out []int
	for i := len(entries) - 1; i >= 0 && entries[i].expires >= now; i-- {
		if offset > 0 {
			offset--
			continue
		}
		if len(out) == limit {
			break
		}
		out = append(out, entries[i].id)
	}
	return out
}

// openClear removes up to max expired entries from the front and returns their ids.
func openClear(now int64, max int) []int {
	entries := openEntries(openList)
	n := 0
	var ids []int
	for n < len(entries) && n < max && entries[n].expires < now {
		ids = append(ids, entries[n].id)
		n++
	}
	openList = encodeOpen(entries[n:])
	return ids
}

store_test.gno

package arena

import (
	"strconv"
	"testing"

	"gno.land/p/nym-gfanton001/gnomepit/engine/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
)

func openRecord(who address, deadline int64) record {
	return record{phase: phaseOpen, challenger: who, deadline: deadline}
}

func showIDs(ids []int) string {
	s := "["
	for i, id := range ids {
		if i > 0 {
			s += " "
		}
		s += strconv.Itoa(id)
	}
	return s + "]"
}

func TestMatchesAcrossChunks(cur realm, t *testing.T) {
	reset()
	rules := engine.ProofOfConcept()
	lastID = 130
	for _, id := range []int{1, 64, 65, 130} {
		saveMatch(rules, id, openRecord(alice, int64(id)))
	}
	for _, id := range []int{1, 64, 65, 130} {
		m, ok := loadMatch(rules, id)
		urequire.True(t, ok, "match missing")
		uassert.Equal(t, int64(id), m.deadline)
		uassert.Equal(t, alice, m.challenger)
	}
	for _, id := range []int{66, 0, 131} {
		_, ok := loadMatch(rules, id)
		uassert.False(t, ok)
	}
	uassert.Equal(t, 3, chunks.Size())
}

func TestDropMatch(cur realm, t *testing.T) {
	reset()
	rules := engine.ProofOfConcept()
	lastID = 64
	saveMatch(rules, 1, openRecord(alice, 1))
	saveMatch(rules, 64, openRecord(bob, 64))
	dropMatch(64)
	_, ok := loadMatch(rules, 64)
	uassert.False(t, ok)
	_, ok = loadMatch(rules, 1)
	uassert.True(t, ok)
	dropMatch(64)
	dropMatch(500)
}

func TestPlayerIDs(cur realm, t *testing.T) {
	reset()
	uassert.Equal(t, 0, len(loadPlayer(alice).ids))
	p := loadPlayer(alice)
	p.add(1)
	p.add(5)
	p.add(9)
	p.add(5)
	savePlayer(alice, p)

	p = loadPlayer(alice)
	uassert.Equal(t, "[9 5]", showIDs(p.newest(0, 2)))
	uassert.Equal(t, "[1]", showIDs(p.newest(2, 2)))
	uassert.Equal(t, "[]", showIDs(p.newest(5, 2)))
	p.remove(5)
	p.remove(77)
	uassert.Equal(t, "[9 1]", showIDs(p.newest(0, 50)))
}

func TestPlayerKeepsLocks(cur realm, t *testing.T) {
	reset()
	p := loadPlayer(alice)
	p.add(1)
	p.locks = []sessionLock{{session: bob, id: 1, expires: 99}}
	savePlayer(alice, p)
	got := loadPlayer(alice)
	uassert.Equal(t, 1, len(got.locks))
	uassert.Equal(t, bob, got.locks[0].session)
	uassert.Equal(t, 1, len(got.ids))
}

func TestOpenList(cur realm, t *testing.T) {
	reset()
	const now = int64(1000)
	openAdd(1, now+10)
	openAdd(2, now+20)
	openAdd(3, now+30)
	uassert.Equal(t, "[3 2]", showIDs(openNewest(now+15, 0, 50)))
	uassert.Equal(t, "[2]", showIDs(openNewest(now+15, 1, 1)))
	uassert.Equal(t, "[1 2]", showIDs(openClear(now+25, 8)))
	uassert.Equal(t, "[3]", showIDs(openNewest(now, 0, 50)))
	openRemove(9)
	openRemove(3)
	uassert.Equal(t, "", openList)
}

func TestOpenClearStopsAtMax(cur realm, t *testing.T) {
	reset()
	openAdd(1, 10)
	openAdd(2, 20)
	openAdd(3, 30)
	uassert.Equal(t, "[1]", showIDs(openClear(100, 1)))
	uassert.Equal(t, 2, len(openEntries(openList)))
}

func TestDropAbsentMatchLeavesChunk(cur realm, t *testing.T) {
	reset()
	rules := engine.ProofOfConcept()
	lastID = 66
	saveMatch(rules, 65, openRecord(alice, 65))
	before := stringAt(&chunks, chunkKey(65))

	dropMatch(66)
	uassert.Equal(t, before, stringAt(&chunks, chunkKey(65)))

	dropMatch(65)
	dropped := stringAt(&chunks, chunkKey(65))
	dropMatch(65)
	uassert.Equal(t, dropped, stringAt(&chunks, chunkKey(65)))
}

func TestOpenExpiryBoundary(cur realm, t *testing.T) {
	reset()
	openAdd(1, 50)
	uassert.Equal(t, "[1]", showIDs(openNewest(50, 0, 50)))
	uassert.Equal(t, "[]", showIDs(openClear(50, 8)))
	uassert.Equal(t, "[1]", showIDs(openClear(51, 8)))
}