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

delegate.gno

package params

// Delegation: letting a realm other than GovDAO manage one specific parameter.
//
// This realm holds a capability nothing else can: the `sys/params` stdlib
// refuses every caller except `gno.land/r/sys/params`, checked in the VM by
// package path, and the same gate covers the getters. So every parameter write
// on the chain physically originates here, and "delegating a parameter" can only
// mean adding a path in this file that authorizes someone other than a GovDAO
// vote.
//
// Two shapes are deliberately NOT used.
//
// Not a registry of key -> realm. This realm can never be redeployed
// (AddPackage refuses an occupied path), and the stdlib gate names this exact
// path, so making a NEW parameter delegatable already requires editing this
// file, which means a chain relaunch. A registry's runtime generality would
// therefore never be exercised: the only freedom that matters is "which realm,
// or none" for keys already blessed in source. A named slot says exactly that
// and nothing more. It also removes a whole class of mistake — there is no
// key string to mis-compose, no container to accidentally expose, and no way for
// a proposal to name a key the author never considered. A shape-based allowlist
// like "<module>:p:<name>" would have admitted bank:p:restricted_denoms and
// auth:p:unrestricted_addrs, which is not a delegation anyone asked for.
//
// Not a capability object. Returning something the delegate holds would make
// authority survive revocation, because the check would have happened at
// construction. The authority is re-checked on every crossing call instead, so
// clearing the slot takes effect immediately.

import (
	"chain"

	"gno.land/r/gov/dao"
)

// Event names. PascalCase with a named const is the house style across r/sys
// and r/gov; the bare lowercase "set" elsewhere in this realm predates it.
const (
	DelegateSetEvent     = "ParamDelegateSet"
	DelegateClearedEvent = "ParamDelegateCleared"
	DelegateWriteEvent   = "ParamDelegateWrite"
)

// assertDelegate authorizes a caller as the holder of a delegated capability.
//
// want is the authorized package path, or "" when nothing is delegated.
//
// The empty check comes FIRST and is load-bearing, not defensive. A direct call
// from a user account has an empty previous package path — that is exactly what
// IsUserCall tests — so comparing against an unset slot would compare "" to ""
// and admit every user on the chain. r/gov/dao's own allowlist has the
// mirror-image bug (it returns true for everyone when the list is empty), kept
// there deliberately for genesis bootstrap. Nothing here needs that, so empty
// denies.
//
// Matching is exact, never a prefix. A sub-realm identity minted by
// cur.Sub(subpath) presents the synthesized path "host#subpath", so a delegate
// may legitimately be a single DAO hosted by a multi-tenant realm — for
// instance "gno.land/r/nt/commondao/v0#dao/42". An anchored-prefix match on the
// host would hand the capability to every DAO that realm hosts, and a bare
// prefix match would additionally match sibling packages. "#" cannot occur in a
// real package path, so exact matching on the full string is unambiguous.
//
// Takes rlm in the non-crossing dispatch position, matching assertValsetCaller
// so the two gates stay one shape.
// subject names what is being written, so the refusal stays specific to the
// capability rather than generic to the mechanism. params_valset_auth.txtar
// pins valset's exact wording as a regression test for PR #5485.
func assertDelegate(_ int, rlm realm, want, subject string) {
	if want == "" {
		panic("unauthorized: no delegate is configured for " + subject)
	}
	// The helper trusts its rlm input, so a future caller threading a stashed
	// or sibling-frame realm value would otherwise bypass the path check below.
	if !rlm.IsCurrent() {
		panic("unauthorized: rlm is not the caller's live cur")
	}
	if rlm.Previous().PkgPath() != want {
		panic("unauthorized: only " + want + " may write " + subject)
	}
}

// assertDelegatePath rejects package paths that must never be stored in a
// delegation slot, at the point a proposal is built rather than when it
// executes.
//
// Rejecting the empty string is the same fail-open guard as in assertDelegate,
// enforced on the way in as well so an accidental clear-by-empty-set cannot be
// mistaken for a grant. Requiring the gno.land/r/ prefix excludes user accounts
// (empty path), pure packages, and ephemeral `maketx run` realms — the last of
// which matters because a run realm's path is non-empty, so a check based on
// "is this code" would let one through.
func assertDelegatePath(pkgpath string) {
	if pkgpath == "" {
		panic("invalid delegate: empty package path")
	}
	if !isRealmPath(pkgpath) {
		panic("invalid delegate: must be a gno.land/r/ realm path, got " + pkgpath)
	}
	// Reject anything no caller could ever present, so a delegation cannot be
	// silently dead: GovDAO would believe it granted the capability while the
	// delegate is refused on every call. The sibling UpdateImpl rejects
	// whitespace-padded entries for the same reason.
	for i := 0; i < len(pkgpath); i++ {
		c := pkgpath[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
		case c == '/' || c == '.' || c == '-' || c == '_' || c == '#':
		default:
			panic("invalid delegate: " + pkgpath +
				" contains a character no package path or sub-identity can hold")
		}
	}
	if n := countByte(pkgpath, '#'); n > 1 {
		panic("invalid delegate: more than one '#' in " + pkgpath)
	}
}

func countByte(s string, b byte) int {
	n := 0
	for i := 0; i < len(s); i++ {
		if s[i] == b {
			n++
		}
	}
	return n
}

const realmPathPrefix = "gno.land/r/"

func isRealmPath(pkgpath string) bool {
	return len(pkgpath) > len(realmPathPrefix) &&
		pkgpath[:len(realmPathPrefix)] == realmPathPrefix
}

// newDelegateProposal builds the GovDAO proposal that applies a delegation
// change. apply mutates the slot and is run only when the vote passes.
//
// event is emitted from inside the executor, so an observer sees the delegation
// change exactly when it takes effect rather than when it was proposed. from is
// the previous holder ("" when none), included so a re-delegation is auditable
// from the single event without reading prior state.
// apply returns the holder it replaced, read at EXECUTION time. Capturing that
// at creation would misreport a re-delegation: two set-proposals created while
// the slot is empty, then executed in sequence, would both emit from="" even
// though the second replaced the first.
func newDelegateProposal(cur realm, event, key, to, title, desc string, apply func() string) dao.ProposalRequest {
	callback := func(cur realm) error {
		from := apply()
		chain.Emit(event, "key", key, "from", from, "to", to)
		return nil
	}
	return dao.NewProposalRequest(title, desc,
		dao.NewSimpleExecutor(0, cur, callback, ""))
}

delegate_test.gno

package params

import (
	"testing"

	prms "sys/params"

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

const (
	testDelegate = "gno.land/r/test/delegate"
	testOther    = "gno.land/r/test/other"
	// A sub-realm identity, the form a single DAO hosted by a multi-tenant
	// realm presents. "#" cannot occur in a real package path.
	testSubDelegate = "gno.land/r/nt/commondao/v0#dao/42"
)

// resetDelegation returns the slot to undelegated. The realm's tests share
// package state, so anything touching the slot must put it back.
func resetDelegation() {
	runSubmittersMgr = ""
	runSubmittersGrants = addrset.Set{}
}

// armRunSubmitters puts addresses on the list the way GovDAO does: by writing
// the parameter, not through the delegate.
//
// Tests need it because the delegate may no longer arm an empty list. An empty
// run_submitters means the gate is off, so the first add would switch a
// chain-wide restriction on rather than curate one, and that is a vote.
func armRunSubmitters(addrs ...string) {
	prms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, true)
}

// unarmRunSubmitters drops addresses the way a GovDAO vote does, bypassing the
// delegate's grant-scoping. Used to build a list whose every remaining entry was
// granted by the delegate, which is the only state where the non-empty floor is
// the binding constraint.
func unarmRunSubmitters(addrs ...string) {
	prms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, false)
}

// TestRunSubmittersUndelegatedDeniesEveryone is the single most important test
// here: with no delegate configured, the slot is "" and a direct user call also
// presents "". A gate that compared the two without checking for empty first
// would admit every account on the chain.
func TestRunSubmittersUndelegatedDeniesEveryone(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	uassert.Equal(t, "", RunSubmittersManager())

	// A user account: PkgPath() is empty, matching the empty slot.
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("nobody")))
	uassert.AbortsContains(t, cur, "no delegate is configured", func() {
		AddRunSubmitters(cross(cur), []string{testutils.TestAddress("victim").String()})
	})

	// And a code realm, for completeness.
	testing.SetRealm(testing.NewCodeRealm(testOther))
	uassert.AbortsContains(t, cur, "no delegate is configured", func() {
		AddRunSubmitters(cross(cur), []string{testutils.TestAddress("victim").String()})
	})
}

