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

gnomod.toml

module = "gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/live/v1"
gno = "0.9"

[addpkg]
  creator = "g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28"
  height = 1575689
  max_deposit = "50000000ugnot"

live.gno

// Package live runs real-time matches between agents, checked by the chain.
//
// The match itself is played off-chain, tick by tick, by two programs that
// read the same game state and send inputs through a relay. The chain never
// sees a plan. It does two things:
//
//  1. Anchor: every 10 seconds (100 ticks) each player sends one hash that
//     covers all of their inputs so far (see AnchorHash). An anchor can only
//     land inside a short window after its time, so a player can neither
//     commit a whole match at the start nor wait and rewrite. A hash shows
//     nothing about the inputs, so the rival cannot copy them.
//  2. Submit: afterwards each player sends their full input log. The chain
//     checks it hashes to the anchors the player sent during the match, then
//     replays both logs on the brawl rules and records the score.
//
// A log written after the fact does not match its anchors, so neither side
// can rewrite their moves after seeing the other's. A player who does not
// anchor and submit in time forfeits.
package live

import (
	"chain"
	"chain/runtime"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"

	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v4"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ufmt/v0"
)

const (
	AnchorTicks  = 100 // ticks between anchors (10 s)
	AnchorBlocks = 2   // blocks that must pass per anchor (testnet blocks are about 4 s)
	MinSeconds   = 60
	MaxSeconds   = 180
	AnchorSlack  = 10  // blocks an anchor may land after its time (about 40 s)
	Grace        = 150 // blocks after the last anchor window, to submit
	MaxName      = 20
)

// Phases of a match.
const (
	Waiting = iota // created, waiting for a second player
	Playing        // being played off-chain; anchors arrive
	Done           // both logs replayed, score recorded
	Forfeit        // a side did not deliver; see Winner
	Void           // neither side delivered
)

var phaseNames = [5]string{"waiting", "playing", "done", "forfeit", "void"}

// A Player is one side of a match.
type Player struct {
	Addr      address
	Name      string
	Class     int
	Anchors   []string // hash after each 100 ticks
	AnchorAt  []int64  // block each anchor landed in
	Inputs    string   // the full log, once submitted
	Submitted bool
}

// A Match is one real-time fight.
type Match struct {
	ID       int
	Seed     uint32
	Ticks    int
	Phase    int
	Start    int64 // block the match started in
	Deadline int64 // after this block a missing side forfeits
	P        [2]*Player
	Gold     [2]int
	Winner   int // -1 none, 0 or 1 once forfeit or done
}

var (
	matches avl.Tree // zero-padded id -> *Match
	nextID  = 1
)

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

func height() int64 { return runtime.ChainHeight() }

func mustMatch(id int) *Match {
	v := matches.Get(key(id))
	if v == nil {
		panic("no match #" + strconv.Itoa(id))
	}
	return v.(*Match)
}

func cleanName(s string) string {
	s = strings.TrimSpace(s)
	if len(s) > MaxName {
		panic("name: " + strconv.Itoa(MaxName) + " characters at most")
	}
	for _, c := range s {
		if c < ' ' || c == '|' || c == '<' || c == '>' || c == '"' || c == '\\' {
			panic("name: plain text only")
		}
	}
	return s
}

func checkClass(class int) {
	if class < rules.Hunter || class > rules.Reader {
		panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
	}
}

// Create opens a match of the given length (60 to 180 seconds, in tens) and
// takes side A.
func Create(cur realm, name string, class, seconds int) int {
	checkClass(class)
	if seconds < MinSeconds || seconds > MaxSeconds || seconds%10 != 0 {
		panic("seconds: 60 to 180, in tens")
	}
	m := &Match{ID: nextID, Ticks: seconds * rules.TPS, Winner: -1}
	m.P[0] = &Player{Addr: cur.Previous().Address(), Name: cleanName(name), Class: class}
	nextID++
	matches.Set(key(m.ID), m)
	chain.Emit("LiveCreated", "match", strconv.Itoa(m.ID), "player", m.P[0].Addr.String())
	return m.ID
}

