engines.gno
10.39 Kb · 313 lines
1package core
2
3import (
4 "chain"
5 "chain/runtime"
6 "chain/runtime/unsafe"
7 "strings"
8
9 "gno.land/p/nt/avl/v0"
10
11 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
12 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
13)
14
15// Engine registry ("art as code", design §5).
16//
17// An engine registers itself from its own /r/ adapter realm; its id is that
18// realm's package path, so nobody can register in someone else's name. The
19// stored interface value's methods are declared in the adapter, so every
20// call runs with the adapter's authority, not core's (interrealm v2 borrow
21// rule #1): engine code cannot write core state. It also cannot call back
22// into a core mutator: all of core's state-changing functions are crossing
23// and need a live cur the engine never has.
24//
25// Honest limits, surfaced to users rather than hidden:
26// - an adapter realm with state could change its art later; the sample
27// fingerprint (VerifyEngine) detects a change of the sample, and review
28// means reading the adapter for statelessness;
29// - a private (re-deployable) adapter cannot register: the VM aborts the
30// registration when core's state would retain the private realm's type
31// (spike A9, observed in gno v1.7.0 test mode; confirm on Onyx).
32type engineRecord struct {
33 id string
34 impl engine.Engine
35 manifest engine.Manifest // core-owned copy
36 fingerprint string // sha256 of Render(SampleInput())
37 claimed bool
38 deprecated bool
39 reviewed bool
40 registeredHeight int64
41}
42
43var (
44 engines avl.Tree // engine id -> *engineRecord
45 engineOrder avl.Tree // safe.PadInt(seq) -> engine id
46 byFingerprint avl.Tree // fingerprint + ":" + engine id -> "" (CV-L3)
47 engineCount int64
48)
49
50// RegisterEngine stores the calling realm's engine (I-12 exception: one
51// sample render in the engine's own registration transaction). The record
52// is immutable afterwards except for the claim/deprecate/review flags.
53func RegisterEngine(cur realm, e engine.Engine) string {
54 id := cur.Previous().PkgPath()
55 if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
56 panic("an engine registers from its own realm (an /r/ package, not a sub-realm or wallet)")
57 }
58 if e == nil {
59 panic("nil engine")
60 }
61 if engines.Has(id) {
62 panic("engine already registered: " + id + " (publish a new version under a new path)")
63 }
64 m := copyManifest(e.Manifest())
65 if err := engine.ValidateManifest(m); err != nil {
66 panic(err)
67 }
68 if err := e.ValidateParams(""); err != nil {
69 panic("engine must accept empty params (its defaults): " + err.Error())
70 }
71 sample := e.Render(engine.SampleInput())
72 if err := engine.CheckSVG(m, sample); err != nil {
73 panic("sample render: " + err.Error())
74 }
75 if err := engine.ValidateTraits(m, e.Traits(engine.SampleInput())); err != nil {
76 panic("sample traits: " + err.Error())
77 }
78
79 fp := safe.Sha256Hex(sample)
80 assertNotRewrap(fp)
81 rec := &engineRecord{
82 id: id,
83 impl: e,
84 manifest: m,
85 fingerprint: fp,
86 registeredHeight: height(),
87 }
88 engines.Set(id, rec)
89 byFingerprint.Set(fp+":"+id, "")
90 engineCount++
91 engineOrder.Set(safe.PadInt(engineCount, cidWidth), id)
92 chain.Emit("EngineRegistered", "id", id, "author", m.Author.String(), "feeBps", itoa(m.FeeBps),
93 "fingerprint", rec.fingerprint)
94 return id
95}
96
97// assertNotRewrap refuses a second engine with the same art (same sample
98// fingerprint) as a live registered one unless the transaction is signed
99// by that engine's author (a new version): wrapping the public /p/ art of
100// someone else's engine in an own adapter with no fee would make the
101// engine-author fee optional (CV-L3). A deprecated engine no longer blocks.
102// A one-byte change of the sample defeats this; the reviewed badge and the
103// gallery's "same art as" hint cover that.
104func assertNotRewrap(fp string) {
105 signer := unsafe.OriginCaller()
106 byFingerprint.Iterate(fp+":", fp+";", func(k string, _ any) bool {
107 rec := mustEngine(k[len(fp)+1:])
108 if !rec.deprecated && rec.manifest.Author != signer {
109 panic("engine renders the same art as " + rec.id + "; only its author " + rec.manifest.Author.String() +
110 " may register another version (or deprecate it first)")
111 }
112 return false
113 })
114}
115
116// ClaimEngine proves the manifest author controls that address. Unclaimed
117// engines cannot back a collection.
118func ClaimEngine(cur realm, id string) {
119 assertNoDeposit(cur)
120 rec := mustEngine(id)
121 if caller(cur) != rec.manifest.Author {
122 panic("only the manifest author " + rec.manifest.Author.String() + " can claim this engine")
123 }
124 rec.claimed = true
125 chain.Emit("EngineClaimed", "id", id)
126}
127
128// DeprecateEngine stops new collections; existing ones keep rendering.
129func DeprecateEngine(cur realm, id string) {
130 assertNoDeposit(cur)
131 rec := mustEngine(id)
132 if !rec.claimed || caller(cur) != rec.manifest.Author {
133 panic("only the engine's author can deprecate it")
134 }
135 rec.deprecated = true
136 chain.Emit("EngineDeprecated", "id", id)
137}
138
139// --- engine-author fee ---------------------------------------------------------
140//
141// An engine's author earns FeeBps (manifest, fixed at registration, <=
142// EngineFeeCapBps) of every primary and secondary sale of a collection that
143// uses the engine, capped by the platform's fees.EngineCapBps. A collection
144// snapshots the fee at Launch (like the protocol fee, SA-I5) and later sales
145// pay min(snapshot, current platform cap), so neither the author nor the
146// admin can raise it on a running collection. No fee when the creator is
147// the author: the creator's own payees already get the sale.
148
149// engineFeeOf is the engine's fee under the current platform cap.
150func engineFeeOf(rec *engineRecord) int64 {
151 if rec.manifest.FeeBps < fees.EngineCapBps {
152 return rec.manifest.FeeBps
153 }
154 return fees.EngineCapBps
155}
156
157// engineFeeQuote is what c would snapshot at a Launch now.
158func engineFeeQuote(c *collection) (address, int64) {
159 rec := mustEngine(c.engineID)
160 author := rec.manifest.Author
161 if author == c.creator {
162 return author, 0
163 }
164 return author, engineFeeOf(rec)
165}
166
167// collectionEngineFee is the fee a sale of c pays now: the Launch snapshot
168// bounded by the current cap; before Launch, the current quote.
169func collectionEngineFee(c *collection) (address, int64) {
170 if c.prov == nil {
171 return engineFeeQuote(c)
172 }
173 if c.engineBps < fees.EngineCapBps {
174 return c.engineAuthor, c.engineBps
175 }
176 return c.engineAuthor, fees.EngineCapBps
177}
178
179// EngineFee is the engine-author share of cid's sales: the author and the
180// bps a sale pays now (0 when the creator is the author). mint/v1 and
181// market/v1 pay safe.BpsOf(amount, bps) to author.
182func EngineFee(cid string) (author address, bps int64) {
183 return collectionEngineFee(mustCollection(cid))
184}
185
186func mustEngine(id string) *engineRecord {
187 v := engines.Get(id)
188 if v == nil {
189 panic("unknown engine " + id)
190 }
191 return v.(*engineRecord)
192}
193
194// copyManifest gives core its own copy: the engine's slice was allocated in
195// the engine realm.
196func copyManifest(m engine.Manifest) engine.Manifest {
197 out := m
198 out.TraitTypes = append([]string{}, m.TraitTypes...)
199 return out
200}
201
202// --- engine reads (Studio, Verify) -------------------------------------------
203
204// RenderWith renders any registered engine for arbitrary params and seed as
205// a data URI — Studio previews and the Verify button.
206func RenderWith(id, params, seed string) string {
207 rec := mustEngine(id)
208 if err := rec.impl.ValidateParams(params); err != nil {
209 panic("params rejected by engine: " + err.Error())
210 }
211 svg := rec.impl.Render(studioInput(params, seed))
212 if err := engine.CheckSVG(rec.manifest, svg); err != nil {
213 return dataURI(placeholderSVG(rec.manifest.Name, "Engine output rejected"))
214 }
215 return dataURI(svg)
216}
217
218// EngineTraits returns a core-owned copy of the engine's traits for seed.
219func EngineTraits(id, params, seed string) []engine.Trait {
220 rec := mustEngine(id)
221 if err := rec.impl.ValidateParams(params); err != nil {
222 panic("params rejected by engine: " + err.Error())
223 }
224 ts := rec.impl.Traits(studioInput(params, seed))
225 if err := engine.ValidateTraits(rec.manifest, ts); err != nil {
226 panic("engine traits rejected: " + err.Error())
227 }
228 return append([]engine.Trait{}, ts...)
229}
230
231func TraitsWith(id, params, seed string) string {
232 w := &safe.JSONWriter{}
233 writeTraits(w, EngineTraits(id, params, seed))
234 return w.String()
235}
236
237// VerifyEngine re-renders the sample and compares it with the fingerprint
238// stored at registration.
239func VerifyEngine(id string) bool {
240 rec := mustEngine(id)
241 return safe.Sha256Hex(rec.impl.Render(engine.SampleInput())) == rec.fingerprint
242}
243
244// EngineManifest is the typed read for other realms (gallery).
245func EngineManifest(id string) engine.Manifest { return copyManifest(mustEngine(id).manifest) }
246
247// EngineStatus is "unclaimed", "unverified", "reviewed" or "deprecated".
248func EngineStatus(id string) string { return engineStatus(mustEngine(id)) }
249
250func engineStatus(rec *engineRecord) string {
251 switch {
252 case rec.deprecated:
253 return "deprecated"
254 case !rec.claimed:
255 return "unclaimed"
256 case rec.reviewed:
257 return "reviewed"
258 }
259 return "unverified"
260}
261
262// Engine is the record as JSON.
263func Engine(id string) string {
264 w := &safe.JSONWriter{}
265 writeEngine(w, mustEngine(id))
266 return w.String()
267}
268
269func Engines(offset, limit int64) string {
270 w := &safe.JSONWriter{}
271 w.BeginArray()
272 engineOrder.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
273 writeEngine(w, mustEngine(v.(string)))
274 return false
275 })
276 w.EndArray()
277 return w.String()
278}
279
280func writeEngine(w *safe.JSONWriter, rec *engineRecord) {
281 m := rec.manifest
282 w.BeginObject()
283 w.StrField("id", rec.id)
284 w.StrField("pkgPath", rec.id) // the adapter realm; read its source (and imports) with vm/qfile
285 w.StrField("name", m.Name)
286 w.StrField("version", m.Version)
287 w.StrField("description", m.Description)
288 w.StrField("license", m.License)
289 w.StrField("author", m.Author.String())
290 w.IntField("feeBps", m.FeeBps)
291 w.IntField("effectiveFeeBps", engineFeeOf(rec))
292 w.StrField("paramsSchema", m.ParamsSchema)
293 w.Key("traitTypes")
294 w.BeginArray()
295 for _, t := range m.TraitTypes {
296 w.Str(t)
297 }
298 w.EndArray()
299 w.BoolField("living", m.Living)
300 w.IntField("maxSvgBytes", m.MaxSVGBytes)
301 w.StrField("fingerprint", rec.fingerprint)
302 w.StrField("status", engineStatus(rec))
303 w.IntField("registeredHeight", rec.registeredHeight)
304 w.EndObject()
305}
306
307func studioInput(params, seed string) engine.Input {
308 in := engine.SampleInput()
309 in.Seed = seed
310 in.Params = params
311 in.Height = height()
312 return in
313}