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/p/nym-moultest123/zones/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186412
  max_deposit = "78000000ugnot"

registry.gno

package zones

import (
	"crypto/sha256"
	"errors"
	"strconv"

	"gno.land/p/nym-moultest123/kit/index/v0"
	"gno.land/p/nym-moultest123/kit/store/v0"
	"gno.land/p/nt/bptree/v0"
)

// Bounds on what the registry holds.
//
// The LIVE registry, pending and approved zones, has a hard cap. Rejected and
// retired zones are kept for the record but do not count against it: each has
// a cap of its own, and when it is reached the zone that has been in that state
// longest is dropped to make room (by when it entered the state, not when it
// was proposed, so a long-lived network retired today is not the next to go).
// So nothing a proposer or a curator does, and no amount of time, can fill the
// registry for good: a cap that only ever fills is a lifetime cap, and on an
// immutable path that is a brick.
//
// The per-address caps make one address cheap to ignore. Neither stops a flood
// from many addresses, because an address is not an identity, so admission to
// the review queue has a gate of its own (MaxPending zones, MaxUnverifiedPerZone
// endpoints awaiting a verdict), well under the hard caps: a flood fills the
// queue and never crowds out an approved zone or a verified endpoint. A
// flagged endpoint has its verdict and leaves the queue, so curators keep a
// warning instead of having to delete it to make room. The gate is checked
// where something enters (Propose, Register); a review or a reset can push a
// count past it, and never fails for it. ProposeExempt and RegisterExempt skip
// it, and the per-address caps, for the reviewers a holder trusts: a full
// queue must not lock out the people who clear it. The queue clears through
// approval, verification, a flag, rejection, RemoveZone, RemoveEndpoint, an
// edit leaving the local kind, and eviction. Flagged endpoints still count
// toward MaxEndpointsPerZone: a flood a curator flags rather than removes can
// fill the places a gated registration may use (all but the last
// ReservedForReviewers), and removing it is the answer. Each entry costs its sender a
// storage deposit, refunded to whoever signs the transaction that
// frees it (on a chain where ugnot is not transfer-locked; on one that is, the
// refund goes to the storage fee collector), so a flooder who withdraws first
// gets it back: a bond, not a fee.
const (
	MaxZones               = 256 // pending and approved zones together
	MaxPending             = 64  // zones awaiting review, all proposers together
	MaxPendingPerProposer  = 4   // open proposals one address may have at once
	MaxRejected            = 64  // rejected zones kept for the record
	MaxRetired             = 128 // retired zones kept for the record
	MaxEndpointsPerZone    = 128
	MaxUnverifiedPerZone   = 64 // endpoints on one zone still waiting for a verdict (flagged ones have theirs)
	MaxEndpointsPerAddress = 16 // endpoints one address may register on one zone
	// MaxDropPerEdit bounds how many endpoints one edit off the local kind
	// drops, and so its gas: a removal rewrites up to about 45 later values in
	// two B+ tree leaves, and a caller can lay ids out so every removal does,
	// which at 128 measured 2.6B, close to a 3B block, and at 64 measures
	// 2.02B even with a chain-id reset spread across leaves and both own URLs
	// moved in the same edit. More waits for removals.
	MaxDropPerEdit = 64
	// ReservedForReviewers is how much of each hard cap (MaxZones live,
	// MaxEndpointsPerZone) only the exempt calls may use: strangers who keep
	// a cap full refill it the block after a curator clears it, and a cap a
	// curator cannot reach is one they cannot act under.
	ReservedForReviewers = 16
)

// The reasons an endpoint carries when its zone changed under it and sent it
// back to unverified. A reset caused by an edit to a pending zone by its own
// proposer records nobody, because that is not a review: ReviewedBy is empty
// and Reason says why. Every other reset (a rejection, a retirement, anybody
// else's edit, any edit to an approved zone) records whoever caused it.
const (
	ChainIDChanged = "the zone's chain id changed; verify again"
	ZoneRetired    = "the zone was retired; verify again if it returns"
	ZoneRejected   = "the zone was rejected; verify again if it is approved"
)

// IsReset reports whether an unverified endpoint is unverified only because its
// zone changed under it: its reason is one of the three above. A reset reaches
// only a verified endpoint, so it says nothing against the endpoint itself.
func IsReset(e Endpoint) bool {
	return e.Status == Unverified && (e.Reason == ChainIDChanged || e.Reason == ZoneRetired || e.Reason == ZoneRejected)
}

// sequences are the registry-wide counters: the last Revision handed out (so
// none is reused) and the last status-entry sequence (the eviction order).
type sequences struct{ rev, seq uint64 }

// fanout is the B+ tree fanout for every container this package builds itself:
// 32, not the 128 EFFECTIVE_GNO.md measured cheapest in memory. Every value in
// a B+ tree leaf is a boxed object of its own, and removing (or inserting) a
// key shifts every later value in the leaf, each shift a store write. Measured
// on a node, one transaction per step (gno master 3cc494ec4): removing the
// first key of a fanout-128 leaf filled with 120 cost 15.8M gas, the last 5.1M,
// about 90k gas per entry shifted for a scalar value (the counters, the unique
// ids) and about 230k for a pointer (the zone and endpoint tables, kit/index);
// at fanout 32 each costs the same per shift, on a leaf a quarter the size. Endpoints are removed and their dedup keys inserted at
// arbitrary positions, so the smaller leaf is worth its larger node overhead
// (671 B per entry against 592).
const fanout = 32

// Registry holds the zones and their endpoints. The zero value is not usable:
// call [NewRegistry]. All its state is behind pointers, so a copy of the value
// is the same registry, not a second one sharing half of it.
//
// Every write touches its record and all of that record's indexes in one
// method. The index writes cannot fail as written: every key is validated
// non-empty and every unique key is checked free before the first write. If a
// later change made one fail, the method returns the error and the holding
// realm's abort undoes the half-applied write; that abort, not this method, is
// the atomicity guarantee.
type Registry struct {
	// The two sequences live behind a pointer like every container here, so a
	// copied Registry value shares them: with them inline, r2 := *r1 would
	// share every zone but count revisions on its own, and hand out a revision
	// r1 had already used, which a stale decision would then pass.
	ids *sequences

	zones      *table
	bySlug     *unique      // slug -> zone id
	byStatus   *index.Index // status -> zone ids, so a page reads only its rows
	entered    *unique      // status|entry sequence -> zone id: who has been in a state longest
	byProposer *counter     // proposer -> how many PENDING zones they have
	approved   *index.Index // chain id -> ids of APPROVED zones naming it

	endpoints *table
	byAddress *unique      // slug|kind|hash(canonical address) -> endpoint id
	byZone    *index.Index // slug -> endpoint ids
	byKind    *index.Index // slug|kind -> endpoint ids, so a page reads only its rows
	byOwner   *counter     // slug|registrant -> how many endpoints they registered
	unchecked *index.Index // slug -> ids of endpoints that are not Verified
	flagged   *counter     // slug -> how many of those are Flagged
	fresh     *counter     // slug -> how many endpoints are Clearable
	private   *index.Index // slug -> ids of endpoints on a private host (a local zone's only)
}

// NewRegistry returns an empty registry.
func NewRegistry() *Registry {
	return &Registry{
		ids:        &sequences{},
		zones:      newTable(),
		bySlug:     newUnique(),
		byStatus:   index.New(),
		entered:    newUnique(),
		byProposer: newCounter(),
		approved:   index.New(),
		endpoints:  newTable(),
		byAddress:  newUnique(),
		byZone:     index.New(),
		byKind:     index.New(),
		byOwner:    newCounter(),
		flagged:    newCounter(),
		fresh:      newCounter(),
		unchecked:  index.New(),
		private:    index.New(),
	}
}

// Propose files a new zone, Pending, under a slug nobody holds.
func (r *Registry) Propose(by address, at int64, slug string, in Info) error {
	return r.propose(by, at, slug, in, true)
}

// ProposeExempt is Propose without the admission gates (MaxPending and
// MaxPendingPerProposer), for the reviewers a holding realm trusts: a flood
// that fills the queue would otherwise lock out the people who clear it. It
// also takes the last ReservedForReviewers places of the live registry, which
// Propose may not; MaxZones itself still holds.
func (r *Registry) ProposeExempt(by address, at int64, slug string, in Info) error {
	return r.propose(by, at, slug, in, false)
}

func (r *Registry) propose(by address, at int64, slug string, in Info, gated bool) error {
	in = trimInfo(in)
	if err := ValidateSlug(slug); err != nil {
		return err
	}
	if err := ValidateInfo(in); err != nil {
		return err
	}
	if !ValidAddress(by) {
		return errors.New("zones: the proposer is not a valid lowercase address")
	}
	if r.bySlug.has(slug) {
		return errors.New("zones: the slug " + strconv.Quote(slug) + " is taken")
	}
	if r.Live() >= MaxZones {
		return errors.New("zones: the registry is full at " + strconv.Itoa(MaxZones) + " pending and approved zones")
	}
	if gated && r.Live() >= MaxZones-ReservedForReviewers {
		return errors.New("zones: the registry's last " + strconv.Itoa(ReservedForReviewers) + " places are kept for curators")
	}
	if gated && r.byStatus.Count(string(Pending)) >= MaxPending {
		return errors.New("zones: " + strconv.Itoa(MaxPending) + " proposals are already waiting for review; try again once a curator has cleared some")
	}
	if n := r.byProposer.count(by.String()); gated && n >= MaxPendingPerProposer {
		return errors.New("zones: " + by.String() + " already has " + strconv.Itoa(n) +
			" pending proposals, the limit is " + strconv.Itoa(MaxPendingPerProposer))
	}
	z := &Zone{Slug: slug, Proposer: by, ProposedAt: at}
	z.setInfo(in)
	id := r.zones.add(z)
	r.bySlug.set(slug, id)
	r.byProposer.inc(by.String())
	return r.enter(z, id, Pending)
}

// enter files a zone under a status, and bumps its Revision: a decision
// prepared against the old status must fail too, or an approval opened before
// a colleague's rejection would quietly reverse it. Only the two states that
// evict read the entry order, so only they write it. The caller has already
// taken the zone out of its old status.
func (r *Registry) enter(z *Zone, id store.ID, to Status) error {
	r.ids.seq++
	r.ids.rev++
	z.Status, z.Entered, z.Revision = to, int64(r.ids.seq), int64(r.ids.rev)
	if evicts(to) {
		r.entered.set(enteredKey(to, z.Entered), id)
	}
	return r.byStatus.Add(string(to), id)
}

func evicts(st Status) bool { return st == Rejected || st == Retired }

// leave takes a zone out of its current status.
func (r *Registry) leave(z *Zone, id store.ID) {
	r.byStatus.Remove(string(z.Status), id)
	if evicts(z.Status) {
		r.entered.remove(enteredKey(z.Status, z.Entered))
	}
	if z.Status == Pending {
		r.byProposer.dec(z.Proposer.String())
	}
	if z.Status == Approved {
		r.approved.Remove(z.ChainID, id)
	}
}

func enteredKey(st Status, seq int64) string { return string(st) + "|" + store.ID(seq).Key() }

// Edit replaces a zone's Info: every field but the slug and the status.
//
// Only a pending or an approved zone can be edited. A rejected one is removed
// and proposed again, or approved first; a retired one is a record, and its
// retirement reason is the thing it is kept for.
//
// Every edit bumps the zone's Revision and records who made it and when. On a
// pending zone that is all, and a reason is refused rather than silently
// dropped: nobody has reviewed anything yet. On an approved zone an edit is a
// curator decision of its own: the reviewed values changed, so the review on
// record is replaced by this one, with a reason required.
//
// When the chain id changes, whatever the status, every endpoint verified
// against the old one goes back to unverified: what was verified was that it
// answered for a chain this zone no longer names. A reset caused by the
// proposer's own edit to a pending zone records no reviewer; any other records
// the editor. An edit that changes nothing is refused, and leaving the local
// kind removes every endpoint on a private or special-use host (IsPrivateHost),
// at most MaxDropPerEdit in one edit, and is refused while one of them carries
// a curator's ruling.
//
// An edit names the revision it was written against, like an approval does, so
// two editors working from the same reading cannot silently undo each other.
func (r *Registry) Edit(slug string, revision int64, in Info, by address, at int64, reason string) error {
	z, zid, err := r.zone(slug)
	if err != nil {
		return err
	}
	if err := stale(z, revision); err != nil {
		return err
	}
	if z.Status != Pending && z.Status != Approved {
		return errors.New("zones: " + slug + " is " + string(z.Status) + "; only a pending or approved zone can be edited")
	}
	in = trimInfo(in)
	if err := ValidateInfo(in); err != nil {
		return err
	}
	if !ValidAddress(by) {
		return errors.New("zones: the editor is not a valid lowercase address")
	}
	reason = TrimSpaces(reason)
	if err := ValidateReason(reason); err != nil {
		return err
	}
	switch {
	case z.Status == Pending && reason != "":
		return errors.New("zones: " + slug + " is pending, and an edit before review takes no reason")
	case z.Status == Approved && !HasVisible(reason):
		return errors.New("zones: " + slug + " is approved, so an edit needs a reason")
	}
	// An edit that changes nothing would still bump the revision, so refusing
	// it is what stops a revision being bumped for its own sake.
	if in == z.Info() {
		return errors.New("zones: that edit changes nothing on " + slug)
	}
	// Leaving the local kind drops the private hosts only a local zone may
	// list, whatever their verdict: they name nothing on the zone it becomes.
	// Dropped in the edit itself, not refused until somebody removes them,
	// because anybody may register one again between that removal and this
	// edit. Only those endpoints are read, from their own index. One a
	// curator ruled on (a verdict, or a reset that left a reason) is a
	// record, maybe one the editor never saw: the edit fails while one is
	// listed, and a curator removes it first, naming its revision. Only a
	// curator can rule, so nobody else can block the edit this way.
	if z.Kind == Local && in.Kind != Local {
		drop := r.private.Lookup(slug)
		if len(drop) > MaxDropPerEdit {
			return errors.New("zones: leaving local would drop " + strconv.Itoa(len(drop)) + " endpoints, more than " +
				strconv.Itoa(MaxDropPerEdit) + " in one edit; remove some first")
		}
		for _, eid := range drop {
			v, _ := r.endpoints.get(eid)
			// Every verdict names its reviewer and a reset leaves a reason, so
			// these two say "ruled on".
			if e := v.(*Endpoint); e.ReviewedBy != "" || e.Reason != "" {
				who := "a curator ruled on; a curator must remove it first"
				if e.Status == Verified {
					who = "is verified; its registrant or a curator must remove it first"
				}
				return errors.New("zones: leaving local would drop endpoint #" + strconv.FormatInt(e.ID, 10) + ", which " + who)
			}
		}
		for _, eid := range drop {
			r.removeEndpoint(eid)
		}
	}
	if in.ChainID != z.ChainID {
		// The proposer is not a reviewer; anybody else editing (a curator, on a
		// pending zone or an approved one) is, and is named on the reset.
		resetBy := address("")
		if z.Status == Approved || by != z.Proposer {
			resetBy = by
		}
		if z.Status == Approved {
			r.approved.Remove(z.ChainID, zid)
			if err := r.approved.Add(in.ChainID, zid); err != nil {
				return err
			}
		}
		if err := r.unverifyAll(slug, resetBy, at, ChainIDChanged); err != nil {
			return err
		}
	}
	if z.Status == Approved {
		z.ReviewedBy, z.ReviewedAt, z.Reason = by, at, reason
	}
	r.ids.rev++
	z.Revision = int64(r.ids.rev)
	z.EditedBy, z.EditedAt = by, at
	z.setInfo(in)
	return nil
}

// ReviewZone records a curator's decision on a zone.
//
// The transitions are the curation policy, and they are deliberately few:
//
//	approve  from pending, rejected or retired   reason optional
//	reject   from pending                        reason REQUIRED
//	retire   from approved                       reason REQUIRED
//
// and a decision restated: the zone's present status again, with a new
// visible reason, which records the new reviewer and bumps the revision and
// does nothing else (no new entry in the state, no eviction, no reset). It is
// the only way to correct a reason.
//
// Every decision names the zone's Revision the curator read, and fails if the
// zone changed since: otherwise a proposer's edit landing just before an
// approval would become official under the curator's name, and a rejection's
// public reason would describe text the curator never saw.
//
// Rejecting or retiring sends every verified endpoint back to unverified: a
// rejected zone was never vouched for, and a retired network's peers may be
// somebody else's hosts by the time anyone reads them. Each state keeps at most
// MaxRejected or MaxRetired zones; the next one in drops the zone that entered
// that state first, with its endpoints. Every transition bumps the zone's
// Revision, so a decision prepared against the old status fails.
//
// Nothing goes back to pending: a rejected zone is approved after all, removed,
// or pushed out by newer rejections. An official zone is never rejected
// after the fact, it is retired, so the record of it having been official
// survives.
func (r *Registry) ReviewZone(slug string, to Status, revision int64, by address, at int64, reason string) error {
	z, id, err := r.zone(slug)
	if err != nil {
		return err
	}
	if !ValidAddress(by) {
		return errors.New("zones: the reviewer is not a valid lowercase address")
	}
	reason = TrimSpaces(reason)
	if err := ValidateReason(reason); err != nil {
		return err
	}
	if err := stale(z, revision); err != nil {
		return err
	}
	if z.Status == to {
		// A decision is restated with a new reason, the only way to correct
		// one: a rejected or retired zone is not editable, and an edit to an
		// approved zone must change something besides its reason.
		if (to == Approved || to == Rejected || to == Retired) && HasVisible(reason) && reason != z.Reason {
			r.ids.rev++
			z.Revision = int64(r.ids.rev)
			z.ReviewedBy, z.ReviewedAt, z.Reason = by, at, reason
			return nil
		}
		return errors.New("zones: " + slug + " is already " + string(to))
	}
	switch to {
	case Approved:
		if z.Status != Pending && r.Live() >= MaxZones {
			return errors.New("zones: the registry is full at " + strconv.Itoa(MaxZones) + " pending and approved zones")
		}
	case Rejected:
		if z.Status == Approved {
			return errors.New("zones: " + slug + " is approved; retire it instead of rejecting it")
		}
		if z.Status != Pending {
			return errors.New("zones: only a pending zone can be rejected; " + slug + " is " + string(z.Status))
		}
	case Retired:
		if z.Status != Approved {
			return errors.New("zones: only an approved zone can be retired; " + slug + " is " + string(z.Status))
		}
	default:
		return errors.New("zones: a review cannot set a zone to " + strconv.Quote(string(to)))
	}
	if (to == Rejected || to == Retired) && !HasVisible(reason) {
		return errors.New("zones: " + string(to) + " needs a reason")
	}
	switch to {
	case Rejected:
		if err := r.unverifyAll(slug, by, at, ZoneRejected); err != nil {
			return err
		}
		r.makeRoom(Rejected, MaxRejected)
	case Retired:
		if err := r.unverifyAll(slug, by, at, ZoneRetired); err != nil {
			return err
		}
		r.makeRoom(Retired, MaxRetired)
	}
	r.leave(z, id)
	if to == Approved {
		if err := r.approved.Add(z.ChainID, id); err != nil {
			return err
		}
	}
	if err := r.enter(z, id, to); err != nil {
		return err
	}
	z.ReviewedBy, z.ReviewedAt, z.Reason = by, at, reason
	return nil
}

// stale refuses a decision written against a revision the zone has moved past.
func stale(z *Zone, revision int64) error {
	if revision != z.Revision {
		return errors.New("zones: " + z.Slug + " changed since you read it: it is at revision " +
			strconv.FormatInt(z.Revision, 10) + ", you acted on revision " + strconv.FormatInt(revision, 10) +
			"; read it again")
	}
	return nil
}

// makeRoom drops the zone that has been in that state longest, when the state
// is at its cap, so the one about to enter fits.
func (r *Registry) makeRoom(status Status, max int) {
	for r.byStatus.Count(string(status)) >= max {
		var oldest store.ID
		r.entered.tree.Iterate(string(status)+"|", string(status)+"}", func(_ string, v any) bool {
			oldest = v.(store.ID)
			return true
		})
		v, _ := r.zones.get(oldest)
		r.removeZone(v.(*Zone), oldest)
	}
}

// RemoveZone deletes a pending or rejected zone and every endpoint registered
// on it, freeing their storage deposit to whoever signs the removal. It names
// the revision it was decided on, so a removal meant for one proposal cannot
// land on another proposed again under the same slug. A zone that has ever
// been official cannot be removed this way: an approved one is retired, and a
// retired one is kept until MaxRetired newer retirements push it out, so
// whoever still holds its chain id can find out what happened to it.
func (r *Registry) RemoveZone(slug string, revision int64) error {
	z, id, err := r.zone(slug)
	if err != nil {
		return err
	}
	if err := stale(z, revision); err != nil {
		return err
	}
	if z.Status == Approved {
		return errors.New("zones: " + slug + " is approved; retire it instead of removing it")
	}
	if z.Status == Retired {
		return errors.New("zones: " + slug + " is retired, and a retired zone is kept on record")
	}
	r.removeZone(z, id)
	return nil
}

// removeZone unwinds a zone, its endpoints and every index. The per-zone index
// keys go in one RemoveKey each rather than an id at a time, which would copy
// the bucket once per endpoint.
func (r *Registry) removeZone(z *Zone, id store.ID) {
	slug := z.Slug
	for _, eid := range r.byZone.Lookup(slug) {
		v, ok := r.endpoints.remove(eid)
		if !ok {
			continue
		}
		r.byOwner.dec(ownerKey(slug, v.(*Endpoint).Registrant))
	}
	// The zone's dedup keys are one contiguous range (a slug is [a-z0-9-], all
	// below "|"), so they are dropped without hashing each address again.
	keys := []string{}
	r.byAddress.tree.Iterate(slug+"|", slug+"}", func(k string, _ any) bool {
		keys = append(keys, k)
		return false
	})
	for _, k := range keys {
		r.byAddress.remove(k)
	}
	r.flagged.drop(slug)
	r.fresh.drop(slug)
	r.byZone.RemoveKey(slug)
	r.unchecked.RemoveKey(slug)
	r.private.RemoveKey(slug)
	for _, k := range EndpointKinds() {
		r.byKind.RemoveKey(kindKey(slug, k))
	}
	r.leave(z, id)
	r.bySlug.remove(slug)
	r.zones.remove(id)
}

// Register adds an endpoint to a zone, Unverified, and returns its id.
//
// A zone takes endpoints while it is pending or approved, and a rejected or
// retired zone takes none. Who may register on a pending zone is the holding
// realm's call; a URL is stored with its scheme and host lowercased and
// without an empty tail (trimEmptyTail), a peer lowercased whole without its
// host's terminal dot, so what is listed is what dials (Canonical, which also drops default ports and reads tcp as http, is
// what they are compared in, not what is stored).
func (r *Registry) Register(by address, at int64, slug string, kind EndpointKind, addr, label string) (int64, error) {
	return r.register(by, at, slug, kind, addr, label, true)
}

// RegisterExempt is Register without the admission gates
// (MaxUnverifiedPerZone and MaxEndpointsPerAddress), for the reviewers a
// holding realm trusts, as ProposeExempt is, and also takes a zone's last
// ReservedForReviewers places; the hard cap, MaxEndpointsPerZone, still holds.
func (r *Registry) RegisterExempt(by address, at int64, slug string, kind EndpointKind, addr, label string) (int64, error) {
	return r.register(by, at, slug, kind, addr, label, false)
}

