Playground
admin.gno
package valopers
import (
"gno.land/p/moul/authz/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/r/gov/dao"
)
var auth *authz.Authorizer
// Auth returns a read-only description of the realm's current governance
// authority (for rendering / inspection). It renders as
//
// contract_authority[contract=gno.land/r/gov/dao,proposer=contract-identity]
//
// i.e. "GovDAO governs this realm, and only GovDAO may drive it" — a
// statement an on-chain reader can act on. The proposer half is
// load-bearing: without it the string is byte-identical whether the
// authority is gated or wide open (see ContractAuthority.String).
//
// It deliberately does NOT return the live *authz.Authorizer: an
// exported handle to the authority would let any realm reach its
// mutators (Transfer, DoByPrevious, ...) directly. Returning a
// description instead of the handle keeps that surface unreachable from
// here in the first place. Valoper.AuthOwner follows the same rule for
// per-operator auth lists.
func Auth() string {
return auth.String()
}
// updateInstructions is the realm's only privileged write. It authorizes
// as the realm that CROSSED INTO valopers, not as valopers itself.
//
// Why DoByPrevious and not DoByCurrent: own-path + DoByCurrent is a
// tautology (see NewContractAuthority's godoc for the mechanism, once).
// `rlm.Previous()` is the caller — on the legitimate path r/gov/dao's
// executor frame, which is what init.gno's authority is pointed at.
//
// What it buys: it is the code-level guard against this realm's most
// likely regression, a maintainer later adding an exported crossing
// entrypoint that reaches here. Under DoByCurrent such an entrypoint
// authorizes for any caller; under DoByPrevious the caller's own address
// is the principal and the gate rejects it. Pinned by
// filetests/z_govdao_only_principal_filetest.gno.
//
// Two things it does NOT cover on its own, both closed elsewhere:
// re-exporting the privileged closure (guarded by the seal in
// NewInstructionsProposalRequest), and exporting a function whose
// signature is assignable to dao's `func(realm) error` callback type,
// which the proxy would invoke on an attacker's behalf. The second was a
// live bypass of this gate until SimpleExecutor.Execute began rejecting
// invocation from outside r/gov/dao (r/gov/dao/types.gno); keep BOTH
// conditions in mind before adding an exported symbol here.
//
// Returns the authorization error rather than panicking on it. That matters
// on the governance path: impl.ExecuteProposal turns an executor ERROR into
// status Denied plus a DeniedReason, but it cannot see a panic — a panic
// aborts the whole ExecuteProposal transaction, burning its gas and leaving
// the proposal stuck Accepted, retryable forever and never deniable. The
// refusal is currently unreachable on the approved route (Previous() there
// is always r/gov/dao), but init.gno's handler is explicitly offered as the
// seam for an intent check (timelock, quorum, audit trail), and the first
// such check to return an error would hit exactly that.
func updateInstructions(_ int, rlm realm, newInstructions string) error {
return auth.DoByPrevious(0, rlm, "update-instructions", func() error {
instructions = newInstructions
return nil
})
}
// NewInstructionsProposalRequest builds the GovDAO proposal that rewrites
// this realm's instructions. It replaces the previously exported
// NewInstructionsProposalCallback.
//
// SECURITY: the privileged closure must never leave this package.
//
// The VM mints a crossing frame's `cur` from the CALLEE's declaring
// package, so a closure declared here always runs with valopers'
// identity no matter who invokes it — and whoever holds the closure
// chooses its Previous() by wrapping it in an executor of their own.
// Handing such a closure to a caller therefore hands out the ability to
// satisfy this realm's gate whichever principal it is pointed at: the
// handler in init.gno runs the action and `instructions` is rewritten
// with no proposal and no vote. That is what the exported callback did.
//
// Returning a dao.ProposalRequest instead seals the capability: the
// executor is an unexported field with no accessor (dao.ProposalRequest
// exposes only Title/Description/Filter), so the only way to reach the
// closure is for GovDAO to execute the proposal that contains it.
//
// Note this is deliberately stronger than returning a dao.Executor —
// even a dao.NewSafeExecutor-wrapped one. Executor.Execute is an
// exported method, so a returned Executor stays directly invocable by
// its holder, and SafeExecutor's only gate (InAllowedDAOs) FAILS OPEN
// while the allowedDAOs list is empty, which is the documented
// bootstrap state (see r/gov/dao/loader/v0). A sealed request has no
// such conditional.
//
// The rule for this realm: no exported function may return a crossing
// closure, a dao.Executor, or anything else that carries valopers'
// frame identity — and no exported function may itself BE such a thing,
// i.e. have a signature assignable to dao's `func(realm) error` callback
// type, since the proxy would then invoke it on an attacker's behalf.
// filetests/z_foreign_realm_capability_filetest.gno pins the first;
// filetests/z_govdao_only_principal_filetest.gno pins the second.
func NewInstructionsProposalRequest(cur realm, newInstructions string) dao.ProposalRequest {
cb := func(cur realm) error {
return updateInstructions(0, cur, newInstructions)
}
title := instructionsProposalTitle
description := ufmt.Sprintf("Update the instructions to: \n\n%s", newInstructions)
return dao.NewProposalRequest(title, description, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// instructionsProposalTitle is the on-chain title of the instructions
// proposal, named as a constant so a test can pin it: it is rendered to
// GovDAO voters and is the string off-chain tooling matches on. It was
// "/p/gnops/valopers: ..." before this realm's proposal construction moved
// here; the "/p/" was simply wrong (valopers is an /r/ realm).
const instructionsProposalTitle = "/r/gnops/valopers: Update instructions"
// rotateAuthority replaces this realm's governance authority.
//
// Unexported, and reachable only through the sealed request built by
// NewAuthorityRotationProposalRequest — same discipline as
// updateInstructions, for the same reason.
//
// authz.Authorizer.Transfer derives its principal as
// rlm.Previous().Address(), so inside a GovDAO-executed callback declared
// here Previous() is r/gov/dao — exactly the principal init.gno's authority
// asserts. No same-package cross() trick is needed.
func rotateAuthority(_ int, rlm realm, newContractPath string) error {
return auth.Transfer(0, rlm, authz.NewContractAuthority(
newContractPath,
func(_ string, action authz.PrivilegedAction) error {
return action()
},
))
}
// NewAuthorityRotationProposalRequest builds the GovDAO proposal that
// re-points this realm's governance authority at `newContractPath`.
//
// WHY THIS EXISTS. Without it the authority installed by init.gno is
// permanently frozen: nothing else calls auth.Transfer, Auth() returns a
// description rather than the live Authorizer, and Transfer routes through
// the authority's own gate — so if the asserted principal ever stops being
// presentable, `instructions` becomes unwritable with no on-chain recovery.
// That is not hypothetical: the r/gov/dao proxy path is a governance
// artifact that can be superseded, and a well-formed but wrong path (say
// the impl path instead of the proxy) is accepted at construction and dead
// forever. Redeploying instead is expensive — r/sys/validators/v0/cache.gno
// hardcodes `const valopersRealmPath`, so a new pkgpath means editing a
// second genesis realm and re-registering every valoper. It must exist
// before deploy, because code cannot be added to a deployed realm.
//
// WHY A PATH AND NOT AN authz.Authority. Taking an Authority would make
// this an open-interface input (Class-3 impl-substitution): a proposal
// could install an always-approve or always-deny authority, and readers of
// Auth() could not tell from the rendered description alone. Taking a path
// keeps the installed authority canonical by construction — always a
// ContractAuthority with the pass-through handler and the contract-identity
// gate — so the only thing governance can change is WHICH principal is
// asserted. The path is validated by authz.NewContractAuthority, which
// panics on a malformed one, aborting the proposal execution rather than
// bricking the realm.
//
// This remains a privileged surface: a majority that can pass this proposal
// can point the authority at a principal it controls. That is the same
// power a majority already has over `instructions`, and it is the price of
// being recoverable at all.
func NewAuthorityRotationProposalRequest(cur realm, newContractPath string) dao.ProposalRequest {
cb := func(cur realm) error {
return rotateAuthority(0, cur, newContractPath)
}
title := "/r/gnops/valopers: Rotate governance authority"
description := ufmt.Sprintf(
"Re-point the valopers governance authority at: \n\n%s\n\n"+
"The authority stays a contract-identity ContractAuthority; only the asserted principal changes.",
newContractPath,
)
return dao.NewProposalRequest(title, description, dao.NewSimpleExecutor(0, cur, cb, ""))
}
// NewInstructionsProposalCallback was removed, not deprecated: it was the
// capability leak described above, so an inert shim would be pointless and
// a working one would reopen the hole. Precedent + replay check: the
// min-fee callback below was already removed the same way even though it
// HAD been used on gnoland1 (GovDAO Prop #19), whereas the instructions
// callback has no on-chain trace at all — the live realm's instructions
// are byte-identical to the genesis default and none of gnoland1's 26
// GovDAO proposals is an "Update instructions" one.
//
// The min-fee callback was removed: the fee now lives in sysparams
// under node:valoper:register_fee, and
// proposal.ProposeNewMinFeeProposalRequest delegates to
// sys/params.NewSysParamUint64PropRequest. Removing avoids the
// forward-compat hazard of a no-op shim with no caller-auth gating.
admin_test.gno
package valopers
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
// TestAuthDescribesGovDAOGate pins init.gno's configuration, including the
// proposer half — which is the load-bearing half.
//
// Deliberately does NOT reassign `auth`: an earlier version of this test
// built its own ContractAuthority and then claimed to "mirror init.gno",
// which meant changing the contract path in init.gno left it green.
//
// Before ContractAuthority.String() rendered the proposer, this assertion
// was blind to the drift that matters: swapping init.gno for
// NewRestrictedContractAuthority(path, handler, NewAutoAcceptAuthority())
// — i.e. reopening the hole for this realm — left the rendered string
// byte-identical and the whole valopers suite green.
//
// It is also blind no longer to a proposer that merely CLAIMS to be the
// contract-identity default: authz renders any non-canonical Authority
// wrapped as custom_authority[...], so a spoofing impl cannot reproduce
// these bytes. See authz's TestSpoofedProposerCannotImpersonateContractIdentity.
func TestAuthDescribesGovDAOGate(cur realm, t *testing.T) {
uassert.Equal(t,
"contract_authority[contract=gno.land/r/gov/dao,proposer=contract-identity]",
Auth())
}
// TestUpdateInstructionsRejectsNonGovDAO is the negative pin for the
// repointed authority, and it is the one that would have caught the
// regression class this realm fears.
//
// The authority is a ContractAuthority for gno.land/r/gov/dao driven by
// DoByPrevious, so the principal is whoever crossed into valopers. Here
// that is the test's own frame, not GovDAO's executor — so the privileged
// write must be refused and `instructions` must not move.
//
// Note what this test could NOT assert before the repoint: under the
// previous ContractAuthority(ownPath) + DoByCurrent pairing, rlm.Address()
// inside any valopers crossing frame is unconditionally valopers' own
// address, so this exact call SUCCEEDED and the old version of this test
// asserted NotPanics. That is why it never pinned anything: the gate it was
// exercising could not reject.
//
// The positive half — that GovDAO can still perform the write — lives in
// proposal/filetests/z_governed_instructions_filetest.gno, which runs
// propose -> vote -> execute end to end.
func TestUpdateInstructionsRejectsNonGovDAO(cur realm, t *testing.T) {
before := instructions
// An ERROR, not a panic: the refusal has to travel back to
// impl.ExecuteProposal as a value so a passed-but-refused proposal can
// be marked Denied instead of aborting the execute transaction. See
// updateInstructions.
err := updateInstructions(0, cur, "SHOULD-NOT-LAND")
uassert.ErrorContains(t, err, "unauthorized",
"a non-GovDAO principal must be refused")
uassert.Equal(t, before, instructions,
"instructions must not move when the gate refuses")
}
// The instructions proposal's on-chain title is rendered to GovDAO voters
// and is what off-chain tooling matches on, so it is pinned rather than
// left to drift silently. It changed in this realm's history from
// "/p/gnops/valopers: ..." (wrong — valopers is an /r/ realm) when
// proposal construction moved out of r/gnops/valopers/proposal.
func TestInstructionsProposalTitleIsPinned(cur realm, t *testing.T) {
uassert.Equal(t, "/r/gnops/valopers: Update instructions", instructionsProposalTitle)
req := NewInstructionsProposalRequest(cross(cur), "whatever")
uassert.Equal(t, instructionsProposalTitle, req.Title())
}
// The authority must be rotatable by GovDAO, or a principal that stops
// being presentable freezes `instructions` with no on-chain recovery (and
// redeploying is expensive: r/sys/validators/v0/cache.gno hardcodes
// valopersRealmPath). This pins that the rotation path exists, is sealed
// the same way the instructions write is, and that a non-GovDAO principal
// cannot drive it.
func TestRotateAuthorityRejectsNonGovDAO(cur realm, t *testing.T) {
before := Auth()
err := rotateAuthority(0, cur, "gno.land/r/gov/dao/v4")
uassert.ErrorContains(t, err, "unauthorized",
"a non-GovDAO principal must not be able to rotate the authority")
uassert.Equal(t, before, Auth(), "the authority must be unchanged")
}
// The rotation request is built here and returned sealed: dao.ProposalRequest
// exposes only Title/Description/Filter, so a holder cannot reach the
// executor. Anyone may build one; only GovDAO can adopt and run it.
func TestRotationProposalRequestIsSealed(cur realm, t *testing.T) {
req := NewAuthorityRotationProposalRequest(cross(cur), "gno.land/r/gov/dao/v4")
uassert.Equal(t, "/r/gnops/valopers: Rotate governance authority", req.Title())
uassert.NotEqual(t, "", req.Description())
// Building the request must not itself perform the rotation.
uassert.Equal(t,
"contract_authority[contract=gno.land/r/gov/dao,proposer=contract-identity]",
Auth())
}
// TestUpdateMinFee was removed: register_fee now lives in sysparams
// (node:valoper:register_fee), governed via the generic
// NewSysParamUint64PropRequest factory. See proposal.gno for the
// replacement flow.
gnomod.toml
module = "gno.land/r/gnops/valopers" gno = "0.9" [addpkg] creator = "g1g3lsfxhvaqgdv4ccemwpnms4fv6t3aq3p5z6u7"
init.gno
package valopers
import (
"gno.land/p/moul/authz/v0"
"gno.land/p/moul/txlink/v0"
"gno.land/p/nt/avl/v0"
)
func init() {
valopers = avl.NewTree()
// The authority is pointed at GovDAO, NOT at this realm.
//
// Pointing it here instead would make the gate compare valopers'
// address to valopers' address: every crossing frame of this package
// has rlm.Address() == PackageAddress(ownPath), so the check could
// never reject. Pointed at r/gov/dao and driven by DoByPrevious
// (see updateInstructions), the principal is the realm that crossed
// in — GovDAO's executor on the legitimate path, and the caller
// itself on any other, which is what makes the check real.
//
// The handler is a pass-through: this is where an intent check
// (timelock, quorum, audit trail) would go if one is ever wanted.
// It is NOT where the caller check lives — that is the authority's
// contract-identity gate, upstream of here.
auth = authz.NewWithAuthority(
authz.NewContractAuthority(
"gno.land/r/gov/dao",
func(_ string, action authz.PrivilegedAction) error {
return action()
},
),
)
instructions = `
# Welcome to the **Valopers** realm
## 📌 Purpose of this Contract
The **Valopers** contract is designed to maintain a registry of **validator profiles**. This registry provides essential information to **GovDAO members**, enabling them to make informed decisions when voting on the inclusion of new validators into the **valset**.
By registering your validator profile, you contribute to a transparent and well-informed governance process within **gno.land**.
---
## 📝 How to Register Your Validator Node
To add your validator node to the registry, use the [**Register**](` + txlink.Call("Register") + `) function with the following parameters:
- **Moniker** (Validator Name)
- Must be **human-readable**
- **Max length**: **32 characters**
- **Allowed characters**: Letters, numbers, spaces, hyphens (**-**), and underscores (**_**)
- **No special characters** at the beginning or end
- **Description** (Introduction & Validator Details)
- **Max length**: **2048 characters**
- Must include answers to the questions listed below
- **Server Type** (Infrastructure Type)
- Must be one of the following values:
- **cloud**: For validators running on cloud infrastructure (AWS, GCP, Azure, etc.)
- **on-prem**: For validators running on on-premises infrastructure
- **data-center**: For validators running in dedicated data centers
- **Operator Address**
- The ` + "`g1...`" + ` address of your operator account (from your ` + "`gnokey`" + ` keyring)
- **Must be controlled by the signer** of this transaction — the realm rejects the call if the signer doesn't control that address
- **Validator Consensus Public Key**
- Your validator node's consensus public key, in the ` + "`gpub1...`" + ` format
- Retrieve it by running: ` + "`gnoland secrets get validator_key`" + `
### ✍️ Required Information for the Description
Please provide detailed answers to the following questions to ensure transparency and improve your chances of being accepted:
1. The name of your validator
2. Networks you are currently validating and your total AuM (assets under management)
3. Links to your **digital presence** (website, social media, etc.). Please include your Discord handle to be added to our main comms channel, the gno.land valoper Discord channel.
4. Contact details
5. Why are you interested in validating on **gno.land**?
6. What contributions have you made or are willing to make to **gno.land**?
---
## 🔄 Updating Your Validator Information
After registration, you can update your validator details using the **update functions** provided by the contract.
---
## 📢 Submitting a Proposal to Join the Validator Set
Once you're satisfied with your **valoper** profile, you need to notify GovDAO; only a GovDAO member can submit a proposal to add you to the validator set.
If you are a GovDAO member, you can nominate yourself by executing the following function: [**r/gnops/valopers/proposal.ProposeNewValidator**](` + txlink.Realm("gno.land/r/gnops/valopers/proposal").Call("ProposeNewValidator") + `)
This will initiate a governance process where **GovDAO** members will vote on your proposal.
---
🚀 **Register now and become a part of gno.land’s validator ecosystem!**
Read more: [How to become a validator](https://github.com/gnolang/gno/tree/master/gno.land/cmd/gnoland#become-a-validator)
Disclaimer: Please note, registering your validator profile and/or validating on testnets does not guarantee a validator slot on the gno.land beta mainnet. However, active participation and contributions to testnets will help establish credibility and may improve your chances for future validator acceptance. The initial validator amount and valset will ultimately be selected through GovDAO governance proposals and acceptance.
---
`
}
pubkey_type_test.gno
package valopers
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
const (
testEd25519PubKey = "gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqkn3nln2k8glpf9kpqtz4h63n7cd0jvxkq6rpk4dxzp4sq527mhqwv40hr"
testSecp256k1PubKey = "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pq0skzdkmzu0r9h6gny6eg8c9dc303xrrudee6z4he4y7cs5rnjwmyf40yaj"
)
func TestPubKeyTypeURL(t *testing.T) {
got, err := pubKeyTypeURL(testEd25519PubKey)
uassert.NoError(t, err)
uassert.Equal(t, "/tm.PubKeyEd25519", got)
got, err = pubKeyTypeURL(testSecp256k1PubKey)
uassert.NoError(t, err)
uassert.Equal(t, "/tm.PubKeySecp256k1", got)
_, err = pubKeyTypeURL("not-a-valid-bech32-pubkey")
uassert.Error(t, err)
}
func TestAssertPubKeyTypeAllowed(t *testing.T) {
// Empty allow-list accepts any well-formed type.
testing.SetSysParamStrings("node", "valset", "pubkey_types", []string{})
uassert.NotPanics(t, cur, func() { assertPubKeyTypeAllowed(testSecp256k1PubKey) })
// ed25519-only allow-list: ed25519 accepted, secp256k1 rejected.
testing.SetSysParamStrings("node", "valset", "pubkey_types", []string{"/tm.PubKeyEd25519"})
uassert.NotPanics(t, cur, func() { assertPubKeyTypeAllowed(testEd25519PubKey) })
uassert.PanicsWithMessage(t, cur, ErrDisallowedPubKeyType.Error(), func() {
assertPubKeyTypeAllowed(testSecp256k1PubKey)
})
// Reset so the non-empty allow-list doesn't leak into other tests.
testing.SetSysParamStrings("node", "valset", "pubkey_types", []string{})
}
rotate_test.gno
package valopers
import (
"chain"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const (
// Second valid pubkey used as the rotation target. Distinct from
// validValidatorInfo's pubkey so the signingRegistry uniqueness
// check is exercised.
rotateTargetPubKey = "gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zq3ds6sdvc0shfkq02h6xx5g0jp04aadexfnpsmgjxu72xz9y30aqfrlpny"
// Test-local mirror of the rotation_period_blocks sys-param's
// default. resetState() seeds the same value into sysparams.
testRotationPeriodBlocks = int64(600)
)
// registerForRotation does the boilerplate setup that every rotation
// test starts from: clear state, register the valoper as info.Address,
// and return the info struct. rlm is threaded into Register via
// cross(rlm) — it's a non-first parameter so the helper stays a
// regular (non-crossing) function.
func registerForRotation(t *testing.T, rlm realm) struct {
Moniker string
Description string
ServerType string
Address address
PubKey string
} {
t.Helper()
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
Register(cross(rlm), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
return info
}
func TestUpdateSigningKey_HappyPath(cur realm, t *testing.T) {
info := registerForRotation(t, cur)
// Advance past the throttle window. SkipHeights doesn't preserve
// the realm context across the boundary, so re-set it before the
// next cross-call.
testing.SkipHeights(testRotationPeriodBlocks + 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
uassert.NotAborts(t, cur, func() {
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
})
v := GetByAddr(info.Address)
uassert.Equal(t, rotateTargetPubKey, v.SigningPubKey)
newSigningAddr, err := chain.PubKeyAddress(rotateTargetPubKey)
urequire.NoError(t, err)
uassert.Equal(t, newSigningAddr, v.SigningAddress)
// New entry active in registry.
rawNew := signingRegistry.Get(newSigningAddr.String())
urequire.NotNil(t, rawNew, "new signing addr in registry")
newEntry := rawNew.(regEntry)
uassert.Equal(t, info.Address, newEntry.OperatorAddress)
uassert.Equal(t, int64(0), newEntry.RetiredAtHeight)
// Old entry retired (still present, RetiredAtHeight > 0).
oldSigningAddr, err := chain.PubKeyAddress(info.PubKey)
urequire.NoError(t, err)
rawOld := signingRegistry.Get(oldSigningAddr.String())
urequire.NotNil(t, rawOld, "old signing addr retained as retired")
oldEntry := rawOld.(regEntry)
uassert.Equal(t, info.Address, oldEntry.OperatorAddress)
uassert.True(t, oldEntry.RetiredAtHeight > 0, "old entry must be retired (RetiredAtHeight > 0)")
}
func TestUpdateSigningKey_ThrottleRejection(cur realm, t *testing.T) {
info := registerForRotation(t, cur)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Try to rotate immediately, before throttle elapses.
uassert.AbortsWithMessage(t, cur, ErrRotationThrottled.Error(), func() {
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
})
// Advance just shy of the threshold; still rejected.
testing.SkipHeights(testRotationPeriodBlocks - 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
uassert.AbortsWithMessage(t, cur, ErrRotationThrottled.Error(), func() {
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
})
// One more block — now exactly at the threshold; allowed.
testing.SkipHeights(1)
testing.SetRealm(testing.NewUserRealm(info.Address))
uassert.NotAborts(t, cur, func() {
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
})
}
func TestUpdateSigningKey_RejectsNonAuthListCaller(cur realm, t *testing.T) {
info := registerForRotation(t, cur)
testing.SkipHeights(testRotationPeriodBlocks + 1)
// Switch to a caller not on the auth list.
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("attacker")))
// Pin the exact authorizable error so this catches an auth
// regression rather than any abort. Empty-substring match (the
// previous form) accepted any panic, including unrelated ones.
uassert.AbortsContains(t, cur, "not in authorized list", func() {
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
})
}
func TestUpdateSigningKey_RejectsReuseOfActiveKey(cur realm, t *testing.T) {
info := registerForRotation(t, cur)
testing.SkipHeights(testRotationPeriodBlocks + 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Try to "rotate" to the same key — already in registry.
uassert.AbortsWithMessage(t, cur, ErrSigningKeyTaken.Error(), func() {
UpdateSigningKey(cross(cur), info.Address, info.PubKey)
})
}
func TestUpdateSigningKey_RejectsRotationOntoActiveValidator(cur realm, t *testing.T) {
// Front-running guard: a rotation whose derived signing address is
// already an active validator must be rejected. Mirrors the same
// guard in Register (valopers.gno: ErrFrontrunValidator). Without
// this, any valoper could rotate onto an unregistered (e.g.
// genesis-seeded) validator slot — v0's executor would overwrite
// the active validator's entry in the effective valset with this
// operator's claim, then a subsequent govDAO remove-op proposal
// would delete it. signingRegistry uniqueness alone doesn't catch
// this case: a genesis-seeded validator never went through
// Register or UpdateSigningKey, so its signing address is absent
// from signingRegistry.
info := registerForRotation(t, cur)
// Seed v0's valset:current with the address that rotateTargetPubKey
// derives to. ValsetEffective is read from valset:current when the
// dirty flag is unset, which is the default.
testing.SetSysParamStrings("node", "valset", "current",
[]string{rotateTargetPubKey + ":1"})
testing.SkipHeights(testRotationPeriodBlocks + 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
uassert.AbortsWithMessage(t, cur, ErrFrontrunValidator.Error(), func() {
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
})
// Cleanup: clear the seeded valset to avoid leaking into sibling
// subtests if the runner doesn't reset package state between them.
testing.SetSysParamStrings("node", "valset", "current", []string{})
}
func TestUpdateSigningKey_RejectsReuseOfRetiredKey(cur realm, t *testing.T) {
info := registerForRotation(t, cur)
// First rotation: info.PubKey -> rotateTargetPubKey. info.PubKey
// becomes retired.
testing.SkipHeights(testRotationPeriodBlocks + 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
// Second rotation back to info.PubKey must fail — it's retired
// but signingRegistry retains it forever.
testing.SkipHeights(testRotationPeriodBlocks + 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
uassert.AbortsWithMessage(t, cur, ErrSigningKeyTaken.Error(), func() {
UpdateSigningKey(cross(cur), info.Address, info.PubKey)
})
}
func TestUpdateSigningKey_LastRotationHeightAdvances(cur realm, t *testing.T) {
info := registerForRotation(t, cur)
testing.SkipHeights(testRotationPeriodBlocks + 1)
testing.SetRealm(testing.NewUserRealm(info.Address))
UpdateSigningKey(cross(cur), info.Address, rotateTargetPubKey)
v := GetByAddr(info.Address)
uassert.True(t, v.LastRotationHeight > 0, "LastRotationHeight set on rotation")
// Immediately after, throttle rejects again.
uassert.AbortsWithMessage(t, cur, ErrRotationThrottled.Error(), func() {
UpdateSigningKey(cross(cur), info.Address, "gpub1pgfj7ard9eg82cjtv4u4xetrwqer2dntxyfzxz3pqddddqg2glc8x4fl7vxjlnr7p5a3czm5kcdp4239sg6yqdc4rc2r5cjrffs")
})
}
valopers.gno
// Package valopers is designed around the permissionless lifecycle of valoper profiles.
package valopers
import (
"chain"
"chain/runtime"
"chain/runtime/unsafe"
"crypto/bech32"
"errors"
"math"
"regexp"
"gno.land/p/moul/realmpath/v0"
"gno.land/p/nt/avl/pager/v0"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/combinederr/v0"
"gno.land/p/nt/ownable/exts/authorizable/v0"
"gno.land/p/nt/ownable/v0"
"gno.land/p/nt/ufmt/v0"
sysparams "gno.land/r/sys/params"
validators "gno.land/r/sys/validators/v0"
)
const (
MonikerMaxLength = 32
DescriptionMaxLength = 2048
// Valid server types
ServerTypeCloud = "cloud"
ServerTypeOnPrem = "on-prem"
ServerTypeDataCenter = "data-center"
)
var (
ErrValoperExists = errors.New("valoper already exists")
ErrValoperMissing = errors.New("valoper does not exist")
ErrInvalidAddress = errors.New("invalid address")
ErrInvalidMoniker = errors.New("moniker is not valid")
ErrInvalidDescription = errors.New("description is not valid")
ErrInvalidServerType = errors.New("server type is not valid")
ErrOperatorSquatGuard = errors.New("post-genesis: caller must equal operator address")
ErrSigningKeyTaken = errors.New("signing address already in registry (active or retired)")
ErrFrontrunValidator = errors.New("post-genesis: signing address is already an active validator")
ErrRotationThrottled = errors.New("rotation throttled: try again later")
ErrRegistryEntryMissing = errors.New("signing address has no active registry entry (corrupted state)")
ErrPaidCallNotDirect = errors.New("a fee is configured: call this directly as a user (maketx call), not from a realm or a maketx run script")
ErrFeeParamOutOfRange = errors.New("configured fee exceeds the maximum representable coin amount")
ErrDisallowedPubKeyType = errors.New("consensus pubkey type is not allowed for validators")
)
var (
valopers *avl.Tree // operator-address -> Valoper
instructions string // markdown instructions for valoper's registration
// signingRegistry maps SigningAddress.String() -> regEntry.
// Permanently retains retired entries to prevent key reuse and
// to support future slashing-attribution by signing address.
signingRegistry = bptree.NewBPTree32()
monikerMaxLengthMiddle = ufmt.Sprintf("%d", MonikerMaxLength-2)
validateMonikerRe = regexp.MustCompile(`^[a-zA-Z0-9][\w -]{0,` + monikerMaxLengthMiddle + `}[a-zA-Z0-9]$`) // 32 characters, including spaces, hyphens or underscores in the middle
)
// regEntry tracks signing-address -> operator with retirement metadata.
// retiredAtHeight == 0 means the entry is currently active for the operator.
type regEntry struct {
OperatorAddress address
RegisteredAtHeight int64
RetiredAtHeight int64
}
// Valoper represents a validator operator profile.
type Valoper struct {
Moniker string // A human-readable name
Description string // A description and details about the valoper
ServerType string // The type of server (cloud/on-prem/data-center)
OperatorAddress address // operator identity, profile key, stable across rotations
SigningPubKey string // current consensus signing pubkey (bech32 gpub1...)
SigningAddress address // = chain.PubKeyAddress(SigningPubKey)
LastRotationHeight int64 // throttle anchor for UpdateSigningKey
KeepRunning bool // operator wants this validator running in the active set
auth *authorizable.Authorizable
}
// AuthOwner returns the operator address that owns this profile's auth
// list. Read-only by construction: it copies out an address rather than
// returning the live *authorizable.Authorizable.
//
// SECURITY: the previous `Auth() *authorizable.Authorizable` was a
// capability leak of the same class this realm's governance authority
// closes by returning a description instead of the live authority.
// `Valoper` is returned BY VALUE from the exported, non-crossing
// GetByAddr, but `auth` is a pointer field, so the copy shared the
// callee's Authorizable. Any realm could therefore obtain a live,
// mutable handle and write through it.
//
// That was a privilege escalation, not merely a wider surface.
// Authorizable's gates read `rlm.Previous().Address()`, so inside a
// hostile realm's frame `Previous()` is whoever called it. When a
// valoper OPERATOR called any function of a hostile realm (faucet,
// airdrop, mint), that realm could reach
// `GetByAddr(operator).Auth().AddToAuthList(...)` and — because
// Previous() was then the operator, the Authorizable's own owner —
// persist itself onto the operator's auth list. From the next
// transaction on it acted alone: UpdateKeepRunning to drain the
// validator, UpdateSigningKey to rotate the consensus key.
//
// The exported wrappers below are NOT equivalent to the raw handle and
// were never the hole: there `cur.Previous()` is the hostile realm
// itself rather than the operator, so the owner check rejects it.
func (v Valoper) AuthOwner() address {
return v.auth.Owner()
}
func AddToAuthList(cur realm, addr address, member address) {
v := GetByAddr(addr)
if err := v.auth.AddToAuthList(0, cur, member); err != nil {
panic(err)
}
}
func DeleteFromAuthList(cur realm, addr address, member address) {
v := GetByAddr(addr)
if err := v.auth.DeleteFromAuthList(0, cur, member); err != nil {
panic(err)
}
}
// Register registers a new valoper. The `addr` parameter is the
// operator address (stable identity, profile key); `pubKey` is the
// consensus signing pubkey, from which the signing address is derived.
//
// Auth shape:
// - Post-genesis: OriginCaller must equal addr (operator-slot squat
// guard). Genesis-mode replay (ChainHeight()==0) bypasses, so
// migration .jsonl txs and historical Register replays succeed.
// - Signing-address uniqueness: derived(pubKey) must not already be
// in signingRegistry, active or retired.
// - Front-running guard: post-genesis, derived(pubKey) must not
// already be an active validator (a fresh registration cannot
// squat on the consensus address of an existing validator).
//
// Why OriginCaller==addr is sufficient for the SQUAT guard (no
// IsUserCall): squatting requires the attacker to satisfy
// OriginCaller==victim, which requires the victim's signing key.
//
// The PAYMENT check is a different matter and does need IsUserCall —
// see assertPaidCallIsDirect. An earlier version of this comment
// claimed the fee was "validated against banker.OriginSend in a way
// that's symmetric to IsUserCall via direct comparison"; there was no
// such comparison, and the fee was bypassable (reported by @D4ryl00).
//
// Auth-list seeding: the profile's Authorizable owner is set to addr
// (NOT OriginCaller). At H>0 the squat guard makes them equal anyway;
// at H==0 the deployer pattern (one signer registers many operators)
// requires owner == addr so each operator can manage their own profile
// post-genesis without needing the deployer's auth.
func Register(cur realm, moniker string, description string, serverType string, addr address, pubKey string) {
// Operator-slot squat guard.
if runtime.ChainHeight() > 0 && unsafe.OriginCaller() != addr {
panic(ErrOperatorSquatGuard)
}
// Fee enforcement (read from sysparams; defaults to 0 until
// governance raises it post-transfer-enablement).
if fee := sysparams.GetValoperRegisterFee(); fee > 0 {
assertPaidCallIsDirect(0, cur)
minFee := minFeeCoin(fee)
sentCoins := unsafe.OriginSend()
if len(sentCoins) != 1 || sentCoins[0].IsLT(minFee) {
panic(ufmt.Sprintf("payment must not be less than %d%s", minFee.Amount, minFee.Denom))
}
}
// Check if the valoper is already registered.
if isValoper(addr) {
panic(ErrValoperExists)
}
// Reject disallowed key types early (else the EndBlocker drops it silently).
assertPubKeyTypeAllowed(pubKey)
// Derive the consensus signing address from the pubkey.
signingAddr, err := chain.PubKeyAddress(pubKey)
if err != nil {
panic(err)
}
// Signing-address uniqueness across all profiles, ever.
if signingRegistry.Has(signingAddr.String()) {
panic(ErrSigningKeyTaken)
}
// Front-running guard: post-genesis, the signing address must
// not already be an active validator.
if runtime.ChainHeight() > 0 && validators.IsValidator(signingAddr) {
panic(ErrFrontrunValidator)
}
v := Valoper{
Moniker: moniker,
Description: description,
ServerType: serverType,
OperatorAddress: addr,
SigningPubKey: pubKey,
SigningAddress: signingAddr,
LastRotationHeight: runtime.ChainHeight(),
KeepRunning: true,
auth: authorizable.New(ownable.NewWithAddress(addr)),
}
if err := v.Validate(); err != nil {
panic(err)
}
// Save the valoper to the set.
valopers.Set(v.OperatorAddress.String(), v)
// Insert into the signing-address registry.
signingRegistry.Set(signingAddr.String(), regEntry{
OperatorAddress: addr,
RegisteredAtHeight: runtime.ChainHeight(),
RetiredAtHeight: 0,
})
// Refresh v0's cache for this operator.
validators.NotifyValoperChanged(cross(cur), addr, v.SigningPubKey, v.SigningAddress, v.KeepRunning)
}
// UpdateMoniker updates an existing valoper's moniker.
func UpdateMoniker(cur realm, addr address, moniker string) {
// Check that the moniker is not empty.
if err := validateMoniker(moniker); err != nil {
panic(err)
}
v := GetByAddr(addr)
// Check that the caller has permissions.
v.auth.AssertPreviousOnAuthList(0, cur)
// Update the moniker.
v.Moniker = moniker
// Save the valoper info.
valopers.Set(addr.String(), v)
}
// UpdateDescription updates an existing valoper's description.
func UpdateDescription(cur realm, addr address, description string) {
// Check that the description is not empty.
if err := validateDescription(description); err != nil {
panic(err)
}
v := GetByAddr(addr)
// Check that the caller has permissions.
v.auth.AssertPreviousOnAuthList(0, cur)
// Update the description.
v.Description = description
// Save the valoper info.
valopers.Set(addr.String(), v)
}
// UpdateKeepRunning updates an existing valoper's active status.
// Calls v0.NotifyValoperChanged because the cache stores KeepRunning.
func UpdateKeepRunning(cur realm, addr address, keepRunning bool) {
v := GetByAddr(addr)
// Check that the caller has permissions.
v.auth.AssertPreviousOnAuthList(0, cur)
// Update status.
v.KeepRunning = keepRunning
// Save the valoper info.
valopers.Set(addr.String(), v)
// Refresh v0's cache (KeepRunning is one of the cached fields).
validators.NotifyValoperChanged(cross(cur), addr, v.SigningPubKey, v.SigningAddress, v.KeepRunning)
}
// UpdateServerType updates an existing valoper's server type.
func UpdateServerType(cur realm, addr address, serverType string) {
// Check that the server type is valid.
if err := validateServerType(serverType); err != nil {
panic(err)
}
v := GetByAddr(addr)
// Check that the caller has permissions.
v.auth.AssertPreviousOnAuthList(0, cur)
// Update server type.
v.ServerType = serverType
// Save the valoper info.
valopers.Set(addr.String(), v)
}
// UpdateSigningKey rotates an operator's consensus signing key.
//
// Auth: caller must be on the operator's auth list (defaults to
// operator at Register time; extendable via AddToAuthList).
//
// Invariants checked at entry:
// - throttle: ChainHeight() - v.LastRotationHeight >=
// rotationPeriodBlocks
// - signingRegistry uniqueness: derived(newPubKey) not in registry
// (active OR retired); permanently blocks key reuse
// - fee: unsafe.OriginSend() >= rotationFee (mirrors Register's
// fee-check pattern)
//
// Effect: profile's SigningPubKey/SigningAddress/LastRotationHeight
// updated; old registry entry marked retired (retiredAtHeight =
// ChainHeight()); new entry inserted into signingRegistry; v0 emits
// remove+add to sysparams via RotateValoperSigningKey; v0 cache
// refreshed via NotifyValoperChanged. Rotation lands in consensus
// at H+2.
//
// Atomicity: Gno tx atomicity rolls back all state if any step
// panics. If v0.RotateValoperSigningKey panics, the registry insert
// and profile mutation revert with it.
func UpdateSigningKey(cur realm, addr address, newPubKey string) {
v := GetByAddr(addr)
// Auth: caller must be on operator's auth list.
v.auth.AssertPreviousOnAuthList(0, cur)
// Throttle: limit one rotation per rotation_period_blocks per
// operator (per profile, not per caller — multi-member auth lists
// can't multiplicative-rotate).
height := runtime.ChainHeight()
if height-v.LastRotationHeight < sysparams.GetValoperRotationPeriodBlocks() {
panic(ErrRotationThrottled)
}
// Fee: enforce only if non-zero (matches Register's pattern;
// rotation_fee defaults to zero pre-transfer-enablement).
if fee := sysparams.GetValoperRotationFee(); fee > 0 {
assertPaidCallIsDirect(0, cur)
minFee := minFeeCoin(fee)
sentCoins := unsafe.OriginSend()
if len(sentCoins) != 1 || sentCoins[0].IsLT(minFee) {
panic(ufmt.Sprintf("payment must not be less than %d%s", minFee.Amount, minFee.Denom))
}
}
// Reject disallowed key types early (else the EndBlocker drops it silently).
assertPubKeyTypeAllowed(newPubKey)
// Derive the new signing address from the new pubkey.
newSigningAddr, err := chain.PubKeyAddress(newPubKey)
if err != nil {
panic(err)
}
// signingRegistry uniqueness: new key must not have ever been
// registered (active or retired).
if signingRegistry.Has(newSigningAddr.String()) {
panic(ErrSigningKeyTaken)
}
// Front-running guard: the derived signing address must not already
// be an active validator. Mirrors the same guard in Register
// (ErrFrontrunValidator). signingRegistry uniqueness above only
// blocks signing addresses that previously went through Register or
// UpdateSigningKey — genesis-seeded validators bypassed both, so
// their signing addresses are absent from signingRegistry. Without
// this check, a valoper could rotate onto such a slot and hijack
// it: v0.RotateValoperSigningKey would overwrite the active entry
// with this operator's claim, and a subsequent govDAO remove-op
// proposal would then delete it.
if validators.IsValidator(newSigningAddr) {
panic(ErrFrontrunValidator)
}
// Remember the previous signing key for the v0 cross-call.
oldPubKey := v.SigningPubKey
oldSigningAddr := v.SigningAddress
// Mark the old registry entry retired. The entry must exist —
// it was inserted at Register time.
rawOld := signingRegistry.Get(oldSigningAddr.String())
if rawOld == nil {
panic(ErrRegistryEntryMissing)
}
oldEntry := rawOld.(regEntry)
oldEntry.RetiredAtHeight = height
signingRegistry.Set(oldSigningAddr.String(), oldEntry)
// Insert the new entry as active.
signingRegistry.Set(newSigningAddr.String(), regEntry{
OperatorAddress: addr,
RegisteredAtHeight: height,
RetiredAtHeight: 0,
})
// Update the profile.
v.SigningPubKey = newPubKey
v.SigningAddress = newSigningAddr
v.LastRotationHeight = height
valopers.Set(addr.String(), v)
// Apply to consensus via v0, then refresh v0's cache view of the
// profile. Order matters only in that both must complete; tx
// atomicity rolls back together on any panic.
validators.RotateValoperSigningKey(cross(cur), addr, oldPubKey, newPubKey)
validators.NotifyValoperChanged(cross(cur), addr, v.SigningPubKey, v.SigningAddress, v.KeepRunning)
}
// GetByAddr fetches the valoper using the operator address, if present.
func GetByAddr(addr address) Valoper {
valoperRaw := valopers.Get(addr.String())
if valoperRaw == nil {
panic(ErrValoperMissing)
}
return valoperRaw.(Valoper)
}
// Render renders the current valoper set.
// "/r/gnops/valopers" lists all valopers, paginated.
// "/r/gnops/valopers:addr" shows the detail for the valoper with the addr.
func Render(fullPath string) string {
req := realmpath.Parse(fullPath)
if req.Path == "" {
return renderHome(fullPath)
} else {
addr := req.Path
if len(addr) < 2 || addr[:2] != "g1" {
return "invalid address " + addr
}
valoperRaw := valopers.Get(addr)
if valoperRaw == nil {
return "unknown address " + addr
}
v := valoperRaw.(Valoper)
return "Valoper's details:\n" + v.Render()
}
}
func renderHome(path string) string {
// if there are no valopers, display instructions
if valopers.Size() == 0 {
return ufmt.Sprintf("%s\n\nNo valopers to display.", instructions)
}
page := pager.NewPager(valopers, 50, false).MustGetPageByPath(path)
output := ""
// if we are on the first page, display instructions
if page.PageNumber == 1 {
output += ufmt.Sprintf("%s\n\n", instructions)
}
for _, item := range page.Items {
v := item.Value.(Valoper)
output += ufmt.Sprintf(" * [%s](/r/gnops/valopers:%s) - [profile](/r/demo/profile:u/%s)\n",
v.Moniker, v.OperatorAddress, v.OperatorAddress)
}
output += "\n"
output += page.Picker(path)
return output
}
// Validate checks if the fields of the Valoper are valid.
func (v *Valoper) Validate() error {
errs := &combinederr.CombinedError{}
errs.Add(validateMoniker(v.Moniker))
errs.Add(validateDescription(v.Description))
errs.Add(validateServerType(v.ServerType))
errs.Add(validateBech32(v.OperatorAddress))
errs.Add(validatePubKey(v.SigningPubKey))
if errs.Size() == 0 {
return nil
}
return errs
}
// Render renders a single valoper with their information.
func (v Valoper) Render() string {
output := ufmt.Sprintf("## %s\n", v.Moniker)
if v.Description != "" {
output += ufmt.Sprintf("%s\n\n", v.Description)
}
output += ufmt.Sprintf("- Operator Address: %s\n", v.OperatorAddress.String())
output += ufmt.Sprintf("- Signing Address: %s\n", v.SigningAddress.String())
output += ufmt.Sprintf("- Signing PubKey: %s\n", v.SigningPubKey)
output += ufmt.Sprintf("- Server Type: %s\n\n", v.ServerType)
output += ufmt.Sprintf("[Profile link](/r/demo/profile:u/%s)\n", v.OperatorAddress)
return output
}
// isValoper checks if the valoper exists.
func isValoper(addr address) bool {
return valopers.Has(addr.String())
}
// validateMoniker checks if the moniker is valid.
func validateMoniker(moniker string) error {
if moniker == "" {
return ErrInvalidMoniker
}
if len(moniker) > MonikerMaxLength {
return ErrInvalidMoniker
}
if !validateMonikerRe.MatchString(moniker) {
return ErrInvalidMoniker
}
return nil
}
// validateDescription checks if the description is valid.
func validateDescription(description string) error {
if description == "" {
return ErrInvalidDescription
}
if len(description) > DescriptionMaxLength {
return ErrInvalidDescription
}
return nil
}
// validateBech32 checks if the value is a valid bech32 address.
func validateBech32(addr address) error {
if !addr.IsValid() {
return ErrInvalidAddress
}
return nil
}
// validatePubKey checks if the public key is valid.
func validatePubKey(pubKey string) error {
if _, _, err := bech32.DecodeNoLimit(pubKey); err != nil {
return err
}
return nil
}
// assertPaidCallIsDirect requires the immediate caller to be a plain EOA,
// and must be paired with every unsafe.OriginSend() amount check in this
// realm. Called only when a fee is actually configured.
//
// unsafe.OriginSend() reports the transaction's declared send ENVELOPE, not
// what this realm received. Only a direct `maketx call` on valopers credits
// the envelope to this realm's address. For a `maketx run` the keeper sets
// pkgAddr := caller (gno.land/pkg/sdk/vm/keeper.go), so the coins move from
// the caller to the caller and never land anywhere at all, while
// OriginSend() still reports the full amount to us. See
// gno.land/adr/pr6062_payable_send_check.md: "MsgRun is exempt: the coins
// are moved from the caller to the caller, so nothing actually moves." So
// the amount check alone verifies intent, never receipt.
//
// Reported by @D4ryl00, with a local-chain reproduction:
// governance sets register_fee to 1000ugnot, an operator runs a script
// calling Register with `-send 1000ugnot`, registration succeeds, valopers
// receives zero, and the operator still holds the coins. No hostile script
// is needed — the envelope is free by construction. Both fees default to 0,
// so nothing was live.
//
// Why IsUserCall and not an address comparison: a run script's realm is
// address-INDISTINGUISHABLE from its user. Inside `main(cur realm)` the
// ephemeral realm's own address IS the caller's EOA address, so every
// address-based guard in this realm accepts a `maketx run` — Register's
// squat guard (OriginCaller == addr) and UpdateSigningKey's auth-list check
// (Previous().Address() on the list) both pass. Only the pkgPath differs,
// and IsUserCall() is the check that reads it. It is therefore the only
// PreviousRealm shape where the envelope is guaranteed to have landed here:
// it excludes intermediate code realms and user-run ephemeral realms alike.
// Same reasoning and same pairing as r/sys/namereg/v0.Register, which reads
// OriginSend for its anti-squatting payment; see the two-guard comment there.
//
// Deliberately inside the `fee > 0` branch rather than at the top of the
// function: while a fee is unset there is no payment to establish receipt
// of, and gating unconditionally would break the operator-authored
// `maketx run` flows that the squat guard is happy to accept. The
// restriction appears exactly when, and only when, money is involved.
//
// KNOWN LIMIT. AddToAuthList takes a plain `member address`, so a REALM
// can sit on an operator's auth list, and once rotation_fee is nonzero
// such a member can no longer drive UpdateSigningKey — it is not a user
// call. An EOA rotation bot is unaffected, which is the shape the
// auth-list docs describe ("HSM-bound or rotation-bot"), so nothing
// documented breaks; a realm-mediated rotation would.
//
// The alternative that would keep realms working is a true receipt check:
// track cumulative fees in realm state and require the realm's own
// balance to have risen by `fee` since the last one. That works for any
// caller shape, but it puts new persisted state and a banker into a
// genesis realm, and lets anyone pre-pay another operator's fee by
// donating to the realm address. Not worth it while both fees are 0 and
// collected fees are unwithdrawable anyway (this realm has no banker, so
// they strand at its address). Revisit if a realm-mediated paid rotation
// is ever actually wanted.
func assertPaidCallIsDirect(_ int, rlm realm) {
// IsCurrent before Previous, as AGENTS.md requires and every other
// (_ int, rlm realm) helper in this tree does (authorizable,
// sys/params/delegate, gov/dao/types, sys/validators/v0/cache).
// Both call sites pass their live cur, so this is defense-in-depth
// against a future caller threading a stale or stashed realm value:
// Previous() reads the prev field verbatim, so on a non-live token
// it answers for the wrong frame.
if !rlm.IsCurrent() {
panic(ErrPaidCallNotDirect)
}
if !rlm.Previous().IsUserCall() {
panic(ErrPaidCallNotDirect)
}
}
// minFeeCoin converts a configured fee (uint64, from sysparams) into the
// ugnot Coin the amount checks compare against.
//
// Coin.Amount is an int64. A fee above MaxInt64 wraps negative, and
// `sentCoins[0].IsLT(minFee)` is then false for every payment — the realm
// reads the fee as configured, runs assertPaidCallIsDirect, and collects
// 1ugnot while reporting "payment must not be less than -1ugnot". Failing
// closed here keeps an unrepresentable fee from opening the paid path
// instead of closing it.
//
// Reachable two ways today, neither requiring malice: governance can set
// any uint64 through the generic r/sys/params factories, and
// valopers/proposal.ProposeNewMinFeeProposalRequest takes an int64 and
// stores uint64(newMinFee), so a negative fee — the obvious way to write
// "disable the fee" — round-trips to 2^64-1. That signature is preserved
// for historical-replay compatibility and is deliberately left alone; the
// bound belongs at the consumption site, which covers both paths.
func minFeeCoin(fee uint64) chain.Coin {
if fee > math.MaxInt64 {
panic(ErrFeeParamOutOfRange)
}
return chain.NewCoin("ugnot", int64(fee))
}
// assertPubKeyTypeAllowed panics if pubKey's type is not in the chain's validator allow-list (empty list accepts any).
func assertPubKeyTypeAllowed(pubKey string) {
allowed := sysparams.GetValsetPubKeyTypes()
if len(allowed) == 0 {
return
}
typeURL, err := pubKeyTypeURL(pubKey)
if err != nil {
panic(err)
}
for _, a := range allowed {
if a == typeURL {
return
}
}
panic(ErrDisallowedPubKeyType)
}
// pubKeyTypeURL returns the amino type URL (e.g. "/tm.PubKeyEd25519") of a bech32 consensus pubkey.
func pubKeyTypeURL(pubKey string) (string, error) {
// gpub exceeds bech32's 90-char cap, so decode without the limit.
_, data5, err := bech32.DecodeNoLimit(pubKey)
if err != nil {
return "", err
}
data, err := bech32.ConvertBits(data5, 5, 8, false)
if err != nil {
return "", err
}
// Type URL is the first amino field: 0x0A <len> <typeURL>.
if len(data) < 2 || data[0] != 0x0A {
return "", errors.New("malformed consensus pubkey: " + pubKey)
}
n := int(data[1])
if n == 0 || len(data) < 2+n {
return "", errors.New("malformed consensus pubkey: " + pubKey)
}
return string(data[2 : 2+n]), nil
}
// validateServerType checks if the server type is valid.
func validateServerType(serverType string) error {
if serverType != ServerTypeCloud &&
serverType != ServerTypeOnPrem &&
serverType != ServerTypeDataCenter {
return ErrInvalidServerType
}
return nil
}
valopers_test.gno
package valopers
import (
"chain"
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/ownable/exts/authorizable/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/ufmt/v0"
)
// Test-local fee constant. Production reads register_fee from sysparams;
// these tests use this value as a reference Coin for OriginSend setup
// and (when needed) seed it via testing.SetSysParamUint64.
var minFee = chain.NewCoin("ugnot", 20*1_000_000)
// cur is a zero-value realm used as a placeholder when forwarding to
// uassert 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
// resetState clears realm-level state and zeroes the valoper sys-params
// so subtests don't leak through valopers (operator slots),
// signingRegistry (signing-address uniqueness), or sys-param values.
func resetState() {
valopers = avl.NewTree()
signingRegistry = bptree.NewBPTree32()
testing.SetSysParamUint64("node", "valoper", "register_fee", 0)
testing.SetSysParamUint64("node", "valoper", "rotation_fee", 0)
testing.SetSysParamInt64("node", "valoper", "rotation_period_blocks", 600)
}
// enableRegisterFee seeds register_fee = minFee.Amount in sysparams
// so the Register fee path fires. Subtests that exercise fee
// rejection or sufficient-fee acceptance call this after resetState.
func enableRegisterFee() {
testing.SetSysParamUint64("node", "valoper", "register_fee", uint64(minFee.Amount))
}
func validValidatorInfo(t *testing.T) struct {
Moniker string
Description string
ServerType string
Address address
PubKey string
} {
t.Helper()
return struct {
Moniker string
Description string
ServerType string
Address address
PubKey string
}{
Moniker: "test-1",
Description: "test-1's description",
ServerType: ServerTypeOnPrem,
Address: address("g1sp8v98h2gadm5jggtzz9w5ksexqn68ympsd68h"),
PubKey: "gpub1pggj7ard9eg82cjtv4u52epjx56nzwgjyg9zqwpdwpd0f9fvqla089ndw5g9hcsufad77fml2vlu73fk8q8sh8v72cza5p",
}
}
func TestValopers_Register(cur realm, t *testing.T) {
t.Run("already a valoper", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
v := Valoper{
Moniker: info.Moniker,
Description: info.Description,
ServerType: info.ServerType,
OperatorAddress: info.Address,
SigningPubKey: info.PubKey,
KeepRunning: true,
}
// Add the valoper directly to the slot.
valopers.Set(v.OperatorAddress.String(), v)
// Send coins.
testing.SetOriginSend(chain.Coins{minFee})
uassert.AbortsWithMessage(t, cur, ErrValoperExists.Error(), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
})
t.Run("no coins deposited", func(cur realm, t *testing.T) {
resetState()
enableRegisterFee()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Send no coins.
testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", 0)})
uassert.AbortsWithMessage(t, cur, ufmt.Sprintf("payment must not be less than %d%s", minFee.Amount, minFee.Denom), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
})
t.Run("insufficient coins amount deposited", func(cur realm, t *testing.T) {
resetState()
enableRegisterFee()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Send invalid coins.
testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", minFee.Amount-1)})
uassert.AbortsWithMessage(t, cur, ufmt.Sprintf("payment must not be less than %d%s", minFee.Amount, minFee.Denom), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
})
t.Run("coin amount deposited is not ugnot", func(cur realm, t *testing.T) {
resetState()
enableRegisterFee()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Send invalid coins.
testing.SetOriginSend(chain.Coins{chain.NewCoin("gnogno", minFee.Amount)})
uassert.AbortsWithMessage(t, cur, "incompatible coin denominations: gnogno, ugnot", func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
})
// A fee above MaxInt64 wraps negative in Coin.Amount, which would make
// the IsLT amount check false for every payment: the realm would read
// the fee as configured and collect 1ugnot. uint64(int64(-1)) is what
// valopers/proposal.ProposeNewMinFeeProposalRequest stores for a
// negative newMinFee, so this is reachable from one governance typo.
t.Run("unrepresentable fee fails closed", func(cur realm, t *testing.T) {
resetState()
testing.SetSysParamUint64("node", "valoper", "register_fee", ^uint64(0))
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Nowhere near the configured fee, and previously accepted.
testing.SetOriginSend(chain.Coins{chain.NewCoin("ugnot", 1)})
uassert.AbortsWithMessage(t, cur, ErrFeeParamOutOfRange.Error(), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.False(t, isValoper(info.Address), "must not register")
})
t.Run("squat guard rejects mismatched OriginCaller", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
// Caller is NOT info.Address: post-genesis squat guard fires.
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("attacker")))
testing.SetOriginSend(chain.Coins{minFee})
uassert.AbortsWithMessage(t, cur, ErrOperatorSquatGuard.Error(), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
})
t.Run("successful registration", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
// Send coins.
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotAborts(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, info.Moniker, valoper.Moniker)
uassert.Equal(t, info.Description, valoper.Description)
uassert.Equal(t, info.ServerType, valoper.ServerType)
uassert.Equal(t, info.Address, valoper.OperatorAddress)
uassert.Equal(t, info.PubKey, valoper.SigningPubKey)
uassert.Equal(t, true, valoper.KeepRunning)
// SigningAddress is derived from the pubkey and present.
derived, err := chain.PubKeyAddress(info.PubKey)
uassert.NoError(t, err)
uassert.Equal(t, derived, valoper.SigningAddress)
// signingRegistry tracks the active entry.
uassert.True(t, signingRegistry.Has(derived.String()), "signingRegistry must contain the active entry")
})
})
t.Run("signing-key reuse rejected", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
// First registration succeeds.
uassert.NotAborts(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
// Second attempt with a different operator addr but the same
// pubkey must fail signingRegistry uniqueness.
other := testutils.TestAddress("other-op")
testing.SetRealm(testing.NewUserRealm(other))
testing.SetOriginSend(chain.Coins{minFee})
uassert.AbortsWithMessage(t, cur, ErrSigningKeyTaken.Error(), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, other, info.PubKey)
})
})
t.Run("front-running guard rejects post-genesis if signing addr already validates", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
// Seed v0's valset:current with the very signing address that
// `info.PubKey` derives to (g1sp8v98...). Any post-genesis
// Register attempting the same pubkey now trips
// `ChainHeight()>0 && validators.IsValidator(signingAddr)`.
testing.SetSysParamStrings("node", "valset", "current", []string{info.PubKey + ":1"})
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.AbortsWithMessage(t, cur, ErrFrontrunValidator.Error(), func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
// Cleanup: clear the seeded valset to avoid leaking into
// later subtests if the package state isn't reset between
// them in this test runner mode.
testing.SetSysParamStrings("node", "valset", "current", []string{})
})
}
func TestValopers_Register_AuthOwnerIsOperatorAddress(cur realm, t *testing.T) {
// Pin: the Authorizable owner is bound to the OperatorAddress
// (the addr arg), NOT to OriginCaller. This matters in the
// genesis-mode deployer pattern: one signer (e.g., the hardfork
// ceremony deployer) registers profiles for many operators.
// Each operator must end up on their own profile's auth list
// so they can manage it post-genesis without depending on the
// deployer.
t.Run("genesis deployer pattern: operator (not deployer) is owner", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
deployer := testutils.TestAddress("deployer")
// Genesis mode: ChainHeight()==0 bypasses the squat guard so
// deployer (OriginCaller) can register a profile for a
// different operator addr.
testing.SetHeight(0)
testing.SetRealm(testing.NewUserRealm(deployer))
testing.SetOriginCaller(deployer)
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
// Auth owner must be the operator addr (info.Address), NOT
// the deployer.
//
// Asserted through the exported AuthOwner() accessor, not the
// private v.auth: AuthOwner is the API that replaced the removed
// Auth() capability leak, so it is what external readers see. A
// second assertion against the underlying Authorizable pins that
// the accessor actually reports the auth list's owner rather
// than echoing OperatorAddress, which is what a plausible
// "simplification" of AuthOwner would do.
v := GetByAddr(info.Address)
uassert.Equal(t, info.Address.String(), v.AuthOwner().String(),
"auth owner must equal OperatorAddress, not OriginCaller")
uassert.Equal(t, v.auth.Owner().String(), v.AuthOwner().String(),
"AuthOwner must report the Authorizable's owner")
// Operator can manage their own profile post-genesis.
testing.SetHeight(100)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginCaller(info.Address)
uassert.NotPanics(t, cur, func() {
UpdateMoniker(cross(cur), info.Address, "operator-renamed")
})
uassert.Equal(t, "operator-renamed", GetByAddr(info.Address).Moniker)
// Deployer cannot manage the operator's profile (not on the
// auth list).
testing.SetRealm(testing.NewUserRealm(deployer))
testing.SetOriginCaller(deployer)
uassert.AbortsContains(t, cur, "caller is not in authorized list", func() {
UpdateMoniker(cross(cur), info.Address, "deployer-attempt")
})
})
t.Run("post-genesis self-Register: operator is owner", func(cur realm, t *testing.T) {
// At H>0 the squat guard forces OriginCaller==addr, so owner
// would be the same regardless. This subtest pins that the
// post-genesis behavior is unchanged.
resetState()
info := validValidatorInfo(t)
testing.SetHeight(100)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginCaller(info.Address)
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
v := GetByAddr(info.Address)
uassert.Equal(t, info.Address.String(), v.AuthOwner().String())
})
}
func TestValopers_UpdateAuthMembers(cur realm, t *testing.T) {
test2Address := testutils.TestAddress("test2")
t.Run("unauthorized member adds member", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
// Add the valoper.
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
// A different caller (not on the auth list) tries to add a member.
testing.SetRealm(testing.NewUserRealm(test2Address))
uassert.AbortsWithMessage(t, cur, authorizable.ErrNotSuperuser.Error(), func() {
AddToAuthList(cross(cur), info.Address, test2Address)
})
})
t.Run("unauthorized member deletes member", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.NotPanics(t, cur, func() {
AddToAuthList(cross(cur), info.Address, test2Address)
})
// A different caller tries to delete a member.
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("attacker")))
uassert.AbortsWithMessage(t, cur, authorizable.ErrNotSuperuser.Error(), func() {
DeleteFromAuthList(cross(cur), info.Address, test2Address)
})
})
t.Run("authorized member adds member", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.NotPanics(t, cur, func() {
AddToAuthList(cross(cur), info.Address, test2Address)
})
testing.SetRealm(testing.NewUserRealm(test2Address))
newMoniker := "new moniker"
uassert.NotPanics(t, cur, func() {
UpdateMoniker(cross(cur), info.Address, newMoniker)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, newMoniker, valoper.Moniker)
})
})
}
func TestValopers_UpdateMoniker(cur realm, t *testing.T) {
test2Address := testutils.TestAddress("test2")
t.Run("non-existing valoper", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
uassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {
UpdateMoniker(cross(cur), info.Address, "new moniker")
})
})
t.Run("invalid caller", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
// Change the caller to someone not on the auth list.
testing.SetRealm(testing.NewUserRealm(test2Address))
uassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {
UpdateMoniker(cross(cur), info.Address, "new moniker")
})
})
t.Run("invalid moniker", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
invalidMonikers := []string{
"", // Empty
" ", // Whitespace
"a", // Too short
"a very long moniker that is longer than 32 characters", // Too long
"!@#$%^&*()+{}|:<>?/.,;'", // Invalid characters
" space in front",
"space in back ",
}
for _, invalidMoniker := range invalidMonikers {
uassert.AbortsWithMessage(t, cur, ErrInvalidMoniker.Error(), func() {
UpdateMoniker(cross(cur), info.Address, invalidMoniker)
})
}
})
t.Run("too long moniker", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.AbortsWithMessage(t, cur, ErrInvalidMoniker.Error(), func() {
UpdateMoniker(cross(cur), info.Address, strings.Repeat("a", MonikerMaxLength+1))
})
})
t.Run("successful update", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
newMoniker := "new moniker"
uassert.NotPanics(t, cur, func() {
UpdateMoniker(cross(cur), info.Address, newMoniker)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, newMoniker, valoper.Moniker)
})
})
}
func TestValopers_UpdateDescription(cur realm, t *testing.T) {
test2Address := testutils.TestAddress("test2")
t.Run("non-existing valoper", func(cur realm, t *testing.T) {
resetState()
uassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {
UpdateDescription(cross(cur), validValidatorInfo(t).Address, "new description")
})
})
t.Run("invalid caller", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
testing.SetRealm(testing.NewUserRealm(test2Address))
uassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {
UpdateDescription(cross(cur), info.Address, "new description")
})
})
t.Run("empty description", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.AbortsWithMessage(t, cur, ErrInvalidDescription.Error(), func() {
UpdateDescription(cross(cur), info.Address, "")
})
})
t.Run("too long description", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.AbortsWithMessage(t, cur, ErrInvalidDescription.Error(), func() {
UpdateDescription(cross(cur), info.Address, strings.Repeat("a", DescriptionMaxLength+1))
})
})
t.Run("successful update", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
newDescription := "new description"
uassert.NotPanics(t, cur, func() {
UpdateDescription(cross(cur), info.Address, newDescription)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, newDescription, valoper.Description)
})
})
}
func TestValopers_UpdateKeepRunning(cur realm, t *testing.T) {
test2Address := testutils.TestAddress("test2")
t.Run("non-existing valoper", func(cur realm, t *testing.T) {
resetState()
uassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {
UpdateKeepRunning(cross(cur), validValidatorInfo(t).Address, false)
})
})
t.Run("invalid caller", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
testing.SetRealm(testing.NewUserRealm(test2Address))
uassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {
UpdateKeepRunning(cross(cur), info.Address, false)
})
})
t.Run("successful update", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.NotPanics(t, cur, func() {
UpdateKeepRunning(cross(cur), info.Address, false)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, false, valoper.KeepRunning)
})
})
}
func TestValopers_UpdateServerType(cur realm, t *testing.T) {
test2Address := testutils.TestAddress("test2")
t.Run("non-existing valoper", func(cur realm, t *testing.T) {
resetState()
uassert.AbortsWithMessage(t, cur, ErrValoperMissing.Error(), func() {
UpdateServerType(cross(cur), validValidatorInfo(t).Address, ServerTypeCloud)
})
})
t.Run("invalid caller", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
testing.SetRealm(testing.NewUserRealm(test2Address))
uassert.AbortsWithMessage(t, cur, authorizable.ErrNotInAuthList.Error(), func() {
UpdateServerType(cross(cur), info.Address, ServerTypeCloud)
})
})
t.Run("invalid server type", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
invalidServerTypes := []string{
"",
"invalid",
"Cloud", // case sensitive
"ON-PREM", // case sensitive
"datacenter", // wrong format
}
for _, invalidType := range invalidServerTypes {
uassert.AbortsWithMessage(t, cur, ErrInvalidServerType.Error(), func() {
UpdateServerType(cross(cur), info.Address, invalidType)
})
}
})
t.Run("successful update", func(cur realm, t *testing.T) {
resetState()
info := validValidatorInfo(t)
testing.SetRealm(testing.NewUserRealm(info.Address))
testing.SetOriginSend(chain.Coins{minFee})
uassert.NotPanics(t, cur, func() {
Register(cross(cur), info.Moniker, info.Description, info.ServerType, info.Address, info.PubKey)
})
uassert.NotPanics(t, cur, func() {
UpdateServerType(cross(cur), info.Address, ServerTypeCloud)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, ServerTypeCloud, valoper.ServerType)
})
uassert.NotPanics(t, cur, func() {
UpdateServerType(cross(cur), info.Address, ServerTypeDataCenter)
})
uassert.NotPanics(t, cur, func() {
valoper := GetByAddr(info.Address)
uassert.Equal(t, ServerTypeDataCenter, valoper.ServerType)
})
})
}