Playground
doc.gno
// Package groups provides Groups containing a base address set plus named // Roles, each with their own member set and metadata. // // A Group is the top-level container — one per DAO, one per permissions // instance, etc. A Role is a named subset within a Group with arbitrary // per-role metadata. // // The API separates three concerns explicitly, so each call site picks the // right semantic: // // - base-only operations: Add, Remove, Has, Size, Iterate; // - role registry operations: AddRole, GetRole, HasRole, RemoveRole, // RoleCount, IterateRoles; // - aggregated operations across base + all roles: HasAny, TotalSize, // IterateAll, RolesContaining, RemoveFromAll. // // # Security model // // A Group, and the *Role values it hands out, are meant to be allocated and // held by the consuming realm. Three rules apply at realm boundaries: // // 1. Do not ACCEPT a *Group or *Role from an external/untrusted caller — // subsequent mutations would route to the allocating (attacker) // realm's authority, and a poisoned Group could cause DoS or // unexpected state. // // 2. Do not RETURN a *Group or *Role from any method or function callable // by untrusted realms. Return *ReadonlyGroup or *ReadonlyRole instead. // Exposing a mutable handle is exactly as dangerous as accepting one. // // 3. Do not TRUST a *ReadonlyGroup or *ReadonlyRole received from an // untrusted caller. A readonly view is a live handle over its creator's // data, not a snapshot: the sender controls the contents and can mutate // them between reads. Base authorization and accounting decisions only // on views derived from a Group you allocated yourself. // // The Readonly() views are the only safe handles to cross a realm boundary — // safe to hand out, per rule 3 not blindly safe to consume. // // # Metadata: do not store mutable pointers // // Each Role has a free-form "meta any" slot. Meta() returns the stored // value as-is, so a pointer stored in meta can be retrieved by an untrusted // reader holding a Readonly() view. A direct field write through that // pointer is still blocked by the realm-ownership // gate, but invoking a MUTATOR METHOD on it (or passing it into a function // that mutates by argument) runs under whatever realm allocated it (borrow // rule #2) and commits the write. This includes common /p/ types such as // *addrset.Set and *avl.Tree — they are mutable pointers, not "just data". // Therefore store only: // // - value types (ints, strings, value structs/slices with NO internal // pointer reaching a mutator-bearing type), or // - a wrapper whose only exported methods are read-only and which holds no // externally-mutable pointer. // // # Readonly views // // Group and Role each expose a Readonly() method returning a typed // read-only view (ReadonlyGroup, ReadonlyRole; role member sets surface as // *addrset.ReadonlySet). The views are concrete structs with unexported // fields and only read-side exported methods, so cross-package callers // cannot mutate through them. package groups
gnomod.toml
module = "gno.land/p/nt/groups/v0" gno = "0.9" [addpkg] creator = "g15ge0ae9077eh40erwrn2eq0xw6wupwqthpv34l"
group.gno
package groups
import (
"errors"
"gno.land/p/moul/addrset/v0"
"gno.land/p/nt/bptree/v0"
)
var (
ErrRoleExists = errors.New("role already exists")
ErrEmptyName = errors.New("role name is required")
)
// Group is a container with a base address set plus a registry of named
// Roles. The zero value is not usable; construct with NewGroup.
//
// # Security
//
// A Group, and the *Role values it hands out, are meant to be allocated and
// held by the consuming realm. Three rules apply at realm boundaries:
//
// 1. Do not ACCEPT a *Group or *Role from an external/untrusted caller —
// subsequent mutations would route to the allocating (attacker)
// realm's authority, and a poisoned Group could cause DoS or
// unexpected state.
//
// 2. Do not RETURN a *Group or *Role from any method or function callable
// by untrusted realms. Return *ReadonlyGroup or *ReadonlyRole instead.
//
// 3. Do not TRUST a *ReadonlyGroup or *ReadonlyRole received from an
// untrusted caller — it is a live handle over the sender's data, not a
// snapshot; the contents are attacker-controlled and can change between
// reads.
//
// Both directions matter: exposing a *Group to attacker code is as
// dangerous as accepting one. The Readonly() views are the only safe
// handles to cross a realm boundary.
type Group struct {
base *addrset.Set
roles *bptree.BPTree // name -> *Role
}
// NewGroup constructs an empty group.
func NewGroup() *Group {
return &Group{
base: &addrset.Set{},
roles: bptree.NewBPTree32(),
}
}
// --- Base set ---
//
// All base methods operate ONLY on the base set; roles are never consulted.
// Use the aggregated forms (HasAny, TotalSize, IterateAll, RemoveFromAll)
// for views across base + roles.
// Add inserts addr into the base set. Returns true if newly added.
func (g *Group) Add(addr address) (added bool) {
return g.base.Add(addr)
}
// Remove deletes addr from the base set. Returns true if it was present.
func (g *Group) Remove(addr address) (removed bool) {
return g.base.Remove(addr)
}
// Has reports whether addr is in the base set. It does NOT consult roles;
// use HasAny for an aggregated check.
func (g *Group) Has(addr address) bool {
return g.base.Has(addr)
}
// Size returns the number of addresses in the base set only.
func (g *Group) Size() int {
return g.base.Size()
}
// Iterate walks the base set (only) in sorted order, starting at offset.
// fn returns true to stop; Iterate returns true if stopped early.
func (g *Group) Iterate(offset, count int, fn func(addr address) bool) (stopped bool) {
g.base.IterateByOffset(offset, count, func(a address) bool {
stopped = fn(a)
return stopped
})
return stopped
}
// --- Role registry ---
// AddRole registers a new empty role. Returns ErrEmptyName if name is
// empty, ErrRoleExists if a role of that name already exists.
func (g *Group) AddRole(name string) (*Role, error) {
if name == "" {
return nil, ErrEmptyName
}
if g.roles.Has(name) {
return nil, ErrRoleExists
}
r := newRole(name)
g.roles.Set(name, r)
return r, nil
}
// GetRole returns the mutable role if it exists.
//
// SECURITY: the returned *Role exposes mutators (Members().Add/Remove,
// SetMeta). Do not pass it to untrusted callers — use GetRole on a
// *ReadonlyGroup for cross-realm exposure.
func (g *Group) GetRole(name string) (r *Role, found bool) {
r, found = g.roles.Get(name).(*Role)
return r, found
}
// HasRole reports whether a role with the given name exists.
func (g *Group) HasRole(name string) bool {
return g.roles.Has(name)
}
// RemoveRole removes the named role and its membership records. Members of
// the removed role are NOT removed from the base set or from any other
// role; only this role's own data is discarded. Returns false if no such
// role exists.
func (g *Group) RemoveRole(name string) (removed bool) {
_, removed = g.roles.Remove(name)
return removed
}
// RoleCount returns the number of registered roles.
func (g *Group) RoleCount() int {
return g.roles.Size()
}
// IterateRoles walks roles in lexicographic name order, starting at offset
// and visiting up to count roles. The callback receives a *ReadonlyRole —
// deliberately not a *Role, so that plumbing an untrusted callback into the
// iteration cannot escalate into role mutation under this realm's authority.
// To mutate, capture names during iteration and revisit via GetRole from a
// trusted context after iteration returns; registry mutation (AddRole,
// RemoveRole) mid-iteration can panic and abort the transaction. fn returns
// true to stop; IterateRoles returns true if stopped early.
func (g *Group) IterateRoles(offset, count int, fn func(*ReadonlyRole) bool) (stopped bool) {
return g.roles.IterateByOffset(offset, count, func(_ string, value any) bool {
return fn(value.(*Role).Readonly())
})
}
// --- Aggregations across base + all roles ---
// HasAny reports whether addr is in the base set OR in any role.
func (g *Group) HasAny(addr address) bool {
if g.base.Has(addr) {
return true
}
found := false
g.roles.IterateByOffset(0, g.roles.Size(), func(_ string, value any) bool {
if value.(*Role).members.Has(addr) {
found = true
return true // stop
}
return false
})
return found
}
// TotalSize returns the count of distinct addresses across the base set and
// all roles, deduplicated. A caller may place the same address in base and
// in multiple roles; TotalSize counts it once.
//
// Implementation note: dedup tracks seen addresses in an internal addrset,
// costing O(N) memory in the total membership.
func (g *Group) TotalSize() int {
n := 0
g.visitDistinct(func(address) bool {
n++
return false
})
return n
}
// IterateAll walks every distinct address across base + all roles,
// deduplicated. Order: base first (in addrset order), then roles in name
// order, skipping addresses already yielded. offset and count apply to the
// deduplicated output, not the pre-dedup items; a negative offset counts as
// zero. fn returns true to stop; IterateAll returns true if stopped early.
//
// The walk is live: do not mutate the group (base set, member sets, or the
// role registry) from within fn — registry mutation mid-iteration can panic
// and abort the transaction. Collect addresses first, mutate after
// IterateAll returns.
//
// Implementation note: dedup tracks seen addresses in an internal addrset
// (O(N) memory in the addresses scanned); scanning stops as soon as the
// requested window has been served. For paginating a large Group without
// dedup, use Iterate (base only) or IterateRoles.
func (g *Group) IterateAll(offset, count int, fn func(addr address) bool) (stopped bool) {
if count <= 0 {
return false
}
if offset < 0 {
offset = 0
}
seen := 0
g.visitDistinct(func(a address) bool {
if seen < offset {
seen++
return false
}
if fn(a) {
stopped = true
return true
}
seen++
return seen-offset >= count
})
return stopped
}
// visitDistinct walks the base set then every role (in name order), calling
// visit once per distinct address the first time it is seen. visit returns
// true to stop the walk early.
func (g *Group) visitDistinct(visit func(addr address) bool) {
seen := &addrset.Set{}
done := false
record := func(a address) bool {
if !seen.Add(a) { // Add returns false when already seen
return false
}
done = visit(a)
return done
}
g.base.IterateByOffset(0, g.base.Size(), record)
if done {
return
}
g.roles.IterateByOffset(0, g.roles.Size(), func(_ string, value any) bool {
r := value.(*Role)
r.members.IterateByOffset(0, r.members.Size(), record)
return done
})
}
// RolesContaining returns the names of all roles containing addr, in
// lexicographic name order. The base set is not consulted (base membership
// is not a "role"). Returns nil if addr is in no roles.
func (g *Group) RolesContaining(addr address) []string {
var names []string
g.roles.IterateByOffset(0, g.roles.Size(), func(name string, value any) bool {
if value.(*Role).members.Has(addr) {
names = append(names, name)
}
return false
})
return names
}
// RemoveFromAll removes addr from the base set and from every role. Returns
// true if it was removed from at least one location.
func (g *Group) RemoveFromAll(addr address) (removed bool) {
if g.base.Remove(addr) {
removed = true
}
g.roles.IterateByOffset(0, g.roles.Size(), func(_ string, value any) bool {
if value.(*Role).members.Remove(addr) {
removed = true
}
return false
})
return removed
}
// Readonly returns a read-only view of the group.
func (g *Group) Readonly() *ReadonlyGroup {
return &ReadonlyGroup{group: g}
}
groups_test.gno
package groups
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
var (
addr0 = address("addr0")
addr1 = address("addr1")
addr2 = address("addr2")
addr3 = address("addr3")
addr4 = address("addr4")
addr5 = address("addr5")
addr6 = address("addr6")
)
// newTestGroup builds the fixture used across tests:
//
// base: addr0, addr1, addr3, addr5
// admins: addr2, addr3, addr5
// mods: addr1, addr4, addr5
//
// Overlap topology: addr0 base-only, addr2 admins-only, addr4 mods-only,
// addr1 base+mods, addr3 base+admins, addr5 base+both roles.
// Distinct addresses: addr0..addr5 (addr6 is never a member).
func newTestGroup(t *testing.T) *Group {
t.Helper()
g := NewGroup()
g.Add(addr0)
g.Add(addr1)
g.Add(addr3)
g.Add(addr5)
admins, err := g.AddRole("admins")
urequire.NoError(t, err)
admins.Members().Add(addr2)
admins.Members().Add(addr3)
admins.Members().Add(addr5)
mods, err := g.AddRole("mods")
urequire.NoError(t, err)
mods.Members().Add(addr1)
mods.Members().Add(addr4)
mods.Members().Add(addr5)
return g
}
func joinAddrs(addrs []address) string {
strs := make([]string, 0, len(addrs))
for _, a := range addrs {
strs = append(strs, string(a))
}
return strings.Join(strs, ",")
}
func TestBaseSet(t *testing.T) {
g := NewGroup()
uassert.Equal(t, 0, g.Size())
uassert.False(t, g.Has(addr1))
uassert.True(t, g.Add(addr1))
uassert.False(t, g.Add(addr1)) // duplicate
uassert.True(t, g.Add(addr2))
uassert.Equal(t, 2, g.Size())
uassert.True(t, g.Has(addr1))
uassert.False(t, g.Has(addr3))
uassert.True(t, g.Remove(addr1))
uassert.False(t, g.Remove(addr1)) // already gone
uassert.Equal(t, 1, g.Size())
uassert.False(t, g.Has(addr1))
}
func TestIterate(t *testing.T) {
g := NewGroup()
g.Add(addr2)
g.Add(addr1)
g.Add(addr3)
var got []address
stopped := g.Iterate(0, 10, func(a address) bool {
got = append(got, a)
return false
})
uassert.False(t, stopped)
uassert.Equal(t, "addr1,addr2,addr3", joinAddrs(got)) // sorted order
got = nil
g.Iterate(1, 1, func(a address) bool {
got = append(got, a)
return false
})
uassert.Equal(t, "addr2", joinAddrs(got))
// Early stop halts iteration, not just the return value.
visited := 0
stopped = g.Iterate(0, 10, func(a address) bool {
visited++
return true
})
uassert.True(t, stopped)
uassert.Equal(t, 1, visited)
// Roles are never consulted.
gg := newTestGroup(t)
got = nil
gg.Iterate(0, 10, func(a address) bool {
got = append(got, a)
return false
})
uassert.Equal(t, "addr0,addr1,addr3,addr5", joinAddrs(got))
}
func TestAddRole(t *testing.T) {
g := NewGroup()
r, err := g.AddRole("admins")
urequire.NoError(t, err)
uassert.Equal(t, "admins", r.Name())
uassert.Equal(t, 0, r.Members().Size())
uassert.Equal(t, 1, g.RoleCount())
_, err = g.AddRole("admins")
uassert.ErrorIs(t, err, ErrRoleExists)
_, err = g.AddRole("")
uassert.ErrorIs(t, err, ErrEmptyName)
uassert.Equal(t, 1, g.RoleCount())
}
func TestGetRoleHasRole(t *testing.T) {
g := newTestGroup(t)
r, found := g.GetRole("admins")
uassert.True(t, found)
uassert.Equal(t, "admins", r.Name())
uassert.True(t, r.Members().Has(addr2))
_, found = g.GetRole("nope")
uassert.False(t, found)
uassert.True(t, g.HasRole("mods"))
uassert.False(t, g.HasRole("nope"))
}
func TestRemoveRole(t *testing.T) {
g := newTestGroup(t)
uassert.True(t, g.RemoveRole("admins"))
uassert.False(t, g.RemoveRole("admins")) // already gone
uassert.Equal(t, 1, g.RoleCount())
uassert.False(t, g.HasRole("admins"))
// Members of the removed role stay in the base set and other roles.
uassert.True(t, g.Has(addr3)) // base
uassert.True(t, g.HasAny(addr5)) // still in base + mods
uassert.False(t, g.HasAny(addr2)) // was only in admins
}
func TestIterateRoles(t *testing.T) {
g := newTestGroup(t)
var names []string
stopped := g.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {
names = append(names, rr.Name())
return false
})
uassert.False(t, stopped)
uassert.Equal(t, "admins,mods", strings.Join(names, ","))
// offset/count window.
names = nil
g.IterateRoles(1, 1, func(rr *ReadonlyRole) bool {
names = append(names, rr.Name())
return false
})
uassert.Equal(t, "mods", strings.Join(names, ","))
// Early stop halts iteration, not just the return value.
names = nil
stopped = g.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {
names = append(names, rr.Name())
return true
})
uassert.True(t, stopped)
uassert.Equal(t, "admins", strings.Join(names, ","))
// Mutation path: capture names during iteration, revisit via GetRole.
names = nil
g.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {
names = append(names, rr.Name())
return false
})
for _, name := range names {
r, found := g.GetRole(name)
urequire.True(t, found)
r.Members().Add(addr6)
}
uassert.Equal(t, "admins,mods", strings.Join(g.RolesContaining(addr6), ","))
}
func TestRoleMeta(t *testing.T) {
g := NewGroup()
r, err := g.AddRole("admins")
urequire.NoError(t, err)
uassert.Nil(t, r.Meta())
r.SetMeta("quorum=2/3")
uassert.Equal(t, "quorum=2/3", r.Meta())
uassert.Equal(t, "quorum=2/3", r.Readonly().Meta())
r.SetMeta(nil)
uassert.Nil(t, r.Meta())
}
func TestHasAny(t *testing.T) {
g := newTestGroup(t)
uassert.True(t, g.HasAny(addr0)) // base only
uassert.True(t, g.HasAny(addr1)) // base + mods
uassert.True(t, g.HasAny(addr2)) // admins only
uassert.True(t, g.HasAny(addr4)) // mods only
uassert.True(t, g.HasAny(addr5)) // base + both roles
uassert.False(t, g.HasAny(addr6)) // nowhere
// Base-only member, no roles registered at all.
g2 := NewGroup()
g2.Add(addr1)
uassert.True(t, g2.HasAny(addr1))
uassert.False(t, g2.HasAny(addr2))
}
func TestTotalSize(t *testing.T) {
uassert.Equal(t, 0, NewGroup().TotalSize())
g := newTestGroup(t)
uassert.Equal(t, 4, g.Size()) // base only
uassert.Equal(t, 6, g.TotalSize()) // addr0..addr5, deduplicated
}
func TestIterateAll(t *testing.T) {
g := newTestGroup(t)
collect := func(offset, count int) (addrs []address, stopped bool) {
stopped = g.IterateAll(offset, count, func(a address) bool {
addrs = append(addrs, a)
return false
})
return addrs, stopped
}
// Order: base first (sorted), then roles in name order, deduplicated.
got, stopped := collect(0, 10)
uassert.False(t, stopped)
uassert.Equal(t, "addr0,addr1,addr3,addr5,addr2,addr4", joinAddrs(got))
// offset/count window over the deduplicated output.
got, _ = collect(1, 2)
uassert.Equal(t, "addr1,addr3", joinAddrs(got))
got, _ = collect(3, 10)
uassert.Equal(t, "addr5,addr2,addr4", joinAddrs(got))
// Window straddling skipped duplicates: count applies to deduplicated
// output, not to scanned items.
got, _ = collect(4, 2)
uassert.Equal(t, "addr2,addr4", joinAddrs(got))
// Degenerate parameters.
got, stopped = collect(6, 10) // offset == total
uassert.False(t, stopped)
uassert.Equal(t, 0, len(got))
got, _ = collect(0, 0)
uassert.Equal(t, 0, len(got))
got, _ = collect(-1, 2) // negative offset counts as zero
uassert.Equal(t, "addr0,addr1", joinAddrs(got))
// Early stop halts iteration, not just the return value.
visited := 0
stopped = g.IterateAll(0, 10, func(a address) bool {
visited++
return true
})
uassert.True(t, stopped)
uassert.Equal(t, 1, visited)
}
// TestIterateAllWindows pins the pagination contract exhaustively: every
// (offset, count) window over the deduplicated walk must equal the
// corresponding slice of the full walk.
func TestIterateAllWindows(t *testing.T) {
g := newTestGroup(t)
var full []address
g.IterateAll(0, 100, func(a address) bool {
full = append(full, a)
return false
})
urequire.Equal(t, 6, len(full))
for offset := 0; offset <= len(full); offset++ {
for count := 1; count <= len(full)+1; count++ {
var page []address
g.IterateAll(offset, count, func(a address) bool {
page = append(page, a)
return false
})
end := offset + count
if end > len(full) {
end = len(full)
}
label := "offset=" + strconv.Itoa(offset) + " count=" + strconv.Itoa(count)
uassert.Equal(t, joinAddrs(full[offset:end]), joinAddrs(page), label)
}
}
}
func TestRolesContaining(t *testing.T) {
g := newTestGroup(t)
uassert.Equal(t, "admins,mods", strings.Join(g.RolesContaining(addr5), ","))
uassert.Equal(t, "admins", strings.Join(g.RolesContaining(addr2), ","))
uassert.Equal(t, "mods", strings.Join(g.RolesContaining(addr1), ",")) // base not consulted
uassert.Equal(t, 0, len(g.RolesContaining(addr0))) // base-only member
uassert.Equal(t, 0, len(g.RolesContaining(addr6)))
}
func TestRemoveFromAll(t *testing.T) {
g := newTestGroup(t)
uassert.True(t, g.RemoveFromAll(addr5)) // base + both roles
uassert.False(t, g.HasAny(addr5))
uassert.True(t, g.RemoveFromAll(addr0)) // base-only: removed reflects the base hit alone
uassert.False(t, g.HasAny(addr0))
uassert.True(t, g.RemoveFromAll(addr2)) // role-only
uassert.False(t, g.HasAny(addr2))
uassert.False(t, g.RemoveFromAll(addr6)) // nowhere
uassert.Equal(t, 3, g.TotalSize()) // addr1, addr3, addr4 remain
uassert.Equal(t, 2, g.RoleCount()) // roles themselves are kept
}
// TestRemoveRoleStaleHandle pins the aliasing semantics: a *Role handle
// held across RemoveRole keeps working as a detached object, but its
// mutations no longer affect the group, and re-adding the name creates a
// fresh, independent role.
func TestRemoveRoleStaleHandle(t *testing.T) {
g := newTestGroup(t)
stale, found := g.GetRole("admins")
urequire.True(t, found)
uassert.True(t, g.RemoveRole("admins"))
// The detached role still works as an orphan object...
uassert.Equal(t, "admins", stale.Name())
stale.Members().Add(addr6)
uassert.True(t, stale.Members().Has(addr6))
// ...but no longer affects the group.
uassert.False(t, g.HasAny(addr6))
uassert.Equal(t, 0, len(g.RolesContaining(addr6)))
uassert.False(t, g.HasAny(addr2)) // addr2 was admins-only
uassert.Equal(t, 5, g.TotalSize()) // fixture minus admins-only addr2
// Re-adding the name yields a fresh empty role, not the stale one.
fresh, err := g.AddRole("admins")
urequire.NoError(t, err)
uassert.Equal(t, 0, fresh.Members().Size())
uassert.False(t, g.HasAny(addr6))
}
func TestReadonlyGroup(t *testing.T) {
g := newTestGroup(t)
rg := g.Readonly()
// Base reads.
uassert.True(t, rg.Has(addr0))
uassert.False(t, rg.Has(addr2))
uassert.Equal(t, 4, rg.Size())
var got []address
stopped := rg.Iterate(0, 10, func(a address) bool {
got = append(got, a)
return false
})
uassert.False(t, stopped)
uassert.Equal(t, "addr0,addr1,addr3,addr5", joinAddrs(got))
// Role registry reads.
uassert.True(t, rg.HasRole("admins"))
uassert.False(t, rg.HasRole("nope"))
uassert.Equal(t, 2, rg.RoleCount())
var names []string
stopped = rg.IterateRoles(0, 10, func(rr *ReadonlyRole) bool {
names = append(names, rr.Name())
return false
})
uassert.False(t, stopped)
uassert.Equal(t, "admins,mods", strings.Join(names, ","))
rr, found := rg.GetRole("admins")
uassert.True(t, found)
uassert.Equal(t, "admins", rr.Name())
uassert.True(t, rr.Members().Has(addr2))
uassert.Equal(t, 3, rr.Members().Size())
_, found = rg.GetRole("nope")
uassert.False(t, found)
// Aggregated reads.
uassert.True(t, rg.HasAny(addr4))
uassert.False(t, rg.HasAny(addr6))
uassert.Equal(t, 6, rg.TotalSize())
got = nil
stopped = rg.IterateAll(0, 10, func(a address) bool {
got = append(got, a)
return false
})
uassert.False(t, stopped)
uassert.Equal(t, "addr0,addr1,addr3,addr5,addr2,addr4", joinAddrs(got))
uassert.True(t, rg.IterateAll(0, 10, func(a address) bool { return true }))
uassert.Equal(t, "admins,mods", strings.Join(rg.RolesContaining(addr5), ","))
}
func TestReadonlyViewsAreLive(t *testing.T) {
g := newTestGroup(t)
rg := g.Readonly()
admins, found := g.GetRole("admins")
urequire.True(t, found)
rr := admins.Readonly()
// Views are thin handles, not snapshots: mutations through the owning
// side are immediately visible through previously created views.
g.Add(addr6)
uassert.Equal(t, 5, rg.Size())
uassert.True(t, rg.Has(addr6))
admins.Members().Add(addr6)
uassert.Equal(t, 4, rr.Members().Size())
uassert.True(t, rr.Members().Has(addr6))
}
readonly.gno
package groups
import "gno.land/p/moul/addrset/v0"
// ReadonlyRole is a read-only view of a Role. It exposes only read-side
// methods and holds the *Role in an unexported field, so cross-package
// callers cannot mutate the role through this type.
type ReadonlyRole struct {
role *Role
}
// Name returns the role's name.
func (rr ReadonlyRole) Name() string {
return rr.role.name
}
// Members returns a read-only view of the role's member set.
func (rr ReadonlyRole) Members() *addrset.ReadonlySet {
return rr.role.members.Readonly()
}
// Meta returns the role's metadata slot.
//
// NOTE: a mutable pointer stored in meta is NOT protected by this readonly
// view — the pointee remains mutable by anyone who retrieves it. See the
// package doc.
func (rr ReadonlyRole) Meta() any {
return rr.role.meta
}
// ReadonlyGroup is a read-only view of a Group. Every method mirrors the
// read-side of Group; mutators are absent. It holds the *Group in an
// unexported field, so cross-package callers cannot mutate through it.
type ReadonlyGroup struct {
group *Group
}
// --- Base set (base only) ---
// Has reports whether addr is in the base set (roles not consulted).
func (rg ReadonlyGroup) Has(addr address) bool {
return rg.group.Has(addr)
}
// Size returns the number of addresses in the base set only.
func (rg ReadonlyGroup) Size() int {
return rg.group.Size()
}
// Iterate walks the base set (only); see Group.Iterate.
func (rg ReadonlyGroup) Iterate(offset, count int, fn func(addr address) bool) (stopped bool) {
return rg.group.Iterate(offset, count, fn)
}
// --- Role registry ---
// GetRole returns a read-only view of the named role if it exists.
func (rg ReadonlyGroup) GetRole(name string) (rr *ReadonlyRole, found bool) {
r, ok := rg.group.GetRole(name)
if !ok {
return nil, false
}
return r.Readonly(), true
}
// HasRole reports whether a role with the given name exists.
func (rg ReadonlyGroup) HasRole(name string) bool {
return rg.group.HasRole(name)
}
// RoleCount returns the number of registered roles.
func (rg ReadonlyGroup) RoleCount() int {
return rg.group.RoleCount()
}
// IterateRoles walks roles in name order; see Group.IterateRoles.
func (rg ReadonlyGroup) IterateRoles(offset, count int, fn func(*ReadonlyRole) bool) (stopped bool) {
return rg.group.IterateRoles(offset, count, fn)
}
// --- Aggregations ---
// HasAny reports whether addr is in the base set OR in any role.
func (rg ReadonlyGroup) HasAny(addr address) bool {
return rg.group.HasAny(addr)
}
// TotalSize returns the deduplicated count across base + all roles.
func (rg ReadonlyGroup) TotalSize() int {
return rg.group.TotalSize()
}
// IterateAll walks every distinct address across base + all roles; see
// Group.IterateAll.
func (rg ReadonlyGroup) IterateAll(offset, count int, fn func(addr address) bool) (stopped bool) {
return rg.group.IterateAll(offset, count, fn)
}
// RolesContaining returns the names of all roles containing addr, in name
// order; see Group.RolesContaining.
func (rg ReadonlyGroup) RolesContaining(addr address) []string {
return rg.group.RolesContaining(addr)
}
role.gno
package groups
import "gno.land/p/moul/addrset/v0"
// Role is a named bucket of addresses with optional metadata.
//
// A Role is always owned by a parent Group; the only way to obtain a *Role
// is Group.AddRole or Group.GetRole. See the Group doc for the realm-
// boundary rules that govern passing *Role values around.
type Role struct {
name string
members *addrset.Set
meta any
}
// newRole constructs a new empty role with the given name. Unexported: the
// only valid path to a *Role is via Group.AddRole, which registers it in
// the parent Group's role registry. A detached Role has no useful API.
func newRole(name string) *Role {
return &Role{
name: name,
members: &addrset.Set{},
}
}
// Name returns the role's registry name.
func (r *Role) Name() string {
return r.name
}
// Members returns a mutable reference to the role's member set; mutations
// through the returned pointer affect the role.
//
// SECURITY: the returned *addrset.Set is mutable. Do not expose it to
// untrusted callers — use Role.Readonly().Members() for a
// cross-realm-safe view.
func (r *Role) Members() *addrset.Set {
return r.members
}
// Meta returns the role's metadata slot. See the package doc for the rule
// against storing mutable pointers in meta.
func (r *Role) Meta() any {
return r.meta
}
// SetMeta sets the role's metadata slot. Passing nil clears it.
//
// SECURITY: do NOT store a pointer whose type has a mutator method (this
// includes common /p/ types like *addrset.Set or *avl.Tree) if untrusted
// realms may hold a Readonly() view of this Group. Meta() returns the stored
// value as-is, so a foreign reader can invoke that method and borrow rule #2
// commits the write under this (the allocating) realm's authority. A direct
// field write through the pointer is still blocked by the realm-ownership
// gate — the leak is specifically mutator-method dispatch. Prefer value types
// with no internal pointers. See the package doc.
func (r *Role) SetMeta(meta any) {
r.meta = meta
}
// Readonly returns a read-only view of the role.
func (r *Role) Readonly() *ReadonlyRole {
return &ReadonlyRole{role: r}
}