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

errors.gno

package gnopm

import "errors"

// Stable, machine-readable error values. Callers (realms, clients, indexers)
// switch on these rather than on message text: a realm turns them into panics,
// and the panic string is the only thing a user ever sees.
var (
	ErrInvalidPkgPath   = errors.New("gnopm: invalid package path")
	ErrInvalidRepo      = errors.New("gnopm: invalid repository URL")
	ErrInvalidCommit    = errors.New("gnopm: invalid commit id")
	ErrInvalidDir       = errors.New("gnopm: invalid directory")
	ErrInvalidRef       = errors.New("gnopm: invalid ref name")
	ErrClaimNotFound    = errors.New("gnopm: no such claim")
	ErrTooManyClaimants = errors.New("gnopm: too many claimants for this package")
)

gnomod.toml

module = "gno.land/p/nym-moultest123/gnopm/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186404
  max_deposit = "17000000ugnot"

helpers_test.gno

package gnopm

// Fixtures shared by the tests in this package.
//
// addrNS is moul's mainnet address, used wherever a test needs a real bech32
// address rather than a plausible-looking string: the address-namespace rule
// turns on the bech32 alphabet, so a made-up "g1aaa..." would pass or fail for
// the wrong reason.
const (
	addrNS   = "g1manfred47kzduec920z88wfr64ylksmdcedlf5"
	alice    = address("g1ubwjz3jmrjwmpuvrsjzgy5qkxf5wrgphzmd2tk")
	bob      = address("g1e8vw6gh284q7ggzqs66ug0zvyf42tzsf5zdhsk")
	carol    = address("g1v9kxjcm9ta047h6lta047h6lta047h6lz7gmv8")
	sha1Zero = "0000000000000000000000000000000000000000"
	sha1One  = "1111111111111111111111111111111111111111"
)

// resolver builds an r/sys/users stand-in from a name -> address table, so the
// ownership rule is tested without importing a realm.
func resolver(table map[string]address) func(string) (address, bool) {
	return func(name string) (address, bool) {
		a, ok := table[name]
		return a, ok
	}
}

pkgpath.gno

package gnopm

import "strings"

// Parsing a gno package path far enough to know who owns it.
//
// A path is "<domain>/<kind>/<namespace>/<name...>", optionally ending in a
// "/vN" version element: "gno.land/p/nym-moultest123/md/v1", "gno.land/r/sys/users",
// "gno.land/r/g1abc.../scratch/v0". The namespace is the third element and it
// is the whole reason this file exists: it decides whether a claim comes from
// the party that controls the path or from a stranger, which is the strongest
// signal the registry can offer about a claim it can never itself verify.

// SplitPkgPath breaks a package path into its domain, kind ("p" or "r"),
// namespace and the remainder. ok is false for anything that is not shaped like
// a publishable gno path.
func SplitPkgPath(s string) (domain, kind, ns, rest string, ok bool) {
	if !ValidPkgPath(s) {
		return "", "", "", "", false
	}
	parts := strings.Split(s, "/")
	return parts[0], parts[1], parts[2], strings.Join(parts[3:], "/"), true
}

// Namespace returns the owning namespace of a package path, or "" if the path
// is not one.
func Namespace(s string) string {
	_, _, ns, _, ok := SplitPkgPath(s)
	if !ok {
		return ""
	}
	return ns
}

// Version returns the trailing "vN" element of a package path, or "" when the
// path carries none. Absent is legal and is not an error: gnoweb serves
// gno.land/u/<name> by calling the realm at exactly /r/<name>/home, so that one
// path can never carry a version.
func Version(s string) string {
	parts := strings.Split(s, "/")
	if len(parts) < 4 {
		return ""
	}
	last := parts[len(parts)-1]
	if len(last) < 2 || last[0] != 'v' {
		return ""
	}
	for i := 1; i < len(last); i++ {
		if last[i] < '0' || last[i] > '9' {
			return ""
		}
	}
	return last
}

// ValidPkgPath reports whether s is shaped like a publishable gno package path.
//
// It does NOT say the path exists on any chain, and cannot: a realm has no way
// to ask whether some other path was ever deployed. That gap is the registry's
// central honesty problem and is documented on Registry.
func ValidPkgPath(s string) bool {
	if s == "" || len(s) > MaxPkgPathLen {
		return false
	}
	if strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") || strings.Contains(s, "//") {
		return false
	}
	parts := strings.Split(s, "/")
	if len(parts) < 4 {
		return false
	}
	// The domain, which is a host and so must carry a dot.
	if !strings.Contains(parts[0], ".") {
		return false
	}
	if parts[1] != "p" && parts[1] != "r" {
		return false
	}
	for _, p := range parts {
		if p == "" || p == "." || p == ".." {
			return false
		}
		for i := 0; i < len(p); i++ {
			if !pathByteOK(p[i]) {
				return false
			}
		}
	}
	return true
}

