Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rpsduel/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "10000000ugnot"
render_example_test.gno
package rpsduel
// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
print(Render(""))
// Output:
// # Rock-Paper-Scissors Duel
//
// Challenge another address to rock-paper-scissors, async and fair: you commit your move as a hash, they reply in the open, then you reveal to settle it. Stall on revealing a losing round and your opponent can claim a forfeit win once the window expires.
//
// - Total duels resolved: 0
// - No champion yet -- be the first to win a duel.
//
// ## How to play
//
// 1. Pick a move and a random salt, e.g. `rock` + `xyz123`.
// 2. Compute your commitment: `ComputeCommit("rock", "xyz123")` (read-only call).
// 3. `Open(opponentAddr, commit)` -- opens the duel, returns its ID.
// 4. The opponent calls `Accept(id, "paper"|"scissors"|"rock")`.
// 5. You call `Reveal(id, "rock", "xyz123")` -- must match your commitment exactly.
// 6. If you never reveal, the opponent can call `ClaimForfeit(id)` after 50 blocks.
//
// View a duel at this realm's path plus its ID (e.g. `.../rpsduel:3`), or a player's record plus their address (e.g. `.../rpsduel:g1youraddress...`).
//
// ## Open duels
//
// _none right now_
}
rpsduel.gno
// Package rpsduel is an asynchronous, two-player rock-paper-scissors duel
// with a commit-reveal handshake. The challenger locks in a move as a
// sha256 commitment up front so the opponent can't peek at it; the
// opponent then replies in the clear (seeing only a hash gives them no
// edge); the challenger reveals last to settle the round. A challenger who
// tries to dodge a losing reveal can be forfeited by the opponent once the
// reveal window expires.
package rpsduel
import (
"crypto/sha256"
"encoding/hex"
"strconv"
"strings"
"chain"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rps/v0"
"gno.land/p/nt/avl/v0"
)
// revealWindow is how many blocks the challenger gets to reveal after the
// opponent accepts before the opponent can claim a forfeit win.
const revealWindow int64 = 50
type duelStatus int
const (
statusPending duelStatus = iota
statusAwaitingReveal
statusResolved
statusForfeited
statusCancelled
)
func (s duelStatus) String() string {
switch s {
case statusPending:
return "pending"
case statusAwaitingReveal:
return "awaiting reveal"
case statusResolved:
return "resolved"
case statusForfeited:
return "forfeited"
case statusCancelled:
return "cancelled"
default:
return "?"
}
}
// duel is one asynchronous round between Challenger and Opponent. The
// challenger's move is hidden behind Commit until Reveal; the opponent's
// move is stored in the clear once they Accept.
type duel struct {
ID string
Challenger address
Opponent address
Commit string // hex sha256 of "<move>:<salt>"
OpponentMove rps.Move
Status duelStatus
Result string // "challenger" | "opponent" | "draw" once settled
Winner address
OpenedAt int64
AcceptedAt int64
RevealDeadline int64
}
// playerState is the persisted record for one address.
type playerState struct {
Wins int
Losses int
Draws int
Forfeits int // times this player, as challenger, failed to reveal in time
Duels int
}
var (
duels avl.Tree // duel ID -> *duel
players avl.Tree // address string -> *playerState
nextID int
totalResolved int
champion address
championWins int
)
// ComputeCommit hashes a move and salt exactly the way Reveal checks it, so
// a caller can compute their commitment (e.g. via a read-only query) before
// calling Open, then remember the salt to pass to Reveal later.
func ComputeCommit(moveStr, salt string) string {
m, ok := rps.Parse(moveStr)
if !ok {
panic("invalid move: use rock, paper, or scissors (r/p/s)")
}
sum := sha256.Sum256([]byte(m.String() + ":" + salt))
return hex.EncodeToString(sum[:])
}
func getOrCreate(addr address) *playerState {
key := addr.String()
if v := players.Get(key); v != nil {
return v.(*playerState)
}
ps := &playerState{}
players.Set(key, ps)
return ps
}
func bumpChampion(addr address, wins int) {
if wins > championWins {
championWins = wins
champion = addr
}
}
// settle scores a revealed round and updates both players' records.
func settle(d *duel, challengerMove rps.Move, result int) {
cs := getOrCreate(d.Challenger)
os := getOrCreate(d.Opponent)
cs.Duels++
os.Duels++
switch result {
case 1:
cs.Wins++
os.Losses++
d.Winner = d.Challenger
d.Result = "challenger"
bumpChampion(d.Challenger, cs.Wins)
case 2:
os.Wins++
cs.Losses++
d.Winner = d.Opponent
d.Result = "opponent"
bumpChampion(d.Opponent, os.Wins)
default:
cs.Draws++
os.Draws++
d.Result = "draw"
}
d.Status = statusResolved
totalResolved++
}
// Open challenges opponentAddr to a duel, locking in the challenger's move
// as a commitment (see ComputeCommit) so the opponent can't see it before
// replying.
func Open(cur realm, opponentAddr string, commitHex string) string {
challenger := cur.Previous().Address()
opponent := address(strings.TrimSpace(opponentAddr))
if !opponent.IsValid() {
panic("invalid opponent address")
}
if opponent == challenger {
panic("cannot duel yourself")
}
commit := strings.ToLower(strings.TrimSpace(commitHex))
if len(commit) != sha256.Size*2 {
panic("commit must be a 64-character hex sha256 digest; build it with ComputeCommit")
}
if _, err := hex.DecodeString(commit); err != nil {
panic("commit must be valid hex")
}
nextID++
id := strconv.Itoa(nextID)
d := &duel{
ID: id,
Challenger: challenger,
Opponent: opponent,
Commit: commit,
Status: statusPending,
OpenedAt: runtime.ChainHeight(),
}
duels.Set(id, d)
chain.Emit("DuelOpened",
"id", id,
"challenger", challenger.String(),
"opponent", opponent.String(),
)
return "duel #" + id + " opened against " + opponent.String() + " -- waiting for them to Accept"
}
// Accept replies to a pending duel with a plain move. Only the challenged
// opponent may call it; going second behind the challenger's hidden
// commitment is what keeps this fair.
func Accept(cur realm, id string, moveStr string) string {
caller := cur.Previous().Address()
v := duels.Get(id)
if v == nil {
panic("no such duel")
}
d := v.(*duel)
if d.Status != statusPending {
panic("duel is " + d.Status.String() + ", not pending")
}
if caller != d.Opponent {
panic("only the challenged opponent can accept this duel")
}
m, ok := rps.Parse(moveStr)
if !ok {
panic("invalid move: use rock, paper, or scissors (r/p/s)")
}
d.OpponentMove = m
d.Status = statusAwaitingReveal
d.AcceptedAt = runtime.ChainHeight()
d.RevealDeadline = d.AcceptedAt + revealWindow
chain.Emit("DuelAccepted", "id", id, "opponentMove", m.String())
return "you played " + m.String() + " in duel #" + id +
" -- waiting for " + d.Challenger.String() + " to reveal by block " +
strconv.Itoa(int(d.RevealDeadline))
}
// Reveal settles an accepted duel. Only the original challenger may call
// it, and only with the exact move+salt that produced their commitment.
func Reveal(cur realm, id string, moveStr string, salt string) string {
caller := cur.Previous().Address()
v := duels.Get(id)
if v == nil {
panic("no such duel")
}
d := v.(*duel)
if d.Status != statusAwaitingReveal {
panic("duel is " + d.Status.String() + ", not awaiting reveal")
}
if caller != d.Challenger {
panic("only the challenger can reveal")
}
m, ok := rps.Parse(moveStr)
if !ok {
panic("invalid move: use rock, paper, or scissors (r/p/s)")
}
sum := sha256.Sum256([]byte(m.String() + ":" + salt))
if hex.EncodeToString(sum[:]) != d.Commit {
panic("revealed move+salt doesn't match your original commitment")
}
result := rps.Beats(m, d.OpponentMove)
settle(d, m, result)
chain.Emit("DuelResolved",
"id", id,
"result", d.Result,
"challengerMove", m.String(),
"opponentMove", d.OpponentMove.String(),
)
return "you revealed " + m.String() + " vs " + d.OpponentMove.String() + " -- " + outcomeMsg(d)
}
func outcomeMsg(d *duel) string {
switch d.Result {
case "challenger":
return "you win duel #" + d.ID + "!"
case "opponent":
return "you lose duel #" + d.ID + " -- " + d.Opponent.String() + " wins."
default:
return "draw."
}
}
// ClaimForfeit lets the opponent collect a default win when the challenger
// dodges revealing (e.g. because they saw the opponent's move and knew
// they'd lose) past the reveal window.
func ClaimForfeit(cur realm, id string) string {
caller := cur.Previous().Address()
v := duels.Get(id)
if v == nil {
panic("no such duel")
}
d := v.(*duel)
if d.Status != statusAwaitingReveal {
panic("duel is " + d.Status.String() + ", not awaiting reveal")
}
if caller != d.Opponent {
panic("only the waiting opponent can claim a forfeit")
}
if runtime.ChainHeight() <= d.RevealDeadline {
panic("reveal window hasn't expired yet")
}
d.Status = statusForfeited
d.Winner = d.Opponent
d.Result = "opponent"
cs := getOrCreate(d.Challenger)
cs.Duels++
cs.Losses++
cs.Forfeits++
os := getOrCreate(d.Opponent)
os.Duels++
os.Wins++
totalResolved++
bumpChampion(d.Opponent, os.Wins)
chain.Emit("DuelForfeited", "id", id, "winner", d.Opponent.String())
return "duel #" + id + " forfeited -- " + d.Challenger.String() + " never revealed"
}
// Cancel withdraws a still-pending duel. Only the challenger may cancel,
// and only before the opponent accepts.
func Cancel(cur realm, id string) string {
caller := cur.Previous().Address()
v := duels.Get(id)
if v == nil {
panic("no such duel")
}
d := v.(*duel)
if d.Status != statusPending {
panic("duel is " + d.Status.String() + ", not pending")
}
if caller != d.Challenger {
panic("only the challenger can cancel this duel")
}
d.Status = statusCancelled
return "duel #" + id + " cancelled"
}
func renderHome() string {
var b strings.Builder
b.WriteString("# Rock-Paper-Scissors Duel\n\n")
b.WriteString("Challenge another address to rock-paper-scissors, async and " +
"fair: you commit your move as a hash, they reply in the open, then you " +
"reveal to settle it. Stall on revealing a losing round and your opponent " +
"can claim a forfeit win once the window expires.\n\n")
b.WriteString("- Total duels resolved: " + strconv.Itoa(totalResolved) + "\n")
if champion.IsValid() {
b.WriteString("- Reigning champion: `" + champion.String() + "` (" +
strconv.Itoa(championWins) + " wins)\n")
} else {
b.WriteString("- No champion yet -- be the first to win a duel.\n")
}
b.WriteString("\n## How to play\n\n")
b.WriteString("1. Pick a move and a random salt, e.g. `rock` + `xyz123`.\n")
b.WriteString("2. Compute your commitment: `ComputeCommit(\"rock\", \"xyz123\")` (read-only call).\n")
b.WriteString("3. `Open(opponentAddr, commit)` -- opens the duel, returns its ID.\n")
b.WriteString("4. The opponent calls `Accept(id, \"paper\"|\"scissors\"|\"rock\")`.\n")
b.WriteString("5. You call `Reveal(id, \"rock\", \"xyz123\")` -- must match your commitment exactly.\n")
b.WriteString("6. If you never reveal, the opponent can call `ClaimForfeit(id)` after " +
strconv.Itoa(int(revealWindow)) + " blocks.\n\n")
b.WriteString("View a duel at this realm's path plus its ID (e.g. `.../rpsduel:3`), " +
"or a player's record plus their address (e.g. `.../rpsduel:g1youraddress...`).\n\n")
b.WriteString("## Open duels\n\n")
open := 0
duels.Iterate("", "", func(key string, value interface{}) bool {
d := value.(*duel)
if d.Status == statusPending {
open++
b.WriteString("- #" + d.ID + ": `" + d.Challenger.String() +
"` waiting on `" + d.Opponent.String() + "` to Accept\n")
} else if d.Status == statusAwaitingReveal {
open++
b.WriteString("- #" + d.ID + ": `" + d.Challenger.String() +
"` must Reveal by block " + strconv.Itoa(int(d.RevealDeadline)) + "\n")
}
return false
})
if open == 0 {
b.WriteString("_none right now_\n")
}
return b.String()
}
func renderDuel(id string) string {
v := duels.Get(id)
if v == nil {
return "# Duel #" + ui.Inline(id) + "\n\nNo such duel.\n"
}
d := v.(*duel)
var b strings.Builder
b.WriteString("# Duel #" + d.ID + "\n\n")
b.WriteString("- Challenger: `" + d.Challenger.String() + "`\n")
b.WriteString("- Opponent: `" + d.Opponent.String() + "`\n")
b.WriteString("- Status: " + d.Status.String() + "\n")
if d.Status == statusAwaitingReveal {
b.WriteString("- Opponent played: **" + d.OpponentMove.String() + "**\n")
b.WriteString("- Reveal deadline: block " + strconv.Itoa(int(d.RevealDeadline)) + "\n")
}
if d.Status == statusResolved || d.Status == statusForfeited {
b.WriteString("- Result: " + d.Result + "\n")
b.WriteString("- Winner: `" + d.Winner.String() + "`\n")
}
return b.String()
}
func renderPlayer(rawAddr string) string {
addr := strings.TrimSpace(rawAddr)
safe := ui.Inline(addr)
v := players.Get(addr)
if v == nil {
return "# Player " + safe + "\n\nNo recorded duels yet.\n"
}
ps := v.(*playerState)
var b strings.Builder
b.WriteString("# Player " + safe + "\n\n")
b.WriteString("- Wins: " + strconv.Itoa(ps.Wins) + "\n")
b.WriteString("- Losses: " + strconv.Itoa(ps.Losses) + "\n")
b.WriteString("- Draws: " + strconv.Itoa(ps.Draws) + "\n")
b.WriteString("- Duels played: " + strconv.Itoa(ps.Duels) + "\n")
if ps.Forfeits > 0 {
b.WriteString("- Forfeited (didn't reveal in time): " + strconv.Itoa(ps.Forfeits) + "\n")
}
return b.String()
}
// Render shows the duel lobby at "", a specific duel when path is a
// numeric ID, or one player's record when path is their bech32 address.
func Render(path string) string {
path = strings.TrimPrefix(strings.TrimSpace(path), "/")
if path == "" {
return renderHome()
}
if _, err := strconv.Atoi(path); err == nil {
return renderDuel(path)
}
return renderPlayer(path)
}
rpsduel_test.gno
package rpsduel
import (
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
)
func resetState() {
duels = avl.Tree{}
players = avl.Tree{}
nextID = 0
totalResolved = 0
var zero address
champion = zero
championWins = 0
}
func TestComputeCommitDeterministicAndSalted(t *testing.T) {
a := ComputeCommit("rock", "salt1")
b := ComputeCommit("rock", "salt1")
if a != b {
t.Fatal("ComputeCommit should be deterministic for the same move+salt")
}
if a == ComputeCommit("rock", "salt2") {
t.Fatal("different salts should produce different commits")
}
if a == ComputeCommit("paper", "salt1") {
t.Fatal("different moves should produce different commits")
}
if len(a) != 64 {
t.Fatalf("commit length = %d, want 64 (hex sha256)", len(a))
}
}
// Crossing: Open/Accept/Reveal mutate realm state, so the test needs `cur realm`.
func TestFullDuelChallengerWins(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
commit := ComputeCommit("paper", "s3cr3t")
testing.SetRealm(testing.NewUserRealm(alice))
Open(cross(cur), bob.String(), commit)
v := duels.Get("1")
if v == nil {
t.Fatal("expected duel #1 to exist")
}
d := v.(*duel)
if d.Status != statusPending {
t.Fatalf("Status = %v, want pending", d.Status)
}
testing.SetRealm(testing.NewUserRealm(bob))
Accept(cross(cur), "1", "rock")
if d.Status != statusAwaitingReveal {
t.Fatalf("Status = %v, want awaiting reveal", d.Status)
}
testing.SetRealm(testing.NewUserRealm(alice))
Reveal(cross(cur), "1", "paper", "s3cr3t")
if d.Status != statusResolved {
t.Fatalf("Status = %v, want resolved", d.Status)
}
if d.Result != "challenger" {
t.Fatalf("Result = %q, want challenger (paper beats rock)", d.Result)
}
if d.Winner != alice {
t.Fatal("expected alice to win")
}
if totalResolved != 1 {
t.Fatalf("totalResolved = %d, want 1", totalResolved)
}
aliceStats := getOrCreate(alice)
if aliceStats.Wins != 1 {
t.Fatalf("alice.Wins = %d, want 1", aliceStats.Wins)
}
bobStats := getOrCreate(bob)
if bobStats.Losses != 1 {
t.Fatalf("bob.Losses = %d, want 1", bobStats.Losses)
}
if !champion.IsValid() || champion != alice {
t.Fatal("champion should be alice")
}
}
func TestRevealMismatchPanics(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
testing.SetRealm(testing.NewUserRealm(alice))
Open(cross(cur), bob.String(), ComputeCommit("rock", "s3cr3t"))
testing.SetRealm(testing.NewUserRealm(bob))
Accept(cross(cur), "1", "scissors")
testing.SetRealm(testing.NewUserRealm(alice))
rec := revive(func() { Reveal(cross(cur), "1", "paper", "s3cr3t") })
if rec == nil {
t.Fatal("expected panic when revealed move doesn't match the commitment")
}
}
func TestOnlyOpponentCanAccept(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
mallory := testutils.TestAddress("mallory")
testing.SetRealm(testing.NewUserRealm(alice))
Open(cross(cur), bob.String(), ComputeCommit("rock", "s3cr3t"))
testing.SetRealm(testing.NewUserRealm(mallory))
rec := revive(func() { Accept(cross(cur), "1", "paper") })
if rec == nil {
t.Fatal("expected panic when a non-opponent accepts")
}
}
func TestClaimForfeitBeforeDeadlinePanics(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
testing.SetRealm(testing.NewUserRealm(alice))
Open(cross(cur), bob.String(), ComputeCommit("rock", "s3cr3t"))
testing.SetRealm(testing.NewUserRealm(bob))
Accept(cross(cur), "1", "paper")
rec := revive(func() { ClaimForfeit(cross(cur), "1") })
if rec == nil {
t.Fatal("expected panic when claiming a forfeit before the reveal window expires")
}
}
func TestClaimForfeitAfterDeadline(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
testing.SetRealm(testing.NewUserRealm(alice))
Open(cross(cur), bob.String(), ComputeCommit("rock", "s3cr3t"))
testing.SetRealm(testing.NewUserRealm(bob))
Accept(cross(cur), "1", "paper")
testing.SkipHeights(revealWindow + 1)
ClaimForfeit(cross(cur), "1")
v := duels.Get("1")
d := v.(*duel)
if d.Status != statusForfeited {
t.Fatalf("Status = %v, want forfeited", d.Status)
}
if d.Winner != bob {
t.Fatal("expected bob to win by forfeit")
}
aliceStats := getOrCreate(alice)
if aliceStats.Forfeits != 1 {
t.Fatalf("alice.Forfeits = %d, want 1", aliceStats.Forfeits)
}
}
func TestCancel(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
bob := testutils.TestAddress("bob")
testing.SetRealm(testing.NewUserRealm(alice))
Open(cross(cur), bob.String(), ComputeCommit("rock", "s3cr3t"))
Cancel(cross(cur), "1")
v := duels.Get("1")
d := v.(*duel)
if d.Status != statusCancelled {
t.Fatalf("Status = %v, want cancelled", d.Status)
}
}
func TestOpenSelfRejected(cur realm, t *testing.T) {
resetState()
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
rec := revive(func() { Open(cross(cur), alice.String(), ComputeCommit("rock", "s3cr3t")) })
if rec == nil {
t.Fatal("expected panic when challenging yourself")
}
}
// Non-crossing: Render is a plain read.
func TestRenderHome(t *testing.T) {
resetState()
out := Render("")
if out == "" {
t.Fatal(`Render("") should not be empty`)
}
}