// TestRunSubmittersOnlyTheDelegateMayWrite pins that authorization is by exact
// package path.
func TestRunSubmittersOnlyTheDelegateMayWrite(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	runSubmittersMgr = testDelegate
	armRunSubmitters(testutils.TestAddress("seeded-by-vote").String())
	addr := testutils.TestAddress("granted").String()

	// A different realm is refused.
	testing.SetRealm(testing.NewCodeRealm(testOther))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		AddRunSubmitters(cross(cur), []string{addr})
	})

	// A user account is refused: an empty path must not match a set slot.
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("nobody")))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		AddRunSubmitters(cross(cur), []string{addr})
	})

	// The delegate itself succeeds.
	testing.SetRealm(testing.NewCodeRealm(testDelegate))
	AddRunSubmitters(cross(cur), []string{addr})
	uassert.True(t, contains(GetRunSubmitters(), addr),
		"the delegate's addition must reach the parameter")
}

// TestRunSubmittersSubRealmIdentityIsExact pins that delegate matching is exact
// string equality, which is what makes a per-DAO delegation safe.
//
// A sub-realm identity minted by cur.Sub(subpath) presents "host#subpath", so a
// single DAO hosted by a multi-tenant realm can hold the capability. Matching by
// prefix instead would hand it to every DAO that host serves -- and CommonDAO
// membership, while invite-gated, is unlimited once invited.
//
// Asserted through the pure predicate rather than by crossing: constructing a
// live sub-realm cur is not something the test harness can do (NewCodeRealm
// rejects "#", and MakeRealm does not satisfy IsCurrent), and the comparison
// under test is the same one assertDelegate performs.
func TestRunSubmittersSubRealmIdentityIsExact(t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	runSubmittersMgr = testSubDelegate

	uassert.True(t, IsRunSubmittersDelegate(testSubDelegate),
		"the named DAO holds the capability")
	uassert.False(t, IsRunSubmittersDelegate("gno.land/r/nt/commondao/v0"),
		"the host realm must not inherit its sub-identity's authority")
	uassert.False(t, IsRunSubmittersDelegate("gno.land/r/nt/commondao/v0#dao/43"),
		"a sibling DAO of the same host must not match")
	uassert.False(t, IsRunSubmittersDelegate("gno.land/r/nt/commondao/v0#dao/4"),
		"a prefix of the subpath must not match")
	uassert.False(t, IsRunSubmittersDelegate(""),
		"an empty path must never match a configured delegate")
}

// TestRunSubmittersRemoveIsScopedToOwnGrants pins that the delegate cannot
// remove an address it did not add, so a list GovDAO curated survives a rogue
// delegate. The companion bound -- that it can never take the list to zero by
// any route -- is TestRunSubmittersCannotEmptyTheList.
func TestRunSubmittersRemoveIsScopedToOwnGrants(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	preexisting := testutils.TestAddress("breakglass").String()
	testing.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey,
		[]string{preexisting})

	runSubmittersMgr = testDelegate
	armRunSubmitters(testutils.TestAddress("seeded-by-vote").String())
	own := testutils.TestAddress("ownadd").String()

	testing.SetRealm(testing.NewCodeRealm(testDelegate))
	AddRunSubmitters(cross(cur), []string{own})

	// It may remove what it granted.
	uassert.True(t, RunSubmittersGrantedBy(address(own)))
	RemoveRunSubmitters(cross(cur), []string{own})
	uassert.False(t, contains(GetRunSubmitters(), own))

	// It may NOT remove the address that predated the delegation.
	uassert.False(t, RunSubmittersGrantedBy(address(preexisting)))
	uassert.AbortsContains(t, cur, "only GovDAO may remove it", func() {
		RemoveRunSubmitters(cross(cur), []string{preexisting})
	})
	uassert.True(t, contains(GetRunSubmitters(), preexisting),
		"the pre-existing entry must survive a refused removal")
}

// TestRunSubmittersCannotEmptyTheList pins the non-empty floor.
//
// An empty run_submitters means the gate is OFF: anyone on the chain may
// MsgRun. So emptying the list is not a smaller version of removing one
// address, it is the unilateral revocation of the whole restriction GovDAO
// voted for -- the one thing this capability must not be able to do.
//
// Grant-scoping alone does not prevent it. It holds only while an entry the
// delegate did not grant survives, and GovDAO replacing the list wholesale can
// remove its own entries without touching the grant record, which is exactly
// the state set up below.
func TestRunSubmittersCannotEmptyTheList(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	runSubmittersMgr = testDelegate
	seed := testutils.TestAddress("seeded-by-vote").String()
	armRunSubmitters(seed)
	a := testutils.TestAddress("granted-a").String()
	b := testutils.TestAddress("granted-b").String()

	testing.SetRealm(testing.NewCodeRealm(testDelegate))
	AddRunSubmitters(cross(cur), []string{a, b})

	// GovDAO then drops its own seed by vote, which grant-scoping does not
	// constrain. This is the only way to reach a list whose every entry was
	// granted by the delegate, now that the delegate cannot arm an empty one --
	// and it is the state where the floor is the last thing standing.
	unarmRunSubmitters(seed)
	uassert.Equal(t, 2, len(GetRunSubmitters()))

	// Every listed address is now one the delegate granted, so grant-scoping
	// permits removing all of them. The floor is the only thing left.
	uassert.True(t, RunSubmittersGrantedBy(address(a)))
	uassert.True(t, RunSubmittersGrantedBy(address(b)))

	// Down to one is fine: shrinking the list is the delegate's job.
	RemoveRunSubmitters(cross(cur), []string{a})
	uassert.Equal(t, 1, len(GetRunSubmitters()))

	// The last one is not.
	uassert.AbortsContains(t, cur, "refusing to empty", func() {
		RemoveRunSubmitters(cross(cur), []string{b})
	})
	uassert.True(t, contains(GetRunSubmitters(), b),
		"the last entry must survive a refused removal")

	// Nor in one call, and nor by naming addresses that are not listed: the
	// count is taken against the parameter, not the argument.
	uassert.AbortsContains(t, cur, "refusing to empty", func() {
		RemoveRunSubmitters(cross(cur), []string{b, b})
	})
	uassert.True(t, contains(GetRunSubmitters(), b))

	// And the delegate is not locked out of its ordinary work: adding still
	// works, and once there are two again it may remove one.
	AddRunSubmitters(cross(cur), []string{a})
	RemoveRunSubmitters(cross(cur), []string{b})
	uassert.True(t, contains(GetRunSubmitters(), a))
	uassert.False(t, contains(GetRunSubmitters(), b))
}

// TestRunSubmittersRevocationDropsGrantRecord pins that a new holder does not
// inherit removal authority over its predecessor's grants.
func TestRunSubmittersRevocationDropsGrantRecord(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	runSubmittersMgr = testDelegate
	armRunSubmitters(testutils.TestAddress("seeded-by-vote").String())
	addr := testutils.TestAddress("byfirst").String()
	testing.SetRealm(testing.NewCodeRealm(testDelegate))
	AddRunSubmitters(cross(cur), []string{addr})
	uassert.True(t, RunSubmittersGrantedBy(address(addr)))

	// Hand the capability over, as the proposal executor would.
	runSubmittersMgr = testOther
	runSubmittersGrants = addrset.Set{}

	testing.SetRealm(testing.NewCodeRealm(testOther))
	uassert.False(t, RunSubmittersGrantedBy(address(addr)))
	uassert.AbortsContains(t, cur, "only GovDAO may remove it", func() {
		RemoveRunSubmitters(cross(cur), []string{addr})
	})
}

// TestDelegatePathValidation pins what may be stored in a slot. An ephemeral
// `maketx run` realm has a NON-empty path, so a check for "is this code" would
// let one through; only the gno.land/r/ requirement excludes it.
func TestDelegatePathValidation(t *testing.T) {
	for _, bad := range []string{
		"",
		"gno.land/p/nt/avl/v0",
		"gno.land/e/g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5/run",
		"gno.land/r/",
		// Paths no caller could ever present. Storing one would leave GovDAO
		// believing it delegated while the delegate is refused on every call.
		"gno.land/r/test/delegate ",                // trailing space
		" gno.land/r/test/delegate",                // leading space
		"gno.land/r/nt/commondao/v0#DAO/42",        // uppercase subpath
		"gno.land/r/nt/commondao/v0#dao/42#dao/43", // two separators
	} {
		// PanicsContains, not AbortsContains: this is a same-realm call, so
		// the panic never crosses a realm boundary and is not an abort.
		uassert.PanicsContains(t, cur, "invalid delegate", func() {
			assertDelegatePath(bad)
		})
	}
	// Sound paths, including a sub-realm identity.
	assertDelegatePath(testDelegate)
	assertDelegatePath(testSubDelegate)
}

