Playground
cid.gno
package media
import (
"encoding/hex"
"strconv"
)
// CIDv1 grammar (design §12.1; frontend chain/cid.ts is the twin):
// multibase 'b' (RFC 4648 base32, lower case, no padding) over exactly
// 0x01 · codec · 0x12 · 0x20 · digest[32], codec 0x55 (raw) or 0x70
// (dag-pb). That is 36 bytes = 58 base32 characters + 'b'. The unused two
// trailing bits must be zero, so every CID has exactly one spelling. CIDv0
// ("Qm…"), upper case, other bases, codecs or hash functions are refused.
const (
b32Alphabet = "abcdefghijklmnopqrstuvwxyz234567"
cidBytes = 36
cidChars = 58 // ceil(36*8/5)
mhSha256 = 0x12
digestLen = 32
)
// ParseCIDv1 returns the codec (CodecRaw or CodecDagPB) and the sha2-256
// digest as lower-case hex.
func ParseCIDv1(s string) (codec int, digestHex string, err error) {
if s == "" {
return 0, "", mediaErr("cid: empty")
}
if len(s) >= 2 && s[0] == 'Q' && s[1] == 'm' {
return 0, "", mediaErr("cid: CIDv0 is not accepted; convert it to CIDv1")
}
if s[0] != 'b' {
return 0, "", mediaErr("cid: multibase must be 'b' (base32 lower case)")
}
if len(s) != cidChars+1 {
return 0, "", mediaErr("cid: expected " + strconv.Itoa(cidChars+1) + " characters, got " + strconv.Itoa(len(s)))
}
bz, derr := base32Decode(s[1:])
if derr != nil {
return 0, "", derr
}
if len(bz) != cidBytes {
return 0, "", mediaErr("cid: wrong length")
}
if bz[0] != 1 {
return 0, "", mediaErr("cid: version must be 1")
}
c := int(bz[1])
if c != CodecRaw && c != CodecDagPB {
return 0, "", mediaErr("cid: codec must be raw (0x55) or dag-pb (0x70)")
}
if bz[2] != mhSha256 || bz[3] != digestLen {
return 0, "", mediaErr("cid: multihash must be sha2-256")
}
return c, hex.EncodeToString(bz[4:]), nil
}
// CIDFromDigest is the inverse of ParseCIDv1. It panics on an unsupported
// codec or a digest that is not 64 lower-case hex characters.
func CIDFromDigest(codec int, digestHex string) string {
if codec != CodecRaw && codec != CodecDagPB {
panic("media: cid: unsupported codec")
}
d, ok := Raw32(digestHex)
if !ok {
panic("media: cid: digest must be 64 lower-case hex characters")
}
bz := make([]byte, 0, cidBytes)
bz = append(bz, 1, byte(codec), mhSha256, digestLen)
bz = append(bz, d...)
return "b" + base32Encode(bz)
}
// IsHex32 reports whether s is exactly 64 lower-case hex characters.
func IsHex32(s string) bool {
_, ok := Raw32(s)
return ok
}
// Raw32 decodes exactly 64 lower-case hex characters into 32 raw bytes
// (one pass, table lookups: VM loops cost ~5k gas per character).
func Raw32(s string) (string, bool) {
if len(s) != 64 {
return "", false
}
out := make([]byte, 32)
for i := 0; i < 32; i++ {
hi, lo := hexRev[s[2*i]], hexRev[s[2*i+1]]
if hi > 15 || lo > 15 {
return "", false
}
out[i] = hi<<4 | lo
}
return string(out), true
}
// hexRev and b32Rev map a byte to its digit value, 0xff when it is not a
// lower-case hex / base32 digit.
const (
hexRev = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
b32Rev = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x1a\x1b\x1c\x1d\x1e\x1f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
)
func base32Encode(bz []byte) string {
out := make([]byte, 0, (len(bz)*8+4)/5)
var buf uint32
bits := uint(0)
for _, b := range bz {
buf = buf<<8 | uint32(b)
bits += 8
for bits >= 5 {
bits -= 5
out = append(out, b32Alphabet[(buf>>bits)&31])
}
buf &= (1 << bits) - 1
}
if bits > 0 {
out = append(out, b32Alphabet[(buf<<(5-bits))&31])
}
return string(out)
}
// base32Decode is strict: lower-case alphabet only, and the unused
// trailing bits must be zero.
func base32Decode(s string) ([]byte, error) {
out := make([]byte, 0, len(s)*5/8)
var buf uint32
bits := uint(0)
for i := 0; i < len(s); i++ {
v := b32Rev[s[i]]
if v > 31 {
return nil, mediaErr("cid: invalid base32 character " + strconv.Quote(s[i:i+1]))
}
buf = buf<<5 | uint32(v)
bits += 5
if bits >= 8 {
bits -= 8
out = append(out, byte(buf>>bits))
buf &= (1 << bits) - 1
}
}
if bits >= 5 || buf != 0 {
return nil, mediaErr("cid: non-canonical base32 padding bits")
}
return out, nil
}
gnomod.toml
module = "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/media/v1" gno = "0.9" [addpkg] creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06" height = 898610 max_deposit = "30000000ugnot"
image.gno
package media
import (
"strconv"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
)
// CheckImage checks a complete file against its declared type: the magic
// bytes and the header's pixel dimensions (each 1..MaxDim, the
// decompression-bomb guard). SVG has no header dimensions (w, h = 0) and
// must pass safe.AssertSVG with the on-chain cap MaxSVGBytes (§0a), the same
// allowlist core applies to every render. Nothing else of a raster file is
// parsed: raster bytes are only ever shown through <img> (SA-M3).
func CheckImage(mime int, data string) (w, h int, err error) {
switch mime {
case MimeSVG:
if err := safe.AssertSVG(data, MaxSVGBytes); err != nil {
return 0, 0, err
}
return 0, 0, nil
case MimePNG:
w, h, err = pngDims(data)
case MimeWebP:
w, h, err = webpDims(data)
case MimeJPEG:
w, h, err = jpegDims(data)
case MimeGIF:
w, h, err = gifDims(data)
default:
return 0, 0, mediaErr("unknown media type " + strconv.Itoa(mime))
}
if err != nil {
return 0, 0, err
}
if w < 1 || h < 1 || w > MaxDim || h > MaxDim {
return 0, 0, mediaErr(MimeName(mime) + ": dimensions " + strconv.Itoa(w) + "x" + strconv.Itoa(h) +
" outside 1.." + strconv.Itoa(MaxDim))
}
return w, h, nil
}
func be16(s string, i int) int { return int(s[i])<<8 | int(s[i+1]) }
func le16(s string, i int) int { return int(s[i]) | int(s[i+1])<<8 }
func le24(s string, i int) int { return int(s[i]) | int(s[i+1])<<8 | int(s[i+2])<<16 }
func be32(s string, i int) int64 {
return int64(s[i])<<24 | int64(s[i+1])<<16 | int64(s[i+2])<<8 | int64(s[i+3])
}
func le32(s string, i int) int64 {
return int64(s[i]) | int64(s[i+1])<<8 | int64(s[i+2])<<16 | int64(s[i+3])<<24
}
// pngDims: signature, then the IHDR chunk (length 13) with big-endian
// width and height. The 4-byte CRC after IHDR must be present.
func pngDims(s string) (int, int, error) {
if len(s) < 33 || s[:8] != "\x89PNG\r\n\x1a\n" {
return 0, 0, mediaErr("png: bad signature or truncated header")
}
if be32(s, 8) != 13 || s[12:16] != "IHDR" {
return 0, 0, mediaErr("png: first chunk must be IHDR")
}
return int(be32(s, 16)), int(be32(s, 20)), nil
}
// webpDims: RIFF container whose size field covers the whole file, form
// type WEBP, then one of the three bitstream headers.
func webpDims(s string) (int, int, error) {
if len(s) < 30 || s[:4] != "RIFF" || s[8:12] != "WEBP" {
return 0, 0, mediaErr("webp: bad RIFF/WEBP header or truncated")
}
if le32(s, 4)+8 != int64(len(s)) {
return 0, 0, mediaErr("webp: RIFF size does not match the file size")
}
switch s[12:16] {
case "VP8 ": // lossy: 3-byte frame tag, start code 9d 01 2a, 14-bit dims
if s[23:26] != "\x9d\x01\x2a" {
return 0, 0, mediaErr("webp: bad VP8 start code")
}
return le16(s, 26) & 0x3fff, le16(s, 28) & 0x3fff, nil
case "VP8L": // lossless: signature 0x2f, 14-bit width-1 and height-1
if s[20] != 0x2f {
return 0, 0, mediaErr("webp: bad VP8L signature")
}
bits := le32(s, 21)
return int(bits&0x3fff) + 1, int((bits>>14)&0x3fff) + 1, nil
case "VP8X": // extended: 24-bit canvas width-1 and height-1
return le24(s, 24) + 1, le24(s, 27) + 1, nil
}
return 0, 0, mediaErr("webp: unknown bitstream chunk")
}
// jpegDims walks the marker segments after SOI up to the first SOFn
// (C0..CF except C4 DHT, C8 JPG, CC DAC). Reaching SOS or EOI first, or
// running out of bytes, is an error.
func jpegDims(s string) (int, int, error) {
if len(s) < 4 || s[0] != 0xff || s[1] != 0xd8 || s[2] != 0xff {
return 0, 0, mediaErr("jpeg: bad SOI")
}
i := 2
for i < len(s) {
if s[i] != 0xff {
return 0, 0, mediaErr("jpeg: expected a marker at byte " + strconv.Itoa(i))
}
for i < len(s) && s[i] == 0xff { // fill bytes
i++
}
if i >= len(s) {
break
}
m := s[i]
i++
switch {
case m == 0xd8 || m == 0x01 || (m >= 0xd0 && m <= 0xd7):
continue // standalone markers
case m == 0xd9 || m == 0xda:
return 0, 0, mediaErr("jpeg: no frame header before scan data")
}
if i+2 > len(s) {
break
}
n := be16(s, i)
if n < 2 || i+n > len(s) {
return 0, 0, mediaErr("jpeg: bad segment length")
}
if m >= 0xc0 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc {
if n < 8 {
return 0, 0, mediaErr("jpeg: short frame header")
}
return be16(s, i+5), be16(s, i+3), nil // width after height
}
i += n
}
return 0, 0, mediaErr("jpeg: truncated before the frame header")
}
func gifDims(s string) (int, int, error) {
if len(s) < 13 || (s[:6] != "GIF87a" && s[:6] != "GIF89a") {
return 0, 0, mediaErr("gif: bad signature or truncated")
}
return le16(s, 6), le16(s, 8), nil
}
media.gno
// Package media is the pure half of Sinopia's uploaded collections
// (docs/uploaded-collections.md §5.1, §0a): media kinds and types, the CIDv1
// grammar the platform accepts, image header checks, and the salt-keyed
// permutation that assigns tokens to artworks. It has no state; the asset
// store (r/…/assets/v1), the upload engine (r/…/engines/upload) and the
// frontend (chain/cid.ts, chain/perm.ts) share these definitions, pinned by
// the golden vectors in docs/test-vectors/upload-v1.json.
package media
import (
"errors"
"strconv"
)
// Storage kinds of one artwork.
const (
KindChain = 1 // bytes stored in assets/v1
KindIPFSRaw = 2 // raw-leaf CIDv1: the CID's digest is the file's sha256 (checked on chain)
KindIPFSUnixFS = 3 // dag-pb CIDv1: digest of the root node, file sha256 stored separately
)
// Media types. GIF is defined for completeness but refused by ParseMime
// (decision D5: svg, png, webp, jpeg only).
const (
MimeSVG = 1
MimePNG = 2
MimeWebP = 3
MimeJPEG = 4
MimeGIF = 5
)
// Limits (decision D4 and design §4).
const (
MaxDim = 4096 // px per side, decompression-bomb guard
MaxSVGBytes = 16384 // on-chain SVG: AssertSVG costs ~30-50k gas/B (WP0)
MaxRasterBytes = 262144 // on-chain png/webp/jpeg per artwork
MaxIPFSRaw = 1 << 20 // single raw block
MaxIPFSUnixFS = 50 << 20 // declared; the frontend enforces it while streaming
)
// CID codecs.
const (
CodecRaw = 0x55
CodecDagPB = 0x70
)
// PermDomain separates the permutation key from every other platform hash
// (under safe.Domain "art").
const PermDomain = "art|upload|perm|v1|"
// Artwork is one record of a store as plain data. It crosses realm
// boundaries as a copy and never points into store state.
type Artwork struct {
Index int64
Kind, Mime int
Size, Have, Editions, SlotEnd int64
SHA256, Digest, CID, Title, Tier string
Traits []string // one value per store trait type ("" = none)
Complete bool
// JSON escaped once by the store (filled by assets/v1 reads, "" otherwise):
// TierJSON is the tier name as a JSON string ("" = no tier); TraitsJSON the
// creator traits as comma-joined {"trait_type":…,"value":…} items in store
// order ("" = none). Lets token reads avoid per-call escaping (review UP-M1).
TierJSON, TraitsJSON string
}
// SlotStart is the first slot of the artwork's range [SlotStart, SlotEnd).
func (a Artwork) SlotStart() int64 { return a.SlotEnd - a.Editions }
// StoreInfo is a store's header as plain data.
type StoreInfo struct {
ID string
Owner address
Label string
Sealed bool
SealedHeight int64
Artworks, Slots, OnchainN, IPFSN, OnchainBytes int64
TraitTypes, Tiers []string
}
// MimeType is the IANA type of a media constant ("" for an unknown one).
func MimeType(m int) string {
switch m {
case MimeSVG:
return "image/svg+xml"
case MimePNG:
return "image/png"
case MimeWebP:
return "image/webp"
case MimeJPEG:
return "image/jpeg"
case MimeGIF:
return "image/gif"
}
return ""
}
// MimeName is the short name ParseMime accepts ("svg", "png", …).
func MimeName(m int) string {
switch m {
case MimeSVG:
return "svg"
case MimePNG:
return "png"
case MimeWebP:
return "webp"
case MimeJPEG:
return "jpeg"
case MimeGIF:
return "gif"
}
return ""
}
// ParseMime maps "svg" | "png" | "webp" | "jpeg" to its constant and panics
// on anything else, "gif" included (D5).
func ParseMime(s string) int {
switch s {
case "svg":
return MimeSVG
case "png":
return MimePNG
case "webp":
return MimeWebP
case "jpeg":
return MimeJPEG
case "gif":
panic("mime: gif is not supported (svg, png, webp, jpeg)")
}
panic("mime: must be svg, png, webp or jpeg, got " + strconv.Quote(s))
}
// KindName is "chain" or "ipfs".
func KindName(k int) string {
switch k {
case KindChain:
return "chain"
case KindIPFSRaw, KindIPFSUnixFS:
return "ipfs"
}
return ""
}
// MaxBytes is the size cap of one artwork of this kind and type.
func MaxBytes(kind, mime int) int64 {
switch kind {
case KindChain:
if mime == MimeSVG {
return MaxSVGBytes
}
return MaxRasterBytes
case KindIPFSRaw:
return MaxIPFSRaw
case KindIPFSUnixFS:
return MaxIPFSUnixFS
}
return 0
}
// Badge is a store's storage badge from its counters (design §9):
// "onchain", "ipfs", "mixed", or "empty" for a store without artworks.
func Badge(onchainN, ipfsN int64) string {
switch {
case onchainN == 0 && ipfsN == 0:
return "empty"
case ipfsN == 0:
return "onchain"
case onchainN == 0:
return "ipfs"
}
return "mixed"
}
func mediaErr(msg string) error { return errors.New("media: " + msg) }
perm.gno
package media
import (
"crypto/sha256"
"strconv"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/safe/v1"
)
// Token → artwork assignment (design §7; frontend chain/perm.ts is the twin).
//
// K = sha256hex(PermDomain + collectionID + "|" + salt)
// slot(tid) = Permute(K, slots, tid-1) (single-artwork store: tid-1)
//
// The salt exists only once the collection is Final (commit–reveal v2), so
// nobody, the creator included, knows any token's slot before every token
// was sold and both secrets were revealed.
// PermKey is the permutation key of collection cid with its final salt.
func PermKey(cid, salt string) string {
return safe.Sha256Hex(PermDomain + cid + "|" + salt)
}
// Permute is a bijection on [0, n): a 4-round Feistel network over b bits
// (b = bitlen(n-1) rounded up to an even number ≥ 2, so 2^b < 4n) with cycle
// walking. Round function: F = big-endian uint64 of the first 8 bytes of
// sha256(keyHex + "|" + r + "|" + R), masked to h = b/2 bits, with r and R
// in decimal. It panics unless 1 ≤ n and 0 ≤ x < n.
func Permute(keyHex string, n, x int64) int64 {
if n < 1 || x < 0 || x >= n {
panic("media: permute: need 0 <= x < n")
}
if n == 1 {
return 0
}
b := bitLen(uint64(n - 1))
if b < 2 {
b = 2
}
if b%2 == 1 {
b++
}
h := uint(b / 2)
mask := uint64(1)<<h - 1
prefix := keyHex + "|"
v := uint64(x)
// The walk stays on x's cycle, which contains x itself (< n), so it
// ends; the bound only guards against a broken hash.
for walk := 0; walk < 1<<uint(b); walk++ {
l, r := v>>h, v&mask
for round := 0; round < 4; round++ {
f := roundF(prefix+strconv.Itoa(round)+"|", r) & mask
l, r = r, l^f
}
v = l<<h | r
if v < uint64(n) {
return int64(v)
}
}
panic("media: permute: cycle walk did not terminate")
}
func roundF(prefix string, r uint64) uint64 {
sum := sha256.Sum256([]byte(prefix + strconv.FormatUint(r, 10)))
return uint64(sum[0])<<56 | uint64(sum[1])<<48 | uint64(sum[2])<<40 | uint64(sum[3])<<32 |
uint64(sum[4])<<24 | uint64(sum[5])<<16 | uint64(sum[6])<<8 | uint64(sum[7])
}
func bitLen(v uint64) int {
n := 0
for v > 0 {
n++
v >>= 1
}
return n
}
// Slot is the slot of token tid (1-based) in a store of `artworks`
// artworks and `slots` slots: the identity tid-1 for a single-artwork store
// (1/1 and editions: "Edition 3 of 50"), Permute(K, slots, tid-1) otherwise.
func Slot(keyHex string, artworks, slots, tid int64) int64 {
if tid < 1 || tid > slots {
panic("media: slot: token id out of range")
}
if artworks == 1 {
return tid - 1
}
return Permute(keyHex, slots, tid-1)
}