// AddressNamespace reports whether ns is shaped like a gno bech32 address, the
// namespace every account owns without registering anything. A caller still
// has to check it is the claimant's own address; this only says which of the
// two ownership rules applies.
func AddressNamespace(ns string) bool {
	if len(ns) != 40 || !strings.HasPrefix(ns, "g1") {
		return false
	}
	for i := 2; i < len(ns); i++ {
		if !strings.ContainsRune(bech32Charset, rune(ns[i])) {
			return false
		}
	}
	return true
}

// bech32Charset is bech32's data alphabet: lowercase alphanumerics minus the
// four characters it drops to avoid transcription errors (1, b, i, o).
const bech32Charset = "023456789acdefghjklmnpqrstuvwxyz"

pkgpath_test.gno

package gnopm

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestValidPkgPath(t *testing.T) {
	cases := []struct {
		name string
		in   string
		want bool
	}{
		{"versioned package", "gno.land/p/nym-moultest123/md/v1", true},
		{"versioned realm", "gno.land/r/nym-moultest123/gnopm/registry/v0", true},
		{"unversioned realm", "gno.land/r/sys/users", true},
		{"address namespace", "gno.land/r/" + addrNS + "/scratch/v0", true},

		{"empty", "", false},
		{"too few elements", "gno.land/p/moul", false},
		{"domain without a dot", "gnoland/p/nym-moultest123/md/v1", false},
		{"unknown kind", "gno.land/x/moul/md/v1", false},
		{"leading slash", "/gno.land/p/nym-moultest123/md/v1", false},
		{"trailing slash", "gno.land/p/nym-moultest123/md/v1/", false},
		{"double slash", "gno.land/p//moul/md", false},
		{"parent traversal", "gno.land/p/nym-moultest123/../md", false},
		{"space", "gno.land/p/nym-moultest123/m d", false},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, ValidPkgPath(tc.in), tc.name)
	}
}

func TestSplitPkgPath(t *testing.T) {
	domain, kind, ns, rest, ok := SplitPkgPath("gno.land/r/nym-moultest123/gnopm/registry/v0")
	uassert.True(t, ok, "splits")
	uassert.Equal(t, "gno.land", domain)
	uassert.Equal(t, "r", kind)
	uassert.Equal(t, "moul", ns)
	uassert.Equal(t, "gnopm/registry/v0", rest)

	_, _, _, _, ok = SplitPkgPath("nonsense")
	uassert.False(t, ok, "rejects a non-path")

	uassert.Equal(t, "moul", Namespace("gno.land/p/nym-moultest123/md/v1"))
	uassert.Equal(t, "", Namespace("nonsense"))
}

func TestVersion(t *testing.T) {
	cases := []struct {
		in, want string
	}{
		{"gno.land/p/nym-moultest123/md/v1", "v1"},
		{"gno.land/p/nym-moultest123/md/v0", "v0"},
		{"gno.land/p/nym-moultest123/md/v10", "v10"},
		{"gno.land/r/sys/users", ""},   // unversioned is legal
		{"gno.land/r/nym-moultest123/home", ""},   // the one path that can never carry one
		{"gno.land/p/nym-moultest123/md/vx", ""},  // not a number
		{"gno.land/p/nym-moultest123/md/v", ""},   // no digits
		{"short", ""},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, Version(tc.in), tc.in)
	}
}

func TestAddressNamespace(t *testing.T) {
	uassert.True(t, AddressNamespace(addrNS), "a real address")
	uassert.False(t, AddressNamespace("moul"), "a name")
	uassert.False(t, AddressNamespace(""), "empty")
	// b, i, o and 1 are exactly the characters bech32 drops.
	uassert.False(t, AddressNamespace("g1bbbfred47kzduec920z88wfr64ylksmdcedlf5"), "wrong length")
}

registry.gno