// TestValsetGateRejectsForeignRealm closes a pre-existing coverage gap found
// while factoring the shared gate: assertValsetCaller had no test in this realm
// at all, so nothing asserted that a realm other than r/sys/validators/v0 is
// refused.
func TestValsetGateRejectsForeignRealm(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewCodeRealm(testOther))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		SetValsetProposal(cross(cur), []string{"somepubkey:1"})
	})

	// A user account must be refused identically -- the empty-path case.
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("nobody")))
	uassert.AbortsContains(t, cur, "unauthorized", func() {
		SetValsetProposal(cross(cur), []string{"somepubkey:1"})
	})
}

// TestAssertNotValsetKeyRejectsGenericFactory closes the other gap: the guard
// whose own comment says it stops "any GovDAO supermajority" from writing
// validator-set state through the generic param factory had no test.
func TestAssertNotValsetKeyRejectsGenericFactory(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("proposer")))
	uassert.AbortsContains(t, cur, "reserved for", func() {
		NewSysParamStringsPropRequest(cross(cur), "node", "valset", "proposed",
			[]string{"somepubkey:1"})
	})
}

func contains(haystack []string, needle string) bool {
	for _, h := range haystack {
		if h == needle {
			return true
		}
	}
	return false
}

// TestRunSubmittersGrantLaunderingIsRefused reproduces a real hole in the first
// version of this code, found by audit.
//
// UpdateSysParamStrings dedupes on add, so re-adding an address already on the
// list is a no-op on the parameter. The first implementation recorded a grant
// for every argument regardless, which let the delegate launder authority over
// entries it never granted:
//
//	read the list -> re-add all of it -> remove all of it
//
// The parameter never changed on the middle step, but every address became
// "granted by me", so the removal was permitted and the allowlist ended empty --
// including the entry that predated the delegation. Since GovDAO proposal
// creation is MsgRun-only, an empty run_submitters means no proposal can be
// created to revoke the delegate or restore the list. That is a chain brick
// recoverable only by relaunch.
func TestRunSubmittersGrantLaunderingIsRefused(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	breakglass := testutils.TestAddress("breakglass2").String()
	testing.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey,
		[]string{breakglass})

	runSubmittersMgr = testDelegate
	armRunSubmitters(testutils.TestAddress("seeded-by-vote").String())
	testing.SetRealm(testing.NewCodeRealm(testDelegate))

	// Step 1: re-add what is already there. A no-op on the parameter, and it
	// must NOT create a grant.
	AddRunSubmitters(cross(cur), GetRunSubmitters())
	uassert.False(t, RunSubmittersGrantedBy(address(breakglass)),
		"re-adding an existing address must not record a grant for it")

	// Step 2: the removal must therefore still be refused.
	uassert.AbortsContains(t, cur, "only GovDAO may remove it", func() {
		RemoveRunSubmitters(cross(cur), []string{breakglass})
	})
	uassert.True(t, contains(GetRunSubmitters(), breakglass),
		"the pre-existing entry must survive")

	// And the whole-list version of the same attack, which is how it would
	// actually be run.
	AddRunSubmitters(cross(cur), GetRunSubmitters())
	uassert.AbortsContains(t, cur, "only GovDAO may remove it", func() {
		RemoveRunSubmitters(cross(cur), GetRunSubmitters())
	})
	uassert.True(t, len(GetRunSubmitters()) > 0,
		"the allowlist must never end up empty at a delegate's hand")

	// A genuinely new address still works normally.
	fresh := testutils.TestAddress("freshgrant").String()
	AddRunSubmitters(cross(cur), []string{fresh})
	uassert.True(t, RunSubmittersGrantedBy(address(fresh)))
	RemoveRunSubmitters(cross(cur), []string{fresh})
	uassert.False(t, contains(GetRunSubmitters(), fresh))
}

// TestRenderShowsDelegationState pins that the page actually reports the state
// it exists to report.
//
// The value of a Render here is that someone auditing the chain can see whether
// a parameter is delegated without knowing to ask. A page that renders the same
// text whether or not a delegation exists would defeat that, so both states are
// checked.
func TestRenderShowsDelegationState(t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	addr := testutils.TestAddress("rendered").String()
	testing.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey,
		[]string{addr})

	// Undelegated: it must say so rather than leave the reader guessing.
	out := Render("")
	uassert.True(t, contains2(out, "nobody"),
		"an undelegated parameter must be reported as such")
	uassert.False(t, contains2(out, testDelegate),
		"no delegate should be named when none is set")

	// Delegated: the holder is named.
	runSubmittersMgr = testDelegate
	armRunSubmitters(testutils.TestAddress("seeded-by-vote").String())
	out = Render("")
	uassert.True(t, contains2(out, testDelegate),
		"the delegate holding the capability must be named")
	uassert.True(t, contains2(out, addr),
		"the addresses the parameter currently allows must be listed")

	// The valset writer is fixed in source, not delegated, and the page should
	// not blur the two.
	uassert.True(t, contains2(out, valsetAuthorizedRealm),
		"the realm that writes valset params must be shown too")
}

// contains2 reports whether s contains sub.
func contains2(s, sub string) bool {
	if len(sub) == 0 {
		return true
	}
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return true
		}
	}
	return false
}

// TestRunSubmittersDelegateCannotArmTheGate covers the direction the non-empty
// floor does not: turning the allowlist ON.
//
// An empty run_submitters means the gate is off and anyone may MsgRun. So a
// delegate adding the first address is not curating a list, it is switching a
// chain-wide restriction on and choosing who it admits -- leaving that address
// the only one on the chain that may run code.
//
// That is unrepairable in band. Creating a GovDAO proposal needs MsgRun, so
// once the gate is armed against the members they cannot propose the vote that
// would reset the list or revoke the delegation, and the floor in
// RemoveRunSubmitters stops the delegate from undoing it either.
func TestRunSubmittersDelegateCannotArmTheGate(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	runSubmittersMgr = testDelegate
	attacker := testutils.TestAddress("attacker").String()

	// The gate starts off.
	uassert.Equal(t, 0, len(GetRunSubmitters()))

	testing.SetRealm(testing.NewCodeRealm(testDelegate))
	uassert.AbortsContains(t, cur, "refusing to arm", func() {
		AddRunSubmitters(cross(cur), []string{attacker})
	})
	uassert.Equal(t, 0, len(GetRunSubmitters()),
		"a refused arm must leave the gate off")

	// Once GovDAO has armed it, the delegate may curate as before.
	seeded := testutils.TestAddress("seeded-by-vote").String()
	armRunSubmitters(seeded)
	testing.SetRealm(testing.NewCodeRealm(testDelegate))
	AddRunSubmitters(cross(cur), []string{attacker})
	uassert.Equal(t, 2, len(GetRunSubmitters()),
		"curating an armed list is still the delegate's job")
}

// TestRunSubmittersKeyIsReservedFromGenericFactories pins that the whole-list
// path is the dedicated constructor and nothing else.
//
// The generic factories take module, submodule and name as arguments, so
// without this any of the nine could write run_submitters and walk past the
// proposer rule in ProposeSetRunSubmitters. Same shape as the valset
// reservation next to it.
func TestRunSubmittersKeyIsReservedFromGenericFactories(cur realm, t *testing.T) {
	addr := testutils.TestAddress("someone").String()

	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamStringsPropRequest(cross(cur), "vm", "p", runSubmittersKey, []string{addr})
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamStringsPropRequestWithTitle(cross(cur), "vm", "p", runSubmittersKey, "t", []string{addr})
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamStringsPropRequestAddWithTitle(cross(cur), "vm", "p", runSubmittersKey, "t", []string{addr})
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamStringsPropRequestRemoveWithTitle(cross(cur), "vm", "p", runSubmittersKey, "t", []string{addr})
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamStringPropRequest(cross(cur), "vm", "p", runSubmittersKey, addr)
	})

	// The four typed factories too. They cannot carry a run_submitters value,
	// but they can name the key, and the reservation is about the key -- all
	// nine share one check on the funnel they return through, so all nine are
	// listed here rather than the five that happen to take strings.
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamInt64PropRequest(cross(cur), "vm", "p", runSubmittersKey, 1)
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamUint64PropRequest(cross(cur), "vm", "p", runSubmittersKey, 1)
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamBoolPropRequest(cross(cur), "vm", "p", runSubmittersKey, true)
	})
	uassert.AbortsContains(t, cur, "reserved for ProposeSetRunSubmitters", func() {
		NewSysParamBytesPropRequest(cross(cur), "vm", "p", runSubmittersKey, []byte{1})
	})

	// A different key in the same module is unaffected.
	uassert.NotAborts(t, cur, func() {
		NewSysParamStringsPropRequest(cross(cur), "vm", "p", "code_submitters", []string{addr})
	})
}

