randomness.gno
11.07 Kb · 299 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/sinopia4/safe/v2"
11 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
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 if c.minted() == 0 { // SEC-F1 (SA-I9): a 0-mint sale stays abortable
149 panic("nothing was minted; the creator may abort and relaunch instead")
150 }
151 p := c.prov
152 if p.round != 0 {
153 panic("randomness already requested for round " + itoa(p.round))
154 }
155 if !p.creatorRevealed && h < revealDeadline(c)-BeaconGraceBlocks {
156 panic("randomness is requested after the creator reveals, or in the window's last " +
157 itoa(BeaconGraceBlocks) + " blocks")
158 }
159 if !bindRound(c, h) {
160 panic("randomness provider returned an invalid or already published round; retry in a later block")
161 }
162 return p.round
163}
164
165// FulfillRandomness takes the bound round's value from the provider as the
166// beacon secret and finalizes (2/2 after the creator, beacon-only when it
167// stayed silent). Permissionless and never paused (I-2); works before and
168// after the deadline while the collection is Closed.
169func FulfillRandomness(cur realm, cid string) {
170 assertNoDeposit(cur)
171 c := mustCollection(cid)
172 h := height()
173 refresh(c, h)
174 if c.state != types.StateClosed {
175 panic("secrets are accepted only after the sale closed (state " + c.state.String() + ")")
176 }
177 if !usesProvider(c) {
178 panic("this collection does not use a randomness provider")
179 }
180 if c.minted() == 0 { // SEC-F1 (SA-I9): a 0-mint sale stays abortable
181 panic("nothing was minted; the creator may abort and relaunch instead")
182 }
183 p := c.prov
184 if p.round == 0 {
185 panic("randomness was not requested yet")
186 }
187 if h <= p.roundHeight {
188 panic("round " + itoa(p.round) + " was bound in this block; fulfill it in a later one")
189 }
190 v := mustProvider(c.beaconSource).impl.Randomness(p.round)
191 if v == "" {
192 panic("round " + itoa(p.round) + " is not available from the provider yet")
193 }
194 consumeRound(c, safe.AssertHex("randomness", v, 32), h)
195}
196
197// bindRound fixes the collection's round to provider.Target() at height h.
198// It refuses (false) a non-positive round or one whose value the provider
199// already has: that value would be known before binding (CV-I6).
200func bindRound(c *collection, h int64) bool {
201 impl := mustProvider(c.beaconSource).impl
202 round := impl.Target()
203 if round <= 0 || isRandomness(impl.Randomness(round)) {
204 return false
205 }
206 c.prov.round, c.prov.roundHeight = round, h
207 chain.Emit("RandomnessRequested", "cid", c.id, "provider", c.beaconSource, "round", itoa(round))
208 return true
209}
210
211func consumeRound(c *collection, v string, h int64) {
212 p := c.prov
213 p.beaconSecret = v
214 p.beaconRevealed = true
215 chain.Emit("BeaconRevealed", "cid", c.id, "provider", c.beaconSource, "round", itoa(p.round), "secret", v)
216 finalize(c, h)
217}
218
219// providerWaitEnd is the last height at which Finalize still waits for the
220// provider: ProviderWaitBlocks after the deadline or the binding.
221func providerWaitEnd(c *collection) int64 {
222 from := revealDeadline(c)
223 if c.prov.roundHeight > from {
224 from = c.prov.roundHeight
225 }
226 return from + ProviderWaitBlocks
227}
228
229// settleProvider is Finalize's provider step after the deadline (CV-M1).
230// It returns true when Finalize is done: the round was bound now (a later
231// Finalize or FulfillRandomness takes its value), or its value finalized
232// the collection. It returns false only when the provider is provably
233// unavailable — no usable value after providerWaitEnd — and Finalize falls
234// back (creator-only / fallback, never a FairLaunch). While the bound round
235// may still arrive it refuses, so nobody can pick the fallback by not
236// fulfilling. After the wait a deprecated provider is not called at all
237// (escape hatch for a provider whose code aborts every call).
238func settleProvider(c *collection, h int64) bool {
239 p := c.prov
240 waited := h > providerWaitEnd(c)
241 if waited && !mustProvider(c.beaconSource).active {
242 return false
243 }
244 if p.round == 0 {
245 if bindRound(c, h) {
246 return true
247 }
248 if waited {
249 return false
250 }
251 panic("the randomness provider cannot bind a round now; retry later (fallback after height " +
252 itoa(providerWaitEnd(c)) + ")")
253 }
254 if h > p.roundHeight {
255 if v := mustProvider(c.beaconSource).impl.Randomness(p.round); isRandomness(v) {
256 consumeRound(c, safe.AssertHex("randomness", v, 32), h)
257 return true
258 }
259 }
260 if waited {
261 return false
262 }
263 panic("waiting for randomness round " + itoa(p.round) + " (FulfillRandomness once it is published; fallback after height " +
264 itoa(providerWaitEnd(c)) + ")")
265}
266
267// isRandomness: a provider value core accepts (64 hex characters).
268func isRandomness(v string) bool {
269 if len(v) != 64 {
270 return false
271 }
272 for i := 0; i < len(v); i++ {
273 c := v[i]
274 if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
275 return false
276 }
277 }
278 return true
279}
280
281// RandomnessProviders lists registered providers (by path) as JSON:
282// [{id, name, active, registeredHeight}]. Registration is open, so only
283// "active" ones (admin-approved) can be chosen at Launch.
284func RandomnessProviders(offset, limit int64) string {
285 w := &safe.JSONWriter{}
286 w.BeginArray()
287 providers.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
288 r := v.(*providerRecord)
289 w.BeginObject()
290 w.StrField("id", r.id)
291 w.StrField("name", r.name)
292 w.BoolField("active", r.active)
293 w.IntField("registeredHeight", r.registeredHeight)
294 w.EndObject()
295 return false
296 })
297 w.EndArray()
298 return w.String()
299}