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.

rpsduel.gno

12.48 Kb · 449 lines
  1// Package rpsduel is an asynchronous, two-player rock-paper-scissors duel
  2// with a commit-reveal handshake. The challenger locks in a move as a
  3// sha256 commitment up front so the opponent can't peek at it; the
  4// opponent then replies in the clear (seeing only a hash gives them no
  5// edge); the challenger reveals last to settle the round. A challenger who
  6// tries to dodge a losing reveal can be forfeited by the opponent once the
  7// reveal window expires.
  8package rpsduel
  9
 10import (
 11	"crypto/sha256"
 12	"encoding/hex"
 13	"strconv"
 14	"strings"
 15
 16	"chain"
 17	"chain/runtime"
 18
 19	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
 20	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rps/v0"
 21	"gno.land/p/nt/avl/v0"
 22)
 23
 24// revealWindow is how many blocks the challenger gets to reveal after the
 25// opponent accepts before the opponent can claim a forfeit win.
 26const revealWindow int64 = 50
 27
 28type duelStatus int
 29
 30const (
 31	statusPending duelStatus = iota
 32	statusAwaitingReveal
 33	statusResolved
 34	statusForfeited
 35	statusCancelled
 36)
 37
 38func (s duelStatus) String() string {
 39	switch s {
 40	case statusPending:
 41		return "pending"
 42	case statusAwaitingReveal:
 43		return "awaiting reveal"
 44	case statusResolved:
 45		return "resolved"
 46	case statusForfeited:
 47		return "forfeited"
 48	case statusCancelled:
 49		return "cancelled"
 50	default:
 51		return "?"
 52	}
 53}
 54
 55// duel is one asynchronous round between Challenger and Opponent. The
 56// challenger's move is hidden behind Commit until Reveal; the opponent's
 57// move is stored in the clear once they Accept.
 58type duel struct {
 59	ID             string
 60	Challenger     address
 61	Opponent       address
 62	Commit         string // hex sha256 of "<move>:<salt>"
 63	OpponentMove   rps.Move
 64	Status         duelStatus
 65	Result         string // "challenger" | "opponent" | "draw" once settled
 66	Winner         address
 67	OpenedAt       int64
 68	AcceptedAt     int64
 69	RevealDeadline int64
 70}
 71
 72// playerState is the persisted record for one address.
 73type playerState struct {
 74	Wins     int
 75	Losses   int
 76	Draws    int
 77	Forfeits int // times this player, as challenger, failed to reveal in time
 78	Duels    int
 79}
 80
 81var (
 82	duels   avl.Tree // duel ID -> *duel
 83	players avl.Tree // address string -> *playerState
 84
 85	nextID        int
 86	totalResolved int
 87
 88	champion     address
 89	championWins int
 90)
 91
 92// ComputeCommit hashes a move and salt exactly the way Reveal checks it, so
 93// a caller can compute their commitment (e.g. via a read-only query) before
 94// calling Open, then remember the salt to pass to Reveal later.
 95func ComputeCommit(moveStr, salt string) string {
 96	m, ok := rps.Parse(moveStr)
 97	if !ok {
 98		panic("invalid move: use rock, paper, or scissors (r/p/s)")
 99	}
100	sum := sha256.Sum256([]byte(m.String() + ":" + salt))
101	return hex.EncodeToString(sum[:])
102}
103
104func getOrCreate(addr address) *playerState {
105	key := addr.String()
106	if v := players.Get(key); v != nil {
107		return v.(*playerState)
108	}
109	ps := &playerState{}
110	players.Set(key, ps)
111	return ps
112}
113
114func bumpChampion(addr address, wins int) {
115	if wins > championWins {
116		championWins = wins
117		champion = addr
118	}
119}
120
121// settle scores a revealed round and updates both players' records.
122func settle(d *duel, challengerMove rps.Move, result int) {
123	cs := getOrCreate(d.Challenger)
124	os := getOrCreate(d.Opponent)
125	cs.Duels++
126	os.Duels++
127
128	switch result {
129	case 1:
130		cs.Wins++
131		os.Losses++
132		d.Winner = d.Challenger
133		d.Result = "challenger"
134		bumpChampion(d.Challenger, cs.Wins)
135	case 2:
136		os.Wins++
137		cs.Losses++
138		d.Winner = d.Opponent
139		d.Result = "opponent"
140		bumpChampion(d.Opponent, os.Wins)
141	default:
142		cs.Draws++
143		os.Draws++
144		d.Result = "draw"
145	}
146	d.Status = statusResolved
147	totalResolved++
148}
149
150// Open challenges opponentAddr to a duel, locking in the challenger's move
151// as a commitment (see ComputeCommit) so the opponent can't see it before
152// replying.
153func Open(cur realm, opponentAddr string, commitHex string) string {
154	challenger := cur.Previous().Address()
155
156	opponent := address(strings.TrimSpace(opponentAddr))
157	if !opponent.IsValid() {
158		panic("invalid opponent address")
159	}
160	if opponent == challenger {
161		panic("cannot duel yourself")
162	}
163
164	commit := strings.ToLower(strings.TrimSpace(commitHex))
165	if len(commit) != sha256.Size*2 {
166		panic("commit must be a 64-character hex sha256 digest; build it with ComputeCommit")
167	}
168	if _, err := hex.DecodeString(commit); err != nil {
169		panic("commit must be valid hex")
170	}
171
172	nextID++
173	id := strconv.Itoa(nextID)
174	d := &duel{
175		ID:         id,
176		Challenger: challenger,
177		Opponent:   opponent,
178		Commit:     commit,
179		Status:     statusPending,
180		OpenedAt:   runtime.ChainHeight(),
181	}
182	duels.Set(id, d)
183
184	chain.Emit("DuelOpened",
185		"id", id,
186		"challenger", challenger.String(),
187		"opponent", opponent.String(),
188	)
189
190	return "duel #" + id + " opened against " + opponent.String() + " -- waiting for them to Accept"
191}
192
193// Accept replies to a pending duel with a plain move. Only the challenged
194// opponent may call it; going second behind the challenger's hidden
195// commitment is what keeps this fair.
196func Accept(cur realm, id string, moveStr string) string {
197	caller := cur.Previous().Address()
198
199	v := duels.Get(id)
200	if v == nil {
201		panic("no such duel")
202	}
203	d := v.(*duel)
204
205	if d.Status != statusPending {
206		panic("duel is " + d.Status.String() + ", not pending")
207	}
208	if caller != d.Opponent {
209		panic("only the challenged opponent can accept this duel")
210	}
211
212	m, ok := rps.Parse(moveStr)
213	if !ok {
214		panic("invalid move: use rock, paper, or scissors (r/p/s)")
215	}
216
217	d.OpponentMove = m
218	d.Status = statusAwaitingReveal
219	d.AcceptedAt = runtime.ChainHeight()
220	d.RevealDeadline = d.AcceptedAt + revealWindow
221
222	chain.Emit("DuelAccepted", "id", id, "opponentMove", m.String())
223
224	return "you played " + m.String() + " in duel #" + id +
225		" -- waiting for " + d.Challenger.String() + " to reveal by block " +
226		strconv.Itoa(int(d.RevealDeadline))
227}
228
229// Reveal settles an accepted duel. Only the original challenger may call
230// it, and only with the exact move+salt that produced their commitment.
231func Reveal(cur realm, id string, moveStr string, salt string) string {
232	caller := cur.Previous().Address()
233
234	v := duels.Get(id)
235	if v == nil {
236		panic("no such duel")
237	}
238	d := v.(*duel)
239
240	if d.Status != statusAwaitingReveal {
241		panic("duel is " + d.Status.String() + ", not awaiting reveal")
242	}
243	if caller != d.Challenger {
244		panic("only the challenger can reveal")
245	}
246
247	m, ok := rps.Parse(moveStr)
248	if !ok {
249		panic("invalid move: use rock, paper, or scissors (r/p/s)")
250	}
251	sum := sha256.Sum256([]byte(m.String() + ":" + salt))
252	if hex.EncodeToString(sum[:]) != d.Commit {
253		panic("revealed move+salt doesn't match your original commitment")
254	}
255
256	result := rps.Beats(m, d.OpponentMove)
257	settle(d, m, result)
258
259	chain.Emit("DuelResolved",
260		"id", id,
261		"result", d.Result,
262		"challengerMove", m.String(),
263		"opponentMove", d.OpponentMove.String(),
264	)
265
266	return "you revealed " + m.String() + " vs " + d.OpponentMove.String() + " -- " + outcomeMsg(d)
267}
268
269func outcomeMsg(d *duel) string {
270	switch d.Result {
271	case "challenger":
272		return "you win duel #" + d.ID + "!"
273	case "opponent":
274		return "you lose duel #" + d.ID + " -- " + d.Opponent.String() + " wins."
275	default:
276		return "draw."
277	}
278}
279
280// ClaimForfeit lets the opponent collect a default win when the challenger
281// dodges revealing (e.g. because they saw the opponent's move and knew
282// they'd lose) past the reveal window.
283func ClaimForfeit(cur realm, id string) string {
284	caller := cur.Previous().Address()
285
286	v := duels.Get(id)
287	if v == nil {
288		panic("no such duel")
289	}
290	d := v.(*duel)
291
292	if d.Status != statusAwaitingReveal {
293		panic("duel is " + d.Status.String() + ", not awaiting reveal")
294	}
295	if caller != d.Opponent {
296		panic("only the waiting opponent can claim a forfeit")
297	}
298	if runtime.ChainHeight() <= d.RevealDeadline {
299		panic("reveal window hasn't expired yet")
300	}
301
302	d.Status = statusForfeited
303	d.Winner = d.Opponent
304	d.Result = "opponent"
305
306	cs := getOrCreate(d.Challenger)
307	cs.Duels++
308	cs.Losses++
309	cs.Forfeits++
310	os := getOrCreate(d.Opponent)
311	os.Duels++
312	os.Wins++
313	totalResolved++
314	bumpChampion(d.Opponent, os.Wins)
315
316	chain.Emit("DuelForfeited", "id", id, "winner", d.Opponent.String())
317
318	return "duel #" + id + " forfeited -- " + d.Challenger.String() + " never revealed"
319}
320
321// Cancel withdraws a still-pending duel. Only the challenger may cancel,
322// and only before the opponent accepts.
323func Cancel(cur realm, id string) string {
324	caller := cur.Previous().Address()
325
326	v := duels.Get(id)
327	if v == nil {
328		panic("no such duel")
329	}
330	d := v.(*duel)
331
332	if d.Status != statusPending {
333		panic("duel is " + d.Status.String() + ", not pending")
334	}
335	if caller != d.Challenger {
336		panic("only the challenger can cancel this duel")
337	}
338
339	d.Status = statusCancelled
340	return "duel #" + id + " cancelled"
341}
342
343func renderHome() string {
344	var b strings.Builder
345	b.WriteString("# Rock-Paper-Scissors Duel\n\n")
346	b.WriteString("Challenge another address to rock-paper-scissors, async and " +
347		"fair: you commit your move as a hash, they reply in the open, then you " +
348		"reveal to settle it. Stall on revealing a losing round and your opponent " +
349		"can claim a forfeit win once the window expires.\n\n")
350
351	b.WriteString("- Total duels resolved: " + strconv.Itoa(totalResolved) + "\n")
352	if champion.IsValid() {
353		b.WriteString("- Reigning champion: `" + champion.String() + "` (" +
354			strconv.Itoa(championWins) + " wins)\n")
355	} else {
356		b.WriteString("- No champion yet -- be the first to win a duel.\n")
357	}
358
359	b.WriteString("\n## How to play\n\n")
360	b.WriteString("1. Pick a move and a random salt, e.g. `rock` + `xyz123`.\n")
361	b.WriteString("2. Compute your commitment: `ComputeCommit(\"rock\", \"xyz123\")` (read-only call).\n")
362	b.WriteString("3. `Open(opponentAddr, commit)` -- opens the duel, returns its ID.\n")
363	b.WriteString("4. The opponent calls `Accept(id, \"paper\"|\"scissors\"|\"rock\")`.\n")
364	b.WriteString("5. You call `Reveal(id, \"rock\", \"xyz123\")` -- must match your commitment exactly.\n")
365	b.WriteString("6. If you never reveal, the opponent can call `ClaimForfeit(id)` after " +
366		strconv.Itoa(int(revealWindow)) + " blocks.\n\n")
367	b.WriteString("View a duel at this realm's path plus its ID (e.g. `.../rpsduel:3`), " +
368		"or a player's record plus their address (e.g. `.../rpsduel:g1youraddress...`).\n\n")
369
370	b.WriteString("## Open duels\n\n")
371	open := 0
372	duels.Iterate("", "", func(key string, value interface{}) bool {
373		d := value.(*duel)
374		if d.Status == statusPending {
375			open++
376			b.WriteString("- #" + d.ID + ": `" + d.Challenger.String() +
377				"` waiting on `" + d.Opponent.String() + "` to Accept\n")
378		} else if d.Status == statusAwaitingReveal {
379			open++
380			b.WriteString("- #" + d.ID + ": `" + d.Challenger.String() +
381				"` must Reveal by block " + strconv.Itoa(int(d.RevealDeadline)) + "\n")
382		}
383		return false
384	})
385	if open == 0 {
386		b.WriteString("_none right now_\n")
387	}
388
389	return b.String()
390}
391
392func renderDuel(id string) string {
393	v := duels.Get(id)
394	if v == nil {
395		return "# Duel #" + ui.Inline(id) + "\n\nNo such duel.\n"
396	}
397	d := v.(*duel)
398
399	var b strings.Builder
400	b.WriteString("# Duel #" + d.ID + "\n\n")
401	b.WriteString("- Challenger: `" + d.Challenger.String() + "`\n")
402	b.WriteString("- Opponent: `" + d.Opponent.String() + "`\n")
403	b.WriteString("- Status: " + d.Status.String() + "\n")
404
405	if d.Status == statusAwaitingReveal {
406		b.WriteString("- Opponent played: **" + d.OpponentMove.String() + "**\n")
407		b.WriteString("- Reveal deadline: block " + strconv.Itoa(int(d.RevealDeadline)) + "\n")
408	}
409	if d.Status == statusResolved || d.Status == statusForfeited {
410		b.WriteString("- Result: " + d.Result + "\n")
411		b.WriteString("- Winner: `" + d.Winner.String() + "`\n")
412	}
413	return b.String()
414}
415
416func renderPlayer(rawAddr string) string {
417	addr := strings.TrimSpace(rawAddr)
418	safe := ui.Inline(addr)
419
420	v := players.Get(addr)
421	if v == nil {
422		return "# Player " + safe + "\n\nNo recorded duels yet.\n"
423	}
424	ps := v.(*playerState)
425
426	var b strings.Builder
427	b.WriteString("# Player " + safe + "\n\n")
428	b.WriteString("- Wins: " + strconv.Itoa(ps.Wins) + "\n")
429	b.WriteString("- Losses: " + strconv.Itoa(ps.Losses) + "\n")
430	b.WriteString("- Draws: " + strconv.Itoa(ps.Draws) + "\n")
431	b.WriteString("- Duels played: " + strconv.Itoa(ps.Duels) + "\n")
432	if ps.Forfeits > 0 {
433		b.WriteString("- Forfeited (didn't reveal in time): " + strconv.Itoa(ps.Forfeits) + "\n")
434	}
435	return b.String()
436}
437
438// Render shows the duel lobby at "", a specific duel when path is a
439// numeric ID, or one player's record when path is their bech32 address.
440func Render(path string) string {
441	path = strings.TrimPrefix(strings.TrimSpace(path), "/")
442	if path == "" {
443		return renderHome()
444	}
445	if _, err := strconv.Atoi(path); err == nil {
446		return renderDuel(path)
447	}
448	return renderPlayer(path)
449}