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

Playground

cache.gno

package validators

import (
	"chain"
	"chain/runtime"
	"sort"
	"strconv"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/sys/validators/v0"
	sysparams "gno.land/r/sys/params"
)

// valopersRealmPath is the only realm allowed to refresh valoperCache
// or invoke RotateValoperSigningKey. Both auth checks below depend on
// being called via `cross` from a crossing function in valopers.
const valopersRealmPath = "gno.land/r/gnops/valopers"

// valoperCache mirrors the (operator -> current signing key) view from
// r/gnops/valopers. Written by valopers via NotifyValoperChanged. Read
// by future operator-keyed proposal flow (step 5).
//
// Pushing (valopers passes the values as args) rather than pulling
// (v0 imports valopers and reads them) — pulling would create an
// import cycle, since valopers already imports v0 for IsValidator.
var valoperCache = bptree.NewBPTree32()

type cacheEntry struct {
	SigningPubKey  string
	SigningAddress address
	KeepRunning    bool
}

// assertValopersCaller panics if the caller realm is not r/gnops/valopers.
// Per docs/resources/gno-interrealm.md, this check works only when (a)
// the host function is a crossing function (`cur realm`) and (b) it's
// invoked via `cross` from a crossing function in valopers. Then
// PreviousRealm() shifts exactly one frame to valopers. A user MsgCall
// would see PreviousRealm() == UserRealm (pkgpath ""); a third realm
// cross-call would see its own pkgpath. Either fails this check.
func assertValopersCaller(_ int, rlm realm) {
	// Defense-in-depth IsCurrent gate. Current call sites pass live
	// cur (cross(cur) from valopers), so this never fires today — but
	// the helper trusts its rlm input, and any future call that threads
	// a stashed/sibling-frame realm value with .Previous().PkgPath() ==
	// valopersRealmPath would silently bypass the gate (Class-2
	// designation forgery; see docs/resources/gno-security.md). Gating
	// here makes the precondition enforceable rather than convention.
	if !rlm.IsCurrent() {
		panic("unauthorized: rlm is not the caller's live cur")
	}
	caller := rlm.Previous().PkgPath()
	if caller != valopersRealmPath {
		panic("caller realm must be " + valopersRealmPath + ", got " + caller)
	}
}

// NotifyValoperChanged refreshes the cached entry for op. Auth: caller
// realm must be r/gnops/valopers.
//
// READ-ONLY against valopers: by design this function does not call
// back into valopers (no pull). Valopers pushes the current values in
// as args. This eliminates the confused-deputy class where v0 → valopers
// callbacks would make valopers see v0 as PreviousRealm.
func NotifyValoperChanged(cur realm, op address, signingPubKey string, signingAddress address, keepRunning bool) {
	assertValopersCaller(0, cur)
	valoperCache.Set(op.String(), cacheEntry{
		SigningPubKey:  signingPubKey,
		SigningAddress: signingAddress,
		KeepRunning:    keepRunning,
	})
}

// RotateValoperSigningKey applies a signing-key rotation to the
// effective valset and publishes the new full set via sysparams.
// Auth: caller realm must be r/gnops/valopers.
//
// Body is read-modify-write against sysparams.GetValsetEffective so
// concurrent same-block writers (other rotations or GovDAO executors)
// accumulate instead of clobbering. Mirrors the executor pattern in
// validators.gno.
//
// Idempotent: if the rotating operator's old signing address is not
// currently in the effective valset (e.g., they were removed), the
// rotation is a no-op at the sysparams level — valopers' profile and
// signingRegistry already record the new key. Either replays cleanly.
//
// Emits ValoperRotated event with op + old/new addresses + height.
func RotateValoperSigningKey(cur realm, op address, oldPubKey, newPubKey string) {
	assertValopersCaller(0, cur)

	oldAddr, err := chain.PubKeyAddress(oldPubKey)
	if err != nil {
		panic("invalid oldPubKey: " + err.Error())
	}
	newAddr, err := chain.PubKeyAddress(newPubKey)
	if err != nil {
		panic("invalid newPubKey: " + err.Error())
	}

	baseline := sysparams.GetValsetEffective()
	set := make(map[address]validators.Validator, len(baseline))
	for _, v := range baseline {
		set[v.Address] = v
	}

	// The rotating operator must currently be in the active set; if
	// not (operator removed before rotating), nothing to publish.
	// Valopers-side state has already been updated regardless.
	prev, ok := set[oldAddr]
	if !ok {
		chain.Emit(
			"ValoperRotated",
			"op", op.String(),
			"oldAddr", oldAddr.String(),
			"newAddr", newAddr.String(),
			"height", strconv.FormatInt(runtime.ChainHeight(), 10),
			"applied", "false",
		)
		return
	}

	delete(set, oldAddr)
	set[newAddr] = validators.Validator{
		Address:     newAddr,
		PubKey:      newPubKey,
		VotingPower: prev.VotingPower,
	}

	// Defense-in-depth: a delete+insert in this branch always leaves
	// at least one entry (the freshly inserted newAddr), so an empty
	// set is unreachable today. Panic explicitly anyway: a future
	// refactor of this body that ends up publishing an empty set
	// would otherwise be silently swallowed by the EndBlocker
	// (which logs and clears dirty for empty publishes), masking
	// the regression.
	if len(set) == 0 {
		panic("rotation would empty the validator set; refused to keep consensus liveness")
	}

	entries := make([]string, 0, len(set))
	for _, v := range set {
		entries = append(entries, v.PubKey+":"+strconv.FormatUint(v.VotingPower, 10))
	}
	sort.Strings(entries)
	sysparams.SetValsetProposal(cross(cur), entries)

	chain.Emit(
		"ValoperRotated",
		"op", op.String(),
		"oldAddr", oldAddr.String(),
		"newAddr", newAddr.String(),
		"height", strconv.FormatInt(runtime.ChainHeight(), 10),
		"applied", "true",
	)
}