func (r *Registry) register(by address, at int64, slug string, kind EndpointKind, addr, label string, gated bool) (int64, error) {
	z, _, err := r.zone(slug)
	if err != nil {
		return 0, err
	}
	if z.Status != Pending && z.Status != Approved {
		return 0, errors.New("zones: " + slug + " is " + string(z.Status) + " and takes no endpoints")
	}
	addr = TrimSpaces(addr)
	label = TrimSpaces(label)
	if kind != Seed && kind != Peer {
		// Validated as it will be stored, so every rule judges the string
		// that dials, length included.
		addr = trimEmptyTail(lowerAuthority(addr))
	}
	if err := ValidateEndpoint(kind, addr); err != nil {
		return 0, err
	}
	if kind == Seed || kind == Peer {
		addr = Canonical(kind, addr) // lowercase, no terminal dot: what tm2 dials
	}
	private := IsPrivateHost(HostOf(kind, addr))
	if z.Kind != Local && private {
		return 0, errors.New("zones: " + slug + " is a " + string(z.Kind) + " zone, and " + addr +
			" names a private or special-use host; only a local zone lists those")
	}
	if err := ValidateLabel(label); err != nil {
		return 0, err
	}
	if !ValidAddress(by) {
		return 0, errors.New("zones: the registrant is not a valid lowercase address")
	}
	akey := addressKey(slug, kind, addr)
	if r.byAddress.has(akey) {
		return 0, errors.New("zones: " + slug + " already lists that " + string(kind) + ": " + addr)
	}
	if n := r.byZone.Count(slug); n >= MaxEndpointsPerZone {
		return 0, errors.New("zones: " + slug + " is full at " + strconv.Itoa(MaxEndpointsPerZone) + " endpoints")
	} else if gated && n >= MaxEndpointsPerZone-ReservedForReviewers {
		return 0, errors.New("zones: " + slug + "'s last " + strconv.Itoa(ReservedForReviewers) + " endpoint places are kept for curators")
	}
	if n := r.Awaiting(slug); gated && n >= MaxUnverifiedPerZone {
		return 0, errors.New("zones: " + slug + " already has " + strconv.Itoa(n) +
			" endpoints waiting for review; try again once a curator has cleared some")
	}
	okey := ownerKey(slug, by)
	if n := r.byOwner.count(okey); gated && n >= MaxEndpointsPerAddress {
		return 0, errors.New("zones: " + by.String() + " already registered " + strconv.Itoa(n) +
			" endpoints on " + slug + ", the limit is " + strconv.Itoa(MaxEndpointsPerAddress))
	}
	e := &Endpoint{Zone: slug, Kind: kind, Address: addr, Label: label, Registrant: by, RegisteredAt: at, Status: Unverified, Exempt: !gated}
	id := r.endpoints.add(e)
	e.ID = int64(id)
	r.ids.rev++
	e.Revision = int64(r.ids.rev)
	r.byAddress.set(akey, id)
	if err := r.byZone.Add(slug, id); err != nil {
		return 0, err
	}
	if err := r.byKind.Add(kindKey(slug, kind), id); err != nil {
		return 0, err
	}
	r.byOwner.inc(okey)
	if gated {
		r.fresh.inc(slug)
	}
	if err := r.unchecked.Add(slug, id); err != nil {
		return 0, err
	}
	if private {
		if err := r.private.Add(slug, id); err != nil {
			return 0, err
		}
	}
	return e.ID, nil
}

// ReviewEndpoint records a curator's verdict on an endpoint. Any verdict may
// follow any other, and the same one again with a new reason (so a typo is
// corrected without passing through a state its registrant may remove it
// from), with these rules:
//
//   - every verdict names the endpoint's Revision as read, and fails if the
//     endpoint changed since: a verdict landing after another curator's,
//     unseen, would silently reverse it;
//   - flagging needs a reason, because "do not use this" with no why is not
//     something an operator can act on;
//   - a verification also names the zone's Revision it was checked against,
//     and fails if the zone changed since: what is verified is that the
//     endpoint answers for THIS zone's chain id, and a proposer could otherwise
//     switch it while the verdict is in flight. A flag or an unverify does
//     not, so an edit to the zone cannot hold off a warning;
//   - only an endpoint of a pending or approved zone can be verified.
func (r *Registry) ReviewEndpoint(id int64, to Verification, zoneRevision, revision int64, by address, at int64, reason string) error {
	e, err := r.endpoint(id)
	if err != nil {
		return err
	}
	if !ValidAddress(by) {
		return errors.New("zones: the reviewer is not a valid lowercase address")
	}
	reason = TrimSpaces(reason)
	if err := ValidateReason(reason); err != nil {
		return err
	}
	switch to {
	case Unverified, Verified, Flagged:
	case "":
		return errors.New("zones: a review needs a verdict")
	default:
		// Exact values only: ParseVerification trims, and a " verified " stored
		// as written would match no filter and count as unverified forever.
		return errors.New("zones: unknown verification " + strconv.Quote(string(to)) + ", want verified, unverified or flagged")
	}
	if e.Status == to && (reason == e.Reason || !HasVisible(reason)) {
		return errors.New("zones: endpoint #" + strconv.FormatInt(id, 10) + " is already " + string(to) +
			"; restating it needs a new reason")
	}
	if to == Flagged && !HasVisible(reason) {
		return errors.New("zones: flagging an endpoint needs a reason")
	}
	z, _, err := r.zone(e.Zone)
	if err != nil {
		return err
	}
	if revision != e.Revision {
		return errors.New("zones: endpoint #" + strconv.FormatInt(id, 10) + " changed since you checked it: it is at revision " +
			strconv.FormatInt(e.Revision, 10) + ", you acted on revision " + strconv.FormatInt(revision, 10))
	}
	if to == Verified {
		if z.Status != Pending && z.Status != Approved {
			return errors.New("zones: " + z.Slug + " is " + string(z.Status) + "; nothing on it can be verified")
		}
		if zoneRevision != z.Revision {
			return errors.New("zones: " + z.Slug + " changed since you checked it against it: it is at revision " +
				strconv.FormatInt(z.Revision, 10) + ", you verified against revision " + strconv.FormatInt(zoneRevision, 10))
		}
	}
	sid := store.ID(id)
	if to == Verified {
		r.unchecked.Remove(e.Zone, sid)
	} else if e.Status == Verified {
		if err := r.unchecked.Add(e.Zone, sid); err != nil {
			return err
		}
	}
	if e.Status == Flagged {
		r.flagged.dec(e.Zone)
	}
	if to == Flagged {
		r.flagged.inc(e.Zone)
	}
	if e.Clearable() {
		r.fresh.dec(e.Zone) // its first verdict: somebody has ruled on it now
	}
	e.Status = to
	e.ReviewedBy, e.ReviewedAt, e.Reason = by, at, reason
	r.ids.rev++
	e.Revision = int64(r.ids.rev)
	return nil
}

// unverifyAll sends every verified endpoint of a zone back to unverified with
// that reason, and by as the reviewer ("" when the proposer's own edit caused
// it). Flagged ones keep their flag. Only the verified ones are read: their
// ids are the zone's ids minus the unchecked ones, both kept ascending, so one
// merge pass finds them without loading the rest.
func (r *Registry) unverifyAll(slug string, by address, at int64, reason string) error {
	all := r.byZone.Lookup(slug)
	skip := r.unchecked.Lookup(slug)
	j := 0
	for _, id := range all {
		for j < len(skip) && skip[j] < id {
			j++
		}
		if j < len(skip) && skip[j] == id {
			continue
		}
		v, ok := r.endpoints.get(id)
		if !ok {
			continue
		}
		e := v.(*Endpoint)
		if err := r.unchecked.Add(slug, id); err != nil {
			return err
		}
		e.Status = Unverified
		e.ReviewedBy, e.ReviewedAt, e.Reason = by, at, reason
		r.ids.rev++
		e.Revision = int64(r.ids.rev)
	}
	return nil
}

// RemoveEndpoint deletes an endpoint, freeing its storage deposit to whoever
// signs the removal. revision is the endpoint's Revision as read: a removal
// fails if a verdict landed since, rather than delete one nobody saw. Who may
// is the holding realm's call.
func (r *Registry) RemoveEndpoint(id, revision int64) error {
	e, err := r.endpoint(id)
	if err != nil {
		return err
	}
	if revision != e.Revision {
		return errors.New("zones: endpoint #" + strconv.FormatInt(id, 10) + " changed since you read it: it is at revision " +
			strconv.FormatInt(e.Revision, 10) + ", you acted on revision " + strconv.FormatInt(revision, 10))
	}
	r.removeEndpoint(store.ID(id))
	return nil
}

// removeEndpoint unwinds the record and all eight of its indexes and counters
// together.
func (r *Registry) removeEndpoint(id store.ID) {
	v, ok := r.endpoints.remove(id)
	if !ok {
		return
	}
	e := v.(*Endpoint)
	r.byAddress.remove(addressKey(e.Zone, e.Kind, e.Address))
	r.byZone.Remove(e.Zone, id)
	r.byKind.Remove(kindKey(e.Zone, e.Kind), id)
	r.byOwner.dec(ownerKey(e.Zone, e.Registrant))
	r.unchecked.Remove(e.Zone, id)
	r.private.Remove(e.Zone, id)
	if e.Status == Flagged {
		r.flagged.dec(e.Zone)
	}
	if e.Clearable() {
		r.fresh.dec(e.Zone)
	}
}

// Revision is the last revision handed out, to a zone or an endpoint. Anything
// that changes after a read gets a later one.
func (r *Registry) Revision() int64 { return int64(r.ids.rev) }

// PrivateEndpoints returns a zone's endpoints on a private host, the ones
// leaving the local kind drops. Only those are read.
func (r *Registry) PrivateEndpoints(slug string) []Endpoint {
	out := []Endpoint{}
	for _, id := range r.private.Lookup(slug) {
		if v, ok := r.endpoints.get(id); ok {
			out = append(out, *v.(*Endpoint))
		}
	}
	return out
}

// Zone returns a copy of the zone under slug.
func (r *Registry) Zone(slug string) (Zone, bool) {
	z, _, err := r.zone(slug)
	if err != nil {
		return Zone{}, false
	}
	return *z, true
}

// Endpoint returns a copy of the endpoint with that id.
func (r *Registry) Endpoint(id int64) (Endpoint, bool) {
	e, err := r.endpoint(id)
	if err != nil {
		return Endpoint{}, false
	}
	return *e, true
}

// EndpointByAddress returns a copy of the endpoint a zone lists under that kind
// and address, compared in [Canonical] form.
func (r *Registry) EndpointByAddress(slug string, kind EndpointKind, addr string) (Endpoint, bool) {
	id, ok := r.byAddress.get(addressKey(slug, kind, addr))
	if !ok {
		return Endpoint{}, false
	}
	v, ok := r.endpoints.get(id)
	if !ok {
		return Endpoint{}, false
	}
	return *v.(*Endpoint), true
}

// ZoneFilter selects zones. A zero field matches anything.
type ZoneFilter struct {
	Status Status
	Kind   Kind
}

// Match reports whether z passes the filter.
func (f ZoneFilter) Match(z Zone) bool {
	return (f.Status == "" || z.Status == f.Status) && (f.Kind == "" || z.Kind == f.Kind)
}

// Zones returns copies of the zones passing f, in the order they were
// proposed. With a status set it reads that status's zones only.
//
// The result, like Endpoints', is capped at its length. A slice handed to
// another realm is readonly there: an append that fits in spare capacity
// writes into it and aborts, one that does not copies and succeeds. Uncapped,
// an importer's append would pass or abort by how many rows the filter
// dropped, which strangers decide by registering.
func (r *Registry) Zones(f ZoneFilter) []Zone {
	if f.Status != "" {
		ids := r.byStatus.Lookup(string(f.Status))
		out := make([]Zone, 0, len(ids))
		for _, id := range ids {
			v, _ := r.zones.get(id)
			if z := v.(*Zone); f.Match(*z) {
				out = append(out, *z)
			}
		}
		return out[:len(out):len(out)]
	}
	out := make([]Zone, 0, r.zones.len())
	r.zones.each(func(v any) {
		if z := v.(*Zone); f.Match(*z) {
			out = append(out, *z)
		}
	})
	return out[:len(out):len(out)]
}

// ZoneCount returns how many zones have that status ("" for all), without
// reading any.
func (r *Registry) ZoneCount(status Status) int {
	if status == "" {
		return r.zones.len()
	}
	return r.byStatus.Count(string(status))
}

// Live returns how many zones are pending or approved: what MaxZones bounds.
func (r *Registry) Live() int {
	return r.byStatus.Count(string(Pending)) + r.byStatus.Count(string(Approved))
}

// ZonePage returns page (1-based) of the zones with that status ("" for every
// status), size per page, in proposal order. A page past the end is empty.
//
// It reads the zones ON the page only; the status's id list (one object, at
// most MaxZones ids) is read whole and sliced.
func (r *Registry) ZonePage(status Status, page, size int) []Zone {
	if status == "" {
		n := r.zones.len()
		if page < 1 || size < 1 || page-1 > n/size {
			return []Zone{}
		}
		if size > n {
			size = n
		}
		out := make([]Zone, 0, size)
		//gnovet:ignore page-offset-overflow bounded by page-1 > n/size at the top
		r.zones.page((page-1)*size, size, func(v any) { out = append(out, *v.(*Zone)) })
		return out
	}
	ids := pageOf(r.byStatus.Lookup(string(status)), page, size)
	out := make([]Zone, 0, len(ids))
	for _, id := range ids {
		v, _ := r.zones.get(id)
		out = append(out, *v.(*Zone))
	}
	return out
}

// ApprovedByChainID returns the approved zones naming that chain id, in
// proposal order. Usually one, but chain ids are not unique across networks
// (every gnodev is "dev"), so it is a list. Only approved zones are indexed, so
// proposals naming a real chain id cost a reader of this nothing.
func (r *Registry) ApprovedByChainID(chainID string) []Zone {
	ids := r.approved.Lookup(chainID)
	out := make([]Zone, 0, len(ids))
	for _, id := range ids {
		v, _ := r.zones.get(id)
		out = append(out, *v.(*Zone))
	}
	return out
}

// SoleApproved returns the approved zone naming that chain id when there is
// exactly one, which is the only case a reader can be pointed at it without a
// guess. It counts first and reads one record at most.
func (r *Registry) SoleApproved(chainID string) (Zone, bool) {
	if r.approved.Count(chainID) != 1 {
		return Zone{}, false
	}
	id, _ := r.approved.First(chainID)
	v, _ := r.zones.get(id)
	return *v.(*Zone), true
}

// EndpointFilter selects endpoints. A zero field matches anything.
type EndpointFilter struct {
	Zone       string
	Kind       EndpointKind
	Status     Verification
	Registrant address
}

// Match reports whether e passes the filter.
func (f EndpointFilter) Match(e Endpoint) bool {
	return (f.Zone == "" || e.Zone == f.Zone) &&
		(f.Kind == "" || e.Kind == f.Kind) &&
		(f.Status == "" || e.Status == f.Status) &&
		(f.Registrant == "" || e.Registrant == f.Registrant)
}

// Endpoints returns copies of the endpoints passing f, oldest first. With a
// zone set it reads that zone's ids only (that kind's, with a kind set), so it
// costs at most MaxEndpointsPerZone records. Without one it reads every
// endpoint in the registry: bound it yourself.
func (r *Registry) Endpoints(f EndpointFilter) []Endpoint {
	if f.Zone != "" {
		var ids []store.ID
		if f.Kind != "" {
			ids = r.byKind.Lookup(kindKey(f.Zone, f.Kind))
		} else {
			ids = r.byZone.Lookup(f.Zone)
		}
		out := make([]Endpoint, 0, len(ids))
		for _, id := range ids {
			v, _ := r.endpoints.get(id)
			if e := v.(*Endpoint); f.Match(*e) {
				out = append(out, *e)
			}
		}
		return out[:len(out):len(out)]
	}
	out := make([]Endpoint, 0, r.endpoints.len())
	r.endpoints.each(func(v any) {
		if e := v.(*Endpoint); f.Match(*e) {
			out = append(out, *e)
		}
	})
	return out[:len(out):len(out)]
}

// Count returns how many endpoints a zone has, and how many of them are
// verified, from the index counts: no endpoint is read.
func (r *Registry) Count(slug string) (verified, total int) {
	total = r.byZone.Count(slug)
	return total - r.unchecked.Count(slug), total
}

// EndpointCount returns how many endpoints of that kind a zone has; "" is
// every kind. No endpoint is read.
func (r *Registry) EndpointCount(slug string, kind EndpointKind) int {
	if kind == "" {
		return r.byZone.Count(slug)
	}
	return r.byKind.Count(kindKey(slug, kind))
}

// Awaiting returns how many of a zone's endpoints are waiting for a verdict,
// what MaxUnverifiedPerZone gates. No endpoint is read.
func (r *Registry) Awaiting(slug string) int {
	return r.unchecked.Count(slug) - r.flagged.count(slug)
}

// Clearable returns how many of a zone's endpoints are Clearable, what a bulk
// clear could remove. No endpoint is read.
func (r *Registry) Clearable(slug string) int { return r.fresh.count(slug) }

// OwnerCount returns how many endpoints that address registered on a zone. No
// endpoint is read.
func (r *Registry) OwnerCount(slug string, who address) int {
	return r.byOwner.count(ownerKey(slug, who))
}

// EndpointPage returns page (1-based) of a zone's endpoints of that kind, ""
// for every kind, size per page, oldest first. Like [Registry.ZonePage] it reads
// the records on the page only, and the bucket's id list (at most
// MaxEndpointsPerZone ids) whole.
func (r *Registry) EndpointPage(slug string, kind EndpointKind, page, size int) []Endpoint {
	var ids []store.ID
	if kind != "" {
		ids = r.byKind.Lookup(kindKey(slug, kind))
	} else {
		ids = r.byZone.Lookup(slug)
	}
	ids = pageOf(ids, page, size)
	out := make([]Endpoint, 0, len(ids))
	for _, id := range ids {
		v, _ := r.endpoints.get(id)
		out = append(out, *v.(*Endpoint))
	}
	return out
}

// pageOf slices ids to one page, 1-based. Out of range is empty, never a
// panic: page and size usually come from a reader's query string.
func pageOf(ids []store.ID, page, size int) []store.ID {
	// The division comes first so a page number near MaxInt cannot overflow
	// the multiplication into a small positive offset.
	if page < 1 || size < 1 || page-1 > len(ids)/size {
		return nil
	}
	//gnovet:ignore page-offset-overflow bounded by page-1 > len(ids)/size above
	start := (page - 1) * size
	if start >= len(ids) {
		return nil
	}
	end := len(ids)
	if len(ids)-start > size {
		end = start + size
	}
	return ids[start:end]
}

// Len returns how many zones the registry holds, whatever their status.
func (r *Registry) Len() int { return r.zones.len() }

func (r *Registry) zone(slug string) (*Zone, store.ID, error) {
	id, ok := r.bySlug.get(slug)
	if !ok {
		return nil, 0, errors.New("zones: no zone " + strconv.Quote(slug))
	}
	v, _ := r.zones.get(id)
	return v.(*Zone), id, nil
}

func (r *Registry) endpoint(id int64) (*Endpoint, error) {
	if id <= 0 {
		return nil, errors.New("zones: no endpoint #" + strconv.FormatInt(id, 10))
	}
	v, ok := r.endpoints.get(store.ID(id))
	if !ok {
		return nil, errors.New("zones: no endpoint #" + strconv.FormatInt(id, 10))
	}
	return v.(*Endpoint), nil
}

// addressKey is the dedup key: the zone, the kind, and a hash of the address
// in [Canonical] form. Hashed so the address part of the key is 16 bytes
// whatever the URL's length,
// instead of a second copy of up to MaxURLLen bytes the record already holds,
// and kept raw rather than hex: it is a key, never shown. Truncated to 128
// bits, which no accidental collision reaches and which only lets a deliberate
// one refuse its own registration. It is the last field, so a byte that happens
// to be "|" cannot be mistaken for a separator.
func addressKey(slug string, kind EndpointKind, addr string) string {
	sum := sha256.Sum256([]byte(Canonical(kind, addr)))
	return slug + "|" + string(kind) + "|" + string(sum[:16])
}

func kindKey(slug string, kind EndpointKind) string { return slug + "|" + string(kind) }

func ownerKey(slug string, who address) string { return slug + "|" + who.String() }

// trimInfo normalizes what a caller typed before it is validated: spaces
// around every field, and each URL's scheme and host lowercased in ASCII
// (both are case-insensitive, gno's link sanitizer is not, so HTTPS:// would
// render as a dead link), and a gnoweb or genesis URL's empty tail dropped
// (trimEmptyTail), as an address bar writes it. Nothing else is rewritten:
// what fails validation is refused, not repaired, and the main RPC with an
// empty tail is refused.
func trimInfo(in Info) Info {
	in.ChainID = TrimSpaces(in.ChainID)
	in.Title = TrimSpaces(in.Title)
	in.Description = TrimSpaces(in.Description)
	in.Kind = Kind(TrimSpaces(string(in.Kind)))
	in.GnowebURL = trimEmptyTail(lowerAuthority(TrimSpaces(in.GnowebURL)))
	in.RPCURL = lowerAuthority(TrimSpaces(in.RPCURL))
	in.GenesisURL = trimEmptyTail(lowerAuthority(TrimSpaces(in.GenesisURL)))
	return in
}

// table is numbered records in a B+ tree: kit/store's shape (an
// id that is never reused, keyed by its seqid encoding so the tree iterates in
// id order) on a B+ tree, the keyed, ordered container EFFECTIVE_GNO.md
// recommends for iteration and pagination. kit/store/v0 sits on an avl, which
// it measured at 2,029 B per entry against a B+ tree's 592 to 671, and about
// six times the gas per entry iterated, and on an immutable path that choice
// is permanent.
type table struct {
	tree *bptree.BPTree
	last uint64
}

func newTable() *table { return &table{tree: bptree.NewBPTreeN(fanout)} }

func (t *table) add(v any) store.ID {
	t.last++
	id := store.ID(t.last)
	t.tree.Set(id.Key(), v)
	return id
}

func (t *table) get(id store.ID) (any, bool) {
	v := t.tree.Get(id.Key())
	return v, v != nil
}

func (t *table) remove(id store.ID) (any, bool) { return t.tree.Remove(id.Key()) }

func (t *table) len() int { return t.tree.Size() }

func (t *table) each(fn func(v any)) {
	t.tree.IterateByOffset(0, t.tree.Size(), func(_ string, v any) bool {
		fn(v)
		return false
	})
}

func (t *table) page(offset, count int, fn func(v any)) {
	t.tree.IterateByOffset(offset, count, func(_ string, v any) bool {
		fn(v)
		return false
	})
}

// unique is a key -> id map in a B+ tree that holds the id itself. kit/index
// stores every key as three objects (a box, an entry struct, an ids array), and
// for a key that only ever has one id two of them say nothing.
type unique struct{ tree *bptree.BPTree }

func newUnique() *unique { return &unique{tree: bptree.NewBPTreeN(fanout)} }

func (u *unique) has(key string) bool { return u.tree.Has(key) }

func (u *unique) get(key string) (store.ID, bool) {
	v := u.tree.Get(key)
	if v == nil {
		return 0, false
	}
	return v.(store.ID), true
}

func (u *unique) set(key string, id store.ID) { u.tree.Set(key, id) }

func (u *unique) remove(key string) { u.tree.Remove(key) }

// counter is a key -> count map in a B+ tree, one object per key. What it
// answers (pending proposals per proposer and endpoints per registrant per
// zone for the caps, flagged endpoints per zone for the admission gate,
// clearable endpoints per zone for the bulk clear) only
// ever asks how many, so keeping the ids would be two more objects per key,
// written and deleted for nothing.
type counter struct{ tree *bptree.BPTree }

func newCounter() *counter { return &counter{tree: bptree.NewBPTreeN(fanout)} }

func (c *counter) count(key string) int {
	v := c.tree.Get(key)
	if v == nil {
		return 0
	}
	return v.(int)
}

func (c *counter) inc(key string) { c.tree.Set(key, c.count(key)+1) }

func (c *counter) dec(key string) {
	if n := c.count(key) - 1; n > 0 {
		c.tree.Set(key, n)
	} else {
		c.tree.Remove(key)
	}
}

func (c *counter) drop(key string) { c.tree.Remove(key) }

registry_test.gno

package zones

