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

Playground

admin.gno

package namereg

import (
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/gov/dao"
	susers "gno.land/r/sys/users"
)

var paused = false // XXX: replace with p/moul/authz

//----------------------------------------
// Privileged mutators.

func setPaused(cur realm, newPausedValue bool) {
	paused = newPausedValue
}

func updateUsername(cur realm, userData *susers.UserData, newName string) error {
	// UpdateName must be called from this realm.
	return userData.UpdateName(0, cur, newName)
}

func deleteUserdata(cur realm, userData *susers.UserData) error {
	// Delete must be called from this realm.
	return userData.Delete(0, cur)
}

func setRegisterPrice(cur realm, newPrice int64) {
	registerPrice = newPrice
}

//----------------------------------------
// Public API

// NewSetPausedExecutor allows GovDAO to pause or unpause this realm
func NewSetPausedExecutor(cur realm, newPausedValue bool) dao.ProposalRequest {
	cb := func(cur realm) error {
		setPaused(cur, newPausedValue)
		return nil
	}

	e := dao.NewSimpleExecutor(0, cur, cb, "")

	if newPausedValue {
		return dao.NewProposalRequest("User Registry V0: Pause", "", e)
	}

	return dao.NewProposalRequest("User Registry V0: Unpause", "", e)
}

// ProposeNewName allows GovDAO to propose a new name for an existing user.
// The associated address and all previous names of a user that changes a
// name are preserved, and all resolve to the new name.
//
// Governance renames bypass the Open Nym Tier `nym-...\d{3}` format intentionally.
// The DAO is the trust root for this realm; if voters approve a rename to
// `vitalik` (e.g. for trademark dispute resolution or system reservations),
// the validation here imposes no further opinion. The new name is still
// subject to the base shape enforced by `r/sys/users.validateName`
// (`^[a-z][a-z0-9]*([_-][a-z0-9]+)*$`, max 64 chars), which runs inside
// the updateUsername callback below.
func ProposeNewName(cur realm, addr address, newName string) dao.ProposalRequest {
	userData := susers.ResolveAddress(addr)
	if userData == nil {
		panic(susers.ErrUserNotExistOrDeleted)
	}

	cb := func(cur realm) error {
		err := updateUsername(cur, userData, newName)
		return err
	}

	e := dao.NewSimpleExecutor(0, cur, cb, "")

	return dao.NewProposalRequest(
		ufmt.Sprintf("User Registry V0: Rename user `%s` to `%s`", userData.Name(), newName),
		"",
		e,
	)
}

// ProposeDeleteUser allows GovDAO to propose deletion of a user
// This will make the associated address and names unresolvable.
// WARN: After deletion, the same address WILL NOT be able to register a new name.
func ProposeDeleteUser(cur realm, addr address, reason string) dao.ProposalRequest {
	userData := susers.ResolveAddress(addr)
	if userData == nil {
		panic(susers.ErrUserNotExistOrDeleted)
	}

	cb := func(cur realm) error {
		return deleteUserdata(cur, userData)
	}

	e := dao.NewSimpleExecutor(0, cur, cb, "")

	return dao.NewProposalRequest(
		ufmt.Sprintf("User Registry V0: Delete user `%s`", userData.Name()),
		reason,
		e,
	)
}

// ProposeNewRegisterPrice allows GovDAO to update the price of registration.
// Rejects prices below MinRegisterPrice (currently 0) at proposal-creation
// time. (audit finding #14: original code only rejected negative values,
// which would have been arithmetically nonsensical.)
func ProposeNewRegisterPrice(cur realm, newPrice int64) dao.ProposalRequest {
	if newPrice < MinRegisterPrice {
		panic(ufmt.Sprintf("price below floor: %d ugnot < %d ugnot (MinRegisterPrice)",
			newPrice, MinRegisterPrice))
	}

	cb := func(cur realm) error {
		setRegisterPrice(cur, newPrice)
		return nil
	}

	e := dao.NewSimpleExecutor(0, cur, cb, "")

	return dao.NewProposalRequest(
		ufmt.Sprintf("User Registry V0: Update registration price to `%d`", newPrice),
		"",
		e,
	)
}

api.gno

package namereg

import (
	"errors"
	"regexp"
	"strings"
)

// Open Nym Tier username format. Anchored.
//   - literal `nym-` prefix (4 chars)
//   - 5-13 lowercase ASCII letters (the alpha stem)
//   - exactly 3 trailing decimal digits
//
// Total length 12-20 chars. Distinct by length from `g1...` addresses
// which are always 40 chars.
const reNymFormat = `^nym-[a-z]{5,13}\d{3}$`

var reNym = regexp.MustCompile(reNymFormat)

