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