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.

drand.gno

8.36 Kb · 226 lines
  1// Package drand is a Sinopia randomness provider (core.RandomnessProvider)
  2// backed by the drand "evmnet" beacon, every round verified on chain.
  3//
  4// Verification is gno.land/p/drand/v0 from gnolang/gno#6268, imported from
  5// its unmodified copy in Sinopia's namespace (realms/p/drand/v0/README.md;
  6// pure Gno on the crypto/bn254, keccak256, modexp natives of gno v1.7.0):
  7// evmnet signs on BN254 (scheme bls-bn254-unchained-on-g1, one round every
  8// 3 s), and Verify checks e(sig, G2) == e(H(round), pk). The randomness of a
  9// round is sha256(signature), the same value drand's API serves.
 10//
 11// Trust: nobody. Submit is permissionless and only stores a round whose
 12// signature verifies against drand's group key, so a submitter can deliver
 13// a round or not, never choose or alter its value. Liveness needs at least
 14// one submitter (the Sinopia keeper, any relayer, the creator, a collector);
 15// if nobody submits, core falls back after ProviderWaitBlocks (CV-M1).
 16//
 17// How core uses it (realms/r/core/randomness.gno):
 18//
 19//  1. Target() is read in the transaction that binds a collection (the
 20//     creator's reveal, RequestRandomness in the grace period, or the first
 21//     Finalize after the deadline). It names the first evmnet round
 22//     published more than MarginSeconds after the current block time, so
 23//     its value is unknown to everyone, including the caller, when the bind
 24//     is committed. Nobody passes a round: the caller cannot choose one.
 25//  2. Anyone fetches that round from drand once it is published and calls
 26//     Submit(round, signature) here.
 27//  3. Anyone calls core.FulfillRandomness (or Finalize): core reads
 28//     Randomness(round) and finalizes.
 29//
 30// Clock assumptions (see README "drand provider"): time.Now() is the block
 31// header time, which tm2 sets to the median of the previous commit's vote
 32// times (BFT time), so a single proposer cannot move it. It lags wall clock by
 33// about one block (measured on Onyx: 4–7 s behind the newest block, blocks
 34// 3.3–5.4 s). MarginSeconds (30 s = 10 rounds) covers that lag, the 3 s
 35// propose timeout and ordinary validator clock skew. The one known case
 36// where block time is much older than wall clock is the first block after a
 37// chain halt (its time comes from the pre-halt commit); Target() then
 38// refuses (0) whenever a later round is already verified here, and core lets
 39// the bind happen later. An honest keeper submitting rounds as they are
 40// published makes that check effective.
 41package drand
 42
 43import (
 44	"chain"
 45	"encoding/binary"
 46	"encoding/hex"
 47	"strconv"
 48	"strings"
 49	"time"
 50
 51	evmnet "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/drand/v0"
 52	"gno.land/p/nt/avl/v0"
 53
 54	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/core"
 55)
 56
 57const (
 58	// MarginSeconds: Target() is the first round published more than this
 59	// many seconds after the block time (10 evmnet rounds).
 60	MarginSeconds = int64(30)
 61	// SigHexLen is an evmnet signature in hex (64 bytes, G1 point x|y).
 62	SigHexLen = 2 * evmnet.SigSize
 63	// maxList bounds Rounds() pages.
 64	maxList = 100
 65)
 66
 67var (
 68	beacons avl.Tree // 8-byte big-endian round -> 64 hex chars (sha256 of the signature)
 69	latest  int64    // highest round verified here (0: none)
 70)
 71
 72type provider struct{}
 73
 74// Name implements core.RandomnessProvider.
 75func (provider) Name() string { return "drand evmnet (BN254, 3 s)" }
 76
 77// Target implements core.RandomnessProvider: the round a bind made in the
 78// current block is tied to, or 0 when the block time is provably stale.
 79func (provider) Target() int64 { return target(time.Now().Unix()) }
 80
 81// Randomness implements core.RandomnessProvider: the verified randomness of
 82// round as 64 lowercase hex characters, or "" while nobody submitted it.
 83func (provider) Randomness(round int64) string {
 84	if round <= 0 {
 85		return ""
 86	}
 87	if v := beacons.Get(key(round)); v != nil {
 88		return v.(string)
 89	}
 90	return ""
 91}
 92
 93// target is the first round published strictly after now+MarginSeconds.
 94// It returns 0 (core: "cannot bind now, retry later") when that round is
 95// not newer than a round already verified here: the block time is then
 96// behind wall clock by more than the margin (e.g. the first block after a
 97// halt) and the round may already be public.
 98func target(now int64) int64 {
 99	r := TargetAt(now)
100	if r <= latest {
101		return 0
102	}
103	return r
104}
105
106// TargetAt is the round a bind at block time unix would get, without the
107// staleness check. For keepers and UIs.
108func TargetAt(unix int64) int64 {
109	return int64(evmnet.RoundAt(unix+MarginSeconds)) + 1
110}
111
112// TimeOf is the unix time at which evmnet publishes round.
113func TimeOf(round int64) int64 {
114	if round <= 0 {
115		return evmnet.GenesisTime
116	}
117	return evmnet.TimeOf(uint64(round))
118}
119
120// Submit verifies round's drand evmnet signature (hex, the "signature" field
121// of https://api.drand.sh/<ChainHash>/public/<round>) and stores its
122// randomness. Permissionless; the caller is never trusted. A round already
123// stored is a no-op (returns the stored value), so concurrent submitters
124// never fail each other. Returns the randomness (64 hex characters).
125func Submit(cur realm, round int64, signature string) string {
126	if round <= 0 {
127		panic("round must be positive")
128	}
129	if v := beacons.Get(key(round)); v != nil {
130		return v.(string)
131	}
132	if len(signature) != SigHexLen {
133		panic("signature must be " + strconv.Itoa(SigHexLen) + " hex characters (drand evmnet)")
134	}
135	sig, err := hex.DecodeString(signature)
136	if err != nil {
137		panic("signature is not hex")
138	}
139	if !evmnet.Verify(uint64(round), sig) {
140		panic("invalid drand evmnet signature for round " + itoa(round))
141	}
142	r := evmnet.Randomness(sig)
143	v := hex.EncodeToString(r[:])
144	beacons.Set(key(round), v)
145	if round > latest {
146		latest = round
147	}
148	chain.Emit("DrandBeacon", "round", itoa(round), "randomness", v)
149	return v
150}
151
152// Register registers this provider with Sinopia core (once; anyone may send
153// it). It stays inert until the admin approves it (timelocked
154// randomness.add).
155func Register(cur realm) string {
156	return core.RegisterRandomnessProvider(cross(cur), provider{})
157}
158
159// Has reports whether round's randomness is stored here.
160func Has(round int64) bool { return round > 0 && beacons.Has(key(round)) }
161
162// Latest is the highest round verified here (0 if none).
163func Latest() int64 { return latest }
164
165// Info returns the provider's parameters and state as JSON.
166func Info() string {
167	return `{"chainHash":"` + evmnet.ChainHash +
168		`","scheme":"` + evmnet.SchemeID +
169		`","genesis":` + itoa(evmnet.GenesisTime) +
170		`,"period":` + itoa(evmnet.Period) +
171		`,"marginSeconds":` + itoa(MarginSeconds) +
172		`,"latest":` + itoa(latest) +
173		`,"stored":` + itoa(int64(beacons.Size())) +
174		`,"target":` + itoa(target(time.Now().Unix())) + `}`
175}
176
177// Rounds lists stored rounds, newest first, as "round:randomness" lines.
178func Rounds(offset, limit int64) string {
179	if limit <= 0 || limit > maxList {
180		limit = maxList
181	}
182	if offset < 0 {
183		offset = 0
184	}
185	var b strings.Builder
186	n := int64(0)
187	beacons.ReverseIterate("", "", func(k string, v any) bool {
188		if n >= offset {
189			b.WriteString(itoa(keyRound(k)) + ":" + v.(string) + "\n")
190		}
191		n++
192		return n >= offset+limit
193	})
194	return b.String()
195}
196
197// Render shows the provider on gnoweb.
198func Render(path string) string {
199	var b strings.Builder
200	b.WriteString("# Sinopia randomness: drand evmnet\n\n")
201	b.WriteString("Public randomness from [drand](https://drand.love) evmnet, every round's BLS (BN254) signature verified on chain " +
202		"with `gno.land/p/drand/v0`. Anyone can `Submit(round, signature)`; nobody can choose or alter a value.\n\n")
203	b.WriteString("- chain hash: `" + evmnet.ChainHash + "`\n")
204	b.WriteString("- next bind target: round " + itoa(target(time.Now().Unix())) + " (margin " + itoa(MarginSeconds) + " s)\n")
205	b.WriteString("- latest verified round: " + itoa(latest) + "\n")
206	b.WriteString("- stored rounds: " + itoa(int64(beacons.Size())) + "\n\n")
207	if beacons.Size() > 0 {
208		b.WriteString("| round | randomness |\n|---|---|\n")
209		for _, line := range strings.Split(strings.TrimSpace(Rounds(0, 10)), "\n") {
210			i := strings.Index(line, ":")
211			b.WriteString("| " + line[:i] + " | `" + line[i+1:] + "` |\n")
212		}
213	}
214	return b.String()
215}
216
217// key encodes round as 8 big-endian bytes so avl order is numeric order.
218func key(round int64) string {
219	var k [8]byte
220	binary.BigEndian.PutUint64(k[:], uint64(round))
221	return string(k[:])
222}
223
224func keyRound(k string) int64 { return int64(binary.BigEndian.Uint64([]byte(k))) }
225
226func itoa(n int64) string { return strconv.FormatInt(n, 10) }