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

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

Playground

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox/usernames"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914308
  max_deposit = "11000000ugnot"

render.gno

package usernames

import (
	"strings"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
	tb "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/toolbox/v0"
	"gno.land/r/sys/users"
)

// hubURL is the toolbox this tool belongs to. A private realm cannot import
// the hub, so the link is a constant on this side; `r/moul/toolbox` holds the
// authoritative copy and its tests check that the tool path matches.
const hubURL = "/r/moul/toolbox"

// maxInput bounds what is echoed back into the page. A render that reflects an
// unbounded query parameter is a page anyone can make arbitrarily large.
const maxInput = 64

// Render routes gnoweb paths:
//
//	/                the form, and what the tool answers
//	/lookup?q=moul   the result, which is where the form submits
//	/moul            the same result, addressable directly
//	/g1manfred...    the same, by address
func Render(path string) string {
	req := realmpath.Parse(path)
	parts := req.PathParts()

	input := req.Query.Get("q")
	if input == "" && len(parts) == 1 && parts[0] != "" && parts[0] != "lookup" {
		input = parts[0]
	}
	if len(parts) > 1 {
		return header() + "\n" + notFound(strings.Join(parts, "/"))
	}
	if input == "" {
		return header() + "\n" + renderHome()
	}
	return header() + "\n" + renderResult(input)
}

func header() string {
	return tb.Nav(hubURL, "Usernames")
}

func renderHome() string {
	var b strings.Builder
	b.WriteString(md.H1("Usernames"))
	b.WriteString("\nWho holds a name, and what name an address holds. Type either one.\n")
	b.WriteString("\n" + form())
	b.WriteString("\n" + md.H2("What this answers"))
	b.WriteString("\n" + md.BulletList([]string{
		"The address behind a username, and the username behind an address.",
		"Whether the name you typed is their **current** name or one they renamed away from.",
		"The canonical key the name collapses to, and who already holds that key.",
	}))
	b.WriteString("\n" + md.H2("The same thing from a terminal"))
	b.WriteString("\nThis page is " + md.InlineCode("r/sys/users") +
		" read through " + md.InlineCode("vm/qeval") + ", with the follow-up questions already asked:\n")
	b.WriteString("\n" + md.LanguageCodeBlock("sh", qevalCommand("moul")))
	b.WriteString("\nTry " + md.Link("moul", "/r/moul/toolbox/usernames:moul") +
		", or paste an address into the box above.\n")
	return b.String()
}

func renderResult(input string) string {
	var b strings.Builder
	b.WriteString(md.H1("Usernames"))
	b.WriteString("\n" + form())

	data := lookup(input)
	if data == nil {
		b.WriteString("\n" + notFound(input))
		return b.String()
	}

	t := ui.NewTable("Field", "Value")
	// RenderLink builds `[@name](/u/name)` with no escaping of its own, which
	// is safe only because r/sys/users validates a name against
	// ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ before storing it: no pipe, no bracket,
	// nothing a table cell or a link would notice.
	t.Row("Username", data.RenderLink(""))
	t.Row("Address", ui.AddrFull(data.Addr()))
	if current := CurrentName(input); current != "" {
		// One ui.Cell over the whole sentence, not a code span per name: a
		// code span escapes for running prose and leaves the `|` that would
		// split the row, and wrapping an already-escaped string again is the
		// double-wrap sanitize refuses to be idempotent about.
		t.Row("Note", ui.Cell("You asked for "+trim(input)+
			", which is an earlier name. The current one is "+current+"."))
	}
	t.Row("Canonical", ui.Cell(users.Canonicalize(data.Name())))
	b.WriteString("\n" + t.String())

	if cmd := qevalCommand(input); cmd != "" {
		b.WriteString("\n" + md.LanguageCodeBlock("sh", cmd))
	}
	return b.String()
}

func notFound(input string) string {
	var b strings.Builder
	b.WriteString("Nothing registered under " + md.InlineCode(trim(input)) + ".\n")
	b.WriteString("\n" + md.BulletList(notFoundHints(input)))
	return b.String()
}