// Reserved alpha-stem prefixes. Names whose stem starts with one of
// these are rejected at format-validation time with ErrReservedPrefix
// (clearer than ErrCanonicalCollision after the fact).
//
// `gi` is intentionally NOT listed: in most rendering targets `i` is
// visually distinct enough from `1`/`l` that legitimate `gi*` names
// (giggles, gimbal, gift, etc.) should remain registerable. Phishing
// protection for the visual class is still enforced by canonical-
// collision detection in r/sys/users — once any `gi*` or `gl*` name
// is registered, all variants under the {l,i,1}→i canonicalization
// collide.
//
// `gl` and `g1` remain listed because they're more visually
// confusable with the bech32 address prefix `g1`. `g1` itself is
// unreachable through the alpha-only stem regex; defense-in-depth
// for any future regex relaxation.
var reservedPrefixes = []string{"gl", "g1", "gno", "atom", "atone", "photon", "cosmos"}

// Exported error sentinels returned by ValidateNymFormat. Use
// errors.Is or direct equality; do not string-match.
//
// ErrReservedPrefix's message is built from reservedPrefixes at package
// init time so the surfaced list never drifts from the actual policy.
//
// Canonical-collision detection moved to r/sys/users in Option B.
// Consumers that previously caught namereg.ErrCanonicalCollision
// should switch to susers.ErrCanonicalCollision.
var (
	ErrInvalidFormat  = errors.New("namereg: name must match nym-[a-z]{5,13}\\d{3}")
	ErrReservedPrefix = errors.New("namereg: stem starts with a reserved prefix (" + strings.Join(reservedPrefixes, "/") + ")")
	ErrBlacklisted    = errors.New("namereg: stem matches a reserved role name")
)

// IsReserved reports whether the given alpha stem matches a reserved
// role name (with implicit `s`-suffix expansion). The check is
// canonicalized — so `vital1k`-style l-substituted variants of a
// reserved name are also caught. O(1) backed by `reservedSet` built
// in init().
func IsReserved(stem string) bool {
	_, found := reservedSet[Canonicalize(stem)]
	return found
}

// ValidateNymFormat checks the regex, prefix-exclusion, and reserved-
// name rules in that order. Returns one of the exported sentinel
// errors per failure mode, or nil on success.
//
// Does NOT run the canonical-collision check — that lives in r/sys/users
// (susers.IsCanonicalTaken or, atomically with the write, inside
// susers.RegisterUser).
func ValidateNymFormat(username string) error {
	if !reNym.MatchString(username) {
		return ErrInvalidFormat
	}

	// Stem is everything between `nym-` (4 chars) and the trailing
	// 3 digits. Regex guarantees 5..13 alpha chars in this slice.
	stem := username[4 : len(username)-3]

	for _, p := range reservedPrefixes {
		if strings.HasPrefix(stem, p) {
			return ErrReservedPrefix
		}
	}

	if IsReserved(stem) {
		return ErrBlacklisted
	}

	return nil
}

// IsPaused exposes the realm's pause flag for cross-controller
// coordination.
func IsPaused() bool {
	return paused
}

blacklist.gno

package namereg

// reservedNames lists role/system identifiers that must never be allocated
// as a registered name. The intent is to prevent Open Nym Tier
// auto-registrations like "nym-admin000" from impersonating system roles.
//
// Sources merged here:
//   - Common role names already covered by Handshake's valid.json (the 90k
//     curated trademark/gTLD-application list) — admin, help, support, etc.
//   - Common role names NOT covered by Handshake — administrator, root,
//     sysadmin, owner, staff, api, etc.
//   - RFC 2606 / RFC 6761 reserved labels — example, invalid, localhost,
//     local, test.
//
// Plural rule: every entry below is ALSO reserved with the literal "s"
// suffix appended. So "doc" reserves both "doc" and "docs"; "setting"
// reserves both "setting" and "settings"; "new" covers "news", and so on.
// Entries are stored in the singular here and the validator appends "s"
// at check time. This halves list maintenance and avoids the temptation
// to add `name+"s"` after every singular entry.
//
// Note on length: the Open Nym Tier regex restricts the [a-z]{5,13}
// middle to 5–13 chars, so entries shorter than 5 (mod, api, bot, god,
// gno, ...) and longer than 13 (administrator, jesuschrist,
// newtendermint, ...) cannot appear in Register() even without this list.
// They are kept anyway because:
//
//	(a) cross-reference value — a single canonical list is easier to audit
//	    than two scope-specific lists with overlapping intent; and
//	(b) future controllers (e.g. a hypothetical DAO-allocated path) can
//	    opt in to the same blacklist by querying IsReserved, providing
//	    defense-in-depth across the registration ecosystem.
//
// IMPORTANT: this list is NOT consulted by `ProposeNewName` — governance
// renames are gated by GovDAO vote alone, not by this blacklist. Voters
// reviewing a rename proposal are responsible for catching collisions
// with reserved names.
//
// Sortedness: entries must be sorted lexicographically (Go's < on strings,
// which is byte-wise ASCII). TestReservedNamesSorted enforces this.
var reservedNames = []string{
	"about",
	"abuse",
	"account",
	"admin",
	"administrator",
	"aib",
	"aibinc",
	"allinbits",
	"allinbitsinc",
	"anonymous",
	"api",
	"atom",
	"atomone",
	"atomonehub",
	"atone",
	"atonehub",
	"bitcoin",
	"blockchain",
	"blog",
	"bot",
	"chain",
	"coin",
	"community",
	"contact",
	"cosmos",
	"cosmoshub",
	"crypto",
	"daemon",
	"dashboard",
	"default",
	"demo",
	"doc",
	"domain",
	"email",
	"ether",
	"ethereum",
	"everyone",
	"example",
	"gno",
	"gnoland",
	"gnolang",
	"gnome",
	"gnot",
	"gnoworld",
	"god",
	"gov",
	"govdao",
	"governance",
	"guest",
	"help",
	"home",
	"host",
	"info",
	"invalid",
	"jaekwon",
	"jesus",
	"jesuschrist",
	"local",
	"localhost",
	"login",
	"mail",
	"mod",
	"moderator",
	"new",
	"newtendermint",
	"newtendermintllc",
	"nt",
	"ntllc",
	"null",
	"owner",
	"photon",
	"profile",
	"register",
	"registry",
	"resolution",
	"resolve",
	"resolver",
	"root",
	"security",
	"service",
	"setting",
	"shop",
	"signup",
	"staff",
	"store",
	"support",
	"sys",
	"sysadmin",
	"system",
	"team",
	"tendermint",
	"test",
	"user",
}

