Repository navigation
feat: add audit pattern harness and security patterns example - #5835
Conversation
Assisted-By: OpenAI Codex
🛠 PR Checks SummaryAll Automated Checks passed. ✅ Manual Checks (for Reviewers):
Read More🤖 This bot helps streamline PR reviews by verifying automated checks and providing guidance for contributors and reviewers. ✅ Automated Checks (for Contributors):🟢 Maintainers must be able to edit this pull request (more info) ☑️ Contributor Actions:
☑️ Reviewer Actions:
📚 Resources:Debug
|
Assisted-By: OpenAI Codex
…odex/audit-guide-examples
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
Assisted-By: OpenAI Codex
|
Two new patterns surfaced while analyzing agent-generated contracts against the audit harness — both are missing from the current pattern set. Missing pattern:
|
…xamples # Conflicts: # AGENTS.md
|
I imagine from this latest comment that there's a bit of work yet to be done on this PR? (I can review if not) |
## Summary Adds `docs/resources/gno-ai-contract-review.md` — a short, checklist-style guide specifically for AI agents reviewing Gno realm code. The guide covers the seven highest-yield issues: 1. Caller identity via `cur realm`, not attacker-controlled `address` parameters 2. Payment guards: `IsUserCall()` not `IsUser()` 3. No exported pointers to mutable state 4. No caller-supplied callbacks invoked under realm authority 5. Interface parameters need canonical-type assertion 6. Never store `realm` values (store `Address()` strings instead) 7. `/p/`-embedded types with callback iterators must stay unexported ## Relationship to existing work This is intentionally more minimal than the other security resources: | Resource | Scope | |----------|-------| | `gno-security-guide.md` | Deep technical threat model, borrow rules, proofs — for realm authors who want to understand why | | `misc/audit-pattern-harness/` ([#5835](#5835)) | Automated tooling: YAML-defined patterns, sanitized fixtures, `gno test` execution, Markdown/JSON reports | | [gno-mcp audit skill](https://github.com/gnoverse/gno-mcp/tree/main/skills/gno-audit) | MCP-packaged harness for AI agents to run audits programmatically | | **this file** | Concise checklist an AI can apply inline during code review without tooling | The audit harness and gno-mcp skill are powerful when you want to run automated checks. This guide fills the lighter-weight use case: an AI agent reading a contract and knowing what to look for, without needing a separate tool invocation. --------- Co-authored-by: Morgan <morgan@morganbaz.com>
# Conflicts: # docs/resources/effective-gno.md # docs/resources/gno-security-guide.md # examples/quarantined/gno.land/r/docs/home/home.gno
…dary, code-span safety)
|
Pushed two commits closing out this review round — I think this is ready to land now.
Both ship with vulnerable+fixed fixtures, expected YAML, unit tests, and the spec-corpus contract; README limitations updated. All local checks green: So the V1 scope discussed above is complete — no open follow-ups left on my side. @thehowl @davd-gzl @Villaquiranm mind giving it a final review so we can merge? Happy to iterate on anything, otherwise I'd like to land this and iterate on the docs in follow-ups. |
There was a problem hiding this comment.
Suggestion: New example proposition, from #5976, that slips every rule:
if caller.IsUserCall() { // "realms only"
panic("realms only")
}maketx run passes it. Case 2 of gno-ai-contract-review.md covers the mirror (payment: require !IsUserCall()), but a realms-only gate needs IsUser(), and neither the checklist nor the harness has it. Want a realm_only_gate rule plus that checklist line?
Follow-up: a -scan mode to run every rule against a realm dir, since the CLI only takes fixture yamls today:
auditpattern -scan /path/to/my/realmSuggestion: the security material is spread across gno-security-guide.md, gno-security.md, and gno-ai-contract-review.md, which overlap a lot. Worth consolidating to one deep reference plus the concise checklist. The harness rule comments and the contract-test corpus still point at gno-security-guide.md, not the concise guide.
After those fixes it looks good to merge to me. I can work on the follow-ups if needed.
|
|
||
| Live at **`https://staging.gno.land/r/<your-g1-addr>/counter`**. | ||
|
|
||
| ## Check security patterns |
There was a problem hiding this comment.
You should put that paragraph in builders/getting-started.md / else. This doc is meant to be example first for copy-paste
|
|
||
| Before publishing a non-trivial realm, read the | ||
| [Gno Security Guide](../resources/gno-security-guide.md). The | ||
| [`misc/audit-pattern-harness`](../../misc/audit-pattern-harness/README.md) |
There was a problem hiding this comment.
If we highlight this tool in beginner doc, we should add an inline example to run it
And IMO ../../misc/audit-pattern-harness/README.md is not clear if it's meant to be a builder-facing scanner
| realm token grants authority only while `cur.IsCurrent()` holds, and a | ||
| concrete callee cannot be swapped for attacker code the way an interface | ||
| or callback parameter can. This is the interrealm pattern | ||
| [daokit's interrealm-v2 port](https://github.com/samouraiworld/gnodaokit/pull/64) |
There was a problem hiding this comment.
Suggestion: I know this is Samourai's repo + my PR, but should this be in official doc? We should prob have a dedicated example for maintainability.
| ### 5.8 `OriginCaller()` as authorization identity | ||
| ### 5.8 `unsafe.PreviousRealm()` alongside a `cur realm` parameter | ||
|
|
||
| `chain/runtime/unsafe.PreviousRealm()` is the pre-`cur realm` API for |
There was a problem hiding this comment.
Suggestion: Should we mention previous design of the inter-realm spec in the security guide?
Since we don't "officially" have user-made packages, and docs / example are up-to-date.
| ) | ||
|
|
||
| var exportedPointerVarRE = regexp.MustCompile(`^var\s+[A-Z]\w*\s+\*`) | ||
| var exportedPointerFuncRE = regexp.MustCompile(`^func\s+([A-Z]\w*)\([^)]*\)\s+\*`) |
There was a problem hiding this comment.
Exported methods returning a pointer slip: no receiver branch.
type Store struct{ acct *Account }
// slips exported_pointer_leak (no receiver branch) and
// pkg_mutable_pointer (type is not *avl.Tree)
func (s *Store) Account() *Account {
return s.acct
}repro
cat > /tmp/rx.go <<'EOF'
package main
import (
"fmt"
"regexp"
)
func main() {
exportedPointerFuncRE := regexp.MustCompile(`^func\s+([A-Z]\w*)\([^)]*\)\s+\*`)
fmt.Println(exportedPointerFuncRE.MatchString(`func (s *Store) Account() *Account`))
}
EOF
go run /tmp/rx.gofalse
| // pkgMutableReturnRE matches an exported function returning a pointer to such a | ||
| // type (guide §5.1a). pkgMutableFieldRE matches an exported struct field or | ||
| // package var of that pointer type (guide §5.1b). | ||
| var pkgMutableReturnRE = regexp.MustCompile(`^func\s+(?:\([^)]*\)\s+)?[A-Z]\w*\([^)]*\)\s+` + pkgMutablePointerTypeRE) |
There was a problem hiding this comment.
Multi-return slips: the type must follow ) directly.
// returns the shared tree; not flagged
func Get() (*avl.Tree, error) {
return gTree, nil
}repro
cat > /tmp/rx.go <<'EOF'
package main
import (
"fmt"
"regexp"
)
func main() {
pkgMutablePointerTypeRE := `\*avl\.Tree\b`
pkgMutableReturnRE := regexp.MustCompile(`^func\s+(?:\([^)]*\)\s+)?[A-Z]\w*\([^)]*\)\s+` + pkgMutablePointerTypeRE)
fmt.Println(pkgMutableReturnRE.MatchString(`func Get() (*avl.Tree, error)`))
}
EOF
go run /tmp/rx.gofalse
| "strings" | ||
| ) | ||
|
|
||
| var exportedPointerVarRE = regexp.MustCompile(`^var\s+[A-Z]\w*\s+\*`) |
There was a problem hiding this comment.
Grouped var (...) blocks slip: ^var required.
var (
// exported pointer to mutable state; slips the grouped-var check, and the
// type is not *avl.Tree so pkg_mutable_pointer misses it too
Shared *Account
)repro
cat > /tmp/rx.go <<'EOF'
package main
import (
"fmt"
"regexp"
)
func main() {
exportedPointerVarRE := regexp.MustCompile(`^var\s+[A-Z]\w*\s+\*`)
fmt.Println(exportedPointerVarRE.MatchString(`Shared *Account`))
}
EOF
go run /tmp/rx.gofalse
| // pkgMutablePointerTypeRE matches known /p/ types whose exported methods mutate | ||
| // the receiver, so a pointer to one is a live mutator handle. avl.Tree is the | ||
| // canonical example (Set/Remove/ReverseIterate); extend as more are documented. | ||
| var pkgMutablePointerTypeRE = `\*avl\.Tree\b` |
There was a problem hiding this comment.
Suggestion: only *avl.Tree is matched; other mutable /p/ pointer types slip.
// mutable /p/ pointer via method; slips pkg_mutable_pointer (not *avl.Tree)
// and exported_pointer_leak (no receiver branch)
func (s *Store) Node() *avl.Node {
return s.node
}repro
cat > /tmp/rx.go <<'EOF'
package main
import (
"fmt"
"regexp"
)
func main() {
pkgMutablePointerTypeRE := regexp.MustCompile(`\*avl\.Tree\b`)
fmt.Println(pkgMutablePointerTypeRE.MatchString(`func (s *Store) Node() *avl.Node`))
}
EOF
go run /tmp/rx.gofalse
| if strings.HasPrefix(trimmed, "//") { | ||
| continue | ||
| } | ||
| if strings.Contains(line, "PreviousRealm()") { |
There was a problem hiding this comment.
crossing is file-wide, so a non-crossing helper's PreviousRealm() is flagged too.
func Enter(cur realm) { /* crossing func in the same file */ }
// non-crossing helper; PreviousRealm() is the normal caller lookup
func who() string {
return runtime.PreviousRealm().PkgPath() // flagged anyway
}| if match == nil { | ||
| continue | ||
| } | ||
| if strings.HasPrefix(match[1], "New") && returnsFreshPointer(lines[i:]) { |
There was a problem hiding this comment.
The fresh-constructor skip needs a New name, so other constructors are flagged.
// fresh pointer, safe; flagged only because the name is not New*
func MakeThing() *Thing {
return &Thing{}
}…xamples Conflict: examples/gno.land/p/nt/avl/v0/README.md — master (gnolang#5950) rewrote the further-reading list; this branch had retargeted the Effective Gno link because the 'Prefer avl.Tree over map for scalable storage' section is renamed to 'Choose storage types by access pattern'. Kept master's list, updated the link.
The audit-pattern harness, security_patterns example and security-guide sections this branch introduced landed on master via gnolang#5835 in a more refined form (10 fixture patterns vs 8, plus review follow-ups). Every conflicted file takes master's version, and docs/resources/gno-security-guide.md is reset to master's copy because master already carries sections 5.8-5.10 — the branch's differently-ordered copies had merged in as duplicates. What remains unique to this branch is two lines gnolang#5835 left behind: - wire audit-pattern-harness into the misc CI matrix - link the security_patterns example from the r/docs home index
The security_patterns realm from gnolang#5835 is linked only from the quarantined home page, which this branch removes. Add the entry to the revived index under Interrealm & Access Control, where its admin gate fits.
The audit pattern harness from gnolang#5835 flags a crossing function that reads cur.Previous() without first checking cur.IsCurrent(), and its security_patterns realm, gno-security-guide.md §5.9 and the community-packages example teach the same rule. A first-position cur realm cannot fail that check. doOpCall adopts whatever realm arrives in the cur slot as the frame's Cur, and IsCurrent() is HIV pointer identity against that same slot, so the check compares a value against itself: a closure-captured cur from an exited frame still reports true. gnovm/adr/interrealm_v2.md states it outright — "Crossing functions do not require cur.IsCurrent() because the runtime ensures that it is always true" — and gnovm/tests/files/zrealm_iscurrent.gno asserts it. The check is load-bearing for a secondary realm parameter, where the caller supplies the value and can forward cur.Previous(); the same filetest pins that case false. current_guard now exempts a first-position cur realm and flags a secondary rlm realm read through .Previous(), .Address() or .PkgPath() before its own .IsCurrent(). On the revived r/docs that takes the rule from 25 hits, all false positives, to none; on examples/quarantined it reports 6 real secondary-parameter reads in place of 90. Fixtures, expected record, README and the affected tests move to the retargeted shape. The vacuous guard goes from security_patterns, from the guide's §5.9 example, comparison table and rule, and from the community-packages SetName example. The realm's test is renamed to name what it asserts.
* fix(gnovm): drop clause-local names on switch fallthrough (#6056)
`fallthrough` from a clause that declares more names than the clause it
falls into panics the VM:
```go
switch 1 {
case 1:
x := 1
_ = x
fallthrough
case 2:
println("two")
}
```
```
unexpected panic: unexpected block size shrinkage: 1 vs 0
```
## Cause
All clauses of a switch share a single runtime `Block` (allocated in
`doOpExec`'s `*SwitchStmt` case). During preprocessing,
`copyFromFauxBlock` copies the switch's own names — those from its init
statement — into every clause's static block, so a clause's static block
is *switch names + that clause's own names*. When a clause matches,
`Block.ExpandWith` grows the shared block's `Values` to that clause's
name count.
`fallthrough` re-used the already-expanded block and called `ExpandWith`
again with the next clause. When the falling-through clause declared
more names than the next one, `len(b.Values)` exceeded the next clause's
`NumNames` and `ExpandWith` tripped its no-shrinkage guard
(`values.go:2951`).
## Fix
Truncate the block back to the switch's own name count before expanding
with the next clause, so it gets fresh slots of its own.
This also fixes a latent equal-size case that never panicked: two
clauses declaring the same number of names hit `ExpandWith`'s `numNames
== len(b.Values)` early return and silently reused the stale slots,
including the previous clause's `*HeapItemValue`.
Truncating is safe because the block never escapes — `doOpFuncLit`
copies `*HeapItemValue`s into `FuncValue.Captures` rather than
referencing the block — and `ExpandWith` mints fresh heap items for the
new slots, so a closure created in the previous clause keeps its own.
## Tests
Five filetests, each verified to produce identical output under real `go
run`:
| File | Covers |
|---|---|
| `switch47.gno` | the reported repro (1 name → 0 names) |
| `switch48.gno` | 3 names → 1 name, plus equal-size clauses with
differing types |
| `switch49.gno` | switch-init names surviving chained fallthroughs into
`default` |
| `switch50.gno` | fallthrough chain inside a loop (slots reused across
iterations) |
| `switch51.gno` | heap-captured clause vars on both sides of the
fallthrough |
## Related, not fixed here
Shadowing a switch-init variable inside a clause fails at preprocess
time, with or without `fallthrough`:
```go
switch v := 1; v {
case 1:
v := "shadow" // panic: StaticBlock.Define2(v) cannot change .T; was int, new string
println(v)
}
```
Same root design (`copyFromFauxBlock` puts the init names into the
clause's static block, so a redeclaration collides instead of
shadowing). Real Go prints `shadow`. Left for a separate change.
---
AI-assisted: the fix and tests were written with Claude Code and
reviewed before submission.
* feat: add audit pattern harness and security patterns example (#5835)
## Summary
Moves the audit pattern harness into this repo and keeps the public
builder-facing updates alongside it.
This adds:
- `misc/audit-pattern-harness`: a small audit pattern harness with YAML
expected records, sanitized fixtures, `gno test` execution, and
Markdown/JSON reports via `cmd/auditpattern`
- eight initial pattern slices:
- `cur.Previous()` before `cur.IsCurrent()`
- raw `Render(path)` markdown output
- `Render` output that depends on map iteration order
- `OriginSend()` without an `IsUserCall()` guard
- `OriginCaller()` used as authorization identity
- caller-supplied callbacks accepted by realm APIs
- interfaces that expose `cur realm`
- exported pointers or pointer getters for mutable state
- `gno.land/r/docs/security_patterns`: a compact example realm showing
authenticated mutators and safe Render output
- security-guide updates for caller-identity selection, Render output,
official markdown sanitizing guidance, and OriginCaller authorization
- Effective Gno storage guidance kept concise, with fuller tree/seqid
examples moved to `gno-data-structures.md`
- `community-packages.md`: a disclaimer-backed place for non-official
helper packages such as `moul/md`, `ulist`, `addrset`, and `fifo`
- a docs index link
The additional patterns were calibrated from local `examples/` plus
checked-out Gno contract repos including GnoSwap, Akkadia, gno-ibc, and
gno-mcp fixtures, then reduced into sanitized fixtures rather than
copying source.
## Validation
- `go test ./...` in `misc/audit-pattern-harness`
- `make run
GO=/home/russel/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.25.9.linux-amd64/bin/go
AUDIT_PATTERN_FLAGS='-gno-bin /tmp/gno-audit-harness-gno'` in
`misc/audit-pattern-harness` with
`GNOROOT=/home/russel/p/gh/gnoland/gno`
- `gno test .` in `examples/gno.land/r/docs/security_patterns` with
`GNOROOT=/home/russel/p/gh/gnoland/gno`
- `gno test .` in `examples/gno.land/r/docs/home` with
`GNOROOT=/home/russel/p/gh/gnoland/gno`
- `git diff --check`
Assisted-By: OpenAI Codex
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Miguel Victoria Villaquiran <miguelvicvil@gmail.com>
* fix(gnovm): allow type-switch with sole `case nil:` (preprocess single-case branch must tag-type-only when ct is nil) (#5766)
- Before: a type-switch whose sole case was `case nil:` (e.g. `switch xx
:= x.(type) { case nil: ... }`) panicked at preprocess with `name xx not
declared` because the single-case shortcut registered the switch var
with `anyValue(ct)` where `ct == nil`; after: the sole-`nil` form is
accepted and `xx` is bound to the tag's static type, matching Go.
- `preprocess1`'s `*TypeSwitchStmt` branch in
`gnovm/pkg/gnolang/preprocess.go` now gates the `len(n.Cases) == 1`
define-with-case-type shortcut on `ct != nil`, so a nil `ct` falls
through to the same tag-type define used for multi-case switches.
- New filetest `gnovm/tests/files/typeswitch1.gno` mirrors gocorpus's
typeswitch1 (sole `case nil:` alongside mixed multi-type cases) and
exercises both the `xx := x.(type)` and bare `xx.(type)` shapes.
---------
Co-authored-by: Lee ByeongJun <lbj199874@gmail.com>
Co-authored-by: ltzmaxwell <6007578+ltzmaxwell@users.noreply.github.com>
* fix(boards2): Fix the doc for GetComments (#6090)
The doc for `GetComments` says it returns "all thread comments and
replies". Maybe this was true in an earlier version, but now it uses
[`Post.Replies`](https://github.com/gnolang/gno/blob/add66f24b895e201280e717f07e4e8cf88334593/examples/gno.land/p/gnoland/boards/post.gno#L41)
which is only direct replies. No need to filter the result. (Note that
the public API doesn't give access to `AllReplies`.)
Signed-off-by: Jeff Thompson <jeff@thefirst.org>
* feat(gno.land): finish the inert-package flow, allowlist MsgRun, delegate params (#6088)
Builds on #5888 and contains it, so this supersedes that PR — please
review this
one instead. Base is master, which #5888 predates by about a month.
Under the inert policy a package is parked when submitted and only runs
once an
approver enables it. Storage gets written at both points, and this fixes
who
pays and when:
- The deposit ceiling is recorded at submit time and honored at enable,
so a
later change to the chain default cannot change what a submitter already
agreed to.
- The namespace and CLA checks moved before the type-check. They ran
after the
object cache was cleared, so the creator was charged nothing.
- Deleting the old package moved below the inert branch. The two
orderings
disagreed on stored state, which is a fork.
- Re-submitting a parked package is now limited to its original creator.
Overwrites are silent, so anyone could clobber a pending submission.
- Parking is skipped at genesis, where there is no approver and the
chain
would fail to boot.
Other changes:
- **MsgRun allowlist.** New `run_submitters` param. Empty means today's
behavior: anyone may send it.
- **Policy enforcement.** The check that decides whether a transaction
carries
code missed `MsgEnablePackage` and `MsgDisablePackage`. It is now an
explicit
list that fails closed for message types added later.
- **Default deposit 600M → 100M ugnot.** This is a ceiling, not a
charge. The
largest real deploy among all 321 genesis packages is 276,098 bytes, so
the
new ceiling clears the worst case by about 3.6x.
- **Simulation now verifies signatures on code-bearing transactions.**
It did
not, so a forged signature naming any address bought a full type-check
and
`init()` run off one unauthenticated request.
- **Parameter delegation.** GovDAO can hand one parameter to one other
realm
and take it back at any time. The delegate may only remove entries it
added
itself. `r/nt/commondao` leaves quarantine, since it is the intended
delegate.
- **gpao fails closed.** It ignored whether the transaction it read
actually
succeeded, so a rejected submission could still be approved.
Merging master also surfaced a determinism bug: `EnablePackage`
type-checked
with a test-file getter, which reads a test-stdlib overlay off the
node's local
disk. #6025 removed exactly that from `AddPackage` for the same reason.
Fixed
here.
Consensus-breaking: new and changed vm params, and the storage-charging
order.
The pinned multistore hash was re-derived by running the test.
ADRs are included for the inert charging work and the delegation design.
AI-assisted, reviewed by me before pushing.
---------
Co-authored-by: moul <94029+moul@users.noreply.github.com>
Co-authored-by: Thomas <thomas.bruyelle@tendermint.com>
* fix(gno.land): post-merge fixes for inert packages (#6093)
3 fixes/commits :
- `MsgRejectPackage`: don't check inert approvers for genesis txs
e09e68c069a7efb1150c2e0ccb32bbff104e0ae7
- Deny new `MsgRejectPackage` to session keys (just like
`MsgAddPackage`, `MsgEnablePackage` and `MsgDisablePackage`)
ce7f217a783477dfafb4239b1e2b3b9081639fe0
- Add missing out-of-gas panic recover from new `QueryInertPaths`
---------
Co-authored-by: moul <94029+moul@users.noreply.github.com>
* perf(gnovm,tm2,gno.land): size-aware encode, decode and render paths
Rework a set of hot paths so that work and allocation scale with the actual
input rather than with a declared or worst-case size: stream the nested
interface JSON encoder, size Gno->Go slice conversions by length instead of
capacity, render BitArray from its backing data, make uniqueDecls O(n), bound
the recursive predefine declaration lookup, price the flat-fee natives on
their real operand size, and vendor a bounded toml decoder for gnomod.toml.
Also tightens a few input validators (multisig key structure, ParseCoins,
gnokms authkeys, gnoweb URL schemes and path length, markdown reader
lifetime), bounds the per-connection p2p receive buffer and the WAL backwards
search, gives the remote signer a dial timeout, errors on unverifiable Merkle
proofs, reworks the grc20 teller surface so the frame-relative teller stays
within the token's own realm, and fixes params baseline handling on a
net-zero storage diff.
Co-authored-by: Morgan Bazalgette <morgan@morganbaz.com>
Co-authored-by: Lee ByeongJun <lbj199874@gmail.com>
Co-authored-by: moul <94029+moul@users.noreply.github.com>
Co-authored-by: davd-gzl <60177543+davd-gzl@users.noreply.github.com>
* test(grc20): assert cross-realm event provenance (#6092)
## Summary
Adds `event_provenance_filetest.gno`, the cross-realm counterpart to the
existing `newtoken_event_filetest.gno`. Test-only; no production code
changes.
Related: #6026, #6042.
## Motivation
`newtoken_event_filetest.gno` (#6042) covers the *within-realm* case: a
realm that reuses a `seqid` announces the same `Token.ID()` twice, so an
indexer can flag it.
The *cross-realm* case has never been pinned by a test, which left the
harder question open: given a `Transfer` event, how does a consumer
decide which realm issued the token? Two fields are involved and neither
is sufficient alone:
- **`pkg_path`** is stamped by the VM from the package whose code calls
`chain.Emit` (`gnovm/stdlibs/chain/emit_event.go`). Every genuine grc20
event therefore carries `gno.land/p/demo/tokens/grc20` — a constant
across the ecosystem, so it identifies the library but never the token.
- **the `token` attribute** carries `Token.ID()`, whose leading
component is `rlm.PkgPath()` captured under `IsCurrent()` in `NewToken`.
Chained, they are sufficient: `pkg_path` proves the event came from
grc20's code, and grc20's code only ever writes an `IsCurrent`-verified
realm prefix into `token`. So for any event bearing grc20's `pkg_path`,
the realm prefix inside `token` is unforgeable.
That property is what the indexer rule rests on, and until now nothing
in the tree would have caught a regression in it.
## What the filetest pins
An impostor realm tries both routes available to it against a canonical
registered token (`foo20`), and fails at each:
1. **Ask grc20 for it.** `NewToken("Foo", "FOO", 4, 0, cur)` — same
name, symbol, decimals and id as foo20 — yields
`gno.land/r/demo/grc20provenance.FOO.0000000`. The id prefix comes from
the live crossing frame, so no argument can make it name another realm.
2. **Bypass grc20.** A hand-emitted `Transfer` carrying foo20's exact id
is stamped `"pkg_path": "gno.land/r/demo/grc20provenance"`. An indexer
accepting `Transfer` only from grc20's `pkg_path` drops it.
The asserted `// Events:` block contains all three events, so the two
`pkg_path` values and both id prefixes are part of the expectation
rather than prose.
## The resulting indexer rule
1. Accept grc20 token events only when `pkg_path ==
"gno.land/p/demo/tokens/grc20"`.
2. Read the issuing realm from the leading component of the `token`
attribute.
3. Flag any realm that announces the same `Token.ID()` in more than one
`NewToken` event.
Steps 1–2 settle provenance across realms; step 3 is the within-realm
signal from #6042. Together they cover the ambiguity described in #6026
without a change to the standard.
## Testing
```
gno test -C examples ./gno.land/p/demo/tokens/... ./gno.land/r/demo/defi/...
gno fmt -diff -C examples ./gno.land/p/demo/tokens/grc20/...
gno lint -C examples ./gno.land/p/demo/tokens/grc20/...
```
No ADR: test-only, and it documents existing behaviour rather than
deciding anything (AGENTS.md exempts simple tests).
* feat(gnovm): add chain params reader API" (#6094)
Continues #5698 by @notJoon, which went stale in May. Their commits are
preserved with authorship; I merged master (resolving conflicts in
native_gas.go and the crossrealm38 hash pin) and added documentation
plus a test for wrong-type reads.
Superseding #5698 rather than pushing to their fork so their branch is
left alone. Happy to close this if @notJoon would rather carry it
themselves.
Outstanding: the six chain/params Get* gas rows are copied from the
matching Set* rather than fitted — native_bench_output.txt has no
samples for them. The benchmarks are in this PR; they need a run on the
reference machine.
---------
Co-authored-by: Lee ByeongJun <lbj199874@gmail.com>
* feat(grc721): rewrite core on the Token/PrivateLedger/Teller axis (1/4) (#6072)
## Summary
Rewrites `p/demo/tokens/grc721` around a `Token` / `PrivateLedger` /
`Teller` axis, replacing the old `BasicNFT` monolith, and migrates every
in-tree consumer in the same change.
This is the first of five PRs split out of #6029, which was too large to
review in one piece.
Each PR builds, lints and tests green on its own.
## Motivation
Three properties of the old API made it hard to use safely under the
current interrealm spec:
- **Caller identity was an argument.** Every writer took `caller
address`, so the calling realm asserted who it was. Nothing tied that
address to the frame actually crossing in, and each consumer
re-implemented the check.
- **Reads and writes shared one handle.** `*BasicNFT` carries exported
mutators, so handing it to another realm is a write-authority grant
under borrow rule 2 — the type could not be exposed, only wrapped.
- **Extensions were in-package.** Metadata and royalty lived inside the
core package, so every collection paid their storage and gas cost
whether or not it used them.
GRC20 had already converged on a Token/Ledger/Teller shape; GRC721
diverging from it forced consumers to learn two mental models for the
same problem.
## What changes
- **Core rewrite** — `token.gno`, `tellers.gno` and `types.gno` replace
`basic_nft.gno`, `igrc721*.gno`, `util.gno` and the in-package
metadata/royalty files. `Token` is the read surface, `PrivateLedger` is
the unshared write authority the issuer keeps, and `Teller` is a
capability that writes *as some account*: it takes a secondary `rlm
realm` and rejects it with `ErrSpoofedRealm` unless `rlm.IsCurrent()`
holds. Five grades cover the realistic cases — `CallerTeller`,
`ReadonlyTeller`, `RealmTeller`, `RealmSubTeller`, and the issuer-only
`ImpersonateTeller`.
- **`NewToken` event** on token creation, with a filetest covering the
emitted attributes.
- **Extension hooks** — `RegisterExtension` attaches an issuer-supplied
`Extension` whose `OnMint` / `OnTransfer` / `OnBurn` fire on every
movement. `ExtensionKind` is the identity: one extension per kind, and a
second registration of an attached kind panics. Hooks run after the
ledger write but before the movement event is emitted, so a hook that
panics vetoes the announcement as well as the transaction.
- **EIP-721 conformance fixes** — `Approve(zero)` now revokes a
per-token approval instead of being rejected; `GetApproved` reports
`ErrInvalidTokenId` for a token that is not a valid NFT, rather than
collapsing it into "not approved"; `SetApprovalForAll(op, false)`
releases the operator entry instead of storing `false`.
- **Docs** — `IsCanonicalTeller` is documented as an authenticity check
on the implementation, not an authorization guard on the acting account;
the issuer-hook trust property is stated explicitly.
- **Consumer migration** — `btree_dao`, `eventix`, `tokenhub` and
`foo721` move to the new API in this same PR, so `examples/` never
breaks. `foo721` stays core-only here and grows into the full showcase
in the last PR of the series.
- **Integration test** — `grc721_emit.txtar` is rewritten against the
new core events.
## Teller confinement
`CallerTeller` resolves the acting account from the calling frame, so it
acts as whoever crossed into the realm holding it. That is meaningful
inside the token's own realm, where the wrappers act for a caller who
knowingly invoked the collection. Anywhere else it is a confused deputy,
and `*Token` is a published pointer — exported vars, the collection
facade, `grc721reg.GetToken` — so any realm could otherwise mint one and
take the NFTs of whoever called it. `TransferFrom` is the sharp case: it
resolves the *spender* from the frame, so a realm reached from an honest
hub spends that hub's approvals against any owner who granted one.
Two layers, matching the Token/Ledger split this PR introduces:
- **Construction privacy** — `CallerTeller` hangs off `*PrivateLedger`,
not `*Token`. The token pointer travels; the ledger does not, since
`NewToken` hands it to the creating realm and nowhere else.
- **A write-time home check** — privacy alone is insufficient, because a
realm may legally build a teller and then export the *value*.
`guardHome` compares the invoking realm against `Token.origRealm` on
every write, leaving a leaked teller inert everywhere but home.
`origRealm` is captured in `NewToken` from `rlm.PkgPath()` under the
existing `IsCurrent` assertion, with any `":subpath"` from `realm.Sub`
stripped on both the stored and the invoking side, so a token created
from a sub frame is not locked out of its own host and a host's
sub-realms are not falsely rejected. `Token.ID()` keeps the raw path, so
identities and the `NewToken` event are unchanged.
The guard keys on the invoking realm alone, deliberately not on whether
the resolved actor is an end user: keying on the actor blocks only the
case where the debited party is the signing user, and leaves a realm
chargeable by a realm it calls.
The supported route for a realm that must move someone else's tokens is
unchanged: the owner `Approve`s it, and it spends as itself through
`RealmTeller`, which is eagerly bound to its own address and
approval-gated.
This matches the teller surface `grc20` carries on master as of acd01fa.
## Breaking change
The old surface is removed wholesale:
- **Core** — `BasicNFT`, `NewBasicNFT`, the `IGRC721Reader` interface,
the `NFTGetter` indirection and the `TokenURI` type.
- **Metadata / royalty** — `NewNFTWithMetadata`, `NewNFTWithRoyalty`,
`IGRC721Metadata`, `IGRC721MetadataOnchain`,
`IGRC721CollectionMetadata`, `IGRC2981`, `Metadata`, `Trait` and
`RoyaltyInfo`. These return as opt-in extensions in #6073.
- **Dropped with no replacement** — `SafeMint` and `SafeTransferFrom`
(EIP-721's receiver check needs a registry, and aliasing it under the
same name would imply a safety this package cannot provide), plus
`TokenURI` / `SetTokenURI` and `Getter()`.
Renamed on the read surface: `Name()` → `GetName()`, `Symbol()` →
`GetSymbol()`, `TokenCount()` → `TotalSupply()`.
Kept identical, so migrating readers is mechanical: `BalanceOf(address)
(int64, error)`, `OwnerOf`, `GetApproved`, `IsApprovedForAll`, `Mint`,
`Burn`, `RenderHome`.
Writers change shape by design: the `caller address` argument is gone,
and the acting account is derived from the crossing frame by a `Teller`
— see Motivation.
Per AGENTS.md, breaking `gno.land/p/demo/` backwards-compat needs
discussion, so flagging it explicitly: the package is not part of the
current testnet genesis set, and every in-tree consumer lives under
`examples/quarantined/`, so the blast radius is limited to this
repository.
Publishing the new API under a parallel `/v2` path was considered and
rejected — it would mean a permanent double surface for a package with
no external consumers on chain.
## Testing
- `gno fmt -diff -C examples ./...`
- `gno lint -C examples ./...`
- `gno test -C examples ./gno.land/p/demo/tokens/grc721/...
./quarantined/...`
- `go test ./gno.land/pkg/integration/ -run 'TestTestdata/grc721'`
`grc721_callerteller_home.txtar` covers both foreign-realm paths — a
frame-resolved `TransferFrom` and a `SetApprovalForAll` land-grab — and
asserts the teller **still works at home**, so the guard is scoped
rather than a blanket disable.
Negative control: returning early from `guardHome` makes the
`TransferFrom` attack succeed and the txtar fail on both the
expected-failure and the error-message assertions.
## The rest of the series
Split out of #6029. All five target `master`; the later four are drafts
and should merge in this order, since each builds on the previous one:
1. core(**this PR**) — core rewrite + consumer migration
2. extensions(#6073) — metadata / royalty / enumerable
3. collection(#6074) — read-only `Collection` + `NFT` handle
4. grc721reg(#6075) — collection registry
---------
Co-authored-by: moul <94029+moul@users.noreply.github.com>
* feat(grc721): add stackable metadata, royalty, and enumerable extensions (2/4) (#6073)
## Summary
Adds three independent, stackable extensions on top of the new GRC721
core.
Each lives in its own package, wraps a core token's ledger, and can be
composed freely — a collection may use none, one, or all three.
Second of five PRs split out of #6029.
## What changes
- **`grc721/metadata`** — EIP-721 Metadata plus the OpenSea attribute
convention. Emits `TokenURIUpdate` / `MetadataUpdate`.
- **`grc721/royalty`** — EIP-2981 royalty info, with per-token overrides
on top of a collection default and a configurable bps cap.
- **`grc721/enumerable`** — EIP-721Enumerable, backed by AVL trees so
iteration order is deterministic.
Each package ships its own `gnomod.toml` and a full unit-test suite.
## Design notes
Extensions wrap rather than embed.
Each constructor takes the core `*PrivateLedger` and returns a read view
plus its own ledger, registering an `Extension` hook (`OnMint` /
`OnTransfer` / `OnBurn`) on the core.
Hooks take no `realm` parameter, so they cannot capture a `cur`, and
only the issuer can attach one.
The flip side — an attached hook runs issuer code on every movement and
can veto a transfer by panicking, and gas scales linearly with the
extension count — is documented as an explicit trust grant rather than
left implicit.
## Reviewing this PR
Draft until the core rewrite (first PR of the series, #6072) merges.
Both target `master`, so the diff below still contains the core commits
until then.
---------
Co-authored-by: moul <94029+moul@users.noreply.github.com>
* feat: pearl testnet release candidate (#6091)
Co-authored-by: gfanton <8671905+gfanton@users.noreply.github.com>
Co-authored-by: moul <94029+moul@users.noreply.github.com>
* fix(tm2): /genesis output not amino-decodable (#6098)
This doesn't affect standard nodes: only gnodev, in-memory nodes,
pkg/integration and the gnogenesis contribs are affected.
Essentially when the genesis app state type doesn't implement
`StreamableResult` (has no `StreamJSON()` method), /genesis misses the
amino `@type` field for the `app_state` field, which makes the output
not aminoJSON decodable.
* refactor(tm2)!: make vesting a field on BaseAccount, not an account type (#6095)
Vesting was three account types, and the bank decided whether to apply a
lock by
type-asserting a stored account to `std.VestingAccount`. That assertion
was the
entire enforcement contract, and it was silent whenever it missed.
It missed. gno.land builds accounts as `*GnoAccount`, while genesis
built
`*ContinuousVestingAccount` from a plain `std.BaseAccount` — so a
vesting account
was not a gno.land account. Three consequences, each verified before
changing
anything:
1. It does not implement `std.AccountUnrestricter`, so while ugnot is a
restricted
denom `canSendCoins` finds no whitelist bit and refuses **every**
transfer. The
vesting lock is never even consulted.
2. `applyUnrestrictedAddrs` does an unchecked `acc.(*GnoAccount)`, so
listing a
vesting address in `UnrestrictedAddrs` **panics the chain during
InitChain**:
`interface conversion: std.Account is *std.BaseAccount, not
*gnoland.GnoAccount`.
3. `gnoclient.QueryAccount` unmarshals every account into a concrete
`gnoland.GnoAccount`, and a vesting account's JSON carried a
`VestingSchedule`
field that type had no place for. Querying one failed outright with
`unknown JSON field "VestingSchedule"` — **no client could read a
vesting
account at all**.
`docs/CONSTITUTION.md` requires the configuration that panicked:
*"Whitelisted
funds remain subject to the vesting schedule."* Vesting accounts were
effectively
non-functional on gno.land.
## The change
One account type. `BaseAccount` gains a `VestingSchedule` field, the
schedule
gains the vesting maths, and `std.Account` gains `GetVesting`,
`SetVesting` and
`LockedCoins`. Enforcement reads the field, so which concrete type is
stored
decides nothing.
Deleted: the `VestingAccount` interface, all three account types, both
constructors, `SpendableCoins`, `upgradeVestingAccount`, the `upgraded`
flag
threaded through `subtract`, and `vestingScheduleOf`.
Adding interface methods costs nothing here: `SetAddress` is implemented
exactly
once in the whole tree, on `*BaseAccount`, so every account type already
inherits
by embedding and no independent implementer exists.
`VestingSchedule.Type` now selects the curve at read time instead of
selecting a
type at genesis, so it can no longer disagree with how an account
actually vests.
`upgradeVestingAccount` is gone because there is nothing left to upgrade
— an
elapsed schedule already locks nothing, so collapsing it saved nothing
and cost a
write on a path that could still fail.
### This does not move the app hash
genproto2 emits a struct field only when it marshals to non-zero length,
and a
zero `VestingSchedule` marshals to nothing, so an account without
vesting encodes
byte-for-byte as before. `json:",omitempty"` does the same for JSON, and
the two
are independent — the binary encoding does not depend on the tag.
Measured, not argued: the integration txtar suite, whose goldens contain
account
query output, passes unchanged.
### Breaking state change
Removing the three amino-registered types means state holding one stops
decoding.
Only genesis ever created them and a fork re-parses the text balances
file, so a
fresh or re-genesised chain is unaffected. **Safe because the chain is
pre-mainnet**; a live chain would need a migration.
## Fixes found alongside
Auditing this turned up three faults in how the genesis balance format
is read and
written. **None is caused by the redesign** — master has all three — but
each
decides whether a vesting schedule survives, so they are fixed here
rather than
left beside code that now depends on them.
- **`gnogenesis balances add` silently unlocked accounts.** `LeftMerge`
only fills
in absent addresses and the input sheets merge first, so overriding an
address's
amount dropped its schedule. Silent: what remains looks like any
ordinary
balance. A tx export names every address that ever transacted, so a
vesting
investor who made one transaction came out unlocked.
- **`gnoland start --genesis-balances-file` rejected vesting entries.**
It read the
sheet with its own split-on-`=` parser, which sees three fields in a
vesting
line. The file `gnogenesis` writes was refused at boot. Now delegates to
the same
parser, deleting the duplicate.
- **`balances add`'s summary print dropped the suffix** that `balances
export`
keeps.
The pattern in each: the account now has one owner of what vesting
means, but the
text format had several.
## Changes by area
**tm2/pkg/std** — `Vesting` field on `BaseAccount`;
`GetVesting`/`SetVesting`/
`LockedCoins` on `std.Account`; `vesting.go` replaces
`vesting_account.go` with
the schedule owning its own maths; three amino registrations removed;
`pb3_gen.go` and `std.proto` regenerated by genproto2 (`vesting = 6`,
appended,
fields 1–5 untouched).
**tm2/pkg/sdk/bank** — `SubtractCoins` reads the field instead of
asserting;
`upgradeVestingAccount` and the `upgraded` flag deleted; `subtract` now
reads the
account when the caller passes nil, so nil means "I do not have it" in
both halves
of that function; the account-tier invariant validates the field.
**gno.land/pkg/gnoland** — `applyBalance` builds one account type and
sets the
schedule, with the `Validate`/`IsAllGTE` guards that lived in the
constructors;
`LoadGenesisBalancesFile` delegates to the canonical sheet parser.
**contribs/gnogenesis** — the two `balances` fixes above, plus a
`verify` warning
when a schedule ends at or before genesis or more than a century after
it
(warns rather than rejects, since fork replay legitimately carries
past-dated
schedules).
**Tests** — schedule arithmetic across boundaries, monotonicity and
conservation
over whole schedules including `MaxInt64`; the vesting-plus-whitelist
regression;
`applyBalance`'s guards; the sheet→genesis→enforcement seam; schedule
survival
across the gas path; the two behaviours mutation showed were free to
change (the
`lockedAmt == 0` shortcut and the `max(...,0)` clamp).
**ADRs** — `tm2/adr/prxxxx_vesting_as_an_account_field.md` and
`tm2/adr/prxxxx_vesting_schedule_sharp_edges.md`. *(Rename both once the
PR
numbers exist.)*
## Verification
- `go test ./tm2/pkg/std/ ./tm2/pkg/sdk/... ./gno.land/pkg/gnoland/...
-count=1` — pass
- `go test ./... -count=1` in `contribs/gnogenesis` — pass
- `go test ./gno.land/pkg/integration/ -run TestTestdata -count=1` —
pass
- `go test ./gno.land/pkg/sdk/vm/ -run Gas -count=1` — pass
- `golangci-lint run --config .github/golangci.yml ./...` — 0 issues
- `make fix` — no-op
Every behavioural change was mutation-tested: the mutation applied,
confirmed to
compile, the test run, then restored and the tree diffed. Notable ones —
giving
`BaseVestingAccount` the three methods fails the interface and hazard
tests;
reverting `applyBalance` to the old shape reproduces the genesis panic
verbatim;
dropping either `applyBalance` guard fails exactly its own two cases;
removing the
`balances add` carry-over fails only the override case.
## Known gap
Vesting has no end-to-end txtar coverage, and the harness cannot
currently express
it — `adduser` parses its amount with `std.ParseCoins`, and `gnoland
start` has no
balances-file flag. Closing that means extending the integration
harness, which
belongs in its own change.
AI-assisted: audit, implementation and tests written with Claude Code,
reviewed
before submission.
* chore(deps): bump brace-expansion from 5.0.6 to 5.0.9 in /gno.land/pkg/gnoweb/frontend (#5992)
Bumps `brace-expansion` from 5.0.6 to 5.0.9 in
`/gno.land/pkg/gnoweb/frontend`.
This PR was originally opened by Dependabot targeting 5.0.7. Two further
high-severity advisories were published after it was opened, so the
lockfile
was bumped manually to 5.0.9 — the current `latest` on npm — to close
all of
them in a single change:
| Advisory | Fixed in | Covered by 5.0.7? |
| --- | --- | --- |
| CVE-2026-13149 — exponential-time expansion of consecutive `{}` groups
| 5.0.7 | yes |
| CVE-2026-14257 — OOM crash via unbounded expansion length | 5.0.8 | no
|
| CVE-2026-69152 — DoS bypassing the CVE-2026-14257 mitigation | 5.0.9 |
no |
`brace-expansion` is a dev-only transitive dependency (`minimatch` <-
`glob`,
`nodemon`), so the shipped gnoweb bundle is unaffected; the exposure was
limited
to the frontend build tooling.
Notes:
- `minimatch@10.2.5` requires `brace-expansion@^5.0.5`, so 5.0.9
resolves within
range and no other package moved. The diff is confined to the four lines
of
the `brace-expansion` entry.
- The `integrity` hash was verified against a SHA-512 computed from the
published tarball.
- 5.0.9 narrows `engines.node` from `18 || 20 || >=22` to `20 || >=22`;
CI runs
`lts/Jod` (Node 22), so this is a no-op here.
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alexis Colin <alexis@jaunebleu.co>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(tm2): fsync the ABCI responses record and stop the block when its write fails (#6085)
## Summary
A node killed between the application's commit of height H and
`SaveState(H)` loses the stored ABCIResponses for H. Every subsequent
start then fails the ABCI handshake with:
```
error during handshake: error on replay: Could not find results for height #H
```
The node never recovers on its own. The record exists precisely to cover
this crash window, but it was written without a flush, so it died in the
same crash it was supposed to protect against. This bricked the same
production node twice in two days.
The fix is two small changes in `SaveABCIResponses`:
1. `db.Set` becomes `db.SetSync`, so the record is on disk before the
application commits.
2. Its write error (previously discarded) is returned, so `ApplyBlock`
stops the block *before* the application commit instead of committing a
height whose recovery record was never stored.
Fixes [#6055](https://github.com/gnolang/gno/issues/6055).
<details>
<summary>Mapping to #6055's items (two are deliberately scoped
out)</summary>
The missing flush and the dropped `SaveABCIResponses` error are fixed
here, with regression tests. Scoped out:
- `SaveState`'s own dropped error: past the application commit a save
failure has no in-place remedy (the app is already at H), so returning
it buys no recovery. Reasonable follow-up.
- A handshake-level test against an *already*-skewed directory: a skewed
store cannot be repaired at handshake time; that scenario belongs to
recovery tooling (see "Recovery for already-skewed stores").
</details>
## Root cause
`BlockExecutor.ApplyBlock` persists a block in this order
(`tm2/pkg/bft/state/execution.go`):
1. `SaveABCIResponses(db, H, …)`, a plain `db.Set`
2. the tx result index, also plain `db.Set`
3. `proxyApp.CommitSync()`: the application store commit, atomic and
fsynced
4. `SaveState(db, state)`, which ends in `db.SetSync`
On the WAL-based backends `Set` is unsynced (pebbledb, the production
default, passes `pebble.NoSync`), so steps 1 and 2 become durable only
when step 4 flushes the log. A death between 3 and 4 loses the responses
**and** the state while the block store and the application keep H:
```
block store = H, application = H, state = H-1, abciResponses(H) = missing
```
`Handshaker.ReplayBlocks` handles this shape by replaying H against a
mock application that serves the stored responses (the real application
must not re-execute a height it already committed). `LoadABCIResponses`
is its only source and there is no fallback: startup fails
deterministically, forever.
This is a regression, not a design choice: the forked code wrote this
key with `SetSync`, and
[#1546](https://github.com/gnolang/gno/pull/1546) removed the flush in
the same PR that added the RPC endpoint making the key undiscardable.
CometBFT v1.x uses the same design as this fix.
<details>
<summary>Full upstream history (how the regression happened, with
references)</summary>
- Every upstream release from v0.33 through v0.34.20 wrote this key with
`SetSync`.
- [tendermint#9159](https://github.com/tendermint/tendermint/pull/9159)
+ [#9253](https://github.com/tendermint/tendermint/pull/9253) (v0.34.21,
2022) downgraded it to `Set`, but *simultaneously* moved crash recovery
to a `SetSync`-written `lastABCIResponseKey` ("We always save the last
ABCI response for crash recovery"). Motivation was state.db bloat
([#8946](https://github.com/tendermint/tendermint/issues/8946)), not
durability.
- tm2 took the downgrade **without** the compensating synced key, in
[#1546](https://github.com/gnolang/gno/pull/1546), commit
[c627995](https://github.com/gnolang/gno/commit/c627995589676bb95a7a2a3b6f341a25a72c02cc),
in response to a [review concern about per-tx fsync
cost](https://github.com/gnolang/gno/pull/1546#discussion_r1497945114).
The reply ("we do a CommitSave just shortly after") is inverted for this
record: its only purpose, per its own doc comment, is the crash *before*
that save. The same PR added the RPC tx-results endpoint (`Tx()`
resolves a hash to a height, then reads `LoadABCIResponses` at that
height), which makes the per-height key load-bearing and undiscardable.
A survey of ~36 active tendermint descendants found no other fork with
neither mechanism.
- CometBFT v1.x restored the per-height `SetSync` and deprecated
`lastABCIResponseKey`
([#1976](https://github.com/cometbft/cometbft/issues/1976),
[#2017](https://github.com/cometbft/cometbft/pull/2017), backport
[#2412](https://github.com/cometbft/cometbft/pull/2412)): the same
design as this PR. (Merged as a write-amplification fix; it stayed off
the v0.38 line over a compaction concern that does not apply to a plain
`Set` to `SetSync` change.)
- Upstream's split-key design only makes sense with their "discard ABCI
responses" config flag, which tm2 cannot have while the RPC endpoint
depends on the per-height key. The singleton is not bulletproof either:
it failed in production on CometBFT v0.38.17
([celestia-app#5070](https://github.com/celestiaorg/celestia-app/issues/5070)).
</details>
## Production evidence
Two occurrences in two days on the same gno testnet node
(non-validator), both while it was fast-syncing after a restart and a
routine graceful stop landed inside `ApplyBlock`:
```
2026-08-20: block store = 288055, app = 288055, state = 288054, abciResponses(288055) ABSENT
2026-08-21: block store = 313891, app = 313891, state = 313890, abciResponses(313891) ABSENT
```
Offline analysis with tm2's own load functions confirmed all three
stores individually intact: no bit-rot, just the skew above. Both losses
happened on a clean process exit, no host crash, so the window is not
host-failure-only (tm2 never closes its databases on shutdown).
Note: this is the handshake replay path (`consensus/replay.go`), not the
RPC path. The same error string is widely reported by relayers as a
pruned-height symptom;
[tendermint#7039](https://github.com/tendermint/tendermint/issues/7039)
is the canonical prior report of this exact height-triple, closed by
stalebot without a fix.
## The fix
With `SetSync`, the responses for H are on disk before the application
commits H, so every crash position maps onto a handshake case that
recovers:
| Crash position | Resulting heights | Handshake path |
|---|---|---|
| before the responses flush | app = state = H-1, store = H | replay H
against the real application |
| after it, before the app commit | app = state = H-1, store = H |
replay H against the real application |
| after the app commit, before the state save | app = store = H, state =
H-1 | replay H against the mock, responses guaranteed present |
The error propagation closes the second door into the same window: a
write that *fails* outright (disk full, I/O error) has nothing to flush,
and the old code proceeded to the application commit anyway. Now
`ApplyBlock` aborts while `app = state = H-1, store = H` still holds,
the healthy replay case, so the node self-recovers once the fault
clears. The handshake's InitChain-time save propagates it the same way.
This is a behavior change worth naming: a state-db write error now stops
the node loudly, where the old code carried on and deferred the failure
to an unrecoverable position. Every production caller already has an
exercised error path for it:
- consensus kills the process (matching how it already treats a failed
WAL fsync as fatal)
- fast sync panics
- the handshake fails the start with a clear error
The caller-by-caller analysis is in the ADR (`tm2/adr/`). The tx result
index write stays fire-and-forget deliberately: it is a lookup index,
rewritten on replay, not a recovery record.
**Cost:** five fsyncs per block become six (block store ×2, consensus
WAL, application store, `SaveState`, plus this one), against a 5 s
default commit interval. Fast sync pays it per block, which is precisely
the path that failed in production.
## Tests
- `TestSaveABCIResponsesIsDurable` (`state/store_test.go`): the
crash-recovery contract of the exported function.
- `TestApplyBlockFlushesABCIResponsesBeforeAppCommit`
(`state/execution_test.go`): the ordering through `ApplyBlock`;
snapshots what a restarting process would find at the instant the
application commits.
- `TestSaveABCIResponsesReturnsWriteError`: a failed write surfaces to
the caller.
- `TestApplyBlockAbortsBeforeAppCommitOnResponsesWriteError`: with a
store refusing the responses key, `ApplyBlock` returns the error and the
application's `Commit` is never invoked.
The durability pair fails with the `SetSync` reverted, with the
production error (`Could not find results for height #1`); the error
pair fails with the propagation reverted (returns nil and commits). The
doubles (`unsyncedWriteDB`, `failingWriteDB` in `state/helpers_test.go`)
model the WAL backends' behavior and the tests assert on observable
store contents after a simulated death, not on which method was called.
`go test ./tm2/pkg/bft/...` passes; `-race` on the state package is
clean.
For context, CometBFT maintainers describe this recovery mechanism as
not "well specified" and hard to test
([cometbft#3290](https://github.com/cometbft/cometbft/issues/3290),
[#493](https://github.com/cometbft/cometbft/issues/493)); upstream has
no equivalent coverage.
## Recovery for already-skewed stores
This PR prevents new occurrences; it does not repair a data directory
already in the skewed state. `contribs/gnobr`
([#5410](https://github.com/gnolang/gno/pull/5410), currently on
`chain/gnoland1`) can already dig such a node out, at the cost of a full
local replay (it wipes `gnolang.db` and replays from height 0). A
lighter path would be an app-store rollback of one version, like
tendermint/CometBFT's `rollback` command
([tendermint#7033](https://github.com/tendermint/tendermint/pull/7033)),
which makes the handshake take the real-application replay path. A
replay-side fallback inside the handshake was considered and rejected as
unsound: rebuilding state for H needs `EndBlock`'s validator/param
updates, which are not derivable from the block, and guessing risks a
silent fork (reasoning in the ADR).
One more follow-up, out of scope here: shutdown does not drain an
in-flight `ApplyBlock` during fast sync, which is why a routine stop hit
this window. Draining narrows the window but cannot make any single
crash position recoverable, so it is complementary, not an alternative.
## AI assistance
AI-assisted; see the ADR's "AI assistance" section for what was
machine-derived and how it was reviewed. The human author reviewed and
owns the change.
## Note for operators
Until recovery tooling lands on master, recovering a skewed store means
restoring from a snapshot. Meanwhile, do not stop a catching-up node:
gate stops on `sync_info.catching_up == false`. That gate is deployed
and validated in production on the affected network's snapshot pipeline.
* fix(docs): don't link-check chain RPC endpoints (#6100)
## Problem
`ci / codegen-verify` (the `docs` matrix leg) is red on `master`, and
has been since 2026-08-27. [Failing
run](https://github.com/gnolang/gno/actions/runs/33150009390):
```
found items that need linting
Remote links that need checking:
>>> https://rpc.gno.land:443 (found in file: docs/resources/gas-fees.md)
>>> https://rpc.gno.land:443 (found in file: docs/users/interact-with-gnokey.md)
... (11 occurrences)
exit status 1
make: *** [Makefile:2: lint] Error 1
```
The links are not actually broken. `rpc.gno.land` is serving a
certificate issued for `rpc.betanet.testnets.gno.land` that **expired on
2026-08-27 14:05 UTC**:
```
$ echo | openssl s_client -connect rpc.gno.land:443 -servername rpc.gno.land \
| openssl x509 -noout -subject -dates
subject=CN=rpc.betanet.testnets.gno.land
notBefore=May 29 14:05:45 2026 GMT
notAfter=Aug 27 14:05:44 2026 GMT
```
The docs linter GETs every remote URL it finds, so the TLS verification
failure surfaces as eleven "broken" links and fails the job.
## Fix
The linter shouldn't be link-checking chain RPC endpoints at all. They
are JSON-RPC APIs, not documentation pages — the response to a plain GET
says nothing about whether the documented endpoint is correct, while it
does make docs CI depend on a live chain's uptime and TLS certificate.
This skips `rpc.*` hosts, which is the same reasoning already applied to
`staging.gno.land` in that file ("deployment-specific hosts whose uptime
is not a CI concern"). It also covers `rpc.pearl.testnets.gno.land`,
which would hit the identical problem at its next certificate rotation.
While here, the exclusion condition — now eight entries with interleaved
comments — moves out of the `if` into `shouldCheckURL`, and the RPC
check runs against the parsed hostname so a path segment like
`https://example.org/rpc.gno.land` is still checked.
`docs/README.md` and the other docs are untouched; the URLs stay exactly
as they are.
## Verification
```
$ cd docs && make lint
Lint complete, no issues found.
$ cd misc/docs/tools/linter && go test ./...
ok
```
`make generate` in `docs/` leaves the tree clean, so the other half of
the `codegen-verify` job is unaffected.
New tests cover the skip list and the hostname-vs-path distinction.
## Still needed (infra, not this PR)
**The `rpc.gno.land` certificate needs renewing.** This PR only stops
docs CI from failing on it; betanet's RPC endpoint is currently unusable
for anything that verifies TLS.
---
Written with AI assistance (Claude Code); reviewed before submitting.
* chore(gno.land)!: remove unused MsgDisablePackage (#6130)
MsgDisablePackage was wired through every layer -- registered in the
amino codec as m_disable_pkg, routed by vmHandler.Process, covered by
txCarriesCode and sessionAlwaysDenied, matched by gnokey's
txNeedsSimulationSignature -- but its keeper method only ever checked
the approver gate and returned "disable_package is not yet implemented".
So the whole surface existed for a message whose only possible outcome
was an error, and the tests pinned that error rather than any behaviour.
The follow-up that would have implemented it never landed, and #6088's
own review notes record why it is not small: it needs eviction of
executed objects from the base store, and the storage deposit taken at
enable would have to be released. Neither has a design.
Its purpose is also unclear. MsgRejectPackage already covers the
operationally needed case -- clearing a package parked awaiting
approval, on the creator's or an approver's request. What is left for
disable is un-deploying live code, which raises questions this series
never answered: what happens to callers that imported the package, to
its realm state, to its storage deposit, and to the addresses that paid
it. That is a design discussion, and it does not need a placeholder
message on the wire to start.
Removes the message, its keeper stub, its route, its amino registration
and the layers that enumerated it; regenerates pb3_gen.go and vm.proto
with `make -C misc/genproto2`; and drops the stub-only tests along with
the disable_package rows in the codec-parity, txCarriesCode,
session-deny and simulation-signature tables. Comments that named the
stub are updated in place.
Nothing that worked stops working, since the message had no success
path. It does unregister the m_disable_pkg amino type, so
vm/disable_package no longer decodes: a chain whose history contains
such a transaction -- it could only fail, but a failed message is still
committed into a block -- cannot replay that block on a post-removal
binary. chain/pearl registers the type, so check before upgrading a
pearl node across this change rather than restarting from a fresh
genesis. No mainnet is affected; there is none.
Closes #6125
* fix(gpao): derive a dependency's name from its production files (#6124)
Importing `gno.land/p/demo/tokens/grc20` is a terminal rejection, and
the reason names a package the submitter never wrote.
Three packages in `examples/` are unimportable this way:
`p/demo/tokens/grc20` (named `grc20subrealm`), `p/demo/tokens/grc721`
(named `grc721dupsignal`), and `p/nt/treasury/v0` (named
`canonicaltest`). Counted across all 325 package directories with the
derivation the chain itself uses.
### A filetest sorts first and names the package
[`vm/qfile` serves a package's files
sorted](https://github.com/gnolang/gno/blob/2ed70a202e6f92364be56c5c17ddd706e0c9d922/gnovm/pkg/gnolang/store.go#L1199),
and [`ReadMemPackage` flattens `filetests/` into that
list](https://github.com/gnolang/gno/blob/2ed70a202e6f92364be56c5c17ddd706e0c9d922/gnovm/pkg/gnolang/mempackage.go#L821-L833),
so a filetest routinely arrives ahead of the production files.
[`packageName` took the first `.gno` file that
parsed](https://github.com/gnolang/gno/blob/2ed70a202e6f92364be56c5c17ddd706e0c9d922/contribs/gpao/getter.go#L123-L134),
and filetests carry package clauses of their own.
```
caller_teller_sub_realm_filetest.gno # package grc20subrealm <- taken
gnomod.toml
token.gno # package grc20
token_test.gno # package grc20_test
```
The wrong name reaches the typechecker, which emits `.gnobuiltins.gno`
under it:
```
.gnobuiltins.gno:1:1: package grc20subrealm; expected package grc20
token.gno:3:14: undefined: address
token.gno:5:14: undefined: realm
```
`handleCandidate` then records `rejected` and marks the content hash
seen, so resubmitting identical bytes changes nothing.
### The chain already has the rule
[`ReadMemPackageFromList`](https://github.com/gnolang/gno/blob/2ed70a202e6f92364be56c5c17ddd706e0c9d922/gnovm/pkg/gnolang/mempackage.go#L910)
derives a package's own name by skipping filetests, whose clauses ["may
have arbitrary package
names"](https://github.com/gnolang/gno/blob/2ed70a202e6f92364be56c5c17ddd706e0c9d922/gnovm/pkg/gnolang/mempackage.go#L964),
and trimming a `_test` suffix. For a package holding only filetests it
[takes the filetests' clause where they agree and the literal
`"filetests"` where they do
not](https://github.com/gnolang/gno/blob/2ed70a202e6f92364be56c5c17ddd706e0c9d922/gnovm/pkg/gnolang/mempackage.go#L1008-L1014).
`packageName` now does the same.
An empty name was never a safe fallback: it leaves `.gnobuiltins.gno`
unparseable, and the verifier reports a panic rather than a diagnostic.
### Left alone
- Which files the typechecker considers is unchanged. The getter labels
the reconstructed package `MPUserProd`, which excludes tests and
filetests at typecheck.
- Which imports are fetched from the chain and which from disk is
unchanged. That is Q5 on #6113.
Other gpao defects and the design questions behind them: #6113.
🤖 Written with AI assistance (Claude); reviewed and submitted by a
human.
---------
Signed-off-by: Jeff Thompson <jeff@thefirst.org>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Morgan <morgan@morganbaz.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Miguel Victoria Villaquiran <miguelvicvil@gmail.com>
Co-authored-by: ltzmaxwell <ltz.maxwell@gmail.com>
Co-authored-by: Lee ByeongJun <lbj199874@gmail.com>
Co-authored-by: ltzmaxwell <6007578+ltzmaxwell@users.noreply.github.com>
Co-authored-by: Jeff Thompson <jeff@thefirst.org>
Co-authored-by: Jae Kwon <53785+jaekwon@users.noreply.github.com>
Co-authored-by: Thomas <thomas.bruyelle@tendermint.com>
Co-authored-by: davd-gzl <60177543+davd-gzl@users.noreply.github.com>
Co-authored-by: jinoosss <112360739+jinoosss@users.noreply.github.com>
Co-authored-by: Antoine Eddi <5222525+aeddi@users.noreply.github.com>
Co-authored-by: gfanton <8671905+gfanton@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alexis Colin <alexis@jaunebleu.co>
Summary
Moves the audit pattern harness into this repo and keeps the public builder-facing updates alongside it.
This adds:
misc/audit-pattern-harness: a small audit pattern harness with YAML expected records, sanitized fixtures,gno testexecution, and Markdown/JSON reports viacmd/auditpatterncur.Previous()beforecur.IsCurrent()Render(path)markdown outputRenderoutput that depends on map iteration orderOriginSend()without anIsUserCall()guardOriginCaller()used as authorization identitycur realmgno.land/r/docs/security_patterns: a compact example realm showing authenticated mutators and safe Render outputgno-data-structures.mdcommunity-packages.md: a disclaimer-backed place for non-official helper packages such asmoul/md,ulist,addrset, andfifoThe additional patterns were calibrated from local
examples/plus checked-out Gno contract repos including GnoSwap, Akkadia, gno-ibc, and gno-mcp fixtures, then reduced into sanitized fixtures rather than copying source.Validation
go test ./...inmisc/audit-pattern-harnessmake run GO=/home/russel/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.25.9.linux-amd64/bin/go AUDIT_PATTERN_FLAGS='-gno-bin /tmp/gno-audit-harness-gno'inmisc/audit-pattern-harnesswithGNOROOT=/home/russel/p/gh/gnoland/gnogno test .inexamples/gno.land/r/docs/security_patternswithGNOROOT=/home/russel/p/gh/gnoland/gnogno test .inexamples/gno.land/r/docs/homewithGNOROOT=/home/russel/p/gh/gnoland/gnogit diff --checkAssisted-By: OpenAI Codex