// notFoundHints says what "not found" means for this particular input, which
// is three different things.
func notFoundHints(input string) []string {
	trimmed := trim(input)
	if address(trimmed).IsValid() {
		return []string{
			"That is a valid address, so it exists on chain. It has no username.",
			"Register one at " + md.Link("r/gnoland/users", "/r/gnoland/users"),
		}
	}
	hints := []string{
		"Nobody holds it, or the account was deleted: a deleted name keeps its tombstone and resolves to nothing.",
	}
	if owner := CanonicalOwner(trimmed); owner != "" {
		hints = append(hints, "A lookalike is taken: "+md.InlineCode(owner)+
			" already holds the canonical key "+md.InlineCode(users.Canonicalize(trimmed))+".")
	} else if Taken(trimmed) {
		hints = append(hints, "The name IS taken, by an account that was deleted or renamed. Registering it would still fail.")
	}
	return hints
}

func form() string {
	return tb.NewQuery("lookup").Field("q", "username or g1 address").String()
}

// qevalCommand is the CLI call this page is the equivalent of, with the input
// substituted. It returns "" for an input that cannot be put inside a fenced
// code block safely: nothing escapes inside a fence, so the only safe move is
// not to print one.
func qevalCommand(input string) string {
	arg := trim(input)
	if !safeArg(arg) {
		return ""
	}
	return "gnokey query vm/qeval -remote https://rpc.gno.land \\\n" +
		"  -data 'gno.land/r/moul/toolbox/usernames.Resolve(\"" + arg + "\")'"
}

// safeArg reports whether s can be interpolated into a shell single-quoted
// string inside a markdown code fence. Usernames and addresses are both well
// inside this set, so a refusal only ever hides the hint, never an answer.
func safeArg(s string) bool {
	if s == "" || len(s) > maxInput {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c >= 'a' && c <= 'z':
		case c >= 'A' && c <= 'Z':
		case c >= '0' && c <= '9':
		case c == '_' || c == '-' || c == '.':
		default:
			return false
		}
	}
	return true
}

// trim bounds an echoed input. Everything downstream escapes it; this only
// stops one query from rendering a page of arbitrary size.
//
// Cut on a rune boundary, not a byte one: s[:maxInput] on a multi-byte
// character leaves half of it, and half a rune is not a character the escapers
// downstream can do anything sensible with. Counting runes also makes the cap
// mean the same thing for every alphabet.
func trim(s string) string {
	n := 0
	for i := range s {
		if n == maxInput {
			return s[:i] + "…"
		}
		n++
	}
	return s
}

render_example_test.gno

package usernames

// ExampleRender pins the tool's landing page.
//
// The landing page only, deliberately: a result page reads r/sys/users, whose
// state is whatever the tests in this package left behind, and an example runs
// after all of them. The results are asserted in render_test.gno instead.
func ExampleRender() {
	print(Render(""))
	// Output:
	// [toolbox](/r/moul/toolbox) / **Usernames**
	//
	// # Usernames
	//
	// Who holds a name, and what name an address holds. Type either one.
	//
	// <gno-form path="lookup">
	// <gno-input name="q" type="text" placeholder="username or g1 address" />
	// </gno-form>
	//
	// ## What this answers
	//
	// - The address behind a username, and the username behind an address.
	// - Whether the name you typed is their **current** name or one they renamed away from.
	// - The canonical key the name collapses to, and who already holds that key.
	//
	// ## The same thing from a terminal
	//
	// This page is `r/sys/users` read through `vm/qeval`, with the follow-up questions already asked:
	//
	// ```sh
	// gnokey query vm/qeval -remote https://rpc.gno.land \
	//   -data 'gno.land/r/moul/toolbox/usernames.Resolve("moul")'
	// ```
	//
	// Try [moul](/r/moul/toolbox/usernames:moul), or paste an address into the box above.
}