// Join takes side B and starts the match. The arena and coins come from the
// block it starts in; both programs read Seed and start playing from tick 0.
func Join(cur realm, id int, name string, class int) {
	m := mustMatch(id)
	if m.Phase != Waiting {
		panic("match #" + strconv.Itoa(id) + " is already full")
	}
	addr := cur.Previous().Address()
	if addr == m.P[0].Addr {
		panic("you cannot join your own match")
	}
	checkClass(class)
	m.P[1] = &Player{Addr: addr, Name: cleanName(name), Class: class}
	h := height()
	m.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31)
	m.Start = h
	m.Phase = Playing
	m.Deadline = h + int64(m.Ticks/AnchorTicks*AnchorBlocks) + Grace
	chain.Emit("LiveStarted", "match", strconv.Itoa(id), "seed", strconv.Itoa(int(m.Seed)),
		"arena", rules.ArenaName(m.Seed), "ticks", strconv.Itoa(m.Ticks))
}

func side(m *Match, addr address) int {
	for s := 0; s < 2; s++ {
		if m.P[s] != nil && m.P[s].Addr == addr {
			return s
		}
	}
	panic("you are not playing in match #" + strconv.Itoa(m.ID))
}

// AnchorHash is the anchor for a chunk of inputs: hex sha256 of the previous
// anchor ("" for the first), a "|", and the next 100 inputs. Anchor k covers
// every input up to tick 100*k, so each anchor commits to the whole log.
func AnchorHash(prev, chunk string) string {
	sum := sha256.Sum256([]byte(prev + "|" + chunk))
	return hex.EncodeToString(sum[:])
}

// Anchor sends your next hash. Anchor k must land in the window from block
// start + 2k to start + 2k + AnchorSlack: not earlier, so you cannot commit a
// whole match in advance, and not later, so you cannot wait to see the
// rival's moves before committing yours. An anchor that misses its window
// can never be sent, and the match is then forfeit.
func Anchor(cur realm, id int, hash string) {
	m := mustMatch(id)
	if m.Phase != Playing {
		panic("match #" + strconv.Itoa(id) + " is " + phaseNames[m.Phase] + ": no anchors")
	}
	s := side(m, cur.Previous().Address())
	p := m.P[s]
	if len(hash) != 64 {
		panic("hash: 64 hex characters (see AnchorHash)")
	}
	k := len(p.Anchors) + 1
	if k > m.Ticks/AnchorTicks {
		panic("every anchor is already in")
	}
	h := height()
	due := m.Start + int64(k*AnchorBlocks)
	if h < due {
		panic("too early for anchor " + strconv.Itoa(k) + ": it lands at block " + strconv.Itoa(int(due)))
	}
	if h > due+AnchorSlack {
		panic("too late for anchor " + strconv.Itoa(k) + ": it had to land by block " + strconv.Itoa(int(due)+AnchorSlack))
	}
	p.Anchors = append(p.Anchors, hash)
	p.AnchorAt = append(p.AnchorAt, h)
	chain.Emit("LiveAnchor", "match", strconv.Itoa(id), "side", strconv.Itoa(s), "k", strconv.Itoa(k), "hash", hash)
}

// Submit sends your full input log: one character per tick (see the brawl
// package's Encode). It must hash to every anchor you sent. When both logs
// are in, the chain replays them and records the score.
func Submit(cur realm, id int, inputs string) {
	m := mustMatch(id)
	if m.Phase != Playing {
		panic("match #" + strconv.Itoa(id) + " is " + phaseNames[m.Phase] + ": nothing to submit")
	}
	s := side(m, cur.Previous().Address())
	p := m.P[s]
	if p.Submitted {
		panic("you already submitted")
	}
	n := m.Ticks / AnchorTicks
	if len(p.Anchors) != n {
		panic("anchor all " + strconv.Itoa(n) + " parts first (you have " + strconv.Itoa(len(p.Anchors)) + ")")
	}
	if len(inputs) != m.Ticks {
		panic("inputs: exactly " + strconv.Itoa(m.Ticks) + " characters, one per tick")
	}
	for i := 0; i < len(inputs); i++ {
		if _, _, ok := rules.Decode(inputs[i]); !ok {
			panic("inputs: tick " + strconv.Itoa(i) + " is not an input character")
		}
	}
	prev := ""
	for k := 0; k < n; k++ {
		prev = AnchorHash(prev, inputs[k*AnchorTicks:(k+1)*AnchorTicks])
		if prev != p.Anchors[k] {
			panic("this log does not match your anchor " + strconv.Itoa(k+1) + ": it is not what you played")
		}
	}
	p.Inputs, p.Submitted = inputs, true
	chain.Emit("LiveSubmitted", "match", strconv.Itoa(id), "side", strconv.Itoa(s))
	if m.P[1-s].Submitted {
		replay(m)
	}
}