// Package gnopm is the domain model of a source registry for gno packages: a
// map from a deployed package path back to the repository, commit and directory
// that produced it.
//
// It exists because gno deliberately broke the link Go gets for free. A Go
// import path IS a repository URL, so pkg.go.dev needs no registry; a gno
// import path is a chain address, so nothing anywhere says which source
// produced the bytes running at gno.land/p/nt/tinyavl/v0.
//
// # What this can and cannot promise
//
// It cannot promise anything, and the design is built around saying so rather
// than around hiding it. Two claims look alike and are not the same:
//
//  1. "this package came from that repository". UNPROVABLE, here or anywhere.
//     Anyone may deploy any bytes and anyone may claim any repository. No
//     registry design fixes this, and one that implies otherwise is worse than
//     none.
//  2. "the bytes live at path P equal the addpkg payload of directory D in
//     repository R at commit C". Mechanically provable, by hashing both sides.
//     It is NOT provable here: a realm cannot clone a repository. It is
//     provable off chain by anything that can, and gnopm already does exactly
//     this against a local tree (`gnopm verify -deployed`).
//
// So this package stores (1), labelled as the claim it is, in the form (2)
// needs to be checkable. A Claim is testimony under a signature. It becomes
// evidence only once something outside the chain has gone and looked.
//
// # What a signature does buy
//
// The chain knows who signed a claim, and that is not nothing. A claim whose
// claimant owns the package path's namespace comes from the party that controls
// the path, which is the closest thing to a promise available without a
// chain-level feature. OwnedBy reports that relationship; it is deliberately
// computed on demand from a caller-supplied resolver and never stored, because
// a name can be transferred and a stored answer would be a claim of its own.
//
// Anyone may still claim any path. That is the "open but tagged" choice, and it
// is made on purpose: gating registration on namespace ownership would mean
// that on day one, when almost nothing is registered by its own deployer, the
// registry is empty and teaches nobody anything. The defence against a
// misleading claim is that it renders as a stranger's claim, ranked below, and
// never as a fact.
package gnopm

import (
	"strings"

	"gno.land/p/nt/avl/v0"
)

// Registry maps a package path to the claims made about its source.
//
// One path may carry several claims, at most one per claimant. That is not a
// flaw to be resolved: a fork is a legitimate second answer, and so is a third
// party filling in the map for a package whose author never will.
type Registry struct {
	packages *avl.Tree // package path -> *Package
	claims   int
}

// New returns an empty registry.
func New() *Registry {
	return &Registry{packages: avl.NewTree()}
}

// Package is every claim made about one package path.
type Package struct {
	PkgPath string
	claims  *avl.Tree // claimant address string -> *Claim
}

// Claim is one address's statement about where a package came from.
//
// Every field except Claimant, Height and UpdatedAt is attacker-controlled.
// They are charset-validated at write time rather than escaped at read time, so
// that a consumer which forgets to escape is still safe: the fields cannot hold
// a byte that means anything to markdown, to a terminal or to a URL parser.
type Claim struct {
	PkgPath  string
	Repo     string // https:// URL of the repository
	Commit   string // 40 or 64 lowercase hex
	Dir      string // subdirectory holding the package, "" for the repo root
	Ref      string // fully-qualified ref the commit was on, optional
	Claimant address
	Height   int64 // block height of the first claim by this claimant
	// UpdatedAt is the height of the most recent write. Equal to Height until
	// the claimant re-registers, which is how a reader tells a claim that has
	// been kept current from one made once and abandoned.
	UpdatedAt int64
}

// Register records or replaces claimant's claim about pkgPath.
//
// Re-registering the same path overwrites that claimant's own previous claim
// and nobody else's, so the ordinary "I deployed a new commit" flow is one call
// with no read first. Height is preserved across an update: it dates the claim,
// not the edit.
func (r *Registry) Register(claimant address, height int64, pkgPath, repo, commit, dir, ref string) (*Claim, error) {
	if !ValidPkgPath(pkgPath) {
		return nil, ErrInvalidPkgPath
	}
	if !ValidRepo(repo) {
		return nil, ErrInvalidRepo
	}
	if !ValidCommit(commit) {
		return nil, ErrInvalidCommit
	}
	if !ValidDir(dir) {
		return nil, ErrInvalidDir
	}
	if !ValidRef(ref) {
		return nil, ErrInvalidRef
	}

	p := r.Package(pkgPath)
	if p == nil {
		p = &Package{PkgPath: pkgPath, claims: avl.NewTree()}
		r.packages.Set(pkgPath, p)
	}

	key := claimant.String()
	c := &Claim{
		PkgPath:   pkgPath,
		Repo:      repo,
		Commit:    commit,
		Dir:       dir,
		Ref:       ref,
		Claimant:  claimant,
		Height:    height,
		UpdatedAt: height,
	}
	if prev := p.Claim(claimant); prev != nil {
		c.Height = prev.Height
	} else {
		if p.claims.Size() >= MaxClaimants {
			return nil, ErrTooManyClaimants
		}
		r.claims++
	}
	p.claims.Set(key, c)
	return c, nil
}

// Withdraw removes claimant's own claim about pkgPath. A claimant can always
// take back what they said; nobody can remove anyone else's.
func (r *Registry) Withdraw(claimant address, pkgPath string) error {
	p := r.Package(pkgPath)
	if p == nil {
		return ErrClaimNotFound
	}
	if _, removed := p.claims.Remove(claimant.String()); !removed {
		return ErrClaimNotFound
	}
	r.claims--
	if p.claims.Size() == 0 {
		r.packages.Remove(pkgPath)
	}
	return nil
}