render_test.gno

package usernames

import (
	"strings"
	"testing"

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

func TestRenderHome(cur realm, t *testing.T) {
	seed(cur, t)

	got := Render("")
	uassert.True(t, strings.Contains(got, "[toolbox](/r/moul/toolbox)"))
	uassert.True(t, strings.Contains(got, "# Usernames"))
	uassert.True(t, strings.Contains(got, `<gno-form path="lookup">`))
	uassert.True(t, strings.Contains(got, `<gno-input name="q"`))
	uassert.True(t, strings.Contains(got, "gnokey query vm/qeval"))
}

func TestRenderResultByPathAndByQuery(cur realm, t *testing.T) {
	seed(cur, t)

	byPath := Render("moul")
	byQuery := Render("lookup?q=moul")
	uassert.Equal(t, byPath, byQuery)
	uassert.True(t, strings.Contains(byPath, "[@moul](/u/moul)"))
	uassert.True(t, strings.Contains(byPath, moulAddr.String()))
	uassert.True(t, strings.Contains(byPath, "Canonical"))
}

func TestRenderResultByAddress(cur realm, t *testing.T) {
	seed(cur, t)

	got := Render(moulAddr.String())
	uassert.True(t, strings.Contains(got, "[@moul](/u/moul)"))
}

func TestRenderNotFound(cur realm, t *testing.T) {
	seed(cur, t)

	got := Render("nobodyholdsthis")
	uassert.True(t, strings.Contains(got, "Nothing registered under"))
	uassert.True(t, strings.Contains(got, "deleted"))

	addr := Render(plainAddr.String())
	uassert.True(t, strings.Contains(addr, "That is a valid address"))
	uassert.True(t, strings.Contains(addr, "/r/gnoland/users"))
}

func TestRenderTooManyParts(cur realm, t *testing.T) {
	seed(cur, t)

	got := Render("a/b")
	uassert.True(t, strings.Contains(got, "Nothing registered under"))
}

// TestRenderEscapesInput: the query parameter is attacker-chosen and a live
// realm can never be fixed, so this is the test that must be seen to fail
// before it is believed.
//
// The property is that the echo is INERT, not that particular bytes are
// absent. A code span makes link syntax inert without removing it, so an
// assertion that the substring is gone would pass for the wrong reason under
// one escaper and fail for the wrong reason under the other.
func TestRenderEscapesInput(cur realm, t *testing.T) {
	seed(cur, t)

	const link = "[x](javascript:alert(1))"
	got := Render("lookup?q=" + "%5Bx%5D%28javascript%3Aalert%281%29%29")
	uassert.True(t, strings.Contains(got, "`"+link+"`"))
	uassert.False(t, strings.Contains(got, " "+link+" "))

	// A backtick in the input cannot close the span early: the fence widens.
	tick := Render("lookup?q=a%60b")
	uassert.True(t, strings.Contains(tick, "``"))
	uassert.False(t, strings.Contains(tick, "under `a`b`."))

	// A heading marker cannot open a block of its own: the echo stays on the
	// line it was put on.
	head := Render("lookup?q=%0A%23%20pwned")
	uassert.False(t, strings.Contains(head, "\n# pwned"))
}

// TestRenderOmitsTheCommandForUnsafeInput: nothing escapes inside a fenced
// code block, so an input that cannot go in one does not get one.
func TestRenderOmitsTheCommandForUnsafeInput(cur realm, t *testing.T) {
	seed(cur, t)

	uassert.True(t, strings.Contains(Render("moul"), "gnokey query vm/qeval"))
	uassert.False(t, strings.Contains(Render("lookup?q=a%60b"), "gnokey query vm/qeval"))
}

func TestRenderNeverEmitsTwoBlankLines(cur realm, t *testing.T) {
	seed(cur, t)

	for _, path := range []string{"", "moul", "nobodyholdsthis", moulAddr.String(), "a/b"} {
		uassert.False(t, strings.Contains(Render(path), "\n\n\n"))
	}
}

usernames.gno

// Package usernames is the toolbox tool for gno.land identities: it turns a
// username into an address, an address into a username, and tells you which
// of the two you are actually holding.
//
// It is the page form of
//
//	gnokey query vm/qeval --data 'gno.land/r/sys/users.ResolveName("akkadia")' -remote https://rpc.gno.land
//
// with the three things that query does not tell you: whether the name you
// asked about is the user's CURRENT name or an alias they renamed away from,
// what canonical key it collapses to, and whether a lookalike of it is already
// taken.
//
// # Why not r/sys/users.ResolveAny
//
// `ResolveAny` returns `(*UserData, bool)` and the bool does not mean "found".
// For an input that parses as an address it returns `(ResolveAddress(addr),
// true)` whatever the lookup produced, so an unregistered address comes back
// as `(nil, true)`. Every caller that reads the bool and dereferences the
// pointer panics on the first address nobody claimed. [lookup] branches on the
// input itself and checks the pointer instead.
//
// Part of [r/moul/toolbox](/r/moul/toolbox).
package usernames

import "gno.land/r/sys/users"

// lookup resolves any input to a user record, or nil.
//
// An input that parses as a gno.land address is only ever looked up as an
// address, and anything else only as a name: a bech32 address is not a legal
// username, so trying both would only widen what a typo can hit.
func lookup(input string) *users.UserData {
	if input == "" {
		return nil
	}
	if addr := address(input); addr.IsValid() {
		return users.ResolveAddress(addr)
	}
	data, _ := users.ResolveName(input)
	return data
}

// Resolve returns the current username and the address behind any input, a
// username or a `g1` address.
//
// found is false when nobody holds it, which is also the answer for a deleted
// user: `r/sys/users` keeps the tombstone and resolves it to nothing.
//
//	gnokey query vm/qeval -data 'gno.land/r/moul/toolbox/usernames.Resolve("moul")'
func Resolve(input string) (name string, addr string, found bool) {
	data := lookup(input)
	if data == nil {
		return "", "", false
	}
	return data.Name(), data.Addr().String(), true
}

// AddressOf returns the address behind a username or an address, or "" when
// nobody holds it.
//
// It is the call another realm would want, and the one it cannot have: this
// realm is `private = true`, so nothing can import it. Over `vm/qeval` it is
// the whole point.
//
//	gnokey query vm/qeval -data 'gno.land/r/moul/toolbox/usernames.AddressOf("moul")'
func AddressOf(input string) string {
	_, addr, found := Resolve(input)
	if !found {
		return ""
	}
	return addr
}

// NameOf returns the current username behind a username or an address, or ""
// when nobody holds it.
func NameOf(input string) string {
	name, _, found := Resolve(input)
	if !found {
		return ""
	}
	return name
}

// Display returns what a page should print for an input: "@name" when there is
// a username, and the input unchanged when there is not.
//
// So it is total over every input a page actually has, and a caller never has
// to branch on "not found" the way [NameOf] makes it. The one input it has
// nothing to say about is "", which it returns unchanged: an empty answer to an
// empty question, rather than a placeholder a page would then have to special
// case anyway.
func Display(input string) string {
	if name := NameOf(input); name != "" {
		return "@" + name
	}
	return input
}

// CurrentName reports the user's current name when input is an alias they
// renamed away from, and "" otherwise.
//
// `r/sys/users` keeps old names resolving on purpose, so an address looked up
// by a name that is no longer current is not an error and nothing in the
// resolve result says so. This is the one call that does.
func CurrentName(input string) string {
	if input == "" {
		return ""
	}
	if addr := address(input); addr.IsValid() {
		return ""
	}
	data, isCurrent := users.ResolveName(input)
	if data == nil || isCurrent {
		return ""
	}
	return data.Name()
}

// Canonical returns the canonical key a name collapses to. Two names with the
// same canonical form cannot both be registered, which is how `r/sys/users`
// refuses a lookalike of an existing account.
//
//	gnokey query vm/qeval -data 'gno.land/r/moul/toolbox/usernames.Canonical("M0ul")'
func Canonical(name string) string { return users.Canonicalize(name) }

// Taken reports whether the exact name is registered, including names that
// were deleted or renamed away from: it answers "would registering this
// fail", not "is somebody using this".
func Taken(name string) bool {
	if name == "" {
		return false
	}
	return users.IsNameTaken(name)
}

// CanonicalOwner returns the name that already holds this name's canonical
// key, or "" when the key is free. A non-empty answer that is not the name
// itself is a lookalike collision.
func CanonicalOwner(name string) string {
	if name == "" {
		return ""
	}
	existing, taken := users.IsCanonicalTaken(name)
	if !taken {
		return ""
	}
	return existing
}

usernames_test.gno

package usernames

import (
	"strings"
	"testing"
	"unicode/utf8"

	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
	"gno.land/r/sys/users"
)

const (
	moulAddr  = address("g1manfred47kzduec920z88wfr64ylksmdcedlf5")
	plainAddr = address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5")
)

// controllerPath is the realm r/sys/users whitelists in its own init when the
// chain id is "dev", which is what `gno test` runs as. Registering a fixture
// means borrowing that identity: this package is not a controller and
// AddControllerAtGenesis cannot be reached from here, since its `_ realm`
// first parameter is the non-crossing threaded form and an external realm
// refuses a cur-call to one.
const controllerPath = "gno.land/r/sys/users/init"

// seed registers the fixtures every test in this file reads.
//
// The SetRealm is immediately followed by a crossing call, which is the only
// shape that works: in a helper that does not itself cross, the switch is
// silently dropped and the caller stays whoever it was.
func seed(cur realm, t *testing.T) {
	t.Helper()
	if users.IsNameTaken("moul") {
		return
	}
	testing.SetRealm(testing.NewCodeRealm(controllerPath))
	urequire.NoError(t, users.RegisterUser(cross(cur), "moul", moulAddr))
}

func TestResolveByName(cur realm, t *testing.T) {
	seed(cur, t)

	name, addr, found := Resolve("moul")
	uassert.True(t, found)
	uassert.Equal(t, "moul", name)
	uassert.Equal(t, moulAddr.String(), addr)
}

func TestResolveByAddress(cur realm, t *testing.T) {
	seed(cur, t)

	name, addr, found := Resolve(moulAddr.String())
	uassert.True(t, found)
	uassert.Equal(t, "moul", name)
	uassert.Equal(t, moulAddr.String(), addr)
}

func TestResolveMisses(cur realm, t *testing.T) {
	seed(cur, t)

	cases := []struct {
		name  string
		input string
	}{
		{"empty", ""},
		{"unknown name", "nobodyholdsthis"},
		{"valid address with no name", plainAddr.String()},
		{"not an address and not a name", "g1notanaddress"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			_, _, found := Resolve(tc.input)
			uassert.False(t, found)
		})
	}
}

