Playground
codec.gno
package standings
import "encoding/binary"
// The standings and the result log are stored as byte strings laid out here, big-endian.
const (
addressSize = 40 // bytes in an address's text
standingFix = 2 + 2 + 2 + 2 + 1 // a standing's bytes before its per-clan counts
resultSize = 1 + 2*addressSize + 1 + 1 + 1 + 4
// resultsPerChunk is the most entries in a log chunk, one string, so a new result grows a
// string instead of adding tree nodes.
resultsPerChunk = 64
)
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[:]...)
}
// addr writes a's 40 characters.
func (w *writer) addr(a address) {
if len(a) != addressSize {
panic("invalid address")
}
w.text(string(a))
}
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) addr() address { return address(r.text(addressSize)) }
// standing is a player's rated record. lastClan is the clan number of their last rated
// match; perClan[i] counts their rated matches with clan number i + 1.
type standing struct {
rating, wins, losses, draws int
lastClan int
perClan []int
}
// decodeStanding reads a standing's bytes: the rating, wins, losses and draws at 2 bytes
// each, the last clan number at 1, then a 2-byte count per clan number played.
func decodeStanding(s string) *standing {
if s == "" {
return nil
}
if len(s) < standingFix || (len(s)-standingFix)%2 != 0 {
panic("malformed standing")
}
r := &reader{s: s}
st := &standing{rating: int(r.u16()), wins: int(r.u16()), losses: int(r.u16()), draws: int(r.u16()), lastClan: int(r.u8())}
for r.left() > 0 {
st.perClan = append(st.perClan, int(r.u16()))
}
return st
}
func encodeStanding(st *standing) string {
w := &writer{}
w.u16(uint64(st.rating))
w.u16(uint64(st.wins))
w.u16(uint64(st.losses))
w.u16(uint64(st.draws))
w.u8(uint64(st.lastClan))
for _, n := range st.perClan {
w.u16(uint64(n))
}
return w.String()
}
// ladderKey orders the ladder: highest rating first, then address order.
func ladderKey(rating int, player address) string {
w := &writer{}
w.u16(uint64(maxRating - rating))
w.text(string(player))
return w.String()
}
// resultEntry is one logged result. writer is the reporting realm's writer number, clans
// the two clan numbers, result 'a', 'b' or 'd', and time the block's Unix seconds.
type resultEntry struct {
writer int
challenger, acceptor address
clans [2]int
result byte
time int64
}
// resultChunkKey is the log key of the chunk that holds result seq, 1 first.
func resultChunkKey(seq int) string {
w := &writer{}
w.u32(uint64((seq - 1) / resultsPerChunk))
return w.String()
}
func encodeResult(e resultEntry) string {
w := &writer{}
w.u8(uint64(e.writer))
w.addr(e.challenger)
w.addr(e.acceptor)
w.u8(uint64(e.clans[0]))
w.u8(uint64(e.clans[1]))
w.u8(uint64(e.result))
w.u32(uint64(e.time))
return w.String()
}
func decodeResult(s string) resultEntry {
if len(s) != resultSize {
panic("malformed result")
}
r := &reader{s: s}
return resultEntry{
writer: int(r.u8()),
challenger: r.addr(),
acceptor: r.addr(),
clans: [2]int{int(r.u8()), int(r.u8())},
result: byte(r.u8()),
time: int64(r.u32()),
}
}
codec_test.gno
package standings
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestLadderKeyOrder(t *testing.T) {
uassert.True(t, ladderKey(1016, bob) < ladderKey(1000, alice), "higher rating first")
uassert.Equal(t, alice < bob, ladderKey(1000, alice) < ladderKey(1000, bob), "address order within a rating")
uassert.Equal(t, 42, len(ladderKey(0, alice)))
}
gnomod.toml
module = "gno.land/r/nym-gfanton001/gnomepit/standings/v0" gno = "0.9" [addpkg] creator = "g18me5p9kqqxyswd8ytrmlv3q8kvy7uacx2v90ne" height = 865684 max_deposit = "17000000ugnot"
query.gno
package standings
import (
"gno.land/p/nt/avl/v0"
"gno.land/r/sys/users"
)
const maxPage = 50
// Standing is one player's place on the ladder. Rank is 1 for the highest rating and
// equal ratings share it; Rank is 0 and Rating 1000 for a player with no rated match.
// Name is the player's gno.land name, "" without one. MainClan is "" until their
// first rated match with a counted clan.
type Standing struct {
Rank int
Player, Name, MainClan string
Rating int
Wins, Losses, Draws int
}
// ClanStanding is one clan's record across rated cross-clan matches.
type ClanStanding struct {
Rank int
Clan string
Rating int
Wins, Losses, Draws int
}
// Result is one logged result. Seq is its place in the log, 1 first; Writer is the path
// of the realm that reported it. Result is "a" when the challenger won, "b" when the
// acceptor did, and "draw"; Time is the block's Unix seconds.
type Result struct {
Seq int
Writer string
Challenger, Acceptor string
ChallengerClan, AcceptorClan string
Result string
Time int64
}
// Leaderboard lists rated players, highest rating first: limit of them after skipping offset.
func Leaderboard(offset, limit int) []Standing {
checkPage(offset, limit)
list := []Standing{}
ladder.TraverseByOffset(offset, limit, true, true, func(n *avl.Node) bool {
s := standingOf(address(n.Key()[2:]))
switch {
case len(list) == 0:
s.Rank = rankOf(s.Rating)
case list[len(list)-1].Rating == s.Rating:
s.Rank = list[len(list)-1].Rank
default:
s.Rank = offset + len(list) + 1
}
list = append(list, s)
return false
})
return list
}
// StandingOf returns player's standing, rated or not.
func StandingOf(player address) Standing {
s := standingOf(player)
if s.Wins+s.Losses+s.Draws > 0 {
s.Rank = rankOf(s.Rating)
}
return s
}
// RatedPlayers counts the players on the ladder.
func RatedPlayers() int {
return ladder.Size()
}
// ClanStandings lists every clan with a rated cross-clan match, highest rating first;
// equal ratings keep first-seen order and share a rank. Clans with no such match are left
// out: they stand at 1000 and 0-0-0.
func ClanStandings() []ClanStanding {
list := []ClanStanding{}
for _, c := range clans {
if c.wins+c.losses+c.draws == 0 {
continue
}
list = append(list, ClanStanding{Clan: c.name, Rating: c.rating, Wins: c.wins, Losses: c.losses, Draws: c.draws})
}
for i := 1; i < len(list); i++ {
for j := i; j > 0 && list[j].Rating > list[j-1].Rating; j-- {
list[j], list[j-1] = list[j-1], list[j]
}
}
for i := range list {
if i > 0 && list[i].Rating == list[i-1].Rating {
list[i].Rank = list[i-1].Rank
} else {
list[i].Rank = i + 1
}
}
return list
}
// Results lists logged results, oldest first: limit of them after skipping offset.
func Results(offset, limit int) []Result {
checkPage(offset, limit)
list := []Result{}
n := resultCount()
if offset >= n {
return list
}
end := offset + limit
if end > n {
end = n
}
for seq := offset + 1; seq <= end; seq++ {
e := resultAt(seq)
list = append(list, Result{
Seq: seq,
Writer: writerPaths[e.writer-1],
Challenger: e.challenger.String(),
Acceptor: e.acceptor.String(),
ChallengerClan: clanName(e.clans[0]),
AcceptorClan: clanName(e.clans[1]),
Result: resultName(e.result),
Time: e.time,
})
}
return list
}
// ResultCount counts the logged results.
func ResultCount() int {
return resultCount()
}
// standingOf is player's standing without its rank.
func standingOf(player address) Standing {
s := Standing{Player: player.String(), Name: nameOf(player), Rating: startRating}
st := loadStanding(player)
if st == nil {
return s
}
s.MainClan = clanName(st.mainClan())
s.Rating, s.Wins, s.Losses, s.Draws = st.rating, st.wins, st.losses, st.draws
return s
}
// nameOf is player's gno.land name, "" when they have none.
func nameOf(player address) string {
u := users.ResolveAddress(player)
if u.IsDeleted() {
return ""
}
return u.Name()
}
// clanName is the name of clan number n, "" for 0, no clan.
func clanName(n int) string {
if n == 0 {
return ""
}
return clans[n-1].name
}
func resultName(b byte) string {
if b == 'd' {
return "draw"
}
return string(b)
}
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")
}
}
query_test.gno
package standings
import (
"strconv"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
"gno.land/r/sys/users"
)
// giveName registers name for a in r/sys/users, as the users realm's genesis controller
// does; the registry outlives reset, so a name given once stays.
func giveName(cur realm, a address, name string) {
if !users.ResolveAddress(a).IsDeleted() {
return
}
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users/init"))
if err := users.RegisterUser(cross(cur), name, a); err != nil {
panic(err.Error())
}
}
func ranks(list []Standing) string {
out := ""
for _, s := range list {
out += strconv.Itoa(s.Rank) + " "
}
return out
}
func TestStandingOfUnrated(t *testing.T) {
reset()
s := StandingOf(carol)
uassert.Equal(t, 0, s.Rank)
uassert.Equal(t, carol.String(), s.Player)
uassert.Equal(t, "", s.Name)
uassert.Equal(t, "", s.MainClan)
uassert.Equal(t, 1000, s.Rating)
uassert.Equal(t, 0, s.Wins+s.Losses+s.Draws)
}
func TestStandingOfNamed(cur realm, t *testing.T) {
reset()
giveName(cur, alice, "alice")
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
s := StandingOf(alice)
uassert.Equal(t, "alice", s.Name)
uassert.Equal(t, 1, s.Rank)
uassert.Equal(t, "Pickers", s.MainClan)
uassert.Equal(t, 1016, s.Rating)
uassert.Equal(t, 1, s.Wins)
uassert.Equal(t, "", StandingOf(bob).Name, "an address without a name has none")
uassert.Equal(t, 2, StandingOf(bob).Rank)
}
func TestLeaderboardSharedRankAcrossPages(t *testing.T) {
reset()
seed(alice, 1016)
seed(bob, 1016)
seed(carol, 1016)
seed(dave, 952)
uassert.Equal(t, "1 1 ", ranks(Leaderboard(0, 2)))
uassert.Equal(t, "1 4 ", ranks(Leaderboard(2, 2)), "a page that opens inside a tie keeps its shared rank")
uassert.Equal(t, "1 1 1 4 ", ranks(Leaderboard(0, 50)))
}
func TestLeaderboardLimits(t *testing.T) {
reset()
uassert.PanicsWithMessage(t, nil, "limit must be 1 to 50", func() { Leaderboard(0, 0) })
uassert.PanicsWithMessage(t, nil, "limit must be 1 to 50", func() { Leaderboard(0, 51) })
uassert.PanicsWithMessage(t, nil, "offset must not be negative", func() { Leaderboard(-1, 10) })
list := Leaderboard(0, 50)
uassert.True(t, list != nil)
uassert.Equal(t, 0, len(list))
}
func TestLeaderboardFiftyNamed(cur realm, t *testing.T) {
reset()
for i := 0; i < 50; i++ {
a := testutils.TestAddress("player" + strconv.Itoa(i))
giveName(cur, a, "player"+strconv.Itoa(i))
seed(a, 1000+i)
}
list := Leaderboard(0, 50)
urequire.Equal(t, 50, len(list))
for i, s := range list {
uassert.Equal(t, 1049-i, s.Rating)
uassert.Equal(t, i+1, s.Rank)
uassert.Equal(t, "player"+strconv.Itoa(49-i), s.Name)
}
}
func TestRatedPlayers(cur realm, t *testing.T) {
reset()
uassert.Equal(t, 0, RatedPlayers())
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
uassert.Equal(t, 2, RatedPlayers())
}
func TestClanStandings(cur realm, t *testing.T) {
reset()
list := ClanStandings()
uassert.True(t, list != nil)
uassert.Equal(t, 0, len(list))
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
Record(cross(cur), carol, dave, "Delvers", "Delvers", "a")
list = ClanStandings()
urequire.Equal(t, 2, len(list), "a clan with only mirror matches is not listed")
uassert.Equal(t, "Pickers", list[0].Clan)
uassert.Equal(t, 1, list[0].Rank)
uassert.Equal(t, 1008, list[0].Rating)
uassert.Equal(t, 1, list[0].Wins)
uassert.Equal(t, "Ironhide", list[1].Clan)
uassert.Equal(t, 2, list[1].Rank)
uassert.Equal(t, 992, list[1].Rating)
uassert.Equal(t, 1, list[1].Losses)
}
func TestResultsPageAcrossChunks(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
for i := 0; i < 65; i++ {
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
}
page := Results(62, 5)
urequire.Equal(t, 3, len(page))
for i, r := range page {
uassert.Equal(t, 63+i, r.Seq)
}
uassert.Equal(t, 65, ResultCount())
}
func TestLeaderboardAndStandingOfAgree(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
Record(cross(cur), carol, dave, "Delvers", "Pickers", "draw")
Record(cross(cur), carol, alice, "Delvers", "Pickers", "a")
Record(cross(cur), dave, bob, "Ironhide", "Ironhide", "b")
Record(cross(cur), bob, carol, "Ironhide", "Delvers", "a")
erin, frank, gina := testutils.TestAddress("erin"), testutils.TestAddress("frank"), testutils.TestAddress("gina")
Record(cross(cur), erin, alice, "Pickers", "Pickers", "a")
Record(cross(cur), frank, gina, "Delvers", "Ironhide", "draw")
board := Leaderboard(0, 50)
urequire.Equal(t, 7, len(board))
for _, s := range board {
uassert.Equal(t, s.Rank, StandingOf(address(s.Player)).Rank, s.Player)
}
for off := 0; off < len(board); off += 2 {
for i, s := range Leaderboard(off, 2) {
uassert.Equal(t, board[off+i].Rank, s.Rank, "the page at offset "+strconv.Itoa(off))
}
}
tied := StandingOf(frank).Rank
uassert.True(t, tied > 1, "frank and gina tie below first place")
uassert.Equal(t, tied, StandingOf(gina).Rank)
}
func TestResultsPage(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
Record(cross(cur), bob, carol, "Ironhide", "Delvers", "b")
Record(cross(cur), carol, alice, "Delvers", "Pickers", "draw")
uassert.Equal(t, 3, ResultCount())
page := Results(1, 2)
urequire.Equal(t, 2, len(page))
uassert.Equal(t, 2, page[0].Seq)
uassert.Equal(t, arenaV0, page[0].Writer)
uassert.Equal(t, bob.String(), page[0].Challenger)
uassert.Equal(t, carol.String(), page[0].Acceptor)
uassert.Equal(t, "Ironhide", page[0].ChallengerClan)
uassert.Equal(t, "Delvers", page[0].AcceptorClan)
uassert.Equal(t, "b", page[0].Result)
uassert.Equal(t, 3, page[1].Seq)
uassert.Equal(t, "draw", page[1].Result)
uassert.Equal(t, "Pickers", page[1].AcceptorClan)
uassert.Equal(t, 0, len(Results(3, 10)), "a page past the log is empty")
uassert.PanicsWithMessage(t, nil, "limit must be 1 to 50", func() { Results(0, 51) })
uassert.PanicsWithMessage(t, nil, "offset must not be negative", func() { Results(-1, 10) })
}
rating.gno
package standings
const (
startRating = 1000
maxRating = 0xFFFF // a ladder key holds the rating in 2 bytes
playerK = 32
clanK = 16
maxClans = 255 // a clan number fills one byte of a standing and a result entry
maxPlayerCount = 0xFFFF // a player's counts are stored in 2 bytes
maxClanCount = 0xFFFFFFFF
)
// clanRecord is a clan's rating and its record in rated matches against other clans.
type clanRecord struct {
name string
rating, wins, losses, draws int
}
// expectedTable is the expected score, in thousandths, of a side whose opponent is rated
// 0, 25, …, 400 points above it: 1 / (1 + 10^(d / 400)), rounded.
var expectedTable = [17]int{500, 464, 429, 394, 360, 327, 297, 267, 240, 215, 192, 170, 151, 133, 118, 104, 91}
// expected is the expected score, in thousandths, of a side rated a against one rated b.
// The gap is capped at 400 points and rounded to the nearest 25.
func expected(a, b int) int {
d := b - a
if d < 0 {
return 1000 - expected(b, a)
}
if d > 400 {
d = 400
}
return expectedTable[(d+12)/25]
}
// eloChange is the change, rounded to the nearest point, of a side rated a that scored
// score thousandths (1000 a win, 500 a draw, 0 a loss) against one rated b.
func eloChange(a, b, score, k int) int {
x := k * (score - expected(a, b))
if x < 0 {
return -((-x + 500) / 1000)
}
return (x + 500) / 1000
}
// applyChange gives a the change delta and b its negative, each kept within 0 to maxRating.
func applyChange(a, b, delta int) (int, int) {
return clampRating(a + delta), clampRating(b - delta)
}
func clampRating(r int) int {
if r < 0 {
return 0
}
if r > maxRating {
return maxRating
}
return r
}
// rate counts a match between a, playing clan number ca, and b, playing clan number cb,
// in which a scored score thousandths: in both standings, on the ladder, and in the clan
// records when both clans are counted and differ.
func rate(a, b address, ca, cb, score int) {
sa, sb := ratedStanding(a), ratedStanding(b)
sa.rating, sb.rating = applyChange(sa.rating, sb.rating, eloChange(sa.rating, sb.rating, score, playerK))
sa.count(score, ca)
sb.count(1000-score, cb)
ladder, _ = ladder.Set(ladderKey(sa.rating, a), nil)
ladder, _ = ladder.Set(ladderKey(sb.rating, b), nil)
saveStanding(a, sa)
saveStanding(b, sb)
if ca == cb || ca == 0 || cb == 0 {
return
}
x, y := &clans[ca-1], &clans[cb-1]
x.rating, y.rating = applyChange(x.rating, y.rating, eloChange(x.rating, y.rating, score, clanK))
tally(score, &x.wins, &x.losses, &x.draws, maxClanCount)
tally(1000-score, &y.wins, &y.losses, &y.draws, maxClanCount)
}
// ratedStanding returns a's standing, created at startRating for a first rated match, and
// takes its key off the ladder until it is counted.
func ratedStanding(a address) *standing {
st := loadStanding(a)
if st == nil {
st = &standing{rating: startRating}
} else {
ladder, _, _, _ = ladder.Remove(ladderKey(st.rating, a))
}
return st
}
// loadStanding returns a's standing, nil before their first rated match.
func loadStanding(a address) *standing {
return decodeStanding(stringAt(&players, string(a)))
}
func saveStanding(a address, st *standing) {
players.Set(string(a), encodeStanding(st))
}
// clanNumber is the clan number of name, its first-seen position plus one. A name not
// seen before gets the next number, or 0, no clan, once maxClans are numbered: a writer
// that fills the table must not abort another writer's endings.
func clanNumber(name string) int {
for i, c := range clans {
if c.name == name {
return i + 1
}
}
if len(clans) == maxClans {
return 0
}
clans = append(clans, clanRecord{name: name, rating: startRating})
return len(clans)
}
// scoreOf is the challenger's score, in thousandths, in a match that ended with result.
func scoreOf(result string) int {
switch result {
case "a":
return 1000
case "b":
return 0
case "draw":
return 500
}
panic("unknown result")
}
// count adds a match scored score thousandths and played as clan number clan, 0 for none.
// perClan grows only as far as the clan numbers s has played.
func (s *standing) count(score, clan int) {
tally(score, &s.wins, &s.losses, &s.draws, maxPlayerCount)
s.lastClan = clan
if clan == 0 {
return
}
for len(s.perClan) < clan {
s.perClan = append(s.perClan, 0)
}
if s.perClan[clan-1] < maxPlayerCount {
s.perClan[clan-1]++
}
}
// tally adds a win, loss or draw for score, each count stopping at ceiling.
func tally(score int, wins, losses, draws *int, ceiling int) {
n := draws
switch score {
case 1000:
n = wins
case 0:
n = losses
}
if *n < ceiling {
*n++
}
}
// mainClan is the clan number s has finished the most rated matches with, 0 for none. A
// tie goes to the last match's clan when it is one of the tied, else to first-seen order.
func (s standing) mainClan() int {
best := 0
for i, n := range s.perClan {
if n > 0 && (best == 0 || n > s.perClan[best-1]) {
best = i + 1
}
}
if best != 0 && s.lastClan >= 1 && s.lastClan <= len(s.perClan) && s.perClan[s.lastClan-1] == s.perClan[best-1] {
return s.lastClan
}
return best
}
// rankOf is the rank a rating holds: 1 plus the number of players rated above it.
func rankOf(rating int) int {
i, _, _ := ladder.Get(ladderKey(rating, ""))
return i + 1
}
rating_test.gno
package standings
import (
"math"
"strconv"
"testing"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
func showStanding(s standing) string {
out := strconv.Itoa(s.rating) + " " + strconv.Itoa(s.wins) + "-" + strconv.Itoa(s.losses) + "-" +
strconv.Itoa(s.draws) + " last " + strconv.Itoa(s.lastClan) + " per"
for _, n := range s.perClan {
out += " " + strconv.Itoa(n)
}
return out
}
// seed gives a a standing at rating with one rated win as Pickers, clan 1, and its ladder
// key.
func seed(a address, rating int) {
clanNumber("Pickers")
saveStanding(a, &standing{rating: rating, wins: 1, lastClan: 1, perClan: []int{1}})
ladder, _ = ladder.Set(ladderKey(rating, a), nil)
}
// ladderKeys lists the ladder's keys in order.
func ladderKeys() []string {
var keys []string
ladder.TraverseByOffset(0, ladder.Size(), true, true, func(n *avl.Node) bool {
keys = append(keys, n.Key())
return false
})
return keys
}
func TestExpectedTableMatchesFormula(t *testing.T) {
for i, e := range expectedTable {
d := float64(i * 25)
uassert.Equal(t, int(math.Round(1000/(1+math.Pow(10, d/400)))), e)
}
}
func TestExpected(t *testing.T) {
uassert.Equal(t, 500, expected(1000, 1000))
uassert.Equal(t, 500, expected(1000, 1012), "a gap of 12 rounds to 0")
uassert.Equal(t, 464, expected(1000, 1013), "a gap of 13 rounds to 25")
uassert.Equal(t, 360, expected(1000, 1100))
uassert.Equal(t, 640, expected(1100, 1000))
uassert.Equal(t, 91, expected(1000, 1500), "the gap is capped at 400")
uassert.Equal(t, 909, expected(1500, 1000))
}
func TestEloChange(t *testing.T) {
uassert.Equal(t, 16, eloChange(1000, 1000, 1000, playerK))
uassert.Equal(t, 0, eloChange(1000, 1000, 500, playerK))
uassert.Equal(t, 20, eloChange(1000, 1100, 1000, playerK))
uassert.Equal(t, -12, eloChange(1000, 1100, 0, playerK))
uassert.Equal(t, 4, eloChange(1000, 1100, 500, playerK))
uassert.Equal(t, 12, eloChange(1100, 1000, 1000, playerK))
uassert.Equal(t, -20, eloChange(1100, 1000, 0, playerK))
uassert.Equal(t, 29, eloChange(1000, 1500, 1000, playerK))
uassert.Equal(t, 8, eloChange(1000, 1000, 1000, clanK))
}
func TestApplyChangeClamps(t *testing.T) {
a, b := applyChange(1000, 1000, 16)
uassert.Equal(t, 1016, a)
uassert.Equal(t, 984, b)
a, b = applyChange(5, 5, -16)
uassert.Equal(t, 0, a, "no rating goes below 0")
uassert.Equal(t, 21, b)
a, b = applyChange(65530, 900, 29)
uassert.Equal(t, maxRating, a, "no rating goes above what the ladder key holds")
uassert.Equal(t, 871, b)
}
func TestRateFirstMatch(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
a := loadStanding(alice)
urequire.True(t, a != nil)
uassert.Equal(t, "1016 1-0-0 last 1 per 1", showStanding(*a))
uassert.Equal(t, 1, a.mainClan())
b := loadStanding(bob)
urequire.True(t, b != nil)
uassert.Equal(t, "984 0-1-0 last 2 per 0 1", showStanding(*b))
uassert.Equal(t, 2, b.mainClan())
uassert.Equal(t, 2, ladder.Size())
uassert.Equal(t, 1, rankOf(1016))
uassert.Equal(t, 2, rankOf(984))
urequire.Equal(t, 2, len(clans))
uassert.True(t, clans[0] == clanRecord{"Pickers", 1008, 1, 0, 0})
uassert.True(t, clans[1] == clanRecord{"Ironhide", 992, 0, 1, 0})
}
func TestRateMovesLadderKeys(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
a, b := loadStanding(alice), loadStanding(bob)
keys := ladderKeys()
urequire.Equal(t, 2, len(keys))
uassert.Equal(t, ladderKey(a.rating, alice), keys[0])
uassert.Equal(t, ladderKey(b.rating, bob), keys[1])
}
func TestRateDraw(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "draw")
uassert.Equal(t, "1000 0-0-1 last 1 per 1", showStanding(*loadStanding(alice)))
uassert.Equal(t, "1000 0-0-1 last 2 per 0 1", showStanding(*loadStanding(bob)))
}
func TestForfeitCountsForClans(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "b")
uassert.Equal(t, 984, loadStanding(alice).rating)
uassert.Equal(t, 1016, loadStanding(bob).rating)
uassert.True(t, clans[0] == clanRecord{"Pickers", 992, 0, 1, 0}, "the clan that ran out of time loses")
uassert.True(t, clans[1] == clanRecord{"Ironhide", 1008, 1, 0, 0})
}
func TestMirrorSkipsClans(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Pickers", "a")
uassert.Equal(t, 1016, loadStanding(alice).rating)
urequire.Equal(t, 1, len(clans))
uassert.True(t, clans[0] == clanRecord{name: "Pickers", rating: startRating})
}
func TestSharedRank(t *testing.T) {
reset()
seed(alice, 1016)
seed(bob, 1016)
seed(carol, 984)
uassert.Equal(t, 1, rankOf(1016))
uassert.Equal(t, 3, rankOf(984))
}
func TestMainClanTie(t *testing.T) {
uassert.Equal(t, 2, standing{lastClan: 2, perClan: []int{2, 2, 0}}.mainClan())
uassert.Equal(t, 1, standing{lastClan: 1, perClan: []int{2, 2, 0}}.mainClan())
uassert.Equal(t, 1, standing{lastClan: 3, perClan: []int{2, 2, 1}}.mainClan(), "a tie the last clan is not in goes to first-seen order")
uassert.Equal(t, 0, standing{}.mainClan())
}
func TestClanNumbersFollowFirstSeen(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Ironhide", "Delvers", "a")
first := showStanding(*loadStanding(alice))
Record(cross(cur), carol, dave, "Pickers", "Ironhide", "a")
urequire.Equal(t, 3, len(clans))
uassert.Equal(t, "Ironhide", clans[0].name)
uassert.Equal(t, "Delvers", clans[1].name)
uassert.Equal(t, "Pickers", clans[2].name)
uassert.Equal(t, "1016 1-0-0 last 1 per 1", first)
uassert.Equal(t, first, showStanding(*loadStanding(alice)), "a new clan moves no earlier count")
uassert.Equal(t, "1016 1-0-0 last 3 per 0 0 1", showStanding(*loadStanding(carol)))
uassert.Equal(t, "984 0-1-0 last 1 per 1", showStanding(*loadStanding(dave)))
}
func TestCountersSaturate(cur realm, t *testing.T) {
reset()
clanNumber("Pickers")
clanNumber("Ironhide")
saveStanding(alice, &standing{rating: startRating, wins: 65535, lastClan: 1, perClan: []int{65535, 0}})
clans[1].losses = 4294967295
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
a := loadStanding(alice)
uassert.Equal(t, 65535, a.wins)
uassert.Equal(t, 65535, a.perClan[0])
uassert.Equal(t, 4294967295, clans[1].losses)
}
func TestResultsLogEachRecord(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
Record(cross(cur), bob, alice, "Ironhide", "Ironhide", "draw")
urequire.Equal(t, 2, resultCount())
now := time.Now().Unix()
first := resultAt(1)
uassert.True(t, first == resultEntry{writer: 1, challenger: alice, acceptor: bob, clans: [2]int{1, 2}, result: 'a', time: now})
second := resultAt(2)
uassert.True(t, second == resultEntry{writer: 1, challenger: bob, acceptor: alice, clans: [2]int{2, 2}, result: 'd', time: now})
}
// TestResultsShareChunks checks that a new log entry grows a chunk string instead of adding
// tree nodes, which would cost a rated ending far more storage.
func TestResultsShareChunks(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
for i := 0; i < 65; i++ {
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
}
uassert.Equal(t, 2, results.Size(), "64 results to a chunk")
uassert.Equal(t, 65, resultCount())
uassert.True(t, resultAt(65) == resultEntry{writer: 1, challenger: alice, acceptor: bob, clans: [2]int{1, 2}, result: 'a', time: time.Now().Unix()})
}
// TestClanPastTheTableCountsForNone checks that a writer filling the clan table cannot stop
// another writer's endings: a clan past the table rates its players and counts for no clan.
func TestClanPastTheTableCountsForNone(cur realm, t *testing.T) {
reset()
for i := 1; i <= 255; i++ {
clanNumber("c" + strconv.Itoa(i))
}
testing.SetRealm(testing.NewCodeRealm(arenaV0))
Record(cross(cur), alice, bob, "c1", "c256", "a")
uassert.Equal(t, 255, len(clans))
uassert.True(t, clans[0] == clanRecord{name: "c1", rating: startRating}, "a clan's record moves only against another counted clan")
uassert.Equal(t, "1016 1-0-0 last 1 per 1", showStanding(*loadStanding(alice)))
uassert.Equal(t, "984 0-1-0 last 0 per", showStanding(*loadStanding(bob)))
uassert.Equal(t, 2, StandingOf(bob).Rank, "a player rated with no counted clan still has a rank")
uassert.Equal(t, "", StandingOf(bob).MainClan)
r := Results(0, 1)[0]
uassert.Equal(t, "c1", r.ChallengerClan)
uassert.Equal(t, "", r.AcceptorClan)
}
standings.gno
// Package standings keeps Gnomepit's ratings, records, ladder and clan ratings, whatever
// arena version played the match. Only realms on its owner's writer list report results.
package standings
import (
"chain/runtime"
"strings"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ownable/v0"
)
const (
maxWriters = 255 // a writer number fills one byte of a result entry
maxClanName = 32
maxPkgPath = 256
)
var (
owner *ownable.Ownable
writerPaths []string // every path ever a writer; its index plus one is its writer number
writers avl.Tree // current writer path → its writer number
players avl.Tree // address → standing bytes
ladder *avl.Node // ladderKey of every rated player → nil
clans []clanRecord // in first-seen order; a clan's index plus one is its clan number
results avl.Tree // resultChunkKey → that chunk's result entries, oldest first
)
func init(cur realm) {
owner = ownable.NewWithAddress(cur.Previous().Address())
addWriter("gno.land/r/nym-gfanton001/gnomepit/arena/v0")
}
// Record rates a match the calling arena reports as ended, and logs it. result is "a" when
// the challenger won, "b" when the acceptor did, and "draw". It aborts unless the caller is
// a realm on the writer list, and on a report no correct arena sends: the same player on
// both sides, another result, or a clan name that is empty or over 32 bytes.
func Record(cur realm, challenger, acceptor address, challengerClan, acceptorClan, result string) {
caller := cur.Previous()
if !caller.IsCode() || !IsWriter(caller.PkgPath()) {
panic("not a writer")
}
if challenger == acceptor {
panic("same player")
}
score := scoreOf(result)
if !validClan(challengerClan) || !validClan(acceptorClan) {
panic("bad clan name")
}
ca, cb := clanNumber(challengerClan), clanNumber(acceptorClan)
rate(challenger, acceptor, ca, cb, score)
appendResult(resultEntry{writer: writers.Get(caller.PkgPath()).(int), challenger: challenger, acceptor: acceptor, clans: [2]int{ca, cb}, result: result[0], time: time.Now().Unix()})
}
// AddWriter lets the realm at pkgpath, a versioned path under gno.land/r/, report results.
// A path that was a writer before gets its old writer number back. Owner only.
func AddWriter(cur realm, pkgpath string) {
refuseSession()
owner.AssertOwnedBy(cur.Previous().Address())
if !isVersionedRealm(pkgpath) {
panic("bad writer path")
}
if IsWriter(pkgpath) {
panic("already a writer")
}
addWriter(pkgpath)
}
// RemoveWriter stops the realm at pkgpath from reporting results. Owner only.
func RemoveWriter(cur realm, pkgpath string) {
refuseSession()
owner.AssertOwnedBy(cur.Previous().Address())
if _, removed := writers.Remove(pkgpath); !removed {
panic("not a writer")
}
}
// 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())
}
}
// refuseSession refuses a call signed with a session key, which its master may have handed
// to a page or a script: the writer list answers only to the owner's own key.
func refuseSession() {
if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
panic("sign with the owner's own key, not a session key")
}
}
// IsWriter reports whether the realm at pkgpath may report results.
func IsWriter(pkgpath string) bool {
return writers.Has(pkgpath)
}
// Writers lists the realms that may report results, in writer-number order.
func Writers() []string {
var list []string
for _, p := range writerPaths {
if writers.Has(p) {
list = append(list, p)
}
}
return list
}
// Owner is the address that manages the writer list.
func Owner() address {
return owner.Owner()
}
func addWriter(pkgpath string) {
n := 0
for i, p := range writerPaths {
if p == pkgpath {
n = i + 1
break
}
}
if n == 0 {
if len(writerPaths) == maxWriters {
panic("too many writers")
}
writerPaths = append(writerPaths, pkgpath)
n = len(writerPaths)
}
writers.Set(pkgpath, n)
}
// isVersionedRealm reports whether pkgpath is under gno.land/r/, at most maxPkgPath bytes of
// lowercase letters, digits and "/._-", and ends in a version element: "v" and one or more
// digits. A sub-realm path, with "#", is refused.
func isVersionedRealm(pkgpath string) bool {
if len(pkgpath) > maxPkgPath || !strings.HasPrefix(pkgpath, "gno.land/r/") {
return false
}
for _, c := range pkgpath {
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("/._-", c)) {
return false
}
}
v := pkgpath[strings.LastIndex(pkgpath, "/")+1:]
if len(v) < 2 || v[0] != 'v' {
return false
}
for _, c := range v[1:] {
if c < '0' || c > '9' {
return false
}
}
return true
}
func validClan(name string) bool {
return len(name) >= 1 && len(name) <= maxClanName
}
func appendResult(e resultEntry) {
key := resultChunkKey(resultCount() + 1)
results.Set(key, stringAt(&results, key)+encodeResult(e))
}
// resultAt is logged result seq, 1 first.
func resultAt(seq int) resultEntry {
at := (seq - 1) % resultsPerChunk * resultSize
return decodeResult(stringAt(&results, resultChunkKey(seq))[at : at+resultSize])
}
// resultCount counts the logged results: every chunk but the last is full.
func resultCount() int {
n := results.Size()
if n == 0 {
return 0
}
_, last := results.GetByIndex(n - 1)
return (n-1)*resultsPerChunk + len(last.(string))/resultSize
}
// stringAt is t's string at key, "" when t has none.
func stringAt(t *avl.Tree, key string) string {
v := t.Get(key)
if v == nil {
return ""
}
return v.(string)
}
standings_test.gno
package standings
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ownable/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
const (
arenaV0 = "gno.land/r/nym-gfanton001/gnomepit/arena/v0"
arenaV1 = "gno.land/r/nym-gfanton001/gnomepit/arena/v1"
)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
dave = testutils.TestAddress("dave")
)
// reset empties the standings and the result log; tests share package globals. It leaves
// the writer list alone.
func reset() {
players = avl.Tree{}
ladder = nil
clans = nil
results = avl.Tree{}
}
// ownedBy makes a the owner: under gno test, init's deployer address is empty.
func ownedBy(a address) {
owner = ownable.NewWithAddress(a)
}
// resetWriters leaves the arena the only writer, as init does.
func resetWriters() {
writerPaths = nil
writers = avl.Tree{}
addWriter(arenaV0)
}
// TestInitSeedsTheArena reads the writers init set, so it runs before any test changes them.
func TestInitSeedsTheArena(t *testing.T) {
uassert.Equal(t, strings.Join([]string{arenaV0}, ","), strings.Join(Writers(), ","))
uassert.True(t, IsWriter(arenaV0))
uassert.False(t, IsWriter(arenaV1))
}
func TestRecordRefusesNonWriters(cur realm, t *testing.T) {
resetWriters()
ownedBy(alice)
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsWithMessage(t, cur, "not a writer", func() {
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
})
testing.SetRealm(testing.NewCodeRealm(arenaV1))
uassert.AbortsWithMessage(t, cur, "not a writer", func() {
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
})
testing.SetRealm(testing.NewUserRealm(alice))
RemoveWriter(cross(cur), arenaV0)
testing.SetRealm(testing.NewCodeRealm(arenaV0))
uassert.AbortsWithMessage(t, cur, "not a writer", func() {
Record(cross(cur), alice, bob, "Pickers", "Ironhide", "a")
})
resetWriters()
}
func TestRecordRefusesBadInput(cur realm, t *testing.T) {
resetWriters()
testing.SetRealm(testing.NewCodeRealm(arenaV0))
long := strings.Repeat("x", 33)
cases := []struct {
name string
challenger, acceptor address
challengerClan, acceptorClan, result string
want string
}{
{"same player", alice, alice, "Pickers", "Ironhide", "a", "same player"},
{"unknown result", alice, bob, "Pickers", "Ironhide", "x", "unknown result"},
{"empty clan", alice, bob, "", "Ironhide", "a", "bad clan name"},
{"long clan", alice, bob, "Pickers", long, "a", "bad clan name"},
}
for _, c := range cases {
uassert.AbortsWithMessage(t, cur, c.want, func() {
Record(cross(cur), c.challenger, c.acceptor, c.challengerClan, c.acceptorClan, c.result)
}, c.name)
}
}
func TestOwnerCalls(cur realm, t *testing.T) {
resetWriters()
ownedBy(alice)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsWithMessage(t, cur, "ownable: caller is not owner", func() { AddWriter(cross(cur), arenaV1) })
uassert.AbortsWithMessage(t, cur, "ownable: caller is not owner", func() { RemoveWriter(cross(cur), arenaV0) })
uassert.AbortsWithMessage(t, cur, "ownable: caller is not owner", func() { TransferOwnership(cross(cur), bob) })
uassert.Equal(t, alice, Owner())
testing.SetRealm(testing.NewUserRealm(alice))
TransferOwnership(cross(cur), bob)
uassert.Equal(t, bob, Owner())
}
func TestAddWriterRefuses(cur realm, t *testing.T) {
resetWriters()
ownedBy(alice)
testing.SetRealm(testing.NewUserRealm(alice))
tooLong := "gno.land/r/" + strings.Repeat("a", 243) + "/v1"
for _, p := range []string{"gno.land/p/x/v0", "gno.land/r/x", "gno.land/r/x/v", "gno.land/r/x/vA", "gno.land/r/x#y/v1", "gno.land/r/X/v1", tooLong} {
uassert.AbortsWithMessage(t, cur, "bad writer path", func() { AddWriter(cross(cur), p) }, p)
}
uassert.AbortsWithMessage(t, cur, "already a writer", func() { AddWriter(cross(cur), arenaV0) })
uassert.AbortsWithMessage(t, cur, "not a writer", func() { RemoveWriter(cross(cur), arenaV1) })
// The arena holds writer number 1, so 254 more paths fill all 255.
for i := 1; i <= 254; i++ {
AddWriter(cross(cur), "gno.land/r/x/v"+strconv.Itoa(i))
}
uassert.AbortsWithMessage(t, cur, "too many writers", func() { AddWriter(cross(cur), "gno.land/r/x/v255") })
resetWriters()
}
func TestReaddedWriterKeepsItsNumber(cur realm, t *testing.T) {
resetWriters()
ownedBy(alice)
testing.SetRealm(testing.NewUserRealm(alice))
AddWriter(cross(cur), arenaV1)
RemoveWriter(cross(cur), arenaV0)
uassert.Equal(t, arenaV1, strings.Join(Writers(), ","))
AddWriter(cross(cur), arenaV0)
uassert.Equal(t, arenaV0+","+arenaV1, strings.Join(Writers(), ","))
resetWriters()
}