import (
	"strconv"
	"strings"
	"testing"

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

var (
	alice   = testutils.TestAddress("alice")
	bob     = testutils.TestAddress("bob")
	curator = testutils.TestAddress("curator")
	carol   = testutils.TestAddress("carol")
)

func onyx() Info {
	return Info{
		ChainID:     "onyx-1",
		Title:       "Onyx",
		Description: "The gno.land testnet.",
		Kind:        Testnet,
		GnowebURL:   "https://onyx.testnets.gno.land",
		RPCURL:      "https://rpc.onyx.testnets.gno.land",
	}
}

func TestProposeAndRead(t *testing.T) {
	r := NewRegistry()
	in := onyx()
	in.Title = "  Onyx  "
	uassert.NoError(t, r.Propose(alice, 10, "onyx", in))

	z, ok := r.Zone("onyx")
	uassert.True(t, ok)
	uassert.Equal(t, "Onyx", z.Title) // trimmed
	uassert.Equal(t, string(Pending), string(z.Status))
	uassert.Equal(t, alice.String(), z.Proposer.String())
	uassert.Equal(t, int64(10), z.ProposedAt)
	uassert.True(t, !z.Reviewed())

	_, ok = r.Zone("nope")
	uassert.False(t, ok)

	uassert.ErrorContains(t, r.Propose(bob, 11, "onyx", onyx()), "is taken")
	uassert.ErrorContains(t, r.Propose(bob, 11, "On yx", onyx()), "slug")
	uassert.ErrorContains(t, r.Propose("", 11, "other", onyx()), "proposer is not a valid lowercase address")
	uassert.Equal(t, 1, r.Len())
}

func TestZoneCopiesAreCopies(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	z, _ := r.Zone("onyx")
	z.Title = "mutated"
	z.Status = Approved
	again, _ := r.Zone("onyx")
	uassert.Equal(t, "Onyx", again.Title)
	uassert.Equal(t, string(Pending), string(again.Status))
}

func TestPendingCapPerProposer(t *testing.T) {
	r := NewRegistry()
	for i := 0; i < MaxPendingPerProposer; i++ {
		uassert.NoError(t, r.Propose(alice, 1, "z"+strconv.Itoa(i), onyx()))
	}
	uassert.ErrorContains(t, r.Propose(alice, 1, "one-more", onyx()), "pending proposals, the limit is")
	// Somebody else is not blocked by alice's spam.
	uassert.NoError(t, r.Propose(bob, 1, "bobs", onyx()))
	// A reviewed proposal frees the slot.
	uassert.NoError(t, r.ReviewZone("z0", Approved, rev(r, "z0"), curator, 2, ""))
	uassert.NoError(t, r.Propose(alice, 3, "one-more", onyx()))
	// So does a removed one.
	uassert.NoError(t, r.RemoveZone("z1", rev(r, "z1")))
	uassert.NoError(t, r.Propose(alice, 3, "and-another", onyx()))
}

func TestReviewTransitions(t *testing.T) {
	cases := []struct {
		from   Status
		to     Status
		reason string
		err    string
	}{
		{Pending, Approved, "", ""},
		{Pending, Rejected, "duplicate of onyx", ""},
		{Pending, Rejected, "", "needs a reason"},
		{Pending, Rejected, "\u200b", "invisible or bidi"},
		{Approved, Retired, "\u2066\u2069", "invisible or bidi"},
		{Pending, Retired, "gone", "only an approved zone can be retired"},
		{Pending, Pending, "", "already pending"},
		{Approved, Retired, "the RPC stopped resolving", ""},
		{Approved, Retired, "  ", "needs a reason"},
		{Approved, Rejected, "x", "retire it instead"},
		{Approved, Approved, "", "already approved"},
		{Rejected, Approved, "reconsidered", ""},
		{Rejected, Retired, "x", "only an approved zone"},
		{Retired, Approved, "it came back", ""},
		{Retired, Rejected, "x", "only a pending zone can be rejected"},
		{Pending, "official", "", "cannot set a zone"},
	}
	for _, c := range cases {
		r := NewRegistry()
		uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
		// Walk the zone to the starting state.
		switch c.from {
		case Approved:
			uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 2, ""))
		case Rejected:
			uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), curator, 2, "setup"))
		case Retired:
			uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 2, ""))
			uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 3, "setup"))
		}
		label := string(c.from) + " -> " + string(c.to)
		err := r.ReviewZone("onyx", c.to, rev(r, "onyx"), curator, 9, c.reason)
		z, _ := r.Zone("onyx")
		if c.err != "" {
			uassert.ErrorContains(t, err, c.err, label)
			uassert.Equal(t, string(c.from), string(z.Status), label)
			continue
		}
		uassert.NoError(t, err, label)
		uassert.Equal(t, string(c.to), string(z.Status), label)
		uassert.Equal(t, curator.String(), z.ReviewedBy.String(), label)
		uassert.Equal(t, int64(9), z.ReviewedAt, label)
		uassert.Equal(t, c.reason, z.Reason, label)
	}
}

func TestEdit(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	in := onyx()
	in.GenesisURL = "https://github.com/gnolang/gno/releases/download/chain/onyx/genesis.json"
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), in, "", 2, ""), "editor is not a valid lowercase address")
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), in, alice, 2, ""))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, in.GenesisURL, z.GenesisURL)
	uassert.False(t, z.Reviewed()) // pending: just an edit

	bad := in
	bad.RPCURL = ""
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), bad, alice, 2, ""), "rpc url is empty")
	uassert.ErrorContains(t, r.Edit("nope", rev(r, "nope"), in, alice, 2, ""), "no zone")
	z, _ = r.Zone("onyx")
	uassert.Equal(t, "https://rpc.onyx.testnets.gno.land", z.RPCURL) // unchanged by the refused edit

	// Once reviewed, an edit is a decision: it needs a reason and an editor, and
	// it replaces the review on record.
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 3, "probed"))
	in.RPCURL = "https://rpc2.onyx.example.com"
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), in, curator, 4, ""), "an edit needs a reason")
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), in, "", 4, "moved"), "editor is not a valid lowercase address")
	z, _ = r.Zone("onyx")
	uassert.Equal(t, "https://rpc.onyx.testnets.gno.land", z.RPCURL)
	uassert.Equal(t, "probed", z.Reason)
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), in, bob, 5, "rpc moved"))
	z, _ = r.Zone("onyx")
	uassert.Equal(t, "https://rpc2.onyx.example.com", z.RPCURL)
	uassert.Equal(t, bob.String(), z.ReviewedBy.String())
	uassert.Equal(t, int64(5), z.ReviewedAt)
	uassert.Equal(t, "rpc moved", z.Reason)
	uassert.Equal(t, string(Approved), string(z.Status))

	// A retired zone is a record: its retirement reason is not editable away.
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 6, "testnet ended"))
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), in, curator, 7, "typo"), "only a pending or approved zone can be edited")
	z, _ = r.Zone("onyx")
	uassert.Equal(t, "testnet ended", z.Reason)
	// Nor is a rejected one.
	uassert.NoError(t, r.Propose(alice, 8, "nope", onyx()))
	uassert.NoError(t, r.ReviewZone("nope", Rejected, rev(r, "nope"), curator, 9, "dup"))
	uassert.ErrorContains(t, r.Edit("nope", rev(r, "nope"), onyx(), alice, 10, ""), "only a pending or approved zone can be edited")
}

// What was verified is that an endpoint answered for the zone's chain id, so
// changing the chain id un-verifies them; changing only the RPC does not.
func TestChainIDEditUnverifiesEndpoints(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(curator, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))
	a, _ := r.Register(alice, 2, "onyx", RPC, "https://a.example.com", "")
	b, _ := r.Register(alice, 2, "onyx", Peer, nodeID+"@b.example.com:26656", "")
	f, _ := r.Register(alice, 2, "onyx", RPC, "https://f.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(a, Verified, zr(r, a), erev(r, a), curator, 3, ""))
	uassert.NoError(t, r.ReviewEndpoint(b, Verified, zr(r, b), erev(r, b), curator, 3, ""))
	uassert.NoError(t, r.ReviewEndpoint(f, Flagged, zr(r, f), erev(r, f), curator, 3, "down"))

	in := onyx()
	in.RPCURL = "https://rpc2.onyx.example.com"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), in, curator, 4, "rpc moved"))
	uassert.Equal(t, 2, len(r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})))

	in.ChainID = "onyx-2"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), in, curator, 5, "relaunched as onyx-2"))
	uassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})))
	e, _ := r.Endpoint(a)
	uassert.Equal(t, string(Unverified), string(e.Status))
	uassert.Equal(t, ChainIDChanged, e.Reason)
	uassert.Equal(t, int64(5), e.ReviewedAt)
	e, _ = r.Endpoint(f)
	uassert.Equal(t, string(Flagged), string(e.Status)) // a flag is not undone by an edit
	uassert.Equal(t, "down", e.Reason)
	// And the reset ones count against the review queue again (the flagged
	// one has its verdict and stays out): verifying one frees it.
	v, _ := r.Count("onyx")
	uassert.Equal(t, 0, v)
	uassert.Equal(t, 2, r.Awaiting("onyx"), "both reset endpoints are back in the queue")
	uassert.NoError(t, r.ReviewEndpoint(a, Verified, zr(r, a), erev(r, a), curator, 6, "answers onyx-2"))
	uassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})))
	v, _ = r.Count("onyx")
	uassert.Equal(t, 1, v)

	// Retiring resets what was verified, at the moment the network stops: a
	// retired network's hosts may be somebody else's by the time anyone reads
	// them. Approving it again does not restore anything.
	uassert.NoError(t, r.ReviewEndpoint(b, Verified, zr(r, b), erev(r, b), curator, 6, ""))
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 6, "stopped"))
	uassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})))
	e, _ = r.Endpoint(b)
	uassert.Equal(t, ZoneRetired, e.Reason)
	uassert.Equal(t, curator.String(), e.ReviewedBy.String())
	uassert.ErrorContains(t, r.ReviewEndpoint(b, Verified, zr(r, b), erev(r, b), curator, 6, ""), "nothing on it can be verified")
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 7, "back up"))
	uassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})))
	e, _ = r.Endpoint(f)
	uassert.Equal(t, string(Flagged), string(e.Status))
	// A pending zone is no exception: a proposer collecting verdicts for one
	// chain id and then switching it gets them all reset.
	uassert.NoError(t, r.Propose(alice, 7, "pend", onyx()))
	pid, _ := r.Register(alice, 7, "pend", RPC, "https://p.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(pid, Verified, zr(r, pid), erev(r, pid), curator, 8, ""))
	other := onyx()
	other.ChainID = "elsewhere-1"
	uassert.NoError(t, r.Edit("pend", rev(r, "pend"), other, alice, 9, ""))
	e, _ = r.Endpoint(pid)
	uassert.Equal(t, string(Unverified), string(e.Status))
	// The proposer's own edit caused the reset, and the proposer is not a
	// reviewer, so none is recorded, and the reason says why.
	uassert.Equal(t, "", e.ReviewedBy.String())
	uassert.Equal(t, ChainIDChanged, e.Reason)
	z, _ := r.Zone("pend")
	uassert.False(t, z.Reviewed()) // still a pending edit: the zone's own review is untouched
}

func TestRegisterAndFilter(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(curator, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))

	rpc, err := r.Register(alice, 5, "onyx", RPC, " https://rpc.onyx.testnets.gno.land ", "gno core")
	uassert.NoError(t, err)
	peer, err := r.Register(bob, 6, "onyx", Peer, nodeID+"@seed-1.onyx.testnets.gno.land:26656", "")
	uassert.NoError(t, err)
	uassert.True(t, rpc > 0 && peer > rpc)

	e, ok := r.Endpoint(rpc)
	uassert.True(t, ok)
	uassert.Equal(t, rpc, e.ID)
	uassert.Equal(t, "https://rpc.onyx.testnets.gno.land", e.Address) // trimmed
	uassert.Equal(t, string(Unverified), string(e.Status))
	uassert.Equal(t, alice.String(), e.Registrant.String())

	// Dedup is case-insensitive: the same host under another spelling.
	_, err = r.Register(bob, 7, "onyx", RPC, "https://RPC.onyx.testnets.gno.land", "")
	uassert.ErrorContains(t, err, "already lists that rpc")
	// ...but a path is case-sensitive, so another path is another endpoint.
	_, err = r.Register(bob, 7, "onyx", Indexer, "https://indexer.example.com/API", "")
	uassert.NoError(t, err)
	_, err = r.Register(bob, 7, "onyx", Indexer, "https://INDEXER.example.com/API", "")
	uassert.ErrorContains(t, err, "already lists that indexer")
	_, err = r.Register(bob, 7, "onyx", Indexer, "https://indexer.example.com/api", "")
	uassert.NoError(t, err)
	// The same address under another kind is a different endpoint.
	_, err = r.Register(bob, 7, "onyx", Gnoweb, "https://rpc.onyx.testnets.gno.land", "")
	uassert.NoError(t, err)

	_, err = r.Register(bob, 7, "nope", RPC, "https://x.y", "")
	uassert.ErrorContains(t, err, "no zone")
	_, err = r.Register(bob, 7, "onyx", Peer, "https://x.y", "")
	uassert.ErrorContains(t, err, "<node id>@")
	_, err = r.Register(bob, 7, "onyx", RPC, "https://x.y", "two\nlines")
	uassert.ErrorContains(t, err, "control character")

	uassert.Equal(t, 5, len(r.Endpoints(EndpointFilter{Zone: "onyx"})))
	uassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: "onyx", Kind: Peer})))
	uassert.Equal(t, 4, len(r.Endpoints(EndpointFilter{Registrant: bob})))
	uassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})))

	uassert.NoError(t, r.ReviewEndpoint(rpc, Verified, zr(r, rpc), erev(r, rpc), curator, 8, "answers onyx-1"))
	vs := r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified})
	uassert.Equal(t, 1, len(vs))
	uassert.Equal(t, "answers onyx-1", vs[0].Reason)
	v, total := r.Count("onyx")
	uassert.Equal(t, 1, v)
	uassert.Equal(t, 5, total)

	uassert.ErrorContains(t, r.ReviewEndpoint(rpc, Verified, zr(r, rpc), erev(r, rpc), curator, 8, "answers onyx-1"), "already verified")
	uassert.ErrorContains(t, r.ReviewEndpoint(peer, Flagged, zr(r, peer), erev(r, peer), curator, 8, ""), "needs a reason")
	uassert.ErrorContains(t, r.ReviewEndpoint(peer, "trusted", zr(r, peer), erev(r, peer), curator, 8, ""), "unknown verification")
	uassert.ErrorContains(t, r.ReviewEndpoint(peer, "", zr(r, peer), erev(r, peer), curator, 8, ""), "needs a verdict")
	uassert.ErrorContains(t, r.ReviewEndpoint(peer, " verified ", zr(r, peer), erev(r, peer), curator, 8, ""), "unknown verification")
	_, err = r.Register(bob, 7, "onyx", " rpc ", "not a url", "")
	uassert.ErrorContains(t, err, "unknown endpoint kind")
	// A scheme's case is not a different endpoint.
	_, err = r.Register(bob, 7, "onyx", Explorer, "HTTPS://Explorer.example.com/x", "")
	uassert.NoError(t, err)
	_, err = r.Register(bob, 7, "onyx", Explorer, "https://explorer.example.com/x", "")
	uassert.ErrorContains(t, err, "already lists that explorer")
	uassert.ErrorContains(t, r.ReviewEndpoint(999, Verified, zr(r, 999), erev(r, 999), curator, 8, ""), "no endpoint #999")
	uassert.ErrorContains(t, r.ReviewEndpoint(0, Verified, zr(r, 0), erev(r, 0), curator, 8, ""), "no endpoint #0")
	uassert.NoError(t, r.ReviewEndpoint(peer, Flagged, zr(r, peer), erev(r, peer), curator, 9, "wrong chain id"))
	uassert.NoError(t, r.ReviewEndpoint(peer, Unverified, zr(r, peer), erev(r, peer), curator, 10, "fixed, re-checking"))

	// Removing frees the dedup key, so the same address can come back.
	uassert.NoError(t, r.RemoveEndpoint(rpc, erev(r, rpc)))
	_, ok = r.Endpoint(rpc)
	uassert.False(t, ok)
	uassert.ErrorContains(t, r.RemoveEndpoint(rpc, erev(r, rpc)), "no endpoint")
	_, err = r.Register(bob, 11, "onyx", RPC, "https://rpc.onyx.testnets.gno.land", "")
	uassert.NoError(t, err)
}

func TestRegisterNeedsALiveZone(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	// Pending takes endpoints: a proposer fills in the peers before review.
	_, err := r.Register(alice, 2, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), curator, 3, "not a gno chain"))
	_, err = r.Register(alice, 4, "onyx", RPC, "https://b.example.com", "")
	uassert.ErrorContains(t, err, "is rejected and takes no endpoints")
}

func TestEndpointCapPerAddress(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	for i := 0; i < MaxEndpointsPerAddress; i++ {
		_, err := r.Register(alice, 2, "onyx", RPC, "https://n"+strconv.Itoa(i)+".example.com", "")
		uassert.NoError(t, err)
	}
	_, err := r.Register(alice, 2, "onyx", RPC, "https://over.example.com", "")
	uassert.ErrorContains(t, err, "the limit is")
	// Bob still can.
	_, err = r.Register(bob, 2, "onyx", RPC, "https://over.example.com", "")
	uassert.NoError(t, err)
}

func TestRemoveZone(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	_, err := r.Register(bob, 2, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 3, ""))
	uassert.ErrorContains(t, r.RemoveZone("onyx", rev(r, "onyx")), "retire it instead")
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 4, "testnet ended"))
	uassert.ErrorContains(t, r.RemoveZone("onyx", rev(r, "onyx")), "kept on record")
	_, ok := r.Zone("onyx")
	uassert.True(t, ok)

	// A rejected zone is removable, endpoints and all.
	uassert.NoError(t, r.Propose(alice, 5, "spam", onyx()))
	_, err = r.Register(bob, 5, "spam", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewZone("spam", Rejected, rev(r, "spam"), curator, 6, "not a network"))
	uassert.NoError(t, r.RemoveZone("spam", rev(r, "spam")))
	_, ok = r.Zone("spam")
	uassert.False(t, ok)
	uassert.Equal(t, 0, len(r.Endpoints(EndpointFilter{Zone: "spam"})))
	uassert.Equal(t, 1, r.Len())
	uassert.ErrorContains(t, r.RemoveZone("spam", rev(r, "spam")), "no zone")
	// The slug and the address are free again.
	uassert.NoError(t, r.Propose(bob, 7, "spam", onyx()))
	_, err = r.Register(bob, 8, "spam", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
}

func TestReviewNeedsAReviewer(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), "", 2, ""), "reviewer is not a valid lowercase address")
	z, _ := r.Zone("onyx")
	uassert.Equal(t, string(Pending), string(z.Status))
	id, err := r.Register(alice, 2, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), "", 3, ""), "reviewer is not a valid lowercase address")
}

// A flood from many addresses fills the review queue and nothing above it.
func TestFloodCannotCrowdOutReviewedEntries(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(curator, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))
	for i := 0; i < MaxPending; i++ {
		uassert.NoError(t, r.Propose(testAddr(i), 2, "flood-"+strconv.Itoa(i), onyx()))
	}
	uassert.ErrorContains(t, r.Propose(bob, 3, "honest", onyx()), "waiting for review")
	uassert.Equal(t, MaxPending+1, r.Len())
	// Clearing one makes room.
	uassert.NoError(t, r.ReviewZone("flood-0", Rejected, rev(r, "flood-0"), curator, 4, "spam"))
	uassert.NoError(t, r.Propose(bob, 5, "honest", onyx()))

	// Endpoints: those waiting for a verdict have their own gate, and verifying frees it.
	ids := []int64{}
	for i := 0; i < MaxUnverifiedPerZone; i++ {
		id, err := r.Register(testAddr(i/MaxEndpointsPerAddress), 6, "onyx", RPC, "https://n"+strconv.Itoa(i)+".example.com", "")
		uassert.NoError(t, err)
		ids = append(ids, id)
	}
	_, err := r.Register(bob, 7, "onyx", RPC, "https://honest.example.com", "")
	uassert.ErrorContains(t, err, "waiting for review")
	uassert.NoError(t, r.ReviewEndpoint(ids[0], Verified, zr(r, ids[0]), erev(r, ids[0]), curator, 8, ""))
	_, err = r.Register(bob, 9, "onyx", RPC, "https://honest.example.com", "")
	uassert.NoError(t, err)
	// The gate is full again (the honest one is waiting). A flag is a verdict,
	// so a flagged endpoint leaves the queue: curators keep the warning and
	// still make room, instead of deleting the warning to make room.
	_, err = r.Register(bob, 11, "onyx", RPC, "https://honest2.example.com", "")
	uassert.ErrorContains(t, err, "waiting for review")
	uassert.NoError(t, r.ReviewEndpoint(ids[1], Flagged, zr(r, ids[1]), erev(r, ids[1]), curator, 12, "spam"))
	_, err = r.Register(bob, 13, "onyx", RPC, "https://honest2.example.com", "")
	uassert.NoError(t, err)
	// Unflagging puts it back in the queue, and a review is never refused for
	// the queue being full, only a registration is.
	uassert.NoError(t, r.ReviewEndpoint(ids[1], Unverified, zr(r, ids[1]), erev(r, ids[1]), curator, 14, "re-checking"))
	_, err = r.Register(bob, 15, "onyx", RPC, "https://honest3.example.com", "")
	uassert.ErrorContains(t, err, "waiting for review")
	uassert.NoError(t, r.RemoveEndpoint(ids[2], erev(r, ids[2])))
	uassert.NoError(t, r.RemoveEndpoint(ids[3], erev(r, ids[3])))
	_, err = r.Register(bob, 16, "onyx", RPC, "https://honest3.example.com", "")
	uassert.NoError(t, err)
}

func testAddr(i int) address { return testutils.TestAddress("flood" + strconv.Itoa(i)) }

func TestZonesFilterAndOrder(t *testing.T) {
	r := NewRegistry()
	mainnet := onyx()
	mainnet.ChainID, mainnet.Kind = "gnoland-1", Mainnet
	uassert.NoError(t, r.Propose(curator, 1, "mainnet", mainnet))
	uassert.NoError(t, r.Propose(curator, 1, "onyx", onyx()))
	uassert.NoError(t, r.Propose(alice, 2, "alices", onyx()))
	uassert.NoError(t, r.ReviewZone("mainnet", Approved, rev(r, "mainnet"), curator, 3, ""))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 3, ""))

	slugs := func(zs []Zone) string {
		s := ""
		for _, z := range zs {
			s += z.Slug + " "
		}
		return s
	}
	uassert.Equal(t, "mainnet onyx alices ", slugs(r.Zones(ZoneFilter{})))
	uassert.Equal(t, "mainnet onyx ", slugs(r.Zones(ZoneFilter{Status: Approved})))
	uassert.Equal(t, "alices ", slugs(r.Zones(ZoneFilter{Status: Pending})))
	uassert.Equal(t, "onyx alices ", slugs(r.Zones(ZoneFilter{Kind: Testnet})))
	uassert.Equal(t, "onyx ", slugs(r.Zones(ZoneFilter{Status: Approved, Kind: Testnet})))
	uassert.Equal(t, "", slugs(r.Zones(ZoneFilter{Kind: Local})))
}