blacklist_test.gno

package namereg

import "testing"

// TestReservedNamesSorted enforces lexicographic ordering on reservedNames.
// The list is intended to be auditable at a glance and to grow over time;
// keeping it sorted makes diffs minimal and makes manual scanning for a
// given entry feasible. If this fails after a maintainer adds an entry,
// re-sort the slice rather than weakening the test.
func TestReservedNamesSorted(cur realm, t *testing.T) {
	for i := 1; i < len(reservedNames); i++ {
		if reservedNames[i-1] >= reservedNames[i] {
			t.Errorf(
				"reservedNames not sorted at index %d: %q should come after %q",
				i, reservedNames[i-1], reservedNames[i],
			)
		}
	}
}

canonical.gno

package namereg

import (
	susers "gno.land/r/sys/users"
)

// reservedSet is the runtime O(1) lookup for the role-name blacklist.
// Built in init() from reservedNames in blacklist.gno: each source
// entry contributes BOTH `Canonicalize(n)` and `Canonicalize(n+"s")`
// as keys, implementing the "implicit `s` suffix" rule documented on
// reservedNames.
//
// Why canonicalize the blacklist itself: validation canonicalizes the
// candidate stem before checking, so the comparison set must also be
// in canonical form. Otherwise a candidate like "vital1k" would
// canonicalize to "vitaiik" but the blacklist would contain only
// "vitalik" — the comparison would miss the match. Keeping both sides
// in canonical form makes the lookup exact.
//
// The blacklist remains namereg/v0-local because it is policy specific
// to the Open Nym Tier. Other controllers may have entirely different
// reserved-name policies, or none at all.
var reservedSet map[string]struct{}

func init() {
	reservedSet = make(map[string]struct{}, len(reservedNames)*2)
	for _, n := range reservedNames {
		reservedSet[Canonicalize(n)] = struct{}{}
		reservedSet[Canonicalize(n+"s")] = struct{}{}
	}
}

// Canonicalize is a delegating shim to r/sys/users.Canonicalize.
//
// HISTORY: namereg/v0 used to host its own per-stem canonical store and
// its own Canonicalize (l→i only). Option B unified the canonical lookup
// into r/sys/users keyed by full canonical name with broader
// substitutions ({l,i,1}→i, {0,o}→o, {-,.,_} stripped). This shim
// preserves the call-site name for local consumers (blacklist init,
// IsReserved) and any external consumer that imported the function
// from namereg/v0 before Option B.
//
// New code should call susers.Canonicalize directly.
func Canonicalize(s string) string {
	return susers.Canonicalize(s)
}

canonical_test.gno

package namereg

import (
	"testing"

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

	susers "gno.land/r/sys/users"
)

// Canonicalize is now a delegating shim to susers.Canonicalize; verify
// the local export and the upstream produce the same output for the
// rules namereg/v0 cares about.
func TestCanonicalize_DelegatesToSusers(cur realm, t *testing.T) {
	cases := []string{
		"",
		"a",
		"alice",
		"vitalik",
		"vital1k",
		"balloon",
		"already-canonical",
		"xyz123",
		"nym-foolbar000",
		"nym-foolbar001",
	}
	for _, in := range cases {
		uassert.Equal(t, susers.Canonicalize(in), Canonicalize(in),
			"namereg.Canonicalize must match susers.Canonicalize")
	}
}

