github.com/EgonCoin/EgonChain@v1.10.16/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/EgonCoin/EgonChain/core"
    31  	"github.com/EgonCoin/EgonChain/core/rawdb"
    32  	"github.com/EgonCoin/EgonChain/core/types"
    33  	"github.com/EgonCoin/EgonChain/core/vm"
    34  	"github.com/EgonCoin/EgonChain/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  		runBenchmark(b, &t)
   178  	}
   179  }
   180  
   181  func runBenchmark(b *testing.B, t *StateTest) {
   182  	for _, subtest := range t.Subtests() {
   183  		subtest := subtest
   184  		key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index)
   185  
   186  		b.Run(key, func(b *testing.B) {
   187  			vmconfig := vm.Config{}
   188  
   189  			config, eips, err := GetChainConfig(subtest.Fork)
   190  			if err != nil {
   191  				b.Error(err)
   192  				return
   193  			}
   194  			vmconfig.ExtraEips = eips
   195  			block := t.genesis(config).ToBlock(nil)
   196  			_, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, false)
   197  
   198  			var baseFee *big.Int
   199  			if config.IsLondon(new(big.Int)) {
   200  				baseFee = t.json.Env.BaseFee
   201  				if baseFee == nil {
   202  					// Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to
   203  					// parent - 2 : 0xa as the basefee for 'this' context.
   204  					baseFee = big.NewInt(0x0a)
   205  				}
   206  			}
   207  			post := t.json.Post[subtest.Fork][subtest.Index]
   208  			msg, err := t.json.Tx.toMessage(post, baseFee)
   209  			if err != nil {
   210  				b.Error(err)
   211  				return
   212  			}
   213  
   214  			// Try to recover tx with current signer
   215  			if len(post.TxBytes) != 0 {
   216  				var ttx types.Transaction
   217  				err := ttx.UnmarshalBinary(post.TxBytes)
   218  				if err != nil {
   219  					b.Error(err)
   220  					return
   221  				}
   222  
   223  				if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil {
   224  					b.Error(err)
   225  					return
   226  				}
   227  			}
   228  
   229  			// Prepare the EVM.
   230  			txContext := core.NewEVMTxContext(msg)
   231  			context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase)
   232  			context.GetHash = vmTestBlockHash
   233  			context.BaseFee = baseFee
   234  			evm := vm.NewEVM(context, txContext, statedb, config, vmconfig)
   235  
   236  			// Create "contract" for sender to cache code analysis.
   237  			sender := vm.NewContract(vm.AccountRef(msg.From()), vm.AccountRef(msg.From()),
   238  				nil, 0)
   239  
   240  			b.ResetTimer()
   241  			for n := 0; n < b.N; n++ {
   242  				// Execute the message.
   243  				snapshot := statedb.Snapshot()
   244  				_, _, err = evm.Call(sender, *msg.To(), msg.Data(), msg.Gas(), msg.Value())
   245  				if err != nil {
   246  					b.Error(err)
   247  					return
   248  				}
   249  				statedb.RevertToSnapshot(snapshot)
   250  			}
   251  
   252  		})
   253  	}
   254  }