func TestPagesAndCounts(t *testing.T) {
	r := NewRegistry()
	for i := 0; i < 7; i++ {
		uassert.NoError(t, r.Propose(testAddr(i), 1, "z"+strconv.Itoa(i), onyx()))
	}
	uassert.NoError(t, r.ReviewZone("z1", Approved, rev(r, "z1"), curator, 2, ""))
	uassert.NoError(t, r.ReviewZone("z3", Approved, rev(r, "z3"), curator, 2, ""))
	uassert.NoError(t, r.ReviewZone("z5", Approved, rev(r, "z5"), curator, 2, ""))
	uassert.Equal(t, 3, r.ZoneCount(Approved))
	uassert.Equal(t, 4, r.ZoneCount(Pending))
	uassert.Equal(t, 7, r.ZoneCount(""))

	page := func(zs []Zone) string {
		out := ""
		for _, z := range zs {
			out += z.Slug + " "
		}
		return out
	}
	uassert.Equal(t, "z1 z3 ", page(r.ZonePage(Approved, 1, 2)))
	uassert.Equal(t, "z5 ", page(r.ZonePage(Approved, 2, 2)))
	uassert.Equal(t, "", page(r.ZonePage(Approved, 3, 2)))
	uassert.Equal(t, "", page(r.ZonePage(Approved, 0, 2)))
	uassert.Equal(t, "", page(r.ZonePage(Approved, 1, 0)))
	uassert.Equal(t, "", page(r.ZonePage(Approved, 1<<62, 1<<10)), "no overflow into a small offset")
	uassert.Equal(t, "z0 z2 z4 z6 ", page(r.ZonePage(Pending, 1, 10)))
	// "" is every status, consistent with ZoneCount("") and ZoneFilter{}.
	uassert.Equal(t, "z0 z1 z2 ", page(r.ZonePage("", 1, 3)))
	uassert.Equal(t, "z6 ", page(r.ZonePage("", 3, 3)))
	uassert.Equal(t, "", page(r.ZonePage("", 4, 3)))
	uassert.Equal(t, "", page(r.ZonePage("", 0, 3)))
	uassert.Equal(t, "", page(r.ZonePage("", 1<<62, 1<<10)), "no overflow into a small offset")
	uassert.Equal(t, "z0 z1 z2 z3 z4 z5 z6 ", page(r.ZonePage("", 1, 1<<40)))
	// The status index follows a review and a removal.
	uassert.NoError(t, r.ReviewZone("z0", Rejected, rev(r, "z0"), curator, 3, "dup"))
	uassert.NoError(t, r.RemoveZone("z2", rev(r, "z2")))
	uassert.Equal(t, "z4 z6 ", page(r.ZonePage(Pending, 1, 10)))
	uassert.Equal(t, "z0 ", page(r.ZonePage(Rejected, 1, 10)))
	uassert.Equal(t, "z1 z3 z5 ", page(r.Zones(ZoneFilter{Status: Approved})))

	// Chain ids are not unique, only approved zones are indexed by one (so a
	// proposal naming a real chain id costs a reader nothing), and the index
	// follows an edit and a retirement.
	uassert.Equal(t, "z1 z3 z5 ", page(r.ApprovedByChainID("onyx-1")))
	in := onyx()
	in.ChainID = "onyx-2"
	uassert.NoError(t, r.Edit("z1", rev(r, "z1"), in, curator, 4, "relaunched"))
	uassert.Equal(t, "z1 ", page(r.ApprovedByChainID("onyx-2")))
	uassert.Equal(t, "z3 z5 ", page(r.ApprovedByChainID("onyx-1")))
	uassert.NoError(t, r.Edit("z4", rev(r, "z4"), in, alice, 4, "")) // pending: not indexed
	uassert.Equal(t, "z1 ", page(r.ApprovedByChainID("onyx-2")))
	uassert.NoError(t, r.ReviewZone("z5", Retired, rev(r, "z5"), curator, 4, "gone"))
	uassert.Equal(t, "z3 ", page(r.ApprovedByChainID("onyx-1")))

	// Endpoints: counts from the indexes, pages by kind.
	for i := 0; i < 5; i++ {
		_, err := r.Register(alice, 5, "z3", RPC, "https://e"+strconv.Itoa(i)+".example.com", "")
		uassert.NoError(t, err)
	}
	pid, err := r.Register(alice, 5, "z3", Peer, nodeID+"@p.example.com:26656", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewEndpoint(pid, Verified, zr(r, pid), erev(r, pid), curator, 6, ""))
	v, total := r.Count("z3")
	uassert.Equal(t, 1, v)
	uassert.Equal(t, 6, total)
	uassert.Equal(t, 5, r.EndpointCount("z3", RPC))
	uassert.Equal(t, 1, r.EndpointCount("z3", Peer))
	uassert.Equal(t, 0, r.EndpointCount("z3", Faucet))
	uassert.Equal(t, 6, r.EndpointCount("z3", ""))
	uassert.Equal(t, 1, len(r.EndpointPage("z3", RPC, 3, 2))) // page 3 of 5 rpcs at 2 a page holds one
	uassert.Equal(t, "https://e4.example.com", r.EndpointPage("z3", RPC, 3, 2)[0].Address)
	uassert.Equal(t, nodeID+"@p.example.com:26656", r.EndpointPage("z3", Peer, 1, 10)[0].Address)
	uassert.Equal(t, 6, len(r.EndpointPage("z3", "", 1, 10)))
	uassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: "z3", Kind: Peer})))
	uassert.NoError(t, r.RemoveEndpoint(pid, erev(r, pid)))
	uassert.Equal(t, 0, r.EndpointCount("z3", Peer))
	v, total = r.Count("z3")
	uassert.Equal(t, 0, v)
	uassert.Equal(t, 5, total)
}

// rev is a zone's current revision, what a curator who just read it approves.
func rev(r *Registry, slug string) int64 {
	z, _ := r.Zone(slug)
	return z.Revision
}

// erev is an endpoint's revision, what a verdict or a removal names.
func erev(r *Registry, id int64) int64 {
	e, ok := r.Endpoint(id)
	if !ok {
		return 0
	}
	return e.Revision
}

// zr is the revision of an endpoint's zone, what a verification also names.
func zr(r *Registry, id int64) int64 {
	e, ok := r.Endpoint(id)
	if !ok {
		return 0
	}
	return rev(r, e.Zone)
}

// An approval names the revision the curator read. An edit landing between the
// reading and the approval makes the approval fail, rather than making text the
// curator never saw official under their name. Remove-and-propose-again cannot
// reuse a revision either.
func TestApprovalBindsToRevision(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	read := rev(r, "onyx")

	swapped := onyx()
	swapped.RPCURL = "https://attacker.example.com"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), swapped, alice, 2, ""))
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, read, curator, 3, ""), "changed since you read it")
	z, _ := r.Zone("onyx")
	uassert.Equal(t, string(Pending), string(z.Status))
	uassert.Equal(t, alice.String(), z.EditedBy.String())
	uassert.Equal(t, int64(2), z.EditedAt)

	// Removed and proposed again under the same slug: a new revision, never the old one.
	uassert.NoError(t, r.RemoveZone("onyx", rev(r, "onyx")))
	uassert.NoError(t, r.Propose(alice, 4, "onyx", onyx()))
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, read, curator, 5, ""), "changed since you read it")
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 5, ""))

	// Verifying an endpoint binds the same way: to the chain id it was checked against.
	id, err := r.Register(alice, 6, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	checked := zr(r, id)
	moved := onyx()
	moved.ChainID = "onyx-2"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), moved, curator, 7, "relaunch"))
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, checked, erev(r, id), curator, 8, ""), "changed since you checked it against it")
	// A revision from the future is as wrong as a past one.
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id)+1, erev(r, id), curator, 8, ""), "changed since")
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id)+1, curator, 8, ""), "changed since")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 8, ""))
	// Every verdict binds to the endpoint as read, too: a verify written before
	// another curator's flag fails rather than silently reversing it.
	read = erev(r, id)
	uassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), read, curator, 9, "down"))
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Unverified, zr(r, id), read, alice, 10, ""), "changed since you checked it")
	// The same verdict again, with a new reason, restates it.
	uassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 11, "down since block 9"))
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 12, "down since block 9"), "restating it needs a new reason")
}

func TestPendingEditTakesNoReason(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), onyx(), alice, 2, "fixed a typo"), "takes no reason")
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 3, ""))
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), onyx(), curator, 4, "\u200b"), "invisible")
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), onyx(), curator, 4, ""), "needs a reason")
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), onyx(), curator, 4, "no change"), "changes nothing")
	in := onyx()
	in.Title = "Onyx testnet"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), in, curator, 4, "retitled"))
}

// Rejected and retired zones are kept for the record, each up to a cap of its
// own, and neither counts against the live registry: nothing a proposer or a
// curator does, and no amount of time, fills it for good.
func TestRecordsNeverFillTheRegistry(t *testing.T) {
	r := NewRegistry()
	for i := 0; i < MaxRejected+3; i++ {
		slug := "rej" + strconv.Itoa(i)
		uassert.NoError(t, r.Propose(testAddr(i), 1, slug, onyx()))
		uassert.NoError(t, r.ReviewZone(slug, Rejected, rev(r, slug), curator, 2, "spam"))
	}
	uassert.Equal(t, MaxRejected, r.ZoneCount(Rejected))
	// The three that entered the rejected state first made room.
	_, ok := r.Zone("rej0")
	uassert.False(t, ok)
	_, ok = r.Zone("rej3")
	uassert.True(t, ok)
	uassert.Equal(t, 0, r.Live())

	for i := 0; i < MaxRetired+2; i++ {
		slug := "ret" + strconv.Itoa(i)
		uassert.NoError(t, r.Propose(curator, 3, slug, onyx()))
		uassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 3, ""))
		uassert.NoError(t, r.ReviewZone(slug, Retired, rev(r, slug), curator, 4, "stopped"))
	}
	uassert.Equal(t, MaxRetired, r.ZoneCount(Retired))
	_, ok = r.Zone("ret0")
	uassert.False(t, ok)
	uassert.Equal(t, 0, r.Live())
	uassert.Equal(t, MaxRejected+MaxRetired, r.Len())

	// The live registry is untouched by all of it.
	uassert.NoError(t, r.Propose(bob, 5, "honest", onyx()))
	uassert.Equal(t, 1, r.Live())
}

// An evicted zone takes its endpoints and every index entry with it, so its
// slug and its addresses can be used again.
func TestEvictionUnwindsEverything(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "first", onyx()))
	_, err := r.Register(alice, 1, "first", RPC, "https://f.example.com", "")
	uassert.NoError(t, err)
	fl, err := r.Register(alice, 1, "first", RPC, "https://flagged.example.com", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewEndpoint(fl, Flagged, zr(r, fl), erev(r, fl), curator, 1, "spam"))
	uassert.NoError(t, r.ReviewZone("first", Rejected, rev(r, "first"), curator, 2, "dup"))
	for i := 0; i < MaxRejected; i++ {
		slug := "rej" + strconv.Itoa(i)
		uassert.NoError(t, r.Propose(testAddr(i), 3, slug, onyx()))
		uassert.NoError(t, r.ReviewZone(slug, Rejected, rev(r, slug), curator, 4, "spam"))
	}
	_, ok := r.Zone("first")
	uassert.False(t, ok)
	_, total := r.Count("first")
	uassert.Equal(t, 0, total)
	uassert.Equal(t, 0, r.OwnerCount("first", alice))
	uassert.Equal(t, 0, r.EndpointCount("first", RPC))
	uassert.NoError(t, r.Propose(alice, 5, "first", onyx()))
	// Neither the review queue nor the flag count of the evicted zone carries
	// over to the slug proposed again.
	uassert.Equal(t, 0, r.Awaiting("first"))
	_, err = r.Register(alice, 5, "first", RPC, "https://f.example.com", "")
	uassert.NoError(t, err)
	uassert.Equal(t, 1, r.Awaiting("first"))
}

// Approving a rejected or retired zone back into the live registry respects
// its cap.
func TestReviveRespectsTheLiveCap(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "back", onyx()))
	uassert.NoError(t, r.ReviewZone("back", Rejected, rev(r, "back"), curator, 1, "not yet"))
	for i := 0; i < MaxZones; i++ {
		slug := "z" + strconv.Itoa(i)
		uassert.NoError(t, r.ProposeExempt(curator, 2, slug, onyx()))
		uassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 2, ""))
	}
	uassert.Equal(t, MaxZones, r.Live())
	uassert.ErrorContains(t, r.ReviewZone("back", Approved, rev(r, "back"), curator, 3, ""), "full at")
	uassert.ErrorContains(t, r.Propose(bob, 3, "more", onyx()), "full at")
	uassert.NoError(t, r.ReviewZone("z0", Retired, rev(r, "z0"), curator, 3, "stopped"))
	uassert.NoError(t, r.ReviewZone("back", Approved, rev(r, "back"), curator, 4, ""))
}

func TestUppercaseAddressesAreRefused(t *testing.T) {
	r := NewRegistry()
	upper := address(strings.ToUpper(alice.String()))
	uassert.True(t, upper.IsValid(), "bech32 itself decodes the uppercase form")
	uassert.False(t, ValidAddress(upper))
	uassert.ErrorContains(t, r.Propose(upper, 1, "onyx", onyx()), "lowercase")
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	_, err := r.Register(upper, 1, "onyx", RPC, "https://a.example.com", "")
	uassert.ErrorContains(t, err, "lowercase")
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), upper, 2, ""), "lowercase")
}

// A peer is stored lowercased whole, so the listed form is the one tm2 dials,
// and two spellings of one host are one peer.
func TestPeerStoredLowercase(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	id, err := r.Register(alice, 1, "onyx", Peer, nodeID+"@SEED-1.Onyx.example.com:26656", "")
	uassert.NoError(t, err)
	e, _ := r.Endpoint(id)
	uassert.Equal(t, nodeID+"@seed-1.onyx.example.com:26656", e.Address)
	_, err = r.Register(alice, 1, "onyx", Peer, nodeID+"@seed-1.onyx.example.com:26656", "")
	uassert.ErrorContains(t, err, "already lists that peer")
	got, ok := r.EndpointByAddress("onyx", Peer, nodeID+"@Seed-1.onyx.example.com:26656")
	uassert.True(t, ok)
	uassert.Equal(t, id, got.ID)
}

// Rejecting sends what was verified on the proposal back to unverified: a
// rejected zone was never vouched for, so nothing on it reads as checked.
func TestRejectUnverifies(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	id, err := r.Register(alice, 1, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 2, ""))
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), curator, 3, "not a gno chain"))
	e, _ := r.Endpoint(id)
	uassert.Equal(t, string(Unverified), string(e.Status))
	uassert.Equal(t, ZoneRejected, e.Reason)
	uassert.Equal(t, curator.String(), e.ReviewedBy.String())
	v, _ := r.Count("onyx")
	uassert.Equal(t, 0, v)
}

// Eviction goes by when a zone entered its state, not when it was proposed: a
// long-lived network retired today is not the next record to go.
func TestEvictionIsByEntryOrder(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(curator, 1, "mainnet", onyx())) // proposed first
	uassert.NoError(t, r.ReviewZone("mainnet", Approved, rev(r, "mainnet"), curator, 1, ""))
	for i := 0; i < MaxRetired; i++ {
		slug := "ret" + strconv.Itoa(i)
		uassert.NoError(t, r.Propose(curator, 2, slug, onyx()))
		uassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 2, ""))
		uassert.NoError(t, r.ReviewZone(slug, Retired, rev(r, slug), curator, 3, "stopped"))
	}
	// Retiring mainnet now drops ret0, the zone retired longest ago.
	uassert.NoError(t, r.ReviewZone("mainnet", Retired, rev(r, "mainnet"), curator, 4, "end of an era"))
	_, ok := r.Zone("ret0")
	uassert.False(t, ok)
	// And the next retirement drops ret1, not mainnet.
	uassert.NoError(t, r.Propose(curator, 5, "next", onyx()))
	uassert.NoError(t, r.ReviewZone("next", Approved, rev(r, "next"), curator, 5, ""))
	uassert.NoError(t, r.ReviewZone("next", Retired, rev(r, "next"), curator, 6, "stopped"))
	_, ok = r.Zone("mainnet")
	uassert.True(t, ok)
	_, ok = r.Zone("ret1")
	uassert.False(t, ok)
}

// Every decision on a zone names the revision it was made on.
func TestEveryZoneDecisionIsRevisionBound(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	old := rev(r, "onyx")
	edited := onyx()
	edited.Title = "Onyx, edited"
	uassert.NoError(t, r.Edit("onyx", old, edited, alice, 2, ""))
	uassert.ErrorContains(t, r.Edit("onyx", old, onyx(), curator, 3, ""), "changed since you read it")
	uassert.ErrorContains(t, r.ReviewZone("onyx", Rejected, old, curator, 3, "spam"), "changed since you read it")
	uassert.ErrorContains(t, r.RemoveZone("onyx", old), "changed since you read it")
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 3, ""))
	uassert.ErrorContains(t, r.ReviewZone("onyx", Retired, old, curator, 4, "gone"), "changed since you read it")
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 4, "gone"))
}

func TestCanonicalHostAndTextEdgeCases(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	// A peer's host loses its terminal dot, so the two spellings are one peer.
	_, err := r.Register(alice, 1, "onyx", Peer, nodeID+"@seed-1.onyx.example.com:26656", "")
	uassert.NoError(t, err)
	_, err = r.Register(alice, 1, "onyx", Peer, nodeID+"@seed-1.onyx.example.com.:26656", "")
	uassert.ErrorContains(t, err, "already lists that peer")
	// An IPv4 host with a terminal dot is refused: Go's dialer cannot use it.
	uassert.ErrorContains(t, ValidateEndpoint(RPC, "http://1.2.3.4.:26657"), "DNS name or an IPv4")
	uassert.ErrorContains(t, ValidateEndpoint(Peer, nodeID+"@1.2.3.4.:26656"), "DNS name or an IPv4")
	// A loopback or private host is a local zone's only.
	_, err = r.Register(alice, 1, "onyx", RPC, "http://127.0.0.1:26657", "")
	uassert.ErrorContains(t, err, "private or special-use")
	_, err = r.Register(alice, 1, "onyx", Peer, nodeID+"@10.1.2.3:26656", "")
	uassert.ErrorContains(t, err, "private or special-use")
	local := onyx()
	local.Kind, local.RPCURL = Local, "http://127.0.0.1:26657"
	uassert.NoError(t, r.Propose(alice, 1, "mine", local))
	_, err = r.Register(alice, 1, "mine", Peer, nodeID+"@127.0.0.1:26656", "")
	uassert.NoError(t, err)
	// Equivalent URL spellings are one endpoint.
	for _, pair := range [][2]string{
		{"https://h.example.com/path", "https://h.example.com/path?"},
		{"https://h.example.com?a=1", "https://h.example.com/?a=1"},
		{"https://h.example.com/%2F", "https://h.example.com/%2f"},
	} {
		uassert.Equal(t, Canonical(Indexer, pair[0]), Canonical(Indexer, pair[1]), pair[0])
	}
	uassert.ErrorContains(t, ValidateEndpoint(Indexer, "https://h.example.com/%7e"), "needs no escaping")
	uassert.ErrorContains(t, ValidateEndpoint(Indexer, "https://h.example.com/%41"), "needs no escaping")
	// Look-alike badges and characters that draw nothing.
	in := onyx()
	for _, title := range []string{"✔ official", "☑ mainnet", "\U0001D159", "main\U000E0100net", "x\ue000", "\u180b", "\u0378"} {
		in.Title = title
		uassert.Error(t, ValidateInfo(in), title)
	}
}

// The per-proposer and per-registrant caps are counts, and they follow every
// way a zone or an endpoint leaves.
func TestCountersFollowRemovals(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	a, _ := r.Register(alice, 1, "onyx", RPC, "https://a.example.com", "")
	_, _ = r.Register(alice, 1, "onyx", RPC, "https://b.example.com", "")
	uassert.Equal(t, 2, r.OwnerCount("onyx", alice))
	uassert.NoError(t, r.RemoveEndpoint(a, erev(r, a)))
	uassert.Equal(t, 1, r.OwnerCount("onyx", alice))
	uassert.NoError(t, r.RemoveZone("onyx", rev(r, "onyx")))
	uassert.Equal(t, 0, r.OwnerCount("onyx", alice))
	for i := 0; i < MaxPendingPerProposer; i++ {
		uassert.NoError(t, r.Propose(alice, 2, "p"+strconv.Itoa(i), onyx()))
	}
	uassert.ErrorContains(t, r.Propose(alice, 2, "over", onyx()), "pending proposals")
	uassert.NoError(t, r.ReviewZone("p0", Approved, rev(r, "p0"), curator, 3, ""))
	uassert.NoError(t, r.Propose(alice, 3, "over", onyx()))
}

func TestSoleApproved(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(curator, 1, "za", onyx()))
	_, ok := r.SoleApproved("onyx-1")
	uassert.False(t, ok, "pending is not approved")
	uassert.NoError(t, r.ReviewZone("za", Approved, rev(r, "za"), curator, 1, ""))
	z, ok := r.SoleApproved("onyx-1")
	uassert.True(t, ok)
	uassert.Equal(t, "za", z.Slug)
	uassert.NoError(t, r.Propose(curator, 1, "zb", onyx()))
	uassert.NoError(t, r.ReviewZone("zb", Approved, rev(r, "zb"), curator, 1, ""))
	_, ok = r.SoleApproved("onyx-1")
	uassert.False(t, ok, "two approved zones share it: no guess")
}

// A status change bumps the revision too: an approval prepared before a
// colleague's rejection fails instead of quietly reversing it.
func TestStatusChangeBumpsTheRevision(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	read := rev(r, "onyx")
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, read, bob, 2, "phishing RPC"))
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, read, curator, 3, ""), "changed since you read it")
	z, _ := r.Zone("onyx")
	uassert.Equal(t, "phishing RPC", z.Reason)
}

// Leaving the local kind drops the private endpoints in the same edit, so
// nobody can block the edit by registering one again after each removal.
func TestLeavingLocalDropsPrivateEndpoints(t *testing.T) {
	r := NewRegistry()
	local := onyx()
	local.Kind, local.RPCURL = Local, "http://127.0.0.1:26657"
	uassert.NoError(t, r.Propose(alice, 1, "mine", local))
	priv, err := r.Register(alice, 1, "mine", Peer, nodeID+"@10.0.0.5:26656", "")
	uassert.NoError(t, err)
	flagged, err := r.Register(bob, 1, "mine", RPC, "http://localhost:1", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.ReviewEndpoint(flagged, Flagged, zr(r, flagged), erev(r, flagged), curator, 1, "squatting"))
	pub, err := r.Register(alice, 1, "mine", RPC, "https://rpc.mine.example.com", "")
	uassert.NoError(t, err)
	// A ruled one is a record: the edit refuses to drop it unseen, and a
	// curator removes it first.
	uassert.ErrorContains(t, r.Edit("mine", rev(r, "mine"), onyx(), alice, 2, ""), "which a curator ruled on")
	uassert.NoError(t, r.RemoveEndpoint(flagged, erev(r, flagged)))
	uassert.NoError(t, r.Edit("mine", rev(r, "mine"), onyx(), alice, 2, ""))
	for _, id := range []int64{priv, flagged} {
		_, ok := r.Endpoint(id)
		uassert.False(t, ok, "a private endpoint is dropped")
	}
	_, ok := r.Endpoint(pub)
	uassert.True(t, ok, "a public one stays")
	uassert.Equal(t, 1, r.EndpointCount("mine", ""))
	uassert.Equal(t, 0, r.OwnerCount("mine", bob))
	uassert.Equal(t, 1, r.Awaiting("mine"))
}

// A curator's chain-id edit of a pending zone names the curator on the resets;
// only the proposer's own edit records nobody.
func TestResetNamesACuratorEditor(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	id, _ := r.Register(alice, 1, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 2, ""))
	moved := onyx()
	moved.ChainID = "onyx-2"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), moved, curator, 3, ""))
	e, _ := r.Endpoint(id)
	uassert.Equal(t, curator.String(), e.ReviewedBy.String())
}

