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.

poker.gno

7.35 Kb · 318 lines
  1// Package poker is a trustless no-limit Texas Hold'em realm. See
  2// docs/protocol.md for the normative protocol and API.
  3package poker
  4
  5import (
  6	"chain"
  7	"chain/banker"
  8	"chain/runtime"
  9	"chain/runtime/unsafe"
 10	"strconv"
 11)
 12
 13const denom = "ugnot"
 14
 15// Seat is an occupied table seat.
 16type Seat struct {
 17	Owner      address
 18	Session    address // empty when the owner acts directly
 19	Stack      int64
 20	SittingOut bool
 21	Leaving    bool // pay out and free the seat when the current hand ends
 22	Waiting    bool // joined during a hand, plays from the next one
 23}
 24
 25// Table is a persistent cash table.
 26type Table struct {
 27	ID              uint64
 28	SmallBlind      int64
 29	BigBlind        int64
 30	MinBuyIn        int64
 31	MaxBuyIn        int64
 32	MaxPlayers      int
 33	ActionTimeout   int64
 34	ChallengeWindow int64
 35	ChallengeBond   int64
 36
 37	Seats    []*Seat
 38	Button   int // seat index of the last button, -1 before the first hand
 39	HandNo   uint64
 40	Hand     *Hand
 41	Deck     string // raw bytes of the latest deck pass of hand DeckHand
 42	DeckHand uint64
 43}
 44
 45var tables []*Table
 46
 47// txCtx carries per-transaction values into helpers.
 48type txCtx struct {
 49	bk     banker.Banker
 50	self   address
 51	caller address
 52	height int64
 53}
 54
 55func newCtx(cur realm) *txCtx {
 56	return &txCtx{
 57		bk:     banker.NewBanker(banker.BankerTypeRealmSend, cur),
 58		self:   cur.Address(),
 59		caller: cur.Previous().Address(),
 60		height: runtime.ChainHeight(),
 61	}
 62}
 63
 64func (c *txCtx) pay(to address, amount int64) {
 65	if amount <= 0 {
 66		return
 67	}
 68	c.bk.SendCoins(c.self, to, chain.Coins{chain.NewCoin(denom, amount)})
 69}
 70
 71// sentUgnot returns the ugnot attached to a direct user call and rejects any
 72// other denomination.
 73func sentUgnot(cur realm) int64 {
 74	sent := unsafe.OriginSend()
 75	if len(sent) == 0 {
 76		return 0
 77	}
 78	if !cur.Previous().IsUserCall() {
 79		panic("coins are only accepted from a direct user call")
 80	}
 81	total := int64(0)
 82	for _, c := range sent {
 83		if c.Denom != denom {
 84			panic("only ugnot is accepted")
 85		}
 86		total += c.Amount
 87	}
 88	return total
 89}
 90
 91func assertNoSend(cur realm) {
 92	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
 93		panic("this call does not accept coins")
 94	}
 95}
 96
 97func getTable(id uint64) *Table {
 98	if id == 0 || id > uint64(len(tables)) {
 99		panic("table not found")
100	}
101	return tables[id-1]
102}
103
104// seatOf returns the seat index for which addr is owner or session, or -1.
105func (t *Table) seatOf(addr address) int {
106	for i, s := range t.Seats {
107		if s != nil && (s.Owner == addr || (s.Session != "" && s.Session == addr)) {
108			return i
109		}
110	}
111	return -1
112}
113
114func (t *Table) ownerSeat(addr address) int {
115	for i, s := range t.Seats {
116		if s != nil && s.Owner == addr {
117			return i
118		}
119	}
120	return -1
121}
122
123// handLive reports whether a hand is in progress with chips still escrowed.
124func (t *Table) handLive() bool {
125	return t.Hand != nil && !t.Hand.Settled
126}
127
128// inLiveHand reports whether seat i plays the live hand.
129func (t *Table) inLiveHand(seat int) bool {
130	if !t.handLive() {
131		return false
132	}
133	return t.Hand.playerIndex(seat) >= 0
134}
135
136// CreateTable creates a table and returns its id.
137func CreateTable(cur realm, smallBlind, bigBlind, minBuyIn, maxBuyIn int64, maxPlayers int, actionTimeoutBlocks, challengeWindowBlocks, challengeBond int64) uint64 {
138	assertNoSend(cur)
139	if smallBlind <= 0 || bigBlind < smallBlind {
140		panic("invalid blinds")
141	}
142	if minBuyIn < bigBlind || maxBuyIn < minBuyIn {
143		panic("invalid buy-in limits")
144	}
145	if maxPlayers < 2 || maxPlayers > maxSeats {
146		panic("maxPlayers must be between 2 and 6")
147	}
148	if actionTimeoutBlocks <= 0 || challengeWindowBlocks <= 0 {
149		panic("timeouts must be positive")
150	}
151	if challengeBond <= 0 {
152		panic("challenge bond must be positive")
153	}
154	t := &Table{
155		ID:              uint64(len(tables) + 1),
156		SmallBlind:      smallBlind,
157		BigBlind:        bigBlind,
158		MinBuyIn:        minBuyIn,
159		MaxBuyIn:        maxBuyIn,
160		MaxPlayers:      maxPlayers,
161		ActionTimeout:   actionTimeoutBlocks,
162		ChallengeWindow: challengeWindowBlocks,
163		ChallengeBond:   challengeBond,
164		Seats:           make([]*Seat, maxPlayers),
165		Button:          -1,
166	}
167	tables = append(tables, t)
168	return t.ID
169}
170
171// Join takes a free seat with the attached ugnot minus gasAllowance as stack and
172// forwards gasAllowance to the session address.
173func Join(cur realm, tableID uint64, session string, gasAllowance int64) {
174	ctx := newCtx(cur)
175	t := getTable(tableID)
176	sent := sentUgnot(cur)
177	owner := ctx.caller
178	if t.seatOf(owner) >= 0 {
179		panic("already seated at this table")
180	}
181	if gasAllowance < 0 {
182		panic("negative gas allowance")
183	}
184	sess := address(session)
185	if session == "" {
186		if gasAllowance != 0 {
187			panic("gas allowance needs a session address")
188		}
189	} else {
190		if !sess.IsValid() {
191			panic("invalid session address")
192		}
193		if sess == owner {
194			panic("session must differ from owner")
195		}
196		if t.seatOf(sess) >= 0 {
197			panic("session address already used at this table")
198		}
199	}
200	stack := sent - gasAllowance
201	if stack < t.MinBuyIn || stack > t.MaxBuyIn {
202		panic("buy-in must be between " + strconv.FormatInt(t.MinBuyIn, 10) + " and " + strconv.FormatInt(t.MaxBuyIn, 10) + " ugnot")
203	}
204	free := -1
205	for i, s := range t.Seats {
206		if s == nil {
207			free = i
208			break
209		}
210	}
211	if free < 0 {
212		panic("table is full")
213	}
214	t.Seats[free] = &Seat{Owner: owner, Session: sess, Stack: stack, Waiting: t.handLive()}
215	if gasAllowance > 0 {
216		ctx.pay(sess, gasAllowance)
217	}
218}
219
220// TopUp adds the attached ugnot to the caller's stack between hands.
221func TopUp(cur realm, tableID uint64) {
222	ctx := newCtx(cur)
223	t := getTable(tableID)
224	sent := sentUgnot(cur)
225	i := t.ownerSeat(ctx.caller)
226	if i < 0 {
227		panic("only the seat owner can top up")
228	}
229	if t.inLiveHand(i) {
230		panic("cannot top up during a hand")
231	}
232	if sent <= 0 {
233		panic("no ugnot attached")
234	}
235	s := t.Seats[i]
236	if s.Stack+sent > t.MaxBuyIn {
237		panic("stack would exceed max buy-in")
238	}
239	s.Stack += sent
240}
241
242// Leave pays out the stack, or marks the seat leaving until the hand ends.
243func Leave(cur realm, tableID uint64) {
244	assertNoSend(cur)
245	ctx := newCtx(cur)
246	t := getTable(tableID)
247	i := t.ownerSeat(ctx.caller)
248	if i < 0 {
249		panic("only the seat owner can leave")
250	}
251	if t.inLiveHand(i) {
252		t.Seats[i].Leaving = true
253		return
254	}
255	t.removeSeat(ctx, i)
256}
257
258func (t *Table) removeSeat(ctx *txCtx, i int) {
259	s := t.Seats[i]
260	if s == nil {
261		return
262	}
263	stack := s.Stack
264	t.Seats[i] = nil
265	ctx.pay(s.Owner, stack)
266}
267
268// SitOut skips the caller from the next hand on.
269func SitOut(cur realm, tableID uint64) {
270	assertNoSend(cur)
271	t := getTable(tableID)
272	i := t.authSeat(cur.Previous().Address())
273	t.Seats[i].SittingOut = true
274}
275
276// SitIn makes the caller eligible again from the next hand.
277func SitIn(cur realm, tableID uint64) {
278	assertNoSend(cur)
279	t := getTable(tableID)
280	i := t.authSeat(cur.Previous().Address())
281	t.Seats[i].SittingOut = false
282}
283
284func (t *Table) authSeat(addr address) int {
285	i := t.seatOf(addr)
286	if i < 0 {
287		panic("caller is not seated at this table")
288	}
289	return i
290}
291
292// escrow returns the ugnot the realm must hold for this table.
293func (t *Table) escrow() int64 {
294	total := int64(0)
295	for _, s := range t.Seats {
296		if s != nil {
297			total += s.Stack
298		}
299	}
300	if t.handLive() {
301		total += t.Hand.Bet.Pot()
302	}
303	return total
304}
305
306// totalEscrow is the ugnot the realm must hold across all tables.
307func totalEscrow() int64 {
308	total := int64(0)
309	for _, t := range tables {
310		total += t.escrow()
311	}
312	return total
313}
314
315// ChallengesEnabled reports whether this deployment accepts challenges.
316func ChallengesEnabled() bool {
317	return challengesEnabled
318}