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