// AssertGenesisValopersConsistent panics if any entry in valset:current
// (the seeded genesis valset) lacks a corresponding valoperCache profile
// whose SigningAddress matches.
//
// **Genesis-mode only.** The function refuses to run unless
// runtime.ChainHeight() == 0. This is the documented intended usage
// (last migration .jsonl tx, before any block has been produced) and
// also closes a post-genesis MsgCall DoS surface — without the guard,
// an attacker could pay gas to repeatedly invoke an O(N) iteration
// over valoperCache + valset:current after the chain is live.
//
// gnoland's InitChainer auto-runs this assertion at end of
// genesis-mode replay when GnoGenesisState.PastChainIDs is non-empty;
// failure aborts the boot unconditionally. valoper-seed and
// hand-crafted migration .jsonls do NOT need to emit the call
// themselves.
//
// Crossing function: callable via MsgCall (only at genesis-mode).
// Doesn't mutate state — pure invariant check. Inverse direction
// (every valoperCache entry must have a corresponding valset:current
// entry) is intentionally NOT checked: extra valoper profiles
// registered without immediate valset inclusion are a normal
// post-genesis state.
func AssertGenesisValopersConsistent(cur realm) {
	if runtime.ChainHeight() != 0 {
		panic("AssertGenesisValopersConsistent is only callable during genesis-mode replay (ChainHeight()==0)")
	}

	// Collect the signing addresses present in valoperCache.
	seen := map[string]bool{}
	valoperCache.Iterate("", "", func(_ string, raw any) bool {
		entry := raw.(cacheEntry)
		seen[entry.SigningAddress.String()] = true
		return false
	})

	// Every entry in valset:current must appear in seen.
	for _, v := range sysparams.GetValsetEntries() {
		if !seen[v.Address.String()] {
			panic("genesis-validator " + v.Address.String() + " has no corresponding valoper profile (signing address not in valoperCache)")
		}
	}
}

cache_test.gno

package validators

import (
	"testing"

	"gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
	sysparams "gno.land/r/sys/params"
)

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

// resetCache clears valoperCache so subtests don't leak state.
func resetCache() {
	valoperCache = bptree.NewBPTree32()
}

func TestNotifyValoperChanged_HappyPath(cur realm, t *testing.T) {
	resetCache()

	op := testutils.TestAddress("op-A")
	signingAddr := mustAddr(t, pubKeyA)

	// Caller realm = valopers; auth check passes.
	testing.SetRealm(testing.NewCodeRealm(valopersRealmPath))

	NotifyValoperChanged(cross(cur), op, pubKeyA, signingAddr, true)

	rawEntry := valoperCache.Get(op.String())
	urequire.NotNil(t, rawEntry, "cache entry must exist")
	entry := rawEntry.(cacheEntry)
	uassert.Equal(t, pubKeyA, entry.SigningPubKey)
	uassert.Equal(t, signingAddr, entry.SigningAddress)
	uassert.Equal(t, true, entry.KeepRunning)

	// Subsequent call updates the same slot.
	signingAddrB := mustAddr(t, pubKeyB)
	NotifyValoperChanged(cross(cur), op, pubKeyB, signingAddrB, false)

	rawEntry = valoperCache.Get(op.String())
	urequire.NotNil(t, rawEntry)
	entry = rawEntry.(cacheEntry)
	uassert.Equal(t, pubKeyB, entry.SigningPubKey)
	uassert.Equal(t, signingAddrB, entry.SigningAddress)
	uassert.Equal(t, false, entry.KeepRunning)
}

func TestNotifyValoperChanged_RejectsNonValopersCaller(cur realm, t *testing.T) {
	resetCache()

	op := testutils.TestAddress("op-A")
	signingAddr := mustAddr(t, pubKeyA)

	// Caller realm = some other realm; auth check rejects.
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/attacker"))

	uassert.AbortsContains(t, cur, "caller realm must be "+valopersRealmPath, func() {
		NotifyValoperChanged(cross(cur), op, pubKeyA, signingAddr, true)
	})

	// User MsgCall — UserRealm has empty pkgpath; rejected the same way.
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("user")))

	uassert.AbortsContains(t, cur, "caller realm must be "+valopersRealmPath, func() {
		NotifyValoperChanged(cross(cur), op, pubKeyA, signingAddr, true)
	})
}

func TestRotateValoperSigningKey_AppliesRotation(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	// Seed the valset with op-A signing under pubKeyA at power=10.
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})

	op := testutils.TestAddress("op-A")
	testing.SetRealm(testing.NewCodeRealm(valopersRealmPath))

	RotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)

	// After rotation the effective set (proposed-when-dirty) should
	// contain pubKeyB at the same power; pubKeyA should be gone.
	uassert.True(t, sysparams.ValsetDirty(), "dirty bit set after RotateValoperSigningKey")

	effective := sysparams.GetValsetEffective()
	urequire.Equal(t, 1, len(effective))
	uassert.Equal(t, pubKeyB, effective[0].PubKey)
	uassert.Equal(t, uint64(10), effective[0].VotingPower)
}

func TestRotateValoperSigningKey_OperatorNotInValset_NoOp(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	// Empty valset; the operator is not currently signing.
	op := testutils.TestAddress("op-A")
	testing.SetRealm(testing.NewCodeRealm(valopersRealmPath))

	// Should not panic; no sysparams write expected (dirty stays false).
	uassert.NotAborts(t, cur, func() {
		RotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)
	})

	uassert.False(t, sysparams.ValsetDirty(), "dirty bit must remain false on no-op rotation")
	uassert.Equal(t, 0, len(sysparams.GetValsetEffective()))
}