func TestReservedSet_BuiltFromBlacklist(cur realm, t *testing.T) {
	// Sanity: every entry from reservedNames AND its `+s` form must be
	// in the canonicalized lookup.
	for _, n := range reservedNames {
		_, gotBare := reservedSet[Canonicalize(n)]
		uassert.True(t, gotBare,
			"reservedSet missing canonical(%q)", n)

		_, gotPlural := reservedSet[Canonicalize(n+"s")]
		uassert.True(t, gotPlural,
			"reservedSet missing canonical(%q+s)", n)
	}
}

func TestIsReserved_LiteralAndCanonical(cur realm, t *testing.T) {
	// Literal entry must be reserved.
	uassert.True(t, IsReserved("admin"), "admin should be reserved")

	// `blogs` covered via `blog`+s rule (blog is in reservedNames).
	uassert.True(t, IsReserved("blogs"), "blogs covered by blog+s")

	// l-substituted: `blog` canonicalizes to `biog`. Both forms blocked
	// because we canonicalize the candidate before lookup.
	uassert.True(t, IsReserved("biog"), "canonical(blog)=biog also blocked")

	// 1-substituted under the new susers.Canonicalize rules: `1` → `i`.
	// `b1og` canonicalizes to `biog`, same as `blog`. Confirms the shim
	// picks up the broader rule set.
	uassert.True(t, IsReserved("b1og"), "1→i variant also blocked")

	// Non-reserved stem should not be flagged.
	uassert.False(t, IsReserved("zulufoxtrot"), "zulufoxtrot is not reserved")

	// Identity passthrough.
	uassert.True(t, IsReserved("tendermint"))
}

errors.gno

package namereg

