github.com/theQRL/go-zond@v0.2.1/tests/state_test.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package tests 18 19 import ( 20 "bufio" 21 "bytes" 22 "fmt" 23 "math/big" 24 "os" 25 "path/filepath" 26 "reflect" 27 "strings" 28 "testing" 29 "time" 30 31 "github.com/theQRL/go-zond/core" 32 "github.com/theQRL/go-zond/core/rawdb" 33 "github.com/theQRL/go-zond/core/state" 34 "github.com/theQRL/go-zond/core/state/snapshot" 35 "github.com/theQRL/go-zond/core/types" 36 "github.com/theQRL/go-zond/core/vm" 37 "github.com/theQRL/go-zond/zond/tracers/logger" 38 ) 39 40 func TestState(t *testing.T) { 41 t.Parallel() 42 43 st := new(testMatcher) 44 // Long tests: 45 st.slow(`^stAttackTest/ContractCreationSpam`) 46 st.slow(`^stBadOpcode/badOpcodes`) 47 st.slow(`^stPreCompiledContracts/modexp`) 48 st.slow(`^stQuadraticComplexityTest/`) 49 st.slow(`^stStaticCall/static_Call50000`) 50 st.slow(`^stStaticCall/static_Return50000`) 51 st.slow(`^stSystemOperationsTest/CallRecursiveBomb`) 52 st.slow(`^stTransactionTest/Opcodes_TransactionInit`) 53 // Very time consuming 54 st.skipLoad(`^stTimeConsuming/`) 55 st.skipLoad(`.*vmPerformance/loop.*`) 56 // Uses 1GB RAM per tested fork 57 st.skipLoad(`^stStaticCall/static_Call1MB`) 58 59 // Broken tests: 60 // EOF is not part of cancun 61 st.skipLoad(`^stEOF/`) 62 63 // For Istanbul, older tests were moved into LegacyTests 64 for _, dir := range []string{ 65 filepath.Join(baseDir, "EIPTests", "StateTests"), 66 stateTestDir, 67 legacyStateTestDir, 68 benchmarksDir, 69 } { 70 st.walk(t, dir, func(t *testing.T, name string, test *StateTest) { 71 for _, subtest := range test.Subtests() { 72 subtest := subtest 73 key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index) 74 75 t.Run(key+"/hash/trie", func(t *testing.T) { 76 withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { 77 var result error 78 test.Run(subtest, vmconfig, false, rawdb.HashScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) { 79 result = st.checkFailure(t, err) 80 }) 81 return result 82 }) 83 }) 84 t.Run(key+"/hash/snap", func(t *testing.T) { 85 withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { 86 var result error 87 test.Run(subtest, vmconfig, true, rawdb.HashScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) { 88 if snaps != nil && state != nil { 89 if _, err := snaps.Journal(state.IntermediateRoot(false)); err != nil { 90 result = err 91 return 92 } 93 } 94 result = st.checkFailure(t, err) 95 }) 96 return result 97 }) 98 }) 99 t.Run(key+"/path/trie", func(t *testing.T) { 100 withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { 101 var result error 102 test.Run(subtest, vmconfig, false, rawdb.PathScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) { 103 result = st.checkFailure(t, err) 104 }) 105 return result 106 }) 107 }) 108 t.Run(key+"/path/snap", func(t *testing.T) { 109 withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { 110 var result error 111 test.Run(subtest, vmconfig, true, rawdb.PathScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) { 112 if snaps != nil && state != nil { 113 if _, err := snaps.Journal(state.IntermediateRoot(false)); err != nil { 114 result = err 115 return 116 } 117 } 118 result = st.checkFailure(t, err) 119 }) 120 return result 121 }) 122 }) 123 } 124 }) 125 } 126 } 127 128 // Transactions with gasLimit above this value will not get a VM trace on failure. 129 const traceErrorLimit = 400000 130 131 func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) { 132 // Use config from command line arguments. 133 config := vm.Config{} 134 err := test(config) 135 if err == nil { 136 return 137 } 138 139 // Test failed, re-run with tracing enabled. 140 t.Error(err) 141 if gasLimit > traceErrorLimit { 142 t.Log("gas limit too high for ZVM trace") 143 return 144 } 145 buf := new(bytes.Buffer) 146 w := bufio.NewWriter(buf) 147 config.Tracer = logger.NewJSONLogger(&logger.Config{}, w) 148 err2 := test(config) 149 if !reflect.DeepEqual(err, err2) { 150 t.Errorf("different error for second run: %v", err2) 151 } 152 w.Flush() 153 if buf.Len() == 0 { 154 t.Log("no ZVM operation logs generated") 155 } else { 156 t.Log("ZVM operation log:\n" + buf.String()) 157 } 158 // t.Logf("ZVM output: 0x%x", tracer.Output()) 159 // t.Logf("ZVM error: %v", tracer.Error()) 160 } 161 162 func BenchmarkZVM(b *testing.B) { 163 // Walk the directory. 164 dir := benchmarksDir 165 dirinfo, err := os.Stat(dir) 166 if os.IsNotExist(err) || !dirinfo.IsDir() { 167 fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the evm-benchmarks submodule?\n", dir) 168 b.Skip("missing test files") 169 } 170 err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 171 if info.IsDir() { 172 return nil 173 } 174 if ext := filepath.Ext(path); ext == ".json" { 175 name := filepath.ToSlash(strings.TrimPrefix(strings.TrimSuffix(path, ext), dir+string(filepath.Separator))) 176 b.Run(name, func(b *testing.B) { runBenchmarkFile(b, path) }) 177 } 178 return nil 179 }) 180 if err != nil { 181 b.Fatal(err) 182 } 183 } 184 185 func runBenchmarkFile(b *testing.B, path string) { 186 m := make(map[string]StateTest) 187 if err := readJSONFile(path, &m); err != nil { 188 b.Fatal(err) 189 return 190 } 191 if len(m) != 1 { 192 b.Fatal("expected single benchmark in a file") 193 return 194 } 195 for _, t := range m { 196 t := t 197 runBenchmark(b, &t) 198 } 199 } 200 201 func runBenchmark(b *testing.B, t *StateTest) { 202 for _, subtest := range t.Subtests() { 203 subtest := subtest 204 key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index) 205 206 b.Run(key, func(b *testing.B) { 207 vmconfig := vm.Config{} 208 209 config, eips, err := GetChainConfig(subtest.Fork) 210 if err != nil { 211 b.Error(err) 212 return 213 } 214 var rules = config.Rules(new(big.Int), 0) 215 216 vmconfig.ExtraEips = eips 217 block := t.genesis(config).ToBlock() 218 triedb, _, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, false, rawdb.HashScheme) 219 defer triedb.Close() 220 221 var baseFee *big.Int 222 baseFee = t.json.Env.BaseFee 223 if baseFee == nil { 224 // Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to 225 // parent - 2 : 0xa as the basefee for 'this' context. 226 baseFee = big.NewInt(0x0a) 227 } 228 post := t.json.Post[subtest.Fork][subtest.Index] 229 msg, err := t.json.Tx.toMessage(post, baseFee) 230 if err != nil { 231 b.Error(err) 232 return 233 } 234 235 // Try to recover tx with current signer 236 if len(post.TxBytes) != 0 { 237 var ttx types.Transaction 238 err := ttx.UnmarshalBinary(post.TxBytes) 239 if err != nil { 240 b.Error(err) 241 return 242 } 243 244 if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil { 245 b.Error(err) 246 return 247 } 248 } 249 250 // Prepare the ZVM. 251 txContext := core.NewZVMTxContext(msg) 252 context := core.NewZVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase) 253 context.GetHash = vmTestBlockHash 254 context.BaseFee = baseFee 255 zvm := vm.NewZVM(context, txContext, statedb, config, vmconfig) 256 257 // Create "contract" for sender to cache code analysis. 258 sender := vm.NewContract(vm.AccountRef(msg.From), vm.AccountRef(msg.From), 259 nil, 0) 260 261 var ( 262 gasUsed uint64 263 elapsed uint64 264 refund uint64 265 ) 266 b.ResetTimer() 267 for n := 0; n < b.N; n++ { 268 snapshot := statedb.Snapshot() 269 statedb.Prepare(rules, msg.From, context.Coinbase, msg.To, vm.ActivePrecompiles(rules), msg.AccessList) 270 b.StartTimer() 271 start := time.Now() 272 273 // Execute the message. 274 _, leftOverGas, err := zvm.Call(sender, *msg.To, msg.Data, msg.GasLimit, msg.Value) 275 if err != nil { 276 b.Error(err) 277 return 278 } 279 280 b.StopTimer() 281 elapsed += uint64(time.Since(start)) 282 refund += statedb.GetRefund() 283 gasUsed += msg.GasLimit - leftOverGas 284 285 statedb.RevertToSnapshot(snapshot) 286 } 287 if elapsed < 1 { 288 elapsed = 1 289 } 290 // Keep it as uint64, multiply 100 to get two digit float later 291 mgasps := (100 * 1000 * (gasUsed - refund)) / elapsed 292 b.ReportMetric(float64(mgasps)/100, "mgas/s") 293 }) 294 } 295 }