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.

engine.gno

14.47 Kb · 429 lines
  1// Package engine is the "art as code" contract, version 2 (design §5.2,
  2// mainnet plan §2.3): what an engine implements, what core hands it, and
  3// the conformance rules both core and engine authors check against.
  4//
  5// v2 adds media engines (uploaded raster/IPFS art that core itself can
  6// serve as TokenURI), per-collection trait types and a launch gate. Input,
  7// Trait, SampleInput and SampleSeed are byte-for-byte the v1 definitions,
  8// so an engine's sample fingerprint does not move when it is re-issued
  9// against v2.
 10//
 11// An engine is registered from its own /r/ adapter realm. Because the
 12// adapter's methods are declared in that realm, core calling them runs the
 13// engine with the adapter's authority, never core's (interrealm v2 borrow
 14// rule #1). Methods receive and return plain values only: an engine never
 15// gets a reference into core state.
 16package engine
 17
 18import (
 19	"errors"
 20	"strconv"
 21	"strings"
 22
 23	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
 24)
 25
 26// Input is everything an engine may depend on. The first eight fields are
 27// v1's; Salt and FirstOwner were added in the core-final round
 28// (2026-11-12). Core fills them only on a token read (TokenURI, TokenCard,
 29// TokenTraits, …) of a Final collection; RenderWith, RenderWithInput and
 30// the registration sample leave them "" (so no fingerprint moves).
 31type Input struct {
 32	Seed           string // 64-hex final seed (sample seeds in Studio)
 33	Params         string // collection params, in the engine's own format
 34	CollectionID   string
 35	TokenID        string
 36	MintHeight     int64
 37	LastMoveHeight int64 // patina: holding time = Height - LastMoveHeight
 38	Moves          int64 // transfers so far
 39	Height         int64 // height of the read (fixed by Verify)
 40	// Salt is the collection's final salt (64 hex; Seed = safe.Seed(cid,
 41	// tid, Salt)), so a collection-level engine needs no read-back of core.
 42	Salt string
 43	// FirstOwner is the address the token was minted to (a sale mint or a
 44	// creator reserve); it never changes, whoever holds the token now.
 45	FirstOwner address
 46}
 47
 48type Trait struct {
 49	Type, Value string
 50}
 51
 52// Engine kinds (Manifest.Kind).
 53const (
 54	// KindSVG: Render is the token's art (an allowlisted SVG).
 55	KindSVG = "svg"
 56	// KindMedia: Media is the token's art (a checked raster/SVG file or an
 57	// ipfs:// CIDv1); Render is the token's "card", an allowlisted SVG that
 58	// SVG-only clients and gnoweb show.
 59	KindMedia = "media"
 60)
 61
 62type Manifest struct {
 63	Name, Version, Description, License string
 64	Author                              address // proven by core.ClaimEngine
 65	ParamsSchema                        string  // JSON Schema subset; Studio builds its form from it
 66	// TraitTypes is the engine's default trait list. A collection uses
 67	// TraitTypes(params), stored by core at CreateCollection when it
 68	// differs; static engines return this list there.
 69	TraitTypes  []string
 70	Living      bool  // Render depends on LastMoveHeight/Moves/Height
 71	MaxSVGBytes int64 // <= MaxSVGBytes; for a media engine the card's cap
 72	// FeeBps is the author's fee on every primary and secondary sale of a
 73	// collection that uses this engine, 0..MaxFeeBps. It is fixed at
 74	// registration; core snapshots it per collection at Launch, caps it by
 75	// the platform's engine-fee cap and waives it when the collection's
 76	// creator is the author.
 77	FeeBps int64
 78	// Kind is KindSVG or KindMedia (required).
 79	Kind string
 80	// MaxMediaBytes caps Media.Data of a media engine: 1..MaxMediaBytes.
 81	// 0 for an SVG engine.
 82	MaxMediaBytes int64
 83}
 84
 85// Media is a media engine's art for one token. Exactly one of Data and URI
 86// is set. Data is the raw file (not base64) as a Go string: strings are
 87// immutable, so core can check and encode it without copying and without
 88// the engine being able to change it afterwards.
 89type Media struct {
 90	Mime   string // MimePNG | MimeWebP | MimeJPEG | MimeSVG
 91	Data   string // on-chain bytes, or ""
 92	URI    string // "ipfs://<CIDv1>" when Data is ""
 93	Sha256 string // lower-case hex of sha256(file); required with Data, optional with URI
 94}
 95
 96// IsZero reports an empty Media (what an SVG engine returns).
 97func (m Media) IsZero() bool {
 98	return m.Mime == "" && m.Data == "" && m.URI == "" && m.Sha256 == ""
 99}
