github.com/calmw/ethereum@v0.1.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/calmw/ethereum/core" 32 "github.com/calmw/ethereum/core/rawdb" 33 "github.com/calmw/ethereum/core/types" 34 "github.com/calmw/ethereum/core/vm" 35 "github.com/calmw/ethereum/eth/tracers/logger" 36 ) 37 38 func TestState(t *testing.T) { 39 t.Parallel() 40 41 st := new(testMatcher) 42 // Long tests: 43 st.slow(`^stAttackTest/ContractCreationSpam`) 44 st.slow(`^stBadOpcode/badOpcodes`) 45 st.slow(`^stPreCompiledContracts/modexp`) 46 st.slow(`^stQuadraticComplexityTest/`) 47 st.slow(`^stStaticCall/static_Call50000`) 48 st.slow(`^stStaticCall/static_Return50000`) 49 st.slow(`^stSystemOperationsTest/CallRecursiveBomb`) 50 st.slow(`^stTransactionTest/Opcodes_TransactionInit`) 51 52 // Very time consuming 53 st.skipLoad(`^stTimeConsuming/`) 54 st.skipLoad(`.*vmPerformance/loop.*`) 55 56 // Uses 1GB RAM per tested fork 57 st.skipLoad(`^stStaticCall/static_Call1MB`) 58 59 // Broken tests: 60 // 61 // The stEOF tests are generated with EOF as part of Shanghai, which 62 // is erroneous. Therefore, these tests are skipped. 63 st.skipLoad(`^EIPTests/stEOF/`) 64 // Expected failures: 65 66 // For Istanbul, older tests were moved into LegacyTests 67 for _, dir := range []string{ 68 stateTestDir, 69 legacyStateTestDir, 70 benchmarksDir, 71 } { 72 st.walk(t, dir, func(t *testing.T, name string, test *StateTest) { 73 for _, subtest := range test.Subtests() { 74 subtest := subtest 75 key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index) 76 77 t.Run(key+"/trie", func(t *testing.T) { 78 withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { 79 _, _, err := test.Run(subtest, vmconfig, false) 80 return st.checkFailure(t, err) 81 }) 82 }) 83 t.Run(key+"/snap", func(t *testing.T) { 84 withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { 85 snaps, statedb, err := test.Run(subtest, vmconfig, true) 86 if snaps != nil && statedb != nil { 87 if _, err := snaps.Journal(statedb.IntermediateRoot(false)); err != nil { 88 return err 89 } 90 } 91 return st.checkFailure(t, err) 92 }) 93 }) 94 } 95 }) 96 } 97 } 98 99 // Transactions with gasLimit above this value will not get a VM trace on failure. 100 const traceErrorLimit = 400000 101 102 func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) { 103 // Use config from command line arguments. 104 config := vm.Config{} 105 err := test(config) 106 if err == nil { 107 return 108 } 109 110 // Test failed, re-run with tracing enabled. 111 t.Error(err) 112 if gasLimit > traceErrorLimit { 113 t.Log("gas limit too high for EVM trace") 114 return 115 } 116 buf := new(bytes.Buffer) 117 w := bufio.NewWriter(buf) 118 config.Tracer = logger.NewJSONLogger(&logger.Config{}, w) 119 err2 := test(config) 120 if !reflect.DeepEqual(err, err2) { 121 t.Errorf("different error for second run: %v", err2) 122 } 123 w.Flush() 124 if buf.Len() == 0 { 125 t.Log("no EVM operation logs generated") 126 } else { 127 t.Log("EVM operation log:\n" + buf.String()) 128 } 129 // t.Logf("EVM output: 0x%x", tracer.Output()) 130 // t.Logf("EVM error: %v", tracer.Error()) 131 } 132 133 func BenchmarkEVM(b *testing.B) { 134 // Walk the directory. 135 dir := benchmarksDir 136 dirinfo, err := os.Stat(dir) 137 if os.IsNotExist(err) || !dirinfo.IsDir() { 138 fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the evm-benchmarks submodule?\n", dir) 139 b.Skip("missing test files") 140 } 141 err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 142 if info.IsDir() { 143 return nil 144 } 145 if ext := filepath.Ext(path); ext == ".json" { 146 name := filepath.ToSlash(strings.TrimPrefix(strings.TrimSuffix(path, ext), dir+string(filepath.Separator))) 147 b.Run(name, func(b *testing.B) { runBenchmarkFile(b, path) }) 148 } 149 return nil 150 }) 151 if err != nil { 152 b.Fatal(err) 153 } 154 } 155 156 func runBenchmarkFile(b *testing.B, path string) { 157 m := make(map[string]StateTest) 158 if err := readJSONFile(path, &m); err != nil { 159 b.Fatal(err) 160 return 161 } 162 if len(m) != 1 { 163 b.Fatal("expected single benchmark in a file") 164 return 165 } 166 for _, t := range m { 167 t := t 168 runBenchmark(b, &t) 169 } 170 } 171 172 func runBenchmark(b *testing.B, t *StateTest) { 173 for _, subtest := range t.Subtests() { 174 subtest := subtest 175 key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index) 176 177 b.Run(key, func(b *testing.B) { 178 vmconfig := vm.Config{} 179 180 config, eips, err := GetChainConfig(subtest.Fork) 181 if err != nil { 182 b.Error(err) 183 return 184 } 185 var rules = config.Rules(new(big.Int), false, 0) 186 187 vmconfig.ExtraEips = eips 188 block := t.genesis(config).ToBlock() 189 _, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, false) 190 191 var baseFee *big.Int 192 if rules.IsLondon { 193 baseFee = t.json.Env.BaseFee 194 if baseFee == nil { 195 // Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to 196 // parent - 2 : 0xa as the basefee for 'this' context. 197 baseFee = big.NewInt(0x0a) 198 } 199 } 200 post := t.json.Post[subtest.Fork][subtest.Index] 201 msg, err := t.json.Tx.toMessage(post, baseFee) 202 if err != nil { 203 b.Error(err) 204 return 205 } 206 207 // Try to recover tx with current signer 208 if len(post.TxBytes) != 0 { 209 var ttx types.Transaction 210 err := ttx.UnmarshalBinary(post.TxBytes) 211 if err != nil { 212 b.Error(err) 213 return 214 } 215 216 if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil { 217 b.Error(err) 218 return 219 } 220 } 221 222 // Prepare the EVM. 223 txContext := core.NewEVMTxContext(msg) 224 context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase) 225 context.GetHash = vmTestBlockHash 226 context.BaseFee = baseFee 227 evm := vm.NewEVM(context, txContext, statedb, config, vmconfig) 228 229 // Create "contract" for sender to cache code analysis. 230 sender := vm.NewContract(vm.AccountRef(msg.From), vm.AccountRef(msg.From), 231 nil, 0) 232 233 var ( 234 gasUsed uint64 235 elapsed uint64 236 refund uint64 237 ) 238 b.ResetTimer() 239 for n := 0; n < b.N; n++ { 240 snapshot := statedb.Snapshot() 241 statedb.Prepare(rules, msg.From, context.Coinbase, msg.To, vm.ActivePrecompiles(rules), msg.AccessList) 242 b.StartTimer() 243 start := time.Now() 244 245 // Execute the message. 246 _, leftOverGas, err := evm.Call(sender, *msg.To, msg.Data, msg.GasLimit, msg.Value) 247 if err != nil { 248 b.Error(err) 249 return 250 } 251 252 b.StopTimer() 253 elapsed += uint64(time.Since(start)) 254 refund += statedb.GetRefund() 255 gasUsed += msg.GasLimit - leftOverGas 256 257 statedb.RevertToSnapshot(snapshot) 258 } 259 if elapsed < 1 { 260 elapsed = 1 261 } 262 // Keep it as uint64, multiply 100 to get two digit float later 263 mgasps := (100 * 1000 * (gasUsed - refund)) / elapsed 264 b.ReportMetric(float64(mgasps)/100, "mgas/s") 265 }) 266 } 267 }