func TestRotateValoperSigningKey_RejectsNonValopersCaller(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})

	op := testutils.TestAddress("op-A")

	// Foreign realm — rejected.
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/attacker"))
	uassert.AbortsContains(t, cur, "caller realm must be "+valopersRealmPath, func() {
		RotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)
	})

	// User MsgCall — UserRealm pkgpath is "" — rejected.
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("user")))
	uassert.AbortsContains(t, cur, "caller realm must be "+valopersRealmPath, func() {
		RotateValoperSigningKey(cross(cur), op, pubKeyA, pubKeyB)
	})

	// Sanity: the valset wasn't mutated by the rejected calls (dirty
	// bit stays false; effective set still equals the seeded current).
	uassert.False(t, sysparams.ValsetDirty())
	effective := sysparams.GetValsetEffective()
	urequire.Equal(t, 1, len(effective))
	uassert.Equal(t, pubKeyA, effective[0].PubKey)
}

func TestAssertGenesisValopersConsistent_HappyPath(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()
	testing.SetHeight(0) // assertion is genesis-mode only

	// Seed valset:current with two genesis validators.
	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":10",
		pubKeyB + ":5",
	})

	// Seed valoperCache with profiles whose SigningAddress matches.
	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	uassert.NotAborts(t, cur, func() {
		AssertGenesisValopersConsistent(cross(cur))
	})
}

func TestAssertGenesisValopersConsistent_PanicsOnMissingProfile(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()
	testing.SetHeight(0)

	// Two validators in valset:current but only one has a profile.
	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":10",
		pubKeyB + ":5",
	})

	opA := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		// op for pubKeyB intentionally missing.
	})

	uassert.AbortsContains(t, cur, "no corresponding valoper profile", func() {
		AssertGenesisValopersConsistent(cross(cur))
	})
}

func TestAssertGenesisValopersConsistent_EmptyValsetTrivial(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()
	testing.SetHeight(0)

	// Empty valset → assertion trivially holds (no entries to check).
	uassert.NotAborts(t, cur, func() {
		AssertGenesisValopersConsistent(cross(cur))
	})
}

func TestAssertGenesisValopersConsistent_RejectsPostGenesis(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()
	// Default test height is non-zero (123); the assertion must
	// refuse to run outside genesis-mode replay.
	uassert.AbortsContains(t, cur, "only callable during genesis-mode replay", func() {
		AssertGenesisValopersConsistent(cross(cur))
	})
}

func TestRotateValoperSigningKey_AccumulatesAcrossSameBlock(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	// Seed valset with two operators signing under pubKeyA and pubKeyC.
	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":10",
		pubKeyC + ":5",
	})

	opA := testutils.TestAddress("op-A")
	opC := testutils.TestAddress("op-C")
	testing.SetRealm(testing.NewCodeRealm(valopersRealmPath))

	// First rotation: A → B. Read-modify-write of GetValsetEffective.
	RotateValoperSigningKey(cross(cur), opA, pubKeyA, pubKeyB)

	// Second rotation in the same block: C → A. Should not clobber
	// the first rotation; should read proposed-when-dirty as baseline.
	RotateValoperSigningKey(cross(cur), opC, pubKeyC, pubKeyA)

	// Final effective set: {pubKeyB:10, pubKeyA:5}. Order may differ
	// because GetValsetEffective parses sysparams' sorted-string slot
	// and returns []Validator preserving that order.
	effective := sysparams.GetValsetEffective()
	urequire.Equal(t, 2, len(effective))

	// Build a power-by-pubkey map and assert.
	powerOf := map[string]uint64{}
	for _, v := range effective {
		powerOf[v.PubKey] = v.VotingPower
	}
	uassert.Equal(t, uint64(10), powerOf[pubKeyB])
	uassert.Equal(t, uint64(5), powerOf[pubKeyA])
	_, ok := powerOf[pubKeyC]
	uassert.False(t, ok, "pubKeyC should be replaced by pubKeyA at the rotated slot")
}

gnomod.toml

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

[addpkg]
  creator = "g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l"

proposal.gno

package validators

import (
	"sort"
	"strconv"
	"strings"

	"chain"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/p/sys/validators/v0"
	"gno.land/r/gov/dao"
	sysparams "gno.land/r/sys/params"
)

// ValoperChange is the operator-keyed input shape for the v0 valset
// proposal builder. Power=0 removes; Power>0 adds (or upserts the
// power on an op already in the active set — Tendermint's natural
// ValidatorUpdate semantics).
//
// Each operator may appear AT MOST ONCE per proposal; duplicates are
// rejected at create-time.
type ValoperChange struct {
	OperatorAddress address
	Power           uint64
}

func NewValoperChange(operatorAddress address, power uint64) ValoperChange {
	return ValoperChange{
		OperatorAddress: operatorAddress,
		Power:           power,
	}
}

const errNoValoperChanges = "no valoper changes proposed"

