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.

provenance.gno

10.62 Kb · 294 lines
  1package core
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6
  7	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
  8	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
  9)
 10
 11// Commit–reveal v2 (design §4.2–4.3, closes RA H-3, M-5, M-6).
 12//
 13// The map is fixed by three inputs: the creator's secret sc, the beacon's
 14// secret sb and the public mint-entropy accumulator acc. Neither committer
 15// knows the other's secret while minting is open, so neither can time the
 16// last mint for a good map. Order of reveals:
 17//
 18//  1. nothing is accepted before Closed (an early reveal informs the other
 19//     side);
 20//  2. the creator may reveal until revealDeadline - BeaconGraceBlocks; the
 21//     beacon follows at any time before the deadline;
 22//  3. inside the last BeaconGraceBlocks only the beacon may reveal. If the
 23//     creator stayed silent, the beacon's reveal finalizes at once
 24//     ("beacon-only"), so the creator never sees sb while it can still
 25//     choose (SA-M1; this also closes the mempool race of a creator
 26//     front-running the beacon's grace reveal);
 27//  4. after revealDeadline anyone finalizes with whatever was revealed.
 28//
 29// What stays open, by design: the beacon, as last revealer after the
 30// creator, can still choose between revealing and not (one bit). It runs
 31// public code and the badge shows the outcome. The transfer lock
 32// (tokens.gno) keeps anyone from trading on early knowledge until Final.
 33//
 34// The second secret sb comes from the committed beacon (below) or, when the
 35// collection was launched with a randomness provider, from the provider's
 36// round bound after the creator's turn (randomness.gno); the order rules and
 37// badges are the same.
 38//
 39// A collection launched without the beacon (only possible while no beacon
 40// or provider is configured, SA-M2) gives the creator the whole choice of the map; it
 41// can have no creator reserve and is never reported as a fair launch
 42// (FairLaunch, Provenance "fair").
 43type provenance struct {
 44	creatorCommit, beaconCommit string
 45	acc                         string
 46	creatorSecret, beaconSecret string
 47	creatorRevealed             bool
 48	beaconRevealed              bool
 49	salt, badge                 string
 50	finalHeight                 int64
 51	round                       int64 // randomness provider round (0 = none bound yet; randomness.gno)
 52	roundHeight                 int64 // height the round was bound at; its value is taken only later (CV-I6)
 53}
 54
 55const (
 56	roleCreator = "creator"
 57	roleBeacon  = "beacon"
 58)
 59
 60// BeaconCommit is the beacon's commitment, before any token exists.
 61func BeaconCommit(cur realm, cid, commitHex string) {
 62	assertNoDeposit(cur)
 63	c := mustCollection(cid)
 64	if beacon == "" || caller(cur) != beacon {
 65		panic("only the configured beacon can commit")
 66	}
 67	if c.state == types.StateDraft || c.prov == nil || !c.useBeacon || usesProvider(c) {
 68		panic("this collection is not waiting for a beacon")
 69	}
 70	if c.prov.beaconCommit != "" {
 71		panic("the beacon already committed")
 72	}
 73	if c.minted() > 0 {
 74		panic("too late: tokens were minted before the beacon committed")
 75	}
 76	commit := safe.AssertHex("commit", commitHex, 32)
 77	if isBurned(c, commit) {
 78		panic("this commitment's secret was already revealed for this collection")
 79	}
 80	c.prov.beaconCommit = commit
 81	chain.Emit("BeaconCommitted", "cid", cid, "commit", commit)
 82}
 83
 84func RevealCreatorSecret(cur realm, cid, secret string) {
 85	assertNoDeposit(cur)
 86	c := mustCollection(cid)
 87	assertCreator(cur, c)
 88	h := height()
 89	assertRevealOpen(c, h)
 90	if c.prov.creatorRevealed {
 91		panic("the creator secret is already revealed")
 92	}
 93	if c.useBeacon {
 94		// SA-M1: once the grace period starts only the beacon may reveal, so
 95		// the creator can never reveal after seeing sb.
 96		if c.prov.beaconRevealed {
 97			panic("the beacon revealed first; the outcome is fixed")
 98		}
 99		if h >= revealDeadline(c)-BeaconGraceBlocks {
100			panic("the creator's reveal window ended at height " + itoa(revealDeadline(c)-BeaconGraceBlocks-1) +
101				"; only the beacon may reveal now")
102		}
103	}
104	assertSecret(c, roleCreator, secret, c.prov.creatorCommit)
105	c.prov.creatorSecret = secret
106	c.prov.creatorRevealed = true
107	chain.Emit("CreatorRevealed", "cid", cid, "secret", secret)
108	if usesProvider(c) && c.prov.round == 0 {
109		// CV-M1: the reveal binds the provider's round in the same tx, so
110		// nobody can delay, time or skip the request afterwards. If the
111		// provider cannot name a fresh round now, anyone binds one later
112		// (RequestRandomness, Finalize); the creator's secret is public then.
113		bindRound(c, h)
114	}
115	if revealsComplete(c) {
116		finalize(c, h)
117	}
118}
119
120func RevealBeaconSecret(cur realm, cid, secret string) {
121	assertNoDeposit(cur)
122	c := mustCollection(cid)
123	if beacon == "" || caller(cur) != beacon {
124		panic("only the configured beacon can reveal")
125	}
126	h := height()
127	assertRevealOpen(c, h)
128	if !c.useBeacon || usesProvider(c) || c.prov.beaconCommit == "" {
129		panic("this collection has no beacon commitment")
130	}
131	if c.prov.beaconRevealed {
132		panic("the beacon secret is already revealed")
133	}
134	if !c.prov.creatorRevealed && h < revealDeadline(c)-BeaconGraceBlocks {
135		panic("the beacon reveals after the creator, or in the window's last " + itoa(BeaconGraceBlocks) + " blocks")
136	}
137	assertSecret(c, roleBeacon, secret, c.prov.beaconCommit)
138	c.prov.beaconSecret = secret
139	c.prov.beaconRevealed = true
140	chain.Emit("BeaconRevealed", "cid", cid, "secret", secret)
141	// After the creator: both secrets are in (2/2). First, in the grace
142	// period: the creator can no longer reveal, so the map is fixed now
143	// (beacon-only) — nobody is left holding a choice (SA-M1).
144	finalize(c, h)
145}
146
147// Finalize is permissionless and never paused (I-2): immediately once every
148// expected secret is revealed, otherwise after revealDeadline (fallback).
149// For a provider collection it first binds or consumes the provider's round
150// (settleProvider) and falls back only when the provider failed to deliver.
151func Finalize(cur realm, cid string) {
152	assertNoDeposit(cur)
153	c := mustCollection(cid)
154	h := height()
155	refresh(c, h)
156	if c.state != types.StateClosed {
157		panic("only a closed collection can be finalized (state " + c.state.String() + ")")
158	}
159	if !revealsComplete(c) && h <= revealDeadline(c) {
160		panic("the reveal window is open until height " + itoa(revealDeadline(c)))
161	}
162	// SA-I9: a sale that minted nothing stays Closed, so its creator can
163	// still abort and relaunch; nobody else can lock it into Final.
164	if c.minted() == 0 {
165		panic("nothing was minted; the creator may abort and relaunch instead")
166	}
167	// CV-M1: a provider collection consumes its round whoever calls; the
168	// fallback needs the provider to have failed for ProviderWaitBlocks.
169	if usesProvider(c) && settleProvider(c, h) {
170		return
171	}
172	finalize(c, h)
173}
174
175func assertRevealOpen(c *collection, h int64) {
176	refresh(c, h)
177	if c.state != types.StateClosed {
178		panic("secrets are accepted only after the sale closed (state " + c.state.String() + ")")
179	}
180	if h > revealDeadline(c) {
181		panic("the reveal window closed; call Finalize")
182	}
183}
184
185func assertSecret(c *collection, role, secret, commit string) {
186	if len(secret) < MinSecretLen || len(secret) > MaxSecretLen {
187		panic("secret must be " + itoa(MinSecretLen) + ".." + itoa(MaxSecretLen) + " bytes")
188	}
189	safe.AssertText("secret", secret, MaxSecretLen)
190	if safe.Commit(runtime.ChainID(), c.id, role, secret) != commit {
191		panic("secret does not match the " + role + " commitment")
192	}
193}
194
195func revealsComplete(c *collection) bool {
196	return c.prov.creatorRevealed && (!c.useBeacon || c.prov.beaconRevealed)
197}
198
199// finalize runs at most once per collection (I-10): every caller checks
200// state Closed, and this sets Final.
201func finalize(c *collection, h int64) {
202	p := c.prov
203	p.salt = safe.Salt(c.id, p.creatorSecret, p.beaconSecret, p.acc)
204	switch {
205	case p.creatorRevealed && p.beaconRevealed:
206		p.badge = BadgeBoth
207	case p.creatorRevealed:
208		p.badge = BadgeCreatorOnly
209	case p.beaconRevealed:
210		p.badge = BadgeBeaconOnly
211	default:
212		p.badge = BadgeFallback
213	}
214	p.finalHeight = h
215	c.state = types.StateFinal
216	c.st.final = true
217	chain.Emit("CollectionFinal", "cid", c.id, "salt", p.salt, "badge", p.badge)
218}
219
220// VerifyProvenance recomputes every commitment and the salt from public
221// data. True only for a Final collection whose record is consistent.
222func VerifyProvenance(cid string) bool {
223	c := mustCollection(cid)
224	if c.state != types.StateFinal {
225		return false
226	}
227	p := c.prov
228	chainID := runtime.ChainID()
229	if p.creatorRevealed && safe.Commit(chainID, c.id, roleCreator, p.creatorSecret) != p.creatorCommit {
230		return false
231	}
232	if p.beaconRevealed && !usesProvider(c) && safe.Commit(chainID, c.id, roleBeacon, p.beaconSecret) != p.beaconCommit {
233		return false
234	}
235	// A provider's value was checked when consumed (FulfillRandomness or
236	// Finalize) against the provider's verified round (p.round); it is recomputable off chain
237	// from the provider's public source (e.g. the drand round).
238	return p.salt == safe.Salt(c.id, p.creatorSecret, p.beaconSecret, p.acc)
239}
240
241// FairLaunch is true only for a Final, consistent collection whose map no
242// single party could choose: launched with the beacon and finalized with
243// both secrets or with the beacon's alone (after the creator stayed
244// silent). Creator-only collections (no beacon: the creator alone knew the
245// only secret and could steer the last mint, SA-M2) and fallbacks are not
246// fair launches, even when VerifyProvenance is true.
247func FairLaunch(cid string) bool {
248	c := mustCollection(cid)
249	if !VerifyProvenance(cid) || !c.useBeacon {
250		return false
251	}
252	return c.prov.badge == BadgeBoth || c.prov.badge == BadgeBeaconOnly
253}
254
255func isBurned(c *collection, commit string) bool {
256	for _, b := range c.burnedCommits {
257		if b == commit {
258			return true
259		}
260	}
261	return false
262}
263
264// Provenance is the whole record as JSON; secrets and salt stay "" until
265// revealed / final.
266func Provenance(cid string) string {
267	c := mustCollection(cid)
268	w := &safe.JSONWriter{}
269	w.BeginObject()
270	w.StrField("cid", c.id)
271	w.StrField("chainId", runtime.ChainID())
272	w.StrField("state", stateAt(c, height()).String())
273	w.IntField("minted", c.minted())
274	w.IntField("reserved", c.reserved)
275	if p := c.prov; p != nil {
276		w.BoolField("useBeacon", c.useBeacon)
277		w.StrField("beaconSource", c.beaconSource)
278		w.IntField("round", p.round)
279		w.IntField("roundHeight", p.roundHeight)
280		w.StrField("creatorCommit", p.creatorCommit)
281		w.StrField("beaconCommit", p.beaconCommit)
282		w.StrField("entropy", p.acc)
283		w.StrField("creatorSecret", p.creatorSecret)
284		w.StrField("beaconSecret", p.beaconSecret)
285		w.StrField("salt", p.salt)
286		w.StrField("badge", p.badge)
287		w.IntField("revealDeadline", revealDeadline(c))
288		w.IntField("finalHeight", p.finalHeight)
289		w.BoolField("verified", VerifyProvenance(cid))
290		w.BoolField("fair", FairLaunch(cid))
291	}
292	w.EndObject()
293	return w.String()
294}