// replay plays both logs against each other on the brawl rules.
func replay(m *Match) {
	g := rules.NewLength(m.Seed, m.P[0].Class, m.P[1].Class, m.Ticks)
	for i := 0; i < m.Ticks && !g.Over(); i++ {
		m0, a0, _ := rules.Decode(m.P[0].Inputs[i])
		m1, a1, _ := rules.Decode(m.P[1].Inputs[i])
		g.Step(m0, a0, m1, a1)
	}
	m.Gold = [2]int{g.F[0].Gold, g.F[1].Gold}
	m.Winner = -1
	if m.Gold[0] > m.Gold[1] {
		m.Winner = 0
	} else if m.Gold[1] > m.Gold[0] {
		m.Winner = 1
	}
	m.Phase = Done
	chain.Emit("LiveDone", "match", strconv.Itoa(m.ID), "goldA", strconv.Itoa(m.Gold[0]), "goldB", strconv.Itoa(m.Gold[1]))
}

// Settle closes a match whose deadline has passed. A side that delivered
// every anchor and its log beats one that did not; if both failed it is void.
// Anyone can call it.
func Settle(cur realm, id int) {
	m := mustMatch(id)
	if m.Phase != Playing {
		panic("match #" + strconv.Itoa(id) + " is " + phaseNames[m.Phase])
	}
	if height() <= m.Deadline {
		panic("not yet: the deadline is block " + strconv.Itoa(int(m.Deadline)))
	}
	ok0, ok1 := m.P[0].Submitted, m.P[1].Submitted
	switch {
	case ok0 && !ok1:
		m.Phase, m.Winner = Forfeit, 0
	case ok1 && !ok0:
		m.Phase, m.Winner = Forfeit, 1
	default:
		m.Phase = Void
	}
	chain.Emit("LiveSettled", "match", strconv.Itoa(id), "phase", phaseNames[m.Phase], "winner", strconv.Itoa(m.Winner))
}

// Reads.

func MatchCount() int { return nextID - 1 }

// Inputs is one side's submitted log ("" until it is in).
func Inputs(id, side int) string {
	if side < 0 || side > 1 {
		panic("side: 0 or 1")
	}
	p := mustMatch(id).P[side]
	if p == nil {
		return ""
	}
	return p.Inputs
}

// Anchors lists a side's anchors so far, joined by commas.
func Anchors(id, side int) string {
	if side < 0 || side > 1 {
		panic("side: 0 or 1")
	}
	p := mustMatch(id).P[side]
	if p == nil {
		return ""
	}
	return strings.Join(p.Anchors, ",")
}

// StateJSON describes a match for the programs and the browser.
func StateJSON(id int) string {
	m := mustMatch(id)
	out := ufmt.Sprintf(`{"id":%d,"phase":%s,"seed":%d,"ticks":%d,"anchorTicks":%d,"start":%d,"deadline":%d,"height":%d,"winner":%d,"gold":[%d,%d],"players":[`,
		m.ID, strconv.Quote(phaseNames[m.Phase]), m.Seed, m.Ticks, AnchorTicks, m.Start, m.Deadline, height(), m.Winner, m.Gold[0], m.Gold[1])
	for s := 0; s < 2; s++ {
		if s == 1 {
			out += ","
		}
		p := m.P[s]
		if p == nil {
			out += "null"
			continue
		}
		out += ufmt.Sprintf(`{"player":%s,"name":%s,"class":%d,"anchors":%d,"submitted":%t}`,
			strconv.Quote(p.Addr.String()), strconv.Quote(p.Name), p.Class, len(p.Anchors), p.Submitted)
	}
	if m.Phase != Waiting {
		return out + `],"arena":` + strconv.Quote(rules.ArenaName(m.Seed)) + "}"
	}
	return out + "]}"
}

// Render draws the match list for gnoweb.
func Render(path string) string {
	out := "# Live matches\n\nAgents fight in real time off-chain. Each side anchors a hash of its inputs every 10 seconds, then submits the full log; the chain checks the log against the anchors and replays both.\n\n"
	if matches.Size() == 0 {
		return out + "No matches yet.\n"
	}
	out += "| Match | Players | Phase | Score |\n|---|---|---|---|\n"
	matches.ReverseIterate("", "", func(k string, v any) bool {
		m := v.(*Match)
		b := "-"
		if m.P[1] != nil {
			b = m.P[1].Name
		}
		out += ufmt.Sprintf("| #%d | %s vs %s | %s | %d-%d |\n", m.ID, m.P[0].Name, b, phaseNames[m.Phase], m.Gold[0], m.Gold[1])
		return false
	})
	return out
}