engines.gno
21.03 Kb · 594 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/sinopia4/engine/v2"
12 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
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 deprecatedBy string // "author" or "admin" (engine.deprecate)
40 superseded bool // a reserved registration of the same art won (I-14)
41 supersededBy string // engine id
42 reviewed bool
43 registeredHeight int64
44 reservation string // reservationSource, reservationCommit or ""
45 priority int64 // 0 (in source), the reservation height, or registeredHeight
46 collections int64 // collections created on this engine (CollectionsByEngine)
47 policy string // PolicyClosed (at registration), PolicyLicensed or PolicyOpen (access.gno, I-19)
48 licences int64 // live licences (<= MaxLicencesPerEngine)
49}
50
51// Engine statuses (EngineStatus, engine JSON "status").
52const (
53 EngineUnclaimed = "unclaimed"
54 EngineUnverified = "unverified"
55 EngineReviewed = "reviewed"
56 EngineDeprecated = "deprecated"
57 EngineSuperseded = "superseded"
58)
59
60const (
61 reservationSource = "source" // fingerprint reserved in config.gno
62 reservationCommit = "commit" // backed by a ReserveFingerprint commitment
63)
64
65var (
66 engines avl.Tree // engine id -> *engineRecord
67 engineOrder avl.Tree // safe.PadInt(seq) -> engine id
68 byFingerprint avl.Tree // fingerprint + ":" + engine id -> "" (CV-L3)
69 byEngine avl.Tree // engine id + ":" + padded cid -> cid (CollectionsByEngine, M-18)
70 engineCount int64
71
72 // reservations: author + ":" + commit -> *fpReservation (ENG-M1). Keyed
73 // by author so copying a pending commitment from the mempool only
74 // creates a useless entry under the copier's own address.
75 reservations avl.Tree
76)
77
78type fpReservation struct {
79 height int64
80}
81
82// RegisterEngine stores the calling realm's engine (I-16: the manifest,
83// default params and one sample render with its traits, in the engine's
84// own registration transaction). The record is immutable afterwards except
85// for the claim/deprecate/review/superseded flags, the collection count and
86// the access policy (access.gno: every engine starts closed).
87//
88// salt is "" or the salt of a ReserveFingerprint commitment made by the
89// manifest author (ENG-M1 rule 2). Fingerprint rules (I-14), with signer =
90// OriginCaller:
91// - every registration must be signed by its manifest author (signer ==
92// Manifest.Author; WP-J J-2: otherwise a tx the author of a live engine
93// signs into a foreign realm could register a re-wrap of that art under
94// another author, since CV-L3 exempts the author's own versions);
95// - a fingerprint reserved in source (config.gno) registers only with
96// signer == Manifest.Author == its reserved author;
97// - a live record of the same art by another author (not deprecated, not
98// superseded) blocks the registration (CV-L3) unless this registration
99// is reserved in source, or backed by a reservation made before that
100// record's own priority (so the record was registered after the
101// reservation's commit; WP-J J-3), or the record is unclaimed and older
102// than UnclaimedHoldBlocks; such records are marked superseded instead.
103func RegisterEngine(cur realm, e engine.Engine, salt string) string {
104 id := cur.Previous().PkgPath()
105 if !strings.HasPrefix(id, runtime.ChainDomain()+"/r/") || strings.Contains(id, "#") {
106 panic("an engine registers from its own realm (an /r/ package, not a sub-realm or wallet)")
107 }
108 if e == nil {
109 panic("nil engine")
110 }
111 if engines.Has(id) {
112 panic("engine already registered: " + id + " (publish a new version under a new path)")
113 }
114 m := copyManifest(e.Manifest())
115 if err := engine.ValidateManifest(m); err != nil {
116 panic(err)
117 }
118 if err := e.ValidateParams(""); err != nil {
119 panic("engine must accept empty params (its defaults): " + err.Error())
120 }
121 sample := e.Render(engine.SampleInput())
122 if err := engine.CheckSVG(m, sample); err != nil {
123 panic("sample render: " + err.Error())
124 }
125 if err := engine.ValidateTraits(m, e.Traits(engine.SampleInput())); err != nil {
126 panic("sample traits: " + err.Error())
127 }
128
129 fp := safe.Sha256Hex(sample)
130 h := height()
131 signer := unsafe.OriginCaller()
132 kind, priority, resKey := registrationPriority(fp, m.Author, signer, salt, h)
133 losers := conflicts(fp, m.Author, kind, priority, h)
134 // every check passed: consume the reservation, then write
135 if resKey != "" {
136 reservations.Remove(resKey)
137 }
138 rec := &engineRecord{
139 id: id,
140 impl: e,
141 manifest: m,
142 fingerprint: fp,
143 registeredHeight: h,
144 reservation: kind,
145 priority: priority,
146 policy: PolicyClosed,
147 }
148 engines.Set(id, rec)
149 byFingerprint.Set(fp+":"+id, "")
150 engineCount++
151 engineOrder.Set(safe.PadInt(engineCount, cidWidth), id)
152 chain.Emit("EngineRegistered", "id", id, "author", m.Author.String(), "feeBps", itoa(m.FeeBps),
153 "fingerprint", rec.fingerprint, "kind", m.Kind, "reservation", kind)
154 for _, l := range losers {
155 l.superseded, l.supersededBy = true, id
156 chain.Emit("EngineSuperseded", "id", l.id, "by", id)
157 }
158 return id
159}
160
161// registrationPriority applies the reservation rules and returns the
162// registration's kind, priority (lower wins) and the reservation key it
163// consumes ("" for none). It writes nothing.
164func registrationPriority(fp string, author, signer address, salt string, h int64) (string, int64, string) {
165 if reserved, ok := reservedAuthorOf(fp); ok {
166 if signer != reserved || author != reserved {
167 panic("fingerprint " + fp + " is reserved for " + reserved.String() +
168 "; only that author may register it (signed by and named in the manifest)")
169 }
170 return reservationSource, 0, ""
171 }
172 if signer != author {
173 panic("an engine registration must be signed by the manifest author " + author.String())
174 }
175 if salt == "" {
176 return "", h, ""
177 }
178 if len(salt) < MinReserveSaltLen || len(salt) > MaxReserveSaltLen {
179 panic("reservation salt must be " + itoa(MinReserveSaltLen) + ".." + itoa(MaxReserveSaltLen) + " bytes")
180 }
181 safe.AssertText("salt", salt, MaxReserveSaltLen)
182 commit := ReservationCommit(runtime.ChainID(), fp, author, salt)
183 key := author.String() + ":" + commit
184 v := reservations.Get(key)
185 if v == nil {
186 panic("no fingerprint reservation of " + author.String() + " matches this engine and salt")
187 }
188 r := v.(*fpReservation)
189 if h <= r.height {
190 panic("the reservation is usable from height " + itoa(r.height+1))
191 }
192 if h > r.height+ReservationTTLBlocks {
193 panic("the reservation expired at height " + itoa(r.height+ReservationTTLBlocks))
194 }
195 return reservationCommit, r.height, key
196}
197
198// conflicts returns the live records of the same art by other authors that
199// this registration (by author, who signed it) supersedes, and panics on one
200// that blocks it (CV-L3, I-14). A deprecated or superseded record never
201// blocks.
202//
203// A commit reservation (priority = its ReserveFingerprint height) beats only
204// a record with a later priority: a plain record registered after the
205// commit height, or a record backed by a later reservation. A record
206// registered at or before the commit height — claimed or not — is never
207// superseded by it (WP-J J-3; rec.priority <= rec.registeredHeight, so a
208// later priority implies a later registration). Unclaimed records still
209// expire after UnclaimedHoldBlocks for every registration.
210func conflicts(fp string, author address, kind string, priority, h int64) []*engineRecord {
211 var losers []*engineRecord
212 byFingerprint.Iterate(fp+":", fp+";", func(k string, _ any) bool {
213 rec := mustEngine(k[len(fp)+1:])
214 if rec.deprecated || rec.superseded || rec.manifest.Author == author {
215 return false
216 }
217 switch {
218 case kind == reservationSource:
219 case !rec.claimed && h > rec.registeredHeight+UnclaimedHoldBlocks:
220 case kind == reservationCommit && rec.priority > priority && rec.registeredHeight > priority:
221 default:
222 panic("engine renders the same art as " + rec.id + "; only its author " + rec.manifest.Author.String() +
223 " may register another version (or deprecate it first)")
224 }
225 losers = append(losers, rec)
226 return false
227 })
228 return losers
229}
230
231// reservedAuthorOf is fp's in-source reserved author (config.gno).
232func reservedAuthorOf(fp string) (address, bool) {
233 for _, r := range reservedFingerprints {
234 if r.fingerprint == fp {
235 return r.author, true
236 }
237 }
238 return "", false
239}
240
241// ReserveFingerprint records a commitment to register an engine whose art
242// is not public yet (ENG-M1 rule 2):
243//
244// commit = ReservationCommit(chainId, fingerprint, author, salt)
245//
246// with salt 32..256 bytes. The caller (a wallet) is the author; the
247// reservation is usable from the next block for ReservationTTLBlocks by a
248// RegisterEngine(…, salt) signed by that author with that Manifest.Author.
249// The commitment reveals nothing, so it cannot be front-run.
250func ReserveFingerprint(cur realm, commitHex string) {
251 assertNoDeposit(cur)
252 if !cur.Previous().IsUserCall() {
253 panic("reserve a fingerprint from the author's wallet")
254 }
255 author := caller(cur)
256 commit := safe.AssertHex("commit", commitHex, 32)
257 key := author.String() + ":" + commit
258 h := height()
259 if v := reservations.Get(key); v != nil && h <= v.(*fpReservation).height+ReservationTTLBlocks {
260 panic("this commitment is already reserved until height " + itoa(v.(*fpReservation).height+ReservationTTLBlocks))
261 }
262 reservations.Set(key, &fpReservation{height: h})
263 chain.Emit("FingerprintReserved", "author", author.String(), "commit", commit,
264 "height", itoa(h), "expires", itoa(h+ReservationTTLBlocks))
265}
266
267// ReservationCommit is the commitment ReserveFingerprint takes:
268// sha256("art|fpres|v1|" + chainID + "|" + fp + "|" + author + "|" + salt).
269func ReservationCommit(chainID, fp string, author address, salt string) string {
270 return safe.Sha256Hex(safe.Domain + "|fpres|v1|" + chainID + "|" + fp + "|" + author.String() + "|" + salt)
271}
272
273// Reservation is the reservation of author for commitHex as JSON
274// {author, commit, height, validFrom, expires, active}, or null.
275func Reservation(author address, commitHex string) string {
276 v := reservations.Get(author.String() + ":" + commitHex)
277 if v == nil {
278 return "null"
279 }
280 r := v.(*fpReservation)
281 h := height()
282 w := &safe.JSONWriter{}
283 w.BeginObject()
284 w.StrField("author", author.String())
285 w.StrField("commit", commitHex)
286 w.IntField("height", r.height)
287 w.IntField("validFrom", r.height+1)
288 w.IntField("expires", r.height+ReservationTTLBlocks)
289 w.BoolField("active", h > r.height && h <= r.height+ReservationTTLBlocks)
290 w.EndObject()
291 return w.String()
292}
293
294// ReservedAuthor is fp's in-source reserved author, or "".
295func ReservedAuthor(fp string) address {
296 a, _ := reservedAuthorOf(fp)
297 return a
298}
299
300// ReservedFingerprints is the in-source table as JSON [{name, fingerprint, author}].
301func ReservedFingerprints() string {
302 w := &safe.JSONWriter{}
303 w.BeginArray()
304 for _, r := range reservedFingerprints {
305 w.BeginObject()
306 w.StrField("name", r.name)
307 w.StrField("fingerprint", r.fingerprint)
308 w.StrField("author", r.author.String())
309 w.EndObject()
310 }
311 w.EndArray()
312 return w.String()
313}
314
315// ClaimEngine proves the manifest author controls that address. Unclaimed
316// engines cannot back a collection.
317func ClaimEngine(cur realm, id string) {
318 assertNoDeposit(cur)
319 rec := mustEngine(id)
320 if caller(cur) != rec.manifest.Author {
321 panic("only the manifest author " + rec.manifest.Author.String() + " can claim this engine")
322 }
323 rec.claimed = true
324 chain.Emit("EngineClaimed", "id", id)
325}
326
327// DeprecateEngine stops new collections; existing ones keep rendering.
328func DeprecateEngine(cur realm, id string) {
329 assertNoDeposit(cur)
330 rec := mustEngine(id)
331 if !rec.claimed || caller(cur) != rec.manifest.Author {
332 panic("only the engine's author can deprecate it")
333 }
334 rec.deprecated, rec.deprecatedBy = true, "author"
335 chain.Emit("EngineDeprecated", "id", id, "by", "author")
336}
337
338// --- engine-author fee ---------------------------------------------------------
339//
340// An engine's author earns FeeBps (manifest, fixed at registration, <=
341// EngineFeeCapBps) of every primary and secondary sale of a collection that
342// uses the engine, capped by the platform's fees.EngineCapBps. A collection
343// snapshots the fee at Launch (like the protocol fee, SA-I5) and later sales
344// pay min(snapshot, current platform cap), so neither the author nor the
345// admin can raise it on a running collection. No fee when the creator is
346// the author: the creator's own payees already get the sale.
347
348// engineFeeOf is the engine's fee under the current platform cap.
349func engineFeeOf(rec *engineRecord) int64 {
350 if rec.manifest.FeeBps < fees.EngineCapBps {
351 return rec.manifest.FeeBps
352 }
353 return fees.EngineCapBps
354}
355
356// engineFeeQuote is what c would snapshot at a Launch now.
357func engineFeeQuote(c *collection) (address, int64) {
358 rec := mustEngine(c.engineID)
359 author := rec.manifest.Author
360 if author == c.creator {
361 return author, 0
362 }
363 if c.licenceFee == LicenceFeeDefault {
364 return author, engineFeeOf(rec)
365 }
366 if c.licenceFee < fees.EngineCapBps {
367 return author, c.licenceFee
368 }
369 return author, fees.EngineCapBps
370}
371
372// collectionEngineFee is the fee a sale of c pays now: the Launch snapshot
373// bounded by the current cap; before Launch, the current quote.
374func collectionEngineFee(c *collection) (address, int64) {
375 if c.prov == nil {
376 return engineFeeQuote(c)
377 }
378 if c.engineBps < fees.EngineCapBps {
379 return c.engineAuthor, c.engineBps
380 }
381 return c.engineAuthor, fees.EngineCapBps
382}
383
384// EngineFee is the engine-author share of cid's sales: the author and the
385// bps a sale pays now (0 when the creator is the author). mint/v1 and
386// market/v1 pay safe.BpsOf(amount, bps) to author.
387func EngineFee(cid string) (author address, bps int64) {
388 return collectionEngineFee(mustCollection(cid))
389}
390
391func mustEngine(id string) *engineRecord {
392 v := engines.Get(id)
393 if v == nil {
394 panic("unknown engine " + id)
395 }
396 return v.(*engineRecord)
397}
398
399// copyManifest gives core its own copy: the engine's slice was allocated in
400// the engine realm.
401func copyManifest(m engine.Manifest) engine.Manifest {
402 out := m
403 out.TraitTypes = append([]string{}, m.TraitTypes...)
404 return out
405}
406
407// --- engine reads (Studio, Verify) -------------------------------------------
408
409// RenderWith renders any registered engine for arbitrary params and seed as
410// a data URI — Studio previews and the Verify button. For a media engine it
411// is the card.
412func RenderWith(id, params, seed string) string {
413 return renderChecked(mustEngine(id), studioInput(params, seed))
414}
415
416// RenderWithInput is RenderWith for a full Input, so living engines can be
417// verified off chain and against their TS twins (M-24). CollectionID and
418// TokenID are "0" and Salt "" as in every studio render; firstOwner is
419// passed through as Input.FirstOwner ("" = none).
420func RenderWithInput(id, params, seed string, mintHeight, lastMove, moves, h int64, firstOwner address) string {
421 in := studioInput(params, seed)
422 in.MintHeight, in.LastMoveHeight, in.Moves, in.Height = mintHeight, lastMove, moves, h
423 in.FirstOwner = firstOwner
424 return renderChecked(mustEngine(id), in)
425}
426
427func renderChecked(rec *engineRecord, in engine.Input) string {
428 if err := rec.impl.ValidateParams(in.Params); err != nil {
429 panic("params rejected by engine: " + err.Error())
430 }
431 svg := rec.impl.Render(in)
432 if err := engine.CheckSVG(rec.manifest, svg); err != nil {
433 return dataURI(placeholderSVG(rec.manifest.Name, "Engine output rejected"))
434 }
435 return dataURI(svg)
436}
437
438// EngineTraits returns a core-owned copy of the engine's traits for seed,
439// checked against TraitTypes(params).
440func EngineTraits(id, params, seed string) []engine.Trait {
441 rec := mustEngine(id)
442 if err := rec.impl.ValidateParams(params); err != nil {
443 panic("params rejected by engine: " + err.Error())
444 }
445 tts := rec.impl.TraitTypes(params)
446 if err := engine.ValidateTraitTypes(tts); err != nil {
447 panic("trait types rejected: " + err.Error())
448 }
449 ts := rec.impl.Traits(studioInput(params, seed))
450 if err := engine.ValidateTraitsFor(tts, ts); err != nil {
451 panic("engine traits rejected: " + err.Error())
452 }
453 return append([]engine.Trait{}, ts...)
454}
455
456func TraitsWith(id, params, seed string) string {
457 w := &safe.JSONWriter{}
458 writeTraits(w, EngineTraits(id, params, seed))
459 return w.String()
460}
461
462// VerifyEngine re-renders the sample and compares it with the fingerprint
463// stored at registration.
464func VerifyEngine(id string) bool {
465 rec := mustEngine(id)
466 return safe.Sha256Hex(rec.impl.Render(engine.SampleInput())) == rec.fingerprint
467}
468
469// EngineManifest is the typed read for other realms (gallery).
470func EngineManifest(id string) engine.Manifest { return copyManifest(mustEngine(id).manifest) }
471
472// EngineStatus is "unclaimed", "unverified", "reviewed", "deprecated" or
473// "superseded".
474func EngineStatus(id string) string { return engineStatus(mustEngine(id)) }
475
476func engineStatus(rec *engineRecord) string {
477 switch {
478 case rec.deprecated:
479 return EngineDeprecated
480 case rec.superseded:
481 return EngineSuperseded
482 case !rec.claimed:
483 return EngineUnclaimed
484 case rec.reviewed:
485 return EngineReviewed
486 }
487 return EngineUnverified
488}
489
490// Engine is the record as JSON.
491func Engine(id string) string {
492 w := &safe.JSONWriter{}
493 writeEngine(w, mustEngine(id))
494 return w.String()
495}
496
497func Engines(offset, limit int64) string {
498 w := &safe.JSONWriter{}
499 w.BeginArray()
500 engineOrder.IterateByOffset(int(offset), int(clampLimit(limit)), func(_ string, v any) bool {
501 writeEngine(w, mustEngine(v.(string)))
502 return false
503 })
504 w.EndArray()
505 return w.String()
506}
507
508// EnginesByFingerprint pages every record with fingerprint fp, in path
509// order (the deploy check's squat scan).
510func EnginesByFingerprint(fp string, offset, limit int64) string {
511 w := &safe.JSONWriter{}
512 w.BeginArray()
513 skipped, written, want := int64(0), int64(0), clampLimit(limit)
514 byFingerprint.Iterate(fp+":", fp+";", func(k string, _ any) bool {
515 if skipped < offset {
516 skipped++
517 return false
518 }
519 writeEngine(w, mustEngine(k[len(fp)+1:]))
520 written++
521 return written >= want
522 })
523 w.EndArray()
524 return w.String()
525}
526
527// CollectionsByEngine pages the collections created on engine id, in
528// creation order (M-18). The count is the engine JSON's "collections".
529func CollectionsByEngine(id string, offset, limit int64) string {
530 mustEngine(id)
531 w := &safe.JSONWriter{}
532 w.BeginArray()
533 prefix := id + ":"
534 skipped, written, want := int64(0), int64(0), clampLimit(limit)
535 byEngine.Iterate(prefix, prefix+"\xff", func(_ string, v any) bool {
536 if skipped < offset {
537 skipped++
538 return false
539 }
540 writeCollection(w, mustCollection(v.(string)))
541 written++
542 return written >= want
543 })
544 w.EndArray()
545 return w.String()
546}
547
548func writeEngine(w *safe.JSONWriter, rec *engineRecord) {
549 m := rec.manifest
550 w.BeginObject()
551 w.StrField("id", rec.id)
552 w.StrField("pkgPath", rec.id) // the adapter realm; read its source (and imports) with vm/qfile
553 w.StrField("name", m.Name)
554 w.StrField("version", m.Version)
555 w.StrField("description", m.Description)
556 w.StrField("license", m.License)
557 w.StrField("author", m.Author.String())
558 w.IntField("feeBps", m.FeeBps)
559 w.IntField("effectiveFeeBps", engineFeeOf(rec))
560 w.StrField("paramsSchema", m.ParamsSchema)
561 w.Key("traitTypes")
562 writeStrings(w, m.TraitTypes)
563 w.BoolField("living", m.Living)
564 w.IntField("maxSvgBytes", m.MaxSVGBytes)
565 w.StrField("kind", m.Kind)
566 w.IntField("maxMediaBytes", m.MaxMediaBytes)
567 w.StrField("fingerprint", rec.fingerprint)
568 w.StrField("status", engineStatus(rec))
569 w.IntField("registeredHeight", rec.registeredHeight)
570 w.StrField("reservation", rec.reservation)
571 w.IntField("priority", rec.priority)
572 w.StrField("supersededBy", rec.supersededBy)
573 w.StrField("deprecatedBy", rec.deprecatedBy)
574 w.IntField("collections", rec.collections)
575 w.StrField("policy", rec.policy)
576 w.IntField("licences", rec.licences)
577 w.EndObject()
578}
579
580func writeStrings(w *safe.JSONWriter, list []string) {
581 w.BeginArray()
582 for _, t := range list {
583 w.Str(t)
584 }
585 w.EndArray()
586}
587
588func studioInput(params, seed string) engine.Input {
589 in := engine.SampleInput()
590 in.Seed = seed
591 in.Params = params
592 in.Height = height()
593 return in
594}