// NewValidatorProposalRequest builds a GovDAO proposal that, when
// executed, applies the deltas to the chain's effective valset and
// publishes the new full set via SetValsetProposal.
//
// NON-CROSSING (no `cur realm`). Direct MsgCall is unsupported;
// proposers route through r/gnops/valopers/proposal's facade
// (which IS crossing and accepts user txs).
//
// Validation at creation time:
//   - Each operator may appear AT MOST ONCE in changes; duplicates
//     panic. Power changes for an op already in the active set use
//     a single {op, newPower} entry (upsert), not the legacy
//     remove/re-add pair.
//   - Every ValoperChange's OperatorAddress must exist in
//     valoperCache. Unknown operators panic.
//   - Adds (Power > 0) require KeepRunning=true. An op that has
//     called UpdateKeepRunning(false) signals opt-out; no proposal
//     can keep them in the active set, period.
//
// Pubkey resolution at execution time: the executor callback
// re-reads valoperCache for each entry to capture the CURRENT
// signing pubkey/address — not the creation-time one. Defends
// against a stale (now-retired) key publication if the operator
// rotated while the proposal sat in GovDAO. Also re-checks
// KeepRunning so an operator flipping to KeepRunning=false between
// propose-create and propose-execute is honored. Removes are
// unaffected (operator address is the lookup key, not signing
// address).
//
// Emits ValidatorAdded / ValidatorRemoved events per entry on
// successful execution. (Power-upsert on an existing op also emits
// ValidatorAdded with the new power.)
func NewValidatorProposalRequest(cur realm, changes []ValoperChange, title, description string) dao.ProposalRequest {
	if len(changes) == 0 {
		panic(errNoValoperChanges)
	}
	title = strings.TrimSpace(title)
	if title == "" {
		panic("proposal title is empty")
	}
	if len(changes) > 40 {
		panic("max number of allowed validators per proposal is 40")
	}

	// Dedupe: each operator may appear at most once per proposal.
	// Power changes are now expressed as a single {op, newPower}
	// upsert entry, so the legacy [{op,0},{op,N}] pair is a duplicate
	// and rejected.
	seen := map[string]bool{}
	for _, c := range changes {
		key := c.OperatorAddress.String()
		if seen[key] {
			panic("duplicate operator in proposal: " + key)
		}
		seen[key] = true
	}

	// Creation-time validation: every operator must exist in cache,
	// and adds require KeepRunning=true. KeepRunning=false is a
	// binding opt-out; no proposal shape can override it.
	for _, c := range changes {
		rawCache := valoperCache.Get(c.OperatorAddress.String())
		if rawCache == nil {
			panic("unknown operator: " + c.OperatorAddress.String())
		}
		entry := rawCache.(cacheEntry)
		if c.Power > 0 && !entry.KeepRunning {
			panic("operator " + c.OperatorAddress.String() + " has KeepRunning=false; refusing to add (operator must call UpdateKeepRunning(true) first)")
		}
	}

	// Render description against creation-time data. Voters see the
	// operator addresses being proposed; signing addresses are an
	// implementation detail resolved at exec.
	var desc strings.Builder
	desc.WriteString(description)
	if len(description) > 0 {
		desc.WriteString("\n\n")
	}
	desc.WriteString("## Validator Updates\n")
	for _, c := range changes {
		if c.Power == 0 {
			desc.WriteString(ufmt.Sprintf("- %s: remove\n", c.OperatorAddress))
		} else {
			desc.WriteString(ufmt.Sprintf("- %s: add (power %d)\n", c.OperatorAddress, c.Power))
		}
	}

	return dao.NewProposalRequest(title, desc.String(), newValoperChangeExecutor(cur, changes))
}

// newValoperChangeExecutor builds the GovDAO executor that, on
// approval, applies the captured ValoperChange deltas. Resolves
// operator → signing addr/pubkey via valoperCache at execution time
// for adds (so a mid-flight rotation doesn't publish a stale key).
// Removes resolve the operator's CURRENT signing address (also via
// cache) — operator-keyed removes are immune to rotation churn.
//
// Power>0 is an upsert against the effective valset map (keyed on
// signing address): if the op is already present under that signing
// address, the entry's voting power is overwritten. Tendermint
// natively handles ValidatorUpdates as upserts, so a single-entry
// power change is the canonical form.
func newValoperChangeExecutor(cur realm, changes []ValoperChange) dao.Executor {
	callback := func(cur realm) error {
		baseline := sysparams.GetValsetEffective()
		set := make(map[address]validators.Validator, len(baseline))
		for _, v := range baseline {
			set[v.Address] = v
		}

		for _, c := range changes {
			rawCache := valoperCache.Get(c.OperatorAddress.String())
			if rawCache == nil {
				panic("operator vanished from valoperCache between propose and execute: " + c.OperatorAddress.String())
			}
			entry := rawCache.(cacheEntry)

			if c.Power == 0 {
				if _, ok := set[entry.SigningAddress]; !ok {
					panic("validator does not exist: " + entry.SigningAddress.String())
				}
				delete(set, entry.SigningAddress)
				chain.Emit(
					"ValidatorRemoved",
					"op", c.OperatorAddress.String(),
					"signingAddr", entry.SigningAddress.String(),
				)
				continue
			}

			// Race-safety: operator may have flipped KeepRunning=false
			// between propose-create and propose-execute. Re-check.
			// The opt-out is binding regardless of proposal shape.
			if !entry.KeepRunning {
				panic("operator " + c.OperatorAddress.String() + " has KeepRunning=false at execution; refusing to add")
			}

			// Upsert at the current signing address. If the entry was
			// already present (single-entry power change on an active
			// validator), this overwrites the prior power.
			set[entry.SigningAddress] = validators.Validator{
				Address:     entry.SigningAddress,
				PubKey:      entry.SigningPubKey,
				VotingPower: c.Power,
			}
			chain.Emit(
				"ValidatorAdded",
				"op", c.OperatorAddress.String(),
				"signingAddr", entry.SigningAddress.String(),
				"power", strconv.FormatUint(c.Power, 10),
			)
		}

		// Liveness floor: refuse to publish an empty set.
		if len(set) == 0 {
			panic("valset proposal would empty the validator set; refused to keep consensus liveness")
		}

		entries := make([]string, 0, len(set))
		for _, v := range set {
			entries = append(entries, v.PubKey+":"+strconv.FormatUint(v.VotingPower, 10))
		}
		sort.Strings(entries)
		sysparams.SetValsetProposal(cross(cur), entries)
		return nil
	}

	return dao.NewSimpleExecutor(0, cur, callback, "")
}

proposal_test.gno

package validators

import (
	"strconv"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/urequire/v0"
	sysparams "gno.land/r/sys/params"
)

// seedCache populates valoperCache with the given (op, pubkey, kr)
// tuples — used in tests to satisfy NewValidatorProposalRequest's
// creation-time membership check without going through valopers.
// asGovDAOProxy is the realm these tests stand in as before invoking an
// executor directly. SimpleExecutor.Execute is invocable only from the
// r/gov/dao namespace; on the live route dao.ExecuteProposal and
// impl.ExecuteProposal thread the proxy's cur to it non-crossing, so
// Previous() inside Execute is this path. Calling Execute from the test's
// own realm is a route no transaction takes.
const asGovDAOProxy = "gno.land/r/gov/dao"