// TestProposeSetRunSubmittersRequiresProposerOnTheList covers the rule that a
// non-empty allowlist must include whoever proposed it.
//
// A list naming nobody who can create a proposal cannot be undone, because
// creating one needs MsgRun. Requiring the proposer's own address proves the
// list is usable: GovDAO refuses a proposal from a non-member, and the proposer
// just signed the transaction, so that address demonstrably holds a key.
func TestProposeSetRunSubmittersRequiresProposerOnTheList(cur realm, t *testing.T) {
	other := testutils.TestAddress("someone-else").String()

	// A list without the proposer is refused.
	uassert.AbortsContains(t, cur, "omits the proposer", func() {
		ProposeSetRunSubmitters(cross(cur), []string{other})
	})

	// Emptying the list is always allowed: that switches the gate off, which
	// cannot lock anyone out.
	uassert.NotAborts(t, cur, func() {
		ProposeSetRunSubmitters(cross(cur), []string{})
	})

	// A list that does include the proposer goes through.
	proposer := testutils.TestAddress("proposer")
	testing.SetRealm(testing.NewUserRealm(proposer))
	uassert.NotAborts(t, cur, func() {
		ProposeSetRunSubmitters(cross(cur), []string{other, proposer.String()})
	})
}

// TestSetRunSubmittersReplacesTheList covers what the whole-list setter does to
// a list that is not empty.
//
// This realm reserves run_submitters from the generic factories, so its own
// setter is the only route by vote. If that setter appended instead of
// replacing, the parameter would be append-only chain-wide: a compromised
// address could never be de-listed and the gate could never be turned back off,
// while the proposal shown to voters would say otherwise.
//
// Every other test here starts from an empty list, where appending and
// replacing look identical, which is why this one starts armed.
func TestSetRunSubmittersReplacesTheList(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	a := testutils.TestAddress("keep-a").String()
	b := testutils.TestAddress("drop-b").String()
	armRunSubmitters(a, b)
	uassert.Equal(t, 2, len(GetRunSubmitters()))

	// Dropping b must actually drop it.
	setRunSubmitters([]string{a})
	got := GetRunSubmitters()
	uassert.Equal(t, 1, len(got), "the list must be replaced, not appended to")
	uassert.True(t, contains(got, a))
	uassert.False(t, contains(got, b), "a de-listed address must be gone")

	// And emptying must switch the gate off, which is what the proposal says.
	setRunSubmitters([]string{})
	uassert.Equal(t, 0, len(GetRunSubmitters()),
		"an empty list must be reachable, or the gate can never be turned off")
}

// TestAssertDelegateRejectsANonLiveRealm covers the IsCurrent check in
// assertDelegate.
//
// This is the shape where the check can actually fire. assertDelegate takes its
// realm as an ordinary parameter, so a caller can hand it a stashed or
// sibling-frame value; without IsCurrent it would then compare that value's
// Previous() against the delegate path and admit whoever assembled it.
//
// Crossing functions cannot be tested this way, and do not need to be: the
// compiler refuses anything but `cur` or `cross(rlm)` as their first argument,
// so their cur is live by construction.
func TestAssertDelegateRejectsANonLiveRealm(cur realm, t *testing.T) {
	resetDelegation()
	defer resetDelegation()

	runSubmittersMgr = testDelegate

	// A synthetic realm whose Previous() names the delegate. The path check
	// alone would admit it; IsCurrent is the only thing that does not.
	fake := testing.MakeRealm(
		testutils.TestAddress("impostor"), "gno.land/r/impostor",
		testing.MakeRealm(testutils.TestAddress("d"), testDelegate, testing.OriginRealm()),
	)
	uassert.Equal(t, testDelegate, fake.Previous().PkgPath(),
		"premise: the forged realm must pass the path check, or this proves nothing")

	// PanicsContains, not Aborts: assertDelegate is called directly here, in
	// this realm, so the refusal is a panic. It surfaces as an abort only when
	// it happens across a realm boundary.
	uassert.PanicsContains(t, cur, "not the caller's live cur", func() {
		assertDelegate(0, fake, runSubmittersMgr, "the "+runSubmittersKey+" allowlist")
	})
}

fee_collector.gno

package params

import (
	"gno.land/r/gov/dao"
)

func NewSetFeeCollectorRequest(cur realm, addr address) dao.ProposalRequest {
	return NewSysParamStringPropRequest(cur,
		"auth", "p", "fee_collector",
		addr.String(),
	)
}

fee_collector_test.gno

package params

import (
	"testing"

	"gno.land/p/nt/urequire/v0"
	"gno.land/r/gov/dao"
)

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

func TestSetFeeCollector(cur realm, t *testing.T) {
	userRealm := testing.NewUserRealm(g1user)
	testing.SetRealm(userRealm)

	pr := NewSetFeeCollectorRequest(cur, userRealm.Address())
	id := dao.MustCreateProposal(cross(cur), pr)
	_, err := dao.GetProposal(id)
	urequire.NoError(t, err)

	urequire.NotPanics(
		t, cur,
		func() {
			dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(id)))
		},
	)

	urequire.NotPanics(
		t, cur,
		func() {
			dao.ExecuteProposal(cross(cur), id)
		},
	)

	// XXX: test that the value got properly updated, when we can get params from gno code
}

gnomod.toml

module = "gno.land/r/sys/params"
gno = "0.9"

[addpkg]
  creator = "g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l"

halt.gno

package params

import (
	"strconv"

	"chain"
	prms "sys/params"

	"gno.land/r/gov/dao"
)

const (
	nodeModulePrefix  = "node"
	haltHeightKey     = "halt_height"
	haltMinVersionKey = "halt_min_version"
)

// NewSetHaltRequest creates a GovDAO proposal to halt all chain nodes at the given block height.
// Once approved and executed, nodes will gracefully stop after committing the specified block,
// enabling coordinated chain upgrades.
//
// minVersion, if non-empty, sets the minimum binary version required to resume after the halt.
// Nodes will refuse to restart unless their version satisfies the minimum requirement,
// preventing old binaries from accidentally resuming a chain halted for an upgrade.
// Example: minVersion="v1.3.0" prevents a v1.2.0 binary from resuming.
//
// minVersion must be a release tag the node can parse: vMAJOR.MINOR.PATCH, or
// betanet's retired chain/gnolandMAJOR.MINOR. It is NOT the chain's launch tag —
// naming "chain/mainnet" here parses as nothing, so the comparison degrades to
// byte equality and refuses the upgraded binary alongside the stale ones, leaving
// the chain unable to restart. This function does not check the shape; the release
// tooling does. See RELEASING.md and gno.land/cmd/gnoland/UPGRADES.md, and prefer
// misc/govdao-scripts/set-halt.sh over writing the call by hand.
//
// Use height=0 to cancel a previously scheduled halt.
func NewSetHaltRequest(cur realm, height int64, minVersion string) dao.ProposalRequest {
	callback := func(cur realm) error {
		prms.SetSysParamInt64(nodeModulePrefix, "p", haltHeightKey, height)
		prms.SetSysParamString(nodeModulePrefix, "p", haltMinVersionKey, minVersion)
		chain.Emit("set_halt",
			"height", strconv.FormatInt(height, 10),
			"min_version", minVersion,
		)
		return nil
	}

	var desc string
	if height == 0 {
		desc = "Cancel the scheduled chain halt and clear the minimum version requirement."
	} else {
		desc = "Halt the chain at block " + strconv.FormatInt(height, 10) + "."
		if minVersion != "" {
			desc += " Requires binary version >= " + minVersion + " to resume."
		}
	}

	e := dao.NewSimpleExecutor(0, cur, callback, "")
	return dao.NewProposalRequest("Set node halt height", desc, e)
}

params.gno

// Package params provides functions for creating parameter executors that
// interface with the Params Keeper.
//
// This package enables setting various parameter types (such as strings,
// integers, booleans, and byte slices) through the GovDAO proposal mechanism.
// Each function returns an executor that, when called, sets the specified
// parameter in the Params Keeper.
//
// The executors are designed to be used within governance proposals to modify
// parameters dynamically. The integration with the GovDAO allows for parameter
// changes to be proposed and executed in a controlled manner, ensuring that
// modifications are subject to governance processes.
//
// Example usage:
//
//	// This executor can be used in a governance proposal to set the parameter.
//	pr := params.NewSysParamStringPropExecutor("bank", "p", "restricted_denoms")
package params

import (
	"chain"
	prms "sys/params"

	"gno.land/r/gov/dao"
)

// this is only used for emitting events.
func syskey(module, submodule, name string) string {
	return module + ":" + submodule + ":" + name
}

