Playground
admin.gno
package users
import (
"chain"
"chain/runtime"
"gno.land/p/moul/addrset/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/gov/dao"
)
const initControllerPath = "gno.land/r/sys/users/init"
var controllers = addrset.Set{} // caller whitelist
func init() {
// auto-whitelist the init controller for bootstrapping for testing chain.
if chainID := runtime.ChainID(); chainID == "dev" {
controllers.Add(chain.PackageAddress(initControllerPath))
}
}
// AddControllerAtGenesis allows adding a controller during chain genesis (height 0).
// This is mostly useful for testing.
func AddControllerAtGenesis(_ realm, addr address) {
height := runtime.ChainHeight()
if height > 0 {
panic("AddControllerAtGenesis can only be called at genesis (height 0)")
}
if !addr.IsValid() {
panic(ErrInvalidAddress)
}
controllers.Add(addr)
}
// ProposeNewController allows GovDAO to add a whitelisted caller
func ProposeNewController(cur realm, addr address) dao.ProposalRequest {
if !addr.IsValid() {
panic(ErrInvalidAddress)
}
cb := func(cur realm) error {
return addToWhitelist(addr)
}
desc := "This proposal adds " + addr.String() + " to `sys/users` realm's callers whitelist."
return dao.NewProposalRequest("Add Whitelisted Caller to \"sys/users\" Realm", desc, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// ProposeControllerRemoval allows GovDAO to add a whitelisted caller
func ProposeControllerRemoval(cur realm, addr address) dao.ProposalRequest {
if !addr.IsValid() {
panic(ErrInvalidAddress)
}
cb := func(cur realm) error {
return deleteFromWhitelist(addr)
}
desc := "This proposal removes " + addr.String() + " from `sys/users` realm's callers whitelist."
return dao.NewProposalRequest("Remove Whitelisted Caller From \"sys/users\" Realm", desc, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// ProposeControllerAdditionAndRemoval allows GovDAO to add a new caller and remove an old caller in the same proposal.
func ProposeControllerAdditionAndRemoval(cur realm, toAdd, toRemove address) dao.ProposalRequest {
if !toAdd.IsValid() || !toRemove.IsValid() {
panic(ErrInvalidAddress)
}
cb := func(cur realm) error {
return applyControllerSwap(toAdd, toRemove)
}
desc := ufmt.Sprintf(
"This proposal adds %s and removes %s from `sys/users` realm's callers whitelist.",
toAdd,
toRemove,
)
return dao.NewProposalRequest("Add and Remove Whitelisted Callers From \"sys/users\" Realm", desc, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// applyControllerSwap is the callback body of ProposeControllerAdditionAndRemoval,
// extracted so it can be unit-tested without driving the full GovDAO flow.
//
// The desired end state is "toAdd is in the whitelist AND toRemove is out".
// Both operations are made idempotent so the swap doesn't silently no-op when
// the chain state has drifted between proposal creation and execution:
//
// - If toAdd is already whitelisted, treat addToWhitelist's
// ErrAlreadyWhitelisted as benign and continue to the remove step.
// - If toRemove is already absent, treat deleteFromWhitelist's
// ErrNotWhitelisted as benign and return success.
//
// Without this idempotency, the original code returned early on an "already
// whitelisted" toAdd and skipped the remove entirely — a swap proposal could
// pass governance and silently leave the old controller active. (audit
// finding #6)
func applyControllerSwap(toAdd, toRemove address) error {
if err := addToWhitelist(toAdd); err != nil && err != ErrAlreadyWhitelisted {
return err
}
if err := deleteFromWhitelist(toRemove); err != nil {
if _, alreadyOut := err.(ErrNotWhitelisted); !alreadyOut {
return err
}
}
return nil
}
// ProposeRegisterUser allows GovDAO to register a name without checking
// controllers. The executor closure runs with ignoreCanonical=true (decision
// #3): DAO grants always bypass canonical-collision detection. Voters see
// any collision in the proposal description and can vote NO if unintended.
func ProposeRegisterUser(cur realm, name string, addr address) dao.ProposalRequest {
// Validate the name and address now, even though registerUser will validate again
if err := validateName(name); err != nil {
panic(err.Error())
}
if !addr.IsValid() {
panic(ErrInvalidAddress)
}
desc := "This proposal registers " + name + " with address " + addr.String() + " in `sys/users`."
if existing, taken := IsCanonicalTaken(name); taken && existing != name {
desc += "\n\nCANONICAL COLLISION: this name's canonical form matches the existing registration of `" +
existing + "`. DAO grants bypass canonical-collision detection — the proposal will succeed if voted in. " +
"If the collision is unintended, vote NO."
}
cb := func(cur realm) error {
return registerUser(cur, name, addr, true) // bypass canonical (decision #3)
}
return dao.NewProposalRequest("Register User to \"sys/users\" Realm", desc, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// ProposeUpdateName allows GovDAO to update a name with an alias without
// checking controllers. Like ProposeRegisterUser, the executor runs with
// ignoreCanonical=true (decision #3).
func ProposeUpdateName(cur realm, addr address, newName string) dao.ProposalRequest {
if !addr.IsValid() {
panic(ErrInvalidAddress)
}
if err := validateName(newName); err != nil {
panic(err.Error())
}
desc := "This proposal updates address " + addr.String() + " with alias " + newName + " in `sys/users`."
if existing, taken := IsCanonicalTaken(newName); taken && existing != newName {
desc += "\n\nCANONICAL COLLISION: the new alias's canonical form matches the existing registration of `" +
existing + "`. DAO grants bypass canonical-collision detection — the proposal will succeed if voted in. " +
"If the collision is unintended, vote NO."
}
cb := func(cur realm) error {
data := ResolveAddress(addr)
if data == nil {
return ErrUserNotExistOrDeleted
}
return data.updateName(newName, true) // bypass canonical (decision #3)
}
return dao.NewProposalRequest("Update Name Alias in \"sys/users\" Realm", desc, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// ProposeDeleteUser allows GovDAO to delete a user without checking controllers
func ProposeDeleteUser(cur realm, addr address) dao.ProposalRequest {
if !addr.IsValid() {
panic(ErrInvalidAddress)
}
cb := func(cur realm) error {
data := ResolveAddress(addr)
if data == nil {
return ErrUserNotExistOrDeleted
}
return data.delete()
}
desc := "This proposal deletes the user with address " + addr.String() + " in `sys/users`."
return dao.NewProposalRequest("Delete User in \"sys/users\" Realm", desc, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// IsController reports whether the given address is currently in the
// controller whitelist. Returns the same boolean that gating checks
// (RegisterUser, UpdateName, Delete) use internally — useful for
// off-chain monitoring and for governance proposals to inspect state
// before voting.
func IsController(addr address) bool {
return controllers.Has(addr)
}
// Controllers returns a snapshot of the current controller whitelist.
// The returned slice is a fresh copy; mutating it does not affect realm
// state. Order is the iteration order of the underlying address set.
//
// Audit finding #20: without this getter, the controller whitelist was
// opaque from outside the package — operators had to read source or
// replay every governance proposal to know who could write to the
// registry. This is the read-only API that closes that gap.
func Controllers() []address {
out := make([]address, 0, controllers.Size())
controllers.IterateByOffset(0, controllers.Size(), func(a address) bool {
out = append(out, a)
return false
})
return out
}
// Helpers
func deleteFromWhitelist(addr address) error {
if !controllers.Has(addr) {
return ErrNotWhitelisted{Caller: "UserRealm{ " + addr.String() + " }"}
}
if ok := controllers.Remove(addr); !ok {
return ErrWhitelistRemoveFailed
}
return nil
}
func addToWhitelist(newCaller address) error {
if !controllers.Add(newCaller) {
return ErrAlreadyWhitelisted
}
return nil
}
api.gno
package users
// IsNameTaken reports whether the exact-string name exists in nameStore.
// Returns true for any name ever registered, including:
//
// - active registrations
// - tombstoned (deleted) users' names — Delete() sets `deleted=true`
// but does not remove the nameStore entry (anti-revival policy)
// - old aliases from renames — UpdateName inserts the new name
// alongside the old; the old key stays (anti-rename-squat policy)
//
// In short: IsNameTaken(name) answers "would RegisterUser(name, _)
// fail with ErrNameTaken?" — same answer for active, deleted, or
// aliased-away names. Pairs with IsCanonicalTaken (canonical-match)
// and ResolveName (active-current-user lookup with full UserData).
//
// No canonicalization is applied. For controllers that want exact-
// match uniqueness without pulling in canonical-collision logic.
func IsNameTaken(name string) bool {
return nameStore.Has(name)
}
// IsCanonicalTaken reports whether the given name's canonical form is
// already registered. Pass the raw name; canonicalization is applied
// internally. The first return is the original (non-canonical) name
// that owns the canonical key, for UX in collision messages.
//
// When a bypass write (RegisterUserIgnoreCanonical or the bypass path
// through ProposeRegisterUser/ProposeUpdateName) overwrites a prior
// canonical entry, this returns the most-recently-written original.
func IsCanonicalTaken(name string) (existing string, taken bool) {
v := canonicalStore.Get(Canonicalize(name))
if v == nil {
return "", false
}
return v.(string), true
}
canonical.gno
package users
import (
"strings"
"gno.land/p/nt/bptree/v0"
)
// canonicalStore maps canonicalized full names to the original name
// that was registered. Keyed by the result of Canonicalize.
//
// Multiple controllers (namereg/v0, future registries, governance,
// genesis bootstrapping) all share this single store via RegisterUser
// and the bypass variant RegisterUserIgnoreCanonical. Cross-controller
// canonical-collision detection is uniform and atomic with the
// nameStore write.
var canonicalStore = bptree.NewBPTree32()
// Canonicalize returns the canonical form of a name. The substitutions
// collapse single-character visual confusables that arise across the
// allowed [a-z0-9] character set, and strip the three separators that
// can sneak between identical alphanumeric runs.
//
// - {l, i, 1} → i
// - {0, o} → o
// - {-, ., _} → stripped
// - all other characters unchanged
//
// CONTRACT: stable. Future controllers that want to share this
// canonical namespace MUST use this exact function — do not roll your
// own. Adding new substitutions later is a breaking change because it
// would silently re-key existing entries in canonicalStore.
//
// Input contract: ASCII-only. r/sys/users.validateName already rejects
// non-ASCII at the registration boundary, so by the time a name reaches
// Canonicalize through the standard write path it is guaranteed to be
// ASCII. Direct callers from other realms must honor this contract;
// non-ASCII bytes are passed through as-is and will produce undefined
// collision behavior.
//
// Multi-char confusables (m↔rn, nn↔m, cl↔d) are NOT canonicalized.
// They require fixed-point substring substitution rounds, which is out
// of scope for the unified store.
//
// Pure: no state access. Safe to call from anywhere.
func Canonicalize(name string) string {
var b strings.Builder
b.Grow(len(name))
for i := 0; i < len(name); i++ {
c := name[i]
switch c {
case 'l', '1':
b.WriteByte('i')
case '0':
b.WriteByte('o')
case '-', '.', '_':
// strip
default:
b.WriteByte(c)
}
}
return b.String()
}
crossrealm_test.gno
package users
import (
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
// TestUpdateNameCallerIdentity verifies that the CurrentRealm() check in
// UpdateName correctly identifies the calling controller.
//
// Background: RegisterUser uses PreviousRealm() because it is a crossing
// function (cur realm). UpdateName uses CurrentRealm() because it is a
// non-crossing method on *UserData. Per the interrealm spec:
//
// - Crossing function: CurrentRealm = this realm, PreviousRealm = caller
// - Non-crossing method on external object, called from crossing context:
// CurrentRealm = caller (unchanged from crossing context)
//
// This test verifies that a whitelisted controller can call UpdateName,
// and a non-whitelisted realm cannot.
func TestUpdateNameCallerIdentity(cur realm, t *testing.T) {
controllerPath := initControllerPath
nonControllerPath := "gno.land/r/evil/attacker"
t.Run("whitelisted_controller_can_update", func(cur realm, t *testing.T) {
cleanStore(t)
// Register as whitelisted controller
testing.SetRealm(testing.NewCodeRealm(controllerPath))
urequire.NoError(t, RegisterUser(cross(cur), "testuser1", testutils.TestAddress("testuser1")))
// Resolve and update name — should succeed because controller is whitelisted
data := ResolveAddress(testutils.TestAddress("testuser1"))
urequire.NotEqual(t, nil, data)
uassert.NoError(t, data.UpdateName(0, cur, "newname1"))
uassert.Equal(t, "newname1", data.Name())
})
t.Run("non_whitelisted_realm_cannot_update", func(cur realm, t *testing.T) {
cleanStore(t)
// Register as whitelisted controller
testing.SetRealm(testing.NewCodeRealm(controllerPath))
urequire.NoError(t, RegisterUser(cross(cur), "testuser2", testutils.TestAddress("testuser2")))
data := ResolveAddress(testutils.TestAddress("testuser2"))
urequire.NotEqual(t, nil, data)
// Switch to non-whitelisted realm — UpdateName should fail
testing.SetRealm(testing.NewCodeRealm(nonControllerPath))
err := data.UpdateName(0, cur, "hacked")
uassert.ErrorContains(t, err, "does not exist in whitelist")
uassert.Equal(t, "testuser2", data.Name()) // name unchanged
})
}
// TestDeleteCallerIdentity verifies the same CurrentRealm() behavior for Delete.
func TestDeleteCallerIdentity(cur realm, t *testing.T) {
controllerPath := initControllerPath
nonControllerPath := "gno.land/r/evil/attacker"
t.Run("whitelisted_controller_can_delete", func(cur realm, t *testing.T) {
cleanStore(t)
testing.SetRealm(testing.NewCodeRealm(controllerPath))
urequire.NoError(t, RegisterUser(cross(cur), "deluser1", testutils.TestAddress("deluser1")))
data := ResolveAddress(testutils.TestAddress("deluser1"))
urequire.NotEqual(t, nil, data)
uassert.NoError(t, data.Delete(0, cur))
uassert.True(t, data.IsDeleted())
})
t.Run("non_whitelisted_realm_cannot_delete", func(cur realm, t *testing.T) {
cleanStore(t)
testing.SetRealm(testing.NewCodeRealm(controllerPath))
urequire.NoError(t, RegisterUser(cross(cur), "deluser2", testutils.TestAddress("deluser2")))
data := ResolveAddress(testutils.TestAddress("deluser2"))
urequire.NotEqual(t, nil, data)
// Switch to non-whitelisted realm — Delete should fail
testing.SetRealm(testing.NewCodeRealm(nonControllerPath))
err := data.Delete(0, cur)
uassert.ErrorContains(t, err, "does not exist in whitelist")
uassert.False(t, data.IsDeleted()) // not deleted
})
}
errors.gno
package users
import (
"errors"
)
const prefix = "r/sys/users: "
var (
ErrAlreadyWhitelisted = errors.New(prefix + "already whitelisted")
ErrWhitelistRemoveFailed = errors.New(prefix + "failed to remove address from whitelist")
ErrNameTaken = errors.New(prefix + "name/Alias already taken")
ErrCanonicalCollision = errors.New(prefix + "name collides with a confusable variant of an existing name")
ErrInvalidAddress = errors.New(prefix + "invalid address")
ErrEmptyUsername = errors.New(prefix + "empty username provided")
ErrNameLikeAddress = errors.New(prefix + "username resembles a gno.land address")
ErrInvalidUsername = errors.New(prefix + "username must match ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ (max 64 chars)")
ErrAlreadyHasName = errors.New(prefix + "username for this address already registered - try creating an Alias")
ErrDeletedUser = errors.New(prefix + "cannot register a new username after deleting")
ErrUserNotExistOrDeleted = errors.New(prefix + "this user does not exist or was deleted")
// ErrInvalidRealm is returned by controller-gated *UserData mutators
// when the supplied rlm is not the caller's live cur (i.e.
// rlm.IsCurrent() is false). Closes Class-2 designation forgery via
// a stored stale realm value whose .Address() resolves to a
// whitelisted controller. See docs/resources/gno-security.md.
ErrInvalidRealm = errors.New(prefix + "rlm is not the caller's live cur")
)
// ErrNotWhitelisted stores the failing caller's realm identity as a
// plain string so the error is a pure data record (no live realm values
// in its fields).
type ErrNotWhitelisted struct {
Caller string // "CodeRealm{ <addr>, <pkgPath> }" or "UserRealm{ <addr> }" — failed the whitelist check
}
// NewErrNotWhitelisted constructs the error with the caller's realm
// identity captured as a string at construction time. The _ int
// discriminator keeps this non-crossing (a non-crossing function can't
// take a `realm`-named-`cur` first param, so we use the standard
// _ int, rlm realm shape).
func NewErrNotWhitelisted(_ int, caller realm) ErrNotWhitelisted {
return ErrNotWhitelisted{
Caller: caller.String(),
}
}
func (e ErrNotWhitelisted) Error() string {
return prefix + "caller realm/user does not exist in whitelist: " + e.Caller
}
gnomod.toml
module = "gno.land/r/sys/users" gno = "0.9" [addpkg] creator = "g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l"
render.gno
package users
import "gno.land/p/nt/ufmt/v0"
func Render(_ string) string {
out := "# r/sys/users\n\n"
out += "`r/sys/users` is a system realm for managing user registrations.\n\n"
out += "User registration is managed through whitelisted controller realms.\n\n"
out += "---\n\n"
out += "## Stats\n\n"
out += ufmt.Sprintf("Total unique addresses registered: **%d**\n\n", addressStore.Size())
out += ufmt.Sprintf("Total unique names registered: **%d**\n\n", nameStore.Size())
return out
}
store.gno
package users
import (
"chain"
"chain/runtime"
"regexp"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/ufmt/v0"
)
var (
nameStore = bptree.NewBPTree32() // name/aliases > *UserData
addressStore = bptree.NewBPTree32() // address > *UserData
reAddressLookalike = regexp.MustCompile(`^g1[a-z0-9]{20,38}$`)
// reName mirrors gno's package-name shape (gnovm/pkg/gnolang/mempackage.go
// `Re_name`): start with a lowercase letter, optional alphanumeric body,
// then any number of (separator + alphanumeric run) — so single hyphens
// or underscores are allowed BETWEEN alphanumerics, but consecutive
// separators (`--`, `__`, `-_`, `_-`) are rejected, and so are leading
// or trailing separators. Lowercase-only — closes the case-confusable
// squatting concern (Alice vs alice were two distinct names under the
// previous case-preserving regex). Length cap of 64 enforced separately
// in validateName.
reName = regexp.MustCompile(`^[a-z][a-z0-9]*([_-][a-z0-9]+)*$`)
)
const maxNameLen = 64
const (
RegisterUserEvent = "Registered"
UpdateNameEvent = "Updated"
DeleteUserEvent = "Deleted"
)
type UserData struct {
addr address
username string // contains the latest name of a user
deleted bool
}
func (u UserData) Name() string {
return u.username
}
func (u UserData) Addr() address {
return u.addr
}
// IsDeleted reports whether this user record is missing or marked deleted.
// A nil receiver returns true — "the user does not exist" is semantically
// indistinguishable from "the user was deleted" for callers that need to
// gate further state changes. This lets call sites collapse the nil check
// and the deleted check into a single guard:
//
// if u.IsDeleted() {
// return ErrUserNotExistOrDeleted
// }
func (u *UserData) IsDeleted() bool {
if u == nil {
return true
}
return u.deleted
}
// RenderLink provides a render link to the user page on gnoweb
// `linkText` is optional
func (u UserData) RenderLink(linkText string) string {
if linkText == "" {
return ufmt.Sprintf("[@%s](/u/%s)", u.username, u.username)
}
return ufmt.Sprintf("[%s](/u/%s)", linkText, u.username)
}
// registerUser adds a new user to the system without checking controllers.
// The ignoreCanonical flag suppresses ErrCanonicalCollision; the canonical
// store is written either way (decision #14: later-wins on bypass).
func registerUser(cur realm, name string, address_XXX address, ignoreCanonical bool) error {
// Validate name
if err := validateName(name); err != nil {
return err
}
// Validate address
if !address_XXX.IsValid() {
return ErrInvalidAddress
}
// Check if name is taken (exact-string match precedes canonical check)
if nameStore.Has(name) {
return ErrNameTaken
}
canonical := Canonicalize(name)
if !ignoreCanonical {
if canonicalStore.Has(canonical) {
return ErrCanonicalCollision
}
}
raw := addressStore.Get(address_XXX.String())
if raw != nil {
// Cannot re-register after deletion
if raw.(*UserData).IsDeleted() {
return ErrDeletedUser
}
// For a second name, use UpdateName
return ErrAlreadyHasName
}
// Create UserData
data := &UserData{
addr: address_XXX,
username: name,
deleted: false,
}
// Set corresponding stores
nameStore.Set(name, data)
addressStore.Set(address_XXX.String(), data)
canonicalStore.Set(canonical, name)
chain.Emit(RegisterUserEvent,
"name", name,
"address", address_XXX.String(),
)
return nil
}
// RegisterUser adds a new user to the system. Enforces canonical-
// collision detection: a name whose Canonicalize-form matches a prior
// registration returns ErrCanonicalCollision.
func RegisterUser(cur realm, name string, address_XXX address) error {
// IsCurrent before Previous, as UpdateName/Delete below already do. The
// file was inconsistent: those three checked it, these two did not.
if !cur.IsCurrent() {
return NewErrNotWhitelisted(0, cur.Previous())
}
// At genesis (height 0), allow any caller to register users.
// After genesis, only whitelisted controllers can register.
if runtime.ChainHeight() > 0 && !controllers.Has(cur.Previous().Address()) {
return NewErrNotWhitelisted(0, cur.Previous())
}
return registerUser(cur, name, address_XXX, false)
}
// RegisterUserIgnoreCanonical is the bypass path: same controller-
// whitelist gate, but ErrCanonicalCollision is suppressed. The canonical
// store is still written; a prior entry with the same canonical key is
// silently overwritten (decision #14, later-wins). Use sparingly — names
// registered here can canonical-collide with existing ones, weakening
// confusable protection for everyone.
func RegisterUserIgnoreCanonical(cur realm, name string, address_XXX address) error {
// IsCurrent before Previous, as UpdateName/Delete below already do. The
// file was inconsistent: those three checked it, these two did not.
if !cur.IsCurrent() {
return NewErrNotWhitelisted(0, cur.Previous())
}
if runtime.ChainHeight() > 0 && !controllers.Has(cur.Previous().Address()) {
return NewErrNotWhitelisted(0, cur.Previous())
}
return registerUser(cur, name, address_XXX, true)
}
// updateName adds a name that is associated with a specific address without
// checking controllers. The ignoreCanonical flag suppresses
// ErrCanonicalCollision; the canonical store is written either way (decision
// #14: later-wins on bypass).
//
// All previous names are preserved and resolvable.
// The new name is the default value returned for address lookups.
func (u *UserData) updateName(newName string, ignoreCanonical bool) error {
// IsDeleted handles both branches: nil receiver (user never existed)
// AND a non-nil receiver whose .deleted is true (a controller cached
// the *UserData pointer before the user was deleted by a separate
// controller or governance proposal). Without the deleted-flag branch,
// nameStore.Set(newName, u) would insert an alias pointing at a
// deleted user — Has(newName) returns true forever but Resolve(newName)
// returns nil (Resolve* APIs filter deleted), so the name is squatted
// with no recovery path. (audit finding #3)
if u.IsDeleted() {
return ErrUserNotExistOrDeleted
}
// Validate name
if err := validateName(newName); err != nil {
return err
}
// Check if the requested Alias is already taken (exact-string match)
if nameStore.Has(newName) {
return ErrNameTaken
}
canonical := Canonicalize(newName)
if !ignoreCanonical {
// No self-collision filter (decision #15): even the user's OWN
// prior canonical claim blocks the rename. Prevents accumulating
// confusable aliases of one's own name through free renames. The
// only path to a self-confusable rename is DAO governance via
// ProposeUpdateName.
if canonicalStore.Has(canonical) {
return ErrCanonicalCollision
}
}
u.username = newName
nameStore.Set(newName, u)
canonicalStore.Set(canonical, newName)
chain.Emit(UpdateNameEvent,
"alias", newName,
"address", u.addr.String(),
)
return nil
}
// UpdateName adds a name that is associated with a specific address.
// Enforces canonical-collision detection.
// All previous names are preserved and resolvable.
// The new name is the default value returned for address lookups.
//
// rlm is the cur of the caller's enclosing crossing function (passed as
// data via the `_ int, rlm realm` non-crossing form). rlm.Address() is
// the calling realm against which we authorize.
func (u *UserData) UpdateName(_ int, rlm realm, newName string) error {
if !rlm.IsCurrent() {
return ErrInvalidRealm
}
if u.IsDeleted() {
return ErrUserNotExistOrDeleted
}
// Validate caller
if !controllers.Has(rlm.Address()) {
return NewErrNotWhitelisted(0, rlm)
}
return u.updateName(newName, false)
}
// UpdateNameIgnoreCanonical is the bypass path: same controller-
// whitelist gate, but ErrCanonicalCollision is suppressed. The canonical
// store is still written; a prior entry with the same canonical key is
// silently overwritten (decision #14, later-wins).
func (u *UserData) UpdateNameIgnoreCanonical(_ int, rlm realm, newName string) error {
if !rlm.IsCurrent() {
return ErrInvalidRealm
}
if u.IsDeleted() {
return ErrUserNotExistOrDeleted
}
if !controllers.Has(rlm.Address()) {
return NewErrNotWhitelisted(0, rlm)
}
return u.updateName(newName, true)
}
// delete marks a user and all their aliases as deleted without checking controllers.
func (u *UserData) delete() error {
if u.IsDeleted() {
return ErrUserNotExistOrDeleted
}
u.deleted = true
chain.Emit(DeleteUserEvent, "address", u.addr.String())
return nil
}
// Delete marks a user and all their aliases as deleted.
// rlm is the cur of the caller's enclosing crossing function; see UpdateName.
func (u *UserData) Delete(_ int, rlm realm) error {
if !rlm.IsCurrent() {
return ErrInvalidRealm
}
if u.IsDeleted() {
return ErrUserNotExistOrDeleted
}
// Validate caller
if !controllers.Has(rlm.Address()) {
return NewErrNotWhitelisted(0, rlm)
}
return u.delete()
}
// Validate validates username and address passed in
// Most of the validation is done in the controllers
// This provides more flexibility down the line
func validateName(username string) error {
if username == "" {
return ErrEmptyUsername
}
if len(username) > maxNameLen {
return ErrInvalidUsername
}
if !reName.MatchString(username) {
return ErrInvalidUsername
}
// Check if the username can be decoded or looks like a valid address
if address(username).IsValid() || reAddressLookalike.MatchString(username) {
return ErrNameLikeAddress
}
return nil
}
store_test.gno
package users
import (
"chain"
"testing"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
var (
alice = "alice"
aliceAddr = testutils.TestAddress(alice)
bob = "bob"
bobAddr = testutils.TestAddress(bob)
whitelistedCallerAddr = chain.PackageAddress(initControllerPath)
)
func TestRegister(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("valid_registration", func(t *testing.T) {
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
res, isLatest := ResolveName(alice)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.True(t, isLatest)
res = ResolveAddress(aliceAddr)
uassert.Equal(t, alice, res.Name())
})
t.Run("invalid_inputs", func(t *testing.T) {
cleanStore(t)
uassert.ErrorContains(t, RegisterUser(cross(cur), "", aliceAddr), ErrEmptyUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), alice, ""), ErrInvalidAddress.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), alice, "invalidaddress"), ErrInvalidAddress.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "username with a space", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t,
RegisterUser(cross(cur), "verylongusernameverylongusernameverylongusernameverylongusername1", aliceAddr),
ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "namewith^&()", aliceAddr), ErrInvalidUsername.Error())
// Lowercase-only enforcement (closes case-confusable squatting via
// Alice/alice/ALICE registering as distinct names — see TO_REVIEW
// adversarial review). reName mirrors gno's mempackage Re_name shape.
uassert.ErrorContains(t, RegisterUser(cross(cur), "Alice", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "ALICE", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "aLice", aliceAddr), ErrInvalidUsername.Error())
// Must start with a lowercase letter. Names starting with a digit,
// underscore, or hyphen are rejected.
uassert.ErrorContains(t, RegisterUser(cross(cur), "1alice", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "9", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "_alice", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "-alice", aliceAddr), ErrInvalidUsername.Error())
// Cannot end with a separator either (the new mempackage-aligned
// regex requires the final char to be in [a-z0-9]).
uassert.ErrorContains(t, RegisterUser(cross(cur), "alice_", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "alice-", aliceAddr), ErrInvalidUsername.Error())
// Cannot have consecutive separators in the middle either.
// Each separator MUST be followed by at least one alphanumeric.
uassert.ErrorContains(t, RegisterUser(cross(cur), "alice--bob", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "alice__bob", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "alice-_bob", aliceAddr), ErrInvalidUsername.Error())
uassert.ErrorContains(t, RegisterUser(cross(cur), "alice_-bob", aliceAddr), ErrInvalidUsername.Error())
// Length cap of exactly 64 — boundary cases.
exactly65 := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // 65 chars
uassert.ErrorContains(t, RegisterUser(cross(cur), exactly65, aliceAddr), ErrInvalidUsername.Error())
})
t.Run("valid_edge_cases", func(t *testing.T) {
// Names valid under the mempackage-aligned reName: starts with a
// letter, may contain hyphens or underscores in the middle, ends
// in [a-z0-9]. The hyphen support is what enables the namereg/v0
// `nym-...` prefix shape.
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur),
"nym-alice123",
testutils.TestAddress("u_nym_alice")))
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur),
"a_b_c",
testutils.TestAddress("u_underscore")))
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur),
"a",
testutils.TestAddress("u_singlechar")))
cleanStore(t)
// 64 chars exactly (length cap is inclusive).
exactly64 := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
urequire.NoError(t, RegisterUser(cross(cur),
exactly64,
testutils.TestAddress("u_64")))
})
t.Run("addr_already_registered", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
// Try registering again
uassert.ErrorContains(t, RegisterUser(cross(cur), "othername", aliceAddr), ErrAlreadyHasName.Error())
})
t.Run("name_taken", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
// Try registering alice's name with bob's address
uassert.ErrorContains(t, RegisterUser(cross(cur), alice, bobAddr), ErrNameTaken.Error())
})
t.Run("user_deleted", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
urequire.NoError(t, data.Delete(0, cur))
// Try re-registering after deletion
uassert.ErrorContains(t, RegisterUser(cross(cur), "newname", aliceAddr), ErrDeletedUser.Error())
})
t.Run("address_lookalike", func(t *testing.T) {
cleanStore(t)
// Address as username
uassert.ErrorContains(t, RegisterUser(cross(cur), "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5", aliceAddr), ErrNameLikeAddress.Error())
// Beginning of address as username
uassert.ErrorContains(t, RegisterUser(cross(cur), "g1jg8mtutu9khhfwc4nxmu", aliceAddr), ErrNameLikeAddress.Error())
uassert.NoError(t, RegisterUser(cross(cur), "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5longerthananaddress", aliceAddr))
})
}
func TestUpdateName(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("valid_direct_alias", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
{
testing.SetOriginCaller(whitelistedCallerAddr)
uassert.NoError(t, data.UpdateName(0, cur, "alice1"))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
})
t.Run("valid_double_alias", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
{
testing.SetOriginCaller(whitelistedCallerAddr)
uassert.NoError(t, data.UpdateName(0, cur, "alice2"))
uassert.NoError(t, data.UpdateName(0, cur, "alice3"))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
uassert.Equal(t, ResolveAddress(aliceAddr).username, "alice3")
})
t.Run("name_taken", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
uassert.Error(t, data.UpdateName(0, cur, alice), ErrNameTaken.Error())
})
t.Run("alias_before_name", func(t *testing.T) {
cleanStore(t)
data := ResolveAddress(aliceAddr) // not registered
uassert.ErrorContains(t, data.UpdateName(0, cur, alice), ErrUserNotExistOrDeleted.Error())
})
t.Run("alias_after_delete", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
{
urequire.NoError(t, data.Delete(0, cur))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
data = ResolveAddress(aliceAddr)
{
uassert.ErrorContains(t, data.UpdateName(0, cur, "newalice"), ErrUserNotExistOrDeleted.Error())
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
})
// Audit finding #3: a controller holding a cached *UserData pointer to a
// user that gets deleted between resolve and update must not be able to
// insert a new alias. The alias_after_delete test above re-resolves and
// gets nil, so it only exercises the u==nil branch. This test holds the
// pointer across the delete and verifies the deleted-flag branch.
t.Run("alias_with_cached_pointer_after_delete", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
// Cache the pointer BEFORE deletion (simulating a controller that
// resolved earlier and held the reference).
cached := ResolveAddress(aliceAddr)
urequire.NotEqual(t, nil, cached)
// Delete via a fresh resolve.
data := ResolveAddress(aliceAddr)
{
urequire.NoError(t, data.Delete(0, cur))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
// The cached pointer is non-nil but its .deleted is now true.
urequire.NotEqual(t, nil, cached)
uassert.True(t, cached.IsDeleted())
// Attempting UpdateName on the cached pointer must reject — without
// this check, "squattedname" would be inserted into nameStore
// pointing at the deleted user, becoming permanently unresolvable
// AND unregisterable.
{
testing.SetOriginCaller(whitelistedCallerAddr)
uassert.ErrorContains(t, cached.UpdateName(0, cur, "squattedname"), ErrUserNotExistOrDeleted.Error())
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
// Confirm the squat didn't happen: nameStore should NOT have it.
uassert.False(t, nameStore.Has("squattedname"))
})
t.Run("invalid_inputs", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
{
testing.SetOriginCaller(whitelistedCallerAddr)
uassert.ErrorContains(t, data.UpdateName(0, cur, ""), ErrEmptyUsername.Error())
uassert.ErrorContains(t, data.UpdateName(0, cur, "username with a space"), ErrInvalidUsername.Error())
uassert.ErrorContains(t,
data.UpdateName(0, cur, "verylongusernameverylongusernameverylongusernameverylongusername1"),
ErrInvalidUsername.Error())
uassert.ErrorContains(t, data.UpdateName(0, cur, "namewith^&()"), ErrInvalidUsername.Error())
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
})
t.Run("address_lookalike", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
{
// Address as username
uassert.ErrorContains(t, data.UpdateName(0, cur, "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"), ErrNameLikeAddress.Error())
// Beginning of address as username
uassert.ErrorContains(t, data.UpdateName(0, cur, "g1jg8mtutu9khhfwc4nxmu"), ErrNameLikeAddress.Error())
uassert.NoError(t, data.UpdateName(0, cur, "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5longerthananaddress"))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
}
})
}
func TestDelete(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("non_existent_user", func(t *testing.T) {
cleanStore(t)
data := ResolveAddress(testutils.TestAddress("unregistered"))
uassert.ErrorContains(t, data.Delete(0, cur), ErrUserNotExistOrDeleted.Error())
})
t.Run("double_delete", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
urequire.NoError(t, data.Delete(0, cur))
data = ResolveAddress(aliceAddr)
uassert.ErrorContains(t, data.Delete(0, cur), ErrUserNotExistOrDeleted.Error())
})
t.Run("valid_delete", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data := ResolveAddress(aliceAddr)
uassert.NoError(t, data.Delete(0, cur))
resolved1, _ := ResolveName(alice)
uassert.Equal(t, nil, resolved1)
uassert.Equal(t, nil, ResolveAddress(aliceAddr))
})
}
func TestRegisterNotWhitelisted(cur realm, t *testing.T) {
t.Run("register_not_whitelisted", func(t *testing.T) {
uassert.ErrorContains(t, RegisterUser(cross(cur), alice, aliceAddr), "does not exist in whitelist")
})
}
func TestCanonicalize(cur realm, t *testing.T) {
cases := []struct {
in, want string
}{
// Single-rule cases.
{"l", "i"}, {"i", "i"}, {"1", "i"},
{"0", "o"}, {"o", "o"},
{"-", ""}, {".", ""}, {"_", ""},
// Identity / pass-through.
{"abc", "abc"}, {"xyz", "xyz"}, {"123", "i23"},
// Open Nym Tier examples from the design doc.
{"nym-vital1k123", "nymvitaiiki23"},
{"nym-vitalik123", "nymvitaiiki23"},
{"nym-vital1k999", "nymvitaiik999"},
// Same stem, different digit suffix → distinct canonicals.
{"nym-foolbar000", "nymfooibarooo"},
{"nym-foolbar001", "nymfooibarooi"},
// Three-way separator equivalence.
{"xyz-com", "xyzcom"},
{"xyz_com", "xyzcom"},
{"xyz.com", "xyzcom"},
// Idempotency: applying twice equals applying once.
{"nymvitaiiki23", "nymvitaiiki23"},
// Empty input.
{"", ""},
}
for _, tc := range cases {
got := Canonicalize(tc.in)
uassert.Equal(t, tc.want, got)
}
}
func TestCanonicalize_NonASCIIPassthrough(cur realm, t *testing.T) {
// ASCII-only contract: the function passes non-ASCII bytes through
// unchanged. Locks the documented contract — registration paths
// reject non-ASCII upstream via validateName, so this code path is
// only reachable through direct callers from other realms.
uassert.Equal(t, "café", Canonicalize("café"))
uassert.Equal(t, "naïve", Canonicalize("naïve"))
}
func TestRegisterUser_CanonicalCollision(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("non_bypass_blocks", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
// Different exact name, same canonical form → ErrCanonicalCollision.
uassert.ErrorContains(t,
RegisterUser(cross(cur), "vital1k", bobAddr),
ErrCanonicalCollision.Error(),
)
})
t.Run("non_bypass_blocks_with_separator_strip", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "xyz-com", aliceAddr))
uassert.ErrorContains(t,
RegisterUser(cross(cur), "xyz_com", bobAddr),
ErrCanonicalCollision.Error(),
)
})
t.Run("non_bypass_allows_different_digit_suffix", func(t *testing.T) {
cleanStore(t)
// Same alpha stem, different digits-after-canonicalization → no collision.
urequire.NoError(t, RegisterUser(cross(cur), "nym-foolbar000", aliceAddr))
urequire.NoError(t, RegisterUser(cross(cur), "nym-foolbar999",
testutils.TestAddress("foolbar999")))
})
t.Run("exact_name_taken_takes_precedence", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
// Same exact name → ErrNameTaken (NOT ErrCanonicalCollision).
// The nameStore.Has check precedes the canonical check.
uassert.ErrorContains(t,
RegisterUser(cross(cur), "vitalik", bobAddr),
ErrNameTaken.Error(),
)
})
}
func TestRegisterUserIgnoreCanonical(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("bypass_succeeds_on_canonical_collision", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
// Bypass succeeds even though canonical collides.
urequire.NoError(t, RegisterUserIgnoreCanonical(cross(cur), "vital1k", bobAddr))
// Both names resolve.
res, _ := ResolveName("vitalik")
uassert.Equal(t, aliceAddr, res.Addr())
res, _ = ResolveName("vital1k")
uassert.Equal(t, bobAddr, res.Addr())
})
t.Run("bypass_later_wins_overwrite", func(t *testing.T) {
cleanStore(t)
// First registration writes canonical entry.
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
existing, taken := IsCanonicalTaken("vital1k")
urequire.True(t, taken)
uassert.Equal(t, "vitalik", existing)
// Bypass write overwrites the canonical entry (decision #14).
urequire.NoError(t, RegisterUserIgnoreCanonical(cross(cur), "vital1k", bobAddr))
existing, taken = IsCanonicalTaken("vitalik")
urequire.True(t, taken)
uassert.Equal(t, "vital1k", existing)
})
t.Run("bypass_still_blocks_exact_taken", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
// Same exact name still blocked, even via the bypass path.
uassert.ErrorContains(t,
RegisterUserIgnoreCanonical(cross(cur), "vitalik", bobAddr),
ErrNameTaken.Error(),
)
})
}
func TestUpdateName_CanonicalCollision(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("self_collision_blocks_per_decision_15", func(t *testing.T) {
cleanStore(t)
// Alice registers vital1k. Canonical store maps "vitaiik" → "vital1k".
urequire.NoError(t, RegisterUser(cross(cur), "vital1k", aliceAddr))
data := ResolveAddress(aliceAddr)
// Alice attempts to rename to a confusable variant of HER OWN name.
// Decision #15: blocked. No self-collision exception in the
// non-bypass path.
testing.SetOriginCaller(whitelistedCallerAddr)
uassert.ErrorContains(t,
data.UpdateName(0, cur, "vitalik"),
ErrCanonicalCollision.Error(),
)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
})
t.Run("different_user_collision_blocks", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
urequire.NoError(t, RegisterUser(cross(cur), "bob", bobAddr))
data := ResolveAddress(bobAddr)
testing.SetOriginCaller(whitelistedCallerAddr)
uassert.ErrorContains(t,
data.UpdateName(0, cur, "vital1k"),
ErrCanonicalCollision.Error(),
)
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
})
t.Run("bypass_allows_self_collision_rename", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vital1k", aliceAddr))
data := ResolveAddress(aliceAddr)
// Bypass path allows the rename (DAO grant scenario).
testing.SetOriginCaller(whitelistedCallerAddr)
urequire.NoError(t, data.UpdateNameIgnoreCanonical(0, cur, "vitalik"))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
// Both names point to alice; latest is "vitalik".
uassert.Equal(t, "vitalik", ResolveAddress(aliceAddr).Name())
// Old name still resolves to alice (decision #4: keep old entry).
res, isLatest := ResolveName("vital1k")
uassert.Equal(t, aliceAddr, res.Addr())
uassert.False(t, isLatest)
})
}
func TestCanonicalEntry_Persists_After_Delete(cur realm, t *testing.T) {
// Decision #5: Delete does NOT remove the canonical entry. Mirrors
// the existing tombstone behavior (anti-revival policy).
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
data := ResolveAddress(aliceAddr)
urequire.NoError(t, data.Delete(0, cur))
// Canonical entry retained.
existing, taken := IsCanonicalTaken("vitalik")
urequire.True(t, taken)
uassert.Equal(t, "vitalik", existing)
// A different user CANNOT register a confusable variant — the deleted
// user's canonical claim still stands.
uassert.ErrorContains(t,
RegisterUser(cross(cur), "vital1k", bobAddr),
ErrCanonicalCollision.Error(),
)
}
func TestCanonicalEntry_Persists_After_UpdateName(cur realm, t *testing.T) {
// Decision #4: UpdateName keeps the OLD canonical entry. Mirrors the
// existing nameStore alias retention (anti-rename-squat policy).
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "alice", aliceAddr))
data := ResolveAddress(aliceAddr)
testing.SetOriginCaller(whitelistedCallerAddr)
urequire.NoError(t, data.UpdateName(0, cur, "alice2"))
testing.SetRealm(testing.NewCodeRealm("gno.land/r/sys/users"))
// Both old and new canonical entries exist.
existing, taken := IsCanonicalTaken("alice")
urequire.True(t, taken)
uassert.Equal(t, "alice", existing)
existing, taken = IsCanonicalTaken("alice2")
urequire.True(t, taken)
uassert.Equal(t, "alice2", existing)
}
// cleanStore should not be needed, as vm store should be reset after each test.
// Reference: https://github.com/gnolang/gno/issues/1982
func cleanStore(t *testing.T) {
t.Helper()
nameStore = bptree.NewBPTree32()
addressStore = bptree.NewBPTree32()
canonicalStore = bptree.NewBPTree32()
}
users.gno
package users
import "gno.land/p/nt/bptree/rotree/v0"
// ResolveName returns the latest UserData of a specific user by name or alias
func ResolveName(name string) (data *UserData, isCurrent bool) {
raw := nameStore.Get(name)
if raw == nil {
return nil, false
}
data = raw.(*UserData)
if data.deleted {
return nil, false
}
return data, name == data.username
}
// ResolveAddress returns the latest UserData of a specific user by address
func ResolveAddress(addr address) *UserData {
raw := addressStore.Get(addr.String())
if raw == nil {
return nil
}
data := raw.(*UserData)
if data.deleted {
return nil
}
return data
}
// ResolveAny tries to resolve any given string to *UserData
// If the input is not found in the registry in any form, nil is returned
func ResolveAny(input string) (*UserData, bool) {
addr := address(input)
if addr.IsValid() {
return ResolveAddress(addr), true
}
return ResolveName(input)
}
// GetReadonlyAddrStore exposes the address store in readonly mode
func GetReadonlyAddrStore() *rotree.ReadOnlyTree {
return rotree.Wrap(addressStore, makeUserDataSafe)
}
// GetReadOnlyNameStore exposes the name store in readonly mode
func GetReadOnlyNameStore() *rotree.ReadOnlyTree {
return rotree.Wrap(nameStore, makeUserDataSafe)
}
func makeUserDataSafe(data any) any {
cpy := new(UserData)
*cpy = *(data.(*UserData))
if cpy.deleted {
return nil
}
// Note: when requesting data from this AVL tree, (exists bool) will be true
// Even if the data is "deleted". This is currently unavoidable
return cpy
}
users_test.gno
package users
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
// 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 TestResolveName(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("single_name", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
res, isLatest := ResolveName(alice)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, alice, res.Name())
uassert.True(t, isLatest)
})
t.Run("name+Alias", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data, _ := ResolveName(alice)
urequire.NoError(t, data.UpdateName(0, cur, "alice1"))
res, isLatest := ResolveName("alice1")
urequire.NotEqual(t, nil, res)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, "alice1", res.Name())
uassert.True(t, isLatest)
})
t.Run("multiple_aliases", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
// RegisterUser and check each Alias
var names []string
names = append(names, alice)
for i := 0; i < 5; i++ {
alias := "alice" + strconv.Itoa(i)
names = append(names, alias)
data, _ := ResolveName(alice)
urequire.NoError(t, data.UpdateName(0, cur, alias))
}
for _, alias := range names {
res, _ := ResolveName(alias)
urequire.NotEqual(t, nil, res)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, "alice4", res.Name())
}
})
}
func TestResolveAddress(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("single_name", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
res := ResolveAddress(aliceAddr)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, alice, res.Name())
})
t.Run("name+Alias", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
data, _ := ResolveName(alice)
urequire.NoError(t, data.UpdateName(0, cur, "alice1"))
res := ResolveAddress(aliceAddr)
urequire.NotEqual(t, nil, res)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, "alice1", res.Name())
})
t.Run("multiple_aliases", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
// RegisterUser and check each Alias
var names []string
names = append(names, alice)
for i := 0; i < 5; i++ {
alias := "alice" + strconv.Itoa(i)
names = append(names, alias)
data, _ := ResolveName(alice)
urequire.NoError(t, data.UpdateName(0, cur, alias))
}
res := ResolveAddress(aliceAddr)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, "alice4", res.Name())
})
}
func TestROStores(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
roNS := GetReadOnlyNameStore()
roAS := GetReadonlyAddrStore()
t.Run("get user data", func(t *testing.T) {
// Name store
aliceDataRaw := roNS.Get(alice)
urequire.NotNil(t, aliceDataRaw)
roData, ok := aliceDataRaw.(*UserData)
uassert.True(t, ok, "Could not cast data from RO tree to UserData")
// Try to modify data
roData.Delete(0, cur)
raw := nameStore.Get(alice)
uassert.False(t, raw.(*UserData).deleted)
// Addr store
aliceDataRaw = roAS.Get(aliceAddr.String())
urequire.NotNil(t, aliceDataRaw)
roData, ok = aliceDataRaw.(*UserData)
uassert.True(t, ok, "Could not cast data from RO tree to UserData")
// Try to modify data
roData.Delete(0, cur)
raw = nameStore.Get(alice)
uassert.False(t, raw.(*UserData).deleted)
})
t.Run("get deleted data", func(t *testing.T) {
raw := nameStore.Get(alice)
aliceData := raw.(*UserData)
urequire.NoError(t, aliceData.Delete(0, cur))
urequire.True(t, aliceData.IsDeleted())
// Should be nil because of makeSafeFn intercepting the value.
rawRoData := roNS.Get(alice)
uassert.Equal(t, rawRoData, nil)
_, ok := rawRoData.(*UserData) // shouldn't be castable
uassert.False(t, ok)
})
}
func TestResolveAny(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("name", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
res, _ := ResolveAny(alice)
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, alice, res.Name())
})
t.Run("address", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), alice, aliceAddr))
res, _ := ResolveAny(aliceAddr.String())
uassert.Equal(t, aliceAddr, res.Addr())
uassert.Equal(t, alice, res.Name())
})
t.Run("not_registered", func(t *testing.T) {
cleanStore(t)
res, _ := ResolveAny(aliceAddr.String())
uassert.Equal(t, nil, res)
})
}
func TestProposeErrors(cur realm, t *testing.T) {
t.Run("propose_register_user_errors", func(t *testing.T) {
urequire.PanicsWithMessage(t, cur, ErrInvalidUsername.Error(), func() {
ProposeRegisterUser(cur, "bad name", aliceAddr)
})
urequire.PanicsWithMessage(t, cur, ErrInvalidAddress.Error(), func() {
ProposeRegisterUser(cur, alice, "badaddress")
})
})
t.Run("propose_update_name_errors", func(t *testing.T) {
cleanStore(t)
urequire.PanicsWithMessage(t, cur, ErrInvalidAddress.Error(), func() {
ProposeUpdateName(cur, "badaddress", "alice1")
})
urequire.PanicsWithMessage(t, cur, ErrInvalidUsername.Error(), func() {
ProposeUpdateName(cur, aliceAddr, "bad name")
})
// Note: unregistered user is not checked at proposal creation time.
// The callback handles it at execution time.
})
t.Run("propose_delete_user_errors", func(t *testing.T) {
cleanStore(t)
urequire.PanicsWithMessage(t, cur, ErrInvalidAddress.Error(), func() {
ProposeDeleteUser(cur, "badaddress")
})
// Note: unregistered user is not checked at proposal creation time.
// The callback handles it at execution time.
})
}
// Audit finding #6: ProposeControllerAdditionAndRemoval used to return early
// from its callback when toAdd was already whitelisted (addToWhitelist
// returned ErrAlreadyWhitelisted), skipping the remove step entirely. A
// passed swap proposal would silently leave the old controller active.
//
// applyControllerSwap is the extracted callback body. These tests exercise
// it directly to confirm:
// - normal swap (toAdd new, toRemove present) succeeds and updates state
// - toAdd already present is benign — remove still happens
// - toRemove already absent is benign — add still happens, no error
// - errors that aren't the idempotency cases still propagate
func TestApplyControllerSwap(t *testing.T) {
// Use unique addresses per subtest to avoid having to drain the
// controllers set (addrset.Set has no clear/iterate-all method, and
// state persists across subtests in this package's tests).
t.Run("normal swap A->B", func(t *testing.T) {
a := testutils.TestAddress("swapA1")
b := testutils.TestAddress("swapB1")
controllers.Add(a)
defer controllers.Remove(b)
uassert.NoError(t, applyControllerSwap(b, a))
uassert.True(t, controllers.Has(b), "b should be whitelisted")
uassert.False(t, controllers.Has(a), "a should be removed")
})
t.Run("toAdd already whitelisted, toRemove present", func(t *testing.T) {
// Regression for audit finding #6. Before the fix, this returned
// ErrAlreadyWhitelisted from the swap callback, skipping the remove
// step entirely — the swap silently no-op'd and the old controller
// stayed active.
a := testutils.TestAddress("swapA2")
b := testutils.TestAddress("swapB2")
controllers.Add(a)
controllers.Add(b)
defer controllers.Remove(b)
uassert.NoError(t, applyControllerSwap(b, a))
uassert.True(t, controllers.Has(b), "b should remain whitelisted")
uassert.False(t, controllers.Has(a), "a should be removed even though b was already in")
})
t.Run("toRemove already absent, toAdd new", func(t *testing.T) {
a := testutils.TestAddress("swapA3")
b := testutils.TestAddress("swapB3")
c := testutils.TestAddress("swapC3") // never added
controllers.Add(a)
defer controllers.Remove(a)
defer controllers.Remove(b)
// Remove c which isn't in the set; should be benign.
uassert.NoError(t, applyControllerSwap(b, c))
uassert.True(t, controllers.Has(b), "b should be whitelisted")
uassert.True(t, controllers.Has(a), "a should still be whitelisted (unchanged)")
uassert.False(t, controllers.Has(c), "c was never in the set")
})
t.Run("both idempotency cases at once", func(t *testing.T) {
// toAdd already in, toRemove already out — should succeed cleanly,
// no state change.
a := testutils.TestAddress("swapA4")
b := testutils.TestAddress("swapB4")
c := testutils.TestAddress("swapC4")
controllers.Add(a)
controllers.Add(b)
defer controllers.Remove(a)
defer controllers.Remove(b)
uassert.NoError(t, applyControllerSwap(b, c))
uassert.True(t, controllers.Has(a))
uassert.True(t, controllers.Has(b))
uassert.False(t, controllers.Has(c))
})
}
// Audit finding #20: the controller whitelist must be queryable from
// outside the package so operators can monitor authority without
// source-diving or replaying governance proposals.
func TestControllerQueries(t *testing.T) {
t.Run("IsController reflects whitelist state", func(t *testing.T) {
a := testutils.TestAddress("queryA1")
b := testutils.TestAddress("queryB1")
// Before any add: both report false.
uassert.False(t, IsController(a))
uassert.False(t, IsController(b))
controllers.Add(a)
defer controllers.Remove(a)
uassert.True(t, IsController(a))
uassert.False(t, IsController(b))
})
t.Run("Controllers returns a snapshot of current whitelist", func(t *testing.T) {
// Use distinct addresses that aren't already in the set from
// other tests in this file.
a := testutils.TestAddress("queryA2")
b := testutils.TestAddress("queryB2")
c := testutils.TestAddress("queryC2")
controllers.Add(a)
controllers.Add(b)
controllers.Add(c)
defer controllers.Remove(a)
defer controllers.Remove(b)
defer controllers.Remove(c)
got := Controllers()
// All three must appear (regardless of order vs other tests'
// leftover entries — we only assert ours are present).
seen := map[string]bool{}
for _, e := range got {
seen[e.String()] = true
}
uassert.True(t, seen[a.String()], "snapshot must contain a")
uassert.True(t, seen[b.String()], "snapshot must contain b")
uassert.True(t, seen[c.String()], "snapshot must contain c")
})
t.Run("Controllers returns a copy — caller mutation does not affect realm", func(t *testing.T) {
a := testutils.TestAddress("queryA3")
controllers.Add(a)
defer controllers.Remove(a)
got := Controllers()
// Mutate the returned slice. The realm's controllers set must not
// be affected.
got = got[:0]
uassert.True(t, controllers.Has(a), "realm state must be unaffected by caller-side slice mutation")
uassert.True(t, IsController(a))
})
}
// ProposeRegisterUser auto-injects a CANONICAL COLLISION warning into
// the proposal description when the proposed name canonical-collides
// with an existing registration. The warning surfaces the colliding
// existing name to voters; the proposal still goes through if voted in
// (decision #3, DAO grants always bypass).
func TestProposeRegisterUser_CollisionWarning(cur realm, t *testing.T) {
testing.SetRealm(testing.NewCodeRealm(initControllerPath))
t.Run("warning_injected_on_collision", func(t *testing.T) {
cleanStore(t)
urequire.NoError(t, RegisterUser(cross(cur), "vitalik", aliceAddr))
req := ProposeRegisterUser(cur, "vital1k", bobAddr)
uassert.True(t,
strings.Contains(req.Description(), "CANONICAL COLLISION"),
"description must include collision warning")
uassert.True(t,
strings.Contains(req.Description(), "`vitalik`"),
"description must name the existing colliding registration")
})
t.Run("no_warning_when_no_collision", func(t *testing.T) {
cleanStore(t)
req := ProposeRegisterUser(cur, "freshname", aliceAddr)
uassert.False(t,
strings.Contains(req.Description(), "CANONICAL COLLISION"),
"description must not include collision warning when name is fresh")
})
}
// Note: full execution of ProposeRegisterUser/ProposeUpdateName closures
// (with ignoreCanonical=true → later-wins overwrite) is exercised end-to-
// end by the integration test in gno.land/pkg/integration/testdata/.
// The bypass-write semantics themselves are covered here at the unit
// level by TestRegisterUserIgnoreCanonical and TestUpdateName_CanonicalCollision.
// TODO Uncomment after gnoweb /u/ page.
//func TestUserRenderLink(cur realm, t *testing.T) {
// testing.SetOriginCaller(whitelistedCallerAddr)
// cleanStore(t)
//
// urequire.NoError(t, RegisterUser(alice, aliceAddr))
//
// data, _ := ResolveName(alice)
// uassert.Equal(t, data.RenderLink(""), ufmt.Sprintf("[@%s](/u/%s)", alice, alice))
// text := "my link text!"
// uassert.Equal(t, data.RenderLink(text), ufmt.Sprintf("[%s](/u/%s)", text, alice))
//}