func seedCache(t *testing.T, entries []struct {
	op          address
	pubKey      string
	keepRunning bool
}) {
	t.Helper()
	for _, e := range entries {
		signingAddr := mustAddr(t, e.pubKey)
		valoperCache.Set(e.op.String(), cacheEntry{
			SigningPubKey:  e.pubKey,
			SigningAddress: signingAddr,
			KeepRunning:    e.keepRunning,
		})
	}
}

func TestNewValidatorProposalRequest_RejectsUnknownOperator(cur realm, t *testing.T) {
	resetCache()

	op := testutils.TestAddress("ghost-op")

	uassert.PanicsContains(t, cur, "unknown operator", func() {
		_ = NewValidatorProposalRequest(cur,
			[]ValoperChange{{OperatorAddress: op, Power: 1}},
			"add ghost",
			"",
		)
	})
}

func TestNewValidatorProposalRequest_RejectsEmptyChanges(cur realm, t *testing.T) {
	resetCache()

	uassert.PanicsContains(t, cur, errNoValoperChanges, func() {
		_ = NewValidatorProposalRequest(cur, nil, "title", "")
	})
}

func TestNewValidatorProposalRequest_RejectsEmptyTitle(cur realm, t *testing.T) {
	resetCache()
	op := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: op, pubKey: pubKeyA, keepRunning: true}})

	uassert.PanicsContains(t, cur, "proposal title is empty", func() {
		_ = NewValidatorProposalRequest(cur,
			[]ValoperChange{{OperatorAddress: op, Power: 1}},
			"   ",
			"",
		)
	})
}

func TestNewValidatorProposalRequest_RejectsTooManyChanges(cur realm, t *testing.T) {
	resetCache()

	// Seed 41 cache entries so the membership check passes; the
	// length cap should fire before the per-entry validation.
	changes := make([]ValoperChange, 41)
	pubkeys := []string{pubKeyA, pubKeyB, pubKeyC}
	for i := 0; i < 41; i++ {
		op := testutils.TestAddress("op-" + strconv.Itoa(i))
		pk := pubkeys[i%3]
		valoperCache.Set(op.String(), cacheEntry{
			SigningPubKey:  pk,
			SigningAddress: mustAddr(t, pk),
			KeepRunning:    true,
		})
		changes[i] = ValoperChange{OperatorAddress: op, Power: 1}
	}

	uassert.PanicsContains(t, cur, "max number of allowed validators per proposal is 40", func() {
		_ = NewValidatorProposalRequest(cur, changes, "too many", "")
	})
}

func TestNewValidatorProposalRequest_DescriptionRendering(cur realm, t *testing.T) {
	resetCache()
	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	pr := NewValidatorProposalRequest(cur,
		[]ValoperChange{
			{OperatorAddress: opA, Power: 5},
			{OperatorAddress: opB, Power: 0},
		},
		"mixed changes",
		"context line",
	)

	desc := pr.Description()
	urequire.True(t, len(desc) > 0)
	uassert.True(t, contains(desc, "context line"))
	uassert.True(t, contains(desc, "## Validator Updates"))
	uassert.True(t, contains(desc, opA.String()+": add (power 5)"))
	uassert.True(t, contains(desc, opB.String()+": remove"))
}

func TestNewValidatorProposalRequest_ExecutorReResolvesPubkey(cur realm, t *testing.T) {
	// Creation-time captured changes: ValoperChange refers to opA.
	// Cache for opA points to pubKeyA at creation. Before execution,
	// opA's cache entry is updated to pubKeyB. Executor must publish
	// the NEW pubkey, not the creation-time one.
	resetValset(t)
	resetCache()

	opA := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: opA, pubKey: pubKeyA, keepRunning: true}})

	changes := []ValoperChange{{OperatorAddress: opA, Power: 7}}

	// Build the executor; it captures `changes` by reference (slice
	// of structs) but resolves SigningPubKey at run-time via cache.
	exec := newValoperChangeExecutor(cur, changes)

	// Simulate operator rotation: opA's cache entry now points to
	// pubKeyB. Captured changes slice is unchanged.
	valoperCache.Set(opA.String(), cacheEntry{
		SigningPubKey:  pubKeyB,
		SigningAddress: mustAddr(t, pubKeyB),
		KeepRunning:    true,
	})

	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, exec.Execute(cross(cur)))

	// Effective valset should contain pubKeyB (post-rotation), not
	// pubKeyA (creation-time).
	effective := sysparams.GetValsetEffective()
	urequire.Equal(t, 1, len(effective))
	uassert.Equal(t, pubKeyB, effective[0].PubKey)
	uassert.Equal(t, uint64(7), effective[0].VotingPower)
}

func TestNewValidatorProposalRequest_RemoveOperator(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	// Seed valset with opA already signing under pubKeyA.
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})

	opA := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: opA, pubKey: pubKeyA, keepRunning: false}})

	// Liveness floor: removing the only validator empties the set.
	// Executor runs inside a crossing dao.Executor.Execute call, so
	// the panic surfaces as an abort, not a regular panic.
	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	uassert.AbortsContains(t, cur, "would empty the validator set", func() {
		_ = newValoperChangeExecutor(cur, []ValoperChange{{OperatorAddress: opA, Power: 0}}).Execute(cross(cur))
	})
}

func TestNewValidatorProposalRequest_RemoveLeavesOthers(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	// Seed valset with two validators.
	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":10",
		pubKeyB + ":5",
	})

	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	changes := []ValoperChange{{OperatorAddress: opA, Power: 0}}
	// Build the executor directly (private function, same package).
	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, newValoperChangeExecutor(cur, changes).Execute(cross(cur)))

	// Effective set: only opB / pubKeyB remains.
	effective := sysparams.GetValsetEffective()
	urequire.Equal(t, 1, len(effective))
	uassert.Equal(t, pubKeyB, effective[0].PubKey)
}

