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.

standings.gno

5.53 Kb · 191 lines
  1// Package standings keeps Gnomepit's ratings, records, ladder and clan ratings, whatever
  2// arena version played the match. Only realms on its owner's writer list report results.
  3package standings
  4
  5import (
  6	"chain/runtime"
  7	"strings"
  8	"time"
  9
 10	"gno.land/p/nt/avl/v0"
 11	"gno.land/p/nt/ownable/v0"
 12)
 13
 14const (
 15	maxWriters  = 255 // a writer number fills one byte of a result entry
 16	maxClanName = 32
 17	maxPkgPath  = 256
 18)
 19
 20var (
 21	owner       *ownable.Ownable
 22	writerPaths []string // every path ever a writer; its index plus one is its writer number
 23	writers     avl.Tree // current writer path → its writer number
 24
 25	players avl.Tree     // address → standing bytes
 26	ladder  *avl.Node    // ladderKey of every rated player → nil
 27	clans   []clanRecord // in first-seen order; a clan's index plus one is its clan number
 28	results avl.Tree     // resultChunkKey → that chunk's result entries, oldest first
 29)
 30
 31func init(cur realm) {
 32	owner = ownable.NewWithAddress(cur.Previous().Address())
 33	addWriter("gno.land/r/nym-gfanton001/gnomepit/arena/v0")
 34}
 35
 36// Record rates a match the calling arena reports as ended, and logs it. result is "a" when
 37// the challenger won, "b" when the acceptor did, and "draw". It aborts unless the caller is
 38// a realm on the writer list, and on a report no correct arena sends: the same player on
 39// both sides, another result, or a clan name that is empty or over 32 bytes.
 40func Record(cur realm, challenger, acceptor address, challengerClan, acceptorClan, result string) {
 41	caller := cur.Previous()
 42	if !caller.IsCode() || !IsWriter(caller.PkgPath()) {
 43		panic("not a writer")
 44	}
 45	if challenger == acceptor {
 46		panic("same player")
 47	}
 48	score := scoreOf(result)
 49	if !validClan(challengerClan) || !validClan(acceptorClan) {
 50		panic("bad clan name")
 51	}
 52	ca, cb := clanNumber(challengerClan), clanNumber(acceptorClan)
 53	rate(challenger, acceptor, ca, cb, score)
 54	appendResult(resultEntry{writer: writers.Get(caller.PkgPath()).(int), challenger: challenger, acceptor: acceptor, clans: [2]int{ca, cb}, result: result[0], time: time.Now().Unix()})
 55}
 56
 57// AddWriter lets the realm at pkgpath, a versioned path under gno.land/r/, report results.
 58// A path that was a writer before gets its old writer number back. Owner only.
 59func AddWriter(cur realm, pkgpath string) {
 60	refuseSession()
 61	owner.AssertOwnedBy(cur.Previous().Address())
 62	if !isVersionedRealm(pkgpath) {
 63		panic("bad writer path")
 64	}
 65	if IsWriter(pkgpath) {
 66		panic("already a writer")
 67	}
 68	addWriter(pkgpath)
 69}
 70
 71// RemoveWriter stops the realm at pkgpath from reporting results. Owner only.
 72func RemoveWriter(cur realm, pkgpath string) {
 73	refuseSession()
 74	owner.AssertOwnedBy(cur.Previous().Address())
 75	if _, removed := writers.Remove(pkgpath); !removed {
 76		panic("not a writer")
 77	}
 78}
 79
 80// TransferOwnership makes newOwner the owner. Owner only.
 81func TransferOwnership(cur realm, newOwner address) {
 82	refuseSession()
 83	if err := owner.TransferOwnership(0, cur, newOwner); err != nil {
 84		panic(err.Error())
 85	}
 86}
 87
 88// refuseSession refuses a call signed with a session key, which its master may have handed
 89// to a page or a script: the writer list answers only to the owner's own key.
 90func refuseSession() {
 91	if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
 92		panic("sign with the owner's own key, not a session key")
 93	}
 94}
 95
 96// IsWriter reports whether the realm at pkgpath may report results.
 97func IsWriter(pkgpath string) bool {
 98	return writers.Has(pkgpath)
 99}
100
101// Writers lists the realms that may report results, in writer-number order.
102func Writers() []string {
103	var list []string
104	for _, p := range writerPaths {
105		if writers.Has(p) {
106			list = append(list, p)
107		}
108	}
109	return list
110}
111
112// Owner is the address that manages the writer list.
113func Owner() address {
114	return owner.Owner()
115}
116
117func addWriter(pkgpath string) {
118	n := 0
119	for i, p := range writerPaths {
120		if p == pkgpath {
121			n = i + 1
122			break
123		}
124	}
125	if n == 0 {
126		if len(writerPaths) == maxWriters {
127			panic("too many writers")
128		}
129		writerPaths = append(writerPaths, pkgpath)
130		n = len(writerPaths)
131	}
132	writers.Set(pkgpath, n)
133}
134
135// isVersionedRealm reports whether pkgpath is under gno.land/r/, at most maxPkgPath bytes of
136// lowercase letters, digits and "/._-", and ends in a version element: "v" and one or more
137// digits. A sub-realm path, with "#", is refused.
138func isVersionedRealm(pkgpath string) bool {
139	if len(pkgpath) > maxPkgPath || !strings.HasPrefix(pkgpath, "gno.land/r/") {
140		return false
141	}
142	for _, c := range pkgpath {
143		if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("/._-", c)) {
144			return false
145		}
146	}
147	v := pkgpath[strings.LastIndex(pkgpath, "/")+1:]
148	if len(v) < 2 || v[0] != 'v' {
149		return false
150	}
151	for _, c := range v[1:] {
152		if c < '0' || c > '9' {
153			return false
154		}
155	}
156	return true
157}
158
159func validClan(name string) bool {
160	return len(name) >= 1 && len(name) <= maxClanName
161}
162
163func appendResult(e resultEntry) {
164	key := resultChunkKey(resultCount() + 1)
165	results.Set(key, stringAt(&results, key)+encodeResult(e))
166}
167
168// resultAt is logged result seq, 1 first.
169func resultAt(seq int) resultEntry {
170	at := (seq - 1) % resultsPerChunk * resultSize
171	return decodeResult(stringAt(&results, resultChunkKey(seq))[at : at+resultSize])
172}
173
174// resultCount counts the logged results: every chunk but the last is full.
175func resultCount() int {
176	n := results.Size()
177	if n == 0 {
178		return 0
179	}
180	_, last := results.GetByIndex(n - 1)
181	return (n-1)*resultsPerChunk + len(last.(string))/resultSize
182}
183
184// stringAt is t's string at key, "" when t has none.
185func stringAt(t *avl.Tree, key string) string {
186	v := t.Get(key)
187	if v == nil {
188		return ""
189	}
190	return v.(string)
191}