// TestResolveAnyTrap is the defect this tool exists not to repeat: for an
// input that parses as an address, r/sys/users.ResolveAny reports true
// whatever the lookup produced, so the pointer it returns can be nil. Pinned
// against the vendored copy so a later upstream fix is visible here.
func TestResolveAnyTrap(cur realm, t *testing.T) {
	seed(cur, t)

	data, ok := users.ResolveAny(plainAddr.String())
	uassert.True(t, ok)
	uassert.True(t, data == nil)

	_, _, found := Resolve(plainAddr.String())
	uassert.False(t, found)
}

func TestAccessors(cur realm, t *testing.T) {
	seed(cur, t)

	uassert.Equal(t, moulAddr.String(), AddressOf("moul"))
	uassert.Equal(t, "moul", NameOf(moulAddr.String()))
	uassert.Equal(t, "@moul", Display("moul"))
	uassert.Equal(t, "@moul", Display(moulAddr.String()))

	uassert.Equal(t, "", AddressOf("nobodyholdsthis"))
	uassert.Equal(t, "", NameOf("nobodyholdsthis"))
	uassert.Equal(t, "nobodyholdsthis", Display("nobodyholdsthis"))
}

func TestCanonicalAndTaken(cur realm, t *testing.T) {
	seed(cur, t)

	uassert.Equal(t, users.Canonicalize("moul"), Canonical("moul"))
	uassert.True(t, Taken("moul"))
	uassert.False(t, Taken("nobodyholdsthis"))
	uassert.False(t, Taken(""))

	uassert.Equal(t, "moul", CanonicalOwner("moul"))
	uassert.Equal(t, "", CanonicalOwner("nobodyholdsthis"))
	uassert.Equal(t, "", CanonicalOwner(""))
}