func TestPrivateHostsAndURLForms(t *testing.T) {
	for _, h := range []string{"validator", "node", "printer.local", "metadata.google.internal", "router.home.arpa",
		"foo.localdomain", "a.localhost", "192.0.0.1", "198.18.0.1", "198.19.255.255", "224.0.0.1", "255.255.255.255",
		"127.1", "0x7f.1", "2130706433",
		"rpc.test", "node.lan", "nas.home", "dc.corp", "wiki.intranet", "box.private", "x.onion", "y.alt",
		"192.0.2.1", "198.51.100.7", "203.0.113.255",
		"gno.example", "x.invalid", "rpc.mail", "ipv4only.arpa", "gnoland.default.service.arpa", "x.arpa",
		"100.127.255.255", "172.16.0.1", "172.31.255.255", "svc.service.consul", "node.lxd", "x.docker", "y.localnet"} {
		uassert.True(t, IsPrivateHost(h), h)
	}
	for _, h := range []string{"rpc.gno.land", "1.1.1.1", "198.20.0.1", "172.32.0.1", "172.15.255.255", "gno.land.", "100.128.0.1",
		"a.latest", "my.salt", "192.0.3.1", "198.51.101.1", "203.0.114.1",
		"example.com", "gmail.com", "arpa.example.com"} {
		uassert.False(t, IsPrivateHost(h), h)
	}
	// tcp:// and http:// are one rpc endpoint, the way gnokey dials them.
	uassert.Equal(t, Canonical(RPC, "tcp://h.example.com:26657"), Canonical(RPC, "http://h.example.com:26657"))
	uassert.Equal(t, Canonical(RPC, "tcp://h.example.com:80"), Canonical(RPC, "http://h.example.com"))
	// An empty query's ? goes; a query ending in ? keeps it.
	uassert.Equal(t, "https://h.example.com/p?a?", Canonical(Indexer, "https://h.example.com/p?a?"))
	// . and .. path segments are another spelling: refused.
	for _, u := range []string{"https://h.example.com/.", "https://h.example.com/./x", "https://h.example.com/a/..", "https://h.example.com/../a"} {
		uassert.ErrorContains(t, ValidateEndpoint(Indexer, u), "path segment", u)
	}
	uassert.NoError(t, ValidateEndpoint(Indexer, "https://h.example.com/a.b/..c/x."))
	in := onyx()
	for _, title := range []string{"⌛ pending", "❎ rejected", "\U0001F6D1 stop", "☒ no"} {
		in.Title = title
		uassert.ErrorContains(t, ValidateInfo(in), "status glyph", title)
	}
}

// A copied Registry value is the same registry: it shares the revision
// counter with the zones it shares, so no revision is handed out twice. With
// the counter inline, an edit through the copy and then one through the
// original would both produce the same revision number, and a decision made on
// the first content would pass against the second.
func TestCopiedRegistryIsTheSameRegistry(t *testing.T) {
	r1 := NewRegistry()
	uassert.NoError(t, r1.Propose(alice, 1, "onyx", onyx()))
	r2 := *r1
	in := onyx()
	in.Title = "via the copy"
	uassert.NoError(t, r2.Edit("onyx", rev(r1, "onyx"), in, alice, 2, ""))
	seen := rev(r1, "onyx") // what a curator read: the copy's content
	in.Title = "via the original"
	uassert.NoError(t, r1.Edit("onyx", seen, in, alice, 3, ""))
	uassert.True(t, rev(r1, "onyx") != seen, "a new content, a new revision")
	uassert.ErrorContains(t, r1.ReviewZone("onyx", Approved, seen, curator, 4, ""), "changed since you read it")
}

// Editing a local zone that stays local drops nothing, and every Info URL is
// checked for a private host, not only the main RPC.
func TestOnlyLeavingLocalDrops(t *testing.T) {
	r := NewRegistry()
	local := onyx()
	local.Kind, local.RPCURL = Local, "http://127.0.0.1:26657"
	uassert.NoError(t, r.Propose(alice, 1, "mine", local))
	id, err := r.Register(alice, 1, "mine", Peer, nodeID+"@10.0.0.5:26656", "")
	uassert.NoError(t, err)
	local.Title = "Mine, renamed"
	uassert.NoError(t, r.Edit("mine", rev(r, "mine"), local, alice, 2, ""))
	_, ok := r.Endpoint(id)
	uassert.True(t, ok, "a local zone keeps its private endpoints")

	for _, set := range []func(*Info){
		func(in *Info) { in.GnowebURL = "http://192.168.1.2" },
		func(in *Info) { in.GenesisURL = "https://files.lan/genesis.json" },
	} {
		in := onyx()
		set(&in)
		uassert.ErrorContains(t, ValidateInfo(in), "private or special-use")
	}
}

// Any edit to an approved zone is a review on record, so a chain-id reset it
// causes names its editor, whoever that is; only a pending zone's own
// proposer resets as nobody.
func TestApprovedEditResetNamesTheEditor(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 2, ""))
	id, _ := r.Register(bob, 3, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 4, ""))
	moved := onyx()
	moved.ChainID = "onyx-2"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), moved, alice, 5, "relaunched"))
	e, _ := r.Endpoint(id)
	uassert.Equal(t, alice.String(), e.ReviewedBy.String())
}

// A curator's exemption is from the review queue, never from the live cap.
func TestExemptStillMeetsTheLiveCap(t *testing.T) {
	r := NewRegistry()
	for i := 0; i < MaxZones; i++ {
		slug := "z" + strconv.Itoa(i)
		uassert.NoError(t, r.ProposeExempt(curator, 1, slug, onyx()))
		uassert.NoError(t, r.ReviewZone(slug, Approved, rev(r, slug), curator, 1, ""))
	}
	uassert.ErrorContains(t, r.ProposeExempt(curator, 2, "one-more", onyx()), "the registry is full")
}

// The URL forms each kind dials: a tcp:// rpc is host and port only, an
// indexer may be a websocket, and IsPrivateHost fails closed on anything but a
// bare host.
func TestURLFormsPerKind(t *testing.T) {
	uassert.ErrorContains(t, ValidateEndpoint(RPC, "tcp://rpc.example.com:26657/websocket"), "host and port only")
	uassert.ErrorContains(t, ValidateEndpoint(RPC, "tcp://rpc.example.com:26657?x=1"), "host and port only")
	uassert.NoError(t, ValidateEndpoint(RPC, "tcp://rpc.example.com:26657"))
	uassert.NoError(t, ValidateEndpoint(RPC, "wss://rpc.example.com/websocket"))
	uassert.NoError(t, ValidateEndpoint(Indexer, "wss://indexer.example.com/graphql/query"))
	uassert.Error(t, ValidateEndpoint(Faucet, "wss://faucet.example.com"))
	for _, h := range []string{"127.0.0.1:26657", "10.0.0.1/", "foo.local:80", "a b", "192.88.99.1"} {
		uassert.True(t, IsPrivateHost(h), h)
	}
}

// A rejection or a retirement is restated with a new reason, the only way to
// correct one, without a second eviction or reset.
func TestARejectionReasonCanBeRestated(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), curator, 2, "wrong netwrok"))
	entered := func() int64 { z, _ := r.Zone("onyx"); return z.Entered }
	before := entered()
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), bob, 3, "wrong network"))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, "wrong network", z.Reason)
	uassert.Equal(t, bob.String(), z.ReviewedBy.String())
	uassert.Equal(t, before, entered(), "a restatement is not a new entry")
	uassert.ErrorContains(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), bob, 4, "wrong network"), "already rejected")
}

// Flagging a verified endpoint puts it back in the unchecked index, so counts
// and a later reset see it as what it is.
func TestFlaggingAVerifiedEndpointUnchecksIt(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))
	id, _ := r.Register(bob, 2, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 3, ""))
	uassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), carol, 4, "down"))
	v, total := r.Count("onyx")
	uassert.Equal(t, 0, v)
	uassert.Equal(t, 1, total)
	uassert.Equal(t, 0, r.Awaiting("onyx"))
	// A retirement then keeps the flag: it resets only what is verified.
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 5, "shut down"))
	e, _ := r.Endpoint(id)
	uassert.Equal(t, string(Flagged), string(e.Status))
	// A restated verdict names its new reviewer.
	uassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 6, "down for good"))
	e, _ = r.Endpoint(id)
	uassert.Equal(t, curator.String(), e.ReviewedBy.String())
}

// A reset moves the endpoint's revision, so a verdict written against the
// verified endpoint fails after a retirement reset it.
func TestAResetMovesTheEndpointRevision(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))
	id, _ := r.Register(bob, 2, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 3, ""))
	read := erev(r, id)
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 4, "shut down"))
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Flagged, zr(r, id), read, carol, 5, "x"), "changed since")
}

// The package README's example, verbatim but for must and the names: it is
// the first thing an importer copies, so it is run.
func TestTheReadmeExampleRuns(t *testing.T) {
	proposer, height := alice, int64(1)
	r := NewRegistry()
	uassert.NoError(t, r.Propose(proposer, height, "onyx", Info{ChainID: "onyx-1", Title: "Onyx",
		Kind: Testnet, RPCURL: "https://rpc.onyx.testnets.gno.land"}))
	z, _ := r.Zone("onyx")
	uassert.NoError(t, r.ReviewZone("onyx", Approved, z.Revision, curator, height, ""))
	z, _ = r.Zone("onyx")
	id, err := r.Register(proposer, height, "onyx", Peer,
		"g1x5mlj5ava0dw9vkf4j6admjlzswm6f06p44krn@seed-1.onyx.testnets.gno.land:26656", "gno core")
	uassert.NoError(t, err)
	e, _ := r.Endpoint(id)
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, z.Revision, e.Revision, curator, height, "answers onyx-1"))
	uassert.Equal(t, 1, len(r.Endpoints(EndpointFilter{Zone: "onyx", Kind: Peer, Status: Verified})))
}

// A verification restated with a new reason names its new reviewer, and a
// zone removed and proposed again starts with no private endpoints on record.
func TestRestatedVerifyAndARemovedZonesPrivateIndex(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	id, _ := r.Register(alice, 1, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 2, "answers"))
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), carol, 3, "answers, re-probed"))
	e, _ := r.Endpoint(id)
	uassert.Equal(t, carol.String(), e.ReviewedBy.String())

	local := onyx()
	local.Kind, local.RPCURL = Local, "http://127.0.0.1:26657"
	uassert.NoError(t, r.Propose(alice, 4, "lab", local))
	_, err := r.Register(alice, 4, "lab", RPC, "http://10.0.0.1:26657", "")
	uassert.NoError(t, err)
	uassert.NoError(t, r.RemoveZone("lab", rev(r, "lab")))
	uassert.NoError(t, r.Propose(alice, 5, "lab", local))
	uassert.Equal(t, 0, len(r.PrivateEndpoints("lab")))
	uassert.NoError(t, r.Edit("lab", rev(r, "lab"), onyx(), alice, 6, ""))
}

// A zone decision naming a revision from the future fails as a stale one does.
func TestAFutureRevisionIsRefused(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, rev(r, "onyx")+1, curator, 2, ""), "changed since you read it")
}

// Restating: any review state with a new visible reason, bumping the
// revision; never with an empty or the same reason.
func TestRestatementRules(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 2, "answers onyx-1"))
	read := rev(r, "onyx")
	uassert.NoError(t, r.ReviewZone("onyx", Approved, read, carol, 3, "answers onyx-1, re-probed"))
	uassert.True(t, rev(r, "onyx") > read, "a restatement moves the revision")
	uassert.ErrorContains(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), carol, 4, " "), "already approved")
	id, _ := r.Register(bob, 4, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 4, "down"))
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), curator, 4, ""), "needs a new reason")
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), curator, 5, "shut down"))
	uassert.NoError(t, r.ReviewZone("onyx", Retired, rev(r, "onyx"), carol, 6, "shut down 2026-10-01"))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, "shut down 2026-10-01", z.Reason)

}

// What a URL is stored as: scheme and host lowercased in ASCII only, the path
// and query as typed; a letter that lowercases into ASCII is refused, not
// folded. A tcp:// rpc path is refused whatever the scheme's case.
func TestStoredURLForm(t *testing.T) {
	r := NewRegistry()
	in := onyx()
	in.GenesisURL = "HTTPS://Files.Example.com/G?Q=1"
	uassert.NoError(t, r.Propose(alice, 1, "onyx", in))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, "https://files.example.com/G?Q=1", z.GenesisURL)
	id, err := r.Register(alice, 1, "onyx", Indexer, "HTTPS://Idx.Example.com?Q=1", "")
	uassert.NoError(t, err)
	e, _ := r.Endpoint(id)
	uassert.Equal(t, "https://idx.example.com?Q=1", e.Address)
	for _, u := range []string{"https://Key.example.com", "https://rpc.İnfo.example.com"} {
		bad := onyx()
		bad.RPCURL = u
		uassert.Error(t, r.Propose(bob, 2, "x"+strconv.Itoa(len(u)), bad), u)
	}
	uassert.ErrorContains(t, ValidateEndpoint(RPC, "TCP://h.example.com:26657/websocket"), "host and port only")
	uassert.False(t, IsPrivateHost("RPC.GNO.LAND"))
	uassert.ErrorContains(t, ValidateEndpoint(RPC, "https://café.example.com"), "'é'")
}

// A curator's leave-local edit is refused while a private endpoint carries a
// ruling of any kind: a reset's reason, a reasonless unverify, a verification;
// a curator who proposed the zone included.
func TestLeavingLocalRefusesEveryRuling(t *testing.T) {
	setup := func() (*Registry, int64) {
		r := NewRegistry()
		local := onyx()
		local.Kind, local.RPCURL = Local, "http://127.0.0.1:26657"
		uassert.NoError(t, r.Propose(curator, 1, "lab", local))
		id, err := r.Register(curator, 1, "lab", RPC, "http://10.0.0.1:26657", "")
		uassert.NoError(t, err)
		return r, id
	}
	r, id := setup()
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), carol, 2, ""))
	uassert.ErrorContains(t, r.Edit("lab", rev(r, "lab"), onyx(), curator, 3, ""), "is verified")

	r, id = setup()
	uassert.NoError(t, r.ReviewEndpoint(id, Flagged, zr(r, id), erev(r, id), carol, 2, "x"))
	uassert.NoError(t, r.ReviewEndpoint(id, Unverified, zr(r, id), erev(r, id), carol, 3, ""))
	uassert.ErrorContains(t, r.Edit("lab", rev(r, "lab"), onyx(), curator, 4, ""), "a curator ruled on")

	r, id = setup()
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), carol, 2, ""))
	moved := onyx()
	moved.Kind, moved.RPCURL, moved.ChainID = Local, "http://127.0.0.1:26657", "lab-2"
	uassert.NoError(t, r.Edit("lab", rev(r, "lab"), moved, curator, 3, "")) // the proposer's reset: no reviewer, a reason
	e, _ := r.Endpoint(id)
	uassert.Equal(t, "", e.ReviewedBy.String())
	uassert.ErrorContains(t, r.Edit("lab", rev(r, "lab"), onyx(), curator, 4, ""), "a curator ruled on")
}

// Clearable counts what a bulk clear may remove: registered through the gate,
// never ruled on. A first verdict or a removal takes one out (a reset cannot:
// it touches only verified endpoints); an exempt registration never counts.
func TestTheClearableCount(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))
	a, _ := r.Register(bob, 2, "onyx", RPC, "https://a.example.com", "")
	b, _ := r.Register(bob, 2, "onyx", RPC, "https://b.example.com", "")
	c, _ := r.Register(bob, 2, "onyx", RPC, "https://c.example.com", "")
	x, _ := r.RegisterExempt(curator, 2, "onyx", RPC, "https://x.example.com", "")
	ex, _ := r.Endpoint(x)
	uassert.True(t, ex.Exempt)
	uassert.False(t, ex.Clearable())
	uassert.Equal(t, 3, r.Clearable("onyx"))
	uassert.NoError(t, r.ReviewEndpoint(a, Verified, zr(r, a), erev(r, a), curator, 3, ""))
	uassert.Equal(t, 2, r.Clearable("onyx"))
	uassert.NoError(t, r.ReviewEndpoint(a, Flagged, zr(r, a), erev(r, a), curator, 3, "down"))
	uassert.Equal(t, 2, r.Clearable("onyx"), "a second verdict changes nothing")
	uassert.NoError(t, r.RemoveEndpoint(b, erev(r, b)))
	uassert.Equal(t, 1, r.Clearable("onyx"))
	moved := onyx()
	moved.ChainID = "onyx-2"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), moved, curator, 4, "relaunch"))
	uassert.Equal(t, 1, r.Clearable("onyx"), "a reset touches only verified endpoints")
	_ = c
}

// One edit off the local kind drops at most MaxDropPerEdit endpoints.
func TestLeavingLocalDropsAtMostTheCap(t *testing.T) {
	r := NewRegistry()
	local := onyx()
	local.Kind, local.RPCURL = Local, "http://127.0.0.1:26657"
	uassert.NoError(t, r.Propose(curator, 1, "lab", local))
	for i := 0; i <= MaxDropPerEdit; i++ {
		_, err := r.RegisterExempt(curator, 1, "lab", RPC, "http://10.0.0."+strconv.Itoa(i%250+1)+":"+strconv.Itoa(26000+i), "")
		uassert.NoError(t, err)
	}
	uassert.ErrorContains(t, r.Edit("lab", rev(r, "lab"), onyx(), curator, 2, ""), "more than 64 in one edit")
	ids := r.PrivateEndpoints("lab")
	uassert.NoError(t, r.RemoveEndpoint(ids[0].ID, ids[0].Revision))
	uassert.NoError(t, r.Edit("lab", rev(r, "lab"), onyx(), curator, 3, ""))
}

// The numbers the READMEs state, pinned: a change to one is a change to what
// the docs promise.
func TestTheDocumentedBounds(t *testing.T) {
	for name, got := range map[string]int{"MaxZones": MaxZones, "MaxPending": MaxPending, "MaxPendingPerProposer": MaxPendingPerProposer,
		"MaxRejected": MaxRejected, "MaxRetired": MaxRetired, "MaxEndpointsPerZone": MaxEndpointsPerZone,
		"MaxUnverifiedPerZone": MaxUnverifiedPerZone, "MaxEndpointsPerAddress": MaxEndpointsPerAddress, "MaxDropPerEdit": MaxDropPerEdit,
		"MaxTitleLen": MaxTitleLen, "MaxDescriptionLen": MaxDescriptionLen, "MaxLabelLen": MaxLabelLen, "MaxReasonLen": MaxReasonLen, "MaxURLLen": MaxURLLen} {
		want := map[string]int{"MaxZones": 256, "MaxPending": 64, "MaxPendingPerProposer": 4, "MaxRejected": 64, "MaxRetired": 128,
			"MaxEndpointsPerZone": 128, "MaxUnverifiedPerZone": 64, "MaxEndpointsPerAddress": 16, "MaxDropPerEdit": 64,
			"MaxTitleLen": 64, "MaxDescriptionLen": 512, "MaxLabelLen": 64, "MaxReasonLen": 280, "MaxURLLen": 256}[name]
		uassert.Equal(t, want, got, name)
	}
}

// Rules the other tests reach only in part.
func TestValidationEdges(t *testing.T) {
	// A private host is refused on every kind but local.
	for _, k := range []Kind{Mainnet, Testnet, Devnet} {
		in := onyx()
		in.Kind, in.RPCURL = k, "http://10.0.0.1:26657"
		uassert.ErrorContains(t, ValidateInfo(in), "private or special-use", string(k))
	}
	// The combining grapheme joiner draws nothing.
	in := onyx()
	in.Title = "On\u034fyx"
	uassert.ErrorContains(t, ValidateInfo(in), "invisible")
	// Needless escapes of unreserved characters, and an entity shape.
	for _, u := range []string{"https://h.example.com/a%5Fb", "https://h.example.com/a%2Db", "https://h.example.com/%2E%2E/x",
		"https://h.example.com/a&#38;b"} {
		uassert.Error(t, ValidateEndpoint(RPC, u), u)
	}
	// Dot segments are a path rule; a query may hold dots.
	uassert.NoError(t, ValidateEndpoint(Explorer, "https://h.example.com/p?x=../y"))
	// Default websocket ports are dropped like the http ones.
	uassert.Equal(t, Canonical(RPC, "wss://h.example.com/ws"), Canonical(RPC, "wss://h.example.com:443/ws"))
	uassert.Equal(t, Canonical(RPC, "ws://h.example.com/ws"), Canonical(RPC, "ws://h.example.com:80/ws"))
}

// What a caller types is trimmed before it is used: the kind, a label, a
// reason; and a restatement of verify or unverify needs a new visible reason.
func TestTrimsAndRestatementReasons(t *testing.T) {
	r := NewRegistry()
	in := onyx()
	in.Kind = " testnet "
	uassert.NoError(t, r.Propose(alice, 1, "onyx", in))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, string(Testnet), string(z.Kind))
	uassert.NoError(t, r.ReviewZone("onyx", Approved, rev(r, "onyx"), curator, 1, ""))
	id, _ := r.Register(bob, 2, "onyx", RPC, "https://a.example.com", "  bob's node  ")
	e, _ := r.Endpoint(id)
	uassert.Equal(t, "bob's node", e.Label)
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 3, "  answers  "))
	e, _ = r.Endpoint(id)
	uassert.Equal(t, "answers", e.Reason)
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Verified, zr(r, id), erev(r, id), curator, 4, " "), "needs a new reason")
	uassert.NoError(t, r.ReviewEndpoint(id, Unverified, zr(r, id), erev(r, id), curator, 5, "x"))
	uassert.ErrorContains(t, r.ReviewEndpoint(id, Unverified, zr(r, id), erev(r, id), curator, 6, ""), "needs a new reason")
	edited := onyx()
	edited.Title = "Onyx, edited"
	uassert.NoError(t, r.Edit("onyx", rev(r, "onyx"), edited, curator, 7, "  retitled  "))
	z, _ = r.Zone("onyx")
	uassert.Equal(t, "retitled", z.Reason)
	uassert.Equal(t, rev(r, "onyx"), r.Revision(), "the last revision handed out")
}

// A zone removed and proposed again starts with nothing clearable.
func TestARemovedZonesClearableCountIsGone(t *testing.T) {
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	_, err := r.Register(alice, 1, "onyx", RPC, "https://a.example.com", "")
	uassert.NoError(t, err)
	uassert.Equal(t, 1, r.Clearable("onyx"))
	uassert.NoError(t, r.RemoveZone("onyx", rev(r, "onyx")))
	uassert.NoError(t, r.Propose(alice, 2, "onyx", onyx()))
	uassert.Equal(t, 0, r.Clearable("onyx"))
}

// URL characters, escapes, schemes, selectors, Parse trimming, pending
// restatement and stored tails.
func TestURLAndTextRules(t *testing.T) {
	// Every character a URL may not hold, one at a time.
	for _, c := range []string{"<", ">", "`", "(", ")", "[", "]", "{", "}", "|", "\\", "^", "#", "\"", "'"} {
		uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/a"+c+"b"), c)
	}
	// A needless escape of a digit or a lowercase letter; the hex case of the
	// first escape digit.
	uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/a%30"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/a%61"))
	uassert.Equal(t, Canonical(RPC, "https://h.example.com/%af"), Canonical(RPC, "https://h.example.com/%AF"))
	// A hex last label reads as an IPv4 number.
	uassert.Error(t, ValidateEndpoint(RPC, "https://a.0x1"))
	uassert.True(t, IsPrivateHost("a.0x1"))
	uassert.True(t, IsPrivateHost("PRINTER.LOCAL"))
	// Schemes per field.
	in := onyx()
	in.GnowebURL = "tcp://onyx.example.com:26657"
	uassert.Error(t, ValidateInfo(in))
	uassert.Error(t, ValidateEndpoint(Indexer, "tcp://indexer.example.com:8546"))
	// Variation selectors only after a base they modify.
	for _, s := range []string{"a\ufe00", "᠀\u180b"} {
		in := onyx()
		in.Title = s
		uassert.ErrorContains(t, ValidateInfo(in), "invisible", s)
	}
	ok := onyx()
	ok.Title = "ᠨ\u180f"
	uassert.NoError(t, ValidateInfo(ok))
	uassert.False(t, HasVisible("\u200b\u200d"))
	// The Parse functions trim.
	st, err := ParseStatus(" approved ")
	uassert.NoError(t, err)
	uassert.Equal(t, string(Approved), string(st))
	k, err := ParseEndpointKind(" rpc ")
	uassert.NoError(t, err)
	uassert.Equal(t, string(RPC), string(k))
	v, err := ParseVerification(" verified ")
	uassert.NoError(t, err)
	uassert.Equal(t, string(Verified), string(v))
	// Nothing goes back to pending, not even as a restatement.
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	uassert.Error(t, r.ReviewZone("onyx", Pending, rev(r, "onyx"), curator, 2, "x"))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, "", z.ReviewedBy.String())
	// An empty query and a bare "/" are not stored, so the dialable spelling
	// is the one listed.
	id, err := r.Register(alice, 3, "onyx", RPC, "https://rpc2.zz.example.com/?", "")
	uassert.NoError(t, err)
	e, _ := r.Endpoint(id)
	uassert.Equal(t, "https://rpc2.zz.example.com", e.Address)
	_, err = r.Register(alice, 3, "onyx", RPC, "https://rpc2.zz.example.com", "")
	uassert.ErrorContains(t, err, "already lists")
	// More private suffixes, more look-alikes.
	for _, h := range []string{"rpc.node.incus", "web.dns.podman", "foo.i2p", "gnoland.default.svc"} {
		uassert.True(t, IsPrivateHost(h), h)
	}
	for _, r := range []rune{0x1FBBD, 0x1F6AD, 0x1F6AF, 0x1F6B1, 0x1F6B3, 0x1F6B7, 0x1F4F5, 0x1F51E, 0x1F10D, 0x1F10F, 0x1F16E} {
		uassert.Error(t, ValidateLabel(string(r)+" official"), string(r))
	}
}