import (
	"errors"

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

var (
	ErrNonUserCall     = errors.New("r/gnoland/users: non-user call")
	ErrPaused          = errors.New("r/gnoland/users: paused")
	ErrInvalidUsername = errors.New("r/gnoland/users: invalid username")

	// ErrInvalidPayment is the sentinel for "OriginSend amount didn't
	// match registerPrice." It deliberately omits the price from its
	// message — the price is read at panic time via errInvalidPayment()
	// below, so users see the CURRENT price even after governance has
	// changed it. Tests that match against this error use it as a
	// substring check via uassert.AbortsWithMessage. (audit finding #13)
	ErrInvalidPayment = errors.New("r/gnoland/users: invalid payment amount")
)

// errInvalidPayment returns the panic value for an OriginSend mismatch.
// Constructed lazily so the formatted price reflects the current value
// of registerPrice rather than the value frozen at package init time.
// Replaces the old `ErrInvalidPayment = ufmt.Errorf(...)` package var
// (audit finding #13) which captured registerPrice once and silently
// drifted out of date after every ProposeNewRegisterPrice execution.
func errInvalidPayment() error {
	return ufmt.Errorf("%s: must send exactly %d ugnot",
		ErrInvalidPayment.Error(), registerPrice)
}

gnomod.toml

module = "gno.land/r/sys/namereg/v0"
gno = "0.9"

[addpkg]
  creator = "g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l"

init.gno

package namereg

import (
	"chain"
	"chain/runtime"

	susers "gno.land/r/sys/users"
)

func init(cur realm) {
	if runtime.ChainHeight() == 0 {
		susers.AddControllerAtGenesis(cross(cur), chain.PackageAddress("gno.land/r/sys/namereg/v0"))
	}
}

preregister.gno

package namereg

import (
	susers "gno.land/r/sys/users"
)

// Pre-registered names bypass the Open Nym Tier `nym-...\d{3}` format
// intentionally. They are bootstrap names allocated at genesis and are
// not subject to the auto-registration regex. They DO appear in
// reservedNames as a defense-in-depth (so a future governance-bypass
// path can't accidentally reallocate them either), but at this layer
// they are written directly via susers.RegisterUserIgnoreCanonical.
//
// Uses the bypass path so curated confusables in the seed (e.g.
// `gnoland` and `gnolang` both canonicalize distinctly today, but a
// future addition that collides must not abort chain bring-up).
// Matches the genesis posture in r/sys/users/init.gno.

// pre-registered users
var preRegisteredUsers = []struct {
	Name    string
	Address address
}{
	// system names.
	// the goal is to make them either team/DAO-owned or ownerless.
	{"archive", "g1xlnyjrnf03ju82v0f98ruhpgnquk28knmjfe5k"}, // -> @archive
	{"demo", "g13ek2zz9qurzynzvssyc4sthwppnruhnp0gdz8n"},    // -> @demo
	{"gno", "g19602kd9tfxrfd60sgreadt9zvdyyuudcyxsz8a"},     // -> @gno
	{"gnoland", "g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7"}, // -> @gnoland
	{"gnolang", "g1yjlnm3z2630gg5mryjd79907e0zx658wxs9hnd"}, // -> @gnolang
	{"gov", "g1g73v2anukg4ej7axwqpthsatzrxjsh0wk797da"},     // -> @gov
	{"nt", "g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l"},      // -> @nt
	{"sys", "g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l"},     // -> @sys
	{"x", "g164sdpew3c2t3rvxj3kmfv7c7ujlvcw2punzzuz"},       // -> @x

	// test1 user
	{"test1", "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"}, // -> @test1
}

func init(cur realm) {
	// add pre-registered users via the bypass path (genesis posture).
	// Errors are intentionally discarded; the seed is curated and any
	// duplicate-address / already-deleted entries (re-init across test
	// realm reuse) just no-op.
	for _, res := range preRegisteredUsers {
		susers.RegisterUserIgnoreCanonical(cross(cur), res.Name, res.Address)
	}
}

render.gno

package namereg

import (
	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/realmpath/v0"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/ufmt/v0"

	"gno.land/r/demo/profile"
	susers "gno.land/r/sys/users"
)

func Render(path string) string {
	req := realmpath.Parse(path)

	if req.Path == "" {
		return renderHomePage()
	}

	// Otherwise, render the user page
	return renderUserPage(req.Path)
}

func renderHomePage() string {
	var out string

	out += "# Gno.land User Registry\n"

	if paused {
		out += md.HorizontalRule()
		out += md.H2("This realm is paused.")
		out += md.Paragraph("Check out [`gno.land/r/sys/users`](/r/sys/users) for the current user registry.")
		out += md.HorizontalRule()
	}

	out += renderIntroParagraph()

	out += md.H2("Latest registrations")
	out += RenderLatestUsersWidget(-1)

	return out
}

func renderIntroParagraph() string {
	out := md.Paragraph("Welcome to the Gno.land User Registry (v0). Please register a username.")
	out += md.Paragraph(`Registering a username grants the registering address the right to deploy packages and realms
under that username’s namespace. For example, if an address registers the username ` + md.InlineCode("nym-alice123") + `, it
will gain permission to deploy packages and realms to package paths with the pattern ` + md.InlineCode("gno.land/{p,r}/nym-alice123/*") + `.`)

	out += md.Paragraph("In V0, usernames must match `nym-<stem><digits>`, where:")
	items := []string{
		"`<stem>` is 5 to 13 lowercase ASCII letters",
		"`<digits>` is exactly 3 decimal digits",
		"The stem must NOT start with `gno`, `gl`, `atom`, `atone`, `photon`, or `cosmos` (reserved prefixes)",
		"The stem must NOT match a reserved role name (admin, root, support, ...)",
		"Confusable variants (e.g. `vitaiik` vs `vitalik` via `l↔i`) are blocked via canonical-form collision detection",
		"Total username length: 12–20 chars (distinct from `g1...` addresses, which are always 40 chars)",
	}
	out += md.BulletList(items)

	out += "\n\n"
	out += md.Paragraph("Vanity names outside this format may be allocated by GovDAO governance through `ProposeNewName`.")

	if !paused {
		amount := ufmt.Sprintf("%dugnot", registerPrice)
		link := txlink.NewLink("Register")
		if registerPrice > 0 {
			link = link.SetSend(amount)
		}

		out += md.H3(ufmt.Sprintf(" [[Click here to register]](%s)", link.URL()))
		// XXX: Display registration price adjusting for dynamic GNOT price when it becomes possible.
		out += ufmt.Sprintf("Registration price: %f GNOT (%s)\n\n", float64(registerPrice)/1_000_000, amount)
	}

	out += md.HorizontalRule()
	out += "\n\n"

	return out
}

// resolveUser resolves the user based on the path, determining if it's a name or address
func resolveUser(path string) (*susers.UserData, bool, bool) {
	if address(path).IsValid() {
		return susers.ResolveAddress(address(path)), false, false
	}

	data, isLatest := susers.ResolveName(path)
	return data, isLatest, true
}

// renderUserPage generates the user page based on user data and path
func renderUserPage(path string) string {
	var out string

	// Render single user page
	data, isLatest, isName := resolveUser(path)
	if data == nil {
		out += md.H1("User not found.")
		out += "This user does not exist or has been deleted.\n"
		return out
	}

	out += md.H1("User - " + md.InlineCode(data.Name()))

	if isName && !isLatest {
		out += md.Paragraph(ufmt.Sprintf(
			"Note: You searched for `%s`, which is a previous name of [`%s`](/u/%s).",
			path, data.Name(), data.Name()))
	} else {
		out += ufmt.Sprintf("Address: %s\n\n", data.Addr().String())

		out += md.H2("Bio")
		out += profile.GetStringField(data.Addr(), "Bio", "No bio defined.")
		out += "\n\n"
		out += ufmt.Sprintf("[Update bio](%s)", txlink.Realm("gno.land/r/demo/profile").Call("SetStringField", "field", "Bio"))
		out += "\n\n"
	}

	return out
}

// RenderLatestUsersWidget renders the latest num registered users.
// For num = -1, the maximum number (100) will be displayed.
func RenderLatestUsersWidget(num int) string {
	size := latestUsers.Size()
	if size == 0 {
		return "No registered users."
	}

	if num > size || num < 0 {
		num = size
	}

	entries := latestUsers.Entries()
	var out string

	for i := size - 1; i >= size-num; i-- {
		user := entries[i].(string)
		out += md.BulletItem(md.UserLink(user))
	}

	return out
}

users.gno

package namereg

import (
	"chain"
	"chain/runtime/unsafe"

	"gno.land/p/moul/fifo/v0"
	susers "gno.land/r/sys/users"
)

// MinRegisterPrice is the lowest price (in ugnot) that
// ProposeNewRegisterPrice will accept. Set to 0 — registration is free
// by default; governance can raise the price via ProposeNewRegisterPrice
// without a floor.
const MinRegisterPrice = int64(0)

var (
	registerPrice = int64(0)      // free by default; governance can raise via ProposeNewRegisterPrice
	latestUsers   = fifo.New(100) // Save the latest 100 users for rendering purposes
)

// Register registers a new username for the caller.
//
// Valid usernames match `nym-[a-z]{5,13}\d{3}`:
//   - literal `nym-` prefix (4 chars)
//   - 5-13 lowercase letters (the alpha stem)
//   - exactly 3 trailing decimal digits
//
// Total length 12-20 chars. The alpha stem additionally must NOT start
// with `gno`/`gi`/`gl` and must not match a reserved role name (with
// implicit `s`-suffix expansion). See ValidateNymFormat for the
// format/blacklist check.
//
// Canonical-collision detection is enforced atomically by
// susers.RegisterUser via the unified canonical store in r/sys/users
// (decision: per Option B, every controller participates in the same
// canonical-form lookup keyed by full canonical name).
//
// Only direct EOA (maketx call) invocations are supported.
func Register(cur realm, username string) {
	// Anti-squatting payment check, two paired guards:
	//
	//   (a) PreviousRealm must be a pure EOA (IsUserCall: pkgPath == "").
	//       This excludes intermediate code realms AND user-run ephemeral
	//       realms ("maketx run" scripts). Both can attach -send to the
	//       tx but spend the coins on something other than forwarding to
	//       this realm, leaving OriginSend() describing a phantom payment.
	//       IsUserCall is the only PreviousRealm shape where the tx-send
	//       envelope is guaranteed to have landed at this realm's address.
	//
	//   (b) OriginSend amount must exactly equal registerPrice. Verifies
	//       the tx actually attached the expected amount.
	//
	// Both checks MUST run together. Removing (a) alone makes (b) meaningless
	// because OriginSend() describes tx intent, not realm receipt.
	if !cur.Previous().IsUserCall() {
		panic(ErrNonUserCall)
	}

	if paused {
		panic(ErrPaused)
	}

	if unsafe.OriginSend().AmountOf("ugnot") != registerPrice {
		panic(errInvalidPayment())
	}

	// Format + prefix + reserved-name check. ValidateNymFormat returns
	// one of ErrInvalidFormat, ErrReservedPrefix, ErrBlacklisted.
	if err := ValidateNymFormat(username); err != nil {
		panic(err)
	}

	// Delegate the canonical-collision check + nameStore write atomically
	// to r/sys/users. Returns susers.ErrCanonicalCollision if the
	// canonical form clashes with an existing registration in any
	// controller.
	registrant := cur.Previous().Address()
	if err := susers.RegisterUser(cross(cur), username, registrant); err != nil {
		panic(err)
	}

	latestUsers.Append(username)
	chain.Emit("Registration", "address", registrant.String(), "name", username)
}

users_test.gno

package namereg

import (
	"chain"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"

	susers "gno.land/r/sys/users"
)

// cur is a zero-value realm used as a placeholder when forwarding to
// uassert/urequire dispatch helpers that gained an `rlm realm` param.
// These tests pass `func()` callbacks (no crossing inside the callback),
// so rlm is ignored — a nil realm here is safe.
var cur realm

func init(cur realm) {
	// Unit tests run with DefaultHeight=123, so the production init() in init.gno
	// (guarded on height==0) is a no-op in tests. Temporarily reset height so we
	// can whitelist this realm as a controller for testing.
	testing.SetHeight(0)
	susers.AddControllerAtGenesis(cross(cur), chain.PackageAddress("gno.land/r/sys/namereg/v0"))
	testing.SetHeight(123)
}

func TestRegister_Valid(cur realm, t *testing.T) {
	// Stems chosen with no `l` characters to keep canonical forms identical
	// to the originals — avoids accidental cross-subtest collisions with
	// other tests that may register l-bearing names.
	validUsernames := []string{
		"nym-bravo123",         // 5-char stem (minimum)
		"nym-tango456",         // 5-char stem
		"nym-victor789",        // 6-char stem
		"nym-romeoecho012",     // 10-char stem
		"nym-mikefoxhote345",   // 11-char stem
		"nym-mikefoxhotenp678", // 13-char stem (maximum)
	}

	for _, username := range validUsernames {
		addr := testutils.TestAddress(username)

		testing.SetRealm(testing.NewUserRealm(addr))
		testing.SetOriginCaller(addr)
		testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))

		urequire.NotPanics(t, cur, func() {
			Register(cross(cur), username)
		})
	}
}