// assertNotValsetKey rejects governance proposals that target the
// node:valset:* key family. Those keys are reserved for the realm-side
// gate in r/sys/params/valset.gno (SetValsetProposal) which checks
// the immediate caller is gno.land/r/sys/validators/v0. Without this
// guard, a generic NewSysParam*PropRequest("node","valset",...) would
// let any GovDAO supermajority bypass the v0 authorization and write
// validator-set state directly.
func assertNotValsetKey(module, submodule string) {
	if module == "node" && submodule == "valset" {
		panic("node:valset:* is reserved for r/sys/validators/v0; use it instead of the generic factory")
	}
}

// assertNotRunSubmittersKey rejects generic proposals that target
// vm:p:run_submitters. Same shape as assertNotValsetKey above, and the same
// reason: the key has a realm-side gate the generic factory would walk past.
//
// An empty run_submitters means the MsgRun gate is OFF. So a non-empty list is
// the chain deciding who may run code, and a list that names nobody able to
// create a GovDAO proposal cannot be changed back -- creating a proposal needs
// MsgRun, because a ProposalRequest carries an Executor that MsgCall cannot
// build from string arguments. The dedicated ProposeSetRunSubmitters in
// run_submitters.gno refuses that list at proposal-creation time, where a human
// can still act on the refusal.
//
// Reserving the key rather than adding the check to all nine factories keeps
// the number of ways to write this parameter at one.
func assertNotRunSubmittersKey(module, submodule, name string) {
	if module == "vm" && submodule == "p" && name == runSubmittersKey {
		panic(runSubmittersKey + " is reserved for ProposeSetRunSubmitters in this realm; " +
			"use it instead of the generic factory")
	}
}

func NewSysParamStringPropRequest(cur realm, module, submodule, name, value string) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamString(module, submodule, name, value) },
		"",
	)
}

func NewSysParamInt64PropRequest(cur realm, module, submodule, name string, value int64) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamInt64(module, submodule, name, value) },
		"",
	)
}

func NewSysParamUint64PropRequest(cur realm, module, submodule, name string, value uint64) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamUint64(module, submodule, name, value) },
		"",
	)
}

func NewSysParamBoolPropRequest(cur realm, module, submodule, name string, value bool) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamBool(module, submodule, name, value) },
		"",
	)
}

func NewSysParamBytesPropRequest(cur realm, module, submodule, name string, value []byte) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamBytes(module, submodule, name, value) },
		"",
	)
}

func NewSysParamStringsPropRequest(cur realm, module, submodule, name string, value []string) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamStrings(module, submodule, name, value) },
		"",
	)
}

func NewSysParamStringsPropRequestWithTitle(cur realm, module, submodule, name, title string, value []string) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.SetSysParamStrings(module, submodule, name, value) },
		title,
	)
}
func NewSysParamStringsPropRequestAddWithTitle(cur realm, module, submodule, name, title string, value []string) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.UpdateSysParamStrings(module, submodule, name, value, true) },
		title,
	)
}
func NewSysParamStringsPropRequestRemoveWithTitle(cur realm, module, submodule, name, title string, value []string) dao.ProposalRequest {
	return newPropRequest(cur, module, submodule, name,
		func() { prms.UpdateSysParamStrings(module, submodule, name, value, false) },
		title,
	)
}
func newPropRequest(cur realm, module, submodule, name string, fn func(), title string) dao.ProposalRequest {
	// The reserved-key checks live here rather than in each factory. Every
	// generic factory returns through this one function, so a factory added
	// later cannot forget them. The dedicated setters for those keys build their
	// own request and never come here, which is what makes them the exception.
	assertNotValsetKey(module, submodule)
	assertNotRunSubmittersKey(module, submodule, name)

	key := syskey(module, submodule, name)
	callback := func(cur realm) error {
		fn()
		chain.Emit("set", "key", key) // TODO document, make const, make consistent. 'k'??
		return nil
	}

	if title == "" {
		title = "Set new sys/params key"
	}

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

	return dao.NewProposalRequest(title, "This proposal wants to add a new key to sys/params: "+key, e)
}

params_test.gno

package params

import (
	"testing"
)

// These tests cover proposal CONSTRUCTION. Reading a value back is possible --
// sys/params exposes typed getters (GetSysParamStrings and friends), which
// valset.gno and delegate_test.gno both use, and tests can seed with
// testing.SetSysParam* -- so add read-back assertions rather than assuming they
// cannot be written. End-to-end execution is additionally covered by the
// propX_filetest.gno files under r/gov/dao/.

func TestNewStringPropRequest(cur realm, t *testing.T) {
	pr := NewSysParamStringPropRequest(cur, "foo", "bar", "baz", "qux")
	if pr.Title() == "" {
		t.Errorf("executor shouldn't be nil")
	}
}

func TestNewSetHaltRequest(cur realm, t *testing.T) {
	pr := NewSetHaltRequest(cur, 100_000, "chain/gnoland1.1")
	if pr.Title() == "" {
		t.Errorf("proposal title shouldn't be empty")
	}
}

func TestNewSetHaltRequestNoVersion(cur realm, t *testing.T) {
	pr := NewSetHaltRequest(cur, 100_000, "")
	if pr.Title() == "" {
		t.Errorf("proposal title shouldn't be empty")
	}
}

func TestNewSetHaltRequestCancel(cur realm, t *testing.T) {
	pr := NewSetHaltRequest(cur, 0, "")
	if pr.Title() == "" {
		t.Errorf("proposal title shouldn't be empty")
	}
}

render.gno

package params

import (
	"gno.land/p/moul/md/v0"
	"gno.land/p/moul/mdtable/v0"
	"gno.land/p/nt/ufmt/v0"
)

// Render shows who, other than GovDAO, may currently write a chain parameter.
//
// This realm had no Render, so the only way to see a delegation was to know it
// existed and query for it by name. That is the wrong shape for state that
// grants a capability: someone auditing the chain should be able to see, in one
// place, whether any parameter is delegated and to whom.
//
// Values are rendered without escaping, which is safe here because none of them
// is free-form. A delegate path has passed assertDelegatePath, which permits
// only lowercase letters, digits and a few separators; the addresses come from
// the parameter itself, which the chain validates as bech32; and the valset
// realm is a compile-time constant.
func Render(path string) string {
	out := md.H1("Chain parameter delegation")
	out += md.Paragraph(
		"Chain parameters are written by GovDAO proposal. A parameter may also " +
			"be delegated to one other realm, which can then manage it without a " +
			"vote. GovDAO keeps full control of every parameter and can withdraw " +
			"a delegation at any time.",
	)

	out += md.HorizontalRule()
	out += md.H2("run_submitters")
	out += md.Paragraph("Addresses allowed to send MsgRun, which runs code the sender supplies.")

	mgr := RunSubmittersManager()
	table := mdtable.Table{Headers: []string{"", ""}}
	if mgr == "" {
		table.Append([]string{md.Bold("Delegated to"), "nobody, only GovDAO may change it"})
	} else {
		table.Append([]string{md.Bold("Delegated to"), md.InlineCode(mgr)})
	}

	listed := GetRunSubmitters()
	table.Append([]string{md.Bold("Addresses allowed"), ufmt.Sprintf("%d", len(listed))})
	out += table.String()

	if mgr != "" {
		// Which entries the delegate may remove again. Anything it did not add
		// is GovDAO's to remove, including whatever the chain started with.
		granted := 0
		for _, a := range listed {
			if RunSubmittersGrantedBy(address(a)) {
				granted++
			}
		}
		out += md.Paragraph(ufmt.Sprintf(
			"%d of those were added by the delegate, and are the only ones it may remove.",
			granted))
	}

	if len(listed) > 0 {
		items := make([]string, 0, len(listed))
		for _, a := range listed {
			items = append(items, md.InlineCode(a))
		}
		out += md.BulletList(items)
	}

	out += md.HorizontalRule()
	out += md.H2("node:valset")
	out += md.Paragraph(
		"Validator set parameters are written by one realm, fixed in this " +
			"realm's source. Unlike a delegation this cannot be repointed by a " +
			"vote, and GovDAO cannot write these keys itself.",
	)
	vtable := mdtable.Table{Headers: []string{"", ""}}
	vtable.Append([]string{md.Bold("Writable only by"), md.InlineCode(valsetAuthorizedRealm)})
	out += vtable.String()

	return out
}

run_submitters.gno

package params

