Playground
challenge.gno
package poker
import (
"bytes"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/cards"
)
// Challenge disputes one element of a shuffle or rekey pass during the
// challenge window (protocol.md section 5).
func Challenge(cur realm, tableID, handNo uint64, accused int, kind string, index int, inB64, inProofHex, outB64, outProofHex string) {
if !challengesEnabled {
panic("challenges are disabled on this deployment")
}
ctx := newCtx(cur)
sent := sentUgnot(cur)
t, h, c := handFor(cur, tableID, handNo)
if h.Phase != phChallenge {
panic("not in challenge window")
}
if ctx.height > h.Deadline {
panic("challenge window has passed")
}
n := h.n()
if accused < 0 || accused >= n {
panic("invalid accused index")
}
if accused == c {
panic("cannot challenge yourself")
}
if index < 0 || index >= cards.DeckSize {
panic("invalid deck index")
}
bond := t.ChallengeBond
challengerSeat := t.Seats[h.Players[c].Seat]
if sent > 0 {
if sent != bond {
panic("attached ugnot must equal the challenge bond")
}
} else if challengerSeat.Stack < bond {
panic("stack too small for the challenge bond")
}
in, err := cards.DecodeElement(inB64)
if err != nil {
panic("in: " + err.Error())
}
out, err := cards.DecodeElement(outB64)
if err != nil {
panic("out: " + err.Error())
}
inProof, err := cards.DecodeHex(inProofHex, cards.ProofLen)
if err != nil {
panic("in proof: " + err.Error())
}
outProof, err := cards.DecodeHex(outProofHex, cards.ProofLen)
if err != nil {
panic("out proof: " + err.Error())
}
seed := seedBytes(h.Players[accused])
var inRoot, outRoot []byte
inPos := index
switch kind {
case "shuffle":
if accused == 0 {
inRoot = cards.CanonRoot()
} else {
inRoot = rootAt(h, accused-1)
}
outRoot = rootAt(h, accused)
inPos = cards.Permutation(seed)[index]
case "rekey":
inRoot = rootAt(h, n+accused-1)
outRoot = rootAt(h, n+accused)
default:
panic("kind must be shuffle or rekey")
}
if !cards.VerifyProof(inRoot, in, inPos, inProof) {
panic("invalid input proof")
}
if !cards.VerifyProof(outRoot, out, index, outProof) {
panic("invalid output proof")
}
e := cards.ShuffleKey(seed)
var guilty bool
if kind == "shuffle" {
guilty = !bytes.Equal(powModP(in, e), out)
} else {
k := cards.CardKey(seed, index)
guilty = !bytes.Equal(powModP(out, e), powModP(in, k))
}
rec := ChallengeRecord{Challenger: c, Accused: accused, Kind: kind, Index: index, Guilty: guilty}
h.Result.Challenges = append(h.Result.Challenges, rec)
accusedSeat := t.Seats[h.Players[accused].Seat]
if guilty {
if sent > 0 {
ctx.pay(ctx.caller, sent)
}
t.abort(ctx, []int{accused}, true)
return
}
if sent == 0 {
challengerSeat.Stack -= bond
}
accusedSeat.Stack += bond
}
func rootAt(h *Hand, pass int) []byte {
b, err := cards.DecodeHex(h.Roots[pass], 32)
if err != nil {
panic("corrupt root")
}
return b
}
gnomod.toml
module = "gno.land/r/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker" gno = "0.9" [addpkg] creator = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm" height = 1091193 max_deposit = "50000000ugnot"
hand.gno
package poker
import (
"strconv"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/cards"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/holdem"
)
// Hand phases.
const (
phShuffle = iota
phRekey
phDealHole
phPreflop
phDealFlop
phFlop
phDealTurn
phTurn
phDealRiver
phRiver
phReveal
phChallenge
phDone
)
var phaseNames = []string{
"shuffle", "rekey", "deal_hole", "preflop", "deal_flop", "flop",
"deal_turn", "turn", "deal_river", "river", "reveal", "challenge", "done",
}
// HandPlayer is a seat's participation in one hand.
type HandPlayer struct {
Seat int
Owner address
Commit string // hex
Seed string // hex, after reveal
Keys map[int]string // position -> hex card key
Revealed bool
Accepted bool
}
// ChallengeRecord is one resolved challenge.
type ChallengeRecord struct {
Challenger int
Accused int
Kind string
Index int
Guilty bool
}
// Result is the outcome of a hand. Credits are what settlement adds to each
// hand player's stack (winnings, or refund plus penalty share on abort).
type Result struct {
Aborted bool
Convicted []int
Stallers []int
Credits []int64
Scores []int
Challenges []ChallengeRecord
}
// Hand is the state of the current or last hand of a table.
type Hand struct {
No uint64
Phase int
Players []*HandPlayer
Bet *holdem.Betting
Roots []string // hex root per accepted deck pass
Owing []bool // per player, for deal steps
Deadline int64
Cards []int // official card per position, after reveal
Result *Result
Settled bool // contributions have been paid out or refunded
}
// maxSeats is the largest table; per-player buffers are sized by it.
const maxSeats = holdem.MaxPlayers
// n is the number of players in the hand, at most maxSeats.
func (h *Hand) n() int { return len(h.Players) }
func (h *Hand) playerIndex(seat int) int {
for j, p := range h.Players {
if p.Seat == seat {
return j
}
}
return -1
}
func isBettingPhase(ph int) bool {
return ph == phPreflop || ph == phFlop || ph == phTurn || ph == phRiver
}
func isDealPhase(ph int) bool {
return ph == phDealHole || ph == phDealFlop || ph == phDealTurn || ph == phDealRiver
}
// turnIndex is the player expected to act in an in-turn phase, else -1.
func (h *Hand) turnIndex() int {
switch {
case h.Phase == phShuffle:
return len(h.Roots)
case h.Phase == phRekey:
return len(h.Roots) - h.n()
case isBettingPhase(h.Phase):
return h.Bet.Turn
}
return -1
}
// owedPositions lists the positions player j must share keys for in the
// current deal step, ascending.
func (h *Hand) owedPositions(j int) []int {
n := h.n()
out := []int{}
switch h.Phase {
case phDealHole:
for i := 0; i < 2*n; i++ {
if i/2 != j {
out = append(out, i)
}
}
case phDealFlop:
out = append(out, 2*n, 2*n+1, 2*n+2)
case phDealTurn:
out = append(out, 2*n+3)
case phDealRiver:
out = append(out, 2*n+4)
}
return out
}
func (t *Table) eligible(i int) bool {
s := t.Seats[i]
return s != nil && !s.SittingOut && !s.Leaving && s.Stack >= t.BigBlind
}
// StartHand moves the button, posts blinds and opens the shuffle.
func StartHand(cur realm, tableID uint64) {
assertNoSend(cur)
ctx := newCtx(cur)
t := getTable(tableID)
t.authSeat(ctx.caller)
if t.Hand != nil && t.Hand.Phase != phDone {
panic("a hand is in progress")
}
m := t.MaxPlayers
seats := []int{}
for k := 1; k <= m; k++ {
i := (t.Button + k + m) % m
if t.eligible(i) {
seats = append(seats, i)
}
}
if len(seats) < 2 {
panic("need at least 2 active players with a stack of at least the big blind")
}
// seats starts with the new button.
button := seats[0]
order := []int{}
if len(seats) == 2 {
order = append(order, seats[0], seats[1])
} else {
order = append(order, seats[1:]...)
order = append(order, button)
}
t.Button = button
t.HandNo++
for _, s := range t.Seats {
if s != nil {
s.Waiting = false
}
}
if len(order) > maxSeats {
panic("too many players")
}
var stackBuf [maxSeats]int64
stacks := stackBuf[:len(order):len(order)]
players := make([]*HandPlayer, len(order))
for j, si := range order {
stacks[j] = t.Seats[si].Stack
players[j] = &HandPlayer{Seat: si, Owner: t.Seats[si].Owner, Keys: map[int]string{}}
}
h := &Hand{
No: t.HandNo,
Phase: phShuffle,
Players: players,
Bet: holdem.NewBetting(stacks, t.SmallBlind, t.BigBlind),
Deadline: ctx.height + t.ActionTimeout,
}
t.Hand = h
t.syncStacks()
}
func (t *Table) syncStacks() {
for j, p := range t.Hand.Players {
t.Seats[p.Seat].Stack = t.Hand.Bet.Players[j].Stack
}
}
// handFor validates the table, hand number and caller, and returns the hand
// and the caller's hand index.
func handFor(cur realm, tableID, handNo uint64) (*Table, *Hand, int) {
t := getTable(tableID)
h := t.Hand
if h == nil || h.No != handNo || handNo != t.HandNo {
panic("stale or unknown hand number")
}
if h.Phase == phDone {
panic("hand is over")
}
seat := t.authSeat(cur.Previous().Address())
j := h.playerIndex(seat)
if j < 0 {
panic("caller is not in this hand")
}
return t, h, j
}
// SubmitShuffle records the caller's commitment and shuffled deck.
func SubmitShuffle(cur realm, tableID, handNo uint64, commitHex, deckB64 string) {
assertNoSend(cur)
ctx := newCtx(cur)
t, h, j := handFor(cur, tableID, handNo)
if h.Phase != phShuffle {
panic("not in shuffle phase")
}
if j != h.turnIndex() {
panic("not this player's turn to shuffle")
}
if _, err := cards.DecodeHex(commitHex, 32); err != nil {
panic("commit: " + err.Error())
}
t.acceptDeck(h, deckB64)
h.Players[j].Commit = commitHex
h.Deadline = ctx.height + t.ActionTimeout
if len(h.Roots) == h.n() {
h.Phase = phRekey
}
}
// SubmitRekey records the caller's re-keyed deck.
func SubmitRekey(cur realm, tableID, handNo uint64, deckB64 string) {
assertNoSend(cur)
ctx := newCtx(cur)
t, h, j := handFor(cur, tableID, handNo)
if h.Phase != phRekey {
panic("not in rekey phase")
}
if j != h.turnIndex() {
panic("not this player's turn to rekey")
}
t.acceptDeck(h, deckB64)
h.Deadline = ctx.height + t.ActionTimeout
if len(h.Roots) == 2*h.n() {
h.startDeal(ctx, t, phDealHole)
}
}
func (t *Table) acceptDeck(h *Hand, deckB64 string) {
deck, root, err := cards.ParseDeck(deckB64)
if err != nil {
panic("deck: " + err.Error())
}
h.Roots = append(h.Roots, cards.EncodeHex(root))
t.Deck = string(deck)
t.DeckHand = h.No
}
func (h *Hand) startDeal(ctx *txCtx, t *Table, phase int) {
h.Phase = phase
var owing [maxSeats]bool
h.Owing = owing[:h.n():h.n()]
for j := range h.Owing {
h.Owing[j] = true
}
h.Deadline = ctx.height + t.ActionTimeout
}
// ShareKeys publishes the caller's card keys for the current deal step.
func ShareKeys(cur realm, tableID, handNo uint64, keysHex string) {
assertNoSend(cur)
ctx := newCtx(cur)
t, h, j := handFor(cur, tableID, handNo)
if !isDealPhase(h.Phase) {
panic("not in a deal phase")
}
if !h.Owing[j] {
panic("keys already shared")
}
pos := h.owedPositions(j)
if len(keysHex) != 64*len(pos) {
panic("expected " + strconv.Itoa(len(pos)) + " keys")
}
if _, err := cards.DecodeHex(keysHex, 32*len(pos)); err != nil {
panic("keys: " + err.Error())
}
p := h.Players[j]
for k, i := range pos {
p.Keys[i] = keysHex[64*k : 64*(k+1)]
}
h.Owing[j] = false
for _, o := range h.Owing {
if o {
return
}
}
h.Owing = nil
switch h.Phase {
case phDealHole:
h.Phase = phPreflop
case phDealFlop:
h.Bet.NextStreet()
h.Phase = phFlop
case phDealTurn:
h.Bet.NextStreet()
h.Phase = phTurn
case phDealRiver:
h.Bet.NextStreet()
h.Phase = phRiver
}
h.Deadline = ctx.height + t.ActionTimeout
t.afterBetting(ctx)
}
// Act applies a betting action by the player to act.
func Act(cur realm, tableID, handNo uint64, action string, amount int64) {
assertNoSend(cur)
ctx := newCtx(cur)
t, h, j := handFor(cur, tableID, handNo)
if !isBettingPhase(h.Phase) {
panic("not in a betting phase")
}
t.applyAction(ctx, j, action, amount)
}
func (t *Table) applyAction(ctx *txCtx, j int, action string, amount int64) {
h := t.Hand
if err := h.Bet.Act(j, action, amount); err != nil {
panic(err.Error())
}
t.syncStacks()
h.Deadline = ctx.height + t.ActionTimeout
t.afterBetting(ctx)
}
// afterBetting moves on once the street needs no more action.
func (t *Table) afterBetting(ctx *txCtx) {
h := t.Hand
if !isBettingPhase(h.Phase) || !h.Bet.StreetComplete() {
return
}
if h.Bet.Closed() || h.Phase == phRiver {
h.Phase = phReveal
h.Deadline = ctx.height + t.ActionTimeout
return
}
switch h.Phase {
case phPreflop:
h.startDeal(ctx, t, phDealFlop)
case phFlop:
h.startDeal(ctx, t, phDealTurn)
case phTurn:
h.startDeal(ctx, t, phDealRiver)
}
}
// RevealSeed opens the caller's seed; published card keys are checked at once.
func RevealSeed(cur realm, tableID, handNo uint64, seedHex string) {
assertNoSend(cur)
ctx := newCtx(cur)
t, h, j := handFor(cur, tableID, handNo)
if h.Phase != phReveal {
panic("not in reveal phase")
}
p := h.Players[j]
if p.Revealed {
panic("seed already revealed")
}
seed, err := cards.DecodeHex(seedHex, 32)
if err != nil {
panic("seed: " + err.Error())
}
if cards.EncodeHex(cards.Commit(seed)) != p.Commit {
panic("seed does not match commitment")
}
p.Seed = seedHex
p.Revealed = true
for pos, key := range p.Keys {
if cards.EncodeHex(cards.CardKey(seed, pos)) != key {
t.abort(ctx, []int{j}, true)
return
}
}
for _, q := range h.Players {
if !q.Revealed {
return
}
}
t.showdown(ctx)
}
func seedBytes(p *HandPlayer) []byte {
b, err := cards.DecodeHex(p.Seed, 32)
if err != nil {
panic("seed missing")
}
return b
}
// showdown derives all cards from the seeds and computes the payouts.
func (t *Table) showdown(ctx *txCtx) {
h := t.Hand
n := h.n()
perms := make([][]int, n)
for j, p := range h.Players {
perms[j] = cards.Permutation(seedBytes(p))
}
h.Cards = cards.OfficialCards(perms)
board := h.Cards[2*n : 2*n+5]
var contribBuf [maxSeats]int64
var foldedBuf [maxSeats]bool
var scoreBuf [maxSeats]int
contrib, folded, scores := contribBuf[:n:n], foldedBuf[:n:n], scoreBuf[:n:n]
for j, bp := range h.Bet.Players {
contrib[j] = bp.Contributed
folded[j] = bp.Folded
if !bp.Folded {
seven := []int{h.Cards[2*j], h.Cards[2*j+1]}
seven = append(seven, board...)
scores[j] = holdem.Evaluate(seven)
} else {
scores[j] = -1
}
}
pots := holdem.BuildPots(contrib, folded)
won := holdem.Distribute(pots, scores, holdem.OddChipOrder(n))
h.Result = &Result{Credits: won, Scores: scores}
if !challengesEnabled {
t.finalize(ctx)
return
}
h.Phase = phChallenge
h.Deadline = ctx.height + t.ChallengeWindow
}
// finalize pays the recorded result and ends the hand.
func (t *Table) finalize(ctx *txCtx) {
h := t.Hand
for j, p := range h.Players {
t.Seats[p.Seat].Stack += h.Result.Credits[j]
}
h.Settled = true
h.Phase = phDone
t.cleanupSeats(ctx)
}
// cleanupSeats pays out and frees seats marked leaving.
func (t *Table) cleanupSeats(ctx *txCtx) {
for i, s := range t.Seats {
if s != nil && s.Leaving {
t.removeSeat(ctx, i)
}
}
}
// abort ends the hand without a showdown: all contributions are refunded and
// each penalized player's whole stack is split equally among the other hand
// players (remainder to the lowest hand index), then the penalized players
// are removed from the table.
func (t *Table) abort(ctx *txCtx, penalized []int, convicted bool) {
h := t.Hand
n := h.n()
var creditBuf [maxSeats]int64
credits := creditBuf[:n:n]
if !h.Settled {
for j, p := range h.Players {
c := h.Bet.Players[j].Contributed
t.Seats[p.Seat].Stack += c
credits[j] = c
}
}
var penBuf [maxSeats]bool
isPen := penBuf[:n:n]
for _, j := range penalized {
isPen[j] = true
}
recipients := []int{}
for j := 0; j < n; j++ {
if !isPen[j] {
recipients = append(recipients, j)
}
}
if len(recipients) > 0 {
for _, j := range penalized {
s := t.Seats[h.Players[j].Seat]
amount := s.Stack
s.Stack = 0
credits[j] = 0
share := amount / int64(len(recipients))
rem := amount - share*int64(len(recipients))
for k, r := range recipients {
add := share
if k == 0 {
add += rem
}
t.Seats[h.Players[r].Seat].Stack += add
credits[r] += add
}
}
}
res := &Result{Aborted: true, Credits: credits}
if h.Result != nil {
res.Challenges = h.Result.Challenges
}
if convicted {
res.Convicted = penalized
} else {
res.Stallers = penalized
}
h.Result = res
h.Settled = true
h.Phase = phDone
for _, j := range penalized {
t.removeSeat(ctx, h.Players[j].Seat)
}
t.cleanupSeats(ctx)
}
// Accept agrees with the result; when all hand players accept, the hand is
// finalized without waiting for the window.
func Accept(cur realm, tableID, handNo uint64) {
assertNoSend(cur)
ctx := newCtx(cur)
t, h, j := handFor(cur, tableID, handNo)
if h.Phase != phChallenge {
panic("not in challenge window")
}
h.Players[j].Accepted = true
for _, p := range h.Players {
if !p.Accepted {
return
}
}
t.finalize(ctx)
}
// Finalize settles the hand once the challenge window has passed.
func Finalize(cur realm, tableID uint64) {
assertNoSend(cur)
ctx := newCtx(cur)
t := getTable(tableID)
h := t.Hand
if h == nil || h.Phase != phChallenge {
panic("no hand in challenge window")
}
if ctx.height <= h.Deadline {
panic("challenge window still open")
}
t.finalize(ctx)
}
// Timeout applies the stall rules once the current deadline has passed.
func Timeout(cur realm, tableID uint64) {
assertNoSend(cur)
ctx := newCtx(cur)
t := getTable(tableID)
h := t.Hand
if h == nil || h.Phase == phDone {
panic("no hand in progress")
}
if ctx.height <= h.Deadline {
panic("deadline not reached")
}
switch {
case isBettingPhase(h.Phase):
j := h.Bet.Turn
if h.Bet.CanCheck(j) {
t.applyAction(ctx, j, "check", 0)
} else {
t.applyAction(ctx, j, "fold", 0)
}
case h.Phase == phShuffle || h.Phase == phRekey:
t.abort(ctx, []int{h.turnIndex()}, false)
case isDealPhase(h.Phase):
stallers := []int{}
for j, o := range h.Owing {
if o {
stallers = append(stallers, j)
}
}
t.abort(ctx, stallers, false)
case h.Phase == phReveal:
stallers := []int{}
for j, p := range h.Players {
if !p.Revealed {
stallers = append(stallers, j)
}
}
t.abort(ctx, stallers, false)
case h.Phase == phChallenge:
t.finalize(ctx)
}
}
poker.gno
// Package poker is a trustless no-limit Texas Hold'em realm. See
// docs/protocol.md for the normative protocol and API.
package poker
import (
"chain"
"chain/banker"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
)
const denom = "ugnot"
// Seat is an occupied table seat.
type Seat struct {
Owner address
Session address // empty when the owner acts directly
Stack int64
SittingOut bool
Leaving bool // pay out and free the seat when the current hand ends
Waiting bool // joined during a hand, plays from the next one
}
// Table is a persistent cash table.
type Table struct {
ID uint64
SmallBlind int64
BigBlind int64
MinBuyIn int64
MaxBuyIn int64
MaxPlayers int
ActionTimeout int64
ChallengeWindow int64
ChallengeBond int64
Seats []*Seat
Button int // seat index of the last button, -1 before the first hand
HandNo uint64
Hand *Hand
Deck string // raw bytes of the latest deck pass of hand DeckHand
DeckHand uint64
}
var tables []*Table
// txCtx carries per-transaction values into helpers.
type txCtx struct {
bk banker.Banker
self address
caller address
height int64
}
func newCtx(cur realm) *txCtx {
return &txCtx{
bk: banker.NewBanker(banker.BankerTypeRealmSend, cur),
self: cur.Address(),
caller: cur.Previous().Address(),
height: runtime.ChainHeight(),
}
}
func (c *txCtx) pay(to address, amount int64) {
if amount <= 0 {
return
}
c.bk.SendCoins(c.self, to, chain.Coins{chain.NewCoin(denom, amount)})
}
// sentUgnot returns the ugnot attached to a direct user call and rejects any
// other denomination.
func sentUgnot(cur realm) int64 {
sent := unsafe.OriginSend()
if len(sent) == 0 {
return 0
}
if !cur.Previous().IsUserCall() {
panic("coins are only accepted from a direct user call")
}
total := int64(0)
for _, c := range sent {
if c.Denom != denom {
panic("only ugnot is accepted")
}
total += c.Amount
}
return total
}
func assertNoSend(cur realm) {
if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
panic("this call does not accept coins")
}
}
func getTable(id uint64) *Table {
if id == 0 || id > uint64(len(tables)) {
panic("table not found")
}
return tables[id-1]
}
// seatOf returns the seat index for which addr is owner or session, or -1.
func (t *Table) seatOf(addr address) int {
for i, s := range t.Seats {
if s != nil && (s.Owner == addr || (s.Session != "" && s.Session == addr)) {
return i
}
}
return -1
}
func (t *Table) ownerSeat(addr address) int {
for i, s := range t.Seats {
if s != nil && s.Owner == addr {
return i
}
}
return -1
}
// handLive reports whether a hand is in progress with chips still escrowed.
func (t *Table) handLive() bool {
return t.Hand != nil && !t.Hand.Settled
}
// inLiveHand reports whether seat i plays the live hand.
func (t *Table) inLiveHand(seat int) bool {
if !t.handLive() {
return false
}
return t.Hand.playerIndex(seat) >= 0
}
// CreateTable creates a table and returns its id.
func CreateTable(cur realm, smallBlind, bigBlind, minBuyIn, maxBuyIn int64, maxPlayers int, actionTimeoutBlocks, challengeWindowBlocks, challengeBond int64) uint64 {
assertNoSend(cur)
if smallBlind <= 0 || bigBlind < smallBlind {
panic("invalid blinds")
}
if minBuyIn < bigBlind || maxBuyIn < minBuyIn {
panic("invalid buy-in limits")
}
if maxPlayers < 2 || maxPlayers > maxSeats {
panic("maxPlayers must be between 2 and 6")
}
if actionTimeoutBlocks <= 0 || challengeWindowBlocks <= 0 {
panic("timeouts must be positive")
}
if challengeBond <= 0 {
panic("challenge bond must be positive")
}
t := &Table{
ID: uint64(len(tables) + 1),
SmallBlind: smallBlind,
BigBlind: bigBlind,
MinBuyIn: minBuyIn,
MaxBuyIn: maxBuyIn,
MaxPlayers: maxPlayers,
ActionTimeout: actionTimeoutBlocks,
ChallengeWindow: challengeWindowBlocks,
ChallengeBond: challengeBond,
Seats: make([]*Seat, maxPlayers),
Button: -1,
}
tables = append(tables, t)
return t.ID
}
// Join takes a free seat with the attached ugnot minus gasAllowance as stack and
// forwards gasAllowance to the session address.
func Join(cur realm, tableID uint64, session string, gasAllowance int64) {
ctx := newCtx(cur)
t := getTable(tableID)
sent := sentUgnot(cur)
owner := ctx.caller
if t.seatOf(owner) >= 0 {
panic("already seated at this table")
}
if gasAllowance < 0 {
panic("negative gas allowance")
}
sess := address(session)
if session == "" {
if gasAllowance != 0 {
panic("gas allowance needs a session address")
}
} else {
if !sess.IsValid() {
panic("invalid session address")
}
if sess == owner {
panic("session must differ from owner")
}
if t.seatOf(sess) >= 0 {
panic("session address already used at this table")
}
}
stack := sent - gasAllowance
if stack < t.MinBuyIn || stack > t.MaxBuyIn {
panic("buy-in must be between " + strconv.FormatInt(t.MinBuyIn, 10) + " and " + strconv.FormatInt(t.MaxBuyIn, 10) + " ugnot")
}
free := -1
for i, s := range t.Seats {
if s == nil {
free = i
break
}
}
if free < 0 {
panic("table is full")
}
t.Seats[free] = &Seat{Owner: owner, Session: sess, Stack: stack, Waiting: t.handLive()}
if gasAllowance > 0 {
ctx.pay(sess, gasAllowance)
}
}
// TopUp adds the attached ugnot to the caller's stack between hands.
func TopUp(cur realm, tableID uint64) {
ctx := newCtx(cur)
t := getTable(tableID)
sent := sentUgnot(cur)
i := t.ownerSeat(ctx.caller)
if i < 0 {
panic("only the seat owner can top up")
}
if t.inLiveHand(i) {
panic("cannot top up during a hand")
}
if sent <= 0 {
panic("no ugnot attached")
}
s := t.Seats[i]
if s.Stack+sent > t.MaxBuyIn {
panic("stack would exceed max buy-in")
}
s.Stack += sent
}
// Leave pays out the stack, or marks the seat leaving until the hand ends.
func Leave(cur realm, tableID uint64) {
assertNoSend(cur)
ctx := newCtx(cur)
t := getTable(tableID)
i := t.ownerSeat(ctx.caller)
if i < 0 {
panic("only the seat owner can leave")
}
if t.inLiveHand(i) {
t.Seats[i].Leaving = true
return
}
t.removeSeat(ctx, i)
}
func (t *Table) removeSeat(ctx *txCtx, i int) {
s := t.Seats[i]
if s == nil {
return
}
stack := s.Stack
t.Seats[i] = nil
ctx.pay(s.Owner, stack)
}
// SitOut skips the caller from the next hand on.
func SitOut(cur realm, tableID uint64) {
assertNoSend(cur)
t := getTable(tableID)
i := t.authSeat(cur.Previous().Address())
t.Seats[i].SittingOut = true
}
// SitIn makes the caller eligible again from the next hand.
func SitIn(cur realm, tableID uint64) {
assertNoSend(cur)
t := getTable(tableID)
i := t.authSeat(cur.Previous().Address())
t.Seats[i].SittingOut = false
}
func (t *Table) authSeat(addr address) int {
i := t.seatOf(addr)
if i < 0 {
panic("caller is not seated at this table")
}
return i
}
// escrow returns the ugnot the realm must hold for this table.
func (t *Table) escrow() int64 {
total := int64(0)
for _, s := range t.Seats {
if s != nil {
total += s.Stack
}
}
if t.handLive() {
total += t.Hand.Bet.Pot()
}
return total
}
// totalEscrow is the ugnot the realm must hold across all tables.
func totalEscrow() int64 {
total := int64(0)
for _, t := range tables {
total += t.escrow()
}
return total
}
// ChallengesEnabled reports whether this deployment accepts challenges.
func ChallengesEnabled() bool {
return challengesEnabled
}
render.gno
package poker
import (
"chain/runtime"
"strconv"
"strings"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/cards"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/holdem"
)
func i64s(v int64) string { return "\"" + strconv.FormatInt(v, 10) + "\"" }
func itoa(v int) string { return strconv.Itoa(v) }
func qs(s string) string { return "\"" + s + "\"" }
func bools(b bool) string {
if b {
return "true"
}
return "false"
}
func intList(xs []int) string {
var b strings.Builder
b.WriteByte('[')
for i, x := range xs {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(itoa(x))
}
b.WriteByte(']')
return b.String()
}
func (t *Table) summaryJSON(b *strings.Builder) {
b.WriteString("{\"id\":" + strconv.FormatUint(t.ID, 10))
b.WriteString(",\"smallBlind\":" + i64s(t.SmallBlind))
b.WriteString(",\"bigBlind\":" + i64s(t.BigBlind))
b.WriteString(",\"minBuyIn\":" + i64s(t.MinBuyIn))
b.WriteString(",\"maxBuyIn\":" + i64s(t.MaxBuyIn))
b.WriteString(",\"maxPlayers\":" + itoa(t.MaxPlayers))
b.WriteString(",\"actionTimeoutBlocks\":" + strconv.FormatInt(t.ActionTimeout, 10))
b.WriteString(",\"challengeWindowBlocks\":" + strconv.FormatInt(t.ChallengeWindow, 10))
b.WriteString(",\"challengeBond\":" + i64s(t.ChallengeBond))
b.WriteString(",\"button\":" + itoa(t.Button))
b.WriteString(",\"handNo\":" + strconv.FormatUint(t.HandNo, 10))
seated := 0
for _, s := range t.Seats {
if s != nil {
seated++
}
}
b.WriteString(",\"seated\":" + itoa(seated))
phase := ""
if t.Hand != nil {
phase = phaseNames[t.Hand.Phase]
}
b.WriteString(",\"phase\":" + qs(phase) + "}")
}
// ListTables returns a JSON array of table summaries.
func ListTables() string {
var b strings.Builder
b.WriteString("[")
for i, t := range tables {
if i > 0 {
b.WriteString(",")
}
t.summaryJSON(&b)
}
b.WriteString("]")
return b.String()
}
// GetTable returns the full table and hand state as JSON.
func GetTable(tableID uint64) string {
t := getTable(tableID)
var b strings.Builder
b.WriteString("{\"id\":" + strconv.FormatUint(t.ID, 10))
b.WriteString(",\"smallBlind\":" + i64s(t.SmallBlind))
b.WriteString(",\"bigBlind\":" + i64s(t.BigBlind))
b.WriteString(",\"minBuyIn\":" + i64s(t.MinBuyIn))
b.WriteString(",\"maxBuyIn\":" + i64s(t.MaxBuyIn))
b.WriteString(",\"maxPlayers\":" + itoa(t.MaxPlayers))
b.WriteString(",\"actionTimeoutBlocks\":" + strconv.FormatInt(t.ActionTimeout, 10))
b.WriteString(",\"challengeWindowBlocks\":" + strconv.FormatInt(t.ChallengeWindow, 10))
b.WriteString(",\"challengeBond\":" + i64s(t.ChallengeBond))
b.WriteString(",\"height\":" + strconv.FormatInt(runtime.ChainHeight(), 10))
b.WriteString(",\"button\":" + itoa(t.Button))
b.WriteString(",\"handNo\":" + strconv.FormatUint(t.HandNo, 10))
b.WriteString(",\"seats\":[")
for i, s := range t.Seats {
if i > 0 {
b.WriteString(",")
}
if s == nil {
b.WriteString("null")
continue
}
b.WriteString("{\"seat\":" + itoa(i))
b.WriteString(",\"owner\":" + qs(s.Owner.String()))
b.WriteString(",\"session\":" + qs(s.Session.String()))
b.WriteString(",\"stack\":" + i64s(s.Stack))
b.WriteString(",\"sittingOut\":" + bools(s.SittingOut))
b.WriteString(",\"leaving\":" + bools(s.Leaving))
b.WriteString(",\"waiting\":" + bools(s.Waiting) + "}")
}
b.WriteString("],\"hand\":")
if t.Hand == nil {
b.WriteString("null}")
return b.String()
}
t.Hand.writeJSON(&b)
b.WriteString("}")
return b.String()
}
func (h *Hand) writeJSON(b *strings.Builder) {
n := h.n()
b.WriteString("{\"handNo\":" + strconv.FormatUint(h.No, 10))
b.WriteString(",\"phase\":" + qs(phaseNames[h.Phase]))
b.WriteString(",\"players\":[")
for j, p := range h.Players {
bp := h.Bet.Players[j]
if j > 0 {
b.WriteString(",")
}
b.WriteString("{\"seat\":" + itoa(p.Seat))
b.WriteString(",\"owner\":" + qs(p.Owner.String()))
b.WriteString(",\"commit\":" + qs(p.Commit))
b.WriteString(",\"contributed\":" + i64s(bp.Contributed))
b.WriteString(",\"streetBet\":" + i64s(bp.StreetBet))
b.WriteString(",\"folded\":" + bools(bp.Folded))
b.WriteString(",\"allIn\":" + bools(bp.AllIn))
b.WriteString(",\"acted\":" + bools(bp.Acted))
canRaise := isBettingPhase(h.Phase) && !bp.Folded && !bp.AllIn && h.Bet.CanRaise(j)
b.WriteString(",\"canRaise\":" + bools(canRaise))
b.WriteString(",\"revealed\":" + bools(p.Revealed))
b.WriteString(",\"accepted\":" + bools(p.Accepted))
b.WriteString(",\"seed\":" + qs(p.Seed))
b.WriteString(",\"keys\":{")
first := true
for pos := 0; pos < cards.DeckSize; pos++ {
k, ok := p.Keys[pos]
if !ok {
continue
}
if !first {
b.WriteString(",")
}
first = false
b.WriteString(qs(itoa(pos)) + ":" + qs(k))
}
b.WriteString("}}")
}
b.WriteString("]")
b.WriteString(",\"turn\":" + itoa(h.turnIndex()))
owing := []int{}
if isDealPhase(h.Phase) {
for j, o := range h.Owing {
if o {
owing = append(owing, j)
}
}
} else if h.Phase == phReveal {
for j, p := range h.Players {
if !p.Revealed {
owing = append(owing, j)
}
}
}
b.WriteString(",\"owing\":" + intList(owing))
b.WriteString(",\"deadline\":" + strconv.FormatInt(h.Deadline, 10))
b.WriteString(",\"pot\":" + i64s(h.Bet.Pot()))
b.WriteString(",\"currentBet\":" + i64s(h.Bet.CurrentBet))
b.WriteString(",\"minRaise\":" + i64s(h.Bet.MinRaise))
b.WriteString(",\"deckSeq\":" + itoa(len(h.Roots)))
b.WriteString(",\"roots\":[")
for i, r := range h.Roots {
if i > 0 {
b.WriteString(",")
}
b.WriteString(qs(r))
}
b.WriteString("]")
if h.Cards != nil {
b.WriteString(",\"board\":" + intList(h.Cards[2*n:2*n+5]))
b.WriteString(",\"cards\":{")
for i, c := range h.Cards {
if i > 0 {
b.WriteString(",")
}
b.WriteString(qs(itoa(i)) + ":" + itoa(c))
}
b.WriteString("}")
} else {
b.WriteString(",\"board\":[],\"cards\":{}")
}
b.WriteString(",\"result\":")
if h.Result == nil {
b.WriteString("null}")
return
}
r := h.Result
b.WriteString("{\"aborted\":" + bools(r.Aborted))
b.WriteString(",\"convicted\":" + intList(r.Convicted))
b.WriteString(",\"stallers\":" + intList(r.Stallers))
b.WriteString(",\"payouts\":{")
for j, c := range r.Credits {
if j > 0 {
b.WriteString(",")
}
b.WriteString(qs(itoa(j)) + ":" + i64s(c))
}
b.WriteString("},\"hands\":{")
first := true
for j, s := range r.Scores {
if s < 0 {
continue
}
if !first {
b.WriteString(",")
}
first = false
b.WriteString(qs(itoa(j)) + ":" + qs(holdem.CategoryName(s)))
}
b.WriteString("},\"challenges\":[")
for i, c := range r.Challenges {
if i > 0 {
b.WriteString(",")
}
b.WriteString("{\"challenger\":" + itoa(c.Challenger) + ",\"accused\":" + itoa(c.Accused) +
",\"kind\":" + qs(c.Kind) + ",\"index\":" + itoa(c.Index) + ",\"guilty\":" + bools(c.Guilty) + "}")
}
b.WriteString("]}}")
}
// GetDeck returns the latest deck pass of the current hand as standard base64,
// or "" before the first pass.
func GetDeck(tableID uint64) string {
t := getTable(tableID)
if t.Hand == nil || t.DeckHand != t.HandNo || len(t.Hand.Roots) == 0 {
return ""
}
return cards.EncodeDeck([]byte(t.Deck))
}
// renderMaxTables is the most tables the list page shows.
const renderMaxTables = 50
// Render shows the newest renderMaxTables tables, or one table at path "<id>".
func Render(path string) string {
if path == "" {
var b strings.Builder
b.WriteString("# Poker tables\n\n")
if len(tables) == 0 {
b.WriteString("No tables yet.\n")
return b.String()
}
b.WriteString("| Table | Blinds | Buy-in | Seated | Hand | Phase |\n|---|---|---|---|---|---|\n")
first := 0
if len(tables) > renderMaxTables {
first = len(tables) - renderMaxTables
}
for k := len(tables) - 1; k >= first; k-- {
t := tables[k]
seated := 0
for i := 0; i < len(t.Seats) && i < maxSeats; i++ {
if t.Seats[i] != nil {
seated++
}
}
phase := "-"
if t.Hand != nil {
phase = phaseNames[t.Hand.Phase]
}
id := strconv.FormatUint(t.ID, 10)
b.WriteString("| [" + id + "](:" + id + ") | " + strconv.FormatInt(t.SmallBlind, 10) + "/" + strconv.FormatInt(t.BigBlind, 10) +
" | " + strconv.FormatInt(t.MinBuyIn, 10) + "-" + strconv.FormatInt(t.MaxBuyIn, 10) +
" | " + itoa(seated) + "/" + itoa(t.MaxPlayers) + " | " + strconv.FormatUint(t.HandNo, 10) + " | " + phase + " |\n")
}
if first > 0 {
b.WriteString("\nShowing the newest " + itoa(renderMaxTables) + " of " + itoa(len(tables)) + " tables. Older tables are at `:<id>`.\n")
}
return b.String()
}
id, err := strconv.ParseUint(path, 10, 64)
if err != nil || id == 0 || id > uint64(len(tables)) {
return "# Not found\n"
}
t := tables[id-1]
var b strings.Builder
b.WriteString("# Table " + path + "\n\n")
b.WriteString("Blinds " + strconv.FormatInt(t.SmallBlind, 10) + "/" + strconv.FormatInt(t.BigBlind, 10) + " ugnot, hand " + strconv.FormatUint(t.HandNo, 10) + "\n\n")
b.WriteString("| Seat | Player | Stack | Status |\n|---|---|---|---|\n")
for i := 0; i < len(t.Seats) && i < maxSeats; i++ {
s := t.Seats[i]
if s == nil {
b.WriteString("| " + itoa(i) + " | (empty) | | |\n")
continue
}
status := []string{}
if i == t.Button {
status = append(status, "button")
}
if s.SittingOut {
status = append(status, "sitting out")
}
if s.Leaving {
status = append(status, "leaving")
}
if s.Waiting {
status = append(status, "waiting")
}
b.WriteString("| " + itoa(i) + " | " + s.Owner.String() + " | " + strconv.FormatInt(s.Stack, 10) + " | " + strings.Join(status, ", ") + " |\n")
}
h := t.Hand
if h == nil {
return b.String()
}
n := h.n()
b.WriteString("\n## Hand " + strconv.FormatUint(h.No, 10) + ": " + phaseNames[h.Phase] + "\n\n")
b.WriteString("Pot " + strconv.FormatInt(h.Bet.Pot(), 10) + " ugnot, deadline block " + strconv.FormatInt(h.Deadline, 10) + "\n\n")
if h.Cards != nil {
board := []string{}
for k := 0; k < 5; k++ {
board = append(board, cards.CardString(h.Cards[2*n+k]))
}
b.WriteString("Board: " + strings.Join(board, " ") + "\n\n")
}
b.WriteString("| # | Seat | Bet | Status | Cards | Result |\n|---|---|---|---|---|---|\n")
for j := 0; j < n && j < maxSeats; j++ {
p := h.Players[j]
bp := h.Bet.Players[j]
status := ""
if bp.Folded {
status = "folded"
} else if bp.AllIn {
status = "all-in"
}
hole := ""
if h.Cards != nil {
hole = cards.CardString(h.Cards[2*j]) + " " + cards.CardString(h.Cards[2*j+1])
}
res := ""
if h.Result != nil && j < len(h.Result.Credits) {
res = "+" + strconv.FormatInt(h.Result.Credits[j], 10)
}
b.WriteString("| " + itoa(j) + " | " + itoa(p.Seat) + " | " + strconv.FormatInt(bp.Contributed, 10) + " | " + status + " | " + hole + " | " + res + " |\n")
}
return b.String()
}
verify.gno
package poker
import (
"crypto/modexp"
"gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/poker/cards"
)
// This file is the only one importing crypto/modexp. For networks without it,
// replace it with verify_nomodexp.gno.txt (renamed to verify.gno).
const challengesEnabled = true
var primeP = cards.P()
// powModP returns base^exp mod P as 256 bytes.
func powModP(base, exp []byte) []byte {
return modexp.ModExp(base, exp, primeP)
}