github.com/theQRL/go-zond@v0.1.1/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/theQRL/go-zond/core"
    32  	"github.com/theQRL/go-zond/core/rawdb"
    33  	"github.com/theQRL/go-zond/core/state"
    34  	"github.com/theQRL/go-zond/core/state/snapshot"
    35  	"github.com/theQRL/go-zond/core/types"
    36  	"github.com/theQRL/go-zond/core/vm"
    37  	"github.com/theQRL/go-zond/zond/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  	// Very time consuming
    54  	st.skipLoad(`^stTimeConsuming/`)
    55  	st.skipLoad(`.*vmPerformance/loop.*`)
    56  	// Uses 1GB RAM per tested fork
    57  	st.skipLoad(`^stStaticCall/static_Call1MB`)
    58  
    59  	// Broken tests:
    60  	// EOF is not part of cancun
    61  	st.skipLoad(`^stEOF/`)
    62  
    63  	// EIP-4844 tests need to be regenerated due to the data-to-blob rename
    64  	st.skipLoad(`^stEIP4844-blobtransactions/`)
    65  
    66  	// Expected failures:
    67  	// These EIP-4844 tests need to be regenerated.
    68  	st.fails(`stEIP4844-blobtransactions/opcodeBlobhashOutOfRange.json`, "test has incorrect state root")
    69  	st.fails(`stEIP4844-blobtransactions/opcodeBlobhBounds.json`, "test has incorrect state root")
    70  
    71  	// For Istanbul, older tests were moved into LegacyTests
    72  	for _, dir := range []string{
    73  		filepath.Join(baseDir, "EIPTests", "StateTests"),
    74  		stateTestDir,
    75  		legacyStateTestDir,
    76  		benchmarksDir,
    77  	} {
    78  		st.walk(t, dir, func(t *testing.T, name string, test *StateTest) {
    79  			for _, subtest := range test.Subtests() {
    80  				subtest := subtest
    81  				key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index)
    82  
    83  				t.Run(key+"/hash/trie", func(t *testing.T) {
    84  					withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error {
    85  						var result error
    86  						test.Run(subtest, vmconfig, false, rawdb.HashScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) {
    87  							result = st.checkFailure(t, err)
    88  						})
    89  						return result
    90  					})
    91  				})
    92  				t.Run(key+"/hash/snap", func(t *testing.T) {
    93  					withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error {
    94  						var result error
    95  						test.Run(subtest, vmconfig, true, rawdb.HashScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) {
    96  							if snaps != nil && state != nil {
    97  								if _, err := snaps.Journal(state.IntermediateRoot(false)); err != nil {
    98  									result = err
    99  									return
   100  								}
   101  							}
   102  							result = st.checkFailure(t, err)
   103  						})
   104  						return result
   105  					})
   106  				})
   107  				t.Run(key+"/path/trie", func(t *testing.T) {
   108  					withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error {
   109  						var result error
   110  						test.Run(subtest, vmconfig, false, rawdb.PathScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) {
   111  							result = st.checkFailure(t, err)
   112  						})
   113  						return result
   114  					})
   115  				})
   116  				t.Run(key+"/path/snap", func(t *testing.T) {
   117  					withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error {
   118  						var result error
   119  						test.Run(subtest, vmconfig, true, rawdb.PathScheme, func(err error, snaps *snapshot.Tree, state *state.StateDB) {
   120  							if snaps != nil && state != nil {
   121  								if _, err := snaps.Journal(state.IntermediateRoot(false)); err != nil {
   122  									result = err
   123  									return
   124  								}
   125  							}
   126  							result = st.checkFailure(t, err)
   127  						})
   128  						return result
   129  					})
   130  				})
   131  			}
   132  		})
   133  	}
   134  }
   135  
   136  // Transactions with gasLimit above this value will not get a VM trace on failure.
   137  const traceErrorLimit = 400000
   138  
   139  func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) {
   140  	// Use config from command line arguments.
   141  	config := vm.Config{}
   142  	err := test(config)
   143  	if err == nil {
   144  		return
   145  	}
   146  
   147  	// Test failed, re-run with tracing enabled.
   148  	t.Error(err)
   149  	if gasLimit > traceErrorLimit {
   150  		t.Log("gas limit too high for EVM trace")
   151  		return
   152  	}
   153  	buf := new(bytes.Buffer)
   154  	w := bufio.NewWriter(buf)
   155  	config.Tracer = logger.NewJSONLogger(&logger.Config{}, w)
   156  	err2 := test(config)
   157  	if !reflect.DeepEqual(err, err2) {
   158  		t.Errorf("different error for second run: %v", err2)
   159  	}
   160  	w.Flush()
   161  	if buf.Len() == 0 {
   162  		t.Log("no EVM operation logs generated")
   163  	} else {
   164  		t.Log("EVM operation log:\n" + buf.String())
   165  	}
   166  	// t.Logf("EVM output: 0x%x", tracer.Output())
   167  	// t.Logf("EVM error: %v", tracer.Error())
   168  }
   169  
   170  func BenchmarkEVM(b *testing.B) {
   171  	// Walk the directory.
   172  	dir := benchmarksDir
   173  	dirinfo, err := os.Stat(dir)
   174  	if os.IsNotExist(err) || !dirinfo.IsDir() {
   175  		fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the evm-benchmarks submodule?\n", dir)
   176  		b.Skip("missing test files")
   177  	}
   178  	err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
   179  		if info.IsDir() {
   180  			return nil
   181  		}
   182  		if ext := filepath.Ext(path); ext == ".json" {
   183  			name := filepath.ToSlash(strings.TrimPrefix(strings.TrimSuffix(path, ext), dir+string(filepath.Separator)))
   184  			b.Run(name, func(b *testing.B) { runBenchmarkFile(b, path) })
   185  		}
   186  		return nil
   187  	})
   188  	if err != nil {
   189  		b.Fatal(err)
   190  	}
   191  }
   192  
   193  func runBenchmarkFile(b *testing.B, path string) {
   194  	m := make(map[string]StateTest)
   195  	if err := readJSONFile(path, &m); err != nil {
   196  		b.Fatal(err)
   197  		return
   198  	}
   199  	if len(m) != 1 {
   200  		b.Fatal("expected single benchmark in a file")
   201  		return
   202  	}
   203  	for _, t := range m {
   204  		t := t
   205  		runBenchmark(b, &t)
   206  	}
   207  }
   208  
   209  func runBenchmark(b *testing.B, t *StateTest) {
   210  	for _, subtest := range t.Subtests() {
   211  		subtest := subtest
   212  		key := fmt.Sprintf("%s/%d", subtest.Fork, subtest.Index)
   213  
   214  		b.Run(key, func(b *testing.B) {
   215  			vmconfig := vm.Config{}
   216  
   217  			config, eips, err := GetChainConfig(subtest.Fork)
   218  			if err != nil {
   219  				b.Error(err)
   220  				return
   221  			}
   222  			var rules = config.Rules(new(big.Int), false, 0)
   223  
   224  			vmconfig.ExtraEips = eips
   225  			block := t.genesis(config).ToBlock()
   226  			triedb, _, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, false, rawdb.HashScheme)
   227  			defer triedb.Close()
   228  
   229  			var baseFee *big.Int
   230  			if rules.IsLondon {
   231  				baseFee = t.json.Env.BaseFee
   232  				if baseFee == nil {
   233  					// Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to
   234  					// parent - 2 : 0xa as the basefee for 'this' context.
   235  					baseFee = big.NewInt(0x0a)
   236  				}
   237  			}
   238  			post := t.json.Post[subtest.Fork][subtest.Index]
   239  			msg, err := t.json.Tx.toMessage(post, baseFee)
   240  			if err != nil {
   241  				b.Error(err)
   242  				return
   243  			}
   244  
   245  			// Try to recover tx with current signer
   246  			if len(post.TxBytes) != 0 {
   247  				var ttx types.Transaction
   248  				err := ttx.UnmarshalBinary(post.TxBytes)
   249  				if err != nil {
   250  					b.Error(err)
   251  					return
   252  				}
   253  
   254  				if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil {
   255  					b.Error(err)
   256  					return
   257  				}
   258  			}
   259  
   260  			// Prepare the EVM.
   261  			txContext := core.NewEVMTxContext(msg)
   262  			context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase)
   263  			context.GetHash = vmTestBlockHash
   264  			context.BaseFee = baseFee
   265  			evm := vm.NewEVM(context, txContext, statedb, config, vmconfig)
   266  
   267  			// Create "contract" for sender to cache code analysis.
   268  			sender := vm.NewContract(vm.AccountRef(msg.From), vm.AccountRef(msg.From),
   269  				nil, 0)
   270  
   271  			var (
   272  				gasUsed uint64
   273  				elapsed uint64
   274  				refund  uint64
   275  			)
   276  			b.ResetTimer()
   277  			for n := 0; n < b.N; n++ {
   278  				snapshot := statedb.Snapshot()
   279  				statedb.Prepare(rules, msg.From, context.Coinbase, msg.To, vm.ActivePrecompiles(rules), msg.AccessList)
   280  				b.StartTimer()
   281  				start := time.Now()
   282  
   283  				// Execute the message.
   284  				_, leftOverGas, err := evm.Call(sender, *msg.To, msg.Data, msg.GasLimit, msg.Value)
   285  				if err != nil {
   286  					b.Error(err)
   287  					return
   288  				}
   289  
   290  				b.StopTimer()
   291  				elapsed += uint64(time.Since(start))
   292  				refund += statedb.GetRefund()
   293  				gasUsed += msg.GasLimit - leftOverGas
   294  
   295  				statedb.RevertToSnapshot(snapshot)
   296  			}
   297  			if elapsed < 1 {
   298  				elapsed = 1
   299  			}
   300  			// Keep it as uint64, multiply 100 to get two digit float later
   301  			mgasps := (100 * 1000 * (gasUsed - refund)) / elapsed
   302  			b.ReportMetric(float64(mgasps)/100, "mgas/s")
   303  		})
   304  	}
   305  }