// Delegated management of vm:p:run_submitters, the allowlist of addresses
// permitted to send MsgRun.
//
// See delegate.gno for why this is a named slot rather than a registry.
//
// What the delegate can and cannot do, and why the asymmetry is this way round:
//
//   - It may ADD addresses. This is the routine work the delegation exists for.
//   - It may REMOVE only addresses it added itself, and never the last one.
//     De-listing its own mistake is a core part of managing an allowlist, so
//     add-only would be a strange capability to hand out. Two bounds keep that
//     safe. Grant-scoping stops it removing an address that predates the
//     delegation. The non-empty floor in RemoveRunSubmitters stops it reaching
//     zero by any route — an empty list means the gate is OFF and anyone may
//     MsgRun, so emptying it would let the delegate revoke the entire
//     restriction GovDAO voted for, which is the one thing this capability must
//     not be able to do.
//   - GovDAO retains everything, through ProposeSetRunSubmitters below -- the
//     generic factories no longer accept this key. That is the bounded reset:
//     one proposal returns the key to a known-good list regardless of what the
//     delegate did, and the proposal shows voters the exact resulting list.
//
// A cost to state plainly rather than bury: this key is read by the ante handler
// on EVERY transaction, before the per-tx gas meter exists, so its length is an
// unmetered per-transaction constant for the whole chain. The delegate therefore
// holds a knob on that constant, bounded only by maxAddressListLen in
// gno.land/pkg/sdk/vm/params.go. That bound is enforced on this path for free:
// UpdateSysParamStrings re-sets the whole list, which re-enters WillSetParam and
// Params.Validate, so both the cap and bech32 validation apply to a delegate's
// additions. A key that is not read on the ante path would be a cheaper first
// delegation; this one is the one that was asked for.

import (
	"chain"
	prms "sys/params"

	"gno.land/p/moul/addrset/v0"

	"gno.land/r/gov/dao"
)

const (
	vmModulePrefix    = "vm"
	vmParamsSubmodule = "p"

	runSubmittersKey = "run_submitters"
)

// runSubmittersMgr is the package path authorized to manage run_submitters.
// Empty means the capability is not delegated, and empty must deny — see
// assertDelegate.
var runSubmittersMgr string

// runSubmittersGrants records which addresses the current delegate added, so
// removal can be scoped to its own grants.
//
// The parameter is the source of truth and this is a side table, so the two can
// disagree — genesis, `gnogenesis params set`, or any future direct keeper write
// produces entries with no grant recorded. That direction is safe: an unrecorded
// address is simply not removable by the delegate, which is the conservative
// answer. Cleared whenever the delegation changes hands, so a new delegate never
// inherits authority over its predecessor's grants.
var runSubmittersGrants = addrset.Set{}

// RunSubmittersManager returns the package path currently authorized to manage
// run_submitters, or "" when the capability is not delegated.
func RunSubmittersManager() string {
	return runSubmittersMgr
}

// RunSubmittersGrantedBy reports whether the current delegate added addr, i.e.
// whether it may remove it.
//
// Exposed so a delegate can check before acting. A delegate that discovers a
// refusal by panicking mid-proposal-execution is in a bad place: the panic
// aborts the transaction, and for a DAO whose proposal has already passed, every
// retry aborts the same way.
func RunSubmittersGrantedBy(addr address) bool {
	return runSubmittersGrants.Has(addr)
}

// IsRunSubmittersDelegate reports whether pkgpath currently holds the
// capability. Pure predicate, for a caller that wants to fail cleanly rather
// than be panicked at.
func IsRunSubmittersDelegate(pkgpath string) bool {
	return pkgpath != "" && pkgpath == runSubmittersMgr
}

// ProposeSetRunSubmittersManager creates a GovDAO proposal handing management of
// run_submitters to pkgpath.
//
// pkgpath may be a sub-realm identity such as
// "gno.land/r/nt/commondao/v0#dao/42", which is how a single DAO hosted by a
// multi-tenant realm is named. Matching is exact, so naming the bare host would
// authorize the host itself and none of its DAOs.
func ProposeSetRunSubmittersManager(cur realm, pkgpath string) dao.ProposalRequest {
	assertDelegatePath(pkgpath)
	if pkgpath == runSubmittersMgr {
		panic("no-op proposal rejected: " + pkgpath + " already manages " + runSubmittersKey)
	}

	// desc uses the manager as of proposal creation, which is the honest thing
	// to show a voter. The EVENT reads it again inside the executor, because two
	// proposals created while the slot is empty and executed in sequence would
	// otherwise both report from="" while the second actually replaced the first.
	from := runSubmittersMgr
	desc := "Authorize " + pkgpath + " to add addresses to the " + runSubmittersKey +
		" allowlist, which gates who may send MsgRun. It may remove only " +
		"addresses it added itself. GovDAO retains full control, including " +
		"replacing the whole list."
	if from != "" {
		desc += " This replaces the current manager, " + from +
			", and discards the record of which addresses it granted."
	}

	return newDelegateProposal(cur, DelegateSetEvent, runSubmittersKey, pkgpath,
		"Delegate "+runSubmittersKey+" management", desc,
		func() string {
			prev := runSubmittersMgr
			runSubmittersMgr = pkgpath
			// A new holder must not inherit removal authority over addresses
			// the previous one granted.
			runSubmittersGrants = addrset.Set{}
			return prev
		})
}

// ProposeClearRunSubmittersManager creates a GovDAO proposal revoking the
// delegation.
//
// Revocation is immediate on execution because the slot is consulted on every
// call. It deliberately does NOT remove addresses the delegate added: sweeping
// them would make the executed effect invisible at vote time, and would silently
// remove nothing whenever the grant record had drifted. Use the existing
// whole-list setter to reset the list to a reviewed value.
func ProposeClearRunSubmittersManager(cur realm) dao.ProposalRequest {
	if runSubmittersMgr == "" {
		panic("no-op proposal rejected: " + runSubmittersKey + " is not delegated")
	}

	from := runSubmittersMgr
	return newDelegateProposal(cur, DelegateClearedEvent, runSubmittersKey, "",
		"Revoke "+runSubmittersKey+" management",
		"Revoke "+from+"'s authority to manage the "+runSubmittersKey+
			" allowlist. Addresses it already added REMAIN on the list; reset the "+
			"list explicitly if that is not wanted.",
		func() string {
			prev := runSubmittersMgr
			runSubmittersMgr = ""
			runSubmittersGrants = addrset.Set{}
			return prev
		})
}

// AddRunSubmitters adds addresses to the run_submitters allowlist.
//
// Callable only by the delegated manager. Addresses already present are a no-op
// (UpdateSysParamStrings dedupes), and the chain still validates every entry and
// enforces the list-length cap, because the update re-sets the whole list.
func AddRunSubmitters(cur realm, addrs []string) {
	assertDelegate(0, cur, runSubmittersMgr, "the "+runSubmittersKey+" allowlist")
	if len(addrs) == 0 {
		return
	}

	// The delegate may curate a list that is already in force. It may not put
	// one into force.
	//
	// An empty run_submitters means the allowlist is OFF and anyone may MsgRun.
	// So the first add is not curation: it switches a chain-wide restriction on
	// and picks who it admits. A delegate adding one address to an empty list
	// leaves that address the only one on the chain that may run code.
	//
	// Refused rather than discouraged because it is unrepairable. Creating a
	// GovDAO proposal needs MsgRun -- a ProposalRequest carries an Executor,
	// which MsgCall cannot build from string arguments -- so once the gate is
	// armed against the members they cannot propose the vote that would undo
	// it, and the floor in RemoveRunSubmitters stops the delegate undoing it
	// either.
	if len(GetRunSubmitters()) == 0 {
		panic("refusing to arm the " + runSubmittersKey +
			" allowlist: it is empty, so the gate is off and anyone may MsgRun. " +
			"Turning it on is a GovDAO vote, not a delegated edit")
	}

	// Record a grant only for an address this call actually ADDED.
	//
	// UpdateSysParamStrings dedupes on add, so passing an address already on the
	// list leaves the parameter unchanged. Recording a grant for it anyway would
	// let the delegate launder authority over entries it never granted: read the
	// list, re-add all of it (a no-op on the parameter, but every address now
	// recorded as its own), then remove all of it -- including whatever predated
	// the delegation. The floor in RemoveRunSubmitters would refuse the last of
	// those removals, but only the last: everything up to it would still go
	// through, leaving the delegate holding the only listed address and so the
	// sole authority over who may MsgRun.
	//
	// So the grant record has to follow the parameter, not the argument.
	present := make(map[string]bool)
	for _, a := range GetRunSubmitters() {
		present[a] = true
	}

	prms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, true)
	for _, a := range addrs {
		if !present[a] {
			runSubmittersGrants.Add(address(a))
		}
	}
	chain.Emit(DelegateWriteEvent,
		"key", runSubmittersKey, "realm", runSubmittersMgr, "op", "add")
}