func TestNewValidatorProposalRequest_AllowsFullValsetReplacement(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})

	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: false},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	changes := []ValoperChange{
		{OperatorAddress: opA, Power: 0},
		{OperatorAddress: opB, Power: 10},
	}
	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, newValoperChangeExecutor(cur, changes).Execute(cross(cur)))

	effective := sysparams.GetValsetEffective()
	urequire.Equal(t, 1, len(effective))
	uassert.Equal(t, pubKeyB, effective[0].PubKey)
	uassert.Equal(t, uint64(10), effective[0].VotingPower)
}

func TestNewValidatorProposalRequest_RejectsKeepRunningFalseAtCreation(cur realm, t *testing.T) {
	resetCache()
	op := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: op, pubKey: pubKeyA, keepRunning: false}})

	uassert.PanicsContains(t, cur, "KeepRunning=false", func() {
		_ = NewValidatorProposalRequest(cur,
			[]ValoperChange{{OperatorAddress: op, Power: 1}},
			"add opted-out", "",
		)
	})
}

func TestNewValidatorProposalRequest_AllowsRemoveOfKeepRunningFalse(cur realm, t *testing.T) {
	// KeepRunning=false is the operator's opt-out signal; removing
	// such an operator must still be allowed (it's the standard
	// exit path). Only adds are gated.
	resetValset(t)
	resetCache()

	// Seed the valset with two operators so removing one doesn't
	// trip the empty-valset liveness floor.
	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":10",
		pubKeyB + ":5",
	})

	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: false}, // opted out
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	// Build proposal succeeds (remove path: Power=0 ignores KeepRunning).
	pr := NewValidatorProposalRequest(cur,
		[]ValoperChange{{OperatorAddress: opA, Power: 0}},
		"remove opted-out opA", "",
	)
	_ = pr

	// Executor also succeeds.
	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, newValoperChangeExecutor(cur, []ValoperChange{{OperatorAddress: opA, Power: 0}}).Execute(cross(cur)))
}

func TestNewValidatorProposalRequest_RejectsDuplicateOp(cur realm, t *testing.T) {
	// Each operator may appear at most once per proposal; any shape
	// that mentions the same op twice must panic at create-time.
	resetCache()
	op := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: op, pubKey: pubKeyA, keepRunning: true}})

	cases := [][]ValoperChange{
		{{OperatorAddress: op, Power: 0}, {OperatorAddress: op, Power: 7}}, // remove + re-add
		{{OperatorAddress: op, Power: 7}, {OperatorAddress: op, Power: 8}}, // double add
		{{OperatorAddress: op, Power: 0}, {OperatorAddress: op, Power: 0}}, // double remove
	}
	for _, changes := range cases {
		uassert.PanicsContains(t, cur, "duplicate operator in proposal", func() {
			_ = NewValidatorProposalRequest(cur, changes, "dup", "")
		})
	}
}

func TestNewValidatorProposalRequest_RejectsPowerUpdatePairForOptedOutOp(cur realm, t *testing.T) {
	// KeepRunning=false is binding: no proposal shape can keep an
	// opted-out operator in the active set. The dedupe rejection
	// fires before the KR check is even reached.
	resetCache()
	op := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: op, pubKey: pubKeyA, keepRunning: false}})

	uassert.PanicsContains(t, cur, "duplicate operator in proposal", func() {
		_ = NewValidatorProposalRequest(cur,
			[]ValoperChange{
				{OperatorAddress: op, Power: 0},
				{OperatorAddress: op, Power: 7},
			},
			"bypass attempt", "",
		)
	})
}

func TestNewValidatorProposalRequest_UpsertExistingValidator(cur realm, t *testing.T) {
	// Single-entry {op, newPower} against an op already in the
	// effective valset must upsert: the existing entry's power is
	// overwritten, no remove/re-add ceremony required.
	resetValset(t)
	resetCache()

	// Seed valset with two validators; we upsert opA's power.
	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":1",
		pubKeyB + ":1",
	})

	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	changes := []ValoperChange{{OperatorAddress: opA, Power: 9}}
	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, newValoperChangeExecutor(cur, changes).Execute(cross(cur)))

	effective := sysparams.GetValsetEffective()
	powerOf := map[string]uint64{}
	for _, v := range effective {
		powerOf[v.PubKey] = v.VotingPower
	}
	uassert.Equal(t, uint64(9), powerOf[pubKeyA], "opA power upserted from 1 to 9")
	uassert.Equal(t, uint64(1), powerOf[pubKeyB], "opB unchanged")
}

func TestNewValidatorProposalRequest_ExecutorRejectsRaceFlippedKeepRunning(cur realm, t *testing.T) {
	// KeepRunning=true at proposal-create time; operator flips to
	// false BEFORE the executor runs. Race-safety check rejects.
	resetValset(t)
	resetCache()

	op := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: op, pubKey: pubKeyA, keepRunning: true}})

	changes := []ValoperChange{{OperatorAddress: op, Power: 5}}
	exec := newValoperChangeExecutor(cur, changes)

	// Operator flips KeepRunning=false BEFORE the executor runs.
	valoperCache.Set(op.String(), cacheEntry{
		SigningPubKey:  pubKeyA,
		SigningAddress: mustAddr(t, pubKeyA),
		KeepRunning:    false,
	})

	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	uassert.AbortsContains(t, cur, "KeepRunning=false at execution", func() {
		_ = exec.Execute(cross(cur))
	})
}

