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.

live.gno

11.20 Kb · 353 lines
  1// Package live runs real-time matches between agents, checked by the chain.
  2//
  3// The match itself is played off-chain, tick by tick, by two programs that
  4// read the same game state and send inputs through a relay. The chain never
  5// sees a plan. It does two things:
  6//
  7//  1. Anchor: every 10 seconds (100 ticks) each player sends one hash that
  8//     covers all of their inputs so far (see AnchorHash). An anchor can only
  9//     land inside a short window after its time, so a player can neither
 10//     commit a whole match at the start nor wait and rewrite. A hash shows
 11//     nothing about the inputs, so the rival cannot copy them.
 12//  2. Submit: afterwards each player sends their full input log. The chain
 13//     checks it hashes to the anchors the player sent during the match, then
 14//     replays both logs on the brawl rules and records the score.
 15//
 16// A log written after the fact does not match its anchors, so neither side
 17// can rewrite their moves after seeing the other's. A player who does not
 18// anchor and submit in time forfeits.
 19package live
 20
 21import (
 22	"chain"
 23	"chain/runtime"
 24	"crypto/sha256"
 25	"encoding/hex"
 26	"strconv"
 27	"strings"
 28
 29	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v4"
 30	"gno.land/p/nt/avl/v0"
 31	"gno.land/p/nt/ufmt/v0"
 32)
 33
 34const (
 35	AnchorTicks  = 100 // ticks between anchors (10 s)
 36	AnchorBlocks = 2   // blocks that must pass per anchor (testnet blocks are about 4 s)
 37	MinSeconds   = 60
 38	MaxSeconds   = 180
 39	AnchorSlack  = 10  // blocks an anchor may land after its time (about 40 s)
 40	Grace        = 150 // blocks after the last anchor window, to submit
 41	MaxName      = 20
 42)
 43
 44// Phases of a match.
 45const (
 46	Waiting = iota // created, waiting for a second player
 47	Playing        // being played off-chain; anchors arrive
 48	Done           // both logs replayed, score recorded
 49	Forfeit        // a side did not deliver; see Winner
 50	Void           // neither side delivered
 51)
 52
 53var phaseNames = [5]string{"waiting", "playing", "done", "forfeit", "void"}
 54
 55// A Player is one side of a match.
 56type Player struct {
 57	Addr      address
 58	Name      string
 59	Class     int
 60	Anchors   []string // hash after each 100 ticks
 61	AnchorAt  []int64  // block each anchor landed in
 62	Inputs    string   // the full log, once submitted
 63	Submitted bool
 64}
 65
 66// A Match is one real-time fight.
 67type Match struct {
 68	ID       int
 69	Seed     uint32
 70	Ticks    int
 71	Phase    int
 72	Start    int64 // block the match started in
 73	Deadline int64 // after this block a missing side forfeits
 74	P        [2]*Player
 75	Gold     [2]int
 76	Winner   int // -1 none, 0 or 1 once forfeit or done
 77}
 78
 79var (
 80	matches avl.Tree // zero-padded id -> *Match
 81	nextID  = 1
 82)
 83
 84func key(id int) string {
 85	s := strconv.Itoa(id)
 86	return strings.Repeat("0", 10-len(s)) + s
 87}
 88
 89func height() int64 { return runtime.ChainHeight() }
 90
 91func mustMatch(id int) *Match {
 92	v := matches.Get(key(id))
 93	if v == nil {
 94		panic("no match #" + strconv.Itoa(id))
 95	}
 96	return v.(*Match)
 97}
 98
 99func cleanName(s string) string {
100	s = strings.TrimSpace(s)
101	if len(s) > MaxName {
102		panic("name: " + strconv.Itoa(MaxName) + " characters at most")
103	}
104	for _, c := range s {
105		if c < ' ' || c == '|' || c == '<' || c == '>' || c == '"' || c == '\\' {
106			panic("name: plain text only")
107		}
108	}
109	return s
110}
111
112func checkClass(class int) {
113	if class < rules.Hunter || class > rules.Reader {
114		panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
115	}
116}
117
118// Create opens a match of the given length (60 to 180 seconds, in tens) and
119// takes side A.
120func Create(cur realm, name string, class, seconds int) int {
121	checkClass(class)
122	if seconds < MinSeconds || seconds > MaxSeconds || seconds%10 != 0 {
123		panic("seconds: 60 to 180, in tens")
124	}
125	m := &Match{ID: nextID, Ticks: seconds * rules.TPS, Winner: -1}
126	m.P[0] = &Player{Addr: cur.Previous().Address(), Name: cleanName(name), Class: class}
127	nextID++
128	matches.Set(key(m.ID), m)
129	chain.Emit("LiveCreated", "match", strconv.Itoa(m.ID), "player", m.P[0].Addr.String())
130	return m.ID
131}
132
133// Join takes side B and starts the match. The arena and coins come from the
134// block it starts in; both programs read Seed and start playing from tick 0.
135func Join(cur realm, id int, name string, class int) {
136	m := mustMatch(id)
137	if m.Phase != Waiting {
138		panic("match #" + strconv.Itoa(id) + " is already full")
139	}
140	addr := cur.Previous().Address()
141	if addr == m.P[0].Addr {
142		panic("you cannot join your own match")
143	}
144	checkClass(class)
145	m.P[1] = &Player{Addr: addr, Name: cleanName(name), Class: class}
146	h := height()
147	m.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31)
148	m.Start = h
149	m.Phase = Playing
150	m.Deadline = h + int64(m.Ticks/AnchorTicks*AnchorBlocks) + Grace
151	chain.Emit("LiveStarted", "match", strconv.Itoa(id), "seed", strconv.Itoa(int(m.Seed)),
152		"arena", rules.ArenaName(m.Seed), "ticks", strconv.Itoa(m.Ticks))
153}
154
155func side(m *Match, addr address) int {
156	for s := 0; s < 2; s++ {
157		if m.P[s] != nil && m.P[s].Addr == addr {
158			return s
159		}
160	}
161	panic("you are not playing in match #" + strconv.Itoa(m.ID))
162}
163
164// AnchorHash is the anchor for a chunk of inputs: hex sha256 of the previous
165// anchor ("" for the first), a "|", and the next 100 inputs. Anchor k covers
166// every input up to tick 100*k, so each anchor commits to the whole log.
167func AnchorHash(prev, chunk string) string {
168	sum := sha256.Sum256([]byte(prev + "|" + chunk))
169	return hex.EncodeToString(sum[:])
170}
171
172// Anchor sends your next hash. Anchor k must land in the window from block
173// start + 2k to start + 2k + AnchorSlack: not earlier, so you cannot commit a
174// whole match in advance, and not later, so you cannot wait to see the
175// rival's moves before committing yours. An anchor that misses its window
176// can never be sent, and the match is then forfeit.
177func Anchor(cur realm, id int, hash string) {
178	m := mustMatch(id)
179	if m.Phase != Playing {
180		panic("match #" + strconv.Itoa(id) + " is " + phaseNames[m.Phase] + ": no anchors")
181	}
182	s := side(m, cur.Previous().Address())
183	p := m.P[s]
184	if len(hash) != 64 {
185		panic("hash: 64 hex characters (see AnchorHash)")
186	}
187	k := len(p.Anchors) + 1
188	if k > m.Ticks/AnchorTicks {
189		panic("every anchor is already in")
190	}
191	h := height()
192	due := m.Start + int64(k*AnchorBlocks)
193	if h < due {
194		panic("too early for anchor " + strconv.Itoa(k) + ": it lands at block " + strconv.Itoa(int(due)))
195	}
196	if h > due+AnchorSlack {
197		panic("too late for anchor " + strconv.Itoa(k) + ": it had to land by block " + strconv.Itoa(int(due)+AnchorSlack))
198	}
199	p.Anchors = append(p.Anchors, hash)
200	p.AnchorAt = append(p.AnchorAt, h)
201	chain.Emit("LiveAnchor", "match", strconv.Itoa(id), "side", strconv.Itoa(s), "k", strconv.Itoa(k), "hash", hash)
202}
203
204// Submit sends your full input log: one character per tick (see the brawl
205// package's Encode). It must hash to every anchor you sent. When both logs
206// are in, the chain replays them and records the score.
207func Submit(cur realm, id int, inputs string) {
208	m := mustMatch(id)
209	if m.Phase != Playing {
210		panic("match #" + strconv.Itoa(id) + " is " + phaseNames[m.Phase] + ": nothing to submit")
211	}
212	s := side(m, cur.Previous().Address())
213	p := m.P[s]
214	if p.Submitted {
215		panic("you already submitted")
216	}
217	n := m.Ticks / AnchorTicks
218	if len(p.Anchors) != n {
219		panic("anchor all " + strconv.Itoa(n) + " parts first (you have " + strconv.Itoa(len(p.Anchors)) + ")")
220	}
221	if len(inputs) != m.Ticks {
222		panic("inputs: exactly " + strconv.Itoa(m.Ticks) + " characters, one per tick")
223	}
224	for i := 0; i < len(inputs); i++ {
225		if _, _, ok := rules.Decode(inputs[i]); !ok {
226			panic("inputs: tick " + strconv.Itoa(i) + " is not an input character")
227		}
228	}
229	prev := ""
230	for k := 0; k < n; k++ {
231		prev = AnchorHash(prev, inputs[k*AnchorTicks:(k+1)*AnchorTicks])
232		if prev != p.Anchors[k] {
233			panic("this log does not match your anchor " + strconv.Itoa(k+1) + ": it is not what you played")
234		}
235	}
236	p.Inputs, p.Submitted = inputs, true
237	chain.Emit("LiveSubmitted", "match", strconv.Itoa(id), "side", strconv.Itoa(s))
238	if m.P[1-s].Submitted {
239		replay(m)
240	}
241}
242
243// replay plays both logs against each other on the brawl rules.
244func replay(m *Match) {
245	g := rules.NewLength(m.Seed, m.P[0].Class, m.P[1].Class, m.Ticks)
246	for i := 0; i < m.Ticks && !g.Over(); i++ {
247		m0, a0, _ := rules.Decode(m.P[0].Inputs[i])
248		m1, a1, _ := rules.Decode(m.P[1].Inputs[i])
249		g.Step(m0, a0, m1, a1)
250	}
251	m.Gold = [2]int{g.F[0].Gold, g.F[1].Gold}
252	m.Winner = -1
253	if m.Gold[0] > m.Gold[1] {
254		m.Winner = 0
255	} else if m.Gold[1] > m.Gold[0] {
256		m.Winner = 1
257	}
258	m.Phase = Done
259	chain.Emit("LiveDone", "match", strconv.Itoa(m.ID), "goldA", strconv.Itoa(m.Gold[0]), "goldB", strconv.Itoa(m.Gold[1]))
260}
261
262// Settle closes a match whose deadline has passed. A side that delivered
263// every anchor and its log beats one that did not; if both failed it is void.
264// Anyone can call it.
265func Settle(cur realm, id int) {
266	m := mustMatch(id)
267	if m.Phase != Playing {
268		panic("match #" + strconv.Itoa(id) + " is " + phaseNames[m.Phase])
269	}
270	if height() <= m.Deadline {
271		panic("not yet: the deadline is block " + strconv.Itoa(int(m.Deadline)))
272	}
273	ok0, ok1 := m.P[0].Submitted, m.P[1].Submitted
274	switch {
275	case ok0 && !ok1:
276		m.Phase, m.Winner = Forfeit, 0
277	case ok1 && !ok0:
278		m.Phase, m.Winner = Forfeit, 1
279	default:
280		m.Phase = Void
281	}
282	chain.Emit("LiveSettled", "match", strconv.Itoa(id), "phase", phaseNames[m.Phase], "winner", strconv.Itoa(m.Winner))
283}
284
285// Reads.
286
287func MatchCount() int { return nextID - 1 }
288
289// Inputs is one side's submitted log ("" until it is in).
290func Inputs(id, side int) string {
291	if side < 0 || side > 1 {
292		panic("side: 0 or 1")
293	}
294	p := mustMatch(id).P[side]
295	if p == nil {
296		return ""
297	}
298	return p.Inputs
299}
300
301// Anchors lists a side's anchors so far, joined by commas.
302func Anchors(id, side int) string {
303	if side < 0 || side > 1 {
304		panic("side: 0 or 1")
305	}
306	p := mustMatch(id).P[side]
307	if p == nil {
308		return ""
309	}
310	return strings.Join(p.Anchors, ",")
311}
312
313// StateJSON describes a match for the programs and the browser.
314func StateJSON(id int) string {
315	m := mustMatch(id)
316	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":[`,
317		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])
318	for s := 0; s < 2; s++ {
319		if s == 1 {
320			out += ","
321		}
322		p := m.P[s]
323		if p == nil {
324			out += "null"
325			continue
326		}
327		out += ufmt.Sprintf(`{"player":%s,"name":%s,"class":%d,"anchors":%d,"submitted":%t}`,
328			strconv.Quote(p.Addr.String()), strconv.Quote(p.Name), p.Class, len(p.Anchors), p.Submitted)
329	}
330	if m.Phase != Waiting {
331		return out + `],"arena":` + strconv.Quote(rules.ArenaName(m.Seed)) + "}"
332	}
333	return out + "]}"
334}
335
336// Render draws the match list for gnoweb.
337func Render(path string) string {
338	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"
339	if matches.Size() == 0 {
340		return out + "No matches yet.\n"
341	}
342	out += "| Match | Players | Phase | Score |\n|---|---|---|---|\n"
343	matches.ReverseIterate("", "", func(k string, v any) bool {
344		m := v.(*Match)
345		b := "-"
346		if m.P[1] != nil {
347			b = m.P[1].Name
348		}
349		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])
350		return false
351	})
352	return out
353}