// Package returns every claim about a path, or nil.
func (r *Registry) Package(pkgPath string) *Package {
	v := r.packages.Get(pkgPath)
	if v == nil {
		return nil
	}
	return v.(*Package)
}

// Size is the number of package paths carrying at least one claim.
func (r *Registry) Size() int { return r.packages.Size() }

// Claims is the total number of claims across every path.
func (r *Registry) Claims() int { return r.claims }

// IteratePackages walks paths in lexical order, which groups a namespace's
// packages together without needing a second index. The callback returns true
// to STOP, following avl's own convention rather than inverting it here.
func (r *Registry) IteratePackages(offset, count int, cb func(*Package) bool) {
	r.packages.IterateByOffset(offset, count, func(_ string, v any) bool {
		return cb(v.(*Package))
	})
}

// IterateNamespace walks every claimed path under "<domain>/<kind>/<ns>/".
func (r *Registry) IterateNamespace(domain, kind, ns string, cb func(*Package) bool) {
	prefix := domain + "/" + kind + "/" + ns + "/"
	r.packages.Iterate(prefix, "", func(k string, v any) bool {
		if !strings.HasPrefix(k, prefix) {
			return true // past the prefix: stop
		}
		return cb(v.(*Package))
	})
}

// Claim returns claimant's claim about this package, or nil.
func (p *Package) Claim(claimant address) *Claim {
	v := p.claims.Get(claimant.String())
	if v == nil {
		return nil
	}
	return v.(*Claim)
}

// Count is how many addresses have claimed this package.
func (p *Package) Count() int { return p.claims.Size() }

// IterateClaims walks the claims in claimant-address order. Order is not
// significance: a caller that wants the owner's claim first must ask OwnedBy,
// because the registry has no opinion about which claim is true.
func (p *Package) IterateClaims(cb func(*Claim) bool) {
	p.claims.Iterate("", "", func(_ string, v any) bool {
		return cb(v.(*Claim))
	})
}

// OwnedBy reports whether c comes from the party that controls the package
// path's namespace: either the address whose own namespace it is, or whoever
// resolve says holds the registered name.
//
// resolve maps a namespace name to the address holding it and whether that name
// is held at all. It is a parameter rather than an import because this package
// stays pure: the realm supplies r/sys/users, and a test supplies a table.
//
// This is the one label in the whole design that is derived rather than
// declared, so it is computed here and never stored. A name can be transferred;
// a stored answer would age into a lie of exactly the kind this package exists
// to avoid.
func (c *Claim) OwnedBy(resolve func(name string) (address, bool)) bool {
	_, _, ns, _, ok := SplitPkgPath(c.PkgPath)
	if !ok {
		return false
	}
	if AddressNamespace(ns) {
		return ns == c.Claimant.String()
	}
	if resolve == nil {
		return false
	}
	addr, held := resolve(ns)
	return held && addr == c.Claimant
}

// SourceURL builds a browsable link to the claimed source: the commit, plus the
// directory when the package is not at the repository root.
//
// GitHub's "/tree/<commit>/<dir>" layout is also GitLab's, Gitea's, Forgejo's
// and Codeberg's, so one construction covers every forge this registry is
// likely to meet. It is a convenience, not a promise the link resolves: the
// repository may be gone, private or renamed since the claim was made, which is
// itself something a verifier reports rather than something a realm can know.
func (c *Claim) SourceURL() string {
	u := strings.TrimSuffix(c.Repo, "/") + "/tree/" + c.Commit
	if c.Dir != "" {
		u += "/" + c.Dir
	}
	return u
}

registry_test.gno

package gnopm

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

const pkgA = "gno.land/p/nym-moultest123/md/v1"

func TestRegisterAndRead(t *testing.T) {
	r := New()
	uassert.Equal(t, 0, r.Size())
	uassert.Equal(t, 0, r.Claims())

	c, err := r.Register(alice, 100, pkgA, "https://github.com/moul/gno-contracts", sha1Zero, "p/moul/md", "refs/heads/main")
	uassert.NoError(t, err)
	uassert.Equal(t, pkgA, c.PkgPath)
	uassert.Equal(t, int64(100), c.Height)
	uassert.Equal(t, int64(100), c.UpdatedAt)
	uassert.Equal(t, 1, r.Size())
	uassert.Equal(t, 1, r.Claims())

	p := r.Package(pkgA)
	uassert.True(t, p != nil, "package exists")
	uassert.Equal(t, 1, p.Count())
	uassert.True(t, p.Claim(alice) != nil, "alice's claim is there")
	uassert.True(t, p.Claim(bob) == nil, "bob has not claimed")
	uassert.True(t, r.Package("gno.land/p/nym-moultest123/nope/v0") == nil, "unclaimed path is nil")
}

