Playground
dice.gno
// Package dice implements a provably-fair on-chain dice game for gno.land.
//
// There is no true randomness on-chain: every node must reach the same result
// deterministically. Instead, each roll derives its 1-6 face from public block
// entropy (chain height) mixed with the caller address and the caller's roll
// count. The derivation is fully reproducible from public data, which is what
// "provably fair" means here — anyone can recompute a roll and verify it.
package dice
import (
"chain"
"chain/runtime"
"strconv"
"strings"
"gno.land/p/nt/avl/v0"
)
// history holds every roll made by a single caller, most recent last.
type history struct {
rolls []int // each value in [1,6]
}
var (
// count[i] is the total number of times face (i+1) has come up globally.
count [6]int
// total is the total number of rolls across all callers.
total int
// players maps caller address string -> *history (deterministic iteration).
players = avl.NewTree()
)
// deriveFace turns public entropy into a face in [1,6]. It is deterministic:
// the same (height, addr, n) always yields the same face, so any observer can
// recompute and verify a roll. Uses a simple FNV-1a-style hash over the mixed
// entropy bytes so different callers at the same height get different faces.
func deriveFace(height int64, addr string, n int) int {
const (
offset = uint64(1469598103934665603)
prime = uint64(1099511628211)
)
h := offset
mix := func(v uint64) {
for i := 0; i < 8; i++ {
h ^= v & 0xff
h *= prime
v >>= 8
}
}
mix(uint64(height))
mix(uint64(n))
for i := 0; i < len(addr); i++ {
h ^= uint64(addr[i])
h *= prime
}
return int(h%6) + 1
}
// Roll performs one dice roll for the calling account and records it.
//
// It is a crossing function (gno 0.9 interrealm convention: `cur realm` first
// parameter). Callers invoke it as Roll(cross(cur)). The result is derived
// deterministically from the current block height, the caller address, and the
// caller's prior roll count — no stored secret, fully verifiable.
func Roll(cur realm) int {
if !cur.IsCurrent() {
panic("dice: spoofed realm value")
}
addr := cur.Previous().Address().String()
var h *history
if v := players.Get(addr); v != nil {
h = v.(*history)
} else {
h = &history{}
players.Set(addr, h)
}
face := deriveFace(runtime.ChainHeight(), addr, len(h.rolls))
h.rolls = append(h.rolls, face)
count[face-1]++
total++
chain.Emit("Roll", "player", addr, "face", strconv.Itoa(face))
return face
}
// RollsOf returns the recorded roll history for an address (oldest first).
// Read-only helper, safe to call as a query.
func RollsOf(addr string) []int {
v := players.Get(addr)
if v == nil {
return nil
}
out := v.(*history).rolls
cp := make([]int, len(out))
copy(cp, out)
return cp
}
// Total returns the global roll count.
func Total() int { return total }
// Distribution returns the global per-face counts, faces 1-6.
func Distribution() [6]int { return count }
// bar renders a proportional ▓/░ bar of fixed width for a face's share.
func bar(n, max, width int) string {
if max <= 0 {
return strings.Repeat("░", width)
}
filled := n * width / max
if filled > width {
filled = width
}
return strings.Repeat("▓", filled) + strings.Repeat("░", width-filled)
}
// Render returns the realm's gnoweb Markdown view.
//
// Render is NOT a crossing function (no `cur realm` param) — it is a read-only
// query surface. It shows the total roll count, a distribution bar chart for
// faces 1-6, and the most recent rolls.
func Render(path string) string {
var b strings.Builder
b.WriteString("# 🎲 Provably-Fair Dice\n\n")
b.WriteString("Every roll is derived deterministically from the block height, ")
b.WriteString("the caller address, and their roll count — no hidden randomness, ")
b.WriteString("fully reproducible from public data.\n\n")
b.WriteString("**Total rolls:** " + strconv.Itoa(total) + "\n\n")
// Distribution bar chart.
b.WriteString("## Distribution\n\n")
max := 0
for _, c := range count {
if c > max {
max = c
}
}
for face := 1; face <= 6; face++ {
c := count[face-1]
pct := 0
if total > 0 {
pct = c * 100 / total
}
b.WriteString("`" + strconv.Itoa(face) + "` ")
b.WriteString(bar(c, max, 20))
b.WriteString(" " + strconv.Itoa(c))
b.WriteString(" (" + strconv.Itoa(pct) + "%)\n\n")
}
// Recent rolls: walk players, collect last rolls, show most recent globally.
b.WriteString("## Recent rolls\n\n")
if total == 0 {
b.WriteString("_No rolls yet. Call `Roll` to play._\n")
return b.String()
}
type entry struct {
addr string
face int
}
recent := []entry{}
players.Iterate("", "", func(key string, value interface{}) bool {
h := value.(*history)
// take up to the last 3 rolls of each player
start := len(h.rolls) - 3
if start < 0 {
start = 0
}
for _, f := range h.rolls[start:] {
recent = append(recent, entry{addr: key, face: f})
}
return false
})
// show at most the last 10 collected
start := len(recent) - 10
if start < 0 {
start = 0
}
for _, e := range recent[start:] {
short := e.addr
if len(short) > 12 {
short = short[:8] + "…" + short[len(short)-4:]
}
b.WriteString("- 🎲 **" + strconv.Itoa(e.face) + "** — `" + short + "`\n")
}
return b.String()
}
dice_test.gno
package dice
import (
"strings"
"testing"
"gno.land/p/nt/avl/v0"
)
// resetState clears package globals between tests since realm state is global.
func resetState() {
count = [6]int{}
total = 0
players = avl.NewTree()
}
func TestDeriveFaceRange(t *testing.T) {
// Every derived face must land in [1,6] regardless of entropy inputs.
cases := []struct {
height int64
addr string
n int
}{
{0, "g1abc", 0},
{1, "g1abc", 1},
{999999, "g1xyzxyzxyz", 42},
{-1, "", 0},
{123456789, "g1deadbeef", 7},
}
for _, c := range cases {
f := deriveFace(c.height, c.addr, c.n)
if f < 1 || f > 6 {
t.Errorf("deriveFace(%d,%q,%d) = %d, want 1..6", c.height, c.addr, c.n, f)
}
}
}
func TestDeriveFaceDeterministic(t *testing.T) {
// Same inputs -> same output (provably fair / reproducible).
a := deriveFace(100, "g1caller", 3)
b := deriveFace(100, "g1caller", 3)
if a != b {
t.Errorf("deriveFace not deterministic: %d != %d", a, b)
}
// Different roll count generally changes entropy; at least it must not panic
// and must stay in range.
c := deriveFace(100, "g1caller", 4)
if c < 1 || c > 6 {
t.Errorf("deriveFace out of range: %d", c)
}
}
func TestDeriveFaceVariesByCaller(t *testing.T) {
// Two different addresses at the same height should not be forced equal;
// verify the hash actually mixes the address by finding at least one
// differing pair across a small sweep.
diff := false
for i := 0; i < 10; i++ {
if deriveFace(50, "g1alice", i) != deriveFace(50, "g1bob", i) {
diff = true
break
}
}
if !diff {
t.Error("deriveFace never differs between two distinct callers over 10 rolls")
}
}
func TestRenderEmpty(t *testing.T) {
resetState()
out := Render("")
if !strings.Contains(out, "Provably-Fair Dice") {
t.Error("Render missing title")
}
if !strings.Contains(out, "Total rolls:** 0") {
t.Errorf("Render should report 0 total rolls, got:\n%s", out)
}
if !strings.Contains(out, "No rolls yet") {
t.Error("Render should show empty-state message")
}
}
func TestDistributionAccounting(t *testing.T) {
resetState()
// Simulate the state mutations Roll performs, without a realm frame.
faces := []int{1, 1, 3, 6, 6, 6}
for _, f := range faces {
count[f-1]++
total++
}
if total != len(faces) {
t.Errorf("total = %d, want %d", total, len(faces))
}
d := Distribution()
if d[0] != 2 {
t.Errorf("face 1 count = %d, want 2", d[0])
}
if d[5] != 3 {
t.Errorf("face 6 count = %d, want 3", d[5])
}
if d[1] != 0 {
t.Errorf("face 2 count = %d, want 0", d[1])
}
out := Render("")
if !strings.Contains(out, "Total rolls:** 6") {
t.Errorf("Render should report 6 total rolls, got:\n%s", out)
}
}
func TestBar(t *testing.T) {
full := bar(10, 10, 10)
if strings.Count(full, "▓") != 10 {
t.Errorf("full bar want 10 filled, got %q", full)
}
empty := bar(0, 10, 10)
if strings.Count(empty, "░") != 10 {
t.Errorf("empty bar want 10 unfilled, got %q", empty)
}
half := bar(5, 10, 10)
if strings.Count(half, "▓") != 5 {
t.Errorf("half bar want 5 filled, got %q", half)
}
}
gnomod.toml
module = "gno.land/r/nym-moultest123/x/daily/dice/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186407 max_deposit = "5000000ugnot"