100
101// Engine is implemented by a stateless value declared in the adapter realm.
102//
103// Contract: deterministic in its arguments; ValidateParams("") must accept
104// the engine's defaults; Render returns raw SVG (core does the base64);
105// Traits only uses types listed in TraitTypes(params), each at most once.
106//
107// Where core runs engine code (I-12/I-16): every read; and on a
108// state-changing path only in the engine user's own transaction —
109// RegisterEngine (Manifest, ValidateParams(""), Render and Traits of the
110// sample), CreateCollection (ValidateParams, TraitTypes) and Launch
111// (CheckLaunch). Core never hands an engine its cur.
112type Engine interface {
113	Manifest() Manifest
114	ValidateParams(params string) error
115	// TraitTypes is the trait list of a collection created with params
116	// (already accepted by ValidateParams). Static engines return
117	// Manifest().TraitTypes.
118	TraitTypes(params string) []string
119	// CheckLaunch is the engine's launch gate: an error aborts core.Launch
120	// (e.g. an upload collection without a bound store, T14). Everything it
121	// needs is passed in; nil for generative engines.
122	CheckLaunch(cid, params string, maxSupply int64) error
123	Traits(in Input) []Trait
124	// Render is the token's art (KindSVG) or its card (KindMedia).
125	Render(in Input) string
126	// Media is the token's art for KindMedia; Media{} for KindSVG.
127	Media(in Input) Media
128}
129
130// Limits core enforces on every engine.
131const (
132	MaxSVGBytes     = 65536
133	MaxTraits       = 32
134	MaxTraitLen     = 64
135	MaxNameLen      = 64
136	MaxVersionLen   = 32
137	MaxDescLen      = 1024
138	MaxLicenseLen   = 64
139	MaxParamsSchema = 4096
140	MaxFeeBps       = 500 // 5%: hard cap of an engine author's fee
141
142	// Media limits (I-15).
143	MaxMediaBytes    = 262144 // on-chain raster per token
144	MaxMediaSVGBytes = 16384  // on-chain SVG served as media (AssertSVG cost)
145	MaxDim           = 4096   // px per side, decompression-bomb guard
146)
147
148// Media types core serves (GIF is refused, uploads D5).
149const (
150	MimeSVG  = "image/svg+xml"
151	MimePNG  = "image/png"
152	MimeWebP = "image/webp"
153	MimeJPEG = "image/jpeg"
154)
155
156// IPFSScheme prefixes Media.URI.
157const IPFSScheme = "ipfs://"
158
159// SampleInput is the fixed input of an engine's fingerprint: core renders it
160// at registration and stores sha256(svg); anyone can recompute it later.
161// Identical to engine/v1's.
162func SampleInput() Input {
163	return Input{
164		Seed:           safe.Sha256Hex(safe.Domain + "|engine-sample|v1"),
165		CollectionID:   "0",
166		TokenID:        "0",
167		MintHeight:     1,
168		LastMoveHeight: 1,
169		Height:         1,
170	}
171}
172
173// SampleSeed returns the i-th Studio/conformance sample seed (as v1).
174func SampleSeed(i int) string {
175	return safe.Sha256Hex(safe.Domain + "|sample|v1|" + strconv.Itoa(i))
176}
177
178// ValidateManifest checks sizes, text hygiene, the author address and the
179// kind.
180func ValidateManifest(m Manifest) error {
181	fields := []struct {
182		name, value string
183		max         int
184		required    bool
185	}{
186		{"name", m.Name, MaxNameLen, true},
187		{"version", m.Version, MaxVersionLen, true},
188		{"description", m.Description, MaxDescLen, false},
189		{"license", m.License, MaxLicenseLen, false},
190		{"paramsSchema", m.ParamsSchema, MaxParamsSchema, false},
191	}
192	for _, f := range fields {
193		if f.required && f.value == "" {
194			return errors.New("manifest " + f.name + ": must not be empty")
195		}
196		if err := safe.CheckText(f.value, f.max); err != nil {
197			return errors.New("manifest " + f.name + ": " + err.Error())
198		}
199	}
200	if !m.Author.IsValid() {
201		return errors.New("manifest author: invalid address")
202	}
203	if err := ValidateTraitTypes(m.TraitTypes); err != nil {
204		return errors.New("manifest: " + err.Error())
205	}
206	if m.FeeBps < 0 || m.FeeBps > MaxFeeBps {
207		return errors.New("manifest feeBps: must be 0.." + strconv.Itoa(MaxFeeBps))
208	}
209	if m.MaxSVGBytes <= 0 || m.MaxSVGBytes > MaxSVGBytes {
210		return errors.New("manifest maxSVGBytes: must be 1.." + strconv.Itoa(MaxSVGBytes))
211	}
212	switch m.Kind {
213	case KindSVG:
214		if m.MaxMediaBytes != 0 {
215			return errors.New("manifest maxMediaBytes: must be 0 for an svg engine")
216		}
217	case KindMedia:
218		if m.MaxMediaBytes <= 0 || m.MaxMediaBytes > MaxMediaBytes {
219			return errors.New("manifest maxMediaBytes: must be 1.." + strconv.Itoa(MaxMediaBytes))
220		}
221	default:
222		return errors.New("manifest kind: must be " + KindSVG + " or " + KindMedia)
223	}
224	return nil
225}
226
227// ValidateTraitTypes checks a trait list: at most MaxTraits non-empty,
228// unique names that pass CheckText(MaxTraitLen).
229func ValidateTraitTypes(tts []string) error {
230	if len(tts) > MaxTraits {
231		return errors.New("too many trait types")
232	}
233	for i, tt := range tts {
234		if tt == "" {
235			return errors.New("empty trait type")
236		}
237		if err := safe.CheckText(tt, MaxTraitLen); err != nil {
238			return errors.New("trait type: " + err.Error())
239		}
240		for _, prev := range tts[:i] {
241			if prev == tt {
242				return errors.New("duplicate trait type " + tt)
243			}
244		}
245	}
246	return nil
247}
248
249// ValidateTraits checks one Traits() result against the manifest's trait
250// list (v1 signature; static engines).
251func ValidateTraits(m Manifest, ts []Trait) error {
252	return ValidateTraitsFor(m.TraitTypes, ts)
253}
254
255// ValidateTraitsFor checks one Traits() result against a collection's
256// trait list: known types, each at most once, values CheckText(MaxTraitLen).
257func ValidateTraitsFor(tts []string, ts []Trait) error {
258	if len(ts) > len(tts) {
259		return errors.New("traits: more traits than trait types")
260	}
261	for i, t := range ts {
262		if !contains(tts, t.Type) {
263			return errors.New("traits: unknown type: " + t.Type)
264		}
265		for _, prev := range ts[:i] {
266			if prev.Type == t.Type {
267				return errors.New("traits: duplicate type " + t.Type)
268			}
269		}
270		if err := safe.CheckText(t.Value, MaxTraitLen); err != nil {
271			return errors.New("traits " + t.Type + ": " + err.Error())
272		}
273	}
274	return nil
275}
276
277// CheckSVG is the output rule core applies to every render (art of an SVG
278// engine, card of a media engine).
279func CheckSVG(m Manifest, svg string) error {
280	return safe.AssertSVG(svg, int(m.MaxSVGBytes))
281}
282
283// CheckMedia is the rule core applies to a media engine's Media before it
284// serves it as TokenURI (I-15). Accepted:
285//
286//   - Data: Mime one of the four media types; SVG <= MaxMediaSVGBytes and
287//     AssertSVG; a raster <= min(m.MaxMediaBytes, MaxMediaBytes) whose
288//     magic and header dimensions (1..MaxDim) match Mime; Sha256 equal to
289//     sha256(Data);
290//   - URI: "ipfs://" + a CIDv1 (base32, raw or dag-pb, sha2-256); Mime one
291//     of the four types; Sha256 "" or 64 lower-case hex, and for a raw CID
292//     equal to the CID's digest.
293//
294// Everything else — both or neither set, another scheme, CIDv0, an unknown
295// mime — is an error.
296func CheckMedia(m Manifest, md Media) error {
297	if md.Data != "" && md.URI != "" {
298		return errors.New("media: data and uri are exclusive")
299	}
300	if !isMime(md.Mime) {
301		return errors.New("media: mime must be one of " + MimePNG + ", " + MimeWebP + ", " + MimeJPEG + ", " + MimeSVG)
302	}
303	if md.Sha256 != "" && !isLowerHex32(md.Sha256) {
304		return errors.New("media: sha256 must be 64 lower-case hex characters")
305	}
306	if md.Data != "" {
307		if md.Sha256 == "" {
308			return errors.New("media: sha256 is required with data")
309		}
310		if md.Mime == MimeSVG {
311			if len(md.Data) > MaxMediaSVGBytes {
312				return errors.New("media: svg larger than " + strconv.Itoa(MaxMediaSVGBytes) + " bytes")
313			}
314			if err := safe.AssertSVG(md.Data, MaxMediaSVGBytes); err != nil {
315				return err
316			}
317		} else {
318			limit := int64(MaxMediaBytes)
319			if m.MaxMediaBytes < limit {
320				limit = m.MaxMediaBytes
321			}
322			if int64(len(md.Data)) > limit {
323				return errors.New("media: file larger than " + strconv.FormatInt(limit, 10) + " bytes")
324			}
325			if err := safe.CheckImage(md.Mime, md.Data); err != nil {
326				return err
327			}
328		}
329		if safe.Sha256Hex(md.Data) != md.Sha256 {
330			return errors.New("media: sha256 does not match the data")
331		}
332		return nil
333	}
334	if md.URI == "" {
335		return errors.New("media: neither data nor uri")
336	}
337	if !strings.HasPrefix(md.URI, IPFSScheme) {
338		return errors.New("media: uri must be " + IPFSScheme + "<CIDv1>")
339	}
340	codec, digest, err := safe.ParseCIDv1(md.URI[len(IPFSScheme):])
341	if err != nil {
342		return err
343	}
344	if codec == safe.CodecRaw && md.Sha256 != "" && md.Sha256 != digest {
345		return errors.New("media: sha256 does not match the raw CID's digest")
346	}
347	return nil
348}
349
350// Conformance is the self-test engine authors run in their _test.gno
351// before registering: manifest, default params and trait types,
352// determinism, size, SVG hygiene, traits, media (KindMedia: CheckMedia or
353// Media{}; KindSVG: Media{}), and — for non-living engines — independence
354// from the living fields.
355func Conformance(e Engine, samples int) error {
356	m := e.Manifest()
357	if err := ValidateManifest(m); err != nil {
358		return err
359	}
360	if err := e.ValidateParams(""); err != nil {
361		return errors.New("default params rejected: " + err.Error())
362	}
363	tts := e.TraitTypes("")
364	if err := ValidateTraitTypes(tts); err != nil {
365		return errors.New("default trait types: " + err.Error())
366	}
367	inputs := []Input{SampleInput()}
368	for i := 0; i < samples; i++ {
369		in := SampleInput()
370		in.Seed = SampleSeed(i)
371		in.TokenID = strconv.Itoa(i + 1)
372		inputs = append(inputs, in)
373	}
374	for _, in := range inputs {
375		svg := e.Render(in)
376		if svg != e.Render(in) {
377			return errors.New("render is not deterministic for seed " + in.Seed)
378		}
379		if err := CheckSVG(m, svg); err != nil {
380			return errors.New("seed " + in.Seed + ": " + err.Error())
381		}
382		if err := ValidateTraitsFor(tts, e.Traits(in)); err != nil {
383			return errors.New("seed " + in.Seed + ": " + err.Error())
384		}
385		md := e.Media(in)
386		if m.Kind == KindSVG && !md.IsZero() {
387			return errors.New("an svg engine returns Media{}")
388		}
389		if m.Kind == KindMedia && !md.IsZero() {
390			if err := CheckMedia(m, md); err != nil {
391				return errors.New("seed " + in.Seed + ": " + err.Error())
392			}
393		}
394		if !m.Living {
395			moved := in
396			moved.Height, moved.Moves, moved.LastMoveHeight = in.Height+1000, in.Moves+3, in.Height+500
397			if e.Render(moved) != svg {
398				return errors.New("non-living engine depends on Height/Moves/LastMoveHeight")
399			}
400		}
401	}
402	return nil
403}
404
405func isMime(s string) bool {
406	return s == MimePNG || s == MimeWebP || s == MimeJPEG || s == MimeSVG
407}
408
409func isLowerHex32(s string) bool {
410	if len(s) != 64 {
411		return false
412	}
413	for i := 0; i < len(s); i++ {
414		c := s[i]
415		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
416			return false
417		}
418	}
419	return true
420}
421
422func contains(list []string, s string) bool {
423	for _, x := range list {
424		if x == s {
425			return true
426		}
427	}
428	return false
429}