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