Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

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/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/sinopia/safe/v1"
gno = "0.9"

[addpkg]
  creator = "g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w"
  height = 799253
  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)
}

// 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, 64)
	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/g19dzk54hhsdc3gllpksuj6gu4a3e6fl8cr6rn4w/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"
)

// forbiddenSVG lists constructs that can run code, load something from the
// network or redefine the document. Engines draw with shapes and paths;
// none of these is needed for that (RA M-7).
var forbiddenSVG = []string{
	"<script", "javascript:", "vbscript:", "<foreignobject", "<iframe",
	"<object", "<embed", "<image", "<!entity", "<!doctype", "<?xml-stylesheet",
	"@import", "&#", // numeric character references would hide a scheme from this scan
}

// AssertSVG checks an engine's raw SVG output: size, envelope, the forbidden
// constructs above, inline event handlers, and any href or url() that does
// not point inside the document. 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 (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>")
	}
	low := strings.ToLower(svg)
	for _, bad := range forbiddenSVG {
		if strings.Contains(low, bad) {
			return errors.New("svg: forbidden construct " + strconv.Quote(bad))
		}
	}
	if hasEventHandler(low) {
		return errors.New("svg: inline event handlers are not allowed")
	}
	if hasExternalRef(low, "href") || hasExternalRef(low, "url(") {
		return errors.New("svg: references must stay inside the document (#id)")
	}
	return nil
}

// hasEventHandler finds an attribute named on<letters> (onload=, onclick =).
func hasEventHandler(low string) bool {
	for i := 0; i+2 < len(low); i++ {
		if low[i] != 'o' || low[i+1] != 'n' {
			continue
		}
		if i > 0 && !isAttrBoundary(low[i-1]) {
			continue
		}
		j := i + 2
		for j < len(low) && low[j] >= 'a' && low[j] <= 'z' {
			j++
		}
		if j == i+2 {
			continue
		}
		for j < len(low) && isSpace(low[j]) {
			j++
		}
		if j < len(low) && low[j] == '=' {
			return true
		}
	}
	return false
}

// hasExternalRef reports an href attribute or url( whose target does not
// start with '#'. key is "href" (also matches xlink:href) or "url(".
func hasExternalRef(low, key string) bool {
	rest := low
	for {
		i := strings.Index(rest, key)
		if i < 0 {
			return false
		}
		j := i + len(key)
		if key == "href" {
			for j < len(rest) && isSpace(rest[j]) {
				j++
			}
			if j >= len(rest) || rest[j] != '=' {
				rest = rest[i+len(key):]
				continue
			}
			j++
		}
		for j < len(rest) && (isSpace(rest[j]) || rest[j] == '"' || rest[j] == '\'') {
			j++
		}
		if j >= len(rest) || rest[j] != '#' {
			return true
		}
		rest = rest[j:]
	}
}

func isAttrBoundary(c byte) bool {
	return isSpace(c) || c == '"' || c == '\'' || c == '/'
}

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("&amp;")
		case '<':
			b.WriteString("&lt;")
		case '>':
			b.WriteString("&gt;")
		case '"':
			b.WriteString("&quot;")
		case '\'':
			b.WriteString("&apos;")
		default:
			b.WriteRune(r)
		}
	}
	return b.String()
}