codec.gno
12.02 Kb · 512 lines
1package arena
2
3import (
4 "encoding/binary"
5 "encoding/hex"
6
7 "gno.land/p/nym-gfanton001/gnomepit/engine/v0"
8)
9
10// Everything stored by the arena is a byte string laid out here, big-endian. This file
11// is the only code that reads or writes those bytes.
12
13const (
14 chunkSize = 64 // match ids per chunk
15 addressSize = 40 // bytes in an address's text
16 sealSize = 32 // bytes in a raw sha256 seal
17 lockSize = addressSize + 4 + 4
18 openSize = 4 + 4
19
20 planBits = 20 // bits per round in a side's plans: 2 for the length, 6 per card
21 cardBits = 6
22 maxPlanLen = 3
23 maxRound = 3
24 maxPool = 16 // cards in a clan's pool; a deck is one bit per pool card
25)
26
27// ---- Bit fields
28
29// bitsAt returns the width bits of v starting at bit at.
30func bitsAt(v uint64, at, width uint) uint64 {
31 return (v >> at) & mask(width)
32}
33
34// withBits returns v with the width bits at bit at replaced by x.
35func withBits(v uint64, at, width uint, x uint64) uint64 {
36 if x&^mask(width) != 0 {
37 panic("value does not fit")
38 }
39 return v&^(mask(width)<<at) | x<<at
40}
41
42func mask(width uint) uint64 {
43 if width >= 64 {
44 return ^uint64(0)
45 }
46 return 1<<width - 1
47}
48
49// ---- Plans
50
51// planAt returns the plan made for round, or nil when it is not yet made.
52func planAt(plans uint64, round int) engine.Plan {
53 at := planOffset(round)
54 n := int(bitsAt(plans, at, 2))
55 if n == 0 {
56 return nil
57 }
58 p := make(engine.Plan, n)
59 for i := range p {
60 p[i] = engine.CardID(bitsAt(plans, at+2+uint(i)*cardBits, cardBits))
61 }
62 return p
63}
64
65// withPlan returns plans with round's plan set to p.
66func withPlan(plans uint64, round int, p engine.Plan) uint64 {
67 if len(p) < 1 || len(p) > maxPlanLen {
68 panic("invalid plan")
69 }
70 at := planOffset(round)
71 v := withBits(0, 0, 2, uint64(len(p)))
72 for i, id := range p {
73 if id < 0 || id >= 1<<cardBits {
74 panic("invalid plan")
75 }
76 v = withBits(v, 2+uint(i)*cardBits, cardBits, uint64(id))
77 }
78 return withBits(plans, at, planBits, 0) | v<<at
79}
80
81// plansMade counts the rounds from the first that have a plan.
82func plansMade(plans uint64) int {
83 n := 0
84 for n < maxRound && bitsAt(plans, planOffset(n+1), 2) != 0 {
85 n++
86 }
87 return n
88}
89
90func planOffset(round int) uint {
91 if round < 1 || round > maxRound {
92 panic("invalid plan")
93 }
94 return uint(round-1) * planBits
95}
96
97// ---- Decks
98
99// deckOnPool returns deck, a set of card ids, as one bit per card of pool in id order.
100func deckOnPool(pool, deck uint64) uint16 {
101 if cardsIn(pool) > maxPool {
102 panic("pool holds more than 16 cards")
103 }
104 if deck&^pool != 0 {
105 panic("deck outside the pool")
106 }
107 var bits uint16
108 k := uint(0)
109 for id := uint(0); id < 64; id++ {
110 if pool&(1<<id) == 0 {
111 continue
112 }
113 if deck&(1<<id) != 0 {
114 bits |= 1 << k
115 }
116 k++
117 }
118 return bits
119}
120
121// deckFromPool is the inverse of deckOnPool.
122func deckFromPool(pool uint64, bits uint16) uint64 {
123 if cardsIn(pool) > maxPool {
124 panic("pool holds more than 16 cards")
125 }
126 var deck uint64
127 k := uint(0)
128 for id := uint(0); id < 64; id++ {
129 if pool&(1<<id) == 0 {
130 continue
131 }
132 if bits&(1<<k) != 0 {
133 deck |= 1 << id
134 }
135 k++
136 }
137 if uint64(bits)>>k != 0 {
138 panic("deck outside the pool")
139 }
140 return deck
141}
142
143func cardsIn(pool uint64) uint {
144 n := uint(0)
145 for ; pool != 0; pool &= pool - 1 {
146 n++
147 }
148 return n
149}
150
151// ---- Byte reading and writing
152
153type writer struct{ b []byte }
154
155func (w *writer) u8(x uint64) { w.b = append(w.b, byte(x)) }
156func (w *writer) text(s string) { w.b = append(w.b, s...) }
157
158func (w *writer) u16(x uint64) {
159 var t [2]byte
160 binary.BigEndian.PutUint16(t[:], uint16(x))
161 w.b = append(w.b, t[:]...)
162}
163
164func (w *writer) u32(x uint64) {
165 var t [4]byte
166 binary.BigEndian.PutUint32(t[:], uint32(x))
167 w.b = append(w.b, t[:]...)
168}
169
170func (w *writer) u64(x uint64) {
171 var t [8]byte
172 binary.BigEndian.PutUint64(t[:], x)
173 w.b = append(w.b, t[:]...)
174}
175
176// addr writes a's 40 characters.
177func (w *writer) addr(a address) {
178 if len(a) != addressSize {
179 panic("invalid address")
180 }
181 w.text(string(a))
182}
183
184// seal writes a seal, 64 hex characters, as 32 raw bytes.
185func (w *writer) seal(s string) {
186 raw, err := hex.DecodeString(s)
187 if err != nil || len(raw) != sealSize {
188 panic("invalid seal")
189 }
190 w.b = append(w.b, raw...)
191}
192
193func (w *writer) String() string { return string(w.b) }
194
195type reader struct {
196 s string
197 at int
198}
199
200func (r *reader) left() int { return len(r.s) - r.at }
201
202func (r *reader) text(n int) string {
203 if r.left() < n {
204 panic("truncated record")
205 }
206 s := r.s[r.at : r.at+n]
207 r.at += n
208 return s
209}
210
211func (r *reader) u8() uint64 { return uint64(r.text(1)[0]) }
212func (r *reader) u16() uint64 { return uint64(binary.BigEndian.Uint16([]byte(r.text(2)))) }
213func (r *reader) u32() uint64 { return uint64(binary.BigEndian.Uint32([]byte(r.text(4)))) }
214func (r *reader) u64() uint64 { return binary.BigEndian.Uint64([]byte(r.text(8))) }
215func (r *reader) addr() address { return address(r.text(addressSize)) }
216
217// seal reads 32 raw bytes as 64 hex characters.
218func (r *reader) seal() string { return hex.EncodeToString([]byte(r.text(sealSize))) }
219
220// ---- Match record
221
222// record is a match as the arena works on it, decoded from its stored bytes. clans holds
223// each side's index in the ruleset plus one, 0 for none; decks and plans are the engine's
224// card sets and the packed plans of withPlan; hp is the HP after each round, per side;
225// carried holds only the Vulnerable and Strength left after the last resolved round.
226// deckSeal and seal are 64 hex characters; box is the raw bytes, up to maxBox, stored with a 2-byte length.
227type record struct {
228 phase, result, reason string
229 clans [2]int
230 deadline int64
231 decks [2]uint64
232 plans [2]uint64
233 hp [3][2]int
234 carried [2]engine.Vitals
235 challenger, acceptor address
236 opponent address
237 deckSeal, seal, box string
238}
239
240const (
241 flagOpponent = 1 << iota
242 flagDeckSeal
243 flagSealBox
244)
245
246// The value of each name is its index; 0 of result and reason is none.
247var (
248 phaseNames = []string{phaseOpen, phaseReveal, phasePlay, phaseEnded}
249 resultNames = []string{"", "a", "b", "draw"}
250 reasonNames = []string{"", "hp", "knockout", "forfeit", "resign"}
251)
252
253func nameIndex(names []string, s, what string) uint64 {
254 for i, n := range names {
255 if n == s {
256 return uint64(i)
257 }
258 }
259 panic("unknown " + what)
260}
261
262func nameAt(names []string, i uint64, what string) string {
263 if i >= uint64(len(names)) {
264 panic("unknown " + what)
265 }
266 return names[i]
267}
268
269func encodeMatch(rules *engine.Ruleset, m record) string {
270 var flags uint64
271 if m.opponent != "" {
272 flags |= flagOpponent
273 }
274 if m.deckSeal != "" {
275 flags |= flagDeckSeal
276 }
277 if m.seal != "" || m.box != "" {
278 flags |= flagSealBox
279 }
280
281 w := &writer{}
282 w.u8(nameIndex(phaseNames, m.phase, "phase") |
283 nameIndex(resultNames, m.result, "result")<<3 |
284 nameIndex(reasonNames, m.reason, "reason")<<5)
285 w.u8(clanNibble(rules, m.clans[0])<<4 | clanNibble(rules, m.clans[1]))
286 w.u8(flags)
287 w.u32(uint64(m.deadline))
288 for side := 0; side < 2; side++ {
289 w.u16(uint64(deckOnPool(poolOf(rules, m.clans[side]), m.decks[side])))
290 }
291 w.u64(m.plans[0])
292 w.u64(m.plans[1])
293 for _, round := range m.hp {
294 for _, hp := range round {
295 if hp < -128 || hp > 127 {
296 panic("hp does not fit a byte")
297 }
298 w.u8(uint64(int8(hp)))
299 }
300 }
301 for _, v := range m.carried {
302 if v.Vulnerable < 0 || v.Vulnerable > 15 || v.Strength < 0 || v.Strength > 15 {
303 panic("carried state does not fit")
304 }
305 w.u8(uint64(v.Vulnerable)<<4 | uint64(v.Strength))
306 }
307 w.addr(m.challenger)
308 if m.phase != phaseOpen {
309 w.addr(m.acceptor)
310 }
311 if flags&flagOpponent != 0 {
312 w.addr(m.opponent)
313 }
314 if flags&flagDeckSeal != 0 {
315 w.seal(m.deckSeal)
316 }
317 if flags&flagSealBox != 0 {
318 if len(m.box) > maxBox {
319 panic("box too long")
320 }
321 w.seal(m.seal)
322 w.u16(uint64(len(m.box)))
323 w.text(m.box)
324 }
325 return w.String()
326}
327
328func decodeMatch(rules *engine.Ruleset, b string) record {
329 var m record
330 r := &reader{s: b}
331 first := r.u8()
332 m.phase = nameAt(phaseNames, first&7, "phase")
333 m.result = nameAt(resultNames, first>>3&3, "result")
334 m.reason = nameAt(reasonNames, first>>5, "reason")
335 clans := r.u8()
336 m.clans = [2]int{int(clans >> 4), int(clans & 15)}
337 flags := r.u8()
338 m.deadline = int64(r.u32())
339 for side := 0; side < 2; side++ {
340 m.decks[side] = deckFromPool(poolOf(rules, m.clans[side]), uint16(r.u16()))
341 }
342 m.plans[0] = r.u64()
343 m.plans[1] = r.u64()
344 for round := range m.hp {
345 for side := range m.hp[round] {
346 m.hp[round][side] = int(int8(r.u8()))
347 }
348 }
349 for side := range m.carried {
350 v := r.u8()
351 m.carried[side] = engine.Vitals{Vulnerable: int(v >> 4), Strength: int(v & 15)}
352 }
353 m.challenger = r.addr()
354 if m.phase != phaseOpen {
355 m.acceptor = r.addr()
356 }
357 if flags&flagOpponent != 0 {
358 m.opponent = r.addr()
359 }
360 if flags&flagDeckSeal != 0 {
361 m.deckSeal = r.seal()
362 }
363 if flags&flagSealBox != 0 {
364 m.seal = r.seal()
365 m.box = r.text(int(r.u16()))
366 }
367 if r.left() != 0 {
368 panic("trailing bytes in record")
369 }
370 return m
371}
372
373// clanNibble is a clan's stored form, its ruleset index plus one, checked against rules.
374func clanNibble(rules *engine.Ruleset, clan int) uint64 {
375 poolOf(rules, clan)
376 return uint64(clan)
377}
378
379// poolOf returns the card pool of clan, 0 for no clan.
380func poolOf(rules *engine.Ruleset, clan int) uint64 {
381 if clan == 0 {
382 return 0
383 }
384 if clan < 0 || clan > len(rules.Clans) {
385 panic("unknown clan")
386 }
387 return rules.Clans[clan-1].Pool
388}
389
390// ---- Chunks
391
392// A chunk holds, for each match id in order, a 2-byte record length and the record. A
393// removed match keeps its place with length 0.
394
395// chunkRecord returns the record in slot, or "" when it is removed or beyond the chunk.
396func chunkRecord(chunk string, slot int) string {
397 r := &reader{s: chunk}
398 for i := 0; r.left() > 0; i++ {
399 rec := r.text(int(r.u16()))
400 if i == slot {
401 return rec
402 }
403 }
404 return ""
405}
406
407// withChunkRecord returns chunk with slot's record set to rec, adding empty slots up to it.
408func withChunkRecord(chunk string, slot int, rec string) string {
409 if slot < 0 || slot >= chunkSize {
410 panic("slot outside the chunk")
411 }
412 if len(rec) > 0xFFFF {
413 panic("record too long")
414 }
415 r := &reader{s: chunk}
416 w := &writer{}
417 for i := 0; i <= slot || r.left() > 0; i++ {
418 var old string
419 if r.left() > 0 {
420 old = r.text(int(r.u16()))
421 }
422 if i == slot {
423 old = rec
424 }
425 w.u16(uint64(len(old)))
426 w.text(old)
427 }
428 return w.String()
429}
430
431// ---- Players
432
433// playerRecord is what the arena keeps per player: the ids of their matches, oldest
434// first, and the session locks that bind a session key to one match.
435type playerRecord struct {
436 ids []int
437 locks []sessionLock
438}
439
440type sessionLock struct {
441 session address
442 id int
443 expires int64
444}
445
446// decodePlayer reads a player's bytes: a 2-byte id count, the ids at 4 bytes each, then the
447// locks.
448// ceiling: joining a match or changing a lock rewrites all of a player's ids, up to 65,535, so
449// gas grows with their matches; an avl index of ids per player if some play thousands.
450func decodePlayer(s string) playerRecord {
451 var p playerRecord
452 if s == "" {
453 return p
454 }
455 r := &reader{s: s}
456 for n := r.u16(); n > 0; n-- {
457 p.ids = append(p.ids, int(r.u32()))
458 }
459 if r.left()%lockSize != 0 {
460 panic("malformed player")
461 }
462 for r.left() > 0 {
463 p.locks = append(p.locks, sessionLock{session: r.addr(), id: int(r.u32()), expires: int64(r.u32())})
464 }
465 return p
466}
467
468func encodePlayer(p playerRecord) string {
469 if len(p.ids) > 0xFFFF {
470 panic("too many matches")
471 }
472 w := &writer{}
473 w.u16(uint64(len(p.ids)))
474 for _, id := range p.ids {
475 w.u32(uint64(id))
476 }
477 for _, l := range p.locks {
478 w.addr(l.session)
479 w.u32(uint64(l.id))
480 w.u32(uint64(l.expires))
481 }
482 return w.String()
483}
484
485// ---- Open challenges
486
487// openEntry is a challenge on the board: its match id and expiry in Unix seconds.
488type openEntry struct {
489 id int
490 expires int64
491}
492
493func openEntries(s string) []openEntry {
494 if len(s)%openSize != 0 {
495 panic("malformed open list")
496 }
497 r := &reader{s: s}
498 var entries []openEntry
499 for r.left() > 0 {
500 entries = append(entries, openEntry{id: int(r.u32()), expires: int64(r.u32())})
501 }
502 return entries
503}
504
505func encodeOpen(entries []openEntry) string {
506 w := &writer{}
507 for _, e := range entries {
508 w.u32(uint64(e.id))
509 w.u32(uint64(e.expires))
510 }
511 return w.String()
512}