assets.gno
25.55 Kb · 820 lines
1// Package assets is Sinopia's immutable asset store for uploaded
2// collections (docs/uploaded-collections.md §4–§6, §0a). An artist creates a
3// store, declares artworks (on-chain bytes or IPFS CIDs, each with its
4// sha256, editions, a creator-assigned tier and trait values), uploads the
5// on-chain bytes in chunks, and seals it. A sealed store never changes: the
6// upload engine (r/…/engines/upload) binds one sealed store to one Draft
7// collection and reads its art from here.
8//
9// Guarantees (design §14):
10// - only the store's owner writes, and only from a wallet (direct
11// MsgCall, IsUserCall); nothing here accepts or holds coins;
12// - a store is Draft until Seal, which is irreversible: records, titles,
13// dictionaries and bytes are immutable afterwards;
14// - an "on-chain" artwork is complete only when every byte is stored,
15// its sha256 equals the declared one and media.CheckImage passed
16// (magic + dimensions; SVG through safe.AssertSVG, 16 KiB cap);
17// - an "ipfs" artwork always says ipfs; a raw CID's digest is checked
18// against the declared sha256 on chain;
19// - every user string passed safe.AssertText and assertPlain (no
20// '<', '>', '&', '"', '\'); JSON goes through safe.JSONWriter.
21//
22// Storage is paid by the owner who writes it, and only the owner can free
23// Draft data (Truncate), so refunds go back to the payer (T8).
24//
25// sinopia4 (mainnet plan WP-F): imports p/media/v2 and p/safe/v2 instead of
26// v1; the store logic, limits, record encoding and JSON bytes are
27// unchanged. media/v2's CheckImage and CID functions delegate to safe/v2,
28// the same checks core applies to an engine's media (I-15). WP-Z: every
29// user string it stores (label, trait type and tier names, titles, values)
30// refuses '<', '>', '&', '"' and '\' (assertPlain), so core and the reader
31// JSON-escape upload text on safe/v2's native fast path (worst-store reader
32// gas, wp-d-notes "Reader worst store", option 1).
33package assets
34
35import (
36 "chain"
37 "chain/markdown"
38 "chain/runtime"
39 "chain/runtime/unsafe"
40 "crypto/sha256"
41 "encoding/hex"
42 "strconv"
43 "strings"
44
45 "gno.land/p/nt/avl/v0"
46
47 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/media/v2"
48 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
49)
50
51// Limits (design §4 as amended by §0a / D4, and by the UP-M1 review fix:
52// every read of the largest store these limits allow must stay far below
53// the 3B query gas cap; worst cases are locked by zz_worst_gas_test.gno in
54// r/reader).
55const (
56 MaxArtworks = 10_000 // = core MaxSupplyCap
57 MaxSlots = 10_000 // Bind requires slots == maxSupply
58 MaxEditions = 10_000
59 MaxTraitTypes = 8 // core-path manifest slots "Trait 1".."Trait 8" (was 16)
60 MaxTiers = 8
61 MaxDictValues = 100 // distinct values per trait type (was 255)
62 MaxStoreValues = 255 // distinct values over all trait types of a store (new; u8 id + 1 in a record)
63 MaxNameLen = 20 // trait type and tier names
64 MaxValueLen = 32 // trait values (was 40)
65 MaxTitleLen = 64 // artwork titles (= engine.MaxTraitLen)
66 MaxLabelLen = 64
67 MaxStoreOnchainBytes = 4 << 20 // ~430 GNOT of deposit at 100 ugnot/B
68 MaxChunk = 262_144 // per AppendBytes call; a tx carries ~540 KB raw (WP0)
69 SegmentBytes = 32_768 // byte-log value size (~6% key overhead, measured)
70 MaxBatch = 100 // records per AddArtworks
71 MaxPage = 20 // Artworks page (was 50)
72)
73
74const zero32 = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
75
76// reserved trait type names: the adapter adds these itself (case-insensitive).
77var reservedTraitTypes = []string{"tier", "edition", "storage", "status", "artwork"}
78
79type store struct {
80 id int64
81 owner address
82 label string
83 sealed bool
84 createdHeight int64
85 sealedHeight int64
86 traitTypes []string // order = slot order ("Trait k")
87 tiers []string // ordered low -> high
88 n int64 // artworks
89 slots int64 // sum of editions
90 onchainN int64
91 ipfsN int64
92 onchainBytes int64 // declared on-chain bytes (sum of chain sizes)
93 logLen int64 // bytes received in the byte log
94 buckets avl.Tree // safe.PadInt(idx/bucketSize, 3) -> *bucket
95 log avl.Tree // safe.PadInt(segment, 3) -> string (<= SegmentBytes)
96 shas *shaIndex
97 // Set composition and names for reads that never loop over artworks and
98 // never escape at read time (review UP-M1). Three slice objects per store.
99 names []string // JSON of the trait types, then of the tiers (escaped once, at NewStore)
100 dict []dictEntry // every distinct trait value, in first-use order; a record stores id + 1
101 cnt []int64 // counters: [0..t] tier artworks, [t+1..2t+1] tier slots (index 0 = untiered),
102 // then per dict entry i: [base+2i] artworks, [base+2i+1] slots (base = 2t+2)
103 perType [MaxTraitTypes]int
104 chainIdx string // indexes of the on-chain artworks, u32 big-endian each, in order
105 chainDone int64 // how many of them are complete (bytes arrive in artwork order)
106}
107
108// dictEntry is one distinct trait value of a store: its trait type, the
109// value and its JSON (escaped once, when first used).
110type dictEntry struct {
111 k int
112 v string
113 js string
114}
115
116func (s *store) cntBase() int { return 2*len(s.tiers) + 2 }
117
118// count counts one record in (sign +1) or out (sign -1).
119func (s *store) count(r *record, sign int64) {
120 ed := r.editions * sign
121 t := len(s.tiers)
122 s.cnt[r.tier] += sign
123 s.cnt[t+1+r.tier] += ed
124 base := s.cntBase()
125 for k := range s.traitTypes {
126 if id := r.traits[k]; id > 0 {
127 s.cnt[base+2*(id-1)] += sign
128 s.cnt[base+2*(id-1)+1] += ed
129 }
130 }
131}
132
133// shaIndex is the sorted list of every artwork's raw sha256 (32 B each),
134// one object per store: duplicate detection without one avl key (~2 KB)
135// per artwork.
136type shaIndex struct {
137 s string
138}
139
140var (
141 stores avl.Tree // safe.PadInt(id, 10) -> *store
142 storeCount int64
143)
144
145func storeKey(id int64) string { return safe.PadInt(id, 10) }
146
147func bucketKey(b int64) string { return safe.PadInt(b, 3) }
148
149func mustStore(storeID string) *store {
150 v := stores.Get(storeKey(safe.ParseID("store", storeID)))
151 if v == nil {
152 panic("unknown store " + strconv.Quote(storeID))
153 }
154 return v.(*store)
155}
156
157func (s *store) idStr() string { return strconv.FormatInt(s.id, 10) }
158
159// assertWallet: every write comes straight from a wallet's MsgCall and
160// carries no coins.
161func assertWallet(cur realm) {
162 if !cur.Previous().IsUserCall() {
163 panic("asset stores are written by their owner's wallet only (direct call)")
164 }
165 if !unsafe.OriginSend().IsZero() {
166 panic("this function does not accept coins")
167 }
168}
169
170func ownedDraft(cur realm, storeID string) *store {
171 assertWallet(cur)
172 s := mustStore(storeID)
173 if cur.Previous().Address() != s.owner {
174 panic("only the store owner " + s.owner.String() + " can change store " + storeID)
175 }
176 if s.sealed {
177 panic("store " + storeID + " is sealed")
178 }
179 return s
180}
181
182// --- writes ------------------------------------------------------------------
183
184// NewStore creates an empty Draft store owned by the calling wallet.
185// traitTypes and tiers are '|'-separated name lists ("" = none): at most 16
186// trait types and 8 tiers (tiers ordered low -> high), names 1..20 bytes,
187// no ':', none of < > & " \ and no leading/trailing space, unique ignoring
188// case; "Tier", "Edition", "Storage", "Status" and "Artwork" are reserved
189// trait types. The label holds none of < > & " \ either.
190// Returns the store id. Event StoreCreated{store, owner}.
191func NewStore(cur realm, label, traitTypes, tiers string) string {
192 assertWallet(cur)
193 safe.AssertText("label", label, MaxLabelLen)
194 assertPlain("label", label)
195 tt := parseNames("traitTypes", traitTypes, MaxTraitTypes, true)
196 ts := parseNames("tiers", tiers, MaxTiers, false)
197 storeCount++
198 s := &store{
199 id: storeCount,
200 owner: cur.Previous().Address(),
201 label: label,
202 createdHeight: runtime.ChainHeight(),
203 traitTypes: tt,
204 tiers: ts,
205 shas: &shaIndex{},
206 names: append(jsonAll(tt), jsonAll(ts)...),
207 cnt: make([]int64, 2*len(ts)+2),
208 }
209 stores.Set(storeKey(s.id), s)
210 chain.Emit("StoreCreated", "store", s.idStr(), "owner", s.owner.String())
211 return s.idStr()
212}
213
214func jsonAll(xs []string) []string {
215 out := make([]string, len(xs))
216 for i, x := range xs {
217 out[i] = jsonStr(x)
218 }
219 return out
220}
221
222// jsonStr is safe.JSONString (same bytes: '"' '\\' \n \r \t, '<' '>' '&',
223// U+2028/9 and other controls escaped) without its per-character hex
224// formatting, which made '<'-heavy text cost ~10x more (UP-M1).
225func jsonStr(x string) string {
226 plain := true
227 for i := 0; i < len(x); i++ {
228 c := x[i]
229 if c < 0x20 || c == '"' || c == '\\' || c == '<' || c == '>' || c == '&' || c == 0x7f || c == 0xe2 {
230 plain = false
231 break
232 }
233 }
234 if plain {
235 return `"` + x + `"`
236 }
237 const hexd = "0123456789abcdef"
238 var b strings.Builder
239 b.WriteByte('"')
240 for _, r := range x {
241 switch r {
242 case '"':
243 b.WriteString(`\"`)
244 case '\\':
245 b.WriteString(`\\`)
246 case '\n':
247 b.WriteString(`\n`)
248 case '\r':
249 b.WriteString(`\r`)
250 case '\t':
251 b.WriteString(`\t`)
252 case '<':
253 b.WriteString(`\u003c`)
254 case '>':
255 b.WriteString(`\u003e`)
256 case '&':
257 b.WriteString(`\u0026`)
258 case 0x2028:
259 b.WriteString(`\u2028`)
260 case 0x2029:
261 b.WriteString(`\u2029`)
262 default:
263 if r < 0x20 || r == 0x7f {
264 b.WriteString(`\u00`)
265 b.WriteByte(hexd[(r>>4)&0xf])
266 b.WriteByte(hexd[r&0xf])
267 continue
268 }
269 b.WriteRune(r)
270 }
271 }
272 b.WriteByte('"')
273 return b.String()
274}
275
276// plainForbidden are the bytes assertPlain refuses: the characters JSON or
277// HTML must escape. Text without them (and without the controls CheckText
278// already refuses) is copied as is by safe.JSONString's native fast path,
279// which keeps every per-token JSON read of an uploaded collection cheap.
280const plainForbidden = `<>&"\`
281
282// plainLo/plainHi: printable ASCII without '"', '\', '<', '>', '&', DEL (the
283// bitmap of safe/v2's JSONString fast path) for one native
284// markdown.MatchCharsetN call; strings of plainMin+ bytes try it first,
285// shorter ones and text with bytes >= 0x80 go through the byte loop.
286const (
287 plainLo = 0xafffffbb00000000
288 plainHi = 0x7fffffffefffffff
289 plainMin = 8
290)
291
292// assertPlain panics when s holds '<', '>', '&', '"' or '\'. The frontend
293// mirrors the rule and its text (frontend/src/chain/uploadRules.ts).
294func assertPlain(field, s string) {
295 if len(s) >= plainMin && markdown.MatchCharsetN(s, plainLo, plainHi, plainLo, plainHi, 0, len(s)) {
296 return
297 }
298 for i := 0; i < len(s); i++ {
299 switch s[i] {
300 case '<', '>', '&', '"', '\\':
301 panic(field + ": may not contain any of " + plainForbidden)
302 }
303 }
304}
305
306func parseNames(field, list string, max int, traits bool) []string {
307 if list == "" {
308 return []string{}
309 }
310 parts := strings.Split(list, "|")
311 if len(parts) > max {
312 panic(field + ": at most " + strconv.Itoa(max))
313 }
314 out := make([]string, 0, len(parts))
315 for _, p := range parts {
316 safe.AssertNonEmptyText(field, p, MaxNameLen)
317 assertPlain(field, p)
318 if strings.Contains(p, ":") || strings.TrimSpace(p) != p {
319 panic(field + ": " + strconv.Quote(p) + " may not contain ':' or leading/trailing spaces")
320 }
321 low := strings.ToLower(p)
322 if traits {
323 for _, r := range reservedTraitTypes {
324 if low == r {
325 panic(field + ": " + strconv.Quote(p) + " is reserved")
326 }
327 }
328 }
329 for _, prev := range out {
330 if strings.ToLower(prev) == low {
331 panic(field + ": duplicate " + strconv.Quote(p))
332 }
333 }
334 out = append(out, p)
335 }
336 return out
337}
338
339// AddArtworks declares up to MaxBatch artworks, one per '\n'-separated line:
340//
341// kind|mime|size|sha256|cid|editions|tier|title|v1|…|vN
342//
343// with exactly one value per trait type of the store (N = len(traitTypes)):
344// - kind "chain" | "ipfs"; mime "svg" | "png" | "webp" | "jpeg";
345// - size: decimal bytes, chain svg <= 16,384, chain raster <= 262,144,
346// ipfs raw <= 1 MiB, ipfs dag-pb <= 50 MiB; the store's on-chain total
347// stays <= 4 MiB;
348// - sha256: 64 lower-case hex of the file bytes, unique in the store
349// (use editions for copies);
350// - cid: "" for chain; for ipfs a CIDv1 (media.ParseCIDv1): raw codec ⇒
351// its digest must equal sha256 (verified binding), dag-pb ⇒ digest stored;
352// - editions 1..10,000 (the store's slots stay <= 10,000);
353// - tier "" or one of the store's tiers; title <= 64 bytes;
354// - values "" (none) or <= 32 bytes, no leading/trailing space; titles
355// and values hold none of < > & " \ (assertPlain); at most
356// 100 distinct values per trait type and 255 over all types of a store.
357//
358// Returns "first-last" (0-based indexes). Event ArtworkAdded per line.
359func AddArtworks(cur realm, storeID, batch string) string {
360 s := ownedDraft(cur, storeID)
361 if batch == "" {
362 panic("batch: empty")
363 }
364 lines := split(batch, '\n')
365 if len(lines) > MaxBatch {
366 panic("batch: at most " + strconv.Itoa(MaxBatch) + " artworks per call")
367 }
368 if s.n+int64(len(lines)) > MaxArtworks {
369 panic("store: at most " + strconv.Itoa(MaxArtworks) + " artworks")
370 }
371 first := s.n
372 shas := make([]string, 0, len(lines))
373 // per-call (type, value) -> id map, built once from the dictionary: a
374 // line costs O(1) per trait instead of a scan of the values (UP-L1)
375 var look map[string]int
376 for i, line := range lines {
377 f := split(line, '|')
378 r, title := s.parseLine(i+1, f, &look)
379 shas = append(shas, r.sha)
380 s.appendRecord(&r, title)
381 // the line's sha256 and CID are already canonical (strict parsers):
382 // re-encoding them would cost ~1.5M gas per line for the same text
383 chain.Emit("ArtworkAdded", "store", s.idStr(), "idx", strconv.FormatInt(s.n-1, 10),
384 "kind", media.KindName(r.kind), "mime", media.MimeName(r.mime),
385 "size", strconv.FormatInt(r.size, 10), "sha256", f[3], "cid", f[4],
386 "editions", strconv.FormatInt(r.editions, 10), "tier", s.tierName(r.tier))
387 }
388 s.shas.insert(shas)
389 return strconv.FormatInt(first, 10) + "-" + strconv.FormatInt(s.n-1, 10)
390}
391
392// split is strings.Split for a one-byte separator in a single pass (half
393// the VM gas of strings.Split, which dominates a 100-line batch).
394func split(s string, sep byte) []string {
395 out := make([]string, 0, 16)
396 start := 0
397 for i := 0; i < len(s); i++ {
398 if s[i] == sep {
399 out = append(out, s[start:i])
400 start = i + 1
401 }
402 }
403 return append(out, s[start:])
404}
405
406func (s *store) parseLine(no int, f []string, look *map[string]int) (record, string) {
407 at := "line " + strconv.Itoa(no) + ": "
408 if want := 8 + len(s.traitTypes); len(f) != want {
409 panic(at + "expected " + strconv.Itoa(want) + " '|'-separated fields, got " + strconv.Itoa(len(f)))
410 }
411 var r record
412 switch f[0] {
413 case "chain":
414 r.kind = media.KindChain
415 case "ipfs":
416 default:
417 panic(at + "kind must be chain or ipfs")
418 }
419 r.mime = parseMime(at, f[1])
420 r.size = parseCount(at+"size", f[2], 1<<62)
421 shaRaw, ok := media.Raw32(f[3])
422 if !ok {
423 panic(at + "sha256 must be 64 lower-case hex characters")
424 }
425 r.sha = shaRaw
426 r.digest = zero32
427 if r.kind == media.KindChain {
428 if f[4] != "" {
429 panic(at + "an on-chain artwork has no cid")
430 }
431 } else {
432 codec, digest, err := media.ParseCIDv1(f[4])
433 if err != nil {
434 panic(at + err.Error())
435 }
436 if codec == media.CodecRaw {
437 if digest != f[3] {
438 panic(at + "a raw CID's digest must equal the file's sha256")
439 }
440 r.kind = media.KindIPFSRaw
441 } else {
442 r.kind = media.KindIPFSUnixFS
443 r.digest, _ = media.Raw32(digest)
444 }
445 }
446 if max := media.MaxBytes(r.kind, r.mime); r.size > max {
447 panic(at + "size " + f[2] + " exceeds " + strconv.FormatInt(max, 10) + " bytes for this kind and type")
448 }
449 r.editions = parseCount(at+"editions", f[5], MaxEditions)
450 if s.slots+r.editions > MaxSlots {
451 panic(at + "the store would exceed " + strconv.Itoa(MaxSlots) + " slots (sum of editions)")
452 }
453 r.tier = s.tierIndex(at, f[6])
454 title := f[7]
455 safe.AssertText(at+"title", title, MaxTitleLen)
456 assertPlain(at+"title", title)
457 for k := range s.traitTypes {
458 r.traits[k] = s.dictIndex(at, k, f[8+k], look)
459 }
460 if r.kind == media.KindChain {
461 if s.onchainBytes+r.size > MaxStoreOnchainBytes {
462 panic(at + "the store would exceed " + strconv.Itoa(MaxStoreOnchainBytes) + " on-chain bytes")
463 }
464 r.logOff = s.onchainBytes
465 } else {
466 r.have = r.size
467 }
468 r.slotEnd = s.slots + r.editions
469 return r, title
470}
471
472func parseMime(at, s string) (m int) {
473 switch s {
474 case "svg":
475 return media.MimeSVG
476 case "png":
477 return media.MimePNG
478 case "webp":
479 return media.MimeWebP
480 case "jpeg":
481 return media.MimeJPEG
482 }
483 panic(at + "mime must be svg, png, webp or jpeg")
484}
485
486// parseCount parses a canonical positive decimal (no sign, no leading zero) <= max.
487func parseCount(field, s string, max int64) int64 {
488 if s == "" || len(s) > 19 || s[0] == '0' {
489 panic(field + ": must be a positive decimal")
490 }
491 var n int64
492 for i := 0; i < len(s); i++ {
493 c := s[i]
494 if c < '0' || c > '9' {
495 panic(field + ": must be a positive decimal")
496 }
497 n = n*10 + int64(c-'0')
498 if n > max {
499 panic(field + ": at most " + strconv.FormatInt(max, 10))
500 }
501 }
502 return n
503}
504
505func (s *store) tierIndex(at, name string) int {
506 if name == "" {
507 return 0
508 }
509 for i, t := range s.tiers {
510 if t == name {
511 return i + 1
512 }
513 }
514 panic(at + "unknown tier " + strconv.Quote(name))
515}
516
517func (s *store) tierName(i int) string {
518 if i == 0 {
519 return ""
520 }
521 return s.tiers[i-1]
522}
523
524func (s *store) dictIndex(at string, k int, v string, look *map[string]int) int {
525 if v == "" {
526 return 0
527 }
528 if *look == nil {
529 m := make(map[string]int, len(s.dict))
530 for i, e := range s.dict {
531 m[strconv.Itoa(e.k)+"|"+e.v] = i + 1
532 }
533 *look = m
534 }
535 key := strconv.Itoa(k) + "|" + v
536 if id, ok := (*look)[key]; ok {
537 return id
538 }
539 // a new value: checked once, stored with its JSON and zero counters
540 safe.AssertText(at+s.traitTypes[k], v, MaxValueLen)
541 assertPlain(at+s.traitTypes[k], v)
542 if strings.TrimSpace(v) != v {
543 panic(at + s.traitTypes[k] + ": no leading or trailing spaces")
544 }
545 if s.perType[k] >= MaxDictValues {
546 panic(at + s.traitTypes[k] + ": at most " + strconv.Itoa(MaxDictValues) + " distinct values")
547 }
548 if len(s.dict) >= MaxStoreValues {
549 panic(at + "a store holds at most " + strconv.Itoa(MaxStoreValues) + " distinct trait values")
550 }
551 s.dict = append(s.dict, dictEntry{k: k, v: v, js: jsonStr(v)})
552 s.cnt = append(s.cnt, 0, 0)
553 s.perType[k]++
554 (*look)[key] = len(s.dict)
555 return len(s.dict)
556}
557
558func (s *store) appendRecord(r *record, title string) {
559 k := bucketKey(s.n / bucketSize)
560 var b *bucket
561 if v := s.buckets.Get(k); v != nil {
562 b = v.(*bucket)
563 } else {
564 b = &bucket{}
565 s.buckets.Set(k, b)
566 }
567 b.rec += r.encode()
568 b.titles += string([]byte{byte(len(title))}) + title
569 if r.kind == media.KindChain {
570 s.onchainN++
571 s.onchainBytes += r.size
572 s.chainIdx += u32(s.n)
573 } else {
574 s.ipfsN++
575 }
576 s.n++
577 s.slots = r.slotEnd
578 s.count(r, 1)
579}
580
581func u32(v int64) string {
582 return string([]byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)})
583}
584
585// insert merges sorted-unique new digests into the index; any duplicate
586// (inside the batch or with an earlier artwork) aborts the call.
587func (x *shaIndex) insert(add []string) {
588 for i := 1; i < len(add); i++ { // insertion sort, <= MaxBatch items
589 for j := i; j > 0 && add[j] < add[j-1]; j-- {
590 add[j], add[j-1] = add[j-1], add[j]
591 }
592 }
593 for i := 1; i < len(add); i++ {
594 if add[i] == add[i-1] {
595 panic("sha256 " + hex.EncodeToString([]byte(add[i])) + " appears twice; use editions for copies")
596 }
597 }
598 var b strings.Builder
599 pos := 0
600 for _, d := range add {
601 at := x.search(d)
602 if at < len(x.s) && x.s[at:at+32] == d {
603 panic("sha256 " + hex.EncodeToString([]byte(d)) + " is already in this store; use editions for copies")
604 }
605 b.WriteString(x.s[pos:at])
606 b.WriteString(d)
607 pos = at
608 }
609 b.WriteString(x.s[pos:])
610 x.s = b.String()
611}
612
613// remove drops the given digests (each present once).
614func (x *shaIndex) remove(drop []string) {
615 for _, d := range drop {
616 at := x.search(d)
617 if at < len(x.s) && x.s[at:at+32] == d {
618 x.s = x.s[:at] + x.s[at+32:]
619 }
620 }
621}
622
623// search is the byte offset of the first entry >= d.
624func (x *shaIndex) search(d string) int {
625 lo, hi := 0, len(x.s)/32
626 for lo < hi {
627 mid := (lo + hi) / 2
628 if x.s[mid*32:mid*32+32] < d {
629 lo = mid + 1
630 } else {
631 hi = mid
632 }
633 }
634 return lo * 32
635}
636
637// AppendBytes stores the next chunk of an on-chain artwork. Bytes arrive
638// in artwork order: idx must be the lowest incomplete on-chain artwork and
639// offset its Have (resume = read Have). chunk is a []byte argument (the
640// keeper decodes the MsgCall's base64 natively, WP0), 1..MaxChunk bytes.
641// When the artwork is complete its sha256 must equal the declared one and
642// media.CheckImage must pass, else the call panics and nothing is stored.
643// Event ArtworkComplete{store, idx}.
644func AppendBytes(cur realm, storeID string, idx, offset int64, chunk []byte) {
645 s := ownedDraft(cur, storeID)
646 if idx < 0 || idx >= s.n {
647 panic("no artwork " + strconv.FormatInt(idx, 10) + " in store " + storeID)
648 }
649 b, i := s.bucketOf(idx)
650 r := decodeRecord(b.raw(i))
651 if r.kind != media.KindChain {
652 panic("artwork " + strconv.FormatInt(idx, 10) + " is not stored on chain")
653 }
654 if r.complete() {
655 panic("artwork " + strconv.FormatInt(idx, 10) + " is already complete")
656 }
657 if offset != r.have {
658 panic("offset must equal have (" + strconv.FormatInt(r.have, 10) + ")")
659 }
660 if r.logOff+r.have != s.logLen {
661 panic("upload the lowest incomplete on-chain artwork first")
662 }
663 n := int64(len(chunk))
664 if n == 0 || n > MaxChunk {
665 panic("chunk must be 1.." + strconv.Itoa(MaxChunk) + " bytes")
666 }
667 if r.have+n > r.size {
668 panic("chunk exceeds the declared size (" + strconv.FormatInt(r.size-r.have, 10) + " bytes left)")
669 }
670 s.appendLog(string(chunk))
671 r.have += n
672 if r.complete() {
673 data := s.readLog(r.logOff, r.size)
674 sum := sha256.Sum256([]byte(data))
675 if string(sum[:]) != r.sha {
676 panic("sha256 mismatch: the uploaded bytes are not the declared file")
677 }
678 if _, _, err := media.CheckImage(r.mime, data); err != nil {
679 panic("artwork " + strconv.FormatInt(idx, 10) + " rejected: " + err.Error())
680 }
681 s.chainDone++ // in-order uploads: idx was the next on-chain artwork
682 chain.Emit("ArtworkComplete", "store", storeID, "idx", strconv.FormatInt(idx, 10))
683 }
684 b.setRaw(i, r.encode())
685}
686
687func (s *store) bucketOf(idx int64) (*bucket, int) {
688 v := s.buckets.Get(bucketKey(idx / bucketSize))
689 if v == nil {
690 panic("assets: missing record bucket")
691 }
692 return v.(*bucket), int(idx % bucketSize)
693}
694
695func (s *store) appendLog(chunk string) {
696 for len(chunk) > 0 {
697 k := bucketKey(s.logLen / SegmentBytes)
698 seg := ""
699 if v := s.log.Get(k); v != nil {
700 seg = v.(string)
701 }
702 n := SegmentBytes - len(seg)
703 if n > len(chunk) {
704 n = len(chunk)
705 }
706 s.log.Set(k, seg+chunk[:n])
707 s.logLen += int64(n)
708 chunk = chunk[n:]
709 }
710}
711
712func (s *store) readLog(off, n int64) string {
713 var b strings.Builder
714 for n > 0 {
715 seg := off / SegmentBytes
716 v := s.log.Get(bucketKey(seg)).(string)
717 lo := off - seg*SegmentBytes
718 hi := int64(len(v))
719 if hi-lo > n {
720 hi = lo + n
721 }
722 b.WriteString(v[lo:hi])
723 n -= hi - lo
724 off += hi - lo
725 }
726 return b.String()
727}
728
729// cutLog shortens the byte log to newLen bytes (frees whole segments).
730func (s *store) cutLog(newLen int64) {
731 for s.logLen > newLen {
732 seg := (s.logLen - 1) / SegmentBytes
733 start := seg * SegmentBytes
734 k := bucketKey(seg)
735 if start >= newLen {
736 s.log.Remove(k)
737 s.logLen = start
738 continue
739 }
740 v := s.log.Get(k).(string)
741 s.log.Set(k, v[:newLen-start])
742 s.logLen = newLen
743 }
744}
745
746// Truncate drops artworks keep..n-1 of a Draft store and cuts the byte log
747// back, freeing their storage (the chain refunds the signer, i.e. the owner
748// who paid it). Trait values first used by dropped artworks stay in the
749// dictionary (with zero counts; they still count towards MaxStoreValues).
750// Event StoreTruncated{store, keep}.
751func Truncate(cur realm, storeID string, keep int64) {
752 s := ownedDraft(cur, storeID)
753 if keep < 0 || keep >= s.n {
754 panic("keep must be 0.." + strconv.FormatInt(s.n-1, 10))
755 }
756 cut := int64(-1)
757 var dropped []string
758 for idx := keep; idx < s.n; idx++ {
759 b, i := s.bucketOf(idx)
760 r := decodeRecord(b.raw(i))
761 dropped = append(dropped, r.sha)
762 s.count(&r, -1)
763 if r.kind == media.KindChain {
764 s.onchainN--
765 if r.complete() {
766 s.chainDone--
767 }
768 if cut < 0 {
769 cut = r.logOff
770 }
771 } else {
772 s.ipfsN--
773 }
774 }
775 s.chainIdx = s.chainIdx[:s.onchainN*4]
776 if cut >= 0 {
777 s.onchainBytes = cut
778 if s.logLen > cut {
779 s.cutLog(cut)
780 }
781 }
782 s.slots = 0
783 if keep > 0 {
784 b, i := s.bucketOf(keep - 1)
785 s.slots = decodeRecord(b.raw(i)).slotEnd
786 }
787 last := (s.n - 1) / bucketSize
788 kb := keep / bucketSize
789 for bk := last; bk > kb; bk-- {
790 s.buckets.Remove(bucketKey(bk))
791 }
792 if keep%bucketSize == 0 {
793 s.buckets.Remove(bucketKey(kb))
794 } else {
795 v := s.buckets.Get(bucketKey(kb)).(*bucket)
796 v.keep(int(keep % bucketSize))
797 }
798 s.n = keep
799 s.shas.remove(dropped)
800 chain.Emit("StoreTruncated", "store", storeID, "keep", strconv.FormatInt(keep, 10))
801}
802
803// Seal freezes a store for good. It needs at least one artwork and every
804// on-chain artwork complete. Event StoreSealed{store, artworks, slots,
805// onchainN, ipfsN, onchainBytes}.
806func Seal(cur realm, storeID string) {
807 s := ownedDraft(cur, storeID)
808 if s.n == 0 {
809 panic("a store needs at least one artwork to be sealed")
810 }
811 if s.logLen != s.onchainBytes {
812 panic("on-chain artworks are incomplete: " + strconv.FormatInt(s.logLen, 10) + " of " +
813 strconv.FormatInt(s.onchainBytes, 10) + " bytes uploaded")
814 }
815 s.sealed = true
816 s.sealedHeight = runtime.ChainHeight()
817 chain.Emit("StoreSealed", "store", storeID, "artworks", strconv.FormatInt(s.n, 10),
818 "slots", strconv.FormatInt(s.slots, 10), "onchainN", strconv.FormatInt(s.onchainN, 10),
819 "ipfsN", strconv.FormatInt(s.ipfsN, 10), "onchainBytes", strconv.FormatInt(s.onchainBytes, 10))
820}