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.

randomness.gno

10.78 Kb · 293 lines
  1package core
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6	"strings"
  7
  8	"gno.land/p/nt/avl/v0"
  9
 10	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
 11	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
 12)
 13
 14// Pluggable randomness sources (beacon v2).
 15//
 16// A collection launched with useBeacon picks its second entropy source at
 17// Launch (LaunchSpec.BeaconSource, frozen by I-6):
 18//
 19//   - types.BeaconCommitted: the platform beacon's commit-reveal
 20//     (provenance.gno; BeaconCommit before the first mint,
 21//     RevealBeaconSecret after the creator).
 22//   - the package path of a randomness provider realm: a public random
 23//     value nobody can know in advance, e.g. a drand round relayed and
 24//     BLS-verified on chain (gnolang/gno#6268 p/drand + r/drand). Nothing
 25//     is committed before the sale; the round is fixed by the creator's
 26//     reveal (same transaction) or, for a silent creator, in the grace
 27//     period / at the deadline, and its value is then consumed by whoever
 28//     calls first (FulfillRandomness or Finalize): no caller can skip it.
 29//
 30// Before any provider is approved (randomness.add) a keeper must run that
 31// requests in the grace period for silent creators and fulfills bound
 32// rounds as soon as they are published (README "Randomness keeper").
 33//
 34// A provider realm registers itself (its id is its package path, as for
 35// engines) and is usable only after the admin approves it through the
 36// timelocked op randomness.add; randomness.deprecate stops new launches,
 37// running collections finish with it. So a drand provider plugs in without
 38// a core redeploy. Its methods are declared in its own realm, so core
 39// calling them runs the provider with the provider's authority (interrealm
 40// v2 borrow rule #1): it cannot write core state, and with no cur it cannot
 41// call a core mutator.
 42//
 43// Order with a provider (same guarantees as the committed beacon, SA-M1;
 44// CV-M1: the outcome never depends on who calls, or when):
 45//
 46//  1. the creator reveals until revealDeadline - BeaconGraceBlocks; the
 47//     reveal itself binds the collection to provider.Target() in the same
 48//     transaction, a round nobody knows yet (its secret is public now, so
 49//     nobody holding a choice learns anything new later);
 50//  2. a silent creator: RequestRandomness (anyone, a keeper) inside the
 51//     grace period, or the first Finalize after revealDeadline, binds the
 52//     round instead — the creator's window is closed by then;
 53//  3. once the provider has the bound round (and not in the binding
 54//     block, CV-I6), FulfillRandomness or Finalize (anyone, before or
 55//     after the deadline) takes its value as the beacon secret and the
 56//     collection is Final (2/2 after the creator, beacon-only otherwise).
 57//     After the deadline Finalize refuses to fall back while the bound
 58//     round may still arrive;
 59//  4. fallback (creator-only / fallback badge, never a FairLaunch) only
 60//     once the provider failed to deliver for ProviderWaitBlocks after the
 61//     deadline or the binding, whichever is later.
 62//
 63// A provider that panics aborts the calling transaction (a realm-boundary
 64// panic cannot be recovered); if an approved provider breaks, the admin
 65// deprecates it and, after the wait, Finalize stops calling it.
 66type RandomnessProvider interface {
 67	// Name is a short label for UIs, e.g. "drand quicknet".
 68	Name() string
 69	// Target is the round a request made in the current block is bound
 70	// to. Its value must be unknowable to anyone at this block (a round
 71	// published strictly in the future). Read-only.
 72	Target() int64
 73	// Randomness is round's verified value as 64 lowercase hex characters
 74	// (32 bytes), or "" while it is not available. Read-only.
 75	Randomness(round int64) string
 76}
 77
 78type providerRecord struct {
 79	id               string
 80	name             string
 81	impl             RandomnessProvider
 82	active           bool // approved by the admin and not deprecated
 83	registeredHeight int64
 84}
 85
 86var (
 87	providers       avl.Tree // provider pkgpath -> *providerRecord
 88	activeProviders int64
 89)
 90
 91const MaxProviderNameLen = 64
 92
 93// RegisterRandomnessProvider stores the calling realm's provider. It is
 94// inert until the admin approves it (randomness.add, timelocked).
 95func RegisterRandomnessProvider(cur realm, p RandomnessProvider) string {
 96	assertNoDeposit(cur)
 97	id := cur.Previous().PkgPath()
 98	if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
 99		panic("a randomness provider registers from its own realm (an /r/ package, not a sub-realm or wallet)")
100	}
101	if p == nil {
102		panic("nil provider")
103	}
104	if providers.Has(id) {
105		panic("randomness provider already registered: " + id)
106	}
107	name := p.Name()
108	safe.AssertNonEmptyText("provider name", name, MaxProviderNameLen)
109	providers.Set(id, &providerRecord{id: id, name: name, impl: p, registeredHeight: height()})
110	chain.Emit("RandomnessProviderRegistered", "id", id, "name", name)
111	return id
112}
113
114func mustProvider(id string) *providerRecord {
115	v := providers.Get(id)
116	if v == nil {
117		panic("unknown randomness provider " + id)
118	}
119	return v.(*providerRecord)
120}
121
122func assertActiveProvider(id string) {
123	if !mustProvider(id).active {
124		panic("randomness provider " + id + " is not approved")
125	}
126}
127
128// beaconAvailable: some unpredictable second source exists, so no launch
129// may opt out of it (SA-M2).
130func beaconAvailable() bool { return beacon != "" || activeProviders > 0 }
131
132func usesProvider(c *collection) bool {
133	return c.useBeacon && c.beaconSource != types.BeaconCommitted
134}
135
136// RequestRandomness binds a provider-backed collection whose creator stayed
137// silent to the provider's next unknowable round (a creator's reveal binds
138// it itself). Permissionless and never paused (I-2); after the deadline the
139// first Finalize binds instead.
140func RequestRandomness(cur realm, cid string) int64 {
141	assertNoDeposit(cur)
142	c := mustCollection(cid)
143	h := height()
144	assertRevealOpen(c, h)
145	if !usesProvider(c) {
146		panic("this collection does not use a randomness provider")
147	}
148	p := c.prov
149	if p.round != 0 {
150		panic("randomness already requested for round " + itoa(p.round))
151	}
152	if !p.creatorRevealed && h < revealDeadline(c)-BeaconGraceBlocks {
153		panic("randomness is requested after the creator reveals, or in the window's last " +
154			itoa(BeaconGraceBlocks) + " blocks")
155	}
156	if !bindRound(c, h) {
157		panic("randomness provider returned an invalid or already published round; retry in a later block")
158	}
159	return p.round
160}
161
162// FulfillRandomness takes the bound round's value from the provider as the
163// beacon secret and finalizes (2/2 after the creator, beacon-only when it
164// stayed silent). Permissionless and never paused (I-2); works before and
165// after the deadline while the collection is Closed.
166func FulfillRandomness(cur realm, cid string) {
167	assertNoDeposit(cur)
168	c := mustCollection(cid)
169	h := height()
170	refresh(c, h)
171	if c.state != types.StateClosed {
172		panic("secrets are accepted only after the sale closed (state " + c.state.String() + ")")
173	}
174	if !usesProvider(c) {
175		panic("this collection does not use a randomness provider")
176	}
177	p := c.prov
178	if p.round == 0 {
179		panic("randomness was not requested yet")
180	}
181	if h <= p.roundHeight {
182		panic("round " + itoa(p.round) + " was bound in this block; fulfill it in a later one")
183	}
184	v := mustProvider(c.beaconSource).impl.Randomness(p.round)
185	if v == "" {
186		panic("round " + itoa(p.round) + " is not available from the provider yet")
187	}
188	consumeRound(c, safe.AssertHex("randomness", v, 32), h)
189}
190
191// bindRound fixes the collection's round to provider.Target() at height h.
192// It refuses (false) a non-positive round or one whose value the provider
193// already has: that value would be known before binding (CV-I6).
194func bindRound(c *collection, h int64) bool {
195	impl := mustProvider(c.beaconSource).impl
196	round := impl.Target()
197	if round <= 0 || isRandomness(impl.Randomness(round)) {
198		return false
199	}
200	c.prov.round, c.prov.roundHeight = round, h
201	chain.Emit("RandomnessRequested", "cid", c.id, "provider", c.beaconSource, "round", itoa(round))
202	return true
203}
204
205func consumeRound(c *collection, v string, h int64) {
206	p := c.prov
207	p.beaconSecret = v
208	p.beaconRevealed = true
209	chain.Emit("BeaconRevealed", "cid", c.id, "provider", c.beaconSource, "round", itoa(p.round), "secret", v)
210	finalize(c, h)
211}
212
213// providerWaitEnd is the last height at which Finalize still waits for the
214// provider: ProviderWaitBlocks after the deadline or the binding.
215func providerWaitEnd(c *collection) int64 {
216	from := revealDeadline(c)
217	if c.prov.roundHeight > from {
218		from = c.prov.roundHeight
219	}
220	return from + ProviderWaitBlocks
221}
222
223// settleProvider is Finalize's provider step after the deadline (CV-M1).
224// It returns true when Finalize is done: the round was bound now (a later
225// Finalize or FulfillRandomness takes its value), or its value finalized
226// the collection. It returns false only when the provider is provably
227// unavailable — no usable value after providerWaitEnd — and Finalize falls
228// back (creator-only / fallback, never a FairLaunch). While the bound round
229// may still arrive it refuses, so nobody can pick the fallback by not
230// fulfilling. After the wait a deprecated provider is not called at all
231// (escape hatch for a provider whose code aborts every call).
232func settleProvider(c *collection, h int64) bool {
233	p := c.prov
234	waited := h > providerWaitEnd(c)
235	if waited && !mustProvider(c.beaconSource).active {
236		return false
237	}
238	if p.round == 0 {
239		if bindRound(c, h) {
240			return true
241		}
242		if waited {
243			return false
244		}
245		panic("the randomness provider cannot bind a round now; retry later (fallback after height " +
246			itoa(providerWaitEnd(c)) + ")")
247	}
248	if h > p.roundHeight {
249		if v := mustProvider(c.beaconSource).impl.Randomness(p.round); isRandomness(v) {
250			consumeRound(c, safe.AssertHex("randomness", v, 32), h)
251			return true
252		}
253	}
254	if waited {
255		return false
256	}
257	panic("waiting for randomness round " + itoa(p.round) + " (FulfillRandomness once it is published; fallback after height " +
258		itoa(providerWaitEnd(c)) + ")")
259}
260
261// isRandomness: a provider value core accepts (64 hex characters).
262func isRandomness(v string) bool {
263	if len(v) != 64 {
264		return false
265	}
266	for i := 0; i < len(v); i++ {
267		c := v[i]
268		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
269			return false
270		}
271	}
272	return true
273}
274
275// RandomnessProviders lists registered providers (by path) as JSON:
276// [{id, name, active, registeredHeight}]. Registration is open, so only
277// "active" ones (admin-approved) can be chosen at Launch.
278func RandomnessProviders(offset, limit int64) string {
279	w := &safe.JSONWriter{}
280	w.BeginArray()
281	providers.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
282		r := v.(*providerRecord)
283		w.BeginObject()
284		w.StrField("id", r.id)
285		w.StrField("name", r.name)
286		w.BoolField("active", r.active)
287		w.IntField("registeredHeight", r.registeredHeight)
288		w.EndObject()
289		return false
290	})
291	w.EndArray()
292	return w.String()
293}