// A claimant re-registering must move their own commit and nothing else, and
// must not restart the clock: Height dates the claim, UpdatedAt dates the edit,
// and telling them apart is how a reader spots a claim nobody has touched since
// the first deploy.
func TestReregisterUpdatesInPlace(t *testing.T) {
	r := New()
	r.Register(alice, 100, pkgA, "https://github.com/moul/gno-contracts", sha1Zero, "p/moul/md", "")
	c, err := r.Register(alice, 250, pkgA, "https://github.com/moul/gno-contracts", sha1One, "p/moul/md", "refs/tags/v1")
	uassert.NoError(t, err)

	uassert.Equal(t, sha1One, c.Commit, "commit moved")
	uassert.Equal(t, "refs/tags/v1", c.Ref, "ref moved")
	uassert.Equal(t, int64(100), c.Height, "height still dates the original claim")
	uassert.Equal(t, int64(250), c.UpdatedAt, "updated at dates the edit")
	uassert.Equal(t, 1, r.Claims(), "still one claim, not two")
	uassert.Equal(t, 1, r.Package(pkgA).Count())
}

// Open but tagged: a second address may claim the same path. The registry has
// no opinion about which is true, and storing both is the point.
func TestSeveralClaimantsCoexist(t *testing.T) {
	r := New()
	r.Register(alice, 100, pkgA, "https://github.com/moul/gno-contracts", sha1Zero, "p/moul/md", "")
	r.Register(bob, 110, pkgA, "https://github.com/someone/fork", sha1One, "md", "")

	p := r.Package(pkgA)
	uassert.Equal(t, 2, p.Count())
	uassert.Equal(t, 2, r.Claims())
	uassert.Equal(t, 1, r.Size(), "still one package path")
	uassert.Equal(t, sha1Zero, p.Claim(alice).Commit)
	uassert.Equal(t, sha1One, p.Claim(bob).Commit)
}

func TestMaxClaimants(t *testing.T) {
	r := New()
	// Fill the path to the cap with distinct claimants.
	base := "g1ubwjz3jmrjwmpuvrsjzgy5qkxf5wrgphzmd2t"
	suffix := "023456789acdefgh"
	for i := 0; i < MaxClaimants; i++ {
		a := address(base + string(suffix[i]))
		_, err := r.Register(a, int64(100+i), pkgA, "https://example.com/x", sha1Zero, "", "")
		uassert.NoError(t, err, "claimant within the cap")
	}
	uassert.Equal(t, MaxClaimants, r.Package(pkgA).Count())

	_, err := r.Register(carol, 999, pkgA, "https://example.com/x", sha1Zero, "", "")
	uassert.ErrorIs(t, err, ErrTooManyClaimants, "one past the cap")

	// An address already at the cap can still update: the cap bounds how many
	// claimants a path carries, never how often one of them corrects itself.
	existing := address(base + string(suffix[0]))
	_, err = r.Register(existing, 999, pkgA, "https://example.com/x", sha1One, "", "")
	uassert.NoError(t, err, "an existing claimant updates at the cap")
}

func TestWithdraw(t *testing.T) {
	r := New()
	r.Register(alice, 100, pkgA, "https://example.com/x", sha1Zero, "", "")
	r.Register(bob, 101, pkgA, "https://example.com/y", sha1One, "", "")

	uassert.ErrorIs(t, r.Withdraw(carol, pkgA), ErrClaimNotFound, "withdrawing what you never said")
	uassert.ErrorIs(t, r.Withdraw(alice, "gno.land/p/nym-moultest123/nope/v0"), ErrClaimNotFound, "unknown path")

	uassert.NoError(t, r.Withdraw(alice, pkgA))
	uassert.Equal(t, 1, r.Claims())
	uassert.Equal(t, 1, r.Size(), "bob's claim keeps the path alive")
	uassert.True(t, r.Package(pkgA).Claim(alice) == nil, "alice is gone")
	uassert.True(t, r.Package(pkgA).Claim(bob) != nil, "bob is untouched")

	uassert.NoError(t, r.Withdraw(bob, pkgA))
	uassert.Equal(t, 0, r.Claims())
	uassert.Equal(t, 0, r.Size(), "the last withdrawal removes the path")
	uassert.True(t, r.Package(pkgA) == nil)
}

