Playground
acl.gno
package memba_notes_rc1
import (
keys "gno.land/r/samcrew/enckeys_v1"
"strings"
)
func writer(n *note, who address) bool {
for _, a := range n.Writers {
if a == who {
return true
}
}
return false
}
func canWrite(cur realm, n *note, who address) bool {
if who == n.Owner {
return true
}
if n.Mode == ModePublicOpen {
return false
}
if writer(n, who) {
return true
}
if encrypted(n.Mode) && !contains(n.Readers, who) {
return false
}
if n.GovWriters && n.Owner == govAddress && govMember(who) {
return true
}
return policyAllows(cur, n, who, OpWrite)
}
func requireWrite(cur realm, n *note, who address) {
if !canWrite(cur, n, who) {
panic("notes: writer required")
}
}
func AddWriter(cur realm, id [16]byte, baseRevision uint64, to address, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateAddWriter(cur, who, id, baseRevision, to, opID)
}
func mutateAddWriter(cur realm, who address, id [16]byte, baseRevision uint64, to address, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if !public(n.Mode) {
panic("notes: encrypted ACL requires atomic manifest")
}
to = keys.CanonicalAddress(to)
if to == n.Owner || writer(n, to) {
panic("notes: writer already present")
}
if len(n.Writers) >= MaxReaders {
panic("notes: too many writers")
}
operation(n, opID)
n.Writers = append(n.Writers, to)
sharedIndex.Set(string(to)+":"+indexKey(n), idText(id))
bump(n, who, opID, "writer-add")
}
func RemoveWriter(cur realm, id [16]byte, baseRevision uint64, to address, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateRemoveWriter(cur, who, id, baseRevision, to, opID)
}
func mutateRemoveWriter(cur realm, who address, id [16]byte, baseRevision uint64, to address, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if !public(n.Mode) {
panic("notes: encrypted ACL requires rotation")
}
to = keys.CanonicalAddress(to)
if !writer(n, to) {
panic("notes: writer missing")
}
operation(n, opID)
for i, a := range n.Writers {
if a == to {
n.Writers = append(n.Writers[:i], n.Writers[i+1:]...)
break
}
}
sharedIndex.Remove(string(to) + ":" + indexKey(n))
bump(n, who, opID, "writer-remove")
}
func ProposeOwner(cur realm, id [16]byte, baseRevision uint64, to address, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateProposeOwner(cur, who, id, baseRevision, to, opID)
}
func mutateProposeOwner(cur realm, who address, id [16]byte, baseRevision uint64, to address, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if to != "" {
to = keys.CanonicalAddress(to)
}
if to == n.Owner {
panic("notes: already owner")
}
operation(n, opID)
n.PendingOwner = to
bump(n, who, opID, "owner-propose")
}
func AcceptOwnership(cur realm, id [16]byte, baseRevision uint64, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateAcceptOwnership(cur, who, id, baseRevision, opID)
}
func mutateAcceptOwnership(cur realm, who address, id [16]byte, baseRevision uint64, opID [16]byte) {
n := live(id)
expected(n, baseRevision)
if n.PendingOwner == "" || who != n.PendingOwner {
panic("notes: pending owner required")
}
isRealm := strings.HasPrefix(cur.Previous().PkgPath(), "gno.land/r/") || who == govAddress
if encrypted(n.Mode) && (!isRealm && !contains(n.Readers, who) || isRealm && n.Mode == ModePrivate) {
panic("notes: encrypted ownership requires current wrap/shared mode")
}
if n.OwnerGeneration == ^uint64(0) {
panic("notes: owner generation exhausted")
}
operation(n, opID)
unindex(n)
n.OwnerIsRealm = isRealm
resetPublicWrites(n)
n.Owner = who
n.PendingOwner = ""
n.OwnerGeneration++
n.GovWriters = false
if encrypted(n.Mode) {
preserveTransferredWriters(n)
}
index(n)
bump(n, who, opID, "owner-accept")
}
func SetListed(cur realm, id [16]byte, baseRevision uint64, listed bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateSetListed(cur, who, id, baseRevision, listed, opID)
}
func mutateSetListed(cur realm, who address, id [16]byte, baseRevision uint64, listed bool, opID [16]byte) {
n := live(id)
if who != n.Owner && moderator(who) {
mutateModerateListing(cur, who, id, baseRevision, listed, opID)
return
}
owner(n, who)
expected(n, baseRevision)
if !public(n.Mode) {
panic("notes: public note required")
}
operation(n, opID)
unindex(n)
n.Listed = listed
index(n)
bump(n, who, opID, "listing")
}
func WritersJSON(idHex string) string {
n := find(readID(idHex))
out := "["
for i, a := range n.Writers {
if i > 0 {
out += ","
}
out += q(string(a))
}
return out + "]"
}
func ListSharedWithJSON(addr address, cursor string, limit int) string {
return page(sharedIndex, string(keys.CanonicalAddress(addr))+":", cursor, limit)
}
admin.gno
package memba_notes_rc1
import (
"chain"
keys "gno.land/r/samcrew/enckeys_v1"
)
func administrator(who address) {
if who != admin {
panic("notes: admin required")
}
}
func SetCreateFee(cur realm, fee int64) {
who := enter(cur, false)
defer leave()
administrator(who)
if fee < 0 || fee > 1000000 {
panic("notes: fee out of range")
}
createFee = fee
}
func SetTreasury(cur realm, to address) {
who := enter(cur, false)
defer leave()
administrator(who)
to = keys.CanonicalAddress(to)
if to == cur.Address() || to == chain.DeriveStorageDepositAddr(RealmPath) {
panic("notes: locked treasury")
}
treasury = to
}
func Pause(cur realm, on bool) {
who := enter(cur, false)
defer leave()
administrator(who)
paused = on
}
func TransferAdmin(cur realm, to address) {
who := enter(cur, false)
defer leave()
administrator(who)
to = keys.CanonicalAddress(to)
if to == govAddress {
panic("notes: governance cannot accept realm administration")
}
pendingAdmin = to
}
func AcceptAdmin(cur realm) {
who := enter(cur, false)
defer leave()
if who != pendingAdmin || pendingAdmin == "" {
panic("notes: pending admin required")
}
admin = who
pendingAdmin = ""
}
// GetAdmin supplies the closed authority readback used by deployment rehearsal.
func GetAdmin() address { return admin }
backup.gno
package memba_notes_rc1
import (
"bytes"
"chain/runtime"
"crypto/bech32"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"gno.land/p/samcrew/avl"
keys "gno.land/r/samcrew/enckeys_v1"
"strconv"
"strings"
)
const MaxBackupBytes = 365
type backupRecord struct {
Record []byte
Mode uint8
Generation, Revision uint64
PublicKeyHash []byte
Last receipt
}
var backupLatest = avl.NewTree()
var backups = avl.NewTree()
// A wallet-protected historical backup cannot become Vault-safe by relabelling.
var standardBackupKeys = avl.NewTree()
func backupKey(who address, generation uint64) string {
s := strconv.FormatUint(generation, 10)
return string(who) + ":" + strings.Repeat("0", 20-len(s)) + s
}
func backupText(record []byte, pos, cap int) (string, int) {
if pos+4 > len(record) {
panic("notes: backup truncated")
}
size := int(binary.BigEndian.Uint32(record[pos : pos+4]))
pos += 4
if size < 1 || size > cap || pos+size > len(record) {
panic("notes: backup text length")
}
for _, b := range record[pos : pos+size] {
if b < 33 || b > 126 {
panic("notes: backup ascii")
}
}
return string(record[pos : pos+size]), pos + size
}
func validateBackup(who address, record []byte) (uint8, uint64, []byte) {
if len(record) < 185 || len(record) > MaxBackupBytes || string(record[:4]) != "MNKB" || record[4] != 1 || record[5] != 1 {
panic("notes: backup format")
}
mode := record[6]
kdf := record[7]
memory := binary.BigEndian.Uint32(record[8:12])
passes := binary.BigEndian.Uint32(record[12:16])
lanes := record[16]
if !(mode == 1 && kdf == 1 && memory == 0 && passes == 0 && lanes == 0 || mode == 2 && kdf == 2 && memory == 65536 && passes == 3 && lanes == 1) {
panic("notes: backup kdf profile")
}
chain, pos := backupText(record, 33, 64)
realmPath, pos := backupText(record, pos, 128)
if chain != runtime.ChainID() || realmPath != RealmPath || len(record) != pos+132 {
panic("notes: backup network/length")
}
encoded, err := bech32.EncodeFromBase256("g", record[pos:pos+20])
if err != nil || address(encoded) != who {
panic("notes: backup address")
}
pos += 20
generation := binary.BigEndian.Uint64(record[pos : pos+8])
pos += 8
hash := record[pos : pos+32]
pk, gen, active := keys.GetKey(who, keys.SuiteXWingV1)
h := sha256.Sum256(pk)
if generation == 0 || generation != gen || !active || !bytes.Equal(hash, h[:]) {
panic("notes: backup registry identity")
}
return mode, generation, copied(hash)
}
func SetSeedBackup(cur realm, baseRevision uint64, record []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
if !cur.Previous().IsUserCall() {
panic("notes: backup directly from account")
}
if opID == ([16]byte{}) || baseRevision == ^uint64(0) {
panic("notes: invalid backup operation")
}
var revision uint64
if v, ok := backupLatest.Get(string(who)); ok {
r := v.(*backupRecord)
revision = r.Revision
if r.Last.Operation == opID {
panic("notes: operation id reused")
}
}
if revision != baseRevision {
panic("notes: stale backup revision")
}
mode, generation, hash := validateBackup(who, record)
exposureKey := string(who) + ":" + hex.EncodeToString(hash)
if mode == 2 {
if _, seen := standardBackupKeys.Get(exposureKey); seen {
panic("notes: vault requires independent identity")
}
} else {
standardBackupKeys.Set(exposureKey, true)
}
r := &backupRecord{copied(record), mode, generation, revision + 1, hash, receipt{opID, who, runtime.ChainHeight()}}
backups.Set(backupKey(who, generation), r)
backupLatest.Set(string(who), r)
}
func backupJSON(r *backupRecord, withRecord bool) string {
s := `{"mode":` + strconv.Itoa(int(r.Mode)) + `,"suite":"xwing-v1","generation":` + u(r.Generation) + `,"revision":` + u(r.Revision) + `,"public_key_hash":` + blob(r.PublicKeyHash) + `,"op_id":` + q(idText(r.Last.Operation)) + `,"actor":` + q(string(r.Last.Actor)) + `,"height":` + q(strconv.FormatInt(r.Last.Height, 10))
if withRecord {
s += `,"record":` + blob(r.Record)
}
return s + `}`
}
func SeedBackupJSON(who address) string {
v, ok := backupLatest.Get(string(keys.CanonicalAddress(who)))
if !ok {
return "null"
}
return backupJSON(v.(*backupRecord), true)
}
func SeedBackupAtJSON(who address, generation uint64) string {
v, ok := backups.Get(backupKey(keys.CanonicalAddress(who), generation))
if !ok {
return "null"
}
return backupJSON(v.(*backupRecord), true)
}
func SeedBackupsJSON(who address, cursor uint64, limit int) string {
who = keys.CanonicalAddress(who)
if limit < 1 || limit > MaxPage {
panic("notes: page limit")
}
items := []string{}
var next uint64
backups.Iterate(backupKey(who, cursor), string(who)+":\xff", func(k string, v interface{}) bool {
r := v.(*backupRecord)
if r.Generation <= cursor {
return false
}
items = append(items, backupJSON(r, false))
next = r.Generation
return len(items) == limit
})
if len(items) < limit {
next = 0
}
return `{"items":[` + strings.Join(items, ",") + `],"next_cursor":` + u(next) + `}`
}
capabilities.gno
package memba_notes_rc1
import (
"gno.land/p/samcrew/avl"
"strconv"
)
// Only explicit public grants are stored. Private notes keep their existing ACL.
var publicWriteGrants = avl.NewTree()
func publicWritesEnabled(n *note) bool {
_, granted := publicWriteGrants.Get(idText(n.ID))
return !n.Deleted && n.Mode == ModePublicOpen && granted
}
func resetPublicWrites(n *note) {
if _, granted := publicWriteGrants.Get(idText(n.ID)); granted {
publicWriteGrants.Remove(idText(n.ID))
}
}
// Community editing never grants ResolveComment or any owner/moderator action.
// Keep requireWrite unchanged for those existing permissions.
// While paused the grant is ignored, so only the existing ACL can edit.
func requireContentWrite(cur realm, n *note, who address) {
if !paused && publicWritesEnabled(n) && cur.Previous().IsUserCall() {
return
}
requireWrite(cur, n, who)
}
func SetPublicWrites(cur realm, id [16]byte, baseRevision uint64, on bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateSetPublicWrites(cur, who, id, baseRevision, on, opID)
}
func mutateSetPublicWrites(cur realm, who address, id [16]byte, baseRevision uint64, on bool, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if n.Mode != ModePublicOpen {
panic("notes: public-open note required")
}
operation(n, opID)
if publicWritesEnabled(n) == on {
panic("notes: public writes unchanged")
}
if on {
publicWriteGrants.Set(idText(id), true)
} else {
resetPublicWrites(n)
}
bump(n, who, opID, "public-writes")
}
// Separate schema: existing NoteJSON consumers retain their exact field set.
func PublicCapabilitiesJSON(idHex string) string {
v, ok := notes.Get(idText(readID(idHex)))
if !ok {
return "null"
}
n := v.(*note)
if !public(n.Mode) {
return "null"
}
return `{"schema":"memba-notes/public-capabilities/v1","id":` + q(idText(n.ID)) + `,"state_revision":` + u(n.Revision) + `,"owner_generation":` + u(n.OwnerGeneration) + `,"mode":` + strconv.Itoa(int(n.Mode)) + `,"deleted":` + strconv.FormatBool(n.Deleted) + `,"allow_public_writes":` + strconv.FormatBool(publicWritesEnabled(n)) + `}`
}
chunks.gno
package memba_notes_rc1
import "strconv"
const MaxBodyChunkBytes = 8192
func NoteMetaJSON(idHex string) string {
v, ok := notes.Get(idText(readID(idHex)))
if !ok {
return "null"
}
return noteJSON(v.(*note), false)
}
// Each page is tied to the complete state revision, including access/mode and
// epoch changes. Clients concatenate binary chunks before decoding UTF8/AEAD.
func NoteBodyChunkJSON(idHex string, expectedRevision uint64, offset, limit int) string {
n := find(readID(idHex))
if expectedRevision != n.Revision {
panic("notes: stale body revision")
}
if limit < 1 || limit > MaxBodyChunkBytes || offset < 0 || offset > n.BodyBytes {
panic("notes: body chunk bounds")
}
end := offset + limit
if end > n.BodyBytes {
end = n.BodyBytes
}
return `{"id":` + q(idText(n.ID)) + `,"state_revision":` + u(n.Revision) + `,"body_revision":` + u(n.BodyRevision) + `,"epoch":` + u(uint64(n.Epoch)) + `,"offset":` + q(strconv.Itoa(offset)) + `,"total":` + q(strconv.Itoa(n.BodyBytes)) + `,"next_offset":` + q(strconv.Itoa(end)) + `,"chunk_blob":` + blob(n.Body[offset:end]) + `}`
}
comments.gno
package memba_notes_rc1
import (
"chain/runtime"
"gno.land/p/samcrew/avl"
"strconv"
"strings"
"unicode/utf8"
)
const MaxCommentBytes = 4000
const MaxAnchorBytes = 600
const CommentCooldownBlocks int64 = 10
const MaxCommentPage = 5
type comment struct {
Sequence uint64
ID, Parent [16]byte
Author address
BodyRevision uint64
Epoch uint32
Anchor, Body []byte
Revision uint64
CreatedHeight int64
Last receipt
Deleted, Hidden, Resolved bool
Encrypted bool
}
var comments = avl.NewTree()
var commentIndex = avl.NewTree()
var cooldowns = avl.NewTree()
func commentKey(id, cid [16]byte) string { return idText(id) + ":" + idText(cid) }
func getComment(id, cid [16]byte) *comment {
v, ok := comments.Get(commentKey(id, cid))
if !ok {
panic("notes: comment missing")
}
return v.(*comment)
}
func commentExpected(c *comment, rev uint64, op [16]byte) {
if c.Revision != rev || rev == ^uint64(0) {
panic("notes: stale comment revision")
}
if op == ([16]byte{}) || c.Last.Operation == op {
panic("notes: invalid comment operation")
}
}
func commentReceipt(c *comment, who address, op [16]byte) {
c.Revision++
c.Last = receipt{op, who, runtime.ChainHeight()}
}
func mayComment(cur realm, n *note, who address) bool {
if n.Mode == ModePublicOpen {
return true
}
if n.Mode == ModePublic {
return who == n.Owner || writer(n, who) || n.GovWriters && n.Owner == govAddress && govMember(who) || policyAllows(cur, n, who, OpComment)
}
if n.Mode == ModeShared {
return contains(n.Readers, who)
}
return false
}
// Public comments carry UTF8 anchor/body separately. Encrypted comments will
// carry their combined authenticated payload in Body and an empty Anchor.
func AddComment(cur realm, id, cid [16]byte, bodyRevision uint64, epoch uint32, parent [16]byte, anchor, body []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
n := live(id)
if paused {
panic("notes: comments paused")
}
if !mayComment(cur, n, who) {
panic("notes: comments denied")
}
if cid == ([16]byte{}) || opID == ([16]byte{}) {
panic("notes: empty comment id")
}
if _, ok := comments.Get(commentKey(id, cid)); ok {
panic("notes: comment id used")
}
if bodyRevision == 0 || bodyRevision > n.BodyRevision || epoch != n.Epoch {
panic("notes: bad comment anchor version")
}
if public(n.Mode) && (len(anchor) > MaxAnchorBytes || !utf8.Valid(anchor) || len(body) == 0 || len(body) > MaxCommentBytes || !utf8.Valid(body) || utf8.RuneCount(body) > 1000) {
panic("notes: invalid comment payload")
}
privateWritable(n)
if encrypted(n.Mode) {
if len(anchor) != 0 {
panic("notes: encrypted anchor must be inside payload")
}
validateCipher(body, n.Epoch, 3, 1, MaxCipherCommentBytes)
}
if parent != ([16]byte{}) {
p := getComment(id, parent)
if p.Deleted {
panic("notes: parent deleted")
}
}
ck := idText(id) + ":" + string(who)
h := runtime.ChainHeight()
if v, ok := cooldowns.Get(ck); ok && h-v.(int64) < CommentCooldownBlocks {
panic("notes: comment cooldown")
}
if n.CommentSequence == ^uint64(0) {
panic("notes: comment sequence exhausted")
}
n.CommentSequence++
c := &comment{Sequence: n.CommentSequence, Encrypted: encrypted(n.Mode), ID: cid, Parent: parent, Author: who, BodyRevision: bodyRevision, Epoch: epoch, Anchor: copied(anchor), Body: copied(body), CreatedHeight: h}
commentReceipt(c, who, opID)
comments.Set(commentKey(id, cid), c)
seq := strconv.FormatUint(c.Sequence, 10)
commentIndex.Set(idText(id)+":"+strings.Repeat("0", 20-len(seq))+seq+":"+idText(cid), commentKey(id, cid))
cooldowns.Set(ck, h)
historyCommentChange(n, c, "comment-add")
}
func DeleteComment(cur realm, id, cid [16]byte, baseRevision uint64, opID [16]byte) {
who := enter(cur, false)
defer leave()
// Authors can clear their current payload even after the note is deleted or
// paused. Public history keeps the original unless a moderator redacts it.
n := find(id)
c := getComment(id, cid)
if c.Author != who {
panic("notes: comment author required")
}
if c.Deleted {
panic("notes: comment deleted")
}
commentExpected(c, baseRevision, opID)
c.Deleted = true
c.Anchor = nil
c.Body = nil
commentReceipt(c, who, opID)
historyCommentChange(n, c, "comment-delete")
}
func ResolveComment(cur realm, id, cid [16]byte, baseRevision uint64, resolved bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateResolveComment(cur, who, id, cid, baseRevision, resolved, opID)
}
func mutateResolveComment(cur realm, who address, id, cid [16]byte, baseRevision uint64, resolved bool, opID [16]byte) {
n := live(id)
requireWrite(cur, n, who)
c := getComment(id, cid)
commentExpected(c, baseRevision, opID)
c.Resolved = resolved
commentReceipt(c, who, opID)
historyCommentChange(n, c, "comment-resolution")
}
func HideComment(cur realm, id, cid [16]byte, baseRevision uint64, hidden bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateHideComment(cur, who, id, cid, baseRevision, hidden, opID)
}
func mutateHideComment(cur realm, who address, id, cid [16]byte, baseRevision uint64, hidden bool, opID [16]byte) {
n := live(id)
if who != n.Owner && !moderator(who) {
panic("notes: owner required or moderator")
}
c := getComment(id, cid)
commentExpected(c, baseRevision, opID)
if v, ok := historyComments.Get(commentKey(id, cid)); ok && !hidden && v.(*historyComment).Redacted {
panic("notes: comment redacted")
}
c.Hidden = hidden
commentReceipt(c, who, opID)
historyCommentChange(n, c, "comment-visibility")
}
func commentJSON(c *comment) string {
return `{"id":` + q(idText(c.ID)) + `,"parent":` + q(idText(c.Parent)) + `,"author":` + q(string(c.Author)) + `,"encrypted":` + strconv.FormatBool(c.Encrypted) + `,"body_revision":` + u(c.BodyRevision) + `,"epoch":` + u(uint64(c.Epoch)) + `,"revision":` + u(c.Revision) + `,"anchor_blob":` + blob(c.Anchor) + `,"body_blob":` + blob(c.Body) + `,"created_height":` + q(strconv.FormatInt(c.CreatedHeight, 10)) + `,"op_id":` + q(idText(c.Last.Operation)) + `,"actor":` + q(string(c.Last.Actor)) + `,"height":` + q(strconv.FormatInt(c.Last.Height, 10)) + `,"deleted":` + strconv.FormatBool(c.Deleted) + `,"hidden":` + strconv.FormatBool(c.Hidden) + `,"resolved":` + strconv.FormatBool(c.Resolved) + `}`
}
func CommentJSON(idHex, cidHex string) string {
v, ok := comments.Get(commentKey(readID(idHex), readID(cidHex)))
if !ok {
return "null"
}
return commentJSON(v.(*comment))
}
// Comments paginate in append order; editing or moderation never reorders them.
func CommentsJSON(idHex, cursor string, limit int) string {
id := readID(idHex)
find(id)
if limit < 1 || limit > MaxCommentPage {
panic("notes: page limit")
}
if cursor != "" {
if len(cursor) != 53 || cursor[20] != ':' {
panic("notes: bad cursor")
}
readID(cursor[21:])
for _, c := range cursor[:20] {
if c < '0' || c > '9' {
panic("notes: bad cursor")
}
}
}
prefix := idText(id) + ":"
start := prefix + cursor
items := []string{}
next := ""
commentIndex.Iterate(start, prefix+"\xff", func(k string, v interface{}) bool {
if cursor != "" && k == start {
return false
}
cv, ok := comments.Get(v.(string))
if !ok {
panic("notes: corrupt comment index")
}
items = append(items, commentJSON(cv.(*comment)))
next = strings.TrimPrefix(k, prefix)
return len(items) == limit
})
if len(items) < limit {
next = ""
}
return `{"items":[` + strings.Join(items, ",") + `],"next_cursor":` + q(next) + `}`
}
// Purge never operates on a live note. Each call erases at most limit records
// (including cooldowns); a permanent note tombstone prevents ID reuse.
func Purge(cur realm, id [16]byte, limit int) int {
who := enter(cur, false)
defer leave()
return mutatePurge(cur, who, id, limit)
}
func mutatePurge(cur realm, who address, id [16]byte, limit int) int {
n := find(id)
owner(n, who)
if !n.Deleted {
panic("notes: delete before purge")
}
if limit < 1 || limit > MaxPage {
panic("notes: purge limit")
}
counts := [5]int{}
counts[0] = purgePrefix(commentIndex, idText(id)+":", limit)
counts[1] = purgePrefix(comments, idText(id)+":", limit-counts[0])
counts[2] = purgePrefix(cooldowns, idText(id)+":", limit-counts[0]-counts[1])
counts[3] = purgePrefix(epochs, idText(id)+":", limit-counts[0]-counts[1]-counts[2])
counts[4] = purgeRequests(n, limit-counts[0]-counts[1]-counts[2]-counts[3])
historyCleanup(n, who, counts)
return counts[0]+counts[1]+counts[2]+counts[3]+counts[4]
}
func purgePrefix(tree *avl.Tree, prefix string, limit int) int {
if limit == 0 {
return 0
}
doomed := []string{}
tree.Iterate(prefix, prefix+"\xff", func(k string, v interface{}) bool { doomed = append(doomed, k); return len(doomed) == limit })
for _, k := range doomed {
tree.Remove(k)
}
return len(doomed)
}
crypto.gno
package memba_notes_rc1
import (
"bytes"
"chain/runtime"
"crypto/bech32"
"crypto/sha256"
"encoding/binary"
keys "gno.land/r/samcrew/enckeys_v1"
"strconv"
)
const ManifestEntryBytes = 1299
const MaxManifestBytes = 2 + MaxReaders*ManifestEntryBytes
const MaxCipherCommentBytes = 5687
type recipient struct {
Who address
Writer bool
Generation uint64
}
func encrypted(mode uint8) bool { return mode <= ModeLink }
func contains(addrs []address, who address) bool {
for _, a := range addrs {
if a == who {
return true
}
}
return false
}
func parseManifest(data []byte, epoch uint32, owner address, mode uint8) []recipient {
return parseManifestFor(data, epoch, owner, mode, "")
}
// A self refresh checks the new caller identity while preserving every other
// already-stored envelope, including revoked or superseded identities.
func parseManifestFor(data []byte, epoch uint32, owner address, mode uint8, currentOnly address) []recipient {
if len(data) < 2 || len(data) > MaxManifestBytes || data[0] != 1 || data[1] < 1 || data[1] > MaxReaders || len(data) != 2+int(data[1])*ManifestEntryBytes {
panic("notes: manifest header/length")
}
result := []recipient{}
previous := []byte(nil)
hasOwner := false
hasWriter := false
for i := 0; i < int(data[1]); i++ {
off := 2 + i*ManifestEntryBytes
raw := data[off : off+20]
if i > 0 && bytes.Compare(raw, previous) <= 0 || data[off+20] > 1 {
panic("notes: manifest order/role")
}
previous = raw
encoded, err := bech32.EncodeFromBase256("g", raw)
if err != nil {
panic("notes: recipient address")
}
who := address(encoded)
generation := binary.BigEndian.Uint64(data[off+21 : off+29])
if generation == 0 {
panic("notes: zero identity generation")
}
wr := off + 61
if data[wr] != 1 || data[wr+1] != 1 || binary.BigEndian.Uint32(data[wr+2:wr+6]) != epoch {
panic("notes: wrap suite/epoch")
}
if binary.BigEndian.Uint64(data[wr+6:wr+14]) != generation || !bytes.Equal(data[off+29:off+61], data[wr+14:wr+46]) {
panic("notes: wrap identity mismatch")
}
if currentOnly == "" || currentOnly == who {
pk, gen, active := keys.GetKey(who, keys.SuiteXWingV1)
if !active || gen != generation {
panic("notes: recipient key inactive/stale")
}
hash := sha256.Sum256(pk)
if !bytes.Equal(hash[:], data[off+29:off+61]) {
panic("notes: recipient public key hash")
}
}
isWriter := data[off+20] == 1
if isWriter {
hasWriter = true
}
if who == owner {
if !isWriter {
panic("notes: owner must write")
}
hasOwner = true
}
if mode == ModeLink && !isWriter {
panic("notes: link wraps are for writers")
}
result = append(result, recipient{who, isWriter, generation})
}
if owner != "" && (!hasOwner || !hasWriter) || mode == ModePrivate && (len(result) != 1 || owner == "") {
panic("notes: missing owner/private readers")
}
return result
}
func validateCipher(blob []byte, epoch uint32, field uint8, revision uint64, cap int) {
if len(blob) < 59 || len(blob) > cap || blob[0] != 1 || blob[1] != 1 || binary.BigEndian.Uint32(blob[2:6]) != epoch || blob[6] != field || binary.BigEndian.Uint64(blob[7:15]) != revision {
panic("notes: invalid cipher envelope")
}
}
func validateCommitment(kc []byte) {
if len(kc) != 32 || bytes.Equal(kc, make([]byte, 32)) {
panic("notes: invalid epoch commitment")
}
}
func appendText(b []byte, s string) []byte {
size := make([]byte, 4)
binary.BigEndian.PutUint32(size, uint32(len(s)))
b = append(b, size...)
return append(b, []byte(s)...)
}
func epochCommitment(id [16]byte, epoch uint32, key []byte) []byte {
b := appendText(nil, "memba-notes/v1/epoch-commitment")
b = appendText(b, runtime.ChainID())
b = appendText(b, RealmPath)
b = append(b, id[:]...)
ep := make([]byte, 4)
binary.BigEndian.PutUint32(ep, epoch)
b = append(b, ep...)
b = append(b, key...)
h := sha256.Sum256(b)
return h[:]
}
func manifestAddress(raw []byte) address {
s, err := bech32.EncodeFromBase256("g", raw)
if err != nil {
panic("notes: manifest address")
}
return address(s)
}
func canonicalRecipient(who address) address { return keys.CanonicalAddress(who) }
func wrapJSON(entry []byte, epoch uint32, who address) string {
return `{"address":` + q(string(who)) + `,"epoch":` + u(uint64(epoch)) + `,"writer":` + strconv.FormatBool(entry[20] == 1) + `,"generation":` + u(binary.BigEndian.Uint64(entry[21:29])) + `,"public_key_hash":` + blob(entry[29:61]) + `,"wrap":` + blob(entry[61:]) + `}`
}
epochs.gno
package memba_notes_rc1
import (
"bytes"
"gno.land/p/samcrew/avl"
"strconv"
"strings"
)
type epochRecord struct {
Epoch uint32
Manifest, Commitment, RevealedKey []byte
}
var epochs = avl.NewTree()
func epochKey(id [16]byte, epoch uint32) string {
s := strconv.FormatUint(uint64(epoch), 10)
return idText(id) + ":" + strings.Repeat("0", 10-len(s)) + s
}
func getEpoch(id [16]byte, epoch uint32) *epochRecord {
v, ok := epochs.Get(epochKey(id, epoch))
if !ok {
panic("notes: epoch missing")
}
return v.(*epochRecord)
}
func privateWritable(n *note) {
if encrypted(n.Mode) && len(getEpoch(n.ID, n.Epoch).RevealedKey) != 0 {
panic("notes: revealed epoch requires rotation")
}
}
func setRecipients(n *note, list []recipient) {
n.Readers = nil
n.Writers = nil
for _, r := range list {
n.Readers = append(n.Readers, r.Who)
if r.Writer && r.Who != n.Owner {
n.Writers = append(n.Writers, r.Who)
}
}
}
func initializeEncrypted(n *note, access, kc []byte) {
validateCommitment(kc)
list := parseManifest(access, 1, n.Owner, n.Mode)
validateCipher(n.Title, 1, 1, 1, MaxCipherTitleBytes)
validateCipher(n.Body, 1, 2, 1, MaxCipherBodyBytes)
n.Epoch = 1
n.Commitment = copied(kc)
setRecipients(n, list)
epochs.Set(epochKey(n.ID, 1), &epochRecord{Epoch: 1, Manifest: copied(access), Commitment: copied(kc)})
}
// Rotate installs the entire next epoch in one transaction. Historical epoch
// records stay available until Delete+boundedPurge; rotation never scans them.
func Rotate(cur realm, id [16]byte, baseRevision uint64, expectedEpoch uint32, mode uint8, title, body, manifest, kc []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateRotate(cur, who, id, baseRevision, expectedEpoch, mode, title, body, manifest, kc, opID)
}
func mutateRotate(cur realm, who address, id [16]byte, baseRevision uint64, expectedEpoch uint32, mode uint8, title, body, manifest, kc []byte, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if !encrypted(n.Mode) || !encrypted(mode) {
panic("notes: encrypted rotation required")
}
if expectedEpoch != n.Epoch || n.Epoch == ^uint32(0) {
panic("notes: stale/exhausted epoch")
}
if n.TitleRevision == ^uint64(0) || n.BodyRevision == ^uint64(0) {
panic("notes: field revision exhausted")
}
ep := n.Epoch + 1
validateCommitment(kc)
if bytes.Equal(kc, n.Commitment) {
panic("notes: fresh epoch commitment required")
}
list := parseManifest(manifest, ep, manifestOwner(n), mode)
validateCipher(title, ep, 1, n.TitleRevision+1, MaxCipherTitleBytes)
validateCipher(body, ep, 2, n.BodyRevision+1, MaxCipherBodyBytes)
operation(n, opID)
unindex(n)
n.Mode = mode
n.Epoch = ep
n.Title = copied(title)
n.Body = copied(body)
n.BodyBytes = len(body)
n.TitleRevision++
n.BodyRevision++
n.Commitment = copied(kc)
n.PendingOwner = ""
setRecipients(n, list)
index(n)
epochs.Set(epochKey(id, ep), &epochRecord{Epoch: ep, Manifest: copied(manifest), Commitment: copied(kc)})
acknowledgeRequests(n, who, opID)
bump(n, who, opID, "rotate")
}
// ApplyAccess grants access to the CURRENT epoch and its history. Removing a
// reader/writer or changing link scope requires Rotate, never this entrypoint.
func ApplyAccess(cur realm, id [16]byte, baseRevision uint64, expectedEpoch uint32, mode uint8, manifest []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateApplyAccess(cur, who, id, baseRevision, expectedEpoch, mode, manifest, opID)
}
func mutateApplyAccess(cur realm, who address, id [16]byte, baseRevision uint64, expectedEpoch uint32, mode uint8, manifest []byte, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
privateWritable(n)
if !encrypted(n.Mode) || expectedEpoch != n.Epoch || !(mode == n.Mode || n.Mode == ModePrivate && mode == ModeShared) {
panic("notes: access transition requires rotation")
}
list := parseManifest(manifest, n.Epoch, manifestOwner(n), mode)
for _, a := range n.Readers {
found := false
for _, r := range list {
if r.Who == a {
found = true
if writer(n, a) && !r.Writer {
panic("notes: writer removal requires rotation")
}
}
}
if !found {
panic("notes: reader removal requires rotation")
}
}
operation(n, opID)
unindex(n)
n.Mode = mode
setRecipients(n, list)
index(n)
getEpoch(id, n.Epoch).Manifest = copied(manifest)
acknowledgeRequests(n, who, opID)
bump(n, who, opID, "access")
}
func Publish(cur realm, id [16]byte, baseRevision uint64, mode uint8, title, body []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutatePublish(cur, who, id, baseRevision, mode, title, body, opID)
}
func mutatePublish(cur realm, who address, id [16]byte, baseRevision uint64, mode uint8, title, body []byte, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if !encrypted(n.Mode) || !public(mode) {
panic("notes: publish transition")
}
if n.TitleRevision == ^uint64(0) || n.BodyRevision == ^uint64(0) {
panic("notes: field revision exhausted")
}
validatePublic(title, body)
operation(n, opID)
unindex(n)
n.Mode = mode
n.Title = copied(title)
n.Body = copied(body)
n.BodyBytes = len(body)
n.TitleRevision++
n.BodyRevision++
n.Listed = true
n.Readers = nil
n.Commitment = nil
n.PendingOwner = ""
index(n)
bump(n, who, opID, "publish")
}
func Reveal(cur realm, id [16]byte, baseRevision uint64, epoch uint32, key []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateReveal(cur, who, id, baseRevision, epoch, key, opID)
}
func mutateReveal(cur realm, who address, id [16]byte, baseRevision uint64, epoch uint32, key []byte, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
ep := getEpoch(id, epoch)
if len(key) != 32 || len(ep.RevealedKey) != 0 || !bytes.Equal(epochCommitment(id, epoch, key), ep.Commitment) {
panic("notes: invalid/already revealed key")
}
operation(n, opID)
ep.RevealedKey = copied(key)
bumpHistory(n, who, opID, "reveal", `,"target_epoch":` + u(uint64(epoch)))
}
func epochJSON(ep *epochRecord, withManifest bool) string {
out := `{"epoch":` + u(uint64(ep.Epoch)) + `,"commitment":` + blob(ep.Commitment) + `,"revealed_key":` + blob(ep.RevealedKey)
if withManifest {
out += `,"manifest":` + blob(ep.Manifest)
}
return out + `}`
}
func EpochJSON(idHex string, epoch uint32) string {
id := readID(idHex)
v, ok := epochs.Get(epochKey(id, epoch))
if !ok {
return "null"
}
return epochJSON(v.(*epochRecord), true)
}
func EpochsJSON(idHex string, cursor uint32, limit int) string {
id := readID(idHex)
find(id)
if limit < 1 || limit > MaxPage {
panic("notes: page limit")
}
items := []string{}
var next uint32
epochs.Iterate(epochKey(id, cursor), idText(id)+":\xff", func(k string, v interface{}) bool {
ep := v.(*epochRecord)
if ep.Epoch <= cursor {
return false
}
items = append(items, epochJSON(ep, false))
next = ep.Epoch
return len(items) == limit
})
if len(items) < limit {
next = 0
}
return `{"items":[` + strings.Join(items, ",") + `],"next_cursor":` + u(uint64(next)) + `}`
}
func ReadersJSON(idHex string) string {
n := find(readID(idHex))
out := "["
for i, a := range n.Readers {
if i > 0 {
out += ","
}
out += q(string(a))
}
return out + "]"
}
func manifestOwner(n *note) address {
if n.OwnerIsRealm {
return ""
}
return n.Owner
}
// Ownership changes do not silently revoke an existing manifest writer.
// Revocation requires the new owner to rotate; old key knowledge also remains.
func preserveTransferredWriters(n *note) {
data := getEpoch(n.ID, n.Epoch).Manifest
n.Writers = nil
for i := 0; i < int(data[1]); i++ {
off := 2 + i*ManifestEntryBytes
if data[off+20] == 1 {
who := manifestAddress(data[off : off+20])
if who != n.Owner {
n.Writers = append(n.Writers, who)
}
}
}
}
func WrapJSON(idHex string, epoch uint32, who address) string {
id := readID(idHex)
who = canonicalRecipient(who)
v, ok := epochs.Get(epochKey(id, epoch))
if !ok {
return "null"
}
data := v.(*epochRecord).Manifest
for i := 0; i < int(data[1]); i++ {
off := 2 + i*ManifestEntryBytes
if manifestAddress(data[off:off+20]) == who {
return wrapJSON(data[off:off+ManifestEntryBytes], epoch, who)
}
}
return "null"
}
// RefreshOwnWrap changes only the caller's identity envelope. It cannot change
// roles, readers, modes or epochs, and never rewrites anybody else's recovery.
func RefreshOwnWrap(cur realm, id [16]byte, baseRevision uint64, expectedEpoch uint32, manifest []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
n := live(id)
expected(n, baseRevision)
privateWritable(n)
if !cur.Previous().IsUserCall() || !encrypted(n.Mode) || expectedEpoch != n.Epoch || !contains(n.Readers, who) {
panic("notes: current reader required")
}
// A reader who accepted Shared ownership may retain a false explicit writer
// flag: ownership is implicit authority. Self-refresh preserves that flag.
manifestAccountOwner := address("")
if n.Mode == ModePrivate {
manifestAccountOwner = n.Owner
}
parseManifestFor(manifest, n.Epoch, manifestAccountOwner, n.Mode, who)
old := getEpoch(id, n.Epoch).Manifest
if len(old) != len(manifest) {
panic("notes: self refresh cannot change readers")
}
changed := false
for i := 0; i < int(old[1]); i++ {
off := 2 + i*ManifestEntryBytes
previous := old[off : off+ManifestEntryBytes]
next := manifest[off : off+ManifestEntryBytes]
if manifestAddress(previous[:20]) == who {
if string(previous[:21]) != string(next[:21]) {
panic("notes: self refresh cannot change role")
}
changed = string(previous) != string(next)
} else if string(previous) != string(next) {
panic("notes: self refresh cannot change another wrap")
}
}
if !changed {
panic("notes: wrap unchanged")
}
operation(n, opID)
getEpoch(id, n.Epoch).Manifest = copied(manifest)
bump(n, who, opID, "self-rekey")
}
getters.gno
package memba_notes_rc1
import (
"encoding/base64"
"gno.land/p/samcrew/avl"
keys "gno.land/r/samcrew/enckeys_v1"
"strconv"
"strings"
)
func q(s string) string { return strconv.Quote(s) }
func u(n uint64) string { return q(strconv.FormatUint(n, 10)) }
func blob(b []byte) string { return "\"" + base64.StdEncoding.EncodeToString(b) + "\"" }
func noteJSON(n *note, withBody bool) string {
s := `{"id":` + q(idText(n.ID)) + `,"owner":` + q(string(n.Owner)) + `,"pending_owner":` + q(string(n.PendingOwner)) + `,"owner_generation":` + u(n.OwnerGeneration) + `,"mode":` + strconv.Itoa(int(n.Mode)) + `,"state_revision":` + u(n.Revision) + `,"title_revision":` + u(n.TitleRevision) + `,"body_revision":` + u(n.BodyRevision) + `,"epoch":` + u(uint64(n.Epoch)) + `,"body_bytes":` + q(strconv.Itoa(n.BodyBytes)) + `,"title_blob":` + blob(n.Title) + `,"commitment":` + blob(n.Commitment) + `,"deleted":` + strconv.FormatBool(n.Deleted) + `,"listed":` + strconv.FormatBool(n.Listed && !n.ModeratorHidden) + `,"owner_listed":` + strconv.FormatBool(n.Listed) + `,"moderator_hidden":` + strconv.FormatBool(n.ModeratorHidden) + `,"created_height":` + q(strconv.FormatInt(n.CreatedHeight, 10)) + `,"op_id":` + q(idText(n.Last.Operation)) + `,"executor":` + q(string(n.LastExecutor)) + `,"gov_writers":` + strconv.FormatBool(n.GovWriters) + `,"actor":` + q(string(n.Last.Actor)) + `,"height":` + q(strconv.FormatInt(n.Last.Height, 10))
if withBody {
s += `,"body_blob":` + blob(n.Body)
}
return s + `}`
}
func NoteJSON(idHex string) string {
v, ok := notes.Get(idText(readID(idHex)))
if !ok {
return "null"
}
return noteJSON(v.(*note), true)
}
func page(tree *avl.Tree, prefix, cursor string, limit int) string {
if limit < 1 || limit > MaxPage {
panic("notes: page limit")
}
if len(cursor) > 53 {
panic("notes: cursor length")
}
if cursor != "" {
if len(cursor) != 53 || cursor[20] != ':' {
panic("notes: bad cursor")
}
readID(cursor[21:])
for _, c := range cursor[:20] {
if c < '0' || c > '9' {
panic("notes: bad cursor")
}
}
}
end := prefix + "\xff"
if cursor != "" {
end = prefix + cursor
}
items := []string{}
next := ""
tree.ReverseIterate(prefix, end, func(key string, value interface{}) bool {
if cursor != "" && key == end {
return false
}
v, ok := notes.Get(value.(string))
if !ok {
panic("notes: corrupt index")
}
items = append(items, noteJSON(v.(*note), false))
next = strings.TrimPrefix(key, prefix)
return len(items) == limit
})
if len(items) < limit {
next = ""
}
return `{"items":[` + strings.Join(items, ",") + `],"next_cursor":` + q(next) + `}`
}
func ListByOwnerJSON(addr address, cursor string, limit int) string {
return page(ownerIndex, string(keys.CanonicalAddress(addr))+":", cursor, limit)
}
func ListPublicJSON(cursor string, limit int) string { return page(publicIndex, "", cursor, limit) }
func ConfigJSON() string {
return `{"realm":` + q(RealmPath) + `,"admin":` + q(string(admin)) + `,"pending_admin":` + q(string(pendingAdmin)) + `,"treasury":` + q(string(treasury)) + `,"create_fee_ugnot":` + q(strconv.FormatInt(createFee, 10)) + `,"paused":` + strconv.FormatBool(paused) + `}`
}
gnomod.toml
module = "gno.land/r/samcrew/memba_notes_rc1" gno = "0.9" [addpkg] creator = "g136j0m08pkm2lwwde9dmlx8uee26llent9s5cpf" height = 398276 max_deposit = "25000000ugnot"
gov.gno
package memba_notes_rc1
import (
"chain"
"chain/runtime"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"gno.land/p/samcrew/daoauth"
gov "gno.land/r/samcrew/memba_gov"
"strconv"
)
const GovRealmPath = "gno.land/r/samcrew/memba_gov"
var govAddress = chain.PackageAddress(GovRealmPath)
func govMember(who address) bool { return gov.IsMember(who) }
func SetGovWriters(cur realm, id [16]byte, baseRevision uint64, on bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateSetGovWriters(cur, who, id, baseRevision, on, opID)
}
func mutateSetGovWriters(cur realm, who address, id [16]byte, baseRevision uint64, on bool, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if n.Owner != govAddress {
panic("notes: gov owner required")
}
operation(n, opID)
n.GovWriters = on
bump(n, who, opID, "gov-writers")
}
func validGovAction(action string) bool {
switch action {
case "AcceptOwnership", "Commit", "Rename", "Rotate", "ApplyAccess", "Publish", "Reveal", "Delete", "AddWriter", "RemoveWriter", "ProposeOwner", "SetPolicy", "SetCommentMode", "SetPublicWrites", "SetListed", "ModerateListing", "SetGovWriters", "HideComment", "ResolveComment", "RejectAccessRequest", "Purge":
return true
}
return false
}
// The typed payload is bounded and hashed as bytes, including its version.
// Every precondition and opID is domain-bound; no raw large/Unicode content is
// put in daoauth's 1024-byte printable-ASCII argument envelope.
func govDigest(n *note, baseRevision, ownerGeneration uint64, expectedEpoch uint32, action string, payload []byte, opID [16]byte) string {
if !validGovAction(action) || len(payload) < 1 || len(payload) > MaxGovPayloadBytes {
panic("notes: unknown/oversize gov operation")
}
b := appendText(nil, "memba-notes/v1/gov-operation")
b = appendText(b, runtime.ChainID())
b = appendText(b, RealmPath)
b = append(b, n.ID[:]...)
number := make([]byte, 8)
binary.BigEndian.PutUint64(number, ownerGeneration)
b = append(b, number...)
binary.BigEndian.PutUint64(number, baseRevision)
b = append(b, number...)
ep := make([]byte, 4)
binary.BigEndian.PutUint32(ep, expectedEpoch)
b = append(b, ep...)
b = append(b, n.Mode)
b = appendText(b, string(n.Owner))
b = appendText(b, string(n.PendingOwner))
b = appendText(b, string(n.Commitment))
b = appendText(b, action)
hash := sha256.Sum256(payload)
b = append(b, hash[:]...)
b = append(b, opID[:]...)
digest := sha256.Sum256(b)
return hex.EncodeToString(digest[:])
}
func GovDigest(idHex string, baseRevision, ownerGeneration uint64, expectedEpoch uint32, action string, payload []byte, opID [16]byte) string {
return govDigest(find(readID(idHex)), baseRevision, ownerGeneration, expectedEpoch, action, payload, opID)
}
func GovApply(cur realm, pid uint64, id [16]byte, baseRevision, ownerGeneration uint64, expectedEpoch uint32, action string, payload []byte, opID [16]byte) {
executor := enter(cur, false)
defer leave()
if !cur.Previous().IsUserCall() {
panic("notes: direct governance executor required")
}
operation(nil, opID)
n := find(id)
expected(n, baseRevision)
if ownerGeneration != n.OwnerGeneration || expectedEpoch != n.Epoch {
panic("notes: stale governance generation/epoch")
}
if action == "AcceptOwnership" {
if n.PendingOwner != govAddress {
panic("notes: pending gov owner required")
}
} else if n.Owner != govAddress && !((action == "ModerateListing" || action == "HideComment") && moderator(govAddress)) {
panic("notes: gov owner required")
}
digest := govDigest(n, baseRevision, ownerGeneration, expectedEpoch, action, payload, opID)
// Failure in dispatch also rolls back Consume in the same transaction.
gov.Consume(cross(cur), pid, "notes."+action, daoauth.New().Str(digest).String(), "note:"+idText(id), gov.Routine, executor)
historyGov = &historyCall{executor, pid, opID, action}
defer func() { historyGov = nil }()
dispatchGov(cur, n, baseRevision, expectedEpoch, action, payload, opID)
if n.Revision > baseRevision && n.Last.Operation == opID {
n.LastExecutor = executor
}
chain.Emit("NoteGoverned", "id", idText(id), "action", action, "pid", strconv.FormatUint(pid, 10), "executor", string(executor), "op_id", idText(opID))
}
func dispatchGov(cur realm, n *note, rev uint64, epoch uint32, action string, payload []byte, op [16]byte) {
r := payloadReader(payload)
id := n.ID
who := govAddress
switch action {
case "AcceptOwnership":
r.done()
mutateAcceptOwnership(cur, who, id, rev, op)
case "Commit":
mask := r.byte()
title := r.blob(MaxCipherTitleBytes)
body := r.blob(MaxCipherBodyBytes)
r.done()
mutateCommit(cur, who, id, rev, epoch, mask, title, body, op)
case "Rename":
title := r.blob(MaxCipherTitleBytes)
r.done()
mutateCommit(cur, who, id, rev, epoch, 1, title, nil, op)
case "Rotate":
mode := r.byte()
title := r.blob(MaxCipherTitleBytes)
body := r.blob(MaxCipherBodyBytes)
manifest := r.blob(MaxManifestBytes)
kc := r.blob(32)
r.done()
mutateRotate(cur, who, id, rev, epoch, mode, title, body, manifest, kc, op)
case "ApplyAccess":
mode := r.byte()
manifest := r.blob(MaxManifestBytes)
r.done()
mutateApplyAccess(cur, who, id, rev, epoch, mode, manifest, op)
case "Publish":
mode := r.byte()
title := r.blob(MaxTitleBytes)
body := r.blob(MaxBodyBytes)
r.done()
mutatePublish(cur, who, id, rev, mode, title, body, op)
case "Reveal":
ep := r.u32()
key := r.take(32)
r.done()
mutateReveal(cur, who, id, rev, ep, key, op)
case "Delete":
r.done()
mutateDelete(cur, who, id, rev, op)
case "AddWriter", "RemoveWriter", "ProposeOwner":
to := address(string(r.blob(90)))
r.done()
if action == "AddWriter" {
mutateAddWriter(cur, who, id, rev, to, op)
} else if action == "RemoveWriter" {
mutateRemoveWriter(cur, who, id, rev, to, op)
} else {
mutateProposeOwner(cur, who, id, rev, to, op)
}
case "SetPolicy":
kind := r.byte()
key := string(r.blob(233))
r.done()
mutateSetPolicy(cur, who, id, rev, kind, key, op)
case "SetPublicWrites":
on := r.boolean()
r.done()
mutateSetPublicWrites(cur, who, id, rev, on, op)
case "SetCommentMode":
on := r.boolean()
r.done()
mutateSetCommentMode(cur, who, id, rev, on, op)
case "SetListed":
on := r.boolean()
r.done()
mutateSetListed(cur, who, id, rev, on, op)
case "ModerateListing":
on := r.boolean()
r.done()
mutateModerateListing(cur, who, id, rev, on, op)
case "SetGovWriters":
on := r.boolean()
r.done()
mutateSetGovWriters(cur, who, id, rev, on, op)
case "HideComment", "ResolveComment":
cid := r.id()
commentRev := r.u64()
on := r.boolean()
r.done()
if action == "HideComment" {
mutateHideComment(cur, who, id, cid, commentRev, on, op)
} else {
mutateResolveComment(cur, who, id, cid, commentRev, on, op)
}
case "RejectAccessRequest":
to := address(string(r.blob(90)))
priorOp := r.id()
r.done()
v, ok := requests.Get(requestKey(id, to))
if !ok || v.(*accessRequest).Last.Operation != priorOp {
panic("notes: stale request approval")
}
mutateRejectAccessRequest(cur, who, id, to, op)
case "Purge":
limit := r.byte()
r.done()
mutatePurge(cur, who, id, int(limit))
default:
panic("notes: unknown governance action")
}
}
gov_codec.gno
package memba_notes_rc1
import (
"encoding/binary"
)
const MaxGovPayloadBytes = MaxCipherTitleBytes + MaxCipherBodyBytes + MaxManifestBytes + 128
type govReader struct {
bytes []byte
pos int
}
func payloadReader(payload []byte) *govReader {
if len(payload) < 1 || len(payload) > MaxGovPayloadBytes || payload[0] != 1 {
panic("notes: gov payload format")
}
return &govReader{payload, 1}
}
func (r *govReader) take(n int) []byte {
if n < 0 || n > len(r.bytes)-r.pos {
panic("notes: gov payload truncated")
}
b := r.bytes[r.pos : r.pos+n]
r.pos += n
return b
}
func (r *govReader) byte() uint8 { return r.take(1)[0] }
func (r *govReader) boolean() bool {
v := r.byte()
if v > 1 {
panic("notes: gov bool")
}
return v == 1
}
func (r *govReader) u64() uint64 { return binary.BigEndian.Uint64(r.take(8)) }
func (r *govReader) u32() uint32 { return binary.BigEndian.Uint32(r.take(4)) }
func (r *govReader) id() [16]byte { var v [16]byte; copy(v[:], r.take(16)); return v }
func (r *govReader) blob(cap int) []byte {
n := r.u32()
if n > uint32(cap) {
panic("notes: gov field cap")
}
return r.take(int(n))
}
func (r *govReader) done() {
if r.pos != len(r.bytes) {
panic("notes: gov trailing bytes")
}
}
history.gno
package memba_notes_rc1
import (
"chain/runtime"
"crypto/sha256"
"encoding/hex"
"gno.land/p/samcrew/avl"
"strconv"
"strings"
)
// Bytes shares the note's committed array: fields are replaced, never mutated in
// place, so history stores each version once and a later commit frees nothing
// another account paid for. A moderator redaction clears Bytes and keeps Hash.
type historyBlob struct {
Bytes []byte
Hash string
Redacted bool
}
// historyVersion is the public state recorded by one note-level event. It keeps
// only what the public history reads expose, never a copy of the live note: no
// private manifest, readers, commitment or receipts. Versions that leave a field
// unchanged share that field's blob.
type historyVersion struct {
Revision, TitleRevision, BodyRevision, OwnerGeneration uint64
Owner, PendingOwner address
Writers []address
PolicyRead, PolicyWrite, PolicyComment string
Epoch uint32
Mode uint8
OwnerIsRealm, GovWriters, Listed, ModeratorHidden bool
Deleted, PublicWrites bool
Title, Body *historyBlob
}
// historyInfo is kept on the public note itself (note.History); the note record
// is retained forever as a tombstone, so it needs no index of its own.
type historyInfo struct {
StartRevision, StartBodyRevision, Head uint64
Latest *historyVersion
}
// One record per event. Operation and Comment hold the raw 16-byte ids ("" for
// none). Version is set on note-level events only; comment and cleanup events
// reuse the current state revision and record no version.
type historyEntry struct {
Seq, Revision, Proposal uint64
Height int64
Actor, Executor address
Operation, Comment string
Action, GovernanceAction, Detail string
Version *historyVersion
}
// historyComment keeps the first public version of a comment (Parent to Body,
// Parent as a raw id or "") and its latest presentation. Anchor and Body share
// the live comment's arrays, so a comment's text is stored once.
type historyComment struct {
Parent string
Author address
BodyRevision uint64
Epoch uint32
CreatedHeight int64
Anchor, Body []byte
AnchorHistory, ParentHistory bool
LatestSeq uint64
Deleted, Hidden, Resolved bool
Redacted bool
}
type historyCall struct {
Executor address
Proposal uint64
Operation [16]byte
Action string
}
var historyEntries = avl.NewTree()
var historyComments = avl.NewTree()
// Only GovApply sets this while the existing busy guard excludes reentry.
var historyGov *historyCall
func historyKey(id [16]byte, seq uint64) string {
s := strconv.FormatUint(seq, 10)
return idText(id) + ":" + strings.Repeat("0", 20-len(s)) + s
}
func historyID(text string) [16]byte {
id := readID(text)
if id == ([16]byte{}) {
panic("notes: empty history id")
}
return id
}
func historyGet(id [16]byte) *historyInfo {
v, ok := notes.Get(idText(id))
if !ok {
return nil
}
return v.(*note).History
}
func historyEntryAt(id [16]byte, seq uint64) *historyEntry {
v, ok := historyEntries.Get(historyKey(id, seq))
if !ok {
panic("notes: history gap")
}
return v.(*historyEntry)
}
// historyVersionAt returns the version recorded by the event with this seq, or
// nil when there is no such event or it is a comment/cleanup event.
func historyVersionAt(id [16]byte, seq uint64) *historyVersion {
v, ok := historyEntries.Get(historyKey(id, seq))
if !ok {
return nil
}
return v.(*historyEntry).Version
}
// historyRevisionEntry finds the note-level event of a public state revision
// without an index. Entries are contiguous from seq 1 and their state revision
// never decreases; each state revision since publication is recorded by exactly
// one note-level event, the first entry carrying it.
func historyRevisionEntry(id [16]byte, h *historyInfo, revision uint64) *historyEntry {
if revision < h.StartRevision || revision > h.Latest.Revision {
return nil
}
lo, hi := uint64(1), h.Head
for lo < hi {
mid := lo + (hi-lo)/2
if historyEntryAt(id, mid).Revision < revision {
lo = mid + 1
} else {
hi = mid
}
}
e := historyEntryAt(id, lo)
if e.Revision != revision || e.Version == nil {
panic("notes: corrupt history")
}
return e
}
func historyBlobOf(data []byte) *historyBlob {
hash := sha256.Sum256(data)
return &historyBlob{Bytes: data, Hash: hex.EncodeToString(hash[:])}
}
func rawID(id [16]byte) string {
if id == ([16]byte{}) {
return ""
}
return string(id[:])
}
func historyNullableRaw(raw string) string {
if raw == "" {
return "null"
}
return q(hex.EncodeToString([]byte(raw)))
}
func historyAppend(n *note, who address, op, cid [16]byte, action, detail string) *historyEntry {
h := n.History
if h == nil || h.Head == ^uint64(0) {
panic("notes: history unavailable/exhausted")
}
h.Head++
e := &historyEntry{Seq: h.Head, Revision: n.Revision, Height: runtime.ChainHeight(), Actor: who, Operation: rawID(op), Comment: rawID(cid), Action: action, Detail: detail}
if historyGov != nil {
e.Executor, e.Proposal, e.GovernanceAction = historyGov.Executor, historyGov.Proposal, historyGov.Action
e.Operation = rawID(historyGov.Operation)
}
if _, exists := historyEntries.Get(historyKey(n.ID, e.Seq)); exists {
panic("notes: history collision")
}
historyEntries.Set(historyKey(n.ID, e.Seq), e)
return e
}
func historyNote(n *note, who address, op [16]byte, action, extra string) {
if !public(n.Mode) {
return
}
h := n.History
if h == nil {
if action != "create" && action != "publish" {
panic("notes: missing public history")
}
h = &historyInfo{StartRevision: n.Revision, StartBodyRevision: n.BodyRevision}
n.History = h
}
previous := "null"
mask := 0
if h.Latest != nil {
previous = u(h.Latest.Revision)
if n.TitleRevision != h.Latest.TitleRevision {
mask |= 1
}
if n.BodyRevision != h.Latest.BodyRevision {
mask |= 2
}
}
switch action {
case "commit":
action = "content-commit"
extra = `,"field_mask":` + strconv.Itoa(mask)
case "comments-mode":
action = "comment-mode"
case "policy":
action = "policy-set"
case "listing":
action = "owner-listing"
case "moderate-listing":
action = "listing-moderation"
case "delete":
action = "note-delete"
case "reveal":
action = "legacy-epoch-reveal"
case "owner-propose":
if n.PendingOwner == "" {
action = "owner-cancel"
}
}
e := historyAppend(n, who, op, [16]byte{}, action, `{"snapshot_revision":`+u(n.Revision)+`,"previous_state_revision":`+previous+extra+`}`)
v := &historyVersion{Revision: n.Revision, TitleRevision: n.TitleRevision, BodyRevision: n.BodyRevision, OwnerGeneration: n.OwnerGeneration,
Owner: n.Owner, PendingOwner: n.PendingOwner, Writers: historyWriters(h.Latest, n.Writers),
PolicyRead: n.Policies[0], PolicyWrite: n.Policies[1], PolicyComment: n.Policies[2], Epoch: n.Epoch, Mode: n.Mode,
OwnerIsRealm: n.OwnerIsRealm, GovWriters: n.GovWriters, Listed: n.Listed, ModeratorHidden: n.ModeratorHidden,
Deleted: n.Deleted, PublicWrites: publicWritesEnabled(n)}
if !n.Deleted {
if h.Latest != nil && h.Latest.TitleRevision == n.TitleRevision {
v.Title = h.Latest.Title
} else {
v.Title = historyBlobOf(n.Title)
}
if h.Latest != nil && h.Latest.BodyRevision == n.BodyRevision {
v.Body = h.Latest.Body
} else {
v.Body = historyBlobOf(n.Body)
}
}
e.Version = v
h.Latest = v
}
// historyWriters shares the previous version's writer list while it is
// unchanged. Recorded lists are never mutated, and the live list is never
// shared: a changed list is copied, since RemoveWriter edits it in place.
func historyWriters(latest *historyVersion, writers []address) []address {
if latest != nil && len(latest.Writers) == len(writers) {
same := true
for i, who := range writers {
if latest.Writers[i] != who {
same = false
break
}
}
if same {
return latest.Writers
}
}
return copiedAddresses(writers)
}
func historyNullableText(s string) string {
if s == "" {
return "null"
}
return q(s)
}
// historyCommentDetail renders a comment reference; cid is the hex id and parent
// the raw parent id ("" for a top-level comment).
func historyCommentDetail(cid, parent string, revision, bodyRevision uint64, deleted, hidden, resolved bool, archived *historyComment) string {
anchorRevision := "null"
if archived.AnchorHistory {
anchorRevision = u(bodyRevision)
}
return `{"comment_id":` + q(cid) + `,"comment_revision":` + u(revision) + `,"content_ref":` + q(cid) + `,"body_revision":` + u(bodyRevision) + `,"anchor_history_body_revision":` + anchorRevision + `,"parent":` + historyNullableRaw(parent) + `,"parent_history_available":` + strconv.FormatBool(archived.ParentHistory) + `,"deleted":` + strconv.FormatBool(deleted) + `,"hidden":` + strconv.FormatBool(hidden) + `,"resolved":` + strconv.FormatBool(resolved) + `}`
}
func historyCommentChange(n *note, c *comment, action string) {
if !public(n.Mode) || c.Encrypted {
return
}
key := commentKey(n.ID, c.ID)
value, exists := historyComments.Get(key)
var archived *historyComment
if action == "comment-add" {
if exists {
panic("notes: comment history collision")
}
h := n.History
if h == nil {
panic("notes: missing public history")
}
// Every body revision since publication is recorded, so the anchored
// version is in public history exactly when it is not older than that.
anchor := c.BodyRevision >= h.StartBodyRevision
_, parent := historyComments.Get(commentKey(n.ID, c.Parent))
// Anchor and Body share the comment's arrays for the same single-copy reason.
archived = &historyComment{Parent: rawID(c.Parent), Author: c.Author, BodyRevision: c.BodyRevision, Epoch: c.Epoch, CreatedHeight: c.CreatedHeight,
Anchor: c.Anchor, Body: c.Body, AnchorHistory: anchor, ParentHistory: parent}
historyComments.Set(key, archived)
} else {
if !exists {
panic("notes: missing public comment history")
}
archived = value.(*historyComment)
}
e := historyAppend(n, c.Last.Actor, c.Last.Operation, c.ID, action, historyCommentDetail(idText(c.ID), rawID(c.Parent), c.Revision, c.BodyRevision, c.Deleted, c.Hidden, c.Resolved, archived))
archived.LatestSeq, archived.Deleted, archived.Hidden, archived.Resolved = e.Seq, c.Deleted, c.Hidden, c.Resolved
}
func historyCleanup(n *note, who address, counts [5]int) {
if !public(n.Mode) {
return
}
total := counts[0] + counts[1] + counts[2] + counts[3] + counts[4]
if total == 0 {
return
}
detail := `{"comment_index":` + u(uint64(counts[0])) + `,"comments":` + u(uint64(counts[1])) + `,"cooldowns":` + u(uint64(counts[2])) + `,"epochs":` + u(uint64(counts[3])) + `,"requests":` + u(uint64(counts[4])) + `,"total":` + u(uint64(total)) + `}`
historyAppend(n, who, [16]byte{}, [16]byte{}, "cleanup", detail)
}
history_reads.gno
package memba_notes_rc1
import "strconv"
func PublicHistoryInfoJSON(idHex string) string {
id := historyID(idHex)
h := historyGet(id)
if h == nil {
return "null"
}
n := h.Latest
return `{"schema":"memba.notes.public-history-info/v1","id":` + q(idHex) + `,"start_state_revision":` + u(h.StartRevision) + `,"start_body_revision":` + u(h.StartBodyRevision) + `,"head_seq":` + u(h.Head) + `,"latest_state_revision":` + u(n.Revision) + `,"retention":"public-moderator-redactable","coverage":"public-since-publication-v1","deleted":` + strconv.FormatBool(n.Deleted) + `,"moderator_hidden":` + strconv.FormatBool(n.ModeratorHidden) + `}`
}
func historyEntryFields(e *historyEntry) string {
proposal := "null"
if e.Proposal != 0 {
proposal = u(e.Proposal)
}
return `"seq":` + u(e.Seq) + `,"action":` + q(e.Action) + `,"height":` + q(strconv.FormatInt(e.Height, 10)) + `,"state_revision":` + u(e.Revision) + `,"actor":` + q(string(e.Actor)) + `,"executor":` + historyNullableText(string(e.Executor)) + `,"op_id":` + historyNullableRaw(e.Operation) + `,"proposal_id":` + proposal
}
func PublicHistoryJSON(idHex string, afterSeq, throughSeq uint64, limit int) string {
id := historyID(idHex)
if limit < 1 || limit > 20 {
panic("notes: history page limit")
}
h := historyGet(id)
if h == nil {
return "null"
}
if throughSeq == 0 {
if afterSeq != 0 {
panic("notes: history first page cursor")
}
throughSeq = h.Head
}
if afterSeq > throughSeq || throughSeq > h.Head {
panic("notes: history cursor")
}
items, next := "", "null"
last, count := afterSeq, 0
// Direct keys preserve contiguity without a scan or after+limit overflow.
for last < throughSeq && count < limit {
last++
e := historyEntryAt(id, last)
if count > 0 {
items += ","
}
items += "{" + historyEntryFields(e) + `,"comment_id":` + historyNullableRaw(e.Comment) + "}"
count++
}
if last < throughSeq {
next = u(last)
}
return `{"schema":"memba.notes.public-history-page/v1","id":` + q(idHex) + `,"through_seq":` + u(throughSeq) + `,"items":[` + items + `],"next_cursor":` + next + `}`
}
func PublicHistoryEntryJSON(idHex string, seq uint64) string {
v, ok := historyEntries.Get(historyKey(historyID(idHex), seq))
if !ok {
return "null"
}
e := v.(*historyEntry)
return `{"schema":"memba.notes.public-history-entry/v1","id":` + q(idHex) + "," + historyEntryFields(e) + `,"governance_action":` + historyNullableText(e.GovernanceAction) + `,"detail":` + e.Detail + `}`
}
// PublicHistoryVersionJSON reads the public state recorded at a state revision.
// recorded_seq is the event that recorded it; PublicHistoryBodyChunkJSON and
// RedactPublicContentAtSeq address that version by this seq.
func PublicHistoryVersionJSON(idHex string, stateRevision uint64) string {
id := historyID(idHex)
h := historyGet(id)
if h == nil {
return "null"
}
e := historyRevisionEntry(id, h, stateRevision)
if e == nil {
return "null"
}
v := e.Version
titleRevision, title, bodyRevision, bodyHash, bodyBytes := "null", "null", "null", "null", "0"
titleRedacted, bodyRedacted := false, false
if v.Title != nil {
titleRevision, titleRedacted = u(v.TitleRevision), v.Title.Redacted
if !titleRedacted {
title = blob(v.Title.Bytes)
}
}
if v.Body != nil {
bodyRevision, bodyHash, bodyBytes, bodyRedacted = u(v.BodyRevision), q(v.Body.Hash), strconv.Itoa(len(v.Body.Bytes)), v.Body.Redacted
}
writers := ""
for i, who := range v.Writers {
if i > 0 {
writers += ","
}
writers += q(string(who))
}
return `{"schema":"memba.notes.public-history-version/v1","id":` + q(idHex) + `,"state_revision":` + u(v.Revision) + `,"recorded_seq":` + u(e.Seq) + `,"owner":` + q(string(v.Owner)) + `,"pending_owner":` + historyNullableText(string(v.PendingOwner)) + `,"owner_is_realm":` + strconv.FormatBool(v.OwnerIsRealm) + `,"owner_generation":` + u(v.OwnerGeneration) + `,"mode":` + strconv.Itoa(int(v.Mode)) + `,"epoch":` + u(uint64(v.Epoch)) + `,"title_revision":` + titleRevision + `,"title_blob":` + title + `,"title_redacted":` + strconv.FormatBool(titleRedacted) + `,"body_revision":` + bodyRevision + `,"body_bytes":` + q(bodyBytes) + `,"body_sha256":` + bodyHash + `,"body_redacted":` + strconv.FormatBool(bodyRedacted) + `,"writers":[` + writers + `],"policies":{"read":` + q(v.PolicyRead) + `,"write":` + q(v.PolicyWrite) + `,"comment":` + q(v.PolicyComment) + `},"gov_writers":` + strconv.FormatBool(v.GovWriters) + `,"allow_public_writes":` + strconv.FormatBool(v.PublicWrites) + `,"owner_listed":` + strconv.FormatBool(v.Listed) + `,"moderator_hidden":` + strconv.FormatBool(v.ModeratorHidden) + `,"deleted":` + strconv.FormatBool(v.Deleted) + `}`
}
// PublicHistoryBodyChunkJSON reads the body of the version recorded by the
// note-level event seq (a version's recorded_seq). A later note-level event
// that kept the body returns the same body; comment and cleanup events, deletion
// versions, unknown seqs and redacted bodies return null.
func PublicHistoryBodyChunkJSON(idHex string, seq uint64, offset, limit int) string {
id := historyID(idHex)
if limit < 1 || limit > MaxBodyChunkBytes || offset < 0 {
panic("notes: history chunk bounds")
}
v := historyVersionAt(id, seq)
if v == nil || v.Body == nil {
return "null"
}
b := v.Body
if b.Redacted {
return "null"
}
if offset > len(b.Bytes) {
panic("notes: history chunk bounds")
}
end := offset + limit
if end > len(b.Bytes) {
end = len(b.Bytes)
}
return `{"schema":"memba.notes.public-history-body/v2","id":` + q(idHex) + `,"seq":` + u(seq) + `,"body_revision":` + u(v.BodyRevision) + `,"sha256":` + q(b.Hash) + `,"offset":` + q(strconv.Itoa(offset)) + `,"total":` + q(strconv.Itoa(len(b.Bytes))) + `,"next_offset":` + q(strconv.Itoa(end)) + `,"chunk_blob":` + blob(b.Bytes[offset:end]) + `}`
}
func PublicHistoryCommentJSON(idHex, cidHex string) string {
id, cid := historyID(idHex), historyID(cidHex)
v, ok := historyComments.Get(commentKey(id, cid))
if !ok {
return "null"
}
h := v.(*historyComment)
// The reference describes the first version: revision 1, not yet deleted, hidden or resolved.
return `{"schema":"memba.notes.public-history-comment/v1","id":` + q(idHex) + `,"comment_id":` + q(cidHex) + `,"content":{"author":` + q(string(h.Author)) + `,"created_height":` + q(strconv.FormatInt(h.CreatedHeight, 10)) + `,"epoch":` + u(uint64(h.Epoch)) + `,"anchor_blob":` + blob(h.Anchor) + `,"body_blob":` + blob(h.Body) + `,"reference":` + historyCommentDetail(cidHex, h.Parent, 1, h.BodyRevision, false, false, false, h) + `},"presentation":{"latest_seq":` + u(h.LatestSeq) + `,"deleted":` + strconv.FormatBool(h.Deleted) + `,"hidden":` + strconv.FormatBool(h.Hidden) + `,"resolved":` + strconv.FormatBool(h.Resolved) + `,"redacted":` + strconv.FormatBool(h.Redacted) + `}}`
}
moderation.gno
package memba_notes_rc1
import keys "gno.land/r/samcrew/enckeys_v1"
const MaxModerators = 32
var moderators []address
func moderator(who address) bool { return who == admin || contains(moderators, who) }
func AddModerator(cur realm, to address) {
who := enter(cur, false)
defer leave()
administrator(who)
to = keys.CanonicalAddress(to)
if contains(moderators, to) {
panic("notes: moderator exists")
}
if len(moderators) >= MaxModerators {
panic("notes: moderator cap")
}
moderators = append(moderators, to)
}
func RemoveModerator(cur realm, to address) {
who := enter(cur, false)
defer leave()
administrator(who)
to = keys.CanonicalAddress(to)
for i, a := range moderators {
if a == to {
moderators = append(moderators[:i], moderators[i+1:]...)
return
}
}
panic("notes: moderator missing")
}
func ModeratorsJSON() string {
out := "["
for i, a := range moderators {
if i > 0 {
out += ","
}
out += q(string(a))
}
return out + "]"
}
// Directory moderation is separate from owner discoverability. Owners cannot
// undo a moderation hide by toggling their own listing preference.
func ModerateListing(cur realm, id [16]byte, baseRevision uint64, visible bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateModerateListing(cur, who, id, baseRevision, visible, opID)
}
func mutateModerateListing(cur realm, who address, id [16]byte, baseRevision uint64, visible bool, opID [16]byte) {
n := live(id)
if !moderator(who) {
panic("notes: moderator required")
}
expected(n, baseRevision)
if !public(n.Mode) {
panic("notes: public note required")
}
operation(n, opID)
unindex(n)
n.ModeratorHidden = !visible
index(n)
bump(n, who, opID, "moderate-listing")
}
// RedactedTitle replaces a redacted current title, which must stay valid.
const RedactedTitle = "Redacted by moderation"
// RedactPublicContentAtSeq removes one public title (field 1) or body (field 2)
// from realm storage: the one recorded by the note-level history event seq (a
// version's recorded_seq). The name carries the addressing so a caller written
// for field revisions cannot act on the wrong version. History stores each field
// revision once, so every version that kept that title or body shows it
// redacted. Public history keeps its SHA-256 and a content-redact entry naming
// the moderator and the field revision. Redacting the current version also
// replaces it (placeholder title, empty body) under a new field revision. Gno
// refunds the freed storage to the moderator who frees it.
func RedactPublicContentAtSeq(cur realm, id [16]byte, baseRevision uint64, field uint8, seq uint64, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateRedactPublicContentAtSeq(cur, who, id, baseRevision, field, seq, opID)
}
func mutateRedactPublicContentAtSeq(cur realm, who address, id [16]byte, baseRevision uint64, field uint8, seq uint64, opID [16]byte) {
n := find(id)
if !moderator(who) {
panic("notes: moderator required")
}
expected(n, baseRevision)
if !public(n.Mode) {
panic("notes: public note required")
}
if field != 1 && field != 2 {
panic("notes: bad redaction field")
}
v := historyVersionAt(n.ID, seq)
if v == nil {
panic("notes: history version missing")
}
name, b, fieldRevision := "title", v.Title, v.TitleRevision
if field == 2 {
name, b, fieldRevision = "body", v.Body, v.BodyRevision
}
if b == nil {
panic("notes: history version missing")
}
if b.Redacted {
panic("notes: already redacted")
}
operation(n, opID)
if !n.Deleted && field == 1 && fieldRevision == n.TitleRevision {
if n.TitleRevision == ^uint64(0) {
panic("notes: title revision exhausted")
}
n.Title = []byte(RedactedTitle)
n.TitleRevision++
}
if !n.Deleted && field == 2 && fieldRevision == n.BodyRevision {
if n.BodyRevision == ^uint64(0) {
panic("notes: body revision exhausted")
}
n.Body = []byte{}
n.BodyBytes = 0
n.BodyRevision++
}
b.Bytes, b.Redacted = nil, true
bumpHistory(n, who, opID, "content-redact", `,"field":`+q(name)+`,"field_revision":`+u(fieldRevision)+`,"sha256":`+q(b.Hash))
}
// RedactPublicComment removes a public comment's anchor and body from both the
// live comment (which becomes hidden and cannot be shown again) and its public
// history. A purged comment keeps only its history record, which is redacted
// the same way; baseRevision is then ignored (pass 0).
func RedactPublicComment(cur realm, id, cid [16]byte, baseRevision uint64, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateRedactPublicComment(cur, who, id, cid, baseRevision, opID)
}
func mutateRedactPublicComment(cur realm, who address, id, cid [16]byte, baseRevision uint64, opID [16]byte) {
n := find(id)
if !moderator(who) {
panic("notes: moderator required")
}
if !public(n.Mode) {
panic("notes: public note required")
}
key := commentKey(id, cid)
v, ok := historyComments.Get(key)
if !ok {
panic("notes: missing public comment history")
}
archived := v.(*historyComment)
if archived.Redacted {
panic("notes: already redacted")
}
cv, live := comments.Get(key)
if !live {
if opID == ([16]byte{}) {
panic("notes: empty operation id")
}
archived.Anchor, archived.Body, archived.Redacted = nil, nil, true
e := historyAppend(n, who, opID, cid, "comment-redact", `{"comment_id":`+q(idText(cid))+`,"purged":true}`)
archived.LatestSeq = e.Seq
return
}
c := cv.(*comment)
commentExpected(c, baseRevision, opID)
archived.Anchor, archived.Body, archived.Redacted = nil, nil, true
c.Anchor, c.Body, c.Hidden = nil, nil, true
commentReceipt(c, who, opID)
historyCommentChange(n, c, "comment-redact")
}
notes.gno
package memba_notes_rc1
import (
"chain"
"chain/banker"
"chain/runtime"
)
// CreateNote is the only payable entrypoint; encrypted creation is atomic.
func CreateNote(cur realm, id [16]byte, mode uint8, title, body, access, commitment []byte, maxFee int64, opID [16]byte) {
who := enter(cur, true)
defer leave()
if !cur.Previous().IsUserCall() {
panic("notes: create directly from your account")
}
if paused {
panic("notes: creation paused")
}
if id == ([16]byte{}) {
panic("notes: empty note id")
}
if _, ok := notes.Get(idText(id)); ok {
panic("notes: note id used")
}
if mode > ModePublicOpen || public(mode) && (len(access) != 0 || len(commitment) != 0) {
panic("notes: unsupported creation mode")
}
if public(mode) {
validatePublic(title, body)
}
operation(nil, opID)
assertCreatePayment(cur, maxFee)
if sequence == ^uint64(0) {
panic("notes: sequence exhausted")
}
sequence++
n := ¬e{ID: id, Owner: who, OwnerGeneration: 1, Mode: mode, TitleRevision: 1, BodyRevision: 1, Title: copied(title), Body: copied(body), BodyBytes: len(body), CreatedHeight: runtime.ChainHeight(), Sequence: sequence, Listed: public(mode)}
if encrypted(mode) {
initializeEncrypted(n, access, commitment)
}
bump(n, who, opID, "create")
notes.Set(idText(id), n)
index(n)
if createFee > 0 {
banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), treasury, chain.Coins{chain.NewCoin("ugnot", createFee)})
}
}
// fieldMask: 1 title, 2 body, 3 both. An unchanged field must be omitted (empty
// blob). The separate field revision advances only when that field changes.
func Commit(cur realm, id [16]byte, baseRevision uint64, expectedEpoch uint32, fieldMask uint8, title, body []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateCommit(cur, who, id, baseRevision, expectedEpoch, fieldMask, title, body, opID)
}
func mutateCommit(cur realm, who address, id [16]byte, baseRevision uint64, expectedEpoch uint32, fieldMask uint8, title, body []byte, opID [16]byte) {
n := live(id)
requireContentWrite(cur, n, who)
expected(n, baseRevision)
if n.Epoch != expectedEpoch {
panic("notes: stale epoch")
}
privateWritable(n)
if fieldMask < 1 || fieldMask > 3 || (fieldMask&1 == 0 && len(title) != 0) || (fieldMask&2 == 0 && len(body) != 0) {
panic("notes: bad field mask")
}
if fieldMask&1 != 0 {
if public(n.Mode) {
validateTitle(title)
} else {
validateCipher(title, n.Epoch, 1, n.TitleRevision+1, MaxCipherTitleBytes)
}
if n.TitleRevision == ^uint64(0) {
panic("notes: title revision exhausted")
}
}
if fieldMask&2 != 0 {
if public(n.Mode) {
validatePublic(n.Title, body)
} else {
validateCipher(body, n.Epoch, 2, n.BodyRevision+1, MaxCipherBodyBytes)
}
if n.BodyRevision == ^uint64(0) {
panic("notes: body revision exhausted")
}
}
operation(n, opID)
if fieldMask&1 != 0 {
n.Title = copied(title)
n.TitleRevision++
}
if fieldMask&2 != 0 {
n.Body = copied(body)
n.BodyBytes = len(body)
n.BodyRevision++
}
bump(n, who, opID, "commit")
}
func Rename(cur realm, id [16]byte, baseRevision uint64, expectedEpoch uint32, title []byte, opID [16]byte) {
Commit(cur, id, baseRevision, expectedEpoch, 1, title, nil, opID)
}
// Delete retains the ID and last operation receipt forever. Large collections
// are purged by bounded follow-up calls, never by an unbounded delete loop.
func Delete(cur realm, id [16]byte, baseRevision uint64, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateDelete(cur, who, id, baseRevision, opID)
}
func mutateDelete(cur realm, who address, id [16]byte, baseRevision uint64, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
operation(n, opID)
unindex(n)
resetPublicWrites(n)
n.Deleted = true
n.Listed = false
n.Title = nil
n.Body = nil
n.BodyBytes = 0
n.Commitment = nil
n.PendingOwner = ""
n.Writers = nil
n.Readers = nil
n.Policies = [3]string{}
n.GovWriters = false
bump(n, who, opID, "delete")
}
func SetCommentMode(cur realm, id [16]byte, baseRevision uint64, open bool, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateSetCommentMode(cur, who, id, baseRevision, open, opID)
}
func mutateSetCommentMode(cur realm, who address, id [16]byte, baseRevision uint64, open bool, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if !public(n.Mode) {
panic("notes: public note required")
}
operation(n, opID)
if open {
n.Mode = ModePublicOpen
} else {
resetPublicWrites(n)
n.Mode = ModePublic
}
bump(n, who, opID, "comments-mode")
}
payable.gno
package memba_notes_rc1
import "chain/runtime/unsafe"
// Inert activation uses the original package creator as OriginCaller, not the
// enabling approver. Runtime e75fef82c keeper_inert.go pins this behavior.
func init() { admin = unsafe.OriginCaller() }
func assertNoCoins() {
if !unsafe.OriginSend().IsZero() {
panic("notes: no coins")
}
}
func assertCreatePayment(cur realm, maxFee int64) {
if !cur.Previous().IsUserCall() {
panic("notes: create directly from your account")
}
if maxFee < 0 || createFee > maxFee {
panic("notes: fee exceeds maximum")
}
coins := unsafe.OriginSend()
if createFee == 0 {
if !coins.IsZero() {
panic("notes: exact fee required")
}
return
}
if len(coins) != 1 || coins[0].Denom != "ugnot" || coins[0].Amount != createFee {
panic("notes: exact fee required")
}
}
policies.gno
package memba_notes_rc1
import (
"gno.land/p/samcrew/avl"
"strconv"
"strings"
)
const (
OpRead uint8 = iota
OpWrite
OpComment
)
// The realm parameter forces an explicit crossing: adapters run with their own
// realm identity. All mutators retain the busy guard throughout callbacks.
type Policy interface {
Allows(cur realm, id [16]byte, who address, op uint8) bool
}
var policies = avl.NewTree()
func RegisterPolicy(cur realm, slug string, p Policy) string {
enter(cur, false)
defer leave()
path := cur.Previous().PkgPath()
if !strings.HasPrefix(path, "gno.land/r/") || len(path) > 200 || len(slug) < 1 || len(slug) > 32 || p == nil {
panic("notes: realm policy required")
}
for _, c := range slug {
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
panic("notes: invalid policy slug")
}
}
key := path + ":" + slug
if _, ok := policies.Get(key); ok {
panic("notes: policy already registered")
}
policies.Set(key, p)
return key
}
func SetPolicy(cur realm, id [16]byte, baseRevision uint64, op uint8, key string, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateSetPolicy(cur, who, id, baseRevision, op, key, opID)
}
func mutateSetPolicy(cur realm, who address, id [16]byte, baseRevision uint64, op uint8, key string, opID [16]byte) {
n := live(id)
owner(n, who)
expected(n, baseRevision)
if op > OpComment {
panic("notes: unknown policy operation")
}
if key != "" {
if _, ok := policies.Get(key); !ok {
panic("notes: policy missing")
}
}
operation(n, opID)
n.Policies[op] = key
bumpHistory(n, who, opID, "policy", `,"policy_op":`+strconv.Itoa(int(op))+`,"policy_key":`+q(key))
}
func policyAllows(cur realm, n *note, who address, op uint8) bool {
key := n.Policies[op]
if key == "" {
return false
}
p, ok := policies.Get(key)
if !ok {
panic("notes: missing stored policy")
}
return p.(Policy).Allows(cross(cur), n.ID, who, op)
}
func PoliciesJSON(idHex string) string {
n := find(readID(idHex))
return `{"read":` + q(n.Policies[0]) + `,"write":` + q(n.Policies[1]) + `,"comment":` + q(n.Policies[2]) + `}`
}
// A holder may grant a read-policy-approved recipient the current epoch. Every
// existing entry must remain byte-identical: a grantee cannot corrupt someone
// else's wrap, change writers, remove access or rotate the owner into new keys.
func GrantAccess(cur realm, id [16]byte, baseRevision uint64, expectedEpoch uint32, manifest []byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
n := live(id)
expected(n, baseRevision)
privateWritable(n)
if n.Mode != ModeShared || expectedEpoch != n.Epoch || !contains(n.Readers, who) {
panic("notes: current shared reader required")
}
list := parseManifest(manifest, n.Epoch, manifestOwner(n), n.Mode)
old := getEpoch(id, n.Epoch).Manifest
for i := 0; i < int(old[1]); i++ {
entry := old[2+i*ManifestEntryBytes : 2+(i+1)*ManifestEntryBytes]
found := false
for j := 0; j < int(manifest[1]); j++ {
next := manifest[2+j*ManifestEntryBytes : 2+(j+1)*ManifestEntryBytes]
if string(entry) == string(next) {
found = true
break
}
}
if !found {
panic("notes: existing wrap immutable for reader")
}
}
added := false
for _, r := range list {
if !contains(n.Readers, r.Who) {
govGrant := n.GovWriters && n.Owner == govAddress && govMember(who) && govMember(r.Who)
if r.Writer || who != n.Owner && !govGrant && !policyAllows(cur, n, r.Who, OpRead) {
panic("notes: read policy denied")
}
added = true
}
}
if !added {
panic("notes: no new reader")
}
operation(n, opID)
unindex(n)
setRecipients(n, list)
index(n)
getEpoch(id, n.Epoch).Manifest = copied(manifest)
acknowledgeRequests(n, who, opID)
bump(n, who, opID, "read-grant")
}
render.gno
package memba_notes_rc1
import (
"strconv"
"strings"
)
// gnoweb uses bounded pages. A revision in every continuation link prevents
// assembling a whitepaper from different edits; the app reads binary chunks.
func Render(path string) string {
if path == "" {
return "# Notes\n\nUse ListPublicJSON for the public directory.\n"
}
if len(path) > 80 {
panic("notes: render path")
}
parts := strings.Split(path, "/")
if len(parts) != 1 && len(parts) != 3 {
panic("notes: render path")
}
n := find(readID(parts[0]))
if n.Deleted {
return "# Deleted note\n\nPast versions remain in chain history.\n"
}
page := 0
if len(parts) == 3 {
rev, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil || rev != n.Revision {
return "# Note changed\n\n[Start again](:" + idText(n.ID) + ").\n"
}
page, err = strconv.Atoi(parts[2])
if err != nil {
panic("notes: render page")
}
}
if !public(n.Mode) {
return "# Encrypted note\n\n" + seal(n.Body) + "\nOwner: " + string(n.Owner) + "\n\nEncrypted bytes: " + strconv.Itoa(n.BodyBytes) + " · Revision " + strconv.FormatUint(n.Revision, 10) + "\n\nOpen this note in Memba to decrypt. This seal is decorative.\n"
}
pages := (n.BodyBytes + MaxBodyChunkBytes - 1) / MaxBodyChunkBytes
if pages == 0 {
pages = 1
}
if page < 0 || page >= pages {
panic("notes: render page")
}
start := renderBoundary(n.Body, page*MaxBodyChunkBytes)
end := renderBoundary(n.Body, (page+1)*MaxBodyChunkBytes)
title := strings.NewReplacer("\\", "\\\\", "[", "\\[", "]", "\\]", "*", "\\*", "_", "\\_", "`", "\\`", "#", "\\#", "<", "<", ">", ">").Replace(string(n.Title))
body := strings.ReplaceAll(strings.ReplaceAll(string(n.Body[start:end]), "<", "<"), ">", ">")
// Entity tokens are text, not Markdown image syntax, even after a backslash.
// Keep ordinary links available without automatically fetching remote images.
body = strings.ReplaceAll(body, " + ") "
}
if page+1 < pages {
nav += "[Next](" + base + strconv.Itoa(page+1) + ") "
}
nav += "[Read the complete note in Memba](https://memba.club/os/notes/" + idText(n.ID) + ")\n"
}
return "# " + title + "\n\n" + body + nav
}
// Advance at most three continuation bytes; adjacent pages use the same
// boundary, so no UTF8 byte is lost or repeated.
func renderBoundary(body []byte, pos int) int {
if pos >= len(body) {
return len(body)
}
for pos < len(body) && body[pos]&0xc0 == 0x80 {
pos++
}
return pos
}
requests.gno
package memba_notes_rc1
import (
"chain/runtime"
"gno.land/p/samcrew/avl"
keys "gno.land/r/samcrew/enckeys_v1"
"strconv"
"strings"
)
const MaxAccessRequests = 256
const RequestTTLBlocks int64 = 10000
type accessRequest struct {
Who address
Expires int64
Active bool
Status string
Last receipt
}
var requests = avl.NewTree()
func requestKey(id [16]byte, who address) string { return idText(id) + ":" + string(who) }
func RequestAccess(cur realm, id [16]byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
n := live(id)
if !cur.Previous().IsUserCall() || !encrypted(n.Mode) || who == n.Owner || contains(n.Readers, who) {
panic("notes: request not applicable")
}
if opID == ([16]byte{}) {
panic("notes: empty operation id")
}
h := runtime.ChainHeight()
if h > int64(9223372036854775807)-RequestTTLBlocks {
panic("notes: request height overflow")
}
key := requestKey(id, who)
if v, ok := requests.Get(key); ok {
r := v.(*accessRequest)
if r.Last.Operation == opID {
panic("notes: operation id reused")
}
if !r.Active && r.Status == "rejected" && r.Expires > h {
panic("notes: request rejected recently")
}
if r.Active {
if r.Expires > h {
panic("notes: request pending")
}
n.RequestCount--
}
}
if n.RequestCount >= MaxAccessRequests {
panic("notes: request capacity; purge expired requests")
}
n.RequestCount++
requests.Set(key, &accessRequest{who, h + RequestTTLBlocks, true, "pending", receipt{opID, who, h}})
}
func closeRequest(n *note, who address, status string, actor address, opID [16]byte) {
v, ok := requests.Get(requestKey(n.ID, who))
if !ok {
panic("notes: request missing")
}
r := v.(*accessRequest)
if !r.Active {
panic("notes: request already closed")
}
if opID == ([16]byte{}) || opID == r.Last.Operation {
panic("notes: invalid request operation")
}
h := runtime.ChainHeight()
r.Active = false
r.Status = status
r.Last = receipt{opID, actor, h}
n.RequestCount--
// A rejection keeps the record until one full TTL after it, so neither the
// requester nor PurgeExpiredRequests can end the re-request cooldown early.
if status == "rejected" {
if h > int64(9223372036854775807)-RequestTTLBlocks {
panic("notes: request height overflow")
}
r.Expires = h + RequestTTLBlocks
}
}
func CancelAccessRequest(cur realm, id [16]byte, opID [16]byte) {
who := enter(cur, false)
defer leave()
n := find(id)
closeRequest(n, who, "cancelled", who, opID)
}
func RejectAccessRequest(cur realm, id [16]byte, to address, opID [16]byte) {
who := enter(cur, false)
defer leave()
mutateRejectAccessRequest(cur, who, id, to, opID)
}
func mutateRejectAccessRequest(cur realm, who address, id [16]byte, to address, opID [16]byte) {
n := live(id)
owner(n, who)
closeRequest(n, keys.CanonicalAddress(to), "rejected", who, opID)
}
func acknowledgeRequests(n *note, actor address, opID [16]byte) {
for _, who := range n.Readers {
if v, ok := requests.Get(requestKey(n.ID, who)); ok {
r := v.(*accessRequest)
if r.Active {
r.Active = false
r.Status = "granted"
r.Last = receipt{opID, actor, runtime.ChainHeight()}
n.RequestCount--
}
}
}
}
func requestJSON(r *accessRequest) string {
return `{"address":` + q(string(r.Who)) + `,"expires_height":` + q(strconv.FormatInt(r.Expires, 10)) + `,"active":` + strconv.FormatBool(r.Active) + `,"status":` + q(r.Status) + `,"op_id":` + q(idText(r.Last.Operation)) + `,"actor":` + q(string(r.Last.Actor)) + `,"height":` + q(strconv.FormatInt(r.Last.Height, 10)) + `}`
}
func AccessRequestJSON(idHex string, who address) string {
v, ok := requests.Get(requestKey(readID(idHex), keys.CanonicalAddress(who)))
if !ok {
return "null"
}
return requestJSON(v.(*accessRequest))
}
func requestStart(id [16]byte, cursor string) string {
if cursor != "" && string(keys.CanonicalAddress(address(cursor))) != cursor {
panic("notes: bad request cursor")
}
return idText(id) + ":" + cursor
}
func AccessRequestsJSON(idHex, cursor string, limit int) string {
id := readID(idHex)
n := find(id)
if limit < 1 || limit > MaxPage {
panic("notes: page limit")
}
start := requestStart(id, cursor)
prefix := idText(id) + ":"
items := []string{}
next := ""
requests.Iterate(start, prefix+"\xff", func(k string, v interface{}) bool {
if cursor != "" && k == start {
return false
}
items = append(items, requestJSON(v.(*accessRequest)))
next = strings.TrimPrefix(k, prefix)
return len(items) == limit
})
if len(items) < limit {
next = ""
}
return `{"items":[` + strings.Join(items, ",") + `],"next_cursor":` + q(next) + `,"active_count":` + u(uint64(n.RequestCount)) + `}`
}
// At most limit records are inspected, not just removed. The returned cursor
// lets a caller sweep the full request set without an unbounded scan.
func PurgeExpiredRequests(cur realm, id [16]byte, cursor string, limit int) string {
enter(cur, false)
defer leave()
n := find(id)
if limit < 1 || limit > MaxPage {
panic("notes: purge limit")
}
start := requestStart(id, cursor)
prefix := idText(id) + ":"
doomed := []string{}
next := ""
inspected := 0
h := runtime.ChainHeight()
requests.Iterate(start, prefix+"\xff", func(k string, v interface{}) bool {
if cursor != "" && k == start {
return false
}
r := v.(*accessRequest)
if r.Expires <= h {
doomed = append(doomed, k)
if r.Active {
n.RequestCount--
}
}
inspected++
next = strings.TrimPrefix(k, prefix)
return inspected == limit
})
for _, key := range doomed {
requests.Remove(key)
}
if inspected < limit {
next = ""
}
return next
}
func purgeRequests(n *note, limit int) int {
if limit == 0 {
return 0
}
prefix := idText(n.ID) + ":"
doomed := []string{}
requests.Iterate(prefix, prefix+"\xff", func(k string, v interface{}) bool {
r := v.(*accessRequest)
if r.Active {
n.RequestCount--
}
doomed = append(doomed, k)
return len(doomed) == limit
})
for _, k := range doomed {
requests.Remove(k)
}
return len(doomed)
}
seal.gno
package memba_notes_rc1
import (
"crypto/sha256"
"encoding/hex"
"strconv"
)
// Decorative fingerprint from public ciphertext only. It is not a historical
// inclusion proof or proof of knowledge of a plaintext/key.
func seal(body []byte) string {
hash := sha256.Sum256(body)
glyphs := []rune("◇◆○●□■△▲✦")
out := "```\n"
for i := 0; i < 81; i++ {
out += string(glyphs[int(hash[i%32]+byte(i/32))%len(glyphs)])
if i%9 == 8 {
out += "\n"
}
}
return out + "```\n"
}
func SealJSON(idHex string) string {
n := find(readID(idHex))
hash := sha256.Sum256(n.Body)
return `{"id":` + q(idText(n.ID)) + `,"state_revision":` + u(n.Revision) + `,"body_revision":` + u(n.BodyRevision) + `,"epoch":` + u(uint64(n.Epoch)) + `,"ciphertext_sha256":` + q(hex.EncodeToString(hash[:])) + `,"encrypted":` + strconv.FormatBool(encrypted(n.Mode) && !n.Deleted) + `,"deleted":` + strconv.FormatBool(n.Deleted) + `,"height":` + q(strconv.FormatInt(n.Last.Height, 10)) + `,"historical_proof":false}`
}
state.gno
package memba_notes_rc1
import (
"chain"
"chain/runtime"
"encoding/hex"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
func enter(cur realm, payable bool) address {
if !cur.IsCurrent() {
panic("notes: stale realm")
}
if busy {
panic("notes: reentry")
}
if !payable {
assertNoCoins()
}
busy = true
return cur.Previous().Address()
}
func leave() { busy = false }
func idText(id [16]byte) string { return hex.EncodeToString(id[:]) }
func readID(s string) [16]byte {
if len(s) != 32 {
panic("notes: bad note id")
}
b, err := hex.DecodeString(s)
if err != nil || hex.EncodeToString(b) != s {
panic("notes: bad note id")
}
var id [16]byte
copy(id[:], b)
return id
}
func find(id [16]byte) *note {
v, ok := notes.Get(idText(id))
if !ok {
panic("notes: note not found")
}
return v.(*note)
}
func live(id [16]byte) *note {
n := find(id)
if n.Deleted {
panic("notes: note deleted")
}
return n
}
func expected(n *note, rev uint64) {
if rev != n.Revision {
panic("notes: stale revision")
}
if rev == ^uint64(0) {
panic("notes: revision exhausted")
}
}
func owner(n *note, who address) {
if n.Owner != who {
panic("notes: owner required")
}
}
func operation(n *note, op [16]byte) {
if op == ([16]byte{}) {
panic("notes: empty operation id")
}
if n != nil && n.Last.Operation == op {
panic("notes: operation id reused")
}
}
func bump(n *note, who address, op [16]byte, action string) {
bumpHistory(n, who, op, action, "")
}
func bumpHistory(n *note, who address, op [16]byte, action, historyExtra string) {
operation(n, op)
n.Revision++
n.Last = receipt{op, who, runtime.ChainHeight()}
n.LastExecutor = ""
historyNote(n, who, op, action, historyExtra)
chain.Emit("NoteChanged", "id", idText(n.ID), "action", action, "revision", strconv.FormatUint(n.Revision, 10), "actor", string(who), "op_id", idText(op))
}
func copied(b []byte) []byte { return append([]byte(nil), b...) }
func public(mode uint8) bool { return mode == ModePublic || mode == ModePublicOpen }
func indexKey(n *note) string {
s := strconv.FormatUint(n.Sequence, 10)
return strings.Repeat("0", 20-len(s)) + s + ":" + idText(n.ID)
}
func index(n *note) {
for _, a := range append(copiedAddresses(n.Writers), n.Readers...) {
sharedIndex.Set(string(a)+":"+indexKey(n), idText(n.ID))
}
ownerIndex.Set(string(n.Owner)+":"+indexKey(n), idText(n.ID))
if public(n.Mode) && n.Listed && !n.ModeratorHidden {
publicIndex.Set(indexKey(n), idText(n.ID))
}
}
func unindex(n *note) {
for _, a := range append(copiedAddresses(n.Writers), n.Readers...) {
sharedIndex.Remove(string(a) + ":" + indexKey(n))
}
ownerIndex.Remove(string(n.Owner) + ":" + indexKey(n))
publicIndex.Remove(indexKey(n))
}
func validateTitle(title []byte) {
if len(title) == 0 || len(title) > MaxTitleBytes || !utf8.Valid(title) || utf8.RuneCount(title) > 80 {
panic("notes: invalid title")
}
s := string(title)
if strings.TrimSpace(s) != s {
panic("notes: invalid title")
}
for _, r := range s {
if r == '/' || unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
panic("notes: invalid title")
}
}
}
func validatePublic(title, body []byte) {
validateTitle(title)
if len(body) > MaxBodyBytes || !utf8.Valid(body) {
panic("notes: invalid body")
}
}
func copiedAddresses(a []address) []address { return append([]address(nil), a...) }
types.gno
// Package memba_notes_rc1 stores versioned Markdown notes and their receipts.
// Publication is immutable; deployment is gated on the complete contract audit.
package memba_notes_rc1
import "gno.land/p/samcrew/avl"
const RealmPath = "gno.land/r/samcrew/memba_notes_rc1"
const ReserveAddress address = "g1jw76lxvzjafw2kyjhdnzwggcftyhnlfjaer2u0"
const (
ModePrivate uint8 = iota
ModeShared
ModeLink
ModePublic
ModePublicOpen
)
const (
MaxBodyBytes = 131072
MaxCipherBodyBytes = 135223
MaxTitleBytes = 160
MaxCipherTitleBytes = 231
MaxReaders = 32
MaxPage = 50
)
type receipt struct {
Operation [16]byte
Actor address
Height int64
}
type note struct {
ID [16]byte
Owner, PendingOwner address
OwnerGeneration uint64
Writers []address
Readers []address
OwnerIsRealm bool
Policies [3]string
RequestCount uint16
GovWriters bool
LastExecutor address
Mode uint8
Revision, TitleRevision, BodyRevision uint64
Epoch uint32
Title, Body, Commitment []byte
BodyBytes int
CreatedHeight int64
Sequence uint64
CommentSequence uint64
Last receipt
Deleted, Listed bool
ModeratorHidden bool
History *historyInfo // public notes only
}
var notes = avl.NewTree()
var ownerIndex = avl.NewTree()
var publicIndex = avl.NewTree()
var sharedIndex = avl.NewTree()
var sequence uint64
var busy bool
var admin, pendingAdmin address
var treasury = ReserveAddress
var createFee int64 = 100000
var paused bool