func TestRegister_Free(cur realm, t *testing.T) {
	oldPrice := registerPrice
	defer func() { registerPrice = oldPrice }()
	registerPrice = 0

	addr := testutils.TestAddress("free-payer")

	testing.SetRealm(testing.NewUserRealm(addr))
	testing.SetOriginCaller(addr)

	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), "nym-foxtrot456")
	})
}

func TestRegister_InvalidFormat(cur realm, t *testing.T) {
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("fmt-payer")))

	cases := []string{
		"",                      // empty
		"    ",                  // whitespace
		"alice123",              // missing nym- prefix
		"usr-alice123",          // wrong prefix
		"nym-",                  // prefix only
		"nym-abc123",            // stem too short (3 chars, need ≥5)
		"nym-abcd123",           // stem too short (4 chars)
		"nym-abcdefghijklmn123", // stem too long (14 chars, need ≤13)
		"nym-Alice123",          // uppercase in stem
		"nym-al1ce123",          // digit in stem
		"nym-alice12",           // only 2 trailing digits
		"nym-alice1234",         // 4 trailing digits (extra digit in stem too long)
		"nym-alice&#($)123",     // special chars in stem
	}

	for _, username := range cases {
		uassert.AbortsWithMessage(t, cur, ErrInvalidFormat.Error(), func() {
			Register(cross(cur), username)
		})
	}
}

