state_test.go 7.6 KB

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