// RemoveRunSubmitters removes addresses from the run_submitters allowlist.
//
// Callable only by the delegated manager, and only for addresses that manager
// added. Refusing rather than silently skipping is deliberate: a partial removal
// that reported success would leave the caller believing an address was
// de-listed when it was not.
func RemoveRunSubmitters(cur realm, addrs []string) {
	assertDelegate(0, cur, runSubmittersMgr, "the "+runSubmittersKey+" allowlist")
	if len(addrs) == 0 {
		return
	}
	for _, a := range addrs {
		if !runSubmittersGrants.Has(address(a)) {
			panic("cannot remove " + a + ": not granted by " + runSubmittersMgr +
				", only GovDAO may remove it")
		}
	}

	// The delegate may not empty the list, whatever it granted.
	//
	// An empty run_submitters means the gate is OFF -- anyone on the chain may
	// send MsgRun. So emptying it is not a smaller version of removing one
	// address, it is the opposite of what the delegation is for: it would let a
	// delegate authorized to curate a list unilaterally revoke the whole
	// restriction GovDAO voted for.
	//
	// Grant-scoping alone does not prevent this. It holds only while at least
	// one entry the delegate did not grant survives, and GovDAO replacing the
	// list wholesale can remove its own entries without touching the grant
	// record. A floor makes the invariant structural instead of emergent.
	//
	// Counted against the parameter, not the argument: the caller may name
	// addresses that are not listed, or name one twice, and neither shrinks the
	// list. Only GovDAO can go to zero, through the whole-list setter, where the
	// resulting list is on the ballot.
	removing := make(map[string]bool, len(addrs))
	for _, a := range addrs {
		removing[a] = true
	}
	remaining := 0
	for _, a := range GetRunSubmitters() {
		if !removing[a] {
			remaining++
		}
	}
	if remaining == 0 {
		panic("refusing to empty the " + runSubmittersKey +
			" allowlist: an empty list disables the gate entirely, so only " +
			"GovDAO may do it")
	}

	prms.UpdateSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs, false)
	for _, a := range addrs {
		runSubmittersGrants.Remove(address(a))
	}
	chain.Emit(DelegateWriteEvent,
		"key", runSubmittersKey, "realm", runSubmittersMgr, "op", "remove")
}

// GetRunSubmitters returns the current allowlist.
func GetRunSubmitters() []string {
	vals, _ := prms.GetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey)
	return vals
}

// ProposeSetRunSubmitters creates a GovDAO proposal replacing the whole
// run_submitters allowlist.
//
// This is the only way to set the list by vote: the generic factories refuse
// the key (see assertNotRunSubmittersKey), so every whole-list write comes
// through here and carries the rule below.
//
// The proposer must be on the list they propose.
//
// An empty run_submitters means the gate is off and anyone may MsgRun. A
// non-empty one therefore decides who may run code at all -- and a list naming
// nobody who can create a GovDAO proposal cannot be undone, because creating a
// proposal needs MsgRun: a ProposalRequest carries an Executor, and MsgCall
// cannot build one from string arguments. The vote would end governance.
//
// Requiring the proposer's own address is a cheap way to prove the list is
// usable rather than merely plausible. GovDAO refuses a proposal from a
// non-member (PreCreateProposal, "only members can create new proposals"), so
// if this proposal exists at all its author is a member -- and they just signed
// the transaction that created it, so the address demonstrably holds a key. A
// list that merely NAMES a member proves neither: the address may belong to
// nobody, since any member can enroll an arbitrary address.
//
// Checked here, at proposal creation, rather than inside the executor. Nothing
// in r/gov/dao recovers from an executor panic, so a check that fires at
// execution turns a passed proposal into one that can never be executed. Here
// the refusal reaches a person who can still fix the list and propose again.
//
// This is a floor, not an invariant. The proposer may resign from GovDAO later,
// and the list is not re-checked when they do. It rules out arriving at a dead
// list in one vote; it cannot rule out drifting into one.
func ProposeSetRunSubmitters(cur realm, addrs []string) dao.ProposalRequest {
	// IsCurrent before Previous, as AGENTS.md requires and assertDelegate does.
	//
	// Belt and braces here rather than load-bearing: the compiler already
	// refuses anything but `cur` or `cross(rlm)` as the first argument to a
	// crossing function, so this cur is live by construction and the check
	// cannot fire. It earns its place if this ever becomes a helper taking an
	// ordinary realm parameter, which is the shape assertDelegate has and where
	// a stashed value really can be threaded in.
	if !cur.IsCurrent() {
		panic("unauthorized: cur is not the caller's live realm")
	}
	proposer := cur.Previous().Address()
	listed := false
	for _, a := range addrs {
		if a == proposer.String() {
			listed = true
			break
		}
	}
	if len(addrs) > 0 && !listed {
		panic("refusing to propose a " + runSubmittersKey + " allowlist that omits " +
			"the proposer " + proposer.String() + ": a non-empty list that names nobody " +
			"who can create a proposal cannot be changed back")
	}

	title := "Set the " + runSubmittersKey + " allowlist"
	desc := "Replace the " + runSubmittersKey + " allowlist, which gates who may " +
		"send MsgRun."
	if len(addrs) == 0 {
		desc += " This empties the list, which switches the gate OFF: anyone may " +
			"send MsgRun."
	} else {
		desc += " Only these addresses may send MsgRun. Creating a GovDAO proposal " +
			"needs MsgRun, so this list also decides who can govern."
		for _, a := range addrs {
			desc += "\n- " + a
		}
	}

	callback := func(cur realm) error {
		setRunSubmitters(addrs)
		chain.Emit("SetRunSubmitters", "key", runSubmittersKey, "proposer", proposer.String())
		return nil
	}
	return dao.NewProposalRequest(title, desc,
		dao.NewSimpleExecutor(0, cur, callback, ""))
}

// setRunSubmitters replaces the whole allowlist.
//
// SetSysParamStrings, not UpdateSysParamStrings: Update with add=true appends
// non-duplicates onto what is already there, so it can never remove an address
// or empty the list. This realm reserves the key from the generic factories, so
// this is the only route by vote -- if it appended, the parameter would be
// append-only chain-wide, a compromised address could never be de-listed, and
// the gate could never be turned back off.
//
// A named function rather than the executor's body inline, so a test can reach
// it: a closure held in a ProposalRequest cannot be called from outside.
func setRunSubmitters(addrs []string) {
	prms.SetSysParamStrings(vmModulePrefix, vmParamsSubmodule, runSubmittersKey, addrs)
}

unlock.gno

package params

import "gno.land/r/gov/dao"

const (
	bankModulePrefix     = "bank"
	restrictedDenomsKey  = "restricted_denoms"
	unlockTransferTitle  = "Proposal to unlock the transfer of ugnot."
	lockTransferTitle    = "Proposal to lock the transfer of ugnot."
	authModulePrefix     = "auth"
	unrestrictedAddrsKey = "unrestricted_addrs"
)

func ProposeUnlockTransferRequest(cur realm) dao.ProposalRequest {
	return NewSysParamStringsPropRequestWithTitle(cur, bankModulePrefix, "p", restrictedDenomsKey, unlockTransferTitle, []string{})
}

func ProposeLockTransferRequest(cur realm) dao.ProposalRequest {
	return NewSysParamStringsPropRequestWithTitle(cur, bankModulePrefix, "p", restrictedDenomsKey, lockTransferTitle, []string{"ugnot"})
}

func ProposeAddUnrestrictedAcctsRequest(cur realm, addrs ...address) dao.ProposalRequest {
	addrStrings := make([]string, 0, len(addrs))
	for _, addr := range addrs {
		s := addr.String()
		addrStrings = append(addrStrings, s)
	}
	return NewSysParamStringsPropRequestAddWithTitle(cur, authModulePrefix, "p", unrestrictedAddrsKey, "Add unrestricted transfer accounts", addrStrings)
}

func ProposeRemoveUnrestrictedAcctsRequest(cur realm, addrs ...address) dao.ProposalRequest {
	addrStrings := make([]string, 0, len(addrs))
	for _, addr := range addrs {
		s := addr.String()
		addrStrings = append(addrStrings, s)
	}
	return NewSysParamStringsPropRequestRemoveWithTitle(cur, authModulePrefix, "p", unrestrictedAddrsKey, "Remove unrestricted transfer accounts", addrStrings)
}

unlock_test.gno

package params

import (
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/urequire/v0"
	"gno.land/r/gov/dao"
	ini "gno.land/r/gov/dao/init/v0"
)

var g1user = testutils.TestAddress("g1user")

func init(cur realm) {
	testing.SetRealm(testing.NewUserRealm(g1user))
	ini.InitWithUsers(cross(cur), g1user)
}

func TestProUnlockTransfer(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(g1user))

	pr := ProposeUnlockTransferRequest(cur)
	id := dao.MustCreateProposal(cross(cur), pr)
	p, err := dao.GetProposal(id)
	urequire.NoError(t, err)
	urequire.Equal(t, unlockTransferTitle, p.Title())
}

func TestFailUnlockTransfer(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(g1user))

	pr := ProposeUnlockTransferRequest(cur)
	id := dao.MustCreateProposal(cross(cur), pr)
	urequire.AbortsWithMessage(
		t, cur,
		"proposal didn't reach supermajority yet: 66.66",
		func() {
			dao.ExecuteProposal(cross(cur), id)
		},
	)
}

