Playground
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/vault/v1" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "5000000ugnot"
vault.gno
package vault
import (
"chain"
"strconv"
"strings"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/nt/avl/v0"
)
// selfPath is this realm's own page. A root-relative link resolves against
// the domain, not the realm, so every link back into it names it in full.
const selfPath = "/r/moul/x/daily/vault/v1"
// vaults maps address string -> *avl.Tree (key string -> value string).
var vaults avl.Tree
// The bounds on what a caller may store. Anyone may open a vault, the root
// page lists every vault, and a vault's page lists every entry.
const (
MaxVaults = 1000
MaxEntries = 100 // per vault
MaxKeyLen = 64
MaxValueLen = 512
)
// vaultFor returns the caller's namespace tree, creating it if needed.
func vaultFor(owner address) *avl.Tree {
k := owner.String()
if v := vaults.Get(k); v != nil {
return v.(*avl.Tree)
}
if vaults.Size() >= MaxVaults {
panic("vault is full at " + strconv.Itoa(MaxVaults) + " vaults")
}
t := &avl.Tree{}
vaults.Set(k, t)
return t
}
// Set stores value under key in the caller's own namespace.
func Set(cur realm, key string, value string) {
who := caller(cur)
if key == "" {
panic("key must not be empty")
}
if len(key) > MaxKeyLen || len(value) > MaxValueLen {
panic("key or value too long")
}
t := vaultFor(who)
if !t.Has(key) && t.Size() >= MaxEntries {
panic("a vault holds at most " + strconv.Itoa(MaxEntries) + " entries")
}
t.Set(key, value)
chain.Emit("VaultSet", "owner", who.String(), "key", key)
}
// Delete removes key from the caller's own namespace.
func Delete(cur realm, key string) {
who := caller(cur)
k := who.String()
v := vaults.Get(k)
if v == nil {
panic("no vault for caller")
}
t := v.(*avl.Tree)
if _, removed := t.Remove(key); !removed {
panic("key not found")
}
if t.Size() == 0 {
vaults.Remove(k)
}
chain.Emit("VaultDelete", "owner", who.String(), "key", key)
}
// Render shows all vaults (root) or a single address's entries ("/<address>").
func Render(path string) string {
p := strings.TrimPrefix(path, "/")
if p == "" {
return renderRoot()
}
return renderAddress(p)
}
func renderRoot() string {
var b strings.Builder
b.WriteString("# Key-Value Vault\n\n")
b.WriteString("A per-address key-value store. Each caller owns their own namespace; only the owner can mutate their entries.\n\n")
if vaults.Size() == 0 {
b.WriteString("_No vaults yet. Call `Set(cur, key, value)` to create one._\n")
return b.String()
}
b.WriteString("## Vaults\n\n")
b.WriteString("| Address | Entries |\n")
b.WriteString("|---|---|\n")
vaults.Iterate("", "", func(k string, v interface{}) bool {
t := v.(*avl.Tree)
b.WriteString("| [")
b.WriteString(k)
b.WriteString("](" + selfPath + ":")
// link back into this realm's render for the address subpage
b.WriteString(k)
b.WriteString(") | ")
b.WriteString(strconv.Itoa(t.Size()))
b.WriteString(" |\n")
return false
})
b.WriteString("\nView an address's entries at path `/<address>`.\n")
return b.String()
}
func renderAddress(addr string) string {
var b strings.Builder
b.WriteString("# Vault: ")
b.WriteString(ui.Inline(addr))
b.WriteString("\n\n")
v := vaults.Get(addr)
if v == nil {
b.WriteString("_No vault for this address._\n")
return b.String()
}
t := v.(*avl.Tree)
b.WriteString("| Key | Value |\n")
b.WriteString("|---|---|\n")
t.Iterate("", "", func(k string, val interface{}) bool {
b.WriteString("| ")
b.WriteString(ui.Cell(k))
b.WriteString(" | ")
b.WriteString(ui.Cell(val.(string)))
b.WriteString(" |\n")
return false
})
b.WriteString("\nTotal entries: ")
b.WriteString(strconv.Itoa(t.Size()))
b.WriteString("\n")
return b.String()
}
// caller is the address that crossed into this realm, after checking that the
// realm token is this frame's own.
func caller(cur realm) address {
if !cur.IsCurrent() {
panic("vault: spoofed realm")
}
return cur.Previous().Address()
}
vault_test.gno
package vault
import (
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
func TestSetAndRender(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
Set(cross(cur), "greeting", "hello")
Set(cross(cur), "lang", "gno")
out := renderAddress(alice.String())
uassert.True(t, strings.Contains(out, "greeting"), "should contain key greeting")
uassert.True(t, strings.Contains(out, "hello"), "should contain value hello")
uassert.True(t, strings.Contains(out, "Total entries: 2"), "should count 2 entries")
root := Render("")
uassert.True(t, strings.Contains(root, alice.String()), "root should list alice")
}
func TestDeleteAndIsolation(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice2")
bob := testutils.TestAddress("bob2")
testing.SetRealm(testing.NewUserRealm(alice))
Set(cross(cur), "shared", "alice-value")
testing.SetRealm(testing.NewUserRealm(bob))
Set(cross(cur), "shared", "bob-value")
// Namespaces are isolated: same key, different owners.
av := vaults.Get(alice.String())
bv := vaults.Get(bob.String())
avVal := av.(*avl.Tree).Get("shared")
bvVal := bv.(*avl.Tree).Get("shared")
uassert.Equal(t, "alice-value", avVal.(string))
uassert.Equal(t, "bob-value", bvVal.(string))
// Bob deletes his own key; alice's remains.
Delete(cross(cur), "shared")
bobStill := vaults.Has(bob.String())
uassert.False(t, bobStill, "bob's vault should be gone after last key removed")
aliceStill := vaults.Has(alice.String())
uassert.True(t, aliceStill, "alice's vault should remain")
// Deleting a missing key aborts.
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsWithMessage(t, cur, "key not found", func() {
Delete(cross(cur), "nope")
})
}
zz_bounds_test.gno
package vault
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// A vault holds a bounded number of entries of bounded size; overwriting an
// existing key is always allowed.
func TestVaultIsBounded(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bounded")))
uassert.AbortsContains(t, cur, "too long", func() { Set(cross(cur), strings.Repeat("k", MaxKeyLen+1), "v") })
for i := 0; i < MaxEntries; i++ {
Set(cross(cur), "k"+strconv.Itoa(i), "v")
}
uassert.AbortsContains(t, cur, "at most", func() { Set(cross(cur), "one-more", "v") })
Set(cross(cur), "k0", "overwritten")
}
// The vault count is bounded globally, not just entries per vault.
func TestVaultCountIsBounded(cur realm, t *testing.T) {
var added []string
for i := 0; vaults.Size() < MaxVaults; i++ {
k := testutils.TestAddress("v" + strconv.Itoa(i)).String()
if vaults.Get(k) == nil {
vaults.Set(k, &avl.Tree{})
added = append(added, k)
}
}
defer func() {
for _, k := range added {
vaults.Remove(k)
}
}()
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("latecomer")))
uassert.AbortsContains(t, cur, "vault is full", func() { Set(cross(cur), "k", "v") })
}
zz_escape_test.gno
package vault
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// A key and a value are the owner's text, written into table cells: a pipe
// must not open a column and a link must not go live.
func TestKeysAndValuesAreTableSafe(cur realm, t *testing.T) {
who := testutils.TestAddress("escaper")
testing.SetRealm(testing.NewUserRealm(who))
Set(cross(cur), "k | [claim](https://evil.example)", "[claim](https://evil.example)")
page := Render(who.String())
uassert.False(t, strings.Contains(page, "[claim](https://evil.example)"), page)
uassert.False(t, strings.Contains(page, "| k | "), page)
}
// A path that names nothing is echoed back on the not-found page. It is the
// visitor's text, so a backtick in it must not close a code span and let a
// link through.
func TestNotFoundPathIsEscaped(t *testing.T) {
out := Render("x` [claim](https://evil.example) `")
uassert.False(t, strings.Contains(out, "[claim](https://evil.example)"), out)
}
zz_links_test.gno
package vault
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// The index links each vault to this realm's own page. It once linked to
// the malformed gno.land/r:<address>.
func TestIndexLinksNameThisRealm(cur realm, t *testing.T) {
who := testutils.TestAddress("linker")
testing.SetRealm(testing.NewUserRealm(who))
Set(cross(cur), "k", "v")
out := Render("")
uassert.True(t, strings.Contains(out, "](/r/moul/x/daily/vault/v1:"+who.String()+")"), out)
}