func TestRegister_ReservedPrefix(cur realm, t *testing.T) {
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("prefix-payer")))

	cases := []string{
		"nym-gnoblah123",    // gno prefix
		"nym-gnomeland456",  // gno prefix
		"nym-glasgow012",    // gl prefix (most-confusable with bech32 g1...)
		"nym-atomic123",     // atom prefix
		"nym-atonex123",     // atone prefix
		"nym-photons456",    // photon prefix
		"nym-cosmoswide789", // cosmos prefix
	}

	for _, username := range cases {
		uassert.AbortsWithMessage(t, cur, ErrReservedPrefix.Error(), func() {
			Register(cross(cur), username)
		})
	}
}

// gi is intentionally NOT in reservedPrefixes (i is visually distinct
// enough from 1/l that legitimate gi* names should be registerable).
// Phishing protection for the gi/gl visual class is enforced by
// canonical-collision detection in r/sys/users — see
// TestRegister_CanonicalCollision.
func TestRegister_GiPrefix_Allowed(cur realm, t *testing.T) {
	addr := testutils.TestAddress("gi-prefix-allowed")
	testing.SetRealm(testing.NewUserRealm(addr))
	testing.SetOriginCaller(addr)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))

	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), "nym-gillette789")
	})
}

func TestRegister_Blacklisted(cur realm, t *testing.T) {
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("blk-payer")))

	cases := []string{
		// `admin` is in reservedNames; with stem 5 chars it now matches the regex.
		"nym-admin123",
		// `support` is reserved (7 chars).
		"nym-support456",
		// `bitcoin` is reserved (7 chars).
		"nym-bitcoin789",
		// Implicit s-suffix expansion: `blog` is reserved, so `blogs` (stem
		// = blog+s) must also be rejected.
		"nym-blogs012",
		// Canonical match: `setting` is reserved → canonical "setting" (no l).
		// Try `setting` directly via 7-char stem.
		"nym-setting345",
		// Canonical match: `news` is reserved via `new+s` rule; canonical
		// of `news` is `news`. With a 5-char stem this won't reach here
		// (stem must be ≥5). Use a longer reserved name with l→i interaction:
		// `tendermint` (10 chars, no l) → canonical = tendermint → blacklisted.
		"nym-tendermint678",
	}

	for _, username := range cases {
		uassert.AbortsWithMessage(t, cur, ErrBlacklisted.Error(), func() {
			Register(cross(cur), username)
		})
	}
}

func TestRegister_CanonicalCollision(cur realm, t *testing.T) {
	// First register a name. Same-digits confusable variant must collide
	// in the unified susers canonical store.
	addr1 := testutils.TestAddress("collision-1")
	testing.SetRealm(testing.NewUserRealm(addr1))
	testing.SetOriginCaller(addr1)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), "nym-balloon123")
	})

	// Then attempt to register a canonical-equivalent variant — same
	// canonical full name (after l→i, etc.). Must reject from susers.
	addr2 := testutils.TestAddress("collision-2")
	testing.SetRealm(testing.NewUserRealm(addr2))
	testing.SetOriginCaller(addr2)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	uassert.AbortsWithMessage(t, cur, susers.ErrCanonicalCollision.Error(), func() {
		Register(cross(cur), "nym-baiioon123")
	})

	// Reverse direction also blocked.
	addr3 := testutils.TestAddress("collision-3")
	testing.SetRealm(testing.NewUserRealm(addr3))
	testing.SetOriginCaller(addr3)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), "nym-papaiio789")
	})

	addr4 := testutils.TestAddress("collision-4")
	testing.SetRealm(testing.NewUserRealm(addr4))
	testing.SetOriginCaller(addr4)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	uassert.AbortsWithMessage(t, cur, susers.ErrCanonicalCollision.Error(), func() {
		Register(cross(cur), "nym-papallo789")
	})
}