func TestRegisterRejectsInvalidInput(t *testing.T) {
	good := func() (string, string, string, string, string) {
		return pkgA, "https://github.com/moul/gno-contracts", sha1Zero, "p/moul/md", "refs/heads/main"
	}
	cases := []struct {
		name string
		mut  func(p, repo, commit, dir, ref *string)
		want error
	}{
		{"bad path", func(p, _, _, _, _ *string) { *p = "nonsense" }, ErrInvalidPkgPath},
		{"bad repo scheme", func(_, repo, _, _, _ *string) { *repo = "javascript:alert(1)" }, ErrInvalidRepo},
		{"abbreviated commit", func(_, _, c, _, _ *string) { *c = "0123456" }, ErrInvalidCommit},
		{"absolute dir", func(_, _, _, d, _ *string) { *d = "/etc" }, ErrInvalidDir},
		{"unqualified ref", func(_, _, _, _, rf *string) { *rf = "main" }, ErrInvalidRef},
	}
	for _, tc := range cases {
		r := New()
		p, repo, commit, dir, ref := good()
		tc.mut(&p, &repo, &commit, &dir, &ref)
		_, err := r.Register(alice, 100, p, repo, commit, dir, ref)
		uassert.ErrorIs(t, err, tc.want, tc.name)
		uassert.Equal(t, 0, r.Claims(), tc.name+": nothing stored")
	}
}

func TestOwnedBy(t *testing.T) {
	names := resolver(map[string]address{"moul": alice})
	r := New()

	c, _ := r.Register(alice, 100, pkgA, "https://example.com/x", sha1Zero, "", "")
	uassert.True(t, c.OwnedBy(names), "the namespace holder claiming their own package")

	c2, _ := r.Register(bob, 101, pkgA, "https://example.com/y", sha1One, "", "")
	uassert.False(t, c2.OwnedBy(names), "a stranger claiming someone else's package")

	// An address namespace belongs to that account with nothing registered, so
	// it resolves with no name lookup at all.
	own := "gno.land/r/" + addrNS + "/scratch/v0"
	c3, err := r.Register(address(addrNS), 102, own, "https://example.com/z", sha1Zero, "", "")
	uassert.NoError(t, err)
	uassert.True(t, c3.OwnedBy(nil), "an address namespace needs no resolver")

	c4, _ := r.Register(bob, 103, own, "https://example.com/w", sha1One, "", "")
	uassert.False(t, c4.OwnedBy(nil), "a stranger in someone's address namespace")

	// An unregistered name is held by nobody, so nobody owns it.
	other := "gno.land/p/nobody/thing/v0"
	c5, _ := r.Register(alice, 104, other, "https://example.com/v", sha1Zero, "", "")
	uassert.False(t, c5.OwnedBy(names), "an unheld namespace is owned by no one")
	uassert.False(t, c5.OwnedBy(nil), "and a nil resolver never invents ownership")

	// A resolver may return an address AND report the name as not held: that is
	// what r/sys/users does for a name whose record survives but is no longer
	// current. The address matching is not enough, the name has to still be
	// held, and dropping the second half of that test is a silent promotion of
	// a stranger's claim.
	stale := func(string) (address, bool) { return alice, false }
	uassert.False(t, c.OwnedBy(stale), "a resolved but unheld name confers nothing")
}

func TestSourceURL(t *testing.T) {
	r := New()
	c, _ := r.Register(alice, 100, pkgA, "https://github.com/moul/gno-contracts", sha1Zero, "p/moul/md", "")
	uassert.Equal(t, "https://github.com/moul/gno-contracts/tree/"+sha1Zero+"/p/nym-moultest123/md", c.SourceURL())

	c2, _ := r.Register(bob, 100, pkgA, "https://github.com/x/y/", sha1One, "", "")
	uassert.Equal(t, "https://github.com/x/y/tree/"+sha1One, c2.SourceURL(), "root package, trailing slash trimmed")
}

func TestIteration(t *testing.T) {
	r := New()
	paths := []string{
		"gno.land/p/alice/one/v0",
		"gno.land/p/nym-moultest123/md/v1",
		"gno.land/p/nym-moultest123/ulist/v0",
		"gno.land/r/nym-moultest123/home",
		"gno.land/p/zed/last/v0",
	}
	for i, p := range paths {
		_, err := r.Register(alice, int64(100+i), p, "https://example.com/x", sha1Zero, "", "")
		uassert.NoError(t, err, p)
	}

	var seen []string
	r.IteratePackages(0, 10, func(p *Package) bool {
		seen = append(seen, p.PkgPath)
		return false
	})
	uassert.Equal(t, 5, len(seen))
	uassert.Equal(t, "gno.land/p/alice/one/v0", seen[0], "lexical order")
	uassert.Equal(t, "gno.land/r/nym-moultest123/home", seen[4], "r sorts after p")

	// A namespace walk must stop at the prefix boundary rather than running to
	// the end of the tree: "moul" is followed by "zed" and by the r/ half.
	var ns []string
	r.IterateNamespace("gno.land", "p", "moul", func(p *Package) bool {
		ns = append(ns, p.PkgPath)
		return false
	})
	uassert.Equal(t, 2, len(ns), "only p/moul")
	uassert.Equal(t, "gno.land/p/nym-moultest123/md/v1", ns[0])
	uassert.Equal(t, "gno.land/p/nym-moultest123/ulist/v0", ns[1])

	// Stopping early stops.
	count := 0
	r.IteratePackages(0, 10, func(p *Package) bool {
		count++
		return true
	})
	uassert.Equal(t, 1, count, "returning true stops the walk")
}

