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/sinopia/safe/v1" gno = "0.9" [addpkg] creator = "g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06" height = 829610 max_deposit = "100000000ugnot"
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 (
"strconv"
"strings"
)
// 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.
func JSONString(s string) string {
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) }
// 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
}
}
money.gno
package safe
import (
"strconv"
"strings"
"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/types/v1"
)
// 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 (
"errors"
"strconv"
"strings"
"unicode/utf8"
)
// 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 svgAttributes, 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;
// - 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).
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 !utf8.ValidString(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>")
}
p := &svgParser{s: svg}
return p.run()
}
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,
}
// svgAttributes are geometry, paint and filter attributes. Absent on
// purpose: style, on*, src, every animation attribute (attributeName, to,
// from, by, begin), and every prefixed name except xlink:href.
var svgAttributes = map[string]bool{
"id": true, "class": true, "version": true, "viewBox": true, "preserveAspectRatio": true,
"x": true, "y": true, "x1": true, "y1": true, "x2": true, "y2": true,
"cx": true, "cy": true, "r": true, "rx": true, "ry": true, "fx": true, "fy": true, "fr": true,
"width": true, "height": true, "d": true, "points": true, "pathLength": true,
"transform": true, "href": true, "xlink:href": true,
"fill": true, "fill-opacity": true, "fill-rule": true,
"stroke": true, "stroke-width": true, "stroke-opacity": true, "stroke-linecap": true,
"stroke-linejoin": true, "stroke-dasharray": true, "stroke-dashoffset": true, "stroke-miterlimit": true,
"opacity": true, "color": true, "visibility": true, "display": true,
"clip-path": true, "clip-rule": true, "mask": true, "filter": true,
"shape-rendering": true, "vector-effect": true, "paint-order": true, "mix-blend-mode": true,
"font-family": true, "font-size": true, "font-weight": true, "font-style": true,
"text-anchor": true, "dominant-baseline": true, "letter-spacing": true,
"textLength": true, "lengthAdjust": true, "dx": true, "dy": true, "rotate": true,
"gradientUnits": true, "gradientTransform": true, "spreadMethod": true,
"offset": true, "stop-color": true, "stop-opacity": true,
"patternUnits": true, "patternContentUnits": true, "patternTransform": true,
"clipPathUnits": true, "maskUnits": true, "maskContentUnits": true,
"filterUnits": true, "primitiveUnits": true, "result": true, "in": true, "in2": true,
"stdDeviation": true, "mode": true, "type": true, "values": true, "operator": true,
"k1": true, "k2": true, "k3": true, "k4": true, "radius": true,
"flood-color": true, "flood-opacity": true, "baseFrequency": true, "numOctaves": true,
"seed": true, "stitchTiles": true, "scale": true, "xChannelSelector": true, "yChannelSelector": true,
"tableValues": true, "slope": true, "intercept": true, "amplitude": true, "exponent": true,
"xmlns": true, "xmlns:xlink": true,
}
type svgParser struct {
s string
i int
stack []string
}
func svgErr(msg string) error { return errors.New("svg: " + msg) }
func (p *svgParser) run() error {
rootDone := false
for p.i < len(p.s) {
if rootDone {
return svgErr("content after the root element")
}
if p.s[p.i] != '<' {
if err := p.text(); err != nil {
return err
}
continue
}
if p.i+1 >= len(p.s) {
return svgErr("unterminated tag")
}
c := p.s[p.i+1]
switch {
case c == '!':
return svgErr("comments, CDATA, doctype and entity declarations are not allowed")
case c == '?':
return svgErr("processing instructions are not allowed")
case c == '/':
if err := p.closeTag(); err != nil {
return err
}
if len(p.stack) == 0 {
rootDone = true
}
default:
first := len(p.stack) == 0
name, selfClosed, err := p.openTag()
if err != nil {
return err
}
if first && name != "svg" {
return svgErr("the root element must be <svg>")
}
if selfClosed && len(p.stack) == 0 {
rootDone = true
}
}
}
if len(p.stack) != 0 {
return svgErr("unclosed element <" + p.stack[len(p.stack)-1] + ">")
}
if !rootDone {
return svgErr("no root element")
}
return nil
}
// text is character data: printable characters, whitespace and the five
// XML entities only.
func (p *svgParser) text() error {
if len(p.stack) == 0 {
return svgErr("text outside the root element")
}
start := p.i
for p.i < len(p.s) && p.s[p.i] != '<' {
p.i++
}
return checkChars(p.s[start:p.i], true)
}
func (p *svgParser) openTag() (string, bool, error) {
p.i++ // '<'
name := p.name()
if name == "" {
return "", false, svgErr("malformed tag")
}
if strings.Contains(name, ":") || !svgElements[name] {
return "", false, svgErr("element <" + name + "> is not allowed")
}
seen := map[string]bool{}
for {
sp := p.spaces()
if p.i >= len(p.s) {
return "", false, svgErr("unterminated tag <" + name + ">")
}
switch p.s[p.i] {
case '>':
p.i++
p.stack = append(p.stack, name)
return name, false, nil
case '/':
if p.i+1 >= len(p.s) || p.s[p.i+1] != '>' {
return "", false, svgErr("malformed tag <" + name + ">")
}
p.i += 2
return name, true, nil
}
if !sp {
return "", false, svgErr("attributes must be separated by whitespace in <" + name + ">")
}
attr := p.name()
if attr == "" {
return "", false, svgErr("malformed attribute in <" + name + ">")
}
if seen[attr] {
return "", false, svgErr("duplicate attribute " + attr)
}
seen[attr] = true
p.spaces()
if p.i >= len(p.s) || p.s[p.i] != '=' {
return "", false, svgErr("attribute " + attr + " needs a value")
}
p.i++
p.spaces()
if p.i >= len(p.s) || (p.s[p.i] != '"' && p.s[p.i] != '\'') {
return "", false, svgErr("attribute " + attr + " must be quoted")
}
q := p.s[p.i]
p.i++
start := p.i
for p.i < len(p.s) && p.s[p.i] != q {
p.i++
}
if p.i >= len(p.s) {
return "", false, svgErr("unterminated value of " + attr)
}
val := p.s[start:p.i]
p.i++
if err := checkAttr(name, attr, val); err != nil {
return "", false, err
}
}
}
func (p *svgParser) closeTag() error {
p.i += 2 // "</"
name := p.name()
p.spaces()
if p.i >= len(p.s) || p.s[p.i] != '>' {
return svgErr("malformed closing tag")
}
p.i++
if len(p.stack) == 0 || p.stack[len(p.stack)-1] != name {
return svgErr("mismatched closing tag </" + name + ">")
}
p.stack = p.stack[:len(p.stack)-1]
return nil
}
// name reads an XML name made of ASCII letters, digits, '-', '_', '.', ':'.
func (p *svgParser) name() string {
start := p.i
for p.i < len(p.s) {
c := p.s[p.i]
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' ||
(p.i > start && ((c >= '0' && c <= '9') || c == '-' || c == '.')) {
p.i++
continue
}
break
}
return p.s[start:p.i]
}
func (p *svgParser) spaces() bool {
start := p.i
for p.i < len(p.s) && isSpace(p.s[p.i]) {
p.i++
}
return p.i > start
}
func checkAttr(elem, attr, val string) error {
if !svgAttributes[attr] {
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
}
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:]
}
}
// 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()
}