@@ -3,9 +3,15 @@ package common_test
33import (
44 "bytes"
55 "errors"
6+ "fmt"
67 "math/big"
78 "os"
9+ "runtime"
10+ "strings"
811 "testing"
12+ "time"
13+ "unicode/utf8"
14+ "unsafe"
915
1016 sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
1117 "github.com/sei-protocol/sei-chain/x/evm/state"
@@ -54,6 +60,51 @@ func TestHandlePrecompileError(t *testing.T) {
5460 common .HandlePrecompileError (errors .New ("other error" ), evm , "other" )
5561}
5662
63+ func TestHandlePrecompileErrorTruncatesLongMessage (t * testing.T ) {
64+ k := & testkeeper .EVMTestApp .EvmKeeper
65+ ctx := testkeeper .EVMTestApp .GetContextForDeliverTx (nil )
66+ stateDB := state .NewDBImpl (ctx , k , false )
67+ evm := & vm.EVM {StateDB : stateDB }
68+
69+ short := errors .New ("short error" )
70+ common .HandlePrecompileError (short , evm , "short" )
71+ require .Same (t , short , stateDB .GetPrecompileError ())
72+
73+ // "€" is three bytes wide, so the cut lands inside a character.
74+ long := fmt .Errorf ("wrapped: %w" , errors .New (strings .Repeat ("€" , common .MaxPrecompileErrorLength )))
75+ common .HandlePrecompileError (long , evm , "long" )
76+ stored := stateDB .GetPrecompileError ()
77+ require .LessOrEqual (t , len (stored .Error ()), common .MaxPrecompileErrorLength )
78+ require .Greater (t , len (stored .Error ()), common .MaxPrecompileErrorLength - utf8 .UTFMax )
79+ require .True (t , utf8 .ValidString (stored .Error ()))
80+ require .True (t , strings .HasPrefix (long .Error (), stored .Error ()))
81+ }
82+
83+ func TestHandlePrecompileErrorDoesNotRetainFullMessage (t * testing.T ) {
84+ k := & testkeeper .EVMTestApp .EvmKeeper
85+ ctx := testkeeper .EVMTestApp .GetContextForDeliverTx (nil )
86+ stateDB := state .NewDBImpl (ctx , k , false )
87+
88+ released := recordLongPrecompileError (& vm.EVM {StateDB : stateDB })
89+ runtime .GC ()
90+ select {
91+ case <- released :
92+ case <- time .After (10 * time .Second ):
93+ t .Fatal ("the StateDB keeps the full message of a truncated precompile error reachable" )
94+ }
95+ require .Error (t , stateDB .GetPrecompileError ())
96+ }
97+
98+ // recordLongPrecompileError records an error with an over-long message on evm's StateDB and returns
99+ // a channel that is closed once that message has been garbage collected.
100+ func recordLongPrecompileError (evm * vm.EVM ) <- chan struct {} {
101+ err := fmt .Errorf ("wrapped: %w" , errors .New (strings .Repeat ("€" , common .MaxPrecompileErrorLength )))
102+ released := make (chan struct {})
103+ runtime .AddCleanup (unsafe .StringData (err .Error ()), func (c chan struct {}) { close (c ) }, released )
104+ common .HandlePrecompileError (err , evm , "long" )
105+ return released
106+ }
107+
57108type MockPrecompileExecutor struct {
58109 throw bool
59110}
0 commit comments