validate.gno

package gnopm

import "strings"

// Size caps. Every string the chain stores is bounded: an unbounded field is an
// unbounded storage deposit, and on gno.land the deposit is paid per byte by
// whoever writes it.
const (
	MaxPkgPathLen = 256
	MaxRepoLen    = 512
	MaxDirLen     = 256
	MaxRefLen     = 255 // git's own limit for a single ref name

	// MaxClaimants bounds how many addresses may claim one package path.
	// Unbounded, it is a spam surface: one path with ten thousand claims is a
	// Render that never returns and a listing nobody can read.
	MaxClaimants = 16
)

// ValidCommit reports whether s is a git object id: 40 (SHA-1) or 64 (SHA-256)
// lowercase hex characters. Case is fixed so the same object always produces
// the same stored bytes, and so a verifier comparing two claims compares two
// comparable strings.
func ValidCommit(s string) bool {
	if len(s) != 40 && len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
			return false
		}
	}
	return true
}

// ValidRepo reports whether s is a repository URL this registry accepts.
//
// Deliberately narrow: "https://" only, a host, and a path. Not a taste
// judgement about git transports, a safety one. Whatever is stored here is
// eventually rendered as a link by this realm, by gnoweb and by every explorer
// that reads the registry, and the set of schemes that are safe to hand a
// browser is exactly one. "javascript:", "data:" and "file:" are the attack;
// "git://" and "ssh://" are merely unreachable from a web page, and a claimant
// who needs one can point at the https mirror every forge already serves.
func ValidRepo(s string) bool {
	if s == "" || len(s) > MaxRepoLen {
		return false
	}
	const scheme = "https://"
	if !strings.HasPrefix(s, scheme) {
		return false
	}
	rest := s[len(scheme):]
	if rest == "" || strings.HasPrefix(rest, "/") {
		return false
	}
	// A host must be present and must not be a userinfo trick
	// ("https://[email protected]/x" fetches from evil.example while
	// reading as GitHub).
	slash := strings.IndexByte(rest, '/')
	host := rest
	if slash >= 0 {
		host = rest[:slash]
	}
	if host == "" || strings.ContainsAny(host, "@:") {
		return false
	}
	if !strings.Contains(host, ".") {
		return false
	}
	for i := 0; i < len(s); i++ {
		if !urlByteOK(s[i]) {
			return false
		}
	}
	return !strings.Contains(s, "..")
}

// urlByteOK is an allowlist, not a denylist: the printable ASCII that appears
// in a real repository URL. Everything else, control characters and the bidi
// overrides in particular, is refused rather than escaped, because a field that
// can only hold safe bytes needs no escaping at any of its render sites.
func urlByteOK(c byte) bool {
	switch {
	case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
		return true
	}
	switch c {
	case '-', '.', '_', '~', ':', '/', '%', '+':
		return true
	}
	return false
}

// ValidDir reports whether s names the subdirectory of the repository holding
// the package. Empty means the repository root, which is the common case for a
// single-package repo and must stay expressible.
func ValidDir(s string) bool {
	if s == "" {
		return true
	}
	if len(s) > MaxDirLen {
		return false
	}
	if strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") {
		return false
	}
	for _, p := range strings.Split(s, "/") {
		if p == "" || p == "." || p == ".." {
			return false
		}
		for i := 0; i < len(p); i++ {
			if !pathByteOK(p[i]) {
				return false
			}
		}
	}
	return true
}

func pathByteOK(c byte) bool {
	switch {
	case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
		return true
	}
	switch c {
	case '-', '.', '_':
		return true
	}
	return false
}

// ValidRef reports whether s is a fully-qualified git ref, or empty.
//
// The ref is optional and is never the thing that is verified: a ref moves, a
// commit does not. It is recorded so a reader can tell a claim pinned to a
// released tag from one pinned to a commit on nobody's branch, and so a
// verifier can check the claimed commit is still reachable from it rather than
// dangling behind a force-push.
func ValidRef(s string) bool {
	if s == "" {
		return true
	}
	if len(s) > MaxRefLen || !strings.HasPrefix(s, "refs/") {
		return false
	}
	if strings.Contains(s, "..") || strings.Contains(s, "@{") {
		return false
	}
	if strings.HasSuffix(s, "/") || strings.HasSuffix(s, ".") {
		return false
	}
	parts := strings.Split(s, "/")
	if len(parts) < 2 {
		return false
	}
	for _, p := range parts {
		if p == "" || p == "@" || strings.HasPrefix(p, ".") || strings.HasSuffix(p, ".lock") {
			return false
		}
		for i := 0; i < len(p); i++ {
			if !refByteOK(p[i]) {
				return false
			}
		}
	}
	return true
}