// What is stored canonicalizes as what was typed, so a check made on the
// typed address (the realm's own-URL reservation) holds for the stored one.
func TestTheStoredFormKeepsItsCanonicalForm(t *testing.T) {
	for _, u := range []string{"https://h.example.com??", "https://h.example.com/??", "https://h.example.com?/",
		"https://h.example.com?path=/", "https://h.example.com/p?x=?", "https://h.example.com/p??", "https://h.example.com/?",
		"https://h.example.com/", "https://h.example.com?", "https://h.example.com/?q=1", "https://h.example.com/p/"} {
		uassert.Equal(t, Canonical(RPC, u), Canonical(RPC, trimEmptyTail(lowerAuthority(u))), u)
	}
	uassert.Equal(t, "https://h.example.com?path=/", trimEmptyTail("https://h.example.com?path=/"))
	uassert.Equal(t, "https://h.example.com??", trimEmptyTail("https://h.example.com??"))
}

// Spaces of every kind (Unicode Zs) and tabs are trimmed; a line separator at
// an edge reaches the validator and is refused, never silently cut. A zone's
// gnoweb and genesis URLs have an empty tail repaired, its main RPC is refused
// with one, and an endpoint is validated as it will be stored.
func TestTrimsSpacesNotLineBreaks(t *testing.T) {
	r := NewRegistry()
	in := onyx()
	in.Title = "Onyx\u2028"
	uassert.ErrorContains(t, r.Propose(alice, 1, "onyx", in), "control character")
	in = onyx()
	in.Description = "\u0085" + in.Description
	uassert.ErrorContains(t, r.Propose(alice, 1, "onyx", in), "control character")
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	_, err := r.Register(alice, 2, "onyx", RPC, "https://a.example.com", "operator\u2028")
	uassert.ErrorContains(t, err, "control character")
	uassert.Equal(t, "x", TrimSpaces(" \tx\t "))
	for _, u := range []string{"https://g.example.com/", "https://g.example.com?", "https://g.example.com/?"} {
		r := NewRegistry()
		in := onyx()
		in.GnowebURL, in.GenesisURL = u, u
		uassert.NoError(t, r.Propose(alice, 1, "xz", in), u)
		z, _ := r.Zone("xz")
		uassert.Equal(t, "https://g.example.com", z.GnowebURL, u)
		uassert.Equal(t, "https://g.example.com", z.GenesisURL, u)
	}
	for _, u := range []string{"https://rpc.example.com/", "https://rpc.example.com?"} {
		bad := onyx()
		bad.RPCURL = u
		uassert.Error(t, ValidateInfo(bad), u)
		uassert.Error(t, NewRegistry().Propose(alice, 1, "xz", bad), "the registry refuses it too: "+u)
	}
	uassert.Equal(t, "Onyx", TrimSpaces("\u00a0Onyx\u3000"))
	uassert.Equal(t, "Onyx\n", TrimSpaces("Onyx\n"))
	// ValidateEndpoint judges the string it is given; Register stores the
	// trimmed form and validates that.
	uassert.Error(t, ValidateEndpoint(RPC, "tcp://rpc.example.com:26657/"), "as given, it has a path")
	id, err := r.Register(alice, 2, "onyx", RPC, "tcp://rpc.example.com:26657/", "")
	uassert.NoError(t, err)
	e, _ := r.Endpoint(id)
	uassert.Equal(t, "tcp://rpc.example.com:26657", e.Address)
	long := "https://e.example.com/" + strings.Repeat("a", MaxURLLen-len("https://e.example.com/"))
	_, err = r.Register(alice, 2, "onyx", Explorer, long+"?", "")
	uassert.NoError(t, err, "257 bytes as typed, 256 as stored")
	_, err = r.Register(alice, 2, "onyx", Explorer, long+"b", "")
	uassert.Error(t, err, "257 as stored")
}

