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.

upload.gno

15.28 Kb · 495 lines
  1// Package upload is the engine/v1 adapter for uploaded collections
  2// (docs/uploaded-collections.md §5.3, §7–§10, §0a). Core knows it as one
  3// more engine; each collection's params name one sealed asset store
  4// ("store:<id>", r/…/assets/v1) and Bind locks that store to the collection
  5// while it is a Draft. After the reveal every token shows the artwork of the
  6// slot a salt-keyed permutation gives it.
  7//
  8// What holds, and why:
  9//   - art theft (T1): ValidateParams accepts a store only when its owner
 10//     signs the Create tx; Bind needs caller == collection creator == store
 11//     owner, from a wallet;
 12//   - no swap after sale (T2): stores are sealed before Bind and never
 13//     change; params are fixed by core; Bind and Unbind run only while core
 14//     says Draft, i.e. before any token was ever minted;
 15//   - one collection per store (T3); slots == maxSupply (T13);
 16//   - snipe resistance (T4/T5): before Final core shows its placeholder and
 17//     never calls Render/Traits; every read here checks Final too; the
 18//     assignment needs the final salt; Render answers core's real call only
 19//     (CollectionID, params and seed must match core's), so RenderWith
 20//     (CollectionID "0") always gets the generic card;
 21//   - SA-L5: this realm and assets/v1 may not be payees (Bind refuses);
 22//   - I-12: Render, Traits and ValidateParams only read; Bind, Unbind and
 23//     Settle are crossing functions; there is no exported non-crossing
 24//     mutator.
 25//
 26// The adapter is stateful by design (bindings and cached keys), declares
 27// Living false, takes no fee (D3) and holds no coins.
 28package upload
 29
 30import (
 31	"chain"
 32	"chain/runtime/unsafe"
 33	"errors"
 34	"strconv"
 35	"strings"
 36
 37	"gno.land/p/nt/avl/v0"
 38
 39	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
 40	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/media/v1"
 41	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
 42	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
 43	assets "gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/assets/v1"
 44	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia3/core"
 45)
 46
 47// author claims the engine in core (ClaimEngine).
 48// TODO(mainnet): the platform's engine-author key, not the deployer.
 49var author = address("g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06")
 50
 51func Author() address { return author }
 52
 53// FeeBps is the engine-author fee (D3: none; fixed forever at Register).
 54const FeeBps = 0
 55
 56// Core-path trait slots (engine/v1 manifests fix their trait types at
 57// registration, so creator trait types appear as "Trait k" = "<Type>: <Value>").
 58const (
 59	TraitTier    = "Creator tier"
 60	TraitArtwork = "Artwork"
 61	TraitEdition = "Edition"
 62	TraitStorage = "Storage"
 63	TraitSlots   = assets.MaxTraitTypes
 64)
 65
 66// MaxTraitsBatch bounds TraitsBatch (JSON); MaxTraitLists bounds the typed
 67// TraitLists the reader pages rarity counts with. Both compute the
 68// permutation key once per call (§0a), never per token.
 69// Sized so the worst store the asset limits allow stays <= 1B test gas per
 70// call (review UP-M1; r/reader/zz_worst_gas_test.gno).
 71const (
 72	MaxTraitsBatch    = 20  // JSON (was 50)
 73	MaxTraitJSONLists = 20  // typed, JSON per token (reader.Cards)
 74	MaxTraitLists     = 250 // typed (was 500)
 75	MaxTraitCounts    = 200 // TraitCounts (reader.TraitCounts)
 76)
 77
 78var (
 79	selfPath   string
 80	assetsPath string
 81
 82	bound avl.Tree // store id -> cid
 83	byCID avl.Tree // cid -> *binding
 84)
 85
 86type binding struct {
 87	store string
 88	salt  string // cached by Settle ("" = read core.Provenance)
 89	key   string // media.PermKey(cid, salt), cached by Settle
 90}
 91
 92func init(cur realm) {
 93	selfPath = cur.PkgPath()
 94	assetsPath = strings.TrimSuffix(selfPath, "/engines/upload") + "/assets/v1"
 95}
 96
 97// SelfPath and AssetsPath are the engine id and the store realm it reads.
 98func SelfPath() string   { return selfPath }
 99func AssetsPath() string { return assetsPath }