// refByteOK is an allowlist, and deliberately narrower than git's own rule.
//
// git rejects a handful of metacharacters and permits everything else, which
// leaves a ref free to contain a backtick, a pipe or a bracket. Every other
// field here is an allowlist precisely so that no consumer has to escape
// anything, and one denylist field would undo that for all of them: a ref
// carrying a pipe breaks out of a markdown table cell, and one carrying a
// backtick breaks out of the inline-code span a renderer wraps it in.
//
// The cost is refs nobody writes. What stays expressible is every ref anyone
// actually has: alphanumerics, and the four separators git tooling puts in a
// name.
func refByteOK(c byte) bool {
	switch {
	case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
		return true
	}
	switch c {
	case '-', '.', '_', '/', '+':
		return true
	}
	return false
}

validate_test.gno

package gnopm

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestValidCommit(t *testing.T) {
	sha1 := strings.Repeat("a", 40)
	sha256 := strings.Repeat("0", 64)
	cases := []struct {
		name string
		in   string
		want bool
	}{
		{"sha1", sha1, true},
		{"sha256", sha256, true},
		{"mixed hex", "0123456789abcdef0123456789abcdef01234567", true},
		{"empty", "", false},
		{"too short", strings.Repeat("a", 39), false},
		{"between the two lengths", strings.Repeat("a", 41), false},
		{"uppercase", strings.Repeat("A", 40), false},
		{"non hex", strings.Repeat("g", 40), false},
		{"abbreviated", "0123456", false},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, ValidCommit(tc.in), tc.name)
	}
}

func TestValidRepo(t *testing.T) {
	cases := []struct {
		name string
		in   string
		want bool
	}{
		{"github", "https://github.com/gnolang/gno", true},
		{"no path", "https://example.com", true},
		{"trailing slash", "https://example.com/x/", true},
		{"port is not a host character here", "https://example.com:8443/x", false},

		{"empty", "", false},
		{"http", "http://github.com/gnolang/gno", false},
		{"git scheme", "git://github.com/gnolang/gno", false},
		{"ssh scheme", "ssh://[email protected]/gnolang/gno", false},
		{"javascript", "javascript:alert(1)", false},
		{"data url", "data:text/html,<script>", false},
		{"scheme relative", "//github.com/gnolang/gno", false},
		{"no host", "https:///gnolang/gno", false},
		{"bare host with no dot", "https://localhost/x", false},
		{"userinfo disguise", "https://[email protected]/gnolang/gno", false},
		{"parent traversal", "https://example.com/../x", false},
		{"space", "https://example.com/a b", false},
		{"markdown link break-out", "https://example.com/a)[x](y", false},
		{"newline", "https://example.com/a\nb", false},
		{"bidi override", "https://example.com/a‮b", false},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, ValidRepo(tc.in), tc.name)
	}
}

func TestValidDir(t *testing.T) {
	cases := []struct {
		name string
		in   string
		want bool
	}{
		{"repo root", "", true},
		{"one element", "examples", true},
		{"nested", "examples/gno.land/p/nt/avl", true},
		{"dots in a name", "p/moul.io/x", true},

		{"absolute", "/examples", false},
		{"trailing slash", "examples/", false},
		{"empty element", "a//b", false},
		{"dot element", "a/./b", false},
		{"parent traversal", "a/../b", false},
		{"backslash", "a\\b", false},
		{"space", "a b", false},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, ValidDir(tc.in), tc.name)
	}
}

func TestValidRef(t *testing.T) {
	cases := []struct {
		name string
		in   string
		want bool
	}{
		{"absent is legal", "", true},
		{"branch", "refs/heads/main", true},
		{"tag", "refs/tags/v1.2.0", true},

		{"unqualified branch", "main", false},
		{"double dot", "refs/heads/a..b", false},
		{"reflog syntax", "refs/heads/a@{1}", false},
		{"trailing slash", "refs/heads/", false},
		{"lock suffix", "refs/heads/main.lock", false},
		{"leading dot", "refs/heads/.hidden", false},
		{"caret", "refs/heads/a^b", false},
		{"space", "refs/heads/a b", false},

		// Narrower than git on purpose: these are legal ref names that would
		// break out of a markdown table cell or an inline-code span, and every
		// other field in this package is an allowlist so that no consumer has
		// to escape anything.
		{"pipe breaks a table cell", "refs/heads/a|b", false},
		{"backtick breaks a code span", "refs/heads/a`b", false},
		{"brackets open a link", "refs/heads/a[b]c", false},
		{"parens close a link", "refs/heads/a(b)c", false},
		{"hash opens a heading", "refs/heads/a#b", false},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, ValidRef(tc.in), tc.name)
	}
}