func TestExeUnlockTransfer(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(g1user))

	pr := ProposeUnlockTransferRequest(cur)
	id := dao.MustCreateProposal(cross(cur), pr)
	_, err := dao.GetProposal(id)
	urequire.NoError(t, err)
	// urequire.True(t, dao.Active == p.Status()) // TODO

	urequire.NotPanics(
		t, cur,
		func() {
			dao.MustVoteOnProposal(cross(cur), dao.NewVoteRequest(dao.YesVote, dao.ProposalID(id)))
		},
	)

	urequire.NotPanics(
		t, cur,
		func() {
			dao.ExecuteProposal(cross(cur), id)
		},
	)
}

valoper.gno

package params

import (
	prms "sys/params"
)

// Valoper sys-param keys consumed by r/gnops/valopers (Register +
// UpdateSigningKey). Governance can update them via the generic
// NewSysParam*PropRequest factories — no realm-side gate is needed
// because the values only affect fees and throttle inside valopers.
const (
	valoperSubmodule = "valoper"

	valoperRegisterFeeKey          = "register_fee"
	valoperRotationFeeKey          = "rotation_fee"
	valoperRotationPeriodBlocksKey = "rotation_period_blocks"
)

// Default values used when the sys-param has never been set by
// governance. Zero fees (GNOT transfers are disabled chain-wide
// pre-fork) and a ~1-hour throttle at 6s/block.
const (
	defaultValoperRegisterFee          = uint64(0)
	defaultValoperRotationFee          = uint64(0)
	defaultValoperRotationPeriodBlocks = int64(600)
)

// GetValoperRegisterFee returns the fee (in ugnot) required to call
// valopers.Register. Defaults to 0 if governance hasn't set it.
func GetValoperRegisterFee() uint64 {
	v, ok := prms.GetSysParamUint64(nodeModulePrefix, valoperSubmodule, valoperRegisterFeeKey)
	if !ok {
		return defaultValoperRegisterFee
	}
	return v
}

// GetValoperRotationFee returns the fee (in ugnot) required to call
// valopers.UpdateSigningKey. Defaults to 0.
func GetValoperRotationFee() uint64 {
	v, ok := prms.GetSysParamUint64(nodeModulePrefix, valoperSubmodule, valoperRotationFeeKey)
	if !ok {
		return defaultValoperRotationFee
	}
	return v
}

// GetValoperRotationPeriodBlocks returns the per-operator rotation
// throttle (in blocks). Defaults to ~1h worth at 6s/block (600).
// This is the primary anti-spam defense pre-fee while rotation_fee
// stays at 0; tightens further once non-zero fees become enforceable.
func GetValoperRotationPeriodBlocks() int64 {
	v, ok := prms.GetSysParamInt64(nodeModulePrefix, valoperSubmodule, valoperRotationPeriodBlocksKey)
	if !ok {
		return defaultValoperRotationPeriodBlocks
	}
	return v
}

valset.gno

package params

import (
	"chain"
	"errors"
	"strconv"
	"strings"

	prms "sys/params"

	"gno.land/p/sys/validators/v0"
)

// Param keys read by gno.land/pkg/gnoland (EndBlocker).
// Keep in sync with gno.land/pkg/gnoland/node_params.go.
// nodeModulePrefix is declared in halt.gno (same package).
const (
	valsetSubmodule = "valset"

	// dirty signals the chain that the proposed valset differs from the
	// current applied one. Realm sets true; EndBlocker clears.
	valsetDirtyKey = "dirty"

	// One []string per slot; each entry has the form "<pubkey>:<power>"
	// (bech32 pubkey + decimal power). Address is derived from pubkey
	// on the chain side and not stored.
	//
	//   proposed = v0's full target valset
	//   current  = chain-managed: the set that becomes ACTIVE AT H+2
	//              once the most recent EndBlock's updates apply.
	//              NOT necessarily the set actively signing the current
	//              block — see ABCI H+2 sequencing.
	valsetProposedKey = "proposed"
	valsetCurrentKey  = "current"

	// pubkey_types: chain-mirrored validator pubkey-type allow-list (read-only here).
	valsetPubKeyTypesKey = "pubkey_types"

	// Only this realm may write valset:proposed and valset:dirty.
	// valset:current is chain-managed (see ctx-sentinel in node_params.go).
	valsetAuthorizedRealm = "gno.land/r/sys/validators/v0"
)

// SetValsetProposal publishes the realm's desired valset. Each entry is
// "<bech32-pubkey>:<decimal-power>"; power=0 removes the validator.
// The chain reads this on the next EndBlocker, diffs it against
// valset:current, and propagates the changes to consensus.
func SetValsetProposal(cur realm, entries []string) {
	assertValsetCaller(0, cur)
	prms.SetSysParamStrings(nodeModulePrefix, valsetSubmodule, valsetProposedKey, entries)
	prms.SetSysParamBool(nodeModulePrefix, valsetSubmodule, valsetDirtyKey, true)
}

// GetValsetEntries returns the chain's authoritative committed
// validator set (the contents of valset:current). This is the
// V_{H+2} view — the set that will be active at H+2 once the most
// recent EndBlock's updates apply, NOT the set signing the current
// block. Callers that want "what v0 reports as the current
// validator set" — including the in-flight proposed set during
// the dirty window — should call GetValsetEffective instead.
func GetValsetEntries() []validators.Validator {
	return parseValsetSlot(valsetCurrentKey)
}

// ValsetDirty reports whether valset:proposed is awaiting EndBlocker.
// Realm callers MUST treat this as transient: the dirty flag is set
// by SetValsetProposal and cleared by the chain's EndBlocker (every
// block where dirty=true on entry exits with dirty=false).
func ValsetDirty() bool {
	d, _ := prms.GetSysParamBool(nodeModulePrefix, valsetSubmodule, valsetDirtyKey)
	return d
}

// GetValsetEffective returns the set that WILL be active at H+2:
// valset:proposed if dirty, else valset:current. Used by v0 so that
// (a) reads after a same-block proposal callback see that proposal's
// effects, and (b) sequential same-block proposals accumulate
// correctly on top of each other.
//
// Misuse warning: this exists for r/sys/validators/v0's internal
// reads. Other realms making "is X a validator" decisions should
// call v0.IsValidator, not this directly, so future changes to v0's
// read semantics propagate uniformly.
func GetValsetEffective() []validators.Validator {
	key := valsetCurrentKey
	if ValsetDirty() {
		key = valsetProposedKey
	}
	return parseValsetSlot(key)
}

func parseValsetSlot(key string) []validators.Validator {
	raw, _ := prms.GetSysParamStrings(nodeModulePrefix, valsetSubmodule, key)
	out := make([]validators.Validator, 0, len(raw))
	for _, e := range raw {
		v, err := parseEntry(e)
		if err != nil {
			panic("valset:" + key + " corrupted: " + err.Error())
		}
		out = append(out, v)
	}
	return out
}

// parseEntry splits "<bech32-pubkey>:<decimal-power>" and derives the
// validator address via the chain.PubKeyAddress native helper.
func parseEntry(entry string) (validators.Validator, error) {
	pkStr, pStr, ok := strings.Cut(entry, ":")
	if !ok {
		return validators.Validator{}, errors.New("missing ':' separator in " + entry)
	}
	addr, err := chain.PubKeyAddress(pkStr)
	if err != nil {
		return validators.Validator{}, err
	}
	power, err := strconv.ParseUint(pStr, 10, 64)
	if err != nil {
		return validators.Validator{}, err
	}
	return validators.Validator{
		Address:     addr,
		PubKey:      pkStr,
		VotingPower: power,
	}, nil
}

// GetValsetPubKeyTypes returns the validator pubkey-type allow-list mirrored from consensus params (empty means accept any).
func GetValsetPubKeyTypes() []string {
	types, _ := prms.GetSysParamStrings(nodeModulePrefix, valsetSubmodule, valsetPubKeyTypesKey)
	return types
}

// assertValsetCaller authorizes the one realm permitted to write valset params.
//
// Delegates to assertDelegate (see delegate.gno) so this realm has exactly one
// authorized-caller gate rather than two that can drift. The distinction that
// remains is deliberate and is NOT expressible through a delegation slot: this
// authorization is a compile-time const, so re-pointing it requires a chain
// relaunch, and assertNotValsetKey locks GovDAO out of the key family entirely.
// A vote-settable slot would let one supermajority re-point the valset writer at
// an arbitrary realm and bypass v0's valoper-existence check, its KeepRunning
// opt-out, and execution-time pubkey re-resolution.
func assertValsetCaller(_ int, rlm realm) {
	assertDelegate(0, rlm, valsetAuthorizedRealm, "valset params")
}