// Chain id charset, text and URL bounds, controls, escapes and trims.
func TestMoreBoundaries(t *testing.T) {
	in := onyx()
	in.ChainID = "onyx:1"
	uassert.Error(t, ValidateInfo(in))
	uassert.Error(t, ValidateReason(strings.Repeat("x", MaxReasonLen+1)))
	uassert.NoError(t, ValidateReason(strings.Repeat("x", MaxReasonLen)))
	uassert.Error(t, ValidateLabel(strings.Repeat("x", MaxLabelLen+1)))
	uassert.NoError(t, ValidateLabel(strings.Repeat("x", MaxLabelLen)))
	for _, c := range []string{"\x1f", "\x7f", "\u009f"} {
		uassert.ErrorContains(t, ValidateLabel("a"+c+"b"), "control character")
	}
	ok := onyx()
	ok.Title = "ᠠ\u180b"
	uassert.NoError(t, ValidateInfo(ok))
	host := "https://" + strings.Repeat("a", 20) + ".example.com/"
	long := host + strings.Repeat("p", MaxURLLen-len(host))
	uassert.NoError(t, ValidateEndpoint(RPC, long))
	uassert.Error(t, ValidateEndpoint(RPC, long+"p"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/a\x7fb"))
	uassert.NoError(t, ValidateEndpoint(Explorer, "https://h.example.com/a&;b"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/a%2z"))
	uassert.NoError(t, ValidateEndpoint(Explorer, "https://h.example.com/p?a=/../"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://a.0X1"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://256.1.1.1"))

	r := NewRegistry()
	in = onyx()
	in.Description = " \t" + in.Description + "\t "
	uassert.NoError(t, r.Propose(alice, 1, "onyx", in))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, onyx().Description, z.Description)
	edited := onyx()
	edited.Title = "Onyx, edited"
	uassert.ErrorContains(t, r.Edit("onyx", rev(r, "onyx"), edited, alice, 2, "x"), "takes no reason")
}

// Boundaries the suites reached only in part.
func TestFurtherBoundaries(t *testing.T) {
	uassert.ErrorContains(t, ValidateLabel(" "), "nothing visible")
	uassert.Error(t, ValidateLabel("a\U000E01EF"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/a%2!"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://h.example.com/%2d"))
	uassert.Error(t, ValidateEndpoint(RPC, "https://1.2.3.4.5"))
	uassert.Error(t, ValidateEndpoint(Peer, nodeID+"@"+strings.Repeat("a", 250)+".example.com:26656"))
	uassert.Equal(t, 16, ReservedForReviewers)

	r := NewRegistry()
	in := onyx()
	in.ChainID = " onyx-1 "
	uassert.NoError(t, r.Propose(alice, 1, "onyx", in))
	z, _ := r.Zone("onyx")
	uassert.Equal(t, "onyx-1", z.ChainID)
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), curator, 2, "first"))
	uassert.NoError(t, r.ReviewZone("onyx", Rejected, rev(r, "onyx"), carol, 9, "restated"))
	z, _ = r.Zone("onyx")
	uassert.Equal(t, int64(9), z.ReviewedAt, "a restatement records when")
}

// Round 13: rules that had no test of their own.
func TestRoundThirteenBoundaries(t *testing.T) {
	// HasVisible is exported, so its filler rule is its own, not checkText's.
	uassert.False(t, HasVisible("\u3164"), "a Hangul filler is not visible")
	uassert.True(t, HasVisible("a\u3164"))
	// A 0x last label is held to the address rule even when it is not hex.
	uassert.Error(t, ValidateEndpoint(RPC, "https://a.0xyz"))
	// A peer is at most MaxURLLen bytes, exactly.
	peer := func(n int) string {
		host := strings.Repeat("a", 63) + "." + strings.Repeat("b", 63) + "." + strings.Repeat("c", 63) + "."
		pre, post := nodeID+"@", ".com:26656"
		return pre + host + strings.Repeat("d", n-len(pre)-len(host)-len(post)) + post
	}
	uassert.Equal(t, MaxURLLen, len(peer(MaxURLLen)))
	uassert.NoError(t, ValidateEndpoint(Peer, peer(MaxURLLen)))
	uassert.Error(t, ValidateEndpoint(Peer, peer(MaxURLLen+1)))
	// A filtered list is capped at its length, so an importer's append copies
	// instead of writing into a slice it may not write.
	r := NewRegistry()
	uassert.NoError(t, r.Propose(alice, 1, "onyx", onyx()))
	for i := 0; i < 3; i++ {
		_, err := r.Register(alice, 1, "onyx", RPC, "https://r"+strconv.Itoa(i)+".example.com", "")
		uassert.NoError(t, err)
	}
	id, err := r.Register(alice, 1, "onyx", RPC, "https://v.example.com", "")
	uassert.NoError(t, err)
	e, _ := r.Endpoint(id)
	z, _ := r.Zone("onyx")
	uassert.NoError(t, r.ReviewEndpoint(id, Verified, z.Revision, e.Revision, alice, 1, ""))
	for _, es := range [][]Endpoint{
		r.Endpoints(EndpointFilter{Zone: "onyx", Status: Verified}),
		r.Endpoints(EndpointFilter{Zone: "onyx", Kind: RPC, Status: Verified}),
		r.Endpoints(EndpointFilter{Status: Verified}),
	} {
		uassert.Equal(t, 1, len(es))
		uassert.Equal(t, len(es), cap(es))
	}
	uassert.NoError(t, r.Propose(alice, 1, "dev", Info{ChainID: "dev", Title: "D", Kind: Devnet, RPCURL: "https://rpc.dev.example.com"}))
	for _, zs := range [][]Zone{r.Zones(ZoneFilter{Kind: Devnet}), r.Zones(ZoneFilter{Status: Pending, Kind: Devnet})} {
		uassert.Equal(t, 1, len(zs))
		uassert.Equal(t, len(zs), cap(zs))
	}
}

zones.gno

// Package zones is the content model of a curated registry of gno.land
// networks: what a zone is, what an endpoint on one is, which strings each
// field accepts, and the curation states both move through.
//
// A zone is one network a person can point a node or a wallet at: mainnet, a
// testnet, a staging chain, somebody's gnodev. An endpoint is one way in: an
// RPC, a gnoweb, a seed or persistent peer, an indexer, a faucet, an explorer.
// Anybody may propose a zone, and register endpoints as the holding realm
// allows; a curator decides which
// zones are official and which endpoints are verified. Every decision is
// recorded with who made it and when; a rejection, a retirement, a flag and an
// edit to an approved zone also require a reason, which the public reads.
//
// The package decides nothing about WHO may act. Every write that records a
// decision takes the acting address and the height as arguments (the two
// removals take neither), and the realm holding the [Registry]
// decides whether that address is a curator, the proposer, or nobody. That is
// the split that lets the same model move under a different authority later (a
// DAO, a system realm) without a line changing here.
//
// Live registry: r/moul/zones.
package zones

import (
	"errors"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"
)

// Status is where a zone stands in curation.
type Status string

const (
	// Pending is a proposal nobody has reviewed yet. Every zone starts here.
	Pending Status = "pending"
	// Approved is an official zone: the one state a reader should trust.
	Approved Status = "approved"
	// Rejected is a proposal a curator turned down, with the reason kept.
	Rejected Status = "rejected"
	// Retired is a zone that was official and no longer runs. It stays
	// listed, because a node operator holding its chain id deserves to find
	// out why nothing answers, until MaxRetired newer retirements push it out.
	Retired Status = "retired"
)

// Kind says what sort of network a zone is.
type Kind string

const (
	Mainnet Kind = "mainnet"
	Testnet Kind = "testnet"
	Devnet  Kind = "devnet"
	Local   Kind = "local"
)

// EndpointKind says what an endpoint is for, and therefore which address
// shape it accepts.
type EndpointKind string

const (
	RPC      EndpointKind = "rpc"      // a tm2 JSON-RPC: http(s) and tcp for gnokey, ws(s) for a subscriber
	Gnoweb   EndpointKind = "gnoweb"   // a gnoweb frontend
	Seed     EndpointKind = "seed"     // a p2p seed, for p2p.seeds
	Peer     EndpointKind = "peer"     // a p2p node, for p2p.persistent_peers
	Indexer  EndpointKind = "indexer"  // a tx-indexer GraphQL endpoint
	Faucet   EndpointKind = "faucet"   // a faucet page or API
	Explorer EndpointKind = "explorer" // a block explorer
)

// Verification is a curator's verdict on an endpoint.
type Verification string

const (
	// Unverified is every endpoint until a curator looks at it. Listed, and
	// labelled as such, never hidden: an unverified RPC is still an RPC.
	Unverified Verification = "unverified"
	// Verified means a curator checked it answers for this zone.
	Verified Verification = "verified"
	// Flagged means a curator says do not use it, and says why.
	Flagged Verification = "flagged"
)

// Statuses, Kinds, EndpointKinds and Verifications list every value of each
// enum in display order, for a Render that wants one section per value.
func Statuses() []Status { return []Status{Approved, Pending, Rejected, Retired} }

func Kinds() []Kind { return []Kind{Mainnet, Testnet, Devnet, Local} }

func EndpointKinds() []EndpointKind {
	return []EndpointKind{RPC, Gnoweb, Seed, Peer, Indexer, Faucet, Explorer}
}

func Verifications() []Verification { return []Verification{Verified, Unverified, Flagged} }

// Bounds on every caller-supplied string. A bound rather than none: every
// stored byte locks a storage deposit, and an unbounded field is a bill a
// stranger chooses the size of.
const (
	MinSlugLen        = 2
	MaxSlugLen        = 32
	MaxChainIDLen     = 50 // tm2's own limit on a chain id
	MaxTitleLen       = 64
	MaxDescriptionLen = 512
	MaxURLLen         = 256
	MaxLabelLen       = 64
	MaxReasonLen      = 280
)

// Info is everything a proposer describes about a zone. It is the part that
// can be edited; the slug, the status and the history cannot.
type Info struct {
	ChainID     string // what a node's genesis and a signer's -chainid say
	Title       string
	Description string
	Kind        Kind
	GnowebURL   string // optional: a local chain may not run one
	RPCURL      string // required: the one endpoint every tool needs
	GenesisURL  string // optional: where to download genesis.json
}

// Zone is a network, as the registry holds it.
//
// Flat on purpose: every field is a scalar. A nested struct inside a persisted
// object is stored as an object of its own, and `gnokey query vm/qeval` prints
// it as an opaque ref(...) instead of its fields, so a reader asking a node for
// a zone would get the slug and nothing they came for. [Zone.Info] gives the
// editable part back as one value.
type Zone struct {
	Slug        string // the key: [a-z0-9-], stable, and what a URL carries
	ChainID     string
	Title       string
	Description string
	Kind        Kind
	GnowebURL   string
	RPCURL      string
	GenesisURL  string

	Status     Status
	Proposer   address
	ProposedAt int64

	// Revision changes on every edit of the zone's Info, on every status
	// change and on every restated decision, and is never reused,
	// not even by a zone removed and proposed again under the same slug. A
	// curator acting on a zone names the revision they read, so an edit that
	// lands between their reading and their decision makes the decision fail
	// instead of attaching their name to text they never saw.
	Revision int64
	EditedBy address // who last edited the Info; empty if nobody has
	EditedAt int64
	Entered  int64 // when it entered its current status, in registry order: eviction goes oldest first

	// The latest curator decision, empty until there is one. A curator's edit
	// to an approved zone is a decision too, and replaces these.
	ReviewedBy address
	ReviewedAt int64
	Reason     string
}

// Info returns the part of the zone a proposer described.
func (z Zone) Info() Info {
	return Info{
		ChainID:     z.ChainID,
		Title:       z.Title,
		Description: z.Description,
		Kind:        z.Kind,
		GnowebURL:   z.GnowebURL,
		RPCURL:      z.RPCURL,
		GenesisURL:  z.GenesisURL,
	}
}

// Reviewed reports whether a curator has decided anything about the zone,
// including an edit made after its first review.
func (z Zone) Reviewed() bool { return z.ReviewedBy != "" }

func (z *Zone) setInfo(in Info) {
	z.ChainID = in.ChainID
	z.Title = in.Title
	z.Description = in.Description
	z.Kind = in.Kind
	z.GnowebURL = in.GnowebURL
	z.RPCURL = in.RPCURL
	z.GenesisURL = in.GenesisURL
}

// Endpoint is one way into a zone, as the registry holds it. Flat for the same
// reason as [Zone].
type Endpoint struct {
	ID           int64
	Zone         string // the zone's slug
	Kind         EndpointKind
	Address      string // a URL, or id@host:port for a seed or a peer
	Label        string // who runs it, or what it is, in the registrant's words
	Registrant   address
	RegisteredAt int64

	Status     Verification
	ReviewedBy address
	ReviewedAt int64
	Reason     string
	// Revision is bumped, from the registry-wide counter zones use, when the
	// endpoint is registered, on every verdict and on every reset. A verdict
	// and a removal name it, so either fails on an endpoint that changed
	// after it was read.
	Revision int64
	// Exempt marks an endpoint registered through RegisterExempt, by a
	// reviewer the holder trusts: never clearable as a never-reviewed one,
	// whoever is a reviewer later.
	Exempt bool
}

// Clearable reports whether nobody has ruled on the endpoint and it was not a
// reviewer's own registration: no verdict (every verdict names its
// reviewer), no reset (every reset leaves a reason), not Exempt. It is what
// a bulk clear of a flood may remove.
func (e Endpoint) Clearable() bool { return !e.Exempt && e.ReviewedBy == "" && e.Reason == "" }

// ParseStatus reads a status from a caller's string. "" is the zero Status,
// which a filter reads as "any".
func ParseStatus(s string) (Status, error) {
	switch st := Status(TrimSpaces(s)); st {
	case "", Pending, Approved, Rejected, Retired:
		return st, nil
	}
	return "", errors.New("zones: unknown status " + strconv.Quote(s) + ", want approved, pending, rejected or retired")
}

// ParseKind reads a zone kind. "" is the zero Kind, "any" to a filter.
func ParseKind(s string) (Kind, error) {
	switch k := Kind(TrimSpaces(s)); k {
	case "", Mainnet, Testnet, Devnet, Local:
		return k, nil
	}
	return "", errors.New("zones: unknown kind " + strconv.Quote(s) + ", want mainnet, testnet, devnet or local")
}

// ParseEndpointKind reads an endpoint kind. "" is "any" to a filter.
func ParseEndpointKind(s string) (EndpointKind, error) {
	switch k := EndpointKind(TrimSpaces(s)); k {
	case "", RPC, Gnoweb, Seed, Peer, Indexer, Faucet, Explorer:
		return k, nil
	}
	return "", errors.New("zones: unknown endpoint kind " + strconv.Quote(s) +
		", want rpc, gnoweb, seed, peer, indexer, faucet or explorer")
}

// ParseVerification reads an endpoint verdict. "" is "any" to a filter.
func ParseVerification(s string) (Verification, error) {
	switch v := Verification(TrimSpaces(s)); v {
	case "", Unverified, Verified, Flagged:
		return v, nil
	}
	return "", errors.New("zones: unknown verification " + strconv.Quote(s) + ", want verified, unverified or flagged")
}

// ValidateSlug accepts 2 to 32 characters of [a-z0-9-], starting and ending
// with a letter or a digit.
//
// Checked at write time rather than escaped at render time, deliberately: the
// slug is also an index key and a URL path segment, so one carrying a slash or
// a pipe would break the link and the table as well as the page.
func ValidateSlug(s string) error {
	if len(s) < MinSlugLen || len(s) > MaxSlugLen {
		return errors.New("zones: a slug is " + strconv.Itoa(MinSlugLen) + " to " +
			strconv.Itoa(MaxSlugLen) + " characters, got " + strconv.Quote(s))
	}
	for i, r := range s {
		alnum := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
		if alnum || (r == '-' && i > 0 && i < len(s)-1) {
			continue
		}
		return errors.New("zones: a slug is [a-z0-9-] and starts and ends alphanumeric, got " + strconv.Quote(s))
	}
	return nil
}

// ValidateChainID accepts what tm2 accepts for a chain id: 1 to 50
// characters, here narrowed to [A-Za-z0-9._-] so it is safe raw in a table.
func ValidateChainID(s string) error {
	if s == "" || len(s) > MaxChainIDLen {
		return errors.New("zones: a chain id is 1 to " + strconv.Itoa(MaxChainIDLen) + " characters")
	}
	for _, r := range s {
		switch {
		case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '_', r == '-':
		default:
			return errors.New("zones: a chain id is [A-Za-z0-9._-], got " + strconv.Quote(s))
		}
	}
	return nil
}

// ValidateInfo checks every field of a zone's description, and returns the
// first problem it finds.
func ValidateInfo(in Info) error {
	if err := ValidateChainID(in.ChainID); err != nil {
		return err
	}
	if err := checkText("title", in.Title, 1, MaxTitleLen); err != nil {
		return err
	}
	if err := checkText("description", in.Description, 0, MaxDescriptionLen); err != nil {
		return err
	}
	// Exact values only: a Kind(" testnet ") stored as written would match no
	// filter (the Registry trims before it validates; a direct caller must).
	switch in.Kind {
	case Mainnet, Testnet, Devnet, Local:
	case "":
		return errors.New("zones: a zone needs a kind: mainnet, testnet, devnet or local")
	default:
		return errors.New("zones: unknown kind " + strconv.Quote(string(in.Kind)) + ", want mainnet, testnet, devnet or local")
	}
	if err := checkURL("rpc url", in.RPCURL, primarySchemes); err != nil {
		return err
	}
	// gnokey's -remote is <scheme>://<host>[:<port>] and reads anything after
	// :// as the socket address: a path, a query, a fragment, even a lone
	// trailing slash, prints a command that cannot dial (https://host/ dials
	// "host/:443"). An rpc ENDPOINT may still carry a path.
	if _, rest, _ := strings.Cut(in.RPCURL, "://"); strings.IndexAny(rest, "/?#") >= 0 {
		return errors.New("zones: the rpc url is <scheme>://<host>[:<port>], what gnokey -remote takes, with no path, not even a trailing slash: " +
			strconv.Quote(in.RPCURL))
	}
	for _, u := range [][2]string{{"gnoweb url", in.GnowebURL}, {"genesis url", in.GenesisURL}} {
		if u[1] == "" {
			continue
		}
		if err := checkURL(u[0], u[1], webSchemes); err != nil {
			return err
		}
	}
	// A loopback or private address names a different machine for every
	// reader. Fine for a local zone, which is exactly that; on any other kind
	// it points a config generator at whatever answers inside the reader's own
	// network.
	if in.Kind != Local {
		for _, u := range []string{in.RPCURL, in.GnowebURL, in.GenesisURL} {
			if u != "" && IsPrivateHost(HostOf(RPC, u)) {
				return errors.New("zones: " + strconv.Quote(u) + " names a private or special-use host; only a local zone lists those")
			}
		}
	}
	return nil
}

// HostOf returns the host of an endpoint address: the part between :// and
// the port or path of a URL, or between @ and the port of a peer. It assumes
// an address that already passed validation.
func HostOf(kind EndpointKind, addr string) string {
	if kind == Seed || kind == Peer {
		_, hostport, _ := strings.Cut(addr, "@")
		if i := strings.LastIndexByte(hostport, ':'); i >= 0 {
			return hostport[:i]
		}
		return hostport
	}
	_, rest, _ := strings.Cut(addr, "://")
	if i := strings.IndexAny(rest, "/?"); i >= 0 {
		rest = rest[:i]
	}
	if i := strings.LastIndexByte(rest, ':'); i >= 0 {
		rest = rest[:i]
	}
	return rest
}

// IsPrivateHost reports whether host names a machine that is different for
// every reader, or no machine at all:
//
//   - a name with no dot (resolved through the reader's own search domain), or
//     one under a suffix reserved for local or private use, or that public DNS
//     does not delegate: .localhost, .local (mDNS), .internal, .localdomain,
//     .test, .example, .invalid, .lan, .home, .corp, .mail, .intranet,
//     .private, .alt, .onion and .i2p, the service-discovery and container names
//     .consul, .lxd, .incus, .docker, .podman, .localnet and .svc, and every
//     .arpa name, which is infrastructure
//     and never a public service (.home.arpa, ipv4only.arpa,
//     default.service.arpa). Hosts files' localhost4, localhost6,
//     ip6-localhost and ip6-loopback have no dot and fall under the first rule;
//   - an IPv4 address in a loopback, private, link-local, carrier-grade NAT,
//     "this network", IETF-protocol, documentation, benchmarking, 6to4 relay
//     anycast, multicast or reserved range;
//   - anything else shaped like a number but not a valid dotted quad, so an
//     outside caller is not told 127.1 is public (validation refuses it anyway).
//
// It fails closed: anything but a bare host ([A-Za-z0-9.-] only) is private
// to it. It looks at the string only; a public name that resolves to a private
// address is beyond what a registry can know.
func IsPrivateHost(host string) bool {
	// Fail closed: anything but a bare host (a port, a path, a stray
	// character) is not one this can vouch for.
	for i := 0; i < len(host); i++ {
		if c := host[i]; !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '-') {
			return true
		}
	}
	h := strings.ToLower(strings.TrimSuffix(host, "."))
	if !strings.Contains(h, ".") {
		return true
	}
	for _, suffix := range []string{".localhost", ".local", ".internal", ".arpa", ".localdomain",
		".test", ".example", ".invalid", ".lan", ".home", ".corp", ".mail", ".intranet", ".private", ".onion", ".alt",
		".consul", ".lxd", ".incus", ".docker", ".podman", ".localnet", ".svc", ".i2p"} {
		if strings.HasSuffix(h, suffix) {
			return true
		}
	}
	labels := strings.Split(h, ".")
	last := labels[len(labels)-1]
	numeric := strings.Trim(last, "0123456789") == "" || strings.HasPrefix(last, "0x")
	if !numeric {
		return false
	}
	if checkIPv4(h) != nil {
		return true
	}
	a, _ := strconv.Atoi(labels[0])
	b, _ := strconv.Atoi(labels[1])
	c, _ := strconv.Atoi(labels[2])
	switch {
	case a == 0, a == 10, a == 127, a >= 224:
		return true
	case a == 169 && b == 254, a == 192 && b == 168:
		return true
	case a == 172 && b >= 16 && b <= 31, a == 100 && b >= 64 && b <= 127:
		return true
	case a == 192 && b == 0 && c == 0, a == 198 && (b == 18 || b == 19), a == 192 && b == 88 && c == 99:
		return true
	case a == 192 && b == 0 && c == 2, a == 198 && b == 51 && c == 100, a == 203 && b == 0 && c == 113:
		return true // documentation ranges
	}
	return false
}

// ValidateEndpoint checks an endpoint's address against the shape its kind
// needs: a URL for everything but a seed or a peer, which are id@host:port.
func ValidateEndpoint(kind EndpointKind, addr string) error {
	switch kind {
	case RPC:
		if err := checkURL("rpc address", addr, rpcSchemes); err != nil {
			return err
		}
		// gnokey dials a tcp:// remote as host:port, path and all, so one with
		// a path is undialable, and Canonical would read it as an http URL
		// that is a different resource.
		if scheme, rest, _ := strings.Cut(addr, "://"); strings.EqualFold(scheme, "tcp") &&
			strings.IndexAny(rest, "/?") >= 0 {
			return errors.New("zones: a tcp:// rpc address is host and port only, no path or query")
		}
		return nil
	case Indexer:
		// A tx-indexer serves GraphQL subscriptions over a websocket too.
		return checkURL("indexer address", addr, rpcSchemes[:4])
	case Gnoweb, Faucet, Explorer:
		return checkURL(string(kind)+" address", addr, webSchemes)
	case Seed, Peer:
		return checkPeer(addr)
	case "":
		return errors.New("zones: an endpoint needs a kind")
	}
	// Exact values only. The Parse functions trim a caller's string, so an
	// EndpointKind(" rpc ") would parse, be stored as written, and then match
	// no filter: refused here rather than normalised behind the caller's back.
	return errors.New("zones: unknown endpoint kind " + strconv.Quote(string(kind)) +
		", want rpc, gnoweb, seed, peer, indexer, faucet or explorer")
}

// ValidateLabel accepts an optional single line of up to 64 characters.
func ValidateLabel(s string) error { return checkText("label", s, 0, MaxLabelLen) }

// ValidateReason accepts an optional single line of up to 280 characters.
// Whether a reason is REQUIRED depends on the decision; see [Registry].
func ValidateReason(s string) error { return checkText("reason", s, 0, MaxReasonLen) }

var (
	// rpcSchemes is what an rpc ENDPOINT may be: a websocket subscriber is a
	// real consumer of one.
	rpcSchemes = []string{"https", "http", "wss", "ws", "tcp"}
	// primarySchemes is what a zone's main RPC may be, narrower on purpose: it
	// is what every tool is pointed at first, gnokey's -remote included, and
	// gnokey's query client dials http, https and tcp only, so a wss:// main
	// RPC would print a command that cannot run.
	primarySchemes = []string{"https", "http", "tcp"}
	webSchemes     = []string{"https", "http"}
)

// ValidAddress reports whether a is a valid g1 address in the one spelling the
// chain uses for it: lowercase. bech32 also decodes an all-uppercase string, so
// IsValid accepts G1ABC…, but every comparison here (curators, proposers,
// registrants, node ids) is on the string, and an uppercase spelling of a real
// address would be a second identity for it.
func ValidAddress(a address) bool {
	return a.IsValid() && string(a) == strings.ToLower(string(a))
}

// HasVisible reports whether s has at least one character a reader can see:
// not a space, not a combining mark, not an invisible format character, not a
// blank filler. A
// required title or reason must, or it passes the "needs a reason" check and
// renders blank.
func HasVisible(s string) bool {
	for _, r := range s {
		if !unicode.IsSpace(r) && !unicode.IsMark(r) && !unicode.Is(unicode.Cf, r) && !isBlankFiller(r) {
			return true
		}
	}
	return false
}

// isBlankFiller is the handful of characters that are letters or symbols by
// category and still draw nothing: the Hangul fillers, the blank Braille cell,
// the musical null notehead, the Egyptian hieroglyph blanks, and the Khmer
// inherent vowels and the Khitan filler (marks by category, drawn as nothing). Unicode does not class them as format
// characters, so they need naming.
func isBlankFiller(r rune) bool {
	switch r {
	case 0x115F, 0x1160, 0x3164, 0xFFA0, 0x2800, 0x1D159, 0x17B4, 0x17B5,
		0x13441, 0x13442, 0x16FE4:
		return true
	}
	return false
}

// isSelector is the variation selectors, all three blocks (U+180E, inside the
// Mongolian range, is a format character and refused as one): invisible on their
// own, and an invisible difference between two spellings of a name.
func isSelector(r rune) bool {
	return (r >= 0xFE00 && r <= 0xFE0F) || (r >= 0xE0100 && r <= 0xE01EF) || (r >= 0x180B && r <= 0x180F)
}

// selects reports whether a variation selector modifies the character before
// it, the one place it is text rather than an invisible difference: the
// emoji and text presentation selectors after a symbol (a phone writes ❤️ as
// U+2764 U+FE0F), the Mongolian free variation selectors after a Mongolian
// letter, and an ideographic variation sequence after a Han ideograph. A
// selector cannot make a badge: every symbol that looks like one is refused on
// its own.
func selects(base, sel rune) bool {
	switch {
	case sel == 0xFE0E || sel == 0xFE0F:
		// The symbols, and the five emoji whose base is punctuation or a
		// letter by category: ‼ ⁉ ℹ 〰 〽.
		return unicode.In(base, unicode.So, unicode.Sm) ||
			base == 0x203C || base == 0x2049 || base == 0x2139 || base == 0x3030 || base == 0x303D
	case sel >= 0x180B && sel <= 0x180F && sel != 0x180E:
		return base >= 0x1820 && base <= 0x18AA
	case sel >= 0xE0100 && sel <= 0xE01EF:
		return unicode.Is(unicode.Han, base)
	}
	return false
}

// isBadge is the status glyphs Render draws, and their look-alikes, refused in
// free text so a title cannot claim "✔ official" beside a pending badge.
func isBadge(r rune) bool {
	switch r {
	case 0x2705, 0x26A0, 0x23F3, 0x274C, 0x23F9, // ✅ ⚠ ⏳ ❌ ⏹, what Render draws
		0x2713, 0x2714, 0x2611, 0x1F5F8, 0x1F5F9, 0x1F197, // check marks, 🆗
		0x2716, 0x2717, 0x2718, 0x2715, 0x274E, 0x2612, 0x1F6AB, 0x26D4, 0x1F6D1, // crosses, no-entry
		0x1F5F4, 0x1F5F5, 0x1F5F6, 0x1F5F7, // ballot x and ballot box with x
		0x231B, 0x23F8, 0x23FA, // ⌛ ⏸ ⏺
		0x1FBB1, 0x237B, 0x10102, // more check marks
		0x1F5D9, 0x2A2F, 0x2573, 0x2BBD, 0x2BBE, 0x2BBF, // more crosses and ballot boxes
		0x29D6, 0x29D7, // hourglasses
		0x2613, 0x2A09, // saltire, n-ary times (× itself is everyday text: 1920×1080)
		0x22A0, 0x2327, 0x1F147, 0x1F187, 0x2297, 0x2A02, 0x1F167, // boxed and circled crosses
		0x1F6C7, 0x2298, 0x29B8, // prohibition signs
		0x24CD, 0x24E7, 0x24B3, 0x1F127, 0x29BB, 0x2A34, 0x2A35, 0x2A37, 0x292B, 0x292C, // circled, parenthesized and crossing x
		0x1F532, 0x1F533, // square buttons, beside ⏹
		0x26DD, 0x1F5BE, 0x2B59, 0x2A36, 0x26D2, 0x1FBC0, 0x1D145, 0x26CC, 0x2A3B, // more boxed, circled and heavy crosses
		0x1FBBD, 0x1F6AD, 0x1F6AF, 0x1F6B1, 0x1F6B3, 0x1F6B7, 0x1F4F5, 0x1F51E, 0x1F10D, 0x1F10F, 0x1F16E: // more no-entry signs
		return true
	}
	return r >= 0x1F7A8 && r <= 0x1F7AE // the geometric crosses beside ✖
}

// checkText bounds a free-text field by runes (so at most four times as many
// bytes) and keeps it to one line of text that shows what it stores:
//
//   - no control character: C0, DEL, C1, U+2028, U+2029. Several are line
//     breaks that ui.Inline folds to a space, the rest draw nothing; either
//     way the text shown would not be the text stored.
//   - no invisible or undrawable character: every format character (Unicode
//     Cf, which covers the bidi controls and isolates, the zero-width
//     characters, U+061C, word joiners, tags), every character that is not
//     graphic (private use, unassigned, noncharacters), the blank fillers, a
//     variation selector except right after a base it modifies (selects), the
//     combining grapheme joiner. A title made of them
//     would pass the length check and render blank or as a box.
//   - no enclosing mark, which draws a badge's frame around any character,
//     and no run of more than four nonspacing marks, which stack over
//     neighbouring lines (a spacing mark takes its own width and ends a run,
//     so Devanagari, Gurmukhi, Burmese and Tibetan words pass), and none of
//     the status glyphs a Render draws.
//   - valid UTF-8, because the page would show U+FFFD for a byte stored raw.
//
// Refused rather than stripped, so what is stored is what is shown.
func checkText(field, s string, min, max int) error {
	// No rune is more than four bytes: anything longer cannot be within max
	// characters, and is refused before a per-rune scan the writer pays for.
	if len(s) > 4*max {
		return errors.New("zones: the " + field + " is longer than " + strconv.Itoa(max) + " characters")
	}
	n, marks, prev := 0, 0, rune(0)
	for i, r := range s {
		if r == utf8.RuneError {
			if _, size := utf8.DecodeRuneInString(s[i:]); size <= 1 {
				return errors.New("zones: the " + field + " is not valid UTF-8")
			}
		}
		if r < 0x20 || (r >= 0x7f && r <= 0x9f) || r == 0x2028 || r == 0x2029 {
			return errors.New("zones: the " + field + " contains a control character")
		}
		if unicode.Is(unicode.Cf, r) || isBlankFiller(r) || r == 0x034F || (isSelector(r) && !selects(prev, r)) {
			return errors.New("zones: the " + field + " contains an invisible or bidi character")
		}
		if !unicode.IsGraphic(r) && !unicode.IsSpace(r) {
			// The chain's unicode tables are Unicode 15.0, so a character
			// assigned since then is refused here even where gno test (which
			// uses the host's newer tables) accepts it.
			return errors.New("zones: the " + field + " contains " + strconv.QuoteToASCII(string(r)) +
				", which this chain does not draw: private use, a noncharacter, or unassigned in its Unicode 15.0 tables")
		}
		if isBadge(r) {
			return errors.New("zones: the " + field + " contains a status glyph a Render draws, or a look-alike of one: " + strconv.Quote(string(r)))
		}
		if unicode.Is(unicode.Me, r) {
			// An enclosing mark draws a frame around what precedes it: !\u20E4
			// is a warning triangle, v\u20DE a checked box. No living script
			// needs one, and keycaps need U+FE0F, refused above.
			return errors.New("zones: the " + field + " contains an enclosing mark, which draws a status glyph's frame")
		}
		if unicode.Is(unicode.Mn, r) {
			marks++
			if marks > 4 {
				return errors.New("zones: the " + field + " stacks more than four combining marks")
			}
		} else {
			marks = 0
		}
		prev = r
		n++
		if n > max {
			break // refused below; no need to classify the rest
		}
	}
	if n > max {
		return errors.New("zones: the " + field + " is longer than " + strconv.Itoa(max) + " characters")
	}
	if n < min {
		return errors.New("zones: the " + field + " is " + strconv.Itoa(min) + " to " +
			strconv.Itoa(max) + " characters, got " + strconv.Itoa(n))
	}
	if s != "" && !HasVisible(s) {
		return errors.New("zones: the " + field + " has nothing visible in it")
	}
	return nil
}

// checkURL accepts scheme://host[:port][/path][?query], in visible ASCII (no
// space, no control), with no character that could close a markdown link or
// open a new construct around it. Narrower than RFC 3986 on purpose: these
// URLs are rendered as links and copied into config files, and neither wants
// a quote or a bracket. Also refused:
//
//   - a fragment (#): it is never sent to the server, so every #1, #2 would be
//     another listing of the same endpoint.
//   - a % not followed by two hex digits, and an &name; shape: the link
//     sanitizer re-encodes both, so the href would differ from the text shown.
func checkURL(field, s string, schemes []string) error {
	if s == "" {
		return errors.New("zones: the " + field + " is empty")
	}
	if len(s) > MaxURLLen {
		return errors.New("zones: the " + field + " is longer than " + strconv.Itoa(MaxURLLen) + " bytes")
	}
	n := len(s)
	for i := 0; i < n; i++ {
		c := s[i]
		if c <= ' ' || c >= 0x7f || isURLForbidden(c) {
			r, _ := utf8.DecodeRuneInString(s[i:]) // the character, not its first byte
			return errors.New("zones: the " + field + " contains " + strconv.QuoteRune(r) + ": " + strconv.Quote(s))
		}
		if c == '%' && (i+2 >= n || !isHex(s[i+1]) || !isHex(s[i+2])) {
			return errors.New("zones: the " + field + " has a % that is not followed by two hex digits: " + strconv.Quote(s))
		}
		if c == '%' && isUnreserved(unhex(s[i+1])<<4|unhex(s[i+2])) {
			// %7E and ~ are the same URL (RFC 3986): one spelling, so two
			// listings cannot be the same endpoint.
			return errors.New("zones: the " + field + " escapes a character that needs no escaping: " + strconv.Quote(s))
		}
		if c == '&' && isEntity(s[i+1:]) {
			return errors.New("zones: the " + field + " contains an HTML entity shape: " + strconv.Quote(s))
		}
	}
	scheme, rest, ok := strings.Cut(s, "://")
	if !ok {
		return errors.New("zones: the " + field + " needs a scheme (" + strings.Join(schemes, ", ") + "): " + strconv.Quote(s))
	}
	// A scheme is case-insensitive, so HTTPS:// is https://; Canonical lowercases
	// it the same way, which is what makes the two one endpoint.
	known := false
	for _, sc := range schemes {
		if strings.ToLower(scheme) == sc {
			known = true
			break
		}
	}
	if !known {
		return errors.New("zones: the " + field + " scheme is " + strconv.Quote(scheme) + ", want one of " +
			strings.Join(schemes, ", "))
	}
	authority := rest
	if i := strings.IndexAny(authority, "/?#"); i >= 0 {
		authority = authority[:i]
		// A "." or ".." path segment is resolved away by every browser and by
		// RFC 3986, so it would be a second spelling of another URL.
		path := rest[i:]
		if j := strings.IndexByte(path, '?'); j >= 0 {
			path = path[:j]
		}
		for _, seg := range strings.Split(path, "/") {
			if seg == "." || seg == ".." {
				return errors.New("zones: the " + field + " has a . or .. path segment: " + strconv.Quote(s))
			}
		}
	}
	if strings.Contains(authority, "@") {
		return errors.New("zones: the " + field + " carries credentials: " + strconv.Quote(s))
	}
	host, port := authority, ""
	if i := strings.LastIndexByte(authority, ':'); i >= 0 {
		host, port = authority[:i], authority[i+1:]
		if err := checkPort(port); err != nil {
			return errors.New("zones: the " + field + "'s port is 1 to 65535, got " + strconv.Quote(port))
		}
	}
	if host == "" {
		return errors.New("zones: the " + field + " has no host: " + strconv.Quote(s))
	}
	if err := checkHost(host); err != nil {
		return errors.New("zones: the " + field + "'s host is a DNS name or an IPv4 address, got " + strconv.Quote(host))
	}
	return nil
}

// checkHost accepts a DNS name or a dotted IPv4 address.
//
// A DNS name is labels of 1 to 63 characters of [A-Za-z0-9-], alphanumeric at
// both ends, at most 253 characters in all, with one optional terminal dot.
// Anything a browser would parse as IPv4 must BE a valid dotted-quad address:
// under the WHATWG URL parser a host whose last label is numeric (decimal, or
// 0x hex) is an IPv4 address, so 0x7f.1 opens 127.0.0.1 and a.1 is no URL at
// all. A last label starting 0x is held to the address rule even when the rest
// is not hex (a browser would take 0xyz as a name): stricter, never looser.
// An address takes no terminal dot. Bracketed IPv6 is refused, deliberately: it is the one host shape that
// needs characters every other field here refuses, and no zone needs it yet.
func checkHost(host string) error {
	name := strings.TrimSuffix(host, ".")
	if name == "" || len(name) > 253 {
		return errors.New("bad host")
	}
	labels := strings.Split(name, ".")
	last := strings.ToLower(labels[len(labels)-1])
	if strings.Trim(last, "0123456789") == "" || strings.HasPrefix(last, "0x") {
		// No terminal dot on an address: browsers accept 1.2.3.4. but Go's
		// dialer, so gnokey and tm2, look it up as a name and fail.
		if name != host {
			return errors.New("bad ipv4")
		}
		return checkIPv4(name)
	}
	for _, label := range labels {
		if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
			return errors.New("bad host")
		}
		for _, r := range label {
			switch {
			case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-':
			default:
				return errors.New("bad host")
			}
		}
	}
	return nil
}

func checkIPv4(s string) error {
	parts := strings.Split(s, ".")
	if len(parts) != 4 {
		return errors.New("bad ipv4")
	}
	for _, p := range parts {
		if p == "" || len(p) > 3 || strings.Trim(p, "0123456789") != "" || (len(p) > 1 && p[0] == '0') {
			return errors.New("bad ipv4")
		}
		if n, _ := strconv.Atoi(p); n > 255 {
			return errors.New("bad ipv4")
		}
	}
	return nil
}

// checkPort accepts 1 to 65535, decimal digits only, no leading zero. Digits
// only because strconv.Atoi takes a sign, and +443 is no port to url.Parse,
// to a browser, or to tm2's peer parser.
func checkPort(port string) error {
	if port == "" || strings.Trim(port, "0123456789") != "" || port[0] == '0' || len(port) > 5 {
		return errors.New("bad port")
	}
	if p, _ := strconv.Atoi(port); p > 65535 {
		return errors.New("bad port")
	}
	return nil
}

// isURLForbidden is the visible ASCII a URL here may not carry: what could
// close a markdown link or open a construct around it, and a fragment.
func isURLForbidden(c byte) bool {
	switch c {
	case '<', '>', '"', '\'', '`', '(', ')', '[', ']', '{', '}', '|', '\\', '^', '#':
		return true
	}
	return false
}

func isHex(c byte) bool {
	return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}

func unhex(c byte) byte {
	switch {
	case c >= '0' && c <= '9':
		return c - '0'
	case c >= 'a' && c <= 'f':
		return c - 'a' + 10
	}
	return c - 'A' + 10
}

// isUnreserved is RFC 3986's unreserved set: what a URL never needs to escape.
func isUnreserved(c byte) bool {
	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
		c == '-' || c == '.' || c == '_' || c == '~'
}

// isEntity reports whether s starts with what an HTML entity would follow an
// ampersand with: a run of [A-Za-z0-9#] closed by a semicolon.
func isEntity(s string) bool {
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c == ';':
			return i > 0
		case (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '#':
		default:
			return false
		}
	}
	return false
}

// TrimSpaces trims spaces (Unicode Zs: U+0020, no-break space, U+3000 and the
// like) and tabs from both ends, and nothing else. strings.TrimSpace also
// strips line breaks and separators (CR, LF, U+0085, U+2028), which free text
// refuses: trimmed first, they would be accepted silently, changed. A line
// break a caller types reaches the validator and is refused there.
func TrimSpaces(s string) string {
	return strings.TrimFunc(s, func(r rune) bool { return r == '\t' || unicode.Is(unicode.Zs, r) })
}

// lowerAuthority lowercases a URL's scheme and host, both case-insensitive,
// and leaves the path and query as typed. Stored that way because gno's link
// sanitizer is not case-insensitive (an HTTPS:// link would render with an
// empty href), and so every later lowercasing of the host (Canonical,
// IsPrivateHost) finds nothing to change: a scan, no copy. ASCII only, see
// asciiLower.
func lowerAuthority(addr string) string {
	scheme, rest, ok := strings.Cut(addr, "://")
	if !ok {
		return addr
	}
	host, tail := rest, ""
	if i := strings.IndexAny(rest, "/?"); i >= 0 {
		host, tail = rest[:i], rest[i:]
	}
	return asciiLower(scheme) + "://" + asciiLower(host) + tail
}

// trimEmptyTail drops an empty tail from a URL, by Canonical's own rules: an
// empty query's "?" (when it is the tail's only "?") and a bare "/". gnokey
// would dial a host with them attached, so an endpoint is not stored with them
// (nor a zone's gnoweb and genesis URLs, which trimInfo repairs the same way, as
// a browser's address bar writes https://host/; its main RPC is refused with
// them, ValidateInfo). Canonical
// drops both too, so Canonical(trimEmptyTail(x)) == Canonical(x), and a check
// made on what a caller typed holds for what is stored. A path is kept as
// typed otherwise ("/?q" stays: Canonical reads it as "?q", a browser too).
func trimEmptyTail(addr string) string {
	scheme, rest, ok := strings.Cut(addr, "://")
	if !ok {
		return addr
	}
	i := strings.IndexAny(rest, "/?")
	if i < 0 {
		return addr
	}
	authority, tail := rest[:i], rest[i:]
	if strings.HasSuffix(tail, "?") && strings.Count(tail, "?") == 1 {
		tail = tail[:len(tail)-1]
	}
	if tail == "/" {
		tail = ""
	}
	return scheme + "://" + authority + tail
}