// Decision #2 in Option B: store key is full canonical username (not
// stem). Same alpha stem with different digit suffixes coexists — does
// not collide.
func TestRegister_SameStemDifferentDigits_Coexist(cur realm, t *testing.T) {
	addrA := testutils.TestAddress("stem-coexist-A")
	testing.SetRealm(testing.NewUserRealm(addrA))
	testing.SetOriginCaller(addrA)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), "nym-foolbar000")
	})

	addrB := testutils.TestAddress("stem-coexist-B")
	testing.SetRealm(testing.NewUserRealm(addrB))
	testing.SetOriginCaller(addrB)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), "nym-foolbar999")
	})
}

func TestRegister_TakenUsername(cur realm, t *testing.T) {
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("taken-payer")))

	username := "nym-zulutwo567"

	urequire.NotPanics(t, cur, func() {
		Register(cross(cur), username)
	})

	// Re-registration of the same exact name is rejected by susers via
	// ErrNameTaken (the nameStore.Has check precedes the canonical check).
	uassert.AbortsWithMessage(t, cur, susers.ErrNameTaken.Error(), func() {
		Register(cross(cur), username)
	})
}

func TestRegister_InvalidPayment(cur realm, t *testing.T) {
	addr := testutils.TestAddress("payment-payer")

	testing.SetRealm(testing.NewUserRealm(addr))
	testing.SetOriginCaller(addr)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 12))) // invalid

	uassert.AbortsContains(t, cur, ErrInvalidPayment.Error(), func() {
		Register(cross(cur), "nym-yankee345")
	})
}

// Audit finding #11: the OriginSend() payment check is only trustworthy
// when the direct caller is a pure EOA (IsUserCall). Any intermediate
// code realm can attach -send to the tx, keep the coins, and call
// Register; OriginSend() would still describe the envelope but namereg
// would receive nothing. The EOA-only guard must reject all such callers.
func TestRegister_IntermediateCodeRealmRejected(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/evil/wrapper"))
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", registerPrice)))

	uassert.AbortsWithMessage(t, cur, ErrNonUserCall.Error(), func() {
		Register(cross(cur), "nym-whisky345")
	})
}

// Audit finding #13: the OriginSend mismatch error must report the
// CURRENT registerPrice, not the value frozen at package init time.
func TestRegister_PaymentErrorReflectsCurrentPrice(cur realm, t *testing.T) {
	oldPrice := registerPrice
	defer func() { registerPrice = oldPrice }()

	registerPrice = 5_000_000

	addr := testutils.TestAddress("price-payer")
	testing.SetRealm(testing.NewUserRealm(addr))
	testing.SetOriginCaller(addr)
	testing.SetOriginSend(chain.NewCoins(chain.NewCoin("ugnot", 1_000_000))) // wrong

	uassert.AbortsContains(t, cur, "5000000", func() {
		Register(cross(cur), "nym-xrayfox678")
	})

	uassert.AbortsContains(t, cur, ErrInvalidPayment.Error(), func() {
		Register(cross(cur), "nym-xrayfox678")
	})
}

// Audit finding #14: ProposeNewRegisterPrice originally rejected only
// negative prices. A passed proposal to set a negative price would
// have been arithmetically nonsense; reject below MinRegisterPrice
// (currently 0) at proposal-creation time so governance can never
// underflow the floor.
func TestProposeNewRegisterPrice_floor(cur realm, t *testing.T) {
	t.Run("zero is accepted (free registration is the default)", func(t *testing.T) {
		urequire.NotPanics(t, cur, func() { ProposeNewRegisterPrice(cur, 0) })
	})

	t.Run("negative is rejected", func(t *testing.T) {
		urequire.PanicsWithMessage(t, cur,
			"price below floor: -1 ugnot < 0 ugnot (MinRegisterPrice)",
			func() { ProposeNewRegisterPrice(cur, -1) })
	})

	t.Run("at floor is accepted", func(t *testing.T) {
		urequire.NotPanics(t, cur, func() { ProposeNewRegisterPrice(cur, MinRegisterPrice) })
	})

	t.Run("above floor is accepted", func(t *testing.T) {
		urequire.NotPanics(t, cur, func() { ProposeNewRegisterPrice(cur, 1_000_000_000) })
	})
}