Playground
doc.gno
// Package validators implements the on-chain validator set management through Proof of Contribution. // The Realm exposes only a public executor for govdao proposals, that can suggest validator set changes. package validators
gnomod.toml
module = "gno.land/r/sys/validators/v2" gno = "0.9" [addpkg] creator = "g1r929wt2qplfawe4lvqv9zuwfdcz4vxdun7qh8l"
gnosdk.gno
package validators
import (
"math"
"gno.land/p/sys/validators/v0"
)
// GetChanges returns the validator changes stored on the realm,
// for blocks in the [from, to] range (inclusive on both ends).
// If to >= math.MaxInt64, it is clamped to math.MaxInt64-1 to avoid overflow.
// Panics if from > to (after clamping).
// This function is intended to be called by gno.land through the GnoSDK.
func GetChanges(from, to int64) []validators.Validator {
if to > math.MaxInt64-1 {
to = math.MaxInt64 - 1
}
if to < from {
panic("invalid range: from must be <= to")
}
valsetChanges := make([]validators.Validator, 0)
// Gather the changes in the [from, to] block range.
// AVL Iterate uses an exclusive end, so we pass to+1.
changes.Iterate(getBlockID(from), getBlockID(to+1), func(_ string, value any) bool {
chs := value.([]change)
for _, ch := range chs {
valsetChanges = append(valsetChanges, ch.validator)
}
return false
})
return valsetChanges
}
init.gno
package validators
import (
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/poa/v0"
)
func init() {
// The default valset protocol is PoA
vp = poa.NewPoA()
// No changes to apply initially
changes = bptree.NewBPTree32()
}
poc.gno
package validators
import (
"strings"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/sys/validators/v0"
"gno.land/r/gov/dao"
)
// NewPropRequest creates a new proposal request that wraps a changes closure
// proposal. This wrapper is required to ensure the GovDAO Realm actually
// executed the callback.
func NewPropRequest(cur realm, changesFn func() []validators.Validator, title, description string) dao.ProposalRequest {
if changesFn == nil {
panic("no set changes proposed")
}
title = strings.TrimSpace(title)
if title == "" {
panic("proposal title is empty")
}
// Get the list of validators now to make sure the list
// doesn't change during the lifetime of the proposal
changes := changesFn()
// Limit the number of validators to keep the description within a limit
// that makes sense because there is not pagination of validators
if len(changes) > 40 {
panic("max number of allowed validators per proposal is 40")
} else if len(changes) == 0 {
panic("proposal requires at least one validator")
}
// List the validator addresses and the action to be taken for each one
var desc strings.Builder
desc.WriteString(description)
if len(description) > 0 {
desc.WriteString("\n\n")
}
desc.WriteString("## Validator Updates\n")
for _, change := range changes {
if change.VotingPower == 0 {
desc.WriteString(ufmt.Sprintf("- %s: remove\n", change.Address))
} else {
desc.WriteString(ufmt.Sprintf("- %s: add\n", change.Address))
}
}
callback := func(cur realm) error {
for _, change := range changes {
if change.VotingPower == 0 {
// This change request is to remove the validator
removeValidator(change.Address)
continue
}
// This change request is to add the validator
addValidator(change)
}
return nil
}
e := dao.NewSimpleExecutor(0, cur, callback, "")
return dao.NewProposalRequest(title, desc.String(), e)
}
// IsValidator returns a flag indicating if the given bech32 address
// is part of the validator set
func IsValidator(addr address) bool {
return vp.IsValidator(addr)
}
// GetValidator returns the typed validator
func GetValidator(addr address) validators.Validator {
if validator, err := vp.GetValidator(addr); err == nil {
return validator
}
panic("validator not found")
}
// GetValidators returns the typed validator set
func GetValidators() []validators.Validator {
return vp.GetValidators()
}
validators.gno
package validators
import (
"chain"
"chain/runtime"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/sys/validators/v0"
)
var (
vp validators.ValsetProtocol // p is the underlying validator set protocol
changes *bptree.BPTree // changes holds any valset changes; seqid(block number) -> []change
)
// change represents a single valset change, tied to a specific block number
type change struct {
blockNum int64 // the block number associated with the valset change
validator validators.Validator // the validator update
}
// addValidator adds a new validator to the validator set.
// If the validator is already present, the method errors out
func addValidator(validator validators.Validator) {
val, err := vp.AddValidator(validator.Address, validator.PubKey, validator.VotingPower)
if err != nil {
panic(err)
}
// Validator added, note the change
ch := change{
blockNum: runtime.ChainHeight(),
validator: val,
}
saveChange(ch)
// Emit the validator set change
chain.Emit(validators.ValidatorAddedEvent)
}
// removeValidator removes the given validator from the set.
// If the validator is not present in the set, the method errors out
func removeValidator(address_XXX address) {
val, err := vp.RemoveValidator(address_XXX)
if err != nil {
panic(err)
}
// Validator removed, note the change
ch := change{
blockNum: runtime.ChainHeight(),
validator: validators.Validator{
Address: val.Address,
PubKey: val.PubKey,
VotingPower: 0, // nullified the voting power indicates removal
},
}
saveChange(ch)
// Emit the validator set change
chain.Emit(validators.ValidatorRemovedEvent)
}
// saveChange saves the valset change
func saveChange(ch change) {
id := getBlockID(ch.blockNum)
setRaw := changes.Get(id)
if setRaw == nil {
changes.Set(id, []change{ch})
return
}
// Save the change
set := setRaw.([]change)
set = append(set, ch)
changes.Set(id, set)
}
// getBlockID converts the block number to a sequential ID
func getBlockID(blockNum int64) string {
return seqid.ID(uint64(blockNum)).String()
}
func Render(_ string) string {
var (
size = changes.Size()
maxDisplay = 10
)
if size == 0 {
return "No valset changes to apply."
}
output := "Valset changes:\n"
changes.ReverseIterateByOffset(0, maxDisplay, func(_ string, value any) bool {
chs := value.([]change)
for _, ch := range chs {
output += ufmt.Sprintf(
"- #%d: %s (%d)\n",
ch.blockNum,
ch.validator.Address.String(),
ch.validator.VotingPower,
)
}
return false
})
return output
}
validators_test.gno
package validators
import (
"chain/runtime"
"math"
"strings"
"testing"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/poa/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/sys/validators/v0"
)
// 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
// generateTestValidators generates a dummy validator set
func generateTestValidators(count int) []validators.Validator {
vals := make([]validators.Validator, 0, count)
for i := 0; i < count; i++ {
val := validators.Validator{
Address: testutils.TestAddress(ufmt.Sprintf("%d", i)),
PubKey: "public-key",
VotingPower: 10,
}
vals = append(vals, val)
}
return vals
}
func TestValidators_AddRemove(t *testing.T) {
// Clear any changes
changes = bptree.NewBPTree32()
var (
vals = generateTestValidators(100)
initialHeight = int64(123)
)
// Add in the validators
for _, val := range vals {
addValidator(val)
// Make sure the validator is added
uassert.True(t, vp.IsValidator(val.Address))
testing.SkipHeights(1)
}
for i := initialHeight; i < initialHeight+int64(len(vals)); i++ {
// Make sure the changes are saved
chs := GetChanges(i, initialHeight+int64(len(vals)))
// We use the funky index calculation to make sure
// changes are properly handled for each block span
uassert.Equal(t, initialHeight+int64(len(vals))-i, int64(len(chs)))
for index, val := range vals[i-initialHeight:] {
// Make sure the changes are equal to the additions
ch := chs[index]
uassert.Equal(t, val.Address, ch.Address)
uassert.Equal(t, val.PubKey, ch.PubKey)
uassert.Equal(t, val.VotingPower, ch.VotingPower)
}
}
// Save the beginning height for the removal
initialRemoveHeight := runtime.ChainHeight()
// Clear any changes
changes = bptree.NewBPTree32()
// Remove the validators
for _, val := range vals {
removeValidator(val.Address)
// Make sure the validator is removed
uassert.False(t, vp.IsValidator(val.Address))
testing.SkipHeights(1)
}
for i := initialRemoveHeight; i < initialRemoveHeight+int64(len(vals)); i++ {
// Make sure the changes are saved
chs := GetChanges(i, initialRemoveHeight+int64(len(vals)))
// We use the funky index calculation to make sure
// changes are properly handled for each block span
uassert.Equal(t, initialRemoveHeight+int64(len(vals))-i, int64(len(chs)))
for index, val := range vals[i-initialRemoveHeight:] {
// Make sure the changes are equal to the additions
ch := chs[index]
uassert.Equal(t, val.Address, ch.Address)
uassert.Equal(t, val.PubKey, ch.PubKey)
uassert.Equal(t, uint64(0), ch.VotingPower)
}
}
}
// TestGetChanges_BoundedRange verifies that GetChanges(from, to) correctly
// returns only changes within the [from, to] block range.
func TestGetChanges_BoundedRange(t *testing.T) {
changes = bptree.NewBPTree32()
vp = poa.NewPoA()
vals := generateTestValidators(3)
// Store additions at block h1
h1 := runtime.ChainHeight()
for _, val := range vals {
addValidator(val)
}
testing.SkipHeights(1)
// Store removals at block h2
h2 := runtime.ChainHeight()
for _, val := range vals {
removeValidator(val.Address)
}
testing.SkipHeights(1)
// Query spanning both blocks returns all changes
all := GetChanges(h1, h2)
uassert.Equal(t, 6, len(all))
// Query for h1 only returns additions
atH1 := GetChanges(h1, h1)
uassert.Equal(t, 3, len(atH1))
for i, ch := range atH1 {
uassert.Equal(t, vals[i].Address, ch.Address)
uassert.True(t, ch.VotingPower > 0)
}
// Query for h2 only returns removals
atH2 := GetChanges(h2, h2)
uassert.Equal(t, 3, len(atH2))
for i, ch := range atH2 {
uassert.Equal(t, vals[i].Address, ch.Address)
uassert.Equal(t, uint64(0), ch.VotingPower)
}
// Query beyond stored range returns empty
uassert.Equal(t, 0, len(GetChanges(h2+1, h2+1)))
}
// TestRender_ShowsNewestWhenOverLimit verifies that Render displays the newest
// maxDisplay buckets when there are more change buckets than maxDisplay.
func TestRender_ShowsNewestWhenOverLimit(t *testing.T) {
changes = bptree.NewBPTree32()
vp = poa.NewPoA()
const total = 13
const maxDisplay = 10
vals := generateTestValidators(total)
base := runtime.ChainHeight()
for i := 0; i < total; i++ {
h := base + int64(i)
changes.Set(getBlockID(h), []change{
{blockNum: h, validator: vals[i]},
})
}
output := Render("")
// Newest maxDisplay buckets must appear.
for i := total - maxDisplay; i < total; i++ {
h := base + int64(i)
uassert.True(t, strings.Contains(output, ufmt.Sprintf("#%d:", h)),
ufmt.Sprintf("expected block #%d in output", h))
}
// Oldest (total - maxDisplay) buckets must NOT appear.
for i := 0; i < total-maxDisplay; i++ {
h := base + int64(i)
uassert.False(t, strings.Contains(output, ufmt.Sprintf("#%d:", h)),
ufmt.Sprintf("block #%d should be absent from output", h))
}
}
// TestRender_ShowsAllWhenUnderLimit verifies that all buckets are displayed when
// there are fewer than maxDisplay, and that no panic occurs from a negative offset.
func TestRender_ShowsAllWhenUnderLimit(t *testing.T) {
changes = bptree.NewBPTree32()
vp = poa.NewPoA()
const total = 5 // less than maxDisplay=10
vals := generateTestValidators(total)
base := runtime.ChainHeight()
for i := 0; i < total; i++ {
h := base + int64(i)
changes.Set(getBlockID(h), []change{
{blockNum: h, validator: vals[i]},
})
}
output := Render("")
for i := 0; i < total; i++ {
h := base + int64(i)
uassert.True(t, strings.Contains(output, ufmt.Sprintf("#%d:", h)),
ufmt.Sprintf("expected block #%d in output", h))
}
}
func TestGetChanges_PanicsOnInvalidRange(cur realm, t *testing.T) {
uassert.PanicsWithMessage(t, cur, "invalid range: from must be <= to", func() {
GetChanges(10, 5)
})
}
func TestGetChanges_ClampsMaxInt64(t *testing.T) {
changes = bptree.NewBPTree32()
vals := generateTestValidators(1)
// Simulate a validator change at block math.MaxInt64-1 (the boundary value).
changes.Set(getBlockID(math.MaxInt64-1), []change{
{blockNum: math.MaxInt64 - 1, validator: vals[0]},
})
// Passing math.MaxInt64 as "to" means "get all updates from here onwards".
// The clamp (to = MaxInt64-1) must still include the boundary block.
result := GetChanges(math.MaxInt64-1, math.MaxInt64)
uassert.Equal(t, 1, len(result))
uassert.Equal(t, vals[0].Address, result[0].Address)
}