// asciiLower lowercases A to Z and nothing else. strings.ToLower also folds
// a few non-ASCII letters into ASCII ones (U+212A KELVIN SIGN to k, U+0130 to
// i), which would turn a URL validation refuses into one it accepts, under a
// spelling the caller never typed.
func asciiLower(s string) string {
	for i := 0; i < len(s); i++ {
		if c := s[i]; c >= 'A' && c <= 'Z' {
			b := []byte(s)
			for j := i; j < len(b); j++ {
				if b[j] >= 'A' && b[j] <= 'Z' {
					b[j] += 'a' - 'A'
				}
			}
			return string(b)
		}
	}
	return s
}

// Canonical is the form two addresses are compared in, so one endpoint cannot
// be listed twice under two spellings: the scheme and the host lowercased (both
// are case-insensitive), the host's terminal dot dropped, the scheme's default
// port dropped (:443 for https and wss, :80 for http and ws), an empty path
// before a query dropped, an empty query's "?" and a bare "/" dropped, the hex
// digits of every %XX escape uppercased, and for an rpc endpoint tcp:// read as
// http://, which is how gnokey dials it. A path or a query that says something
// is kept as typed: those are case-sensitive and name different resources. A
// peer is lowercased whole and loses its host's terminal dot: its node id is
// lowercase bech32 and its host is a name.
func Canonical(kind EndpointKind, addr string) string {
	if kind == Seed || kind == Peer {
		id, hostport, ok := strings.Cut(asciiLower(addr), "@")
		if !ok {
			return asciiLower(addr)
		}
		if i := strings.LastIndexByte(hostport, ':'); i >= 0 {
			hostport = strings.TrimSuffix(hostport[:i], ".") + hostport[i:]
		}
		return id + "@" + hostport
	}
	scheme, rest, ok := strings.Cut(addr, "://")
	if !ok {
		return addr
	}
	scheme = asciiLower(scheme)
	if kind == RPC && scheme == "tcp" {
		scheme = "http"
	}
	i := strings.IndexAny(rest, "/?")
	if i < 0 {
		i = len(rest)
	}
	authority, tail := asciiLower(rest[:i]), rest[i:]
	host, port := authority, ""
	if j := strings.LastIndexByte(authority, ':'); j >= 0 {
		host, port = authority[:j], authority[j+1:]
	}
	host = strings.TrimSuffix(host, ".")
	switch {
	case port == "443" && (scheme == "https" || scheme == "wss"),
		port == "80" && (scheme == "http" || scheme == "ws"):
		port = ""
	}
	if port != "" {
		host += ":" + port
	}
	if strings.HasSuffix(tail, "?") && strings.Count(tail, "?") == 1 {
		tail = tail[:len(tail)-1] // an empty query, not a query ending in "?"
	}
	if strings.HasPrefix(tail, "/?") {
		tail = tail[1:]
	}
	if tail == "/" {
		tail = ""
	}
	return scheme + "://" + host + upperEscapes(tail)
}

// upperEscapes uppercases the two hex digits of every %XX in s.
func upperEscapes(s string) string {
	if !strings.Contains(s, "%") {
		return s
	}
	b := []byte(s)
	for i := 0; i+2 < len(b); i++ {
		if b[i] == '%' {
			b[i+1] = toUpperHex(b[i+1])
			b[i+2] = toUpperHex(b[i+2])
		}
	}
	return string(b)
}

func toUpperHex(c byte) byte {
	if c >= 'a' && c <= 'f' {
		return c - 'a' + 'A'
	}
	return c
}

// checkPeer accepts a tm2 p2p address: <node id>@<host>:<port>, where the node
// id is the node's g1 address, as `gnoland secrets get node_id` prints it.
func checkPeer(s string) error {
	id, hostport, ok := strings.Cut(s, "@")
	if !ok {
		return errors.New("zones: a peer is <node id>@<host>:<port>, got " + strconv.Quote(s))
	}
	if len(s) > MaxURLLen {
		return errors.New("zones: a peer is longer than " + strconv.Itoa(MaxURLLen) + " bytes")
	}
	// Lowercase only: bech32 also decodes an all-uppercase id, but tm2 compares
	// node ids byte for byte when it dials, so an uppercase one never connects.
	if !ValidAddress(address(id)) {
		return errors.New("zones: a peer's node id is a lowercase g1 address, got " + strconv.Quote(id))
	}
	i := strings.LastIndexByte(hostport, ':')
	if i <= 0 {
		return errors.New("zones: a peer needs a port: " + strconv.Quote(s))
	}
	host, port := hostport[:i], hostport[i+1:]
	if err := checkPort(port); err != nil {
		return errors.New("zones: a peer's port is 1 to 65535, got " + strconv.Quote(port))
	}
	if err := checkHost(host); err != nil {
		return errors.New("zones: a peer's host is a DNS name or an IPv4 address, got " + strconv.Quote(host))
	}
	return nil
}

zones_test.gno

package zones

import (
	"strings"
	"testing"

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

// A real node id, from mainnet's published persistent_peers.
const nodeID = "g15rcv5yqef3kvnmueqvkyw8y05sd40jz9p3n5su"

func TestValidateSlug(t *testing.T) {
	cases := []struct {
		in, err string
	}{
		{"mainnet", ""},
		{"onyx", ""},
		{"moul-staging", ""},
		{"t1", ""},
		{"a", "2 to 32"},
		{strings.Repeat("a", 33), "2 to 32"},
		{"Mainnet", "[a-z0-9-]"},
		{"-onyx", "[a-z0-9-]"},
		{"onyx-", "[a-z0-9-]"},
		{"on_yx", "[a-z0-9-]"},
		{"on/yx", "[a-z0-9-]"},
		{"on|yx", "[a-z0-9-]"},
	}
	for _, c := range cases {
		err := ValidateSlug(c.in)
		if c.err == "" {
			uassert.NoError(t, err, c.in)
		} else {
			uassert.ErrorContains(t, err, c.err, c.in)
		}
	}
}

func TestValidateChainID(t *testing.T) {
	uassert.NoError(t, ValidateChainID("gnoland-1"))
	uassert.NoError(t, ValidateChainID("moulstaging-1"))
	uassert.NoError(t, ValidateChainID("dev"))
	uassert.NoError(t, ValidateChainID("test_5.x"))
	uassert.ErrorContains(t, ValidateChainID(""), "1 to 50")
	uassert.ErrorContains(t, ValidateChainID(strings.Repeat("x", 51)), "1 to 50")
	uassert.ErrorContains(t, ValidateChainID("gno land"), "[A-Za-z0-9._-]")
	uassert.ErrorContains(t, ValidateChainID("a|b"), "[A-Za-z0-9._-]")
}

func TestValidateEndpoint(t *testing.T) {
	cases := []struct {
		kind EndpointKind
		addr string
		err  string
	}{
		{RPC, "https://rpc.gno.land", ""},
		{RPC, "https://rpc.gno.land:443", ""},
		{RPC, "http://127.0.0.1:26657", ""},
		{RPC, "tcp://127.0.0.1:26657", ""},
		{RPC, "wss://rpc.gno.land/websocket", ""},
		{Gnoweb, "https://gno.land", ""},
		{Indexer, "https://indexer.gno.land/graphql/query", ""},
		{Faucet, "https://onyx.testnets.gno.land/faucet", ""},
		{Explorer, "https://gnoscan.io/?chainId=onyx-1", ""},
		{Seed, nodeID + "@seed-1.gno.land:26656", ""},
		{Peer, nodeID + "@10.0.0.1:26656", ""},

		{RPC, "", "is empty"},
		{RPC, "rpc.gno.land", "needs a scheme"},
		{RPC, "ftp://rpc.gno.land", "scheme is"},
		{Gnoweb, "tcp://gno.land", "scheme is"},
		{RPC, "https://", "has no host"},
		{RPC, "https:///path", "has no host"},
		{RPC, "https://user:[email protected]", "credentials"},
		{Gnoweb, "https://gno.land/a b", "contains"},
		{Gnoweb, "https://gno.land/)evil", "contains"},
		{Gnoweb, "https://gno.land/[x]", "contains"},
		{Gnoweb, "https://gno.land/\"x", "contains"},
		{Gnoweb, "https://gno.land/é", "contains"},
		{Gnoweb, "https://gno.land/" + strings.Repeat("a", MaxURLLen), "longer than"},

		{RPC, "https://:26657", "has no host"},
		{RPC, "https://host:not-a-port", "port is 1 to 65535"},
		{RPC, "https://host:99999", "port is 1 to 65535"},
		{RPC, "https://host:", "port is 1 to 65535"},
		{RPC, "https://ho_st", "DNS name"},
		{RPC, "https://[::1]:26657", "contains"},
		{RPC, "https://rpc.gno.land:443/path?x=1", ""},
		{RPC, "https://rpc.gno.land:443/path?x=1#f", "contains"}, // a fragment is never sent: no second listing
		{RPC, "https://rpc.gno.land:+443", "port is 1 to 65535"},
		{Gnoweb, "https://gno.land/%zz", "two hex digits"},
		{Gnoweb, "https://gno.land/%2", "two hex digits"},
		{Gnoweb, "https://gno.land/%2F", ""},
		{Gnoweb, "https://gno.land/?a=1&b=2", ""},
		{Gnoweb, "https://gno.land/?a=1&amp;b=2", "entity"},
		{Gnoweb, "https://0x7f.1", "DNS name"},
		{Gnoweb, "https://a.1", "DNS name"},
		{Gnoweb, "https://foo.123", "DNS name"},
		{Gnoweb, "https://1.2.3.4", ""},
		{Peer, "[email protected]:26656", "lowercase g1 address"},
		{Peer, nodeID + "@seed-1.gno.land:+26656", "1 to 65535"},
		{Peer, nodeID + "@" + strings.Repeat("a.", 120) + "example:26656", "longer than"},
		{RPC, "https://rpc.gno.land.", ""},
		{RPC, "http://10.0.0.1:26657", ""},
		{RPC, "http://localhost:26657", ""},
		{RPC, "https://-.example.com", "DNS name"},
		{RPC, "https://bad-.example.com", "DNS name"},
		{RPC, "https://-bad.example.com", "DNS name"},
		{RPC, "https://foo..example.com", "DNS name"},
		{RPC, "https://.example.com", "DNS name"},
		{RPC, "https://example..", "DNS name"},
		{RPC, "https://" + strings.Repeat("a", 64) + ".example.com", "DNS name"},
		{RPC, "https://" + strings.Repeat("a", 63) + ".example.com", ""},
		{RPC, "http://300.1.1.1", "DNS name"},
		{RPC, "http://1.2.3", "DNS name"},
		{RPC, "http://01.2.3.4", "DNS name"},
		{Peer, nodeID + "@bad-.example.com:26656", "DNS name"},

		{Peer, "seed-1.gno.land:26656", "<node id>@"},
		{Peer, "[email protected]:26656", "g1 address"},
		{Peer, nodeID + "@seed-1.gno.land", "needs a port"},
		{Peer, nodeID + "@:26656", "needs a port"},
		{Peer, nodeID + "@seed-1.gno.land:0", "1 to 65535"},
		{Peer, nodeID + "@seed-1.gno.land:65536", "1 to 65535"},
		{Peer, nodeID + "@seed-1.gno.land:080", "1 to 65535"},
		{Peer, nodeID + "@seed-1.gno.land:port", "1 to 65535"},
		{Seed, nodeID + "@seed_1.gno.land:26656", "DNS name"},
		{Seed, nodeID + "@[::1]:26656", "DNS name"},

		{RPC, "HTTPS://rpc.gno.land", ""},
		{Gnoweb, "Https://gno.land", ""},
		{" rpc ", "not a url", "unknown endpoint kind"},
		{"RPC", "https://rpc.gno.land", "unknown endpoint kind"},
		{"", "https://gno.land", "needs a kind"},
		{"grpc", "https://gno.land", "unknown endpoint kind"},
	}
	for _, c := range cases {
		err := ValidateEndpoint(c.kind, c.addr)
		label := string(c.kind) + " " + c.addr
		if c.err == "" {
			uassert.NoError(t, err, label)
		} else {
			uassert.ErrorContains(t, err, c.err, label)
		}
	}
}

func TestValidateInfo(t *testing.T) {
	ok := Info{ChainID: "onyx-1", Title: "Onyx", Kind: Testnet, RPCURL: "https://rpc.onyx.testnets.gno.land"}
	uassert.NoError(t, ValidateInfo(ok))
	// A loopback main RPC is a local zone's, and only a local zone's: it names a
	// different machine for every reader.
	tcp := ok
	tcp.RPCURL = "tcp://127.0.0.1:26657"
	uassert.ErrorContains(t, ValidateInfo(tcp), "private or special-use")
	tcp.Kind = Local
	uassert.NoError(t, ValidateInfo(tcp))
	for _, h := range []string{"http://localhost:26657", "http://10.0.0.1:26657", "http://192.168.1.2", "http://172.20.0.1",
		"http://169.254.169.254", "http://100.64.0.1", "http://0.0.0.0:26657", "http://api.localhost"} {
		in := ok
		in.RPCURL = h
		uassert.ErrorContains(t, ValidateInfo(in), "private or special-use", h)
	}
	pub := ok
	pub.RPCURL = "http://172.32.0.1"
	uassert.NoError(t, ValidateInfo(pub))

	bad := func(mut func(*Info), want string) {
		in := ok
		mut(&in)
		uassert.ErrorContains(t, ValidateInfo(in), want)
	}
	bad(func(in *Info) { in.ChainID = "" }, "chain id")
	bad(func(in *Info) { in.Title = "" }, "title is 1 to 64")
	bad(func(in *Info) { in.Title = strings.Repeat("x", MaxTitleLen+1) }, "title is longer than 64")
	bad(func(in *Info) { in.Title = "two\nlines" }, "control character")
	bad(func(in *Info) { in.Title = "\u200b" }, "invisible or bidi")
	bad(func(in *Info) { in.Title = "\u2060" }, "invisible or bidi")
	bad(func(in *Info) { in.Title = "\u3164" }, "invisible or bidi")
	bad(func(in *Info) { in.Title = "\u061cOnyx" }, "invisible or bidi")
	bad(func(in *Info) { in.Title = "Onyx\U000e0041" }, "invisible or bidi")
	bad(func(in *Info) { in.Title = "\u2800" }, "invisible or bidi")
	bad(func(in *Info) { in.Title = "x\u17b4" }, "invisible or bidi")    // Khmer inherent vowels draw nothing
	bad(func(in *Info) { in.Description = "\u0301" }, "nothing visible") // optional, but not blank
	bad(func(in *Info) { in.Title = "\ue000 Onyx" }, "which this chain does not draw")
	bad(func(in *Info) { in.Title = "a\u180bb" }, "invisible or bidi")   // a Mongolian selector after a Latin letter
	bad(func(in *Info) { in.Title = "Onyx\ufe0f" }, "invisible or bidi") // after a letter it modifies nothing
	bad(func(in *Info) { in.Title = "a\U000e0100" }, "invisible or bidi")
	for _, r := range []rune{0x115F, 0x1160, 0xFFA0, 0x17B5, 0x13441, 0x13442, 0x16FE4} {
		r := r
		bad(func(in *Info) { in.Title = "on" + string(r) + "yx" }, "invisible or bidi")
	}
	// Enclosing marks draw a badge's frame around any character.
	for _, s := range []string{"!\u20e4 flagged", "v\u20de verified", "x\u20e0", "x\u20dd"} {
		s := s
		bad(func(in *Info) { in.Title = s }, "enclosing mark")
	}
	// √ is maths, not a badge; × is everyday text. A variation selector after a
	// base it modifies is text: an emoji heart as a phone writes it, a
	// Mongolian free variant, an ideographic variation sequence.
	for _, s := range []string{"fees scale with \u221an", "1920\u00d71080", "made with \u2764\ufe0f",
		"\u2764\ufe0e text heart", "\u2211\ufe0f", "\u203c\ufe0f new", "\u2049\ufe0f", "\u2139\ufe0f", "\u3030\ufe0f", "\u303d\ufe0f",
		"\u18aa\u180b",
		"\u1828\u180b\u1821", "\u845b\U000e0100"} {
		good := ok
		good.Description = s
		uassert.NoError(t, ValidateInfo(good), s)
	}
	for _, r := range []rune{0x2713, 0x2714, 0x2611, 0x1F5F8, 0x1F5F9, 0x1F197, 0x2716, 0x2717, 0x2718, 0x2715,
		0x274E, 0x2612, 0x1F6AB, 0x26D4, 0x1F6D1, 0x1F5F4, 0x1F5F7, 0x231B, 0x23F8, 0x23FA, 0x2705, 0x26A0,
		0x23F3, 0x274C, 0x23F9, 0x1FBB1, 0x237B, 0x10102, 0x1F5D9, 0x2A2F, 0x2573, 0x2BBD, 0x2BBF, 0x29D6,
		0x29D7, 0x1F7A8, 0x1F7AE, 0x2613, 0x2A09, 0x22A0, 0x2327, 0x1F147, 0x1F187, 0x2297, 0x2A02, 0x1F167,
		0x1F6C7, 0x2298, 0x29B8, 0x24CD, 0x24E7, 0x24B3, 0x1F127, 0x29BB, 0x2A34, 0x2A35, 0x2A37, 0x292B,
		0x292C, 0x1F532, 0x1F533, 0x26DD, 0x1F5BE, 0x2B59, 0x2A36, 0x26D2, 0x1FBC0, 0x1D145, 0x26CC, 0x2A3B,
		0x2BBE, 0x1F5F5, 0x1F5F6} {
		r := r
		bad(func(in *Info) { in.Title = string(r) + " official" }, "status glyph")
	}
	bad(func(in *Info) { in.Title = "\u2705 official mainnet" }, "status glyph")
	bad(func(in *Info) { in.Title = "Z\u0301\u0301\u0301\u0301\u0301" }, "combining marks")
	// The limit is a run: four marks pass, and a base character ends a run, so
	// two runs of three are not a stack of six. A spacing mark is not a stack
	// either, so real words in these scripts pass.
	// A spacing mark (U+093E) between two runs of four ends the first run.
	for _, word := range []string{"Z\u0301\u0301\u0301\u0301", "a\u0301\u0301\u0301b\u0301\u0301\u0301",
		"\u0915\u0301\u0301\u0301\u0301\u093e\u0301\u0301\u0301\u0301",
		"ज़िंदगी", "ਜ਼ਿੰਦਗੀ", "ကြိုး", "སྒྲུབ"} {
		good := ok
		good.Title = word
		uassert.NoError(t, ValidateInfo(good), word)
	}
	bad(func(in *Info) { in.Title = "\u0301" }, "nothing visible")
	bad(func(in *Info) { in.Title = "bad\xffbyte" }, "not valid UTF-8")
	bad(func(in *Info) { in.Title = "alpha\u2028beta" }, "control character")
	bad(func(in *Info) { in.Title = "alpha\u2029beta" }, "control character")
	bad(func(in *Info) { in.Title = "alpha\u0085beta" }, "control character")
	bad(func(in *Info) { in.Description = "x\u009by" }, "control character")
	bad(func(in *Info) { in.Title = "Onyx\u202e" }, "invisible or bidi")
	bad(func(in *Info) { in.Description = "fine\u200dtext" }, "invisible or bidi")
	bad(func(in *Info) { in.Description = strings.Repeat("x", MaxDescriptionLen+1) }, "description is longer than 512")
	bad(func(in *Info) { in.Kind = "" }, "needs a kind")
	bad(func(in *Info) { in.Kind = "betanet" }, "unknown kind")
	bad(func(in *Info) { in.RPCURL = "" }, "rpc url is empty")
	// The main RPC is what gnokey -remote gets, which dials http, https, tcp.
	bad(func(in *Info) { in.RPCURL = "wss://rpc.onyx.testnets.gno.land/websocket" }, "rpc url scheme")
	bad(func(in *Info) { in.RPCURL = "ws://rpc.onyx.testnets.gno.land/websocket" }, "rpc url scheme")
	bad(func(in *Info) { in.RPCURL = "https://rpc.example.com/path" }, "no path")
	bad(func(in *Info) { in.RPCURL = "https://rpc.example.com?x=1" }, "no path")
	bad(func(in *Info) { in.RPCURL = "https://rpc.example.com:443#f" }, "contains")
	bad(func(in *Info) { in.RPCURL = "https://rpc.example.com/" }, "no path")
	bad(func(in *Info) { in.Kind = " testnet " }, "unknown kind")
	port := ok
	port.RPCURL = "https://rpc.onyx.testnets.gno.land:443"
	uassert.NoError(t, ValidateInfo(port))
	bad(func(in *Info) { in.GnowebURL = "gno.land" }, "gnoweb url needs a scheme")
	bad(func(in *Info) { in.GenesisURL = "tcp://x" }, "genesis url scheme")

	// Runes, not bytes: a 64-character title of multi-byte runes is fine.
	in := ok
	in.Title = strings.Repeat("é", MaxTitleLen)
	uassert.NoError(t, ValidateInfo(in))
}

func TestCanonical(t *testing.T) {
	uassert.Equal(t, "https://rpc.gno.land/API?Q=1", Canonical(RPC, "HTTPS://RPC.Gno.Land/API?Q=1"))
	uassert.Equal(t, "https://rpc.gno.land", Canonical(RPC, "https://RPC.gno.land"))
	// One endpoint, one key: every spelling below is the same server.
	for _, same := range []string{"https://rpc.gno.land", "https://rpc.gno.land/", "https://rpc.gno.land.",
		"https://rpc.gno.land:443", "https://rpc.gno.land?", "HTTPS://RPC.gno.land.:443/"} {
		uassert.Equal(t, "https://rpc.gno.land", Canonical(RPC, same), same)
	}
	uassert.Equal(t, "http://h.example.com", Canonical(Gnoweb, "http://h.example.com:80"))
	uassert.Equal(t, "http://h.example.com:443", Canonical(Gnoweb, "http://h.example.com:443")) // not http's default
	uassert.Equal(t, "https://h.example.com/api", Canonical(Indexer, "https://h.example.com:443/api"))
	uassert.Equal(t, nodeID+"@seed-1.gno.land:26656", Canonical(Peer, nodeID+"@SEED-1.gno.land:26656"))
}

func TestParse(t *testing.T) {
	for _, s := range []string{"", "approved", "pending", "rejected", "retired"} {
		_, err := ParseStatus(s)
		uassert.NoError(t, err, s)
	}
	_, err := ParseStatus("official")
	uassert.ErrorContains(t, err, "unknown status")

	_, err = ParseKind("betanet")
	uassert.ErrorContains(t, err, "unknown kind")
	k, err := ParseKind(" testnet ")
	uassert.NoError(t, err)
	uassert.Equal(t, string(Testnet), string(k))

	_, err = ParseEndpointKind("grpc")
	uassert.ErrorContains(t, err, "unknown endpoint kind")
	_, err = ParseVerification("trusted")
	uassert.ErrorContains(t, err, "unknown verification")

	// Every listed value parses back to itself.
	for _, v := range EndpointKinds() {
		got, err := ParseEndpointKind(string(v))
		uassert.NoError(t, err)
		uassert.Equal(t, string(v), string(got))
	}
	for _, v := range Kinds() {
		got, _ := ParseKind(string(v))
		uassert.Equal(t, string(v), string(got))
	}
	for _, v := range Statuses() {
		got, _ := ParseStatus(string(v))
		uassert.Equal(t, string(v), string(got))
	}
	for _, v := range Verifications() {
		got, _ := ParseVerification(string(v))
		uassert.Equal(t, string(v), string(got))
	}
}