100
101// --- engine/v1 ---------------------------------------------------------------
102
103// impl is zero-size and declared here, so core runs it with this realm's
104// authority (interrealm v2 borrow rule #1).
105type impl struct{}
106
107func traitTypes() []string {
108	out := []string{TraitTier, TraitArtwork, TraitEdition, TraitStorage}
109	for k := 1; k <= TraitSlots; k++ {
110		out = append(out, "Trait "+strconv.Itoa(k))
111	}
112	return out
113}
114
115func (impl) Manifest() engine.Manifest {
116	return engine.Manifest{
117		Name:    "Sinopia Upload",
118		Version: "1.0.0",
119		Description: "Uploaded art: each token shows the artwork of its slot in a sealed asset store (assets/v1), " +
120			"assigned by a permutation keyed by the final salt. Stateful platform engine (store bindings); " +
121			"tiers and traits are assigned by the creator.",
122		License:     "artist's own",
123		Author:      author,
124		TraitTypes:  traitTypes(),
125		Living:      false,
126		MaxSVGBytes: media.MaxSVGBytes,
127		FeeBps:      FeeBps,
128	}
129}
130
131// ValidateParams accepts "" (registration, Studio) or exactly
132// "store:<id>" of an existing, sealed, unbound store whose owner signs this
133// transaction (art-theft guard). In qeval there is no signer, so store
134// params are refused there: intended (Studio never offers them). No writes.
135func (impl) ValidateParams(p string) error {
136	if p == "" {
137		return nil
138	}
139	id, ok := parseParams(p)
140	if !ok {
141		return errors.New("params must be store:<id>")
142	}
143	if !storeExists(id) {
144		return errors.New("unknown store " + id)
145	}
146	si := assets.Info(id)
147	if !si.Sealed {
148		return errors.New("store " + id + " is not sealed")
149	}
150	if v := bound.Get(id); v != nil {
151		return errors.New("store " + id + " is already bound to collection " + v.(string))
152	}
153	if si.Owner != unsafe.OriginCaller() {
154		return errors.New("store owner is not the signer")
155	}
156	return nil
157}
158
159func (impl) Render(in engine.Input) string {
160	r, ok := coreResolve(in)
161	if !ok {
162		return cardSVG
163	}
164	if r.art.Kind == media.KindChain && r.art.Mime == media.MimeSVG {
165		return assets.ArtworkBytes(r.store, r.art.Index) // passed AssertSVG(16 KiB) at upload; core re-checks
166	}
167	return certificateSVG(r)
168}
169
170func (impl) Traits(in engine.Input) []engine.Trait {
171	if in.Params == "" || in.CollectionID == "0" {
172		return []engine.Trait{}
173	}
174	r, ok := coreResolve(in)
175	if !ok {
176		return []engine.Trait{{Type: TraitStorage, Value: "Not bound"}}
177	}
178	a := r.art
179	var out []engine.Trait
180	if a.Tier != "" {
181		out = append(out, engine.Trait{Type: TraitTier, Value: a.Tier})
182	}
183	title := a.Title
184	if title == "" {
185		title = "#" + strconv.FormatInt(a.Index+1, 10)
186	}
187	out = append(out, engine.Trait{Type: TraitArtwork, Value: title})
188	if a.Editions > 1 {
189		out = append(out, engine.Trait{Type: TraitEdition, Value: editionLabel(r.edition, a.Editions)})
190	}
191	out = append(out, engine.Trait{Type: TraitStorage, Value: storageLabel(a.Kind)})
192	for k, v := range a.Traits {
193		if v != "" {
194			out = append(out, engine.Trait{Type: "Trait " + strconv.Itoa(k+1), Value: r.si.TraitTypes[k] + ": " + v})
195		}
196	}
197	return out
198}
199
200// Register is an explicit call (not init: under the inert package policy
201// init runs in the approver's tx). Anyone may call it, once.
202func Register(cur realm) string {
203	return core.RegisterEngine(cross(cur), impl{})
204}
205
206// --- binding -----------------------------------------------------------------
207
208// Bind locks the collection's store (its params "store:<id>") to the
209// collection. Caller == core creator == store owner, from a wallet; core
210// state Draft; the collection uses this engine; the store is sealed and not
211// bound elsewhere; maxSupply == the store's slots; no primary or royalty
212// payee is this realm or assets/v1 (SA-L5). Event StoreBound{store, cid}.
213func Bind(cur realm, cid string) {
214	assertWallet(cur)
215	who := cur.Previous().Address()
216	info := core.Info(cid)
217	assertUploadDraft(info, cid)
218	if who != info.Creator {
219		panic("only the collection's creator can bind its store")
220	}
221	id, ok := parseParams(info.Params)
222	if !ok || !storeExists(id) {
223		panic("collection " + cid + " has no store params (store:<id>)")
224	}
225	si := assets.Info(id)
226	if si.Owner != who {
227		panic("only the owner of store " + id + " can bind it")
228	}
229	if !si.Sealed {
230		panic("store " + id + " is not sealed")
231	}
232	if byCID.Has(cid) {
233		panic("collection " + cid + " is already bound")
234	}
235	if v := bound.Get(id); v != nil {
236		panic("store " + id + " is already bound to collection " + v.(string))
237	}
238	if info.MaxSupply != si.Slots {
239		panic("maxSupply " + strconv.FormatInt(info.MaxSupply, 10) + " must equal the store's slots " +
240			strconv.FormatInt(si.Slots, 10))
241	}
242	assertPayees(cid)
243	bound.Set(id, cid)
244	byCID.Set(cid, &binding{store: id})
245	chain.Emit("StoreBound", "store", id, "cid", cid)
246}
247
248// Unbind releases the store while the collection is still a Draft.
249// Creator only. Event StoreUnbound{store, cid}.
250func Unbind(cur realm, cid string) {
251	assertWallet(cur)
252	info := core.Info(cid)
253	assertUploadDraft(info, cid)
254	if cur.Previous().Address() != info.Creator {
255		panic("only the collection's creator can unbind its store")
256	}
257	v := byCID.Get(cid)
258	if v == nil {
259		panic("collection " + cid + " is not bound")
260	}
261	id := v.(*binding).store
262	byCID.Remove(cid)
263	bound.Remove(id)
264	chain.Emit("StoreUnbound", "store", id, "cid", cid)
265}
266
267// Settle caches the permutation key once the collection is Final. Anyone
268// may call it; it is deterministic (the salt is final) and idempotent, and
269// it only saves read gas: the lazy path computes the same key.
270// Event Settled{cid, key} (first call only).
271func Settle(cur realm, cid string) {
272	if cur.Previous().IsUserCall() && !unsafe.OriginSend().IsZero() {
273		panic("this function does not accept coins")
274	}
275	info := core.Info(cid)
276	if info.EngineID != selfPath {
277		panic("collection " + cid + " does not use the upload engine")
278	}
279	if info.State != types.StateFinal {
280		panic("collection " + cid + " is not final yet")
281	}
282	v := byCID.Get(cid)
283	if v == nil {
284		panic("collection " + cid + " is not bound to a store")
285	}
286	b := v.(*binding)
287	if b.key != "" {
288		return
289	}
290	salt := provenanceSalt(core.Provenance(cid))
291	if salt == "" {
292		panic("collection " + cid + " has no final salt")
293	}
294	b.salt = salt
295	b.key = media.PermKey(cid, salt)
296	chain.Emit("Settled", "cid", cid, "key", b.key)
297}
298
299func assertWallet(cur realm) {
300	if !cur.Previous().IsUserCall() {
301		panic("call this directly from a wallet")
302	}
303	if !unsafe.OriginSend().IsZero() {
304		panic("this function does not accept coins")
305	}
306}
307
308func assertUploadDraft(info types.CollectionInfo, cid string) {
309	if info.EngineID != selfPath {
310		panic("collection " + cid + " does not use the upload engine")
311	}
312	if info.State != types.StateDraft {
313		panic("collection " + cid + " is " + info.State.String() +
314			"; stores are bound or unbound only while it is a draft (no token was ever minted)")
315	}
316}
317
318// assertPayees refuses this realm and assets/v1 as primary or royalty
319// payees (SA-L5: neither can ever spend a payment). Core already refuses
320// itself, its sub-addresses, minters, the engine adapter and its siblings.
321func assertPayees(cid string) {
322	bad := []address{chain.PackageAddress(selfPath), chain.PackageAddress(assetsPath)}
323	var addrs []address
324	for _, p := range core.PrimaryPayees(cid) {
325		addrs = append(addrs, p.Addr)
326	}
327	for _, part := range strings.Split(jsonStrField(core.Collection(cid), "royaltyPayees"), ",") {
328		if a, _, ok := strings.Cut(part, ":"); ok {
329			addrs = append(addrs, address(a))
330		}
331	}
332	for _, a := range addrs {
333		for _, b := range bad {
334			if a == b {
335				panic("payee " + a.String() + " is a platform realm that cannot spend; use a wallet")
336			}
337		}
338	}
339}
340
341// jsonStrField reads a string field of core's JSON. Values written by
342// safe.JSONWriter escape '"', so the key pattern cannot be forged by user text.
343func jsonStrField(js, key string) string {
344	pat := `"` + key + `":"`
345	i := strings.Index(js, pat)
346	if i < 0 {
347		return ""
348	}
349	rest := js[i+len(pat):]
350	j := strings.IndexByte(rest, '"')
351	if j < 0 {
352		return ""
353	}
354	return rest[:j]
355}
356
357// provenanceSalt is the final salt from core.Provenance JSON ("" before
358// Final). The pattern `"salt":"` cannot be forged: JSONWriter escapes every
359// '"' inside a secret.
360func provenanceSalt(prov string) string {
361	s := jsonStrField(prov, "salt")
362	if !media.IsHex32(s) {
363		return ""
364	}
365	return s
366}
367
368// parseParams accepts exactly "store:<id>" with a canonical decimal id.
369func parseParams(p string) (string, bool) {
370	if !strings.HasPrefix(p, "store:") {
371		return "", false
372	}
373	id := p[len("store:"):]
374	if id == "" || len(id) > 10 || id[0] == '0' {
375		return "", false
376	}
377	for i := 0; i < len(id); i++ {
378		if id[i] < '0' || id[i] > '9' {
379			return "", false
380		}
381	}
382	return id, true
383}
384
385func storeExists(id string) bool {
386	n, err := strconv.ParseInt(id, 10, 64)
387	return err == nil && n >= 1 && n <= assets.StoreCount()
388}
389
390// tidNum is the numeric token id, 0 for a non-canonical one.
391func tidNum(tid string) int64 {
392	if tid == "" || len(tid) > 12 || tid[0] == '0' {
393		return 0
394	}
395	var n int64
396	for i := 0; i < len(tid); i++ {
397		c := tid[i]
398		if c < '0' || c > '9' {
399			return 0
400		}
401		n = n*10 + int64(c-'0')
402	}
403	return n
404}
405
406// --- resolution ----------------------------------------------------------------
407
408// resolved is one token's assignment.
409type resolved struct {
410	cid, tid      string
411	info          types.CollectionInfo
412	store         string
413	si            media.StoreInfo
414	key           string
415	slot, edition int64
416	art           media.Artwork
417}
418
419// coreResolve answers only core's own TokenURI/TokenTraits call for a
420// Final, bound collection: CollectionID, params and seed must be exactly
421// what core passes (§7 snipe resistance). Anything else gets the card.
422func coreResolve(in engine.Input) (resolved, bool) {
423	var r resolved
424	if in.Params == "" || in.CollectionID == "0" {
425		return r, false
426	}
427	v := byCID.Get(in.CollectionID)
428	if v == nil {
429		return r, false
430	}
431	b := v.(*binding)
432	if in.Params != "store:"+b.store {
433		return r, false
434	}
435	info := core.Info(in.CollectionID)
436	if info.EngineID != selfPath || info.State != types.StateFinal || info.Params != in.Params {
437		return r, false
438	}
439	salt := saltOf(in.CollectionID, b)
440	if salt == "" || in.Seed != safe.Seed(in.CollectionID, in.TokenID, salt) {
441		return r, false
442	}
443	n := tidNum(in.TokenID)
444	if n < 1 || n > info.MaxSupply {
445		return r, false
446	}
447	return assign(in.CollectionID, in.TokenID, n, info, b.store, assets.Info(b.store), keyOf(in.CollectionID, b, salt), nil), true
448}
449
450func saltOf(cid string, b *binding) string {
451	if b.salt != "" {
452		return b.salt
453	}
454	return provenanceSalt(core.Provenance(cid))
455}
456
457func keyOf(cid string, b *binding, salt string) string {
458	if b.key != "" {
459		return b.key
460	}
461	return media.PermKey(cid, salt)
462}
463
464// assign maps token n to its slot, artwork and edition. With a cache (trait
465// batches) artworks are read once per batch and without their hashes/CID
466// (assets.ArtworkMeta); without one the full record is read.
467func assign(cid, tid string, n int64, info types.CollectionInfo, store string, si media.StoreInfo, key string,
468	cache map[int64]media.Artwork,
469) resolved {
470	slot := media.Slot(key, si.Artworks, si.Slots, n)
471	idx, edition := assets.SlotArtwork(store, slot)
472	var a media.Artwork
473	if cache != nil {
474		if c, ok := cache[idx]; ok {
475			a = c
476		} else {
477			a = assets.ArtworkMeta(store, idx)
478			cache[idx] = a
479		}
480	} else {
481		a = assets.ArtworkAt(store, idx)
482	}
483	return resolved{cid: cid, tid: tid, info: info, store: store, si: si, key: key, slot: slot, edition: edition, art: a}
484}
485
486func editionLabel(e, of int64) string {
487	return strconv.FormatInt(e, 10) + "/" + strconv.FormatInt(of, 10)
488}
489
490func storageLabel(kind int) string {
491	if kind == media.KindChain {
492		return "On-chain"
493	}
494	return "IPFS"
495}