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.

draw.gno

5.15 Kb · 217 lines
  1package fairness
  2
  3// Deterministic draw: a seed-driven byte stream and a weighted, multi-winner
  4// sample taken from it without replacement.
  5//
  6// Everything here is a pure function of its inputs, so the same seed over the
  7// same roster gives the same winners wherever it is recomputed — in a realm,
  8// in a test, or in a verifier script off chain.
  9
 10import (
 11	"errors"
 12	"strconv"
 13)
 14
 15// maxUint64 is 2^64-1.
 16const maxUint64 uint64 = 1<<64 - 1
 17
 18// Ticket is one entry in a draw.
 19//
 20// ID is the entrant's stable identity — FairDrop uses the bech32 address
 21// string, so the roster is ordered and deduplicated by address. Commit is the
 22// seal, Secret the revealed preimage (empty until reveal) and Rank 0 until the
 23// draw, then 1..k for winners. The package only reads ID, Weight and Commit;
 24// Secret and Rank are carried so a realm can keep one record per ticket.
 25type Ticket struct {
 26	ID     string
 27	Weight uint64
 28	Commit string
 29	Secret string
 30	Rank   int
 31}
 32
 33// Insert adds t to a roster kept in canonical (ascending ID) order and refuses
 34// an ID that is already present. One call therefore enforces both rules a
 35// draw depends on: a single ticket per entrant, and the fixed ordering the
 36// seed fold and the draw walk over.
 37//
 38// The returned slice is a new slice; the caller must keep it.
 39func Insert(roster []Ticket, t Ticket) ([]Ticket, error) {
 40	if t.ID == "" {
 41		return roster, errors.New("fairness: empty entrant id")
 42	}
 43	if t.Weight == 0 {
 44		return roster, errors.New("fairness: weight must be positive")
 45	}
 46
 47	n := len(roster)
 48	lo, hi := 0, n
 49	for lo < hi {
 50		mid := (lo + hi) / 2
 51		if roster[mid].ID < t.ID {
 52			lo = mid + 1
 53		} else {
 54			hi = mid
 55		}
 56	}
 57	if lo < n && roster[lo].ID == t.ID {
 58		return roster, errors.New("fairness: entrant already holds a ticket")
 59	}
 60
 61	out := make([]Ticket, n+1)
 62	for i := 0; i < lo; i++ {
 63		out[i] = roster[i]
 64	}
 65	out[lo] = t
 66	for i := lo; i < n; i++ {
 67		out[i+1] = roster[i]
 68	}
 69	return out, nil
 70}
 71
 72// Find returns the index of the ticket held by id, or -1.
 73func Find(roster []Ticket, id string) int {
 74	lo, hi := 0, len(roster)
 75	for lo < hi {
 76		mid := (lo + hi) / 2
 77		if roster[mid].ID < id {
 78			lo = mid + 1
 79		} else {
 80			hi = mid
 81		}
 82	}
 83	if lo < len(roster) && roster[lo].ID == id {
 84		return lo
 85	}
 86	return -1
 87}
 88
 89// Stream is a deterministic byte stream: SHA-256 in counter mode over the
 90// seed. It exists so a draw needs no randomness from the chain, which is what
 91// makes the result reproducible by anyone holding the seed.
 92type Stream struct {
 93	seed string
 94	ctr  uint64
 95	pool []byte
 96	pos  int
 97}
 98
 99// NewStream starts a stream at seed.
100func NewStream(seed string) *Stream {
101	return &Stream{seed: seed}
102}
103
104func (s *Stream) refill() {
105	sum := sha256Sum(s.seed + "|" + strconv.FormatUint(s.ctr, 10))
106	s.ctr++
107	s.pool = sum
108	s.pos = 0
109}
110
111// Uint64 returns the next 8 stream bytes as a big-endian unsigned integer.
112func (s *Stream) Uint64() uint64 {
113	if s.pool == nil || s.pos+8 > len(s.pool) {
114		s.refill()
115	}
116	var v uint64
117	for i := 0; i < 8; i++ {
118		v = (v << 8) | uint64(s.pool[s.pos+i])
119	}
120	s.pos += 8
121	return v
122}
123
124// Below returns a uniform integer in [0, n) by rejection sampling, so no
125// residue is favoured by the modulo. It panics on n == 0.
126func (s *Stream) Below(n uint64) uint64 {
127	if n == 0 {
128		panic("fairness: Below(0)")
129	}
130	limit := (maxUint64 / n) * n
131	for {
132		v := s.Uint64()
133		if v < limit {
134			return v % n
135		}
136	}
137}
138
139// Draw samples up to k distinct tickets from roster, without replacement,
140// with probability proportional to Weight, and returns their IDs in the order
141// they were drawn (index 0 is rank 1). Zero-weight tickets are never drawn.
142//
143// The order of roster must be canonical (as Insert maintains it), because the
144// stream walks the roster in that order.
145func Draw(seed string, roster []Ticket, k int) []string {
146	if k <= 0 || len(roster) == 0 {
147		return []string{}
148	}
149	if k > len(roster) {
150		k = len(roster)
151	}
152
153	// Work on a copy so the caller's roster (realm state) is untouched.
154	pool := make([]Ticket, len(roster))
155	for i := 0; i < len(roster); i++ {
156		pool[i] = roster[i]
157	}
158
159	s := NewStream(seed)
160	winners := make([]string, 0, k)
161	for len(winners) < k {
162		var total uint64
163		for i := 0; i < len(pool); i++ {
164			w := pool[i].Weight
165			if w > 0 && total > maxUint64-w {
166				panic("fairness: total weight overflows uint64")
167			}
168			total += w
169		}
170		if total == 0 {
171			break
172		}
173
174		pick := s.Below(total)
175		at := -1
176		var acc uint64
177		for i := 0; i < len(pool); i++ {
178			if pool[i].Weight == 0 {
179				continue
180			}
181			acc += pool[i].Weight
182			if pick < acc {
183				at = i
184				break
185			}
186		}
187		if at < 0 {
188			// Unreachable while total > 0, kept as a hard stop rather than a
189			// silent wrong pick.
190			panic("fairness: weighted pick fell through")
191		}
192
193		winners = append(winners, pool[at].ID)
194
195		kept := make([]Ticket, 0, len(pool)-1)
196		for i := 0; i < len(pool); i++ {
197			if i != at {
198				kept = append(kept, pool[i])
199			}
200		}
201		pool = kept
202	}
203	return winners
204}
205
206// TotalWeight sums the weights of a roster, panicking rather than wrapping.
207func TotalWeight(roster []Ticket) uint64 {
208	var total uint64
209	for i := 0; i < len(roster); i++ {
210		w := roster[i].Weight
211		if w > 0 && total > maxUint64-w {
212			panic("fairness: total weight overflows uint64")
213		}
214		total += w
215	}
216	return total
217}