Repository navigation
Conversation
Contributor
Author
|
PS: Logos are... emojis? nevermind only one way to know for sure. |
Contributor
Author
|
Tests should become a part of the Makefile |
thehowl
added a commit
that referenced
this pull request
Jan 15, 2024
Before:
```
gno test -verbose .
=== RUN TestFtoa
panic: cannot convert BigintKind to Uint64Kind
goroutine 1 [running]:
github.com/gnolang/gno/gnovm/pkg/gnolang.ConvertTo(0x0, {0xecc8b8, 0xc00026c3f0}, 0xc00011e190, {0xebe6d8, 0xeb0d78})
/home/howl/oc/gno/gnovm/pkg/gnolang/values_conversions.go:868 +0x6479
github.com/gnolang/gno/gnovm/pkg/gnolang.(*Machine).doOpConvert(0xc0000f4a20)
/home/howl/oc/gno/gnovm/pkg/gnolang/op_expressions.go:699 +0x71
github.com/gnolang/gno/gnovm/pkg/gnolang.(*Machine).Run(0xc0000f4a20)
/home/howl/oc/gno/gnovm/pkg/gnolang/machine.go:1227 +0xfce
[... more stacktrace ...]
```
After:
```
=== RUN TestFtoa
.: test pkg: panic: cannot convert BigintKind to Uint32Kind
gno machine: Machine:
CheckTypes: false
Op: [OpHalt OpBody OpRangeIter OpPopBlock OpBody OpReturn OpBody OpPopResults OpExec OpBody OpPopResults OpExec OpBody OpForLoop OpPopBlock OpBody OpDefine OpBody OpReturn OpPrecall OpBody OpPopBlock OpBody OpPopBlock OpBody OpPopBlock OpBody OpPopResults OpExec OpBody OpDefine]
Values: (len: 9)
#8 (ryuFtoaFixed32 func(d *gno.land/r/fG5GBXmX.decimalSlice,mant uint32,exp int,prec int)())
#7 (genericFtoa func(dst []uint8,val float64,fmt uint8,prec int,bitSize int)( []uint8))
#6 (typeval{string} type{})
#5 (FormatFloat func(f float64,fmt uint8,prec int,bitSize int)( string))
#4 (TestFtoa func(t *testing.T)())
#3 (tRunner func(t *testing.T,fn testing.testingFunc,logSteps bool)())
#2 (RunTest func(runFlag string,verbose bool,test testing.InternalTest)(ret string))
#1 (slice[(struct{("TestFtoa" string),(TestFtoa func(t *testing.T)())} testing.InternalTest),(struct{("TestFormatFloatInvalidBitSize" string),(TestFormatFloatInvalidBitSize func(t *testing.T)())} testing.InternalTest)] []testing.InternalTest)
#0 (runtest func(name string)(report string))
Exprs:
#0 (const-type string)(genericFtoa<VPBlock(3,12)>((const (make func(t type{},z ...interface{})( []uint8)))([](const-type uint8), (const (0 int)), max<VPBlock(3,21)>(prec<VPBlock(1,2)> + (const (4 int)), (const (24 int)))), f<VPBlock(1,0)>, fmt<VPBlock(1,1)>, prec<VPBlock(1,2)>, bitSize<VPBlock(1,3)>))
Stmts:
#16 bodyStmt[0/0/12]=di<VPBlock(1,7)>, dfrac<VPBlock(1,12)> := di<VPBlock(1,7)> >> extra<VPBlock(1,10)>, di<VPBlock(1,7)> & extraMask<VPBlock(1,11)>*
#15 return
#14 bodyStmt[0/0/2]=ok<VPBlock(4,12)> = (const (true bool))
#13 bodyStmt[0/0/4]=(end)
#12 bodyStmt[0/0/1]=(end)
#11 bodyStmt[0/0/14]=if !ok<VPBlock(2,12)> { return bigFtoa<VPBlock(4,13)>(dst<VPBlock(2,0)>, prec<VPBlock(2,3)>, fmt<VPBlock(2,2)>, (const-type bool)(neg<VPBlock(2,8)>), mant<VPBlock(2,10)>, exp<VPBlock(2,9)>, flt<VPBlock(2,7)>) }
#10 bodyStmt[0/0/1]=(end)
#9 bodyStmt[0/0/1]=if (const-type bool)(s<VPBlock(2,0)> != test<VPBlock(3,1)>.s) { t<VPBlock(4,0)>.Error((const ("testN=32" string)), test<VPBlock(3,1)>.f, (const-type string)(test<VPBlock(3,1)>.fmt), test<VPBlock(3,1)>.prec, (const ("want" string)), test<VPBlock(3,1)>.s, (const ("got" string)), s<VPBlock(2,0)>) }*
#8 bodyStmt[0/0/6]=(end)
#7 bodyStmt[0/0/1]=(end)
#6 return
#5 bodyStmt[0/0/4]=t<VPBlock(1,0)>.finished = (const (true bool))
#4 return
#3 bodyStmt[0/0/3]=report<VPBlock(1,5)> := t<VPBlock(1,4)>.report()
#2 bodyStmt[0/0/1]=(end)
#1 bodyStmt[2/0/1]=(end)
#0 bodyStmt[0/0/1]=panic((const ("no such test: " string)) + name<VPBlock(1,0)>)*
Blocks:
@(1) Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2d2c0,Source:func ryuFtoaFixed32(d *(decimalS...,Parent:0xc000bf43c0)
d: (&0xc004331cb8.(*gno.land/r/fG5GBXmX.decimalSlice) *gno.land/r/fG5GBXmX.decimalSlice)
mant: (16777216 uint32)
exp: (-23 int)
prec: (6 int)
e2: (-24 int)
q: (5 int)
exact: (true bool)
di: (1638400000 uint32)
dexp2: (-14 int)
d0: (true bool)
extra: (14 uint)
extraMask: (undefined)
dfrac: (undefined)
roundUp: (undefined)
(s vals) @(1) Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc00036bc20,Source:func ryuFtoaFixed32(d *(decimalS...,Parent:0xc00052f620)
d: (nil *gno.land/r/fG5GBXmX.decimalSlice)
mant: (0 uint32)
exp: (0 int)
prec: (0 int)
e2: (0 int)
q: (0 int)
exact: (false <untyped> bool)
di: (0 uint32)
dexp2: (0 int)
d0: (false bool)
extra: (0 uint)
extraMask: (0 uint32)
dfrac: (0 uint32)
roundUp: (false bool)
(s typs) @(1) [*gno.land/r/fG5GBXmX.decimalSlice uint32 int int int int <untyped> bool uint32 int bool uint uint32 uint32 bool]
@(2) Block(ID:89285d5563b8e2373ce3416c367151d9c4102930:5,Addr:0xc000bf43c0,Source:file{ package strconv; import bi...,Parent:0xc0003325a0)
bits: (package(bits math/bits) package{})
(s vals) @(2) Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc00052f620,Source:file{ package strconv; import bi...,Parent:0xc00037ede0)
bits: (package(bits math/bits) package{})
(s typs) @(2) [package{}]
@(3) gno.land/r/fG5GBXmX
Blocks (other):
#13 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2d0e0,Source:if (const-type bool)(bitSize<VPB...,Parent:0xc004f2cd20)
(static) #13 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc00016b020,Source:if (const-type bool)(bitSize<VPB...,Parent:0xc00016bac8)
#12 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2cd20,Source:if (const-type bool)(fmt<VPBlock...,Parent:0xc004f2cb40)
(static) #12 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc00016b820,Source:if (const-type bool)(fmt<VPBlock...,Parent:0xc000170568)
#11 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2cb40,Source:if (const-type bool)(shortest<VP...,Parent:0xc004f2be00)
(static) #11 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc000170020,Source:if (const-type bool)(shortest<VP...,Parent:0xc000701420)
#10 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2be00,Source:func genericFtoa(dst [](const-ty...,Parent:0xc0017a0000)
dst: (slice[0x] []uint8)
val: (1 float64)
fmt: (101 uint8)
prec: (5 int)
bitSize: (32 int)
.res_0: (nil []uint8)
bits: (1065353216 uint64)
flt: (&0xc005fd7668.(*gno.land/r/fG5GBXmX.floatInfo) *gno.land/r/fG5GBXmX.floatInfo)
neg: (false bool)
exp: (0 int)
mant: (8388608 uint64)
digs: (struct{(slice[0x000000000000000000000000000000000000000000000000] []uint8),(0 int),(0 int)} gno.land/r/fG5GBXmX.decimalSlice)
ok: (false bool)
shortest: (false bool)
(static) #10 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc000701420,Source:func genericFtoa(dst [](const-ty...,Parent:0xc00023c2e0)
dst: (nil []uint8)
val: (0 float64)
fmt: (0 uint8)
prec: (0 int)
bitSize: (0 int)
.res_0: (nil []uint8)
bits: (undefined)
flt: (undefined)
neg: (false <untyped> bool)
exp: (0 int)
mant: (0 uint64)
digs: (undefined)
ok: (false bool)
shortest: (false <untyped> bool)
#9 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2b680,Source:func FormatFloat(f (const-type f...,Parent:0xc0017a0000)
f: (1 float64)
fmt: (101 uint8)
prec: (5 int)
bitSize: (32 int)
.res_0: ( string)
(static) #9 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc000700c20,Source:func FormatFloat(f (const-type f...,Parent:0xc00023c2e0)
f: (0 float64)
fmt: (0 uint8)
prec: (0 int)
bitSize: (0 int)
.res_0: ( string)
#8 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004f2b4a0,Source:if (const-type bool)((const-type...,Parent:0xc004d60780)
(static) #8 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc0004e4020,Source:if (const-type bool)((const-type...,Parent:0xc0003fac20)
#7 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004d60780,Source:for i<VPBlock(1,0)> := (const (0...,Parent:0xc004d605a0)
i: (0 int)
test: (&0xc0080f1300.(*gno.land/r/fG5GBXmX.ftoaTest) *gno.land/r/fG5GBXmX.ftoaTest)
s: ("1.00000e+00" string)
x: (slice[0x616263312E3030303030652B3030] []uint8)
(static) #7 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc0003fac20,Source:for i<VPBlock(1,0)> := (const (0...,Parent:0xc000101420)
i: (0 int)
test: (nil *gno.land/r/fG5GBXmX.ftoaTest)
s: ( string)
x: (nil []uint8)
#6 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004d605a0,Source:func TestFtoa(t *(testing<VPBloc...,Parent:0xc008cd8000)
t: (&0xc0049c01e0.(*testing.T) *testing.T)
(static) #6 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc000101420,Source:func TestFtoa(t *(testing<VPBloc...,Parent:0xc0004ee020)
t: (nil *testing.T)
#5 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004c39c20,Source:func tRunner(t *(T<VPBlock(2,3)>...,Parent:0xc0083aa780)
t: (&0xc0049c01e0.(*testing.T) *testing.T)
fn: (TestFtoa func(t *testing.T)())
logSteps: (false bool)
(static) #5 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc001ff8020,Source:func tRunner(t *(T<VPBlock(2,3)>...,Parent:0xc0008ed620)
t: (nil *testing.T)
fn: (nil testing.testingFunc)
logSteps: (false bool)
#4 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004c39860,Source:func RunTest(runFlag (const-type...,Parent:0xc0083aa780)
runFlag: ("" string)
verbose: (true bool)
test: (struct{("TestFtoa" string),(TestFtoa func(t *testing.T)())} testing.InternalTest)
ret: ( string)
t: (&0xc0049c01e0.(*testing.T) *testing.T)
report: (undefined)
out: (undefined)
(static) #4 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc001fefc20,Source:func RunTest(runFlag (const-type...,Parent:0xc0008ed620)
runFlag: ( string)
verbose: (false bool)
test: (nil testing.InternalTest)
ret: ( string)
t: (nil *testing.T)
report: (nil testing.Report)
out: (nil gonative{[]uint8})
#3 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004c39680,Source:if (const-type bool)(test<VPBloc...,Parent:0xc004c394a0)
(static) #3 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc0083f1020,Source:if (const-type bool)(test<VPBloc...,Parent:0xc00bfc6f20)
#2 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004c394a0,Source:for _<VPBlock(0,0)>, test<VPBloc...,Parent:0xc004c392c0)
test: (struct{("TestFtoa" string),(TestFtoa func(t *testing.T)())} testing.InternalTest)
(static) #2 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc00bfc6f20,Source:for _<VPBlock(0,0)>, test<VPBloc...,Parent:0xc009e5e420)
test: (nil testing.InternalTest)
#1 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc004c392c0,Source:func runtest(name (const-type st...,Parent:0xc004c38f00)
name: ("TestFtoa" string)
report: ( string)
(static) #1 Block(ID:0000000000000000000000000000000000000000:0,Addr:0xc009e5e420,Source:func runtest(name (const-type st...,Parent:0xc0082d1ba0)
name: ( string)
report: ( string)
Frames:
#8 [FRAME FUNC:ryuFtoaFixed32 RECV:(undefined) (4 args) 28/8/1/15/14 LASTPKG:gno.land/r/fG5GBXmX LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
#7 [FRAME FUNC:genericFtoa RECV:(undefined) (5 args) 20/7/1/11/10 LASTPKG:gno.land/r/fG5GBXmX LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
#6 [FRAME FUNC:FormatFloat RECV:(undefined) (4 args) 17/5/0/10/9 LASTPKG:gno.land/r/fG5GBXmX LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
#5 [FRAME LABEL: 13/5/0/8/7]
#4 [FRAME FUNC:TestFtoa RECV:(undefined) (1 args) 11/4/0/6/6 LASTPKG:testing LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
#3 [FRAME FUNC:tRunner RECV:(undefined) (3 args) 8/3/0/4/5 LASTPKG:testing LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
#2 [FRAME FUNC:RunTest RECV:(undefined) (3 args) 6/2/0/3/4 LASTPKG:gno.land/r/fG5GBXmX LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
#1 [FRAME LABEL: 2/1/0/1/2]
#0 [FRAME FUNC:runtest RECV:(undefined) (1 args) 1/0/0/0/1 LASTPKG:gno.land/r/fG5GBXmX LASTRLM:Realm{Path:"gno.land/r/fG5GBXmX",Time:881}#89285D5563B8E2373CE3416C367151D9C4102930]
Realm:
gno.land/r/fG5GBXmX
Exceptions:
[]
stracktrace:
test.go:446 main.runTestFiles.func1
panic.go:914 runtime.gopanic
values_conversions.go:868 gnolang.ConvertTo
op_expressions.go:699 gnolang.(*Machine).doOpConvert
machine.go:1227 gnolang.(*Machine).Run
machine.go:636 gnolang.(*Machine).Eval
test.go:478 main.runTestFiles
test.go:346 main.gnoTestPkg
test.go:257 main.execTest
test.go:99 main.newTestCmd.func1
command.go:233 commands.(*Command).Run
command.go:237 commands.(*Command).Run
command.go:118 commands.(*Command).ParseAndRun
main.go:14 main.main
proc.go:267 runtime.main
asm_amd64.s:1650 runtime.goexit
; panic: gno.land/r/fG5GBXmX_test/decimal_test.gno:5: dot imports not allowed in Gno
gno machine: Machine:
CheckTypes: false
Op: []
Values: (len: 0)
Exprs:
Stmts:
Blocks:
@(1) gno.land/r/fG5GBXmX_test
Blocks (other):
Frames:
Realm:
gno.land/r/fG5GBXmX_test
Exceptions:
[]
stracktrace:
stracktrace:
…no/gnovm/cmd/gno/test.go:446 main.runTestFiles.func1
…/go/src/runtime/panic.go:914 runtime.gopanic
…kg/gnolang/preprocess.go:173 gnolang.Preprocess.func2.1
…/go/src/runtime/panic.go:920 runtime.gopanic
…o/src/math/big/natdiv.go:520 big.nat.div
…b/go/src/math/big/int.go:268 big.(*Int).Quo
…pkg/gnolang/op_binary.go:870 gnolang.quoAssign
…pkg/gnolang/op_binary.go:256 gnolang.(*Machine).doOpQuo
…m/pkg/gnolang/machine.go:1154 gnolang.(*Machine).Run
…m/pkg/gnolang/machine.go:662 gnolang.(*Machine).EvalStatic
…kg/gnolang/preprocess.go:2150 gnolang.evalConst
…kg/gnolang/preprocess.go:784 gnolang.Preprocess.func2
…kg/gnolang/transcribe.go:728 gnolang.transcribe
…kg/gnolang/transcribe.go:371 gnolang.transcribe
…kg/gnolang/transcribe.go:670 gnolang.transcribe
…kg/gnolang/transcribe.go:708 gnolang.transcribe
…kg/gnolang/transcribe.go:133 gnolang.Transcribe
…kg/gnolang/preprocess.go:149 gnolang.Preprocess
…m/pkg/gnolang/machine.go:443 gnolang.(*Machine).runFiles
…m/pkg/gnolang/machine.go:398 gnolang.(*Machine).RunFiles
…no/gnovm/cmd/gno/test.go:466 main.runTestFiles
…no/gnovm/cmd/gno/test.go:346 main.gnoTestPkg
…no/gnovm/cmd/gno/test.go:257 main.execTest
…no/gnovm/cmd/gno/test.go:99 main.newTestCmd.func1
…/pkg/commands/command.go:233 commands.(*Command).Run
…/pkg/commands/command.go:237 commands.(*Command).Run
…/pkg/commands/command.go:118 commands.(*Command).ParseAndRun
…no/gnovm/cmd/gno/main.go:14 main.main
…b/go/src/runtime/proc.go:267 runtime.main
…/src/runtime/asm_amd64.s:1650 runtime.goexit
FAIL
FAIL . 2.19s
FAIL
FAIL
FAIL: 0 build errors, 1 test errors
```
zivkovicmilos
added a commit
that referenced
this pull request
Jun 24, 2024
* Update proto location * Add initial consensus flow * Detail consensus flow * Add unit tests for the propose timeout
This was referenced Nov 28, 2023
matijamarjanovic
pushed a commit
to matijamarjanovic/gno
that referenced
this pull request
May 15, 2025
…d-new-tests feat: json adaptation and new mk tests
zivkovicmilos
pushed a commit
that referenced
this pull request
May 30, 2025
clockworkgr
added a commit
that referenced
this pull request
Apr 17, 2026
Eliminates allocations and redundant tree walks on the highest-frequency APIs (Set, Remove, Hash, WorkingHash, SaveVersion, GetNonMembershipProof, AvailableVersions) without changing tree semantics, hashing, versioning, or proof format. Full race suite (~385s) and downstream consumers (tm2/pkg/store/bptree, gno.land/pkg/sdk/vm) pass unchanged. Finding #4 — saveNode skips clean subtrees. - The old recursion called inner.getChild(i) for every child, which triggers a DB read + ReadNode + 31-hash mini-merkle rebuild for any loaded-but-unchanged sibling of a mutated leaf. - saveNode now consults inner.childNodes[i] directly: nil entries are unchanged (their serialized ref and hash were preserved by Clone() and remain authoritative); cached children whose NodeKey is already set are clean reads and also skipped. Only dirty children (childNodes[i] != nil && GetNodeKey() == nil) are recursed into. Finding #14 — AvailableVersions uses a single prefix scan. - Previous implementation iterated v := first..latest and called VersionExists per value, producing O(retained_versions) random DB point lookups and inflating cost on long-lived chains. - Now runs one PrefixRoot iterator, parsing the big-endian version tail of each key and returning results in ascending order without a sort step. Finding #17 — Conditional root COW clone. - treeInsert and treeRemove previously cloned the root on every call, a ~4.3 KB struct copy per Set / Remove even when the tree had already been cloned earlier in the same working version. - MutableTree.cowRoot() now clones only when t.root is shared with t.lastSaved or still carries a durable NodeKey from a prior SaveVersion / LoadVersion; subsequent mutations in the same working version descend into an already-mutable root. Set and Remove call cowRoot(); treeInsert and treeRemove trust the caller. - Snapshot now defensively clones t.root so subsequent COW mutations on the MutableTree cannot corrupt the snapshot's view. The existing TestMutableTree_COW_OldReferencesValid is updated to capture via Snapshot() (the public API) rather than reach into tree.root. Finding #21 — Hot-path allocation reductions. Several independent issues were driving allocations on every Set, every Hash() call, and every proof step. All are addressed under a single heading because they share the same measurement. * NodeKey bytes cache. - NodeKey carries its serialized form (12 bytes) on the struct and NewNodeKey / NextNodeKey / GetNodeKey precompute it at construction. GetKey() is now a field load on the hot paths; the lazy assignment is kept for struct-literal callers (tests). - GetNodeKey makes a defensive copy of the input before caching so buffer reuse at the DB layer cannot corrupt later GetKey() reads. * encodeNodeKeyBytes bypasses the NodeKey wrapper. - allocValueKey and Importer.Add only need the 12 serialized bytes; they now call encodeNodeKeyBytes directly, saving one heap allocation per Set and per imported leaf. * Root-hash cache on MutableTree. - cachedRootHash and cachedSavedHash hold the []byte views returned by WorkingHash() / Hash(). Each naive `h := x.Hash(); return h[:]` forced h to escape to the heap on every call; downstream callers (store wrappers, block execution) invoke these many times per block. - Invalidated at all mutation points: Set and Remove clear cachedRootHash; LoadVersion clears both; Rollback reuses the saved hash as the new working hash; SaveVersion reuses the working hash as the new saved hash. SaveVersion now routes through WorkingHash() so the first caller populates both caches in one step and the idempotent-save path reuses the cached bytes. * MiniMerkleDepth compile-time constant. - The former miniMerkleDepth() ran a log₂ loop on every call. It is now a const (= 5) with an init-time assertion that B == 1<<MiniMerkleDepth, so future B changes still produce a build-time failure if the constant is not updated. * SiblingPath returns fixed-size arrays. - Returning [MiniMerkleDepth]Hash / [MiniMerkleDepth]int by value keeps the proof-step results on the caller's stack. The old make([]T, 0, 5) pair allocated twice per proof inner op. * Leaf and inner split scratch arrays live on the stack. - leafInsert and innerInsert previously issued eight make() calls across the split paths. The scratch arrays are now declared as fixed-size locals (`var allKeys [B+1][]byte`, etc.) and passed as slices to splitLeaf / splitInner, which copy out of them before returning. Escape analysis confirms the backing arrays do not escape. * Non-membership proof walks reduced from six to three. - The old GetNonMembershipProof walked the tree six times: Has → GetWithIndex → GetByIndex(idx-1) → createExistenceProof(leftKey) → GetByIndex(idx) → createExistenceProof(rightKey). Each neighbor existence proof re-walked by key even though we had just descended to that index. - The new implementation calls treeGetWithIndex once to combine the absence check with the would-be index, then builds each neighbor's existence proof via a new findPathToIndex + buildExistenceProofFromPath pair that descends by index and collects the path in a single walk. createExistenceProof is refactored to share buildExistenceProofFromPath. - innerOps is preallocated to len(path)*MiniMerkleDepth to avoid append-time regrowth. Tests: - Full bptree race suite passes (no behavioural change). - TestMutableTree_COW_OldReferencesValid rewritten to use Snapshot(). - Mini-merkle tests updated to reference MiniMerkleDepth. - Existing proof and non-membership tests exercise the merged walk.
8 tasks done
clockworkgr
added a commit
that referenced
this pull request
Apr 22, 2026
Closes the nine confirmed findings from the PR #5571 review pass on the v2/v3 leaf-format work (commits 2133015, d56a693, 44a223c). None of the fixes change tree semantics (structure, hashing, versioning, proof format are untouched); they close cache-coherence bugs, silent-corruption passthroughs, and doc/contract drift. Findings #1 and #2 had deterministic reproducers in the review thread that produced wrong root hashes. Finding #6 surfaced a chain-divergence class where a corrupt value-store record made the tree return an empty value with err == nil. The remaining fixes are smaller correctness or documentation closures. Findings closed =============== #1 (HIGH) — leaf-shift loops did not shift slotsDirty in parallel Files: insert.go, remove.go The five leaf-mutation paths (leafInsert / leafRemove / redistributeRight / redistributeLeft / merge LeafNode case) shifted keys, valueHashes, valueKeys, inlineValues, and slotHashes in parallel — but left the slotsDirty bitmap at the pre-shift indices. rebuildMiniMerkleIncremental then trusted slotHashes[i] for the shifted-in slot whose dirty bit had been left at the old index, emitting a corrupt root hash. Reproducer (in slotsdirty_regression_test.go): empty tree → Set(K20), Set(K30), Set(K10) without intervening Hash() → WorkingHash() disagreed with the same three keys committed in sorted order. Fix: added shiftSlotsDirtyUp / shiftSlotsDirtyDown helpers that mirror the existing shiftInlineMaskUp / shiftInlineMaskDown bit shifts. Wired them into all five mutation sites. For the borrow / absorb cases (redistributeRight at lastIdx → 0, redistributeLeft at 0 → dst, merge at i → lBase+i), the moved slot's dirty bit is mirrored into the destination so the destination's slotHashes validity tracks the source's pre-move state. #2 (HIGH) — InnerNode.Clone() omitted miniTreeDirty File: node.go The explicit struct literal in InnerNode.Clone (added in commit 2133015 alongside the new miniTreeDirty field) did not copy the field. Clones got the Go zero value (false), so a clone of a dirty inner answered Hash() from the pre-mutation mini-merkle heap without rebuilding. Reachable via Snapshot() on a dirty root, common after a deeper-level split. Reproducer (in slotsdirty_regression_test.go): build a 64-key tree, mutate to dirty the root inner, clone, assert clone.Hash() matches root.Hash(). Fix: added miniTreeDirty: n.miniTreeDirty to the field list. #3 (LOW) — slotsDirty doc named the wrong rebuild function File: node.go The slotsDirty field doc said "RebuildMiniMerkle skips slots whose key/value did not change". That function actually rebuilds every occupied slot unconditionally; the function honoring slotsDirty is rebuildMiniMerkleIncremental. Doc rewritten to name the right function and to clarify both rebuild paths. #4 / #9 (HIGH / LOW) — InlineValueThreshold doc/resolver contradiction Files: options.go, mutable_tree.go options.go:25-26 documented "Zero selects DefaultInlineValueThreshold" while resolveInlineThreshold mapped opt == 0 to -1 (disabled). DefaultOptions() returns Options{}, so callers following the documented API silently got inline values disabled. Resolved per the implementing commit (d56a693) intent: the default IS disabled; callers opt into inline storage explicitly. Updated all three doc sites (Options.InlineValueThreshold, InlineValueThresholdOption, resolveInlineThreshold) to match the resolver behaviour and removed the temporal "as in pre-v2 behaviour" wording per CLAUDE.md "no temporal docs" rule. #5 (MEDIUM) — Get-hit hydration aliased leaf.inlineValues[i] File: mutable_tree.go The Get path on a tree-walk hit called fastNodes.Add(string(key), val) with val from leaf.valueAt — which returns leaf.inlineValues[i] for inline slots, a slice aliased to the leaf's own storage. The Set path copied via cacheValueForKey; the Get path didn't. A caller-side mutation of the returned bytes would corrupt both leaf and cache. Fix: defensive copy before Add, mirroring cacheValueForKey. #6 (HIGH) — silent corruption passthrough on missing value record Files: errors.go, nodedb.go, prune_test.go nodeDB.GetValue returned (nil, nil) for an absent DB record under a "callers should check val == nil explicitly" convention. No caller actually did, so a corrupt value store (record deleted out-of-band) surfaced as an empty value with err == nil — indistinguishable from a legitimate Get miss. App-layer hashes garbage, chain diverges, no log, no error. Fix: added ErrValueMissing to the typed-error set; nodeDB.GetValue now returns it instead of (nil, nil). The resolver chain (resolveValue, valueResolverFn, leaf.valueAt) bubbles it up naturally to every read path that already checked err. Updated TestPrune_EmptyVersionOrphansCleaned to assert the new contract (was relying on the old (nil, nil) for missing). #7 (MEDIUM) — Remove swallowed resolveValue error File: mutable_tree.go MutableTree.Remove did `val, _ = t.resolveValue(oldPayload.valueKey)` so the caller could not distinguish "old value was nil" from "couldn't read old value". Combined with #6, a corrupt store made Remove return (nil, true, nil) on a key that did exist. Fix: capture the error, log it via t.logger. The slot has already been shifted out of the leaf at this point so returning early would leave the tree in a partially-mutated state with no coherent retry path; logging preserves the diagnostic trail without breaking the Remove contract. A future change could surface a wrapped error distinguishing resolution failure from a healthy no-old-value case. #8 (LOW) — saveBufPool comment described the wrong policy File: nodedb.go The comment said "Buffers return to the pool with a minimum capacity to avoid re-growing on the next large node". The actual policy is the opposite: a MAXIMUM cap (saveBufCapCap = 8 KiB) that discards oversize buffers on Put so a single pathological node doesn't inflate every pooled buffer. Comment rewritten to describe the actual mechanism. #10 (LOW) — ADVANCED_PLAN.md was temporal scaffolding File: ADVANCED_PLAN.md (deleted) The ~400-line file was development scaffolding: phase status table ("✅ landed", "⬜ open"), baseline commit SHAs, benchmark rules addressed to the author. Per CLAUDE.md "NEVER write comments with temporal words... describing what changed", the entire document is temporal. Removed; phase planning belongs in a PR body or an internal wiki, not in the package. Note: finding #11 (benchmarks missing pebbledb) was already addressed by the merge from feat/alex/bp32tree-second-pass (commit dd30b0a). Regression coverage =================== slotsdirty_regression_test.go pins both reproducers from the review thread: - TestRegression_SlotsDirtyShiftedOnInsert — Set(K20),Set(K30), Set(K10) hash matches the same keys committed in sorted order. - TestRegression_InnerCloneCopiesMiniTreeDirty — clone Hash() matches original Hash() after dirtying the root inner. Future changes to leaf-shift discipline or InnerNode.Clone field membership must keep these passing. Verification ============ go test -count=1 -timeout=10m ./tm2/pkg/bptree/... ./tm2/pkg/store/bptree/... PASS (full suite, ~27 s) go test -race -count=1 -timeout=10m -run='TestRegression|TestPrune| TestSet|TestRemove|TestSaveVersion|TestLoadVersion|TestStore| TestImmutable|TestGetImmutable|TestIdempotent' ./tm2/pkg/bptree/ ./tm2/pkg/store/bptree/ PASS (~189 s)
jaekwon
added a commit
that referenced
this pull request
Apr 25, 2026
…pr and interface field sites (BINARY_FIXES #13,#26) Widens writeLengthPrefixedField and writeInterfaceFieldMarshal to mirror reflect's writeFieldIfNotEmpty (binary_encode.go:592): the outer field is elided when the inner body is zero-length OR exactly one byte of value 0x00. Together with #4/#22 (Any field 2), the rollback contract is now uniform across all three emission-site kinds (struct-repr / Time / Duration / nested struct, interface, and Any.Value). Structural hardening — today no generator-emitted MarshalBinary2 can produce [0x00] output (writeReprMarshal rolls that back at the top level, and MarshalAnyBinary2 always emits the TypeURL field), but the gate must hold for hand-written MarshalBinary2 and future emission paths. Adds generator-output inspection tests in genproto2_test.go anchored on PrimitivesStruct (Time/Duration/nested-struct sites) and ReprElem2 (interface site). Regenerates all pb3_gen.go with the new gate. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
jaekwon
added a commit
that referenced
this pull request
May 4, 2026
Bug #4 (analogous to bug #1 in a different code path): SignVote / SendRequest after Stop blocked for the full timeoutAccept (default 3s, measured 3.001s) before returning ErrConnectionTimeout. The previous fix added stopCh to WaitForConnection but bypassed signerEndpoint.WaitConnection by inlining the select. ensureConnection (called from SendRequestLocked → sendRequestLocked) still used base WaitConnection without a stopCh select arm, so it pinned the caller plus instanceMtx for the full maxWait when the endpoint was stopping. Cascade impact: RetrySignerClient retries up to 5 times with 1s sleep between attempts, so on a stopped endpoint a single SignVote through the retry layer would stall ~20s before the caller saw an error. Fix: thread stopCh through signerEndpoint.WaitConnection (option b from the report). Both WaitForConnection and ensureConnection now select on it. The base method's signature changes — small surface area, only one struct embeds signerEndpoint today. Verified: TestBugFix_SignVoteAfterStopReturnsPromptly asserts SignVote-after-Stop returns in <500ms (measured 33.5µs in the manual probe). All other privval tests pass under -race; lint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
jaekwon
added a commit
that referenced
this pull request
May 14, 2026
…Teller safety UserTeller in foo20 was an exported package-level interface-typed var that no external realm consumed. Defense-in-depth fix: unexport it. Foreign code can no longer read the var to construct an embedded wrapper and try to weaponize it through any future Teller-accepting entry point. bar20.UserTeller is intentionally exported for `maketx run` consumption (per the package comment). Leave it exported but add a doc comment explaining why it is safe: the underlying *fnTeller resolves the source-of-funds via cur.Previous().Address() under IsCurrent, so a caller can only spend their OWN balance, not the reader's. No cur is leaked via this exposure. Both addresses the lesson-#4 "no exported package-level var of any interface type" rule. The foo20 case follows the strong rule; the bar20 case is the documented exception (concrete capability semantics make the read-and-call exposure safe). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
jaekwon
added a commit
that referenced
this pull request
May 14, 2026
…ollow-up Three surveys (interfaces in /p/, footgun configurations in /r/, runtime.Realm + closure captures everywhere) surfaced spots that the just-landed cur-leak migration did not fix. Annotate each with a plain-English SECURITY XXX comment so the issue stays visible until someone gets to it, and so future readers of the code see the risk in context rather than buried in a planning doc. Annotations break down by severity: Likely exploitable today: - r/jjoptimist/eventix paymentToken `any` — an attacker can supply their own *grc20.Token with a rigged ledger; buyers pay in worthless attacker-tokens and receive real NFT tickets. - r/moul/config TransferManagement — accepts any Authority impl; hostile impl can lock or escalate; no path back once installed. HIGH-urgency unmigrated subsystems: - p/samcrew/daokit (Action / ActionHandler) + p/samcrew/daocond (Condition / Ballot) — open interfaces registered via Resources.Set run with the DAO's authority; malicious Condition.Eval can re-enter the DAO mid-execution (classic re-entrancy attack shape). - p/nt/commondao/v0/exts/definition WithExecutor — ExecFunc takes a realm parameter; same cur-disclosure shape as daokit pre-migration, but commondao is a peer subsystem that hasn't been migrated yet. - p/nt/commondao/v0 UseStorageFactory / WithValidation / WithTally — caller-supplied callbacks that control membership and proposal outcomes; behavior-substitution risk. - p/samcrew/daocond MembersThreshold — captured predicate functions control "who is a member" and "how many members exist." Lesson #4 violations (no exploit today, but anti-pattern in package state — fix opportunistically to keep audits clean): - r/sys/users/errors.gno ErrNotWhitelisted holds runtime.Realm struct fields. - r/gov/dao/v3/impl/impl.gno + r/gov/dao/proxy.gno — full runtime.Realm value captured into a package var at init. - r/demo/disperse, r/archive/boards, r/gnoland/boards2/v1{boards, protected} — Address/PkgPath captured at init time into package vars; safe today because the values are stable, but the pattern invites future leaks. Parity-test infrastructure explicitly called out: - r/tests/vm/crossrealm.Closure2 — exported `func(realm)` var. DELIBERATE VM-test pattern; annotated so production code authors don't copy it. Also commits the working-tree .claude/ config dir (per request). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
clockworkgr
pushed a commit
that referenced
this pull request
May 25, 2026
Bug #4 (analogous to bug #1 in a different code path): SignVote / SendRequest after Stop blocked for the full timeoutAccept (default 3s, measured 3.001s) before returning ErrConnectionTimeout. The previous fix added stopCh to WaitForConnection but bypassed signerEndpoint.WaitConnection by inlining the select. ensureConnection (called from SendRequestLocked → sendRequestLocked) still used base WaitConnection without a stopCh select arm, so it pinned the caller plus instanceMtx for the full maxWait when the endpoint was stopping. Cascade impact: RetrySignerClient retries up to 5 times with 1s sleep between attempts, so on a stopped endpoint a single SignVote through the retry layer would stall ~20s before the caller saw an error. Fix: thread stopCh through signerEndpoint.WaitConnection (option b from the report). Both WaitForConnection and ensureConnection now select on it. The base method's signature changes — small surface area, only one struct embeds signerEndpoint today. Verified: TestBugFix_SignVoteAfterStopReturnsPromptly asserts SignVote-after-Stop returns in <500ms (measured 33.5µs in the manual probe). All other privval tests pass under -race; lint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Merged
6 tasks done
thehowl
added a commit
that referenced
this pull request
Oct 14, 2026
…f reloading them every block (#6308) ## What `getBeginBlockLastCommitInfo` loaded the validator set of `block.Height-1` from the stateDB on every block. tm2 stores a validator set only when it changes and every `valSetCheckpointInterval` (100000) blocks, so each load replayed `IncrementProposerPriority` from the last stored set — up to 100000 steps — and the cost of a block grew linearly across each checkpoint window. `ApplyBlock` already holds that set as `state.LastValidators`; this PR uses it. ## Measurements Profiled with pprof on a gno.land mainnet node (v1.5.0, 8 vCPU) while it synced from genesis, with nothing else changed between samples; at both heights gnoland-1 had 4 validators, each of power 60: | height | blocks past the last checkpoint | `LoadValidators` share of CPU | |---|---|---| | ~80,000 | 80,000 | 49% | | ~116,000 | 16,000 | 13% | The replay is linear in the distance from the last stored set and close to linear in the validator count. A micro-benchmark of `IncrementProposerPriority(k)` costs, per step per validator, about 9 ns (Apple M4 Pro) to 16 ns (Ryzen 7 7840U) with 4 validators of equal power, since every tie in `CompareProposerPriority` is broken by comparing addresses, and 4–7 ns with distinct powers. That is ~4–6 ms a block for mainnet's 4 validators at the end of a checkpoint window, and ~15 ms (distinct powers) to ~85 ms (equal powers, ~21 ns per step per validator on the Ryzen) at 40 validators. Estimate, not a measured before/after of a full sync: with the load gone, a sync from genesis spends about a third less CPU on average (≈1.5× faster) and ≈2× less near the end of each window. Happy to add a measured resync if wanted. ## The change `tm2/pkg/bft/state/execution.go`: when `state` is the state the block builds on (`state.LastBlockHeight == block.Height-1`, which `state.ValidateBlock` enforces on the `ApplyBlock` path), the commit info is built from `state.LastValidators`. Otherwise — `ExecCommitBlock` replays the blocks the app is missing against the *latest* state, whose `LastValidators` belong to another height — it loads by height as before. Why the app sees exactly what it saw: - `state.LastValidators` are the validators of `block.Height-1`, the set that signed `block.LastCommit`: `updateState` carries `NextValidators` forward by copy, and `saveState` stores that same set two heights ahead. - Members and order are identical to the stored set; `IncrementProposerPriority` only changes priorities and the proposer, never the order. - The commit info reads only addresses, powers and the position of each precommit. Proposer priorities, the one thing the replay computed, never reached it. - So `RequestBeginBlock` is byte-identical and app hashes do not change. The commit-size sanity check is kept. ## Tests - `TestGetBeginBlockLastCommitInfo_LastValidators`: with the state the block builds on, the votes come from `state.LastValidators` and nothing is loaded (the stored set is deleted first — on master this panics with `Could not find validator set for height #4` — and `Validators` and `NextValidators` are given other members, so only `LastValidators` can give the expected votes); with a stale state, as `ExecCommitBlock` hands one, the stored set is used, not the state's. - `go test` for `tm2/pkg/bft/state/...`, `tm2/pkg/bft/blockchain/...` and the consensus replay, handshake and WAL tests pass locally. ## Files - `tm2/pkg/bft/state/execution.go` — the change - `tm2/pkg/bft/state/execution_test.go` — the test - `tm2/adr/` — ADR, added in a follow-up commit once the PR number was known ## Considered, not included - Lowering `valSetCheckpointInterval` (e.g. to 1000) would also bound the loads that remain (RPC `/validators`, the restart replay), but it keeps a load on every block and, on data written by older binaries, the new checkpoint heights are absent so `LoadValidators` falls back to replaying from the last change height. Details in the ADR; a possible follow-up. - In the same profiles `EndBlocker` spends 7–9% of CPU decoding the auth params on every block (`gno.land/pkg/gnoland/app.go`); a separate change. ## AI assistance Opened by an AI coding agent (Claude Code) at the request of, and on behalf of, its human owner @jaekwon, who is responsible for it. The ADR records the context the agent worked from. Opened as a draft for CI and review before being marked ready. --------- Co-authored-by: moul <[email protected]> Co-authored-by: Morgan Bazalgette <[email protected]>
aeddi
pushed a commit
that referenced
this pull request
Oct 16, 2026
…f reloading them every block (#6308) ## What `getBeginBlockLastCommitInfo` loaded the validator set of `block.Height-1` from the stateDB on every block. tm2 stores a validator set only when it changes and every `valSetCheckpointInterval` (100000) blocks, so each load replayed `IncrementProposerPriority` from the last stored set — up to 100000 steps — and the cost of a block grew linearly across each checkpoint window. `ApplyBlock` already holds that set as `state.LastValidators`; this PR uses it. ## Measurements Profiled with pprof on a gno.land mainnet node (v1.5.0, 8 vCPU) while it synced from genesis, with nothing else changed between samples; at both heights gnoland-1 had 4 validators, each of power 60: | height | blocks past the last checkpoint | `LoadValidators` share of CPU | |---|---|---| | ~80,000 | 80,000 | 49% | | ~116,000 | 16,000 | 13% | The replay is linear in the distance from the last stored set and close to linear in the validator count. A micro-benchmark of `IncrementProposerPriority(k)` costs, per step per validator, about 9 ns (Apple M4 Pro) to 16 ns (Ryzen 7 7840U) with 4 validators of equal power, since every tie in `CompareProposerPriority` is broken by comparing addresses, and 4–7 ns with distinct powers. That is ~4–6 ms a block for mainnet's 4 validators at the end of a checkpoint window, and ~15 ms (distinct powers) to ~85 ms (equal powers, ~21 ns per step per validator on the Ryzen) at 40 validators. Estimate, not a measured before/after of a full sync: with the load gone, a sync from genesis spends about a third less CPU on average (≈1.5× faster) and ≈2× less near the end of each window. Happy to add a measured resync if wanted. ## The change `tm2/pkg/bft/state/execution.go`: when `state` is the state the block builds on (`state.LastBlockHeight == block.Height-1`, which `state.ValidateBlock` enforces on the `ApplyBlock` path), the commit info is built from `state.LastValidators`. Otherwise — `ExecCommitBlock` replays the blocks the app is missing against the *latest* state, whose `LastValidators` belong to another height — it loads by height as before. Why the app sees exactly what it saw: - `state.LastValidators` are the validators of `block.Height-1`, the set that signed `block.LastCommit`: `updateState` carries `NextValidators` forward by copy, and `saveState` stores that same set two heights ahead. - Members and order are identical to the stored set; `IncrementProposerPriority` only changes priorities and the proposer, never the order. - The commit info reads only addresses, powers and the position of each precommit. Proposer priorities, the one thing the replay computed, never reached it. - So `RequestBeginBlock` is byte-identical and app hashes do not change. The commit-size sanity check is kept. ## Tests - `TestGetBeginBlockLastCommitInfo_LastValidators`: with the state the block builds on, the votes come from `state.LastValidators` and nothing is loaded (the stored set is deleted first — on master this panics with `Could not find validator set for height #4` — and `Validators` and `NextValidators` are given other members, so only `LastValidators` can give the expected votes); with a stale state, as `ExecCommitBlock` hands one, the stored set is used, not the state's. - `go test` for `tm2/pkg/bft/state/...`, `tm2/pkg/bft/blockchain/...` and the consensus replay, handshake and WAL tests pass locally. ## Files - `tm2/pkg/bft/state/execution.go` — the change - `tm2/pkg/bft/state/execution_test.go` — the test - `tm2/adr/` — ADR, added in a follow-up commit once the PR number was known ## Considered, not included - Lowering `valSetCheckpointInterval` (e.g. to 1000) would also bound the loads that remain (RPC `/validators`, the restart replay), but it keeps a load on every block and, on data written by older binaries, the new checkpoint heights are absent so `LoadValidators` falls back to replaying from the last change height. Details in the ADR; a possible follow-up. - In the same profiles `EndBlocker` spends 7–9% of CPU decoding the auth params on every block (`gno.land/pkg/gnoland/app.go`); a separate change. ## AI assistance Opened by an AI coding agent (Claude Code) at the request of, and on behalf of, its human owner @jaekwon, who is responsible for it. The ADR records the context the agent worked from. Opened as a draft for CI and review before being marked ready. --------- Co-authored-by: moul <[email protected]> Co-authored-by: Morgan Bazalgette <[email protected]> (cherry picked from commit 723b92b)
This was referenced Oct 27, 2026
thehowl
pushed a commit
that referenced
this pull request
Nov 3, 2026
…eability ADR (#6404) ## Summary Rescoped after review: this PR now adds `amino.UnmarshalCanonical` and the ADR that analyses transaction malleability and lays out the fix in three steps. It changes no behaviour. - **Wire fix: #6399** (`amino:"skip_zero"` on `Signature.SessionAddr`). This PR's first version fixed the same field with a dedicated `std.SessionAddress` type; review of both preferred #6399, which keeps the field's Go type and adds a reusable tag, so that part was removed here. - **This PR: the check.** `amino.UnmarshalCanonical(bz, ptr)` decodes, re-encodes with `Marshal`, and rejects `bz` unless it is byte-for-byte what this encoder produces for the decoded value, whatever the mechanism of the alternative encoding. Two limits, both in the ADR: `Marshal` can emit bytes the check rejects where a repr's producer is laxer than its consumer (an unsorted `std.Coins` string), and canonical bytes can still be invalid (`0a 00`, a nil message). - **Enforcement: #6406.** `runTx` decodes with `UnmarshalCanonical` unconditionally, shipped as a coordinated upgrade after #6399 and the clients have drained the old encoding. ### The bug A transaction is identified by `sha256` over its raw amino bytes, while its signatures cover the amino JSON sign doc. Amino, like protobuf, accepts several encodings of one value, so appending an explicit empty memo (`0x22 0x00`), padding any varint, or writing out any omitted default field yields bytes that decode to the identical tx and pass `CheckTx` and `DeliverTx` under a different hash. Once the variant is included, the sender's own bytes fail on the consumed sequence. Nine such mutations were reproduced on a real `gnoland` app at every nesting level; both decoder paths accept all of them. ## Rollout 1. #6399 merges and ships as a rolling release (nodes accept both encodings, as today). 2. This PR merges. 3. Clients: Go tools rebuilt after #6399; `amino-ts` 0.2.1 (gnolang/amino-ts#2) already emits the canonical bytes through an interim repr and gnolang/amino-ts#4 mirrors `skip_zero` as a field option; the ts-proto clients already emit the canonical form. 4. The written-out zero session address drains from traffic. 5. #6406 ships as a coordinated upgrade (the #5368 halt mechanism: GovDAO halt with `halt_min_version`; the upgrades-ledger entry is written once the chain runs the release, #6381), riding the next coordinated release on the mainnet line after `v1.5.1`. Blocks before its halt height are replayed by the earlier binaries, so there is deliberately no height gate. ## Changes by file - `tm2/pkg/amino/amino.go`: `UnmarshalCanonical` (package function and `Codec` method). Like `Unmarshal` it takes `*T` or `**T`; deeper pointers, which `Unmarshal` decodes through and `Marshal` panics on, are refused with an error before decoding. - `tm2/pkg/amino/canonical_test.go` (new): the four non-canonical classes on a local struct (the reflect path); a generated type, `tests.PrimitivesStruct`, for the genproto2 path that `std.Tx` takes in `runTx`, with the path asserted through the codec stats and a padded tag, value and nested message length; `*T`, `**T` and `***T` targets; a non-nil pointer to a zero struct stays canonical. - `tm2/adr/pr6404_tx_canonical_encoding.md`: context, decision, rollout, alternatives (enforce now, the dedicated type, the height gate, strict decoder, canonical hash, mempool canonicalisation), consequences including the sibling-repository byte comparison. - `tm2/pkg/amino/README.md`: a section on encoding changes and consensus, as asked in review: once transactions must be byte-exact, any change to the bytes `Marshal` produces for a type that reaches consensus is a protocol change, whether it comes from a field tag such as `amino:"skip_zero"`, a repr type's `MarshalAmino`, or a regenerated codec, and needs a coordinated upgrade. ## Sibling repositories The same nine txs were encoded with each client and diffed against an encoder that omits the zero session address: | Repo | Result | |---|---| | tm2-js-client 3.3.0, gno-js-client 3.1.0, gno-types 1.1.1 | identical on all nine | | amino-ts 0.2.0 | identical except the zero session address; fixed in 0.2.1 (gnolang/amino-ts#2), tag mirrored in gnolang/amino-ts#4 | | gnonative, tx-indexer (pinned after #5307) | write the old form until they bump this module | | supernova, faucet (pinned before #5307) | already omit it | | ledger-ts, ledger-app-gno | sign the JSON sign doc only; unaffected | ## Verification `go test ./tm2/pkg/amino/...` and `golangci-lint` on the package; the rest of the tree is untouched apart from the README. Related: #6399 (wire fix), #6406 (enforcement, stacked on this branch), gnolang/amino-ts#2 and #4 (client side).
thehowl
added a commit
that referenced
this pull request
Nov 6, 2026
## Summary Phase 2 of the transaction malleability fix. #6404 (merged 2026-11-03) added `amino.UnmarshalCanonical`; #6399 (merged 2026-11-02) took the zero session address off the wire, without which the written-out zero address would be the canonical form and the omitted one not, the reverse of what the clients emit. Both are in master, which this PR now targets. `BaseApp.runTx` now decodes every transaction, in every mode, with `amino.UnmarshalCanonical`: a transaction is identified by the hash of its bytes while its signatures cover the sign doc, so any other encoding of the same transaction was the same transaction under another hash. Bytes that are not the canonical encoding are rejected with `std.ErrTxDecode`, and `Log` names the first differing byte. ## No height gate Review on #6404 showed that gnoland-1's history is mostly non-canonical (about 81% of 213k transactions carry the written-out zero session address the old Go encoder produced). A height gate was implemented and set aside: the upgrades ledger (`gno.land/pkg/upgrades`) binds each released version to the block range from its own halt height to its successor's, and history is replayed by switching binaries at those heights. The enforcing release therefore never executes blocks produced under the lenient rule, and nothing in state has to say where the rule starts. The ADR records the alternative and the reasoning. ## Rollout State-breaking; rides the coordinated halt mechanism from #5368 that gnoland-1 already runs (GovDAO halt with `halt_min_version` set to the enforcing release, so an old binary cannot restart past the halt and a new one cannot start early, with the entry in `misc/deployments/mainnet.gno.land/upgrades.json` written once the chain runs the release, #6381), and only after the written-out zero session address has drained from live traffic. The release it rides is the next coordinated release on the mainnet line after `v1.5.1`; its release page and the halt announcement name the height once the proposal has executed. Merge order: #6399 and #6404, both merged, then this PR, then the related `runTx` tx-encoding change omarsy has queued behind it. 1. #6399 and #6404 ship first, as a rolling release: the wire fix is backward compatible and `UnmarshalCanonical` changes no behaviour. 2. Clients: Go tools rebuilt from the module after #6399; `amino-ts` 0.2.1 or later (gnolang/amino-ts#2 shipped the bytes, gnolang/amino-ts#4 mirrors `skip_zero` as a field option); the ts-proto clients (`tm2-js-client`, `gno-js-client`, `gno-types`) already emit the canonical form. 3. This PR, at the halt. From its first block every master-key transaction from an older Go client is refused, and a node syncing from genesis on this release alone stops at the first non-canonical historical block: it has to switch binaries at the ledger's heights, as for any state-breaking release. Clients must emit canonical amino: coins strings in Go's rendering (sorted by denom, no whitespace), lowercase bech32, no explicit defaults, no padded varints. ## Also in this PR - **Nil messages are rejected up front.** An empty `Any` (`0a 00`) decodes to a nil message and is its canonical encoding, so the check passes it; `ValidateBasic` then dereferenced it and `runTx`'s recover reported an internal error, at about 16x the CPU of a decode error and uncharged (found in review of #6404). `validateBasicTxMsgs` now returns `std.ErrUnknownRequest` for it. - **A nil `Package` in `MsgAddPackage` and `MsgRun` is refused up front.** Such a message is non-nil and canonical, so it passes both checks above; its `ValidateBasic` then dereferenced the nil `*std.MemPackage`, and the recovered panic cost about thirteen times a clean rejection (found in review here). Both now return `ErrInvalidPkgPath("missing package")`; the other seven messages gno.land registers already return clean errors. A delivered tx's error type is in the results hash, so the guard rides this halt. - **`Log` on decode failures.** Decode errors take `Error` and `Log` from `ABCIResultFromError`, set field by field so nothing already on `result` is overwritten; `Log` carries the reason where it used to be empty. `Log` is excluded from `ResultsHash`; this is a visible RPC response change only. - **Cost, measured on attacker-chosen inputs** where signature verification is never reached (`Unmarshal` vs `UnmarshalCanonical`, from the #6404 review): 1 KB memo 3.5 → 5.6 µs, 100 KB memo 23.5 → 32.3 µs, 999 KB memo 121.5 → 190.0 µs, 797 KB with 7000 msgs 8.1 → 14.9 ms. Bounded by the mempool's `maxTxBytes` check, by `Marshal` running only after a successful `Unmarshal`, and by the pre-existing unpriced decode being the larger term. ## Changes by file - `tm2/pkg/sdk/baseapp.go`: `runTx` decodes with `UnmarshalCanonical`; decode failures set `result.Error` and `result.Log` from `ABCIResultFromError`; `validateBasicTxMsgs` rejects nil messages. - `tm2/pkg/sdk/baseapp_test.go`: a padded-tag re-encoding is rejected in `CheckTx` and `DeliverTx`; a nil message fails as a bad request, not a recovered panic. - `gno.land/pkg/sdk/vm/msgs.go`, `msgs_test.go`: the nil `Package` guard on `MsgAddPackage` and `MsgRun`, with a table case each. - `gno.land/pkg/gnoland/app_session_addr_test.go`: #6399's `TestDeliverTxZeroSessionAddr` flipped as its own comment anticipated. The old bytes, built by its `legacyTxBytes`, decode to the same signed tx and are refused as a decode error in both modes while the new bytes deliver; the app-hash, tampered-signature and per-byte gas comparisons that held only while the old bytes delivered are gone. - `gno.land/pkg/gnoland/tx_canonical_test.go` (new): end to end on a real app with a signed bank send. Four mutations that decode to the same signed tx (explicit empty memo, padded first tag, padded value inside the fee, padded length inside the message `Any`) are rejected in both modes while the sender's own bytes still deliver. `MsgAddPackage` and `MsgRun` with a nil `Package` are refused as a bad request in both modes with no recovered panic. Small wire helpers split and re-join fields so enclosing lengths are recomputed. - `tm2/adr/pr6406_canonical_tx_enforcement.md`: context, decision, the set-aside gate and other alternatives, consequences including the measured cost, the `Log` change and the dependency on #6399. - `gno.land/cmd/gnoland/UPGRADES.md`: operator-facing section on the rule, replay, and when to schedule the halt. ## Verification `go test` for `tm2/pkg/sdk/...`, `gno.land/pkg/gnoland`, `gno.land/pkg/gnoclient`; the full `go test ./gno.land/pkg/integration/ -run TestTestdata` (fresh chains are strict from block 1; gnokey emits canonical bytes); `golangci-lint` on the changed packages. Related: #6399 (wire fix), #6404 (phase 1), gnolang/amino-ts#2 and #4 (client side). --------- Co-authored-by: Morgan <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
I've added a github action that tests the realms.
Next: building logos!