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

7.08 Kb · 196 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 only once the
 26//     creator can no longer choose (RequestRandomness), then anyone pulls
 27//     its value (FulfillRandomness).
 28//
 29// A provider realm registers itself (its id is its package path, as for
 30// engines) and is usable only after the admin approves it through the
 31// timelocked op randomness.add; randomness.deprecate stops new launches,
 32// running collections finish with it. So a drand provider plugs in without
 33// a core redeploy. Its methods are declared in its own realm, so core
 34// calling them runs the provider with the provider's authority (interrealm
 35// v2 borrow rule #1): it cannot write core state, and with no cur it cannot
 36// call a core mutator.
 37//
 38// Order with a provider (same guarantees as the committed beacon, SA-M1):
 39//
 40//  1. the creator reveals until revealDeadline - BeaconGraceBlocks;
 41//  2. RequestRandomness (anyone) after the creator revealed, or inside the
 42//     grace period when it stayed silent, and no later than revealDeadline
 43//     - RequestMargin: binds the collection to provider.Target(), a round
 44//     whose value nobody knows yet — not the creator, whose secret is
 45//     public or whose window is closed, not the minters, whose sale is over;
 46//  3. FulfillRandomness (anyone) once the provider has that round: the
 47//     value becomes the beacon secret and the collection is Final at once
 48//     (2/2 after the creator, beacon-only in grace);
 49//  4. after revealDeadline Finalize works as before (creator-only /
 50//     fallback if the provider never delivered).
 51type RandomnessProvider interface {
 52	// Name is a short label for UIs, e.g. "drand quicknet".
 53	Name() string
 54	// Target is the round a request made in the current block is bound
 55	// to. Its value must be unknowable to anyone at this block (a round
 56	// published strictly in the future). Read-only.
 57	Target() int64
 58	// Randomness is round's verified value as 64 lowercase hex characters
 59	// (32 bytes), or "" while it is not available. Read-only.
 60	Randomness(round int64) string
 61}
 62
 63type providerRecord struct {
 64	id               string
 65	name             string
 66	impl             RandomnessProvider
 67	active           bool // approved by the admin and not deprecated
 68	registeredHeight int64
 69}
 70
 71var (
 72	providers       avl.Tree // provider pkgpath -> *providerRecord
 73	activeProviders int64
 74)
 75
 76const MaxProviderNameLen = 64
 77
 78// RegisterRandomnessProvider stores the calling realm's provider. It is
 79// inert until the admin approves it (randomness.add, timelocked).
 80func RegisterRandomnessProvider(cur realm, p RandomnessProvider) string {
 81	assertNoDeposit(cur)
 82	id := cur.Previous().PkgPath()
 83	if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
 84		panic("a randomness provider registers from its own realm (an /r/ package, not a sub-realm or wallet)")
 85	}
 86	if p == nil {
 87		panic("nil provider")
 88	}
 89	if providers.Has(id) {
 90		panic("randomness provider already registered: " + id)
 91	}
 92	name := p.Name()
 93	safe.AssertNonEmptyText("provider name", name, MaxProviderNameLen)
 94	providers.Set(id, &providerRecord{id: id, name: name, impl: p, registeredHeight: height()})
 95	chain.Emit("RandomnessProviderRegistered", "id", id, "name", name)
 96	return id
 97}
 98
 99func mustProvider(id string) *providerRecord {
100	v := providers.Get(id)
101	if v == nil {
102		panic("unknown randomness provider " + id)
103	}
104	return v.(*providerRecord)
105}
106
107func assertActiveProvider(id string) {
108	if !mustProvider(id).active {
109		panic("randomness provider " + id + " is not approved")
110	}
111}
112
113// beaconAvailable: some unpredictable second source exists, so no launch
114// may opt out of it (SA-M2).
115func beaconAvailable() bool { return beacon != "" || activeProviders > 0 }
116
117func usesProvider(c *collection) bool {
118	return c.useBeacon && c.beaconSource != types.BeaconCommitted
119}
120
121// RequestRandomness binds a provider-backed collection to the provider's
122// next unknowable round. Permissionless and never paused (I-2).
123func RequestRandomness(cur realm, cid string) int64 {
124	assertNoDeposit(cur)
125	c := mustCollection(cid)
126	h := height()
127	assertRevealOpen(c, h)
128	if !usesProvider(c) {
129		panic("this collection does not use a randomness provider")
130	}
131	p := c.prov
132	if p.round != 0 {
133		panic("randomness already requested for round " + itoa(p.round))
134	}
135	dl := revealDeadline(c)
136	if !p.creatorRevealed && h < dl-BeaconGraceBlocks {
137		panic("randomness is requested after the creator reveals, or in the window's last " +
138			itoa(BeaconGraceBlocks) + " blocks")
139	}
140	if h > dl-RequestMargin {
141		panic("too late to request randomness (last height " + itoa(dl-RequestMargin) + "); call Finalize after the deadline")
142	}
143	round := mustProvider(c.beaconSource).impl.Target()
144	if round <= 0 {
145		panic("randomness provider returned an invalid round")
146	}
147	p.round = round
148	chain.Emit("RandomnessRequested", "cid", cid, "provider", c.beaconSource, "round", itoa(round))
149	return round
150}
151
152// FulfillRandomness takes the requested round's value from the provider as
153// the beacon secret and finalizes (2/2 after the creator, beacon-only when
154// it stayed silent). Permissionless and never paused (I-2).
155func FulfillRandomness(cur realm, cid string) {
156	assertNoDeposit(cur)
157	c := mustCollection(cid)
158	h := height()
159	assertRevealOpen(c, h)
160	if !usesProvider(c) {
161		panic("this collection does not use a randomness provider")
162	}
163	p := c.prov
164	if p.round == 0 {
165		panic("randomness was not requested yet")
166	}
167	v := mustProvider(c.beaconSource).impl.Randomness(p.round)
168	if v == "" {
169		panic("round " + itoa(p.round) + " is not available from the provider yet")
170	}
171	v = safe.AssertHex("randomness", v, 32)
172	p.beaconSecret = v
173	p.beaconRevealed = true
174	chain.Emit("BeaconRevealed", "cid", cid, "provider", c.beaconSource, "round", itoa(p.round), "secret", v)
175	finalize(c, h)
176}
177
178// RandomnessProviders lists registered providers (by path) as JSON:
179// [{id, name, active, registeredHeight}]. Registration is open, so only
180// "active" ones (admin-approved) can be chosen at Launch.
181func RandomnessProviders(offset, limit int64) string {
182	w := &safe.JSONWriter{}
183	w.BeginArray()
184	providers.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
185		r := v.(*providerRecord)
186		w.BeginObject()
187		w.StrField("id", r.id)
188		w.StrField("name", r.name)
189		w.BoolField("active", r.active)
190		w.IntField("registeredHeight", r.registeredHeight)
191		w.EndObject()
192		return false
193	})
194	w.EndArray()
195	return w.String()
196}