Playground
blocks.gno
package safe
// AvgBlockMs is the measured mainnet average block time (RA §1: 200k blocks
// in 708,660 s). Use it only for UI estimates and defaults; every on-chain
// rule is stated in blocks.
const AvgBlockMs = 3540
// BlocksFor converts a duration to blocks, rounding up.
func BlocksFor(seconds int64) int64 {
if seconds <= 0 {
return 0
}
return (seconds*1000 + AvgBlockMs - 1) / AvgBlockMs
}
gnomod.toml
module = "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2" gno = "0.9" [addpkg] creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06" height = 1237263 max_deposit = "20000000ugnot"
hash.gno
package safe
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"strconv"
"strings"
)
// MaxMerkleDepth bounds a proof: 2^32 leaves is far beyond any allowlist.
const MaxMerkleDepth = 32
func Sha256Hex(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
// --- commit–reveal v2 (design §4.2) --------------------------------------
//
// Every formula is domain-separated by platform, purpose, version, chain and
// collection, so a secret or commit is useless anywhere else (RA M-5). They
// live here, not in core, so the frontend's verifier, the beacon service and
// the tests all port one definition.
// Commit is the value a creator ("creator") or the beacon ("beacon") commits
// to for collection cid on chain chainID.
func Commit(chainID, cid, role, secret string) string {
return Sha256Hex(Domain + "|commit|v2|" + chainID + "|" + cid + "|" + role + "|" + secret)
}
// InitialEntropy seeds a collection's mint-entropy accumulator.
func InitialEntropy(chainID, cid string) string {
return Sha256Hex(Domain + "|acc|v2|" + chainID + "|" + cid)
}
// MixEntropy folds one mint call into the accumulator. The inputs are
// public, but none existed when the secrets were committed, which is what
// stops a committer from choosing the map their own mints receive.
func MixEntropy(acc string, to address, height, first, last int64) string {
return Sha256Hex(acc + "|" + to.String() + "|" + strconv.FormatInt(height, 10) + "|" +
strconv.FormatInt(first, 10) + "-" + strconv.FormatInt(last, 10))
}
// Salt binds both secrets ("" when not revealed) to the final accumulator.
func Salt(cid, creatorSecret, beaconSecret, acc string) string {
return Sha256Hex(Domain + "|salt|v2|" + cid + "|" + creatorSecret + "|" + beaconSecret + "|" + acc)
}
// Seed is the per-token engine seed once the salt is final.
func Seed(cid, tid, salt string) string {
return Sha256Hex(Domain + "|seed|v1|" + cid + "|" + tid + "|" + salt)
}
// --- allowlist merkle proofs (design §4.6) -------------------------------
// AllowlistLeaf is the leaf for addr in collection cid's allowlist tree.
func AllowlistLeaf(cid string, addr address) string {
return Sha256Hex(Domain + "|al|v1|" + cid + "|" + addr.String())
}
// MerkleVerify checks a sorted-pair sha256 proof ("hex,hex,…", leaf to
// root). An empty proof means the tree has a single leaf equal to the root.
// Malformed input is simply false: proofs come from untrusted callers.
func MerkleVerify(rootHex, leafHex, proof string) bool {
root, err := hex.DecodeString(rootHex)
if err != nil || len(root) != 32 {
return false
}
node, err := hex.DecodeString(leafHex)
if err != nil || len(node) != 32 {
return false
}
if proof != "" {
steps := strings.Split(proof, ",")
if len(steps) > MaxMerkleDepth {
return false
}
for _, step := range steps {
sibling, err := hex.DecodeString(step)
if err != nil || len(sibling) != 32 {
return false
}
node = hashPair(node, sibling)
}
}
return bytes.Equal(node, root)
}
// MerkleNodeTag prefixes every inner node (SA-I2): an inner node hashes
// 0x01 || lo || hi, while a leaf is the hash of a text that starts with
// Domain ("art|al|v1|…"), so an inner node can never be presented as a leaf
// or the other way round.
const MerkleNodeTag = byte(0x01)
// hashPair hashes the two children in byte order, so a proof needs no
// left/right flags.
func hashPair(a, b []byte) []byte {
if bytes.Compare(b, a) < 0 {
a, b = b, a
}
buf := make([]byte, 0, 65)
buf = append(buf, MerkleNodeTag)
buf = append(buf, a...)
buf = append(buf, b...)
sum := sha256.Sum256(buf)
return sum[:]
}
// MerkleParent is hashPair on hex nodes, for tests and the off-chain builder.
func MerkleParent(aHex, bHex string) string {
a, errA := hex.DecodeString(aHex)
b, errB := hex.DecodeString(bHex)
if errA != nil || errB != nil {
panic("MerkleParent: invalid hex")
}
return hex.EncodeToString(hashPair(a, b))
}
json.gno
package safe
import (
"chain/markdown"
"strconv"
"strings"
)
// Byte classes as 128-bit bitmaps for the native markdown.MatchCharsetN
// (one call checks a whole string at ~0.7 gas per byte; bytes >= 0x80 never
// match). jsonSafe: printable ASCII that JSONString copies unchanged (not
// '"', '\', '<', '>', '&', DEL). rawSafe: [A-Za-z0-9+/=:;,._-].
const (
jsonSafeLo = 0xafffffbb00000000
jsonSafeHi = 0x7fffffffefffffff
rawSafeLo = 0x2ffff80000000000
rawSafeHi = 0x07fffffe87fffffe
// jsonFastMin: below this length the byte loop is cheaper than the
// native call.
jsonFastMin = 8
)
// JSONString returns s as a quoted JSON string. Beyond the mandatory
// escapes it also escapes U+2028/U+2029 (RA L-12) and '<', '>', '&', so the
// output is safe to inline in HTML as well. Strings that need no escape
// (printable ASCII without '"', '\', '<', '>', '&') take a native fast
// path; the output is the same.
func JSONString(s string) string {
if len(s) >= jsonFastMin && markdown.MatchCharsetN(s, jsonSafeLo, jsonSafeHi, jsonSafeLo, jsonSafeHi, 0, len(s)) {
return "\"" + s + "\""
}
const hexDigits = "0123456789abcdef"
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch r {
case '"':
b.WriteString(`\"`)
case '\\':
b.WriteString(`\\`)
case '\n':
b.WriteString(`\n`)
case '\r':
b.WriteString(`\r`)
case '\t':
b.WriteString(`\t`)
case '<', '>', '&', 0x2028, 0x2029:
b.WriteString(`\u`)
b.WriteString(PadHex(int64(r), 4))
default:
if r < 0x20 || r == 0x7f {
b.WriteString(`\u00`)
b.WriteByte(hexDigits[(r>>4)&0xf])
b.WriteByte(hexDigits[r&0xf])
continue
}
b.WriteRune(r)
}
}
b.WriteByte('"')
return b.String()
}
// PadHex renders n in lowercase hex, zero-padded to width.
func PadHex(n int64, width int) string {
s := strconv.FormatInt(n, 16)
if len(s) >= width {
return s
}
return strings.Repeat("0", width-len(s)) + s
}
// JSONWriter is the single JSON producer of every read API (design
// §2.5: reads return primitives or JSON, never positional text). It tracks
// commas itself, so callers only describe structure:
//
// w := &safe.JSONWriter{}
// w.BeginObject(); w.Key("id"); w.Str("1"); w.EndObject()
type JSONWriter struct {
b strings.Builder
hasItems []bool // one entry per open container
afterKey bool
}
func (w *JSONWriter) BeginObject() { w.open('{') }
func (w *JSONWriter) EndObject() { w.close('}') }
func (w *JSONWriter) BeginArray() { w.open('[') }
func (w *JSONWriter) EndArray() { w.close(']') }
// Key starts an object member; the next value call writes its value.
func (w *JSONWriter) Key(k string) {
w.separate()
w.b.WriteString(JSONString(k))
w.b.WriteByte(':')
w.afterKey = true
}
func (w *JSONWriter) Str(v string) { w.value(JSONString(v)) }
func (w *JSONWriter) Int(v int64) { w.value(strconv.FormatInt(v, 10)) }
func (w *JSONWriter) Bool(v bool) { w.value(strconv.FormatBool(v)) }
// Raw writes v verbatim. Only for JSON produced by another JSONWriter.
func (w *JSONWriter) Raw(v string) { w.value(v) }
// RawStr writes v as a JSON string without escaping. v may only hold
// [A-Za-z0-9+/=:;,._-] (base64, hex, decimal, a data: URI header), which
// JSON never escapes; any other byte panics. One native pass instead of a
// rune loop: a 350 KB data URI costs well under 1M gas (M-4, UP-I1).
func (w *JSONWriter) RawStr(v string) {
if !markdown.MatchCharsetN(v, rawSafeLo, rawSafeHi, rawSafeLo, rawSafeHi, 0, len(v)) {
panic("JSONWriter: RawStr value may only hold [A-Za-z0-9+/=:;,._-]")
}
w.separate()
w.b.WriteByte('"')
w.b.WriteString(v)
w.b.WriteByte('"')
}
// RawStrField is Key + RawStr.
func (w *JSONWriter) RawStrField(k, v string) { w.Key(k); w.RawStr(v) }
// StrField and IntField are Key+value shorthands.
func (w *JSONWriter) StrField(k, v string) { w.Key(k); w.Str(v) }
func (w *JSONWriter) IntField(k string, v int64) { w.Key(k); w.Int(v) }
func (w *JSONWriter) BoolField(k string, v bool) { w.Key(k); w.Bool(v) }
func (w *JSONWriter) String() string { return w.b.String() }
func (w *JSONWriter) open(c byte) {
w.separate()
w.b.WriteByte(c)
w.hasItems = append(w.hasItems, false)
}
func (w *JSONWriter) close(c byte) {
if len(w.hasItems) == 0 {
panic("JSONWriter: close without open")
}
w.hasItems = w.hasItems[:len(w.hasItems)-1]
w.b.WriteByte(c)
}
func (w *JSONWriter) value(v string) {
w.separate()
w.b.WriteString(v)
}
// separate writes the comma before an item, except right after a key.
func (w *JSONWriter) separate() {
if w.afterKey {
w.afterKey = false
return
}
if n := len(w.hasItems); n > 0 {
if w.hasItems[n-1] {
w.b.WriteByte(',')
}
w.hasItems[n-1] = true
}
}
media.gno
package safe
import (
"encoding/hex"
"errors"
"strconv"
)
// Media checks, moved in from p/media/v1 (image.gno, cid.gno) so core can
// validate an engine's media (mainnet plan §2.1, M-3) without importing an
// upload package. Behaviour and error texts are unchanged ("media: …");
// the frontend twins are chain/cid.ts and the image header check of the
// upload layer (docs/test-vectors/upload-v1.json).
// IANA media types CheckImage and ImageDims understand. GIF is parsed for
// completeness; callers decide which types they accept.
const (
MimeSVG = "image/svg+xml"
MimePNG = "image/png"
MimeWebP = "image/webp"
MimeJPEG = "image/jpeg"
MimeGIF = "image/gif"
)
// Media limits.
const (
MaxDim = 4096 // px per side, decompression-bomb guard
MaxSVGImageBytes = 16384 // CheckImage's AssertSVG cap for an SVG file
)
// CID codecs.
const (
CodecRaw = 0x55
CodecDagPB = 0x70
)
// IPFSScheme prefixes an IPFS URI.
const IPFSScheme = "ipfs://"
func mediaErr(msg string) error { return errors.New("media: " + msg) }
// mimeShort is the short name used in error texts ("png", …), "" when the
// type is not a raster type ImageDims parses.
func mimeShort(mime string) string {
switch mime {
case MimePNG:
return "png"
case MimeWebP:
return "webp"
case MimeJPEG:
return "jpeg"
case MimeGIF:
return "gif"
}
return ""
}
// CheckImage checks a complete file against its declared IANA type: an SVG
// must pass AssertSVG with MaxSVGImageBytes; a raster file must carry the
// type's magic bytes and header dimensions of 1..MaxDim per side
// (ImageDims). Nothing else of a raster file is parsed: raster bytes are
// only ever shown through <img> (SA-M3).
func CheckImage(mime, data string) error {
if mime == MimeSVG {
return AssertSVG(data, MaxSVGImageBytes)
}
_, _, err := ImageDims(mime, data)
return err
}
// ImageDims returns a raster file's pixel dimensions after checking its
// magic bytes and header (PNG IHDR, WebP VP8/VP8L/VP8X, JPEG SOFn, GIF
// logical screen) and the 1..MaxDim bound per side.
func ImageDims(mime, data string) (w, h int, err error) {
switch mime {
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.Quote(mime))
}
if err != nil {
return 0, 0, err
}
if w < 1 || h < 1 || w > MaxDim || h > MaxDim {
return 0, 0, mediaErr(mimeShort(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
}
// 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
}
// IsIPFSURI reports whether s is IPFSScheme followed by a CIDv1 that
// ParseCIDv1 accepts.
func IsIPFSURI(s string) bool {
if len(s) <= len(IPFSScheme) || s[:len(IPFSScheme)] != IPFSScheme {
return false
}
_, _, err := ParseCIDv1(s[len(IPFSScheme):])
return err == 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).
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
}
money.gno
package safe
import (
"strconv"
"strings"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
)
// BpsDenominator is 100% in basis points (EIP-2981, royalty/v0).
const BpsDenominator = 10000
// BpsOf returns floor(amount * bps / 10000) without ever forming the full
// product, so it cannot overflow for any amount >= 0 and 0 <= bps <= 10000.
func BpsOf(amount, bps int64) int64 {
if amount < 0 {
panic("BpsOf: negative amount")
}
if bps < 0 || bps > BpsDenominator {
panic("BpsOf: bps out of range")
}
return (amount/BpsDenominator)*bps + (amount%BpsDenominator)*bps/BpsDenominator
}
// AssertBps panics unless 0 <= bps <= cap.
func AssertBps(field string, bps, cap int64) {
if bps < 0 || bps > cap {
panic(field + ": must be between 0 and " + strconv.FormatInt(cap, 10) + " bps")
}
}
// ParsePayees parses "g1…:7000,g1…:3000": 1..max distinct valid addresses,
// each with a positive share, shares summing to exactly 10000.
func ParsePayees(field, s string, max int) []types.Payee {
if s == "" {
panic(field + ": must not be empty")
}
parts := strings.Split(s, ",")
if len(parts) > max {
panic(field + ": at most " + strconv.Itoa(max) + " payees")
}
out := make([]types.Payee, 0, len(parts))
var total int64
for _, part := range parts {
addrStr, bpsStr, ok := strings.Cut(part, ":")
if !ok {
panic(field + ": expected address:bps, got " + strconv.Quote(part))
}
addr := address(addrStr)
if !addr.IsValid() {
panic(field + ": invalid address " + strconv.Quote(addrStr))
}
bps, err := strconv.ParseInt(bpsStr, 10, 64)
if err != nil || bps <= 0 || bps > BpsDenominator {
panic(field + ": invalid share " + strconv.Quote(bpsStr))
}
for _, p := range out {
if p.Addr == addr {
panic(field + ": duplicate payee " + addrStr)
}
}
total += bps
out = append(out, types.Payee{Addr: addr, Bps: bps})
}
if total != BpsDenominator {
panic(field + ": shares must sum to 10000 bps, got " + strconv.FormatInt(total, 10))
}
return out
}
// FormatPayees is the inverse of ParsePayees.
func FormatPayees(ps []types.Payee) string {
parts := make([]string, len(ps))
for i, p := range ps {
parts[i] = p.Addr.String() + ":" + strconv.FormatInt(p.Bps, 10)
}
return strings.Join(parts, ",")
}
// SplitByBps divides amount by the payees' shares. The rounding remainder
// goes to the first payee, so the parts always sum to exactly amount — the
// property every "no balance left behind" invariant (I-3, I-4) relies on.
func SplitByBps(amount int64, ps []types.Payee) []int64 {
if len(ps) == 0 {
panic("SplitByBps: no payees")
}
out := make([]int64, len(ps))
var given int64
for i, p := range ps {
out[i] = BpsOf(amount, p.Bps)
given += out[i]
}
out[0] += amount - given
return out
}
svg.gno
package safe
import (
"chain/markdown"
"errors"
"strconv"
"strings"
)
// AssertSVG checks an engine's raw SVG output with a strict allowlist
// (SA-M3; it replaced a substring blacklist that namespace prefixes, URL
// whitespace and CSS escapes could slip past). The document is tokenized
// as XML and must be well formed:
//
// - only the elements in svgElements, without a namespace prefix: no
// script, style, foreignObject, image, a, animation (set, animate*) or
// anything else that can run code, load a resource or redefine the page;
// - only the attributes in svgAttributeList, without a prefix except
// xlink:href and the two fixed xmlns declarations; event handlers and
// style= are therefore impossible;
// - attribute values hold no control character, backslash, '<', ':' or
// non-allowlisted entity, so no URL scheme (javascript:, data:, http:)
// can be spelled, however it is split or escaped; url() must be
// url(#id) and href must be #id;
// - (v2, WP-J J-4) no CSS <image> function that takes a URL as a string:
// no value may contain image(, image-set(, cross-fade( or element(
// (ASCII case-insensitive, Go lower-casing, so also -webkit-image-set(),
// İmage(), …), and mask must be exactly "none" or "url(#id)";
// - no comments, CDATA, doctype, entities or processing instructions.
//
// The frontend shows art only through <img>, which never runs scripts; this
// check is the defence in depth for every other place a data: URI ends up
// (wallets, explorers, indexers; RA M-7, design §5.4).
//
// v2 (mainnet plan §2.1, M-2) accepts exactly the documents v1 accepts,
// except the J-4 rule above, and returns the same error texts, at ~3k
// instead of ~30k gas per byte: one table-driven pass proves ordinary
// tokens clean, and every token it cannot prove clean goes through v1's
// checks unchanged (checkAttr, checkChars), so the first error found is
// v1's; the J-4 checks (checkCSSValue) run on a value only after v1's checks
// passed it. UTF-8 validity is one native MatchCharsetN call for ASCII
// documents, and long d/points values are skipped with native probes.
// Proof: v1's tests, the differential corpus zz_svg_corpus_test.gno (v2 =
// the TypeScript twin; v1 = v2 except on J-4 documents, listed by case) and
// the gas filetests z_svg_gas_*.
func AssertSVG(svg string, maxBytes int) error {
if len(svg) == 0 {
return errors.New("svg: empty")
}
if len(svg) > maxBytes {
return errors.New("svg: larger than " + strconv.Itoa(maxBytes) + " bytes")
}
if !validUTF8(svg) {
return errors.New("svg: invalid UTF-8")
}
if !strings.HasPrefix(svg, "<svg") || !strings.HasSuffix(svg, "</svg>") {
return errors.New("svg: must start with <svg and end with </svg>")
}
return scanSVG(svg)
}
const (
svgNS = "http://www.w3.org/2000/svg"
xlinkNS = "http://www.w3.org/1999/xlink"
)
// svgElements are the drawing elements an engine may use.
var svgElements = map[string]bool{
"svg": true, "g": true, "defs": true, "symbol": true, "use": true,
"title": true, "desc": true,
"path": true, "rect": true, "circle": true, "ellipse": true,
"line": true, "polyline": true, "polygon": true,
"text": true, "tspan": true,
"linearGradient": true, "radialGradient": true, "stop": true,
"clipPath": true, "mask": true, "pattern": true,
"filter": true, "feGaussianBlur": true, "feOffset": true, "feBlend": true,
"feColorMatrix": true, "feComposite": true, "feFlood": true, "feMerge": true,
"feMergeNode": true, "feMorphology": true, "feTurbulence": true,
"feDisplacementMap": true, "feComponentTransfer": true, "feFuncR": true,
"feFuncG": true, "feFuncB": true, "feFuncA": true,
}
// svgAttributeList holds the geometry, paint and filter attributes (the v1
// set, reordered: the first six have the fixed ids below). Absent on
// purpose: style, on*, src, every animation attribute (attributeName, to,
// from, by, begin), and every prefixed name except xlink:href. An
// attribute's id is its index + 1 (frontend chain/assertSvg.ts uses the
// same list).
var svgAttributeList = []string{
"xmlns", "xmlns:xlink", "href", "xlink:href", "d", "points",
"id", "class", "version", "viewBox", "preserveAspectRatio",
"x", "y", "x1", "y1", "x2", "y2", "cx", "cy", "r", "rx", "ry", "fx", "fy", "fr",
"width", "height", "pathLength", "transform",
"fill", "fill-opacity", "fill-rule",
"stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
"stroke-linejoin", "stroke-dasharray", "stroke-dashoffset", "stroke-miterlimit",
"opacity", "color", "visibility", "display",
"clip-path", "clip-rule", "mask", "filter",
"shape-rendering", "vector-effect", "paint-order", "mix-blend-mode",
"font-family", "font-size", "font-weight", "font-style",
"text-anchor", "dominant-baseline", "letter-spacing",
"textLength", "lengthAdjust", "dx", "dy", "rotate",
"gradientUnits", "gradientTransform", "spreadMethod",
"offset", "stop-color", "stop-opacity",
"patternUnits", "patternContentUnits", "patternTransform",
"clipPathUnits", "maskUnits", "maskContentUnits",
"filterUnits", "primitiveUnits", "result", "in", "in2",
"stdDeviation", "mode", "type", "values", "operator",
"k1", "k2", "k3", "k4", "radius",
"flood-color", "flood-opacity", "baseFrequency", "numOctaves",
"seed", "stitchTiles", "scale", "xChannelSelector", "yChannelSelector",
"tableValues", "slope", "intercept", "amplitude", "exponent",
}
const (
idXmlns = 1 + iota
idXmlnsXlink
idHref
idXlinkHref
idD
idPoints
idMask = 47 // "mask" (J-4: none or url(#id) only); checked in init
)
// svgAttrIDs maps an allowlisted attribute to its id (1..len); 0 = not allowed.
var svgAttrIDs = map[string]int{}
func init() {
if len(svgAttributeList) > 127 {
panic("safe: svgAttributeList outgrew the two-word seen mask")
}
for i, a := range svgAttributeList {
svgAttrIDs[a] = i + 1
}
if svgAttrIDs["mask"] != idMask {
panic("safe: idMask is not the id of mask")
}
}
// Byte classes, generated (256-byte tables indexed by the byte):
// - textClass: 0 plain, 1 '<', 2 '&', 3 byte >= 0x80, 4 control or DEL
// (not \t \n \r);
// - valueClass: 0 plain, 1 '"', 2 '\'', 3 'u', 'U' (url() check) or '('
// (J-4 function check), 4 '&', 5 byte >= 0x80, 6 '<', '>', ':', '\',
// control or DEL;
// - nameFirst / nameRest: XML name characters as v1 reads them (ASCII
// letters, '_', ':'; then also digits, '-', '.');
// - spaceClass: ' ', \t, \n, \r.
//
// valuePlainLo/Hi is valueClass 0 as a MatchCharsetN bitmap.
const (
textClass = "\x04\x04\x04\x04\x04\x04\x04\x04\x04\x00\x00\x04\x04\x00\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x04\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\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\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\x00\x00\x04\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03"
valueClass = "\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x00\x00\x01\x00\x00\x00\x04\x02\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x06\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05"
nameFirst = "\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\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\x01\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\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\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\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\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\x00\x00\x00\x00\x00"
nameRest = "\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\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\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\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\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\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\x00\x00\x00\x00\x00"
spaceClass = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\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\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\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\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\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\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\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"
valuePlainLo = 0xabfffe3b00000000
valuePlainHi = 0x7fdfffffefdfffff
)
func svgErr(msg string) error { return errors.New("svg: " + msg) }
// validUTF8 is utf8.ValidString: an ASCII document passes one native call;
// otherwise s is valid exactly when decoding to runes and re-encoding gives
// s back (an invalid byte decodes to U+FFFD, which re-encodes as EF BF BD,
// never as the byte itself).
func validUTF8(s string) bool {
if markdown.MatchCharsetN(s, ^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0), 0, len(s)) {
return true
}
return string([]rune(s)) == s
}
// plainRun returns the end of the run of valueClass-0 bytes that starts at
// i, found with native probes (doubling, then bisection); i when the run is
// shorter than the first probe.
func plainRun(s string, i int) int {
lim := len(s) - i
lo, hi := 0, 32
for {
if hi > lim {
hi = lim
}
if !markdown.MatchCharsetN(s[i:i+hi], valuePlainLo, valuePlainHi, valuePlainLo, valuePlainHi, 0, hi) {
break
}
lo = hi
if hi == lim {
return i + lo
}
hi *= 2
}
if lo == 0 {
return i
}
for hi-lo > 1 {
mid := (lo + hi) / 2
if markdown.MatchCharsetN(s[i:i+mid], valuePlainLo, valuePlainHi, valuePlainLo, valuePlainHi, 0, mid) {
lo = mid
} else {
hi = mid
}
}
return i + lo
}
// entityAt reports whether one of the five XML entities starts at s[i]. An
// entity holds no '<' or quote, so matching against the whole document is
// the same as v1's match against the text run or attribute value. The '&'
// lies before the '<' of the final "</svg>", so i+6 <= len(s).
func entityAt(s string, i int) bool {
switch s[i+1] {
case 'a':
return s[i:i+5] == "&" || s[i:i+6] == "'"
case 'l':
return s[i:i+4] == "<"
case 'g':
return s[i:i+4] == ">"
case 'q':
return s[i:i+6] == """
}
return false
}
// scanSVG is v1's parser as one pass. s starts with "<svg" and ends with
// "</svg>", so every '<' is at most at len(s)-6 and the last byte is '>':
// the table loops stop at one of them and need no bounds check, and no
// token can start inside the final "/svg>" except through its '<'.
func scanSVG(s string) error {
n := len(s)
// Every element needs at least 3 bytes ("<g>"), so the depth stays
// below n/3: the stack never grows (append would copy it).
stack := make([]string, n/3+1)
depth := 0
i := 0
rootDone := false
for i < n {
if rootDone {
return svgErr("content after the root element")
}
if s[i] != '<' {
// character data: printable characters, whitespace and the
// five XML entities only (v1 text + checkChars)
if depth == 0 {
return svgErr("text outside the root element")
}
start := i
for {
for textClass[s[i]] == 0 {
i++
}
k := textClass[s[i]]
if k == 1 {
break
}
if k == 2 && entityAt(s, i) {
i++
continue
}
if k == 3 && !(s[i] == 0xc2 && s[i+1] < 0xa0) { // not a C1 control
i++
continue
}
for i < n && s[i] != '<' {
i++
}
if err := checkChars(s[start:i], true); err != nil {
return err
}
break
}
continue
}
c := s[i+1]
if c == '!' {
return svgErr("comments, CDATA, doctype and entity declarations are not allowed")
}
if c == '?' {
return svgErr("processing instructions are not allowed")
}
if c == '/' {
i += 2
start := i
if nameFirst[s[i]] != 0 {
i++
for nameRest[s[i]] != 0 {
i++
}
}
name := s[start:i]
for spaceClass[s[i]] != 0 {
i++
}
if s[i] != '>' {
return svgErr("malformed closing tag")
}
i++
if depth == 0 || stack[depth-1] != name {
return svgErr("mismatched closing tag </" + name + ">")
}
depth--
if depth == 0 {
rootDone = true
}
continue
}
// open tag
i++
start := i
if nameFirst[s[i]] != 0 {
i++
for nameRest[s[i]] != 0 {
i++
}
}
name := s[start:i]
if name == "" {
return svgErr("malformed tag")
}
if !svgElements[name] { // no allowed element holds ':'
return svgErr("element <" + name + "> is not allowed")
}
first := depth == 0
selfClosed := false
var seenLo, seenHi uint64
for {
sp := false
if spaceClass[s[i]] != 0 {
sp = true
i++
for spaceClass[s[i]] != 0 {
i++
}
}
c := s[i]
if c == '>' {
i++
stack[depth] = name
depth++
break
}
if c == '/' {
if s[i+1] != '>' {
return svgErr("malformed tag <" + name + ">")
}
i += 2
selfClosed = true
break
}
if !sp {
return svgErr("attributes must be separated by whitespace in <" + name + ">")
}
astart := i
if nameFirst[s[i]] != 0 {
i++
for nameRest[s[i]] != 0 {
i++
}
}
attr := s[astart:i]
if attr == "" {
return svgErr("malformed attribute in <" + name + ">")
}
// A name outside the allowlist (id 0) fails after its value is
// read, as in v1, so it can never be a duplicate.
id := svgAttrIDs[attr]
if id > 0 {
if id < 64 {
b := uint64(1) << uint(id)
if seenLo&b != 0 {
return svgErr("duplicate attribute " + attr)
}
seenLo |= b
} else {
b := uint64(1) << uint(id-64)
if seenHi&b != 0 {
return svgErr("duplicate attribute " + attr)
}
seenHi |= b
}
}
for spaceClass[s[i]] != 0 {
i++
}
if s[i] != '=' {
return svgErr("attribute " + attr + " needs a value")
}
i++
for spaceClass[s[i]] != 0 {
i++
}
q := s[i]
if q != '"' && q != '\'' {
return svgErr("attribute " + attr + " must be quoted")
}
qk := byte(1)
if q == '\'' {
qk = 2
}
i++
vstart := i
if id == idD || id == idPoints {
i = plainRun(s, i)
}
// mask (J-4) always takes the v1 path, then checkCSSValue
slow := id == idMask
chk := 0 // 1: url() check, 2: a CSS image function (J-4)
for {
for valueClass[s[i]] == 0 {
i++
}
k := valueClass[s[i]]
if k == qk {
break
}
if k <= 2 { // the other quote
i++
continue
}
if k == 3 {
if s[i] != '(' {
chk |= 1
} else if e, p := s[i-1]|0x20, s[i-2]|0x20; ((e == 'e' && (p == 'g' || p == 'd')) ||
(e == 't' && (p == 'e' || p == 'n'))) && cssImageFuncBefore(s, vstart, i) {
// prefilter: every word ends in "ge", "de", "et" or "nt"
// (rotate(, translate(, scale( … never call it)
chk |= 2
}
i++
continue
}
if k == 4 && entityAt(s, i) {
i++
continue
}
if k == 5 && !(s[i] == 0xc2 && s[i+1] < 0xa0) { // not a C1 control
i++
continue
}
slow = true
break
}
if slow {
for i < n && s[i] != q {
i++
}
if i >= n {
return svgErr("unterminated value of " + attr)
}
val := s[vstart:i]
i++
if err := checkAttr(name, attr, val); err != nil {
return err
}
if err := checkCSSValue(id, attr, val); err != nil {
return err
}
continue
}
// clean value: checkChars and the ':' '\' '<' rule pass
val := s[vstart:i]
i++
if id == 0 {
return svgErr("attribute " + attr + " is not allowed")
}
if id <= idXlinkHref {
if id == idXmlns {
return svgErr("xmlns must be " + svgNS) // a clean value holds no ':'
}
if id == idXmlnsXlink {
return svgErr("xmlns:xlink must be " + xlinkNS)
}
if !isFragment(val) {
return svgErr("references must stay inside the document (#id)")
}
continue
}
if chk != 0 {
if chk&1 != 0 {
if err := checkURLRefsLowered(val); err != nil {
return err
}
}
if chk&2 != 0 {
return svgErr("attribute " + attr + cssImageFuncErr)
}
}
}
if first && name != "svg" {
return svgErr("the root element must be <svg>")
}
if selfClosed && depth == 0 {
rootDone = true
}
}
if depth != 0 {
return svgErr("unclosed element <" + stack[depth-1] + ">")
}
if !rootDone {
return svgErr("no root element")
}
return nil
}
// checkAttr is v1's attribute check, unchanged: allowlist, the two xmlns
// values, characters, ':' '\' '<', href, url().
func checkAttr(elem, attr, val string) error {
if svgAttrIDs[attr] == 0 {
return svgErr("attribute " + attr + " is not allowed")
}
switch attr {
case "xmlns":
if val != svgNS {
return svgErr("xmlns must be " + svgNS)
}
return nil
case "xmlns:xlink":
if val != xlinkNS {
return svgErr("xmlns:xlink must be " + xlinkNS)
}
return nil
}
if err := checkChars(val, false); err != nil {
return svgErr("attribute " + attr + ": " + err.Error())
}
if strings.ContainsAny(val, ":\\<") {
return svgErr("attribute " + attr + " contains a forbidden character (':', '\\' or '<')")
}
if attr == "href" || attr == "xlink:href" {
if !isFragment(val) {
return svgErr("references must stay inside the document (#id)")
}
return nil
}
return checkURLRefs(val)
}
// checkCSSValue is the J-4 rule (v2 only), run on a value v1's checks
// passed: no CSS function that takes an image URL as a string (a
// protocol-relative or path URL needs no ':' and no url(), and browsers
// fetch it when the SVG is inlined or opened as a document), and mask is
// exactly "none" or "url(#id)" (the one allowlisted attribute whose CSS
// property takes an <image>).
func checkCSSValue(id int, attr, val string) error {
for i := 0; i < len(val); i++ {
if val[i] == '(' && cssImageFuncBefore(val, 0, i) {
return svgErr("attribute " + attr + cssImageFuncErr)
}
}
if id == idMask && val != "none" &&
!(len(val) >= 7 && val[:5] == "url(#" && val[len(val)-1] == ')' && isFragment(val[4:len(val)-1])) {
return svgErr("mask must be none or url(#id)")
}
return nil
}
const cssImageFuncErr = " uses a CSS image function (image, image-set, cross-fade, element)"
// cssImageFuncs are the CSS functions that take an image URL as a string
// (J-4); with the '(' after them, a value may not contain them.
var cssImageFuncs = []string{"image", "image-set", "cross-fade", "element"}
// cssImageFuncBefore reports whether s[start:p] (p is a '(') ends with one
// of cssImageFuncs after Go's strings.ToLower: ASCII letters fold, and the
// only non-ASCII rune lowering to a letter of these words is U+0130 ('i';
// U+212A lowers to 'k', which none holds). Every other byte compares exactly.
func cssImageFuncBefore(s string, start, p int) bool {
for _, w := range cssImageFuncs {
j := p
k := len(w) - 1
for ; k >= 0; k-- {
c := w[k]
if j > start && (s[j-1] == c || (c >= 'a' && c <= 'z' && s[j-1]|0x20 == c)) {
j--
continue
}
if c == 'i' && j-1 > start && s[j-2] == 0xc4 && s[j-1] == 0xb0 { // U+0130
j -= 2
continue
}
break
}
if k < 0 {
return true
}
}
return false
}
// checkURLRefs is v1's url() rule: every url( must hold #id.
func checkURLRefs(val string) error {
low := strings.ToLower(val)
for {
k := strings.Index(low, "url")
if k < 0 {
return nil
}
rest := strings.TrimLeft(low[k+3:], " ")
if !strings.HasPrefix(rest, "(") {
low = low[k+3:]
continue
}
rest = strings.TrimLeft(rest[1:], " ")
end := strings.IndexByte(rest, ')')
if end < 0 || !isFragment(strings.TrimRight(rest[:end], " ")) {
return svgErr("references must stay inside the document (url(#id))")
}
low = rest[end:]
}
}
// checkURLRefsLowered is checkURLRefs without strings.ToLower: it scans val
// once and compares case-insensitively. The url() rule only looks at ASCII
// bytes ("url", '(', ')', ' ', fragment characters); the only non-ASCII
// runes Go's ToLower maps to ASCII are U+0130 (to 'i') and U+212A (to 'k'),
// so fragmentLowered accepts their UTF-8 forms as fragment characters.
// Every other non-ASCII byte fails a match either way. val is valid UTF-8.
func checkURLRefsLowered(val string) error {
n := len(val)
p := 0
for {
k := -1
for j := p; j+2 < n; j++ {
if val[j]|0x20 == 'u' && val[j+1]|0x20 == 'r' && val[j+2]|0x20 == 'l' {
k = j
break
}
}
if k < 0 {
return nil
}
r := k + 3
for r < n && val[r] == ' ' {
r++
}
if r >= n || val[r] != '(' {
p = k + 3
continue
}
r++
for r < n && val[r] == ' ' {
r++
}
e := r
for e < n && val[e] != ')' {
e++
}
if e >= n {
return svgErr("references must stay inside the document (url(#id))")
}
t := e
for t > r && val[t-1] == ' ' {
t--
}
if !fragmentLowered(val[r:t]) {
return svgErr("references must stay inside the document (url(#id))")
}
p = e
}
}
// fragmentLowered is isFragment(strings.ToLower(v)) for valid UTF-8 v.
func fragmentLowered(v string) bool {
if len(v) < 2 || v[0] != '#' {
return false
}
for i := 1; i < len(v); i++ {
c := v[i]
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' {
continue
}
if c == 0xe2 && i+2 < len(v) && v[i+1] == 0x84 && v[i+2] == 0xaa { // U+212A KELVIN SIGN -> 'k'
i += 2
continue
}
if c == 0xc4 && i+1 < len(v) && v[i+1] == 0xb0 { // U+0130 -> 'i'
i++
continue
}
return false
}
return true
}
// checkChars allows printable characters and the five XML entities; text
// (character data) may also hold whitespace, attribute values only spaces.
func checkChars(s string, isText bool) error {
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '&':
ok := false
for _, e := range []string{"&", "<", ">", """, "'"} {
if strings.HasPrefix(s[i:], e) {
ok = true
break
}
}
if !ok {
return svgErr("only & < > " ' entities are allowed")
}
case c == 0x7f || (c < 0x20 && !(isText && isSpace(c))):
return svgErr("control characters are not allowed")
case c == '>' && !isText:
return svgErr("'>' in an attribute value")
}
}
for _, r := range s {
if r >= 0x80 && r <= 0x9f {
return svgErr("control characters are not allowed")
}
}
return nil
}
func isFragment(v string) bool {
if len(v) < 2 || v[0] != '#' {
return false
}
for i := 1; i < len(v); i++ {
c := v[i]
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') {
return false
}
}
return true
}
func isSpace(c byte) bool {
return c == ' ' || c == '\t' || c == '\n' || c == '\r'
}
text.gno
// Package safe holds the pure checks and formulas every platform realm
// shares: text and SVG validation, basis-point math, payee splits, merkle
// proofs, provenance hashes and the one JSON writer. Nothing here has state.
package safe
import (
"errors"
"strconv"
"strings"
"unicode/utf8"
)
// Domain separates every hash this platform commits to from hashes of the
// same bytes made for any other purpose. It equals the brand slug and
// changes with it (paths change anyway when the brand is chosen).
const Domain = "art"
// CheckText reports why s may not be stored as user-visible text.
//
// Rejected: invalid UTF-8; C0 and C1 control characters, which include tab,
// newline and carriage return (the record-injection vector of RA H-1); DEL;
// U+2028/U+2029, which end a line in older JavaScript parsers (RA L-12); and
// every bidi control or zero-width character that lets one string render as
// another.
func CheckText(s string, maxLen int) error {
if len(s) > maxLen {
return errors.New("too long (max " + strconv.Itoa(maxLen) + " bytes)")
}
if !utf8.ValidString(s) {
return errors.New("invalid UTF-8")
}
for _, r := range s {
if forbiddenRune(r) {
return errors.New("forbidden character U+" + strings.ToUpper(strconv.FormatInt(int64(r), 16)))
}
}
return nil
}
// AssertText panics with the field name when CheckText rejects s.
func AssertText(field, s string, maxLen int) {
if err := CheckText(s, maxLen); err != nil {
panic(field + ": " + err.Error())
}
}
// AssertNonEmptyText is AssertText that also refuses "".
func AssertNonEmptyText(field, s string, maxLen int) {
if s == "" {
panic(field + ": must not be empty")
}
AssertText(field, s, maxLen)
}
func forbiddenRune(r rune) bool {
switch {
case r < 0x20, r == 0x7f, r >= 0x80 && r <= 0x9f:
return true
case r == 0x061c, r == 0xfeff: // Arabic letter mark, zero-width no-break space
return true
case r >= 0x200b && r <= 0x200f: // zero-width space/joiners, LRM, RLM
return true
case r == 0x2028, r == 0x2029:
return true
case r >= 0x202a && r <= 0x202e: // bidi embeddings and overrides
return true
case r >= 0x2066 && r <= 0x2069: // bidi isolates
return true
}
return false
}
// AssertSymbol enforces the grc721 symbol alphabet ([A-Za-z0-9_-], 1..11
// bytes) up front, so the error names the field instead of surfacing from
// grc721.NewToken.
func AssertSymbol(field, s string) {
if s == "" || len(s) > 11 {
panic(field + ": must be 1-11 characters")
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-') {
panic(field + ": only A-Z, a-z, 0-9, '_' and '-' are allowed")
}
}
}
// AssertHex checks that s is exactly nBytes of hex and returns it lowercased.
func AssertHex(field, s string, nBytes int) string {
if len(s) != 2*nBytes {
panic(field + ": must be " + strconv.Itoa(2*nBytes) + " hex characters")
}
low := strings.ToLower(s)
for i := 0; i < len(low); i++ {
c := low[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
panic(field + ": must be hex")
}
}
return low
}
// ParseID parses a positive decimal id ("1", "42"). Leading zeros, signs
// and empty strings are refused so every id has exactly one spelling.
func ParseID(field, s string) int64 {
if s == "" || len(s) > 18 || s[0] == '0' {
panic(field + ": invalid id " + strconv.Quote(s))
}
var n int64
for i := 0; i < len(s); i++ {
c := s[i]
if c < '0' || c > '9' {
panic(field + ": invalid id " + strconv.Quote(s))
}
n = n*10 + int64(c-'0')
}
return n
}
// PadInt renders n with leading zeros to width digits, so decimal ids and
// prices sort correctly as avl keys. n must be >= 0.
func PadInt(n int64, width int) string {
s := strconv.FormatInt(n, 10)
if len(s) >= width {
return s
}
return strings.Repeat("0", width-len(s)) + s
}
// XMLEscape makes s safe as SVG/XML character data or a quoted attribute.
func XMLEscape(s string) string {
var b strings.Builder
for _, r := range s {
switch r {
case '&':
b.WriteString("&")
case '<':
b.WriteString("<")
case '>':
b.WriteString(">")
case '"':
b.WriteString(""")
case '\'':
b.WriteString("'")
default:
b.WriteRune(r)
}
}
return b.String()
}