// TestCurrentNameOnAlias: r/sys/users keeps an old name resolving after a
// rename and nothing in the resolve result says it is old. CurrentName is the
// only call that does.
func TestCurrentNameOnAlias(cur realm, t *testing.T) {
	seed(cur, t)

	const old = "aliasfixture"
	const now = "renamedfixture"

	if !users.IsNameTaken(old) {
		testing.SetRealm(testing.NewCodeRealm(controllerPath))
		urequire.NoError(t, users.RegisterUser(cross(cur), old, plainAddr))
	}

	data := users.ResolveAddress(plainAddr)
	urequire.True(t, data != nil)
	if data.Name() == old {
		testing.SetRealm(testing.NewCodeRealm(controllerPath))
		urequire.NoError(t, data.UpdateName(0, cur, now))
	}

	uassert.Equal(t, now, CurrentName(old))
	uassert.Equal(t, "", CurrentName(now))
	uassert.Equal(t, "", CurrentName(plainAddr.String()))
	uassert.Equal(t, "", CurrentName("nobodyholdsthis"))
	uassert.Equal(t, "", CurrentName(""))

	// The old name still resolves, to the current one.
	name, _, found := Resolve(old)
	uassert.True(t, found)
	uassert.Equal(t, now, name)
}

func TestSafeArg(t *testing.T) {
	cases := []struct {
		name string
		in   string
		want bool
	}{
		{"username", "moul", true},
		{"address", "g1manfred47kzduec920z88wfr64ylksmdcedlf5", true},
		{"dashes and dots", "a-b.c_d", true},
		{"empty", "", false},
		{"quote", "a'b", false},
		{"backtick", "a`b", false},
		{"fence", "```", false},
		{"dollar", "$(id)", false},
		{"too long", strings.Repeat("a", maxInput+1), false},
		{"exactly max", strings.Repeat("a", maxInput), true},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			uassert.Equal(t, tc.want, safeArg(tc.in))
		})
	}
}

func TestTrim(t *testing.T) {
	uassert.Equal(t, "moul", trim("moul"))
	long := strings.Repeat("a", maxInput+10)
	uassert.Equal(t, strings.Repeat("a", maxInput)+"…", trim(long))
}

// TestTrimCutsOnARuneBoundary: a byte cut at maxInput lands inside the
// multi-byte character here and leaves half of it, which no escaper
// downstream can do anything sensible with.
func TestTrimCutsOnARuneBoundary(t *testing.T) {
	in := strings.Repeat("a", maxInput-1) + "é" + "tail"
	got := trim(in)
	uassert.Equal(t, strings.Repeat("a", maxInput-1)+"é"+"…", got)
	uassert.True(t, utf8.ValidString(got))

	// And the cap counts characters, not bytes, so an all-multibyte input
	// keeps maxInput of them rather than half as many.
	accents := strings.Repeat("é", maxInput+5)
	uassert.Equal(t, strings.Repeat("é", maxInput)+"…", trim(accents))
}

// TestDisplayOnEmpty pins the one input Display has nothing to say about.
func TestDisplayOnEmpty(t *testing.T) {
	uassert.Equal(t, "", Display(""))
}