func TestNewValidatorProposalRequest_NaturalRotationFlow_NoGhost(cur realm, t *testing.T) {
	// RotateValoperSigningKey publishes valset:proposed before any
	// subsequent executor reads, so baseline always reflects the
	// post-rotation state. A later power-update upserts at NEW only;
	// no OLD ghost.
	resetValset(t)
	resetCache()

	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":1",
		pubKeyB + ":5",
	})
	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	testing.SetRealm(testing.NewCodeRealm(valopersRealmPath))
	RotateValoperSigningKey(cross(cur), opA, pubKeyA, pubKeyC)
	NotifyValoperChanged(cross(cur), opA, pubKeyC, mustAddr(t, pubKeyC), true)

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/gov/dao/impl/v0"))
	urequire.NoError(t, newValoperChangeExecutor(cur,
		[]ValoperChange{{OperatorAddress: opA, Power: 2}},
	).Execute(cross(cur)))

	effective := sysparams.GetValsetEffective()
	powerOf := map[string]uint64{}
	for _, v := range effective {
		powerOf[v.PubKey] = v.VotingPower
	}
	uassert.Equal(t, uint64(2), powerOf[pubKeyC], "opA published at NEW power=2")
	uassert.Equal(t, uint64(5), powerOf[pubKeyB], "opB unchanged")
	_, ghost := powerOf[pubKeyA]
	uassert.False(t, ghost, "OLD signing key (pubKeyA) must not linger in valset")
	urequire.Equal(t, 2, len(effective), "exactly two entries — opA(NEW), opB")
}

func TestNewValidatorProposalRequest_PhantomBaselineDocumentsUnreachableState(cur realm, t *testing.T) {
	// Pin executor behavior on a phantom state (cache=NEW,
	// valset:current=OLD, dirty=false) — unreachable via natural
	// flow because RotateValoperSigningKey publishes proposed
	// before NotifyValoperChanged updates the cache. If a future
	// code path ever updates the cache without going through
	// Rotate, the asymmetry would be a real bug; this test pins
	// the current behavior so the divergence surfaces.
	resetValset(t)
	resetCache()

	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":1",
		pubKeyB + ":5",
	})

	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyC, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, newValoperChangeExecutor(cur,
		[]ValoperChange{{OperatorAddress: opA, Power: 2}},
	).Execute(cross(cur)))

	effective := sysparams.GetValsetEffective()
	powerOf := map[string]uint64{}
	for _, v := range effective {
		powerOf[v.PubKey] = v.VotingPower
	}
	uassert.Equal(t, uint64(1), powerOf[pubKeyA], "phantom OLD lingers from baseline")
	uassert.Equal(t, uint64(2), powerOf[pubKeyC], "executor upserts at NEW")
	uassert.Equal(t, uint64(5), powerOf[pubKeyB], "opB unchanged")
	urequire.Equal(t, 3, len(effective),
		"three entries — phantom-state ghost; this state is unreachable via natural flow")
}

func TestNewValidatorProposalRequest_SameBlockExecuteThenRotate(cur realm, t *testing.T) {
	// Same-block ordering: proposal-execute writes proposed
	// (dirty=true); a subsequent rotation reads proposed-when-dirty
	// and accumulates the prior power change rather than clobbering
	// back to current.
	resetValset(t)
	resetCache()

	testing.SetSysParamStrings(module, submodule, currKey, []string{
		pubKeyA + ":1",
		pubKeyB + ":5",
	})

	opA := testutils.TestAddress("op-A")
	opB := testutils.TestAddress("op-B")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{
		{op: opA, pubKey: pubKeyA, keepRunning: true},
		{op: opB, pubKey: pubKeyB, keepRunning: true},
	})

	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	urequire.NoError(t, newValoperChangeExecutor(cur,
		[]ValoperChange{{OperatorAddress: opA, Power: 3}},
	).Execute(cross(cur)))

	testing.SetRealm(testing.NewCodeRealm(valopersRealmPath))
	RotateValoperSigningKey(cross(cur), opA, pubKeyA, pubKeyC)
	NotifyValoperChanged(cross(cur), opA, pubKeyC, mustAddr(t, pubKeyC), true)

	effective := sysparams.GetValsetEffective()
	powerOf := map[string]uint64{}
	for _, v := range effective {
		powerOf[v.PubKey] = v.VotingPower
	}
	uassert.Equal(t, uint64(3), powerOf[pubKeyC], "rotation accumulates with prior upsert; final power=3")
	uassert.Equal(t, uint64(5), powerOf[pubKeyB], "opB unchanged")
	_, gotOld := powerOf[pubKeyA]
	uassert.False(t, gotOld, "OLD signing key (pubKeyA) must not appear after rotation")
	urequire.Equal(t, 2, len(effective), "exactly two entries — opA(NEW) and opB")
}

// TestNewValidatorProposalRequest_ExecutorVanishedCacheEntryPanics pins
// the "operator vanished from valoperCache between propose and execute"
// branch. No production path deletes from valoperCache today (only Set
// is called by NotifyValoperChanged), but bptree.BPTree exposes Remove
// so the underlying data structure does support deletion. This test
// simulates that hypothetical state directly via the package-private
// cache var to confirm the executor panics with the documented message
// rather than silently mis-publishing an empty/wrong valset.
//
// If a future commit ever introduces a public cache-delete path, this
// test still passes — it's a contract-pinning test for the panic itself.
// If the team decides the branch is unreachable enough to drop, this
// test is the first thing to break.
func TestNewValidatorProposalRequest_ExecutorVanishedCacheEntryPanics(cur realm, t *testing.T) {
	resetValset(t)
	resetCache()

	op := testutils.TestAddress("op-A")
	seedCache(t, []struct {
		op          address
		pubKey      string
		keepRunning bool
	}{{op: op, pubKey: pubKeyA, keepRunning: true}})

	exec := newValoperChangeExecutor(cur,
		[]ValoperChange{{OperatorAddress: op, Power: 5}},
	)

	// Simulate the unreachable-today state: cache entry deleted between
	// proposal-create and proposal-execute. Direct package-private mutation
	// (NOT a public API) — production code has no path here today.
	_, removed := valoperCache.Remove(op.String())
	urequire.True(t, removed, "fixture: cache entry must have been present before Remove")

	testing.SetRealm(testing.NewCodeRealm(asGovDAOProxy))

	uassert.AbortsContains(t, cur, "operator vanished from valoperCache between propose and execute", func() {
		_ = exec.Execute(cross(cur))
	})
}

// contains is a tiny strings.Contains shim so tests don't import a
// new package.
func contains(s, substr string) bool {
	for i := 0; i+len(substr) <= len(s); i++ {
		if s[i:i+len(substr)] == substr {
			return true
		}
	}
	return false
}

