github.com/jimmyx0x/go-ethereum@v1.10.28/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/ethereum/go-ethereum/core" 32 "github.com/ethereum/go-ethereum/core/rawdb" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/core/vm" 35 "github.com/ethereum/go-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 // Not yet supported TODO 60 st.skipLoad(`^stEIP3540/`) 61 st.skipLoad(`^stEIP3860/`) 62 63 // Broken tests: 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 tracer := logger.NewJSONLogger(&logger.Config{}, w) 119 config.Debug, config.Tracer = true, tracer 120 err2 := test(config) 121 if !reflect.DeepEqual(err, err2) { 122 t.Errorf("different error for second run: %v", err2) 123 } 124 w.Flush() 125 if buf.Len() == 0 { 126 t.Log("no EVM operation logs generated") 127 } else { 128 t.Log("EVM operation log:\n" + buf.String()) 129 } 130 // t.Logf("EVM output: 0x%x", tracer.Output()) 131 // t.Logf("EVM error: %v", tracer.Error()) 132 } 133 134 func BenchmarkEVM(b *testing.B) { 135 // Walk the directory. 136 dir := benchmarksDir 137 dirinfo, err := os.Stat(dir) 138 if os.IsNotExist(err) || !dirinfo.IsDir() { 139 fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the evm-benchmarks submodule?\n", dir) 140 b.Skip("missing test files") 141 } 142 err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 143 if info.IsDir() { 144 return nil 145 } 146 if ext := filepath.Ext(path); ext == ".json" { 147 name := filepath.ToSlash(strings.TrimPrefix(strings.TrimSuffix(path, ext), dir+string(filepath.Separator))) 148 b.Run(name, func(b *testing.B) { runBenchmarkFile(b, path) }) 149 } 150 return nil 151 }) 152 if err != nil { 153 b.Fatal(err) 154 } 155 } 156 157 func runBenchmarkFile(b *testing.B, path string) { 158 m := make(map[string]StateTest) 159 if err := readJSONFile(path, &m); err != nil { 160 b.Fatal(err) 161 return 162 } 163 if len(m) != 1 { 164 b.Fatal("expected single benchmark in a file") 165 return 166 } 167 for _, t := range m { 168 t := t 169 runBenchmark(b, &t) 170 } 171 } 172 173 func runBenchmark(b *testing.B, t *StateTest) { 174 for _, subtest := range t.Subtests() { 175 subtest := subtest 176 key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index) 177 178 b.Run(key, func(b *testing.B) { 179 vmconfig := vm.Config{} 180 181 config, eips, err := GetChainConfig(subtest.Fork) 182 if err != nil { 183 b.Error(err) 184 return 185 } 186 var rules = config.Rules(new(big.Int), false, new(big.Int)) 187 188 vmconfig.ExtraEips = eips 189 block := t.genesis(config).ToBlock() 190 _, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, false) 191 192 var baseFee *big.Int 193 if rules.IsLondon { 194 baseFee = t.json.Env.BaseFee 195 if baseFee == nil { 196 // Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to 197 // parent - 2 : 0xa as the basefee for 'this' context. 198 baseFee = big.NewInt(0x0a) 199 } 200 } 201 post := t.json.Post[subtest.Fork][subtest.Index] 202 msg, err := t.json.Tx.toMessage(post, baseFee) 203 if err != nil { 204 b.Error(err) 205 return 206 } 207 208 // Try to recover tx with current signer 209 if len(post.TxBytes) != 0 { 210 var ttx types.Transaction 211 err := ttx.UnmarshalBinary(post.TxBytes) 212 if err != nil { 213 b.Error(err) 214 return 215 } 216 217 if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil { 218 b.Error(err) 219 return 220 } 221 } 222 223 // Prepare the EVM. 224 txContext := core.NewEVMTxContext(msg) 225 context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase) 226 context.GetHash = vmTestBlockHash 227 context.BaseFee = baseFee 228 evm := vm.NewEVM(context, txContext, statedb, config, vmconfig) 229 230 // Create "contract" for sender to cache code analysis. 231 sender := vm.NewContract(vm.AccountRef(msg.From()), vm.AccountRef(msg.From()), 232 nil, 0) 233 234 var ( 235 gasUsed uint64 236 elapsed uint64 237 refund uint64 238 ) 239 b.ResetTimer() 240 for n := 0; n < b.N; n++ { 241 snapshot := statedb.Snapshot() 242 statedb.Prepare(rules, msg.From(), context.Coinbase, msg.To(), vm.ActivePrecompiles(rules), msg.AccessList()) 243 b.StartTimer() 244 start := time.Now() 245 246 // Execute the message. 247 _, leftOverGas, err := evm.Call(sender, *msg.To(), msg.Data(), msg.Gas(), msg.Value()) 248 if err != nil { 249 b.Error(err) 250 return 251 } 252 253 b.StopTimer() 254 elapsed += uint64(time.Since(start)) 255 refund += statedb.GetRefund() 256 gasUsed += msg.Gas() - leftOverGas 257 258 statedb.RevertToSnapshot(snapshot) 259 } 260 if elapsed < 1 { 261 elapsed = 1 262 } 263 // Keep it as uint64, multiply 100 to get two digit float later 264 mgasps := (100 * 1000 * (gasUsed - refund)) / elapsed 265 b.ReportMetric(float64(mgasps)/100, "mgas/s") 266 }) 267 } 268 }