validators.gno

// Package validators implements on-chain validator set management
// through Proof of Authority. The realm exposes a public proposal
// constructor for GovDAO; on approval, the proposal callback applies
// the captured deltas to the chain's effective valset and publishes
// the new full set via gno.land/r/sys/params. The chain's EndBlocker
// reads the result on the next block and propagates to consensus.
//
// No in-realm validator state. All reads go through
// sysparams.GetValsetEffective (proposed-if-dirty, else current).
package validators

import (
	"chain/runtime"
	"strings"

	"gno.land/p/nt/ufmt/v0"
	"gno.land/p/sys/validators/v0"
	sysparams "gno.land/r/sys/params"
)

// Operator-keyed proposal builder lives in proposal.gno
// (NewValidatorProposalRequest + newValoperChangeExecutor). The legacy
// signing-keyed NewProposalRequest was removed: every valid
// signing-keyed input is also a valid operator-keyed input under
// always-on valoper enforcement.

// IsValidator returns true if addr is part of the effective validator
// set (proposed if a v0 proposal is awaiting EndBlocker, else
// current).
func IsValidator(addr address) bool {
	for _, v := range sysparams.GetValsetEffective() {
		if v.Address == addr {
			return true
		}
	}
	return false
}

// GetValidator returns the validator with the given address from the
// effective set; panics if absent.
func GetValidator(addr address) validators.Validator {
	for _, v := range sysparams.GetValsetEffective() {
		if v.Address == addr {
			return v
		}
	}
	panic("validator not found")
}

// GetValidators returns the effective validator set.
func GetValidators() []validators.Validator {
	return sysparams.GetValsetEffective()
}

// Render displays the effective validator set.
func Render(string) string {
	var sb strings.Builder
	h := runtime.ChainHeight()
	set := sysparams.GetValsetEffective()
	sb.WriteString(ufmt.Sprintf("## Valset at height %d\n\n", h))
	if len(set) == 0 {
		sb.WriteString("Valset is empty.\n")
		return sb.String()
	}
	for i, v := range set {
		sb.WriteString(ufmt.Sprintf("- #%d: %s (%d)\n", i, v.Address.String(), v.VotingPower))
	}
	return sb.String()
}

validators_test.gno

// Tests for stateless v0.
//
// State isolation: gno's test runner constructs a fresh testParams
// per top-level TestXxx, but t.Run subtests share the same map.
// Each subtest below seeds (or clears) the valset slots it cares
// about up front; do the same when adding cases.
package validators

import (
	"chain"
	"testing"

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

const (
	// Three distinct deterministic test pubkeys (and the addresses
	// they derive to) used across the cases below. Stable across
	// runs.
	pubKeyA = "gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zq3ds6sdvc0shfkq02h6xx5g0jp04aadexfnpsmgjxu72xz9y30aqfrlpny"
	pubKeyB = "gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p"
	pubKeyC = "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqddddqg2glc8x4fl7vxjlnr7p5a3czm5kcdp4239sg6yqdc4rc2r5cjrffs"

	module    = "node"
	submodule = "valset"
	currKey   = "current"
	propKey   = "proposed"
	dirtyKey  = "dirty"
)

func resetValset(t *testing.T) {
	t.Helper()
	testing.SetSysParamStrings(module, submodule, currKey, []string{})
	testing.SetSysParamStrings(module, submodule, propKey, []string{})
	testing.SetSysParamBool(module, submodule, dirtyKey, false)
}

func mustAddr(t *testing.T, pk string) address {
	t.Helper()
	a, err := chain.PubKeyAddress(pk)
	urequire.NoError(t, err, "valid pubkey")
	return a
}

func TestEffectiveView_DirtyFalseReadsCurrent(cur realm, t *testing.T) {
	resetValset(t)
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})

	addrA := mustAddr(t, pubKeyA)
	urequire.True(t, IsValidator(addrA), "A in current")
	urequire.Equal(t, 1, len(GetValidators()))
}

func TestEffectiveView_DirtyTrueReadsProposed(cur realm, t *testing.T) {
	resetValset(t)
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})
	testing.SetSysParamStrings(module, submodule, propKey, []string{pubKeyA + ":10", pubKeyB + ":1"})
	testing.SetSysParamBool(module, submodule, dirtyKey, true)

	addrA := mustAddr(t, pubKeyA)
	addrB := mustAddr(t, pubKeyB)
	urequire.True(t, IsValidator(addrA), "A still visible")
	urequire.True(t, IsValidator(addrB), "B visible via proposed")
	urequire.Equal(t, 2, len(GetValidators()))
}

func TestGetValidator_ReturnsParsedEntry(cur realm, t *testing.T) {
	resetValset(t)
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":42"})

	v := GetValidator(mustAddr(t, pubKeyA))
	urequire.Equal(t, uint64(42), v.VotingPower)
	urequire.Equal(t, pubKeyA, v.PubKey)
}

func TestRender_DefaultTestHeight(cur realm, t *testing.T) {
	resetValset(t)
	testing.SetSysParamStrings(module, submodule, currKey, []string{pubKeyA + ":10"})

	out := Render("")
	// gnovm/pkg/test/test.go sets DefaultHeight = 123.
	urequire.Equal(t,
		"## Valset at height 123\n\n- #0: "+mustAddr(t, pubKeyA).String()+" (10)\n",
		out)
}

// The same-block accumulation, panic-on-remove-of-missing,
// panic-on-add-of-existing, and pubkey-validation tests for the
// signing-keyed NewProposalRequest/newValsetChangeExecutor were
// removed alongside the function itself. Equivalent coverage for
// the operator-keyed flow lives in proposal_test.gno
// (TestNewValidatorProposalRequest_*) and cache_test.gno
// (TestRotateValoperSigningKey_AccumulatesAcrossSameBlock).
//
// Empty-final-set rejection in the executor still applies; it's
// covered by TestNewValidatorProposalRequest_RemoveOperator in
// proposal_test.gno.