github.com/dim4egster/coreth@v0.10.2/core/vm/runtime/runtime_test.go (about)

     1  // (c) 2019-2021, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package runtime
    28  
    29  import (
    30  	"fmt"
    31  	"math/big"
    32  	"os"
    33  	"strings"
    34  	"testing"
    35  
    36  	"github.com/dim4egster/coreth/accounts/abi"
    37  	"github.com/dim4egster/coreth/consensus"
    38  	"github.com/dim4egster/coreth/core"
    39  	"github.com/dim4egster/coreth/core/rawdb"
    40  	"github.com/dim4egster/coreth/core/state"
    41  	"github.com/dim4egster/coreth/core/types"
    42  	"github.com/dim4egster/coreth/core/vm"
    43  	"github.com/dim4egster/coreth/eth/tracers"
    44  	"github.com/dim4egster/coreth/eth/tracers/logger"
    45  	"github.com/dim4egster/coreth/params"
    46  	"github.com/ethereum/go-ethereum/common"
    47  	"github.com/ethereum/go-ethereum/core/asm"
    48  
    49  	// force-load native tracers to trigger registration
    50  	_ "github.com/dim4egster/coreth/eth/tracers/native"
    51  )
    52  
    53  func TestDefaults(t *testing.T) {
    54  	cfg := new(Config)
    55  	setDefaults(cfg)
    56  
    57  	if cfg.Difficulty == nil {
    58  		t.Error("expected difficulty to be non nil")
    59  	}
    60  
    61  	if cfg.Time == nil {
    62  		t.Error("expected time to be non nil")
    63  	}
    64  	if cfg.GasLimit == 0 {
    65  		t.Error("didn't expect gaslimit to be zero")
    66  	}
    67  	if cfg.GasPrice == nil {
    68  		t.Error("expected time to be non nil")
    69  	}
    70  	if cfg.Value == nil {
    71  		t.Error("expected time to be non nil")
    72  	}
    73  	if cfg.GetHashFn == nil {
    74  		t.Error("expected time to be non nil")
    75  	}
    76  	if cfg.BlockNumber == nil {
    77  		t.Error("expected block number to be non nil")
    78  	}
    79  }
    80  
    81  func TestEVM(t *testing.T) {
    82  	defer func() {
    83  		if r := recover(); r != nil {
    84  			t.Fatalf("crashed with: %v", r)
    85  		}
    86  	}()
    87  
    88  	Execute([]byte{
    89  		byte(vm.DIFFICULTY),
    90  		byte(vm.TIMESTAMP),
    91  		byte(vm.GASLIMIT),
    92  		byte(vm.PUSH1),
    93  		byte(vm.ORIGIN),
    94  		byte(vm.BLOCKHASH),
    95  		byte(vm.COINBASE),
    96  	}, nil, nil)
    97  }
    98  
    99  func TestExecute(t *testing.T) {
   100  	ret, _, err := Execute([]byte{
   101  		byte(vm.PUSH1), 10,
   102  		byte(vm.PUSH1), 0,
   103  		byte(vm.MSTORE),
   104  		byte(vm.PUSH1), 32,
   105  		byte(vm.PUSH1), 0,
   106  		byte(vm.RETURN),
   107  	}, nil, nil)
   108  	if err != nil {
   109  		t.Fatal("didn't expect error", err)
   110  	}
   111  
   112  	num := new(big.Int).SetBytes(ret)
   113  	if num.Cmp(big.NewInt(10)) != 0 {
   114  		t.Error("Expected 10, got", num)
   115  	}
   116  }
   117  
   118  func TestCall(t *testing.T) {
   119  	state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   120  	address := common.HexToAddress("0x0a")
   121  	state.SetCode(address, []byte{
   122  		byte(vm.PUSH1), 10,
   123  		byte(vm.PUSH1), 0,
   124  		byte(vm.MSTORE),
   125  		byte(vm.PUSH1), 32,
   126  		byte(vm.PUSH1), 0,
   127  		byte(vm.RETURN),
   128  	})
   129  
   130  	ret, _, err := Call(address, nil, &Config{State: state})
   131  	if err != nil {
   132  		t.Fatal("didn't expect error", err)
   133  	}
   134  
   135  	num := new(big.Int).SetBytes(ret)
   136  	if num.Cmp(big.NewInt(10)) != 0 {
   137  		t.Error("Expected 10, got", num)
   138  	}
   139  }
   140  
   141  func BenchmarkCall(b *testing.B) {
   142  	var definition = `[{"constant":true,"inputs":[],"name":"seller","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"abort","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"refund","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"buyer","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"confirmReceived","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"state","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":false,"inputs":[],"name":"confirmPurchase","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[],"name":"Aborted","type":"event"},{"anonymous":false,"inputs":[],"name":"PurchaseConfirmed","type":"event"},{"anonymous":false,"inputs":[],"name":"ItemReceived","type":"event"},{"anonymous":false,"inputs":[],"name":"Refunded","type":"event"}]`
   143  
   144  	var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056")
   145  
   146  	abi, err := abi.JSON(strings.NewReader(definition))
   147  	if err != nil {
   148  		b.Fatal(err)
   149  	}
   150  
   151  	cpurchase, err := abi.Pack("confirmPurchase")
   152  	if err != nil {
   153  		b.Fatal(err)
   154  	}
   155  	creceived, err := abi.Pack("confirmReceived")
   156  	if err != nil {
   157  		b.Fatal(err)
   158  	}
   159  	refund, err := abi.Pack("refund")
   160  	if err != nil {
   161  		b.Fatal(err)
   162  	}
   163  
   164  	b.ResetTimer()
   165  	for i := 0; i < b.N; i++ {
   166  		for j := 0; j < 400; j++ {
   167  			Execute(code, cpurchase, nil)
   168  			Execute(code, creceived, nil)
   169  			Execute(code, refund, nil)
   170  		}
   171  	}
   172  }
   173  func benchmarkEVM_Create(bench *testing.B, code string) {
   174  	var (
   175  		statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   176  		sender     = common.BytesToAddress([]byte("sender"))
   177  		receiver   = common.BytesToAddress([]byte("receiver"))
   178  	)
   179  
   180  	statedb.CreateAccount(sender)
   181  	statedb.SetCode(receiver, common.FromHex(code))
   182  	runtimeConfig := Config{
   183  		Origin:      sender,
   184  		State:       statedb,
   185  		GasLimit:    10000000,
   186  		Difficulty:  big.NewInt(0x200000),
   187  		Time:        new(big.Int).SetUint64(0),
   188  		Coinbase:    common.Address{},
   189  		BlockNumber: new(big.Int).SetUint64(1),
   190  		ChainConfig: &params.ChainConfig{
   191  			ChainID:             big.NewInt(1),
   192  			HomesteadBlock:      new(big.Int),
   193  			ByzantiumBlock:      new(big.Int),
   194  			ConstantinopleBlock: new(big.Int),
   195  			DAOForkBlock:        new(big.Int),
   196  			DAOForkSupport:      false,
   197  			EIP150Block:         new(big.Int),
   198  			EIP155Block:         new(big.Int),
   199  			EIP158Block:         new(big.Int),
   200  		},
   201  		EVMConfig: vm.Config{},
   202  	}
   203  	// Warm up the intpools and stuff
   204  	bench.ResetTimer()
   205  	for i := 0; i < bench.N; i++ {
   206  		Call(receiver, []byte{}, &runtimeConfig)
   207  	}
   208  	bench.StopTimer()
   209  }
   210  
   211  func BenchmarkEVM_CREATE_500(bench *testing.B) {
   212  	// initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
   213  	benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
   214  }
   215  func BenchmarkEVM_CREATE2_500(bench *testing.B) {
   216  	// initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
   217  	benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
   218  }
   219  func BenchmarkEVM_CREATE_1200(bench *testing.B) {
   220  	// initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
   221  	benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
   222  }
   223  func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
   224  	// initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
   225  	benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
   226  }
   227  
   228  func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
   229  	header := types.Header{
   230  		Coinbase:   common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
   231  		Number:     big.NewInt(int64(n)),
   232  		ParentHash: parentHash,
   233  		Time:       1000,
   234  		Nonce:      types.BlockNonce{0x1},
   235  		Extra:      []byte{},
   236  		Difficulty: big.NewInt(0),
   237  		GasLimit:   100000,
   238  	}
   239  	return &header
   240  }
   241  
   242  type dummyChain struct {
   243  	counter int
   244  }
   245  
   246  // Engine retrieves the chain's consensus engine.
   247  func (d *dummyChain) Engine() consensus.Engine {
   248  	return nil
   249  }
   250  
   251  // GetHeader returns the hash corresponding to their hash.
   252  func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
   253  	d.counter++
   254  	parentHash := common.Hash{}
   255  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   256  	copy(parentHash[:], s)
   257  
   258  	//parentHash := common.Hash{byte(n - 1)}
   259  	//fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
   260  	return fakeHeader(n, parentHash)
   261  }
   262  
   263  // TestBlockhash tests the blockhash operation. It's a bit special, since it internally
   264  // requires access to a chain reader.
   265  func TestBlockhash(t *testing.T) {
   266  	// Current head
   267  	n := uint64(1000)
   268  	parentHash := common.Hash{}
   269  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   270  	copy(parentHash[:], s)
   271  	header := fakeHeader(n, parentHash)
   272  
   273  	// This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
   274  	// then iteratively fetches all blockhashes back to n-260.
   275  	// It returns
   276  	// 1. the first (should be zero)
   277  	// 2. the second (should be the parent hash)
   278  	// 3. the last non-zero hash
   279  	// By making the chain reader return hashes which correlate to the number, we can
   280  	// verify that it obtained the right hashes where it should
   281  
   282  	/*
   283  
   284  		pragma solidity ^0.5.3;
   285  		contract Hasher{
   286  
   287  			function test() public view returns (bytes32, bytes32, bytes32){
   288  				uint256 x = block.number;
   289  				bytes32 first;
   290  				bytes32 last;
   291  				bytes32 zero;
   292  				zero = blockhash(x); // Should be zeroes
   293  				first = blockhash(x-1);
   294  				for(uint256 i = 2 ; i < 260; i++){
   295  					bytes32 hash = blockhash(x - i);
   296  					if (uint256(hash) != 0){
   297  						last = hash;
   298  					}
   299  				}
   300  				return (zero, first, last);
   301  			}
   302  		}
   303  
   304  	*/
   305  	// The contract above
   306  	data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
   307  	// The method call to 'test()'
   308  	input := common.Hex2Bytes("f8a8fd6d")
   309  	chain := &dummyChain{}
   310  	ret, _, err := Execute(data, input, &Config{
   311  		GetHashFn:   core.GetHashFn(header, chain),
   312  		BlockNumber: new(big.Int).Set(header.Number),
   313  	})
   314  	if err != nil {
   315  		t.Fatalf("expected no error, got %v", err)
   316  	}
   317  	if len(ret) != 96 {
   318  		t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
   319  	}
   320  
   321  	zero := new(big.Int).SetBytes(ret[0:32])
   322  	first := new(big.Int).SetBytes(ret[32:64])
   323  	last := new(big.Int).SetBytes(ret[64:96])
   324  	if zero.BitLen() != 0 {
   325  		t.Fatalf("expected zeroes, got %x", ret[0:32])
   326  	}
   327  	if first.Uint64() != 999 {
   328  		t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
   329  	}
   330  	if last.Uint64() != 744 {
   331  		t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
   332  	}
   333  	if exp, got := 255, chain.counter; exp != got {
   334  		t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
   335  	}
   336  }
   337  
   338  // benchmarkNonModifyingCode benchmarks code, but if the code modifies the
   339  // state, this should not be used, since it does not reset the state between runs.
   340  func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) {
   341  	cfg := new(Config)
   342  	setDefaults(cfg)
   343  	cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   344  	cfg.GasLimit = gas
   345  	if len(tracerCode) > 0 {
   346  		tracer, err := tracers.New(tracerCode, new(tracers.Context), nil)
   347  		if err != nil {
   348  			b.Fatal(err)
   349  		}
   350  		cfg.EVMConfig = vm.Config{
   351  			Debug:  true,
   352  			Tracer: tracer,
   353  		}
   354  	}
   355  	var (
   356  		destination = common.BytesToAddress([]byte("contract"))
   357  		vmenv       = NewEnv(cfg)
   358  		sender      = vm.AccountRef(cfg.Origin)
   359  	)
   360  	cfg.State.CreateAccount(destination)
   361  	eoa := common.HexToAddress("E0")
   362  	{
   363  		cfg.State.CreateAccount(eoa)
   364  		cfg.State.SetNonce(eoa, 100)
   365  	}
   366  	reverting := common.HexToAddress("EE")
   367  	{
   368  		cfg.State.CreateAccount(reverting)
   369  		cfg.State.SetCode(reverting, []byte{
   370  			byte(vm.PUSH1), 0x00,
   371  			byte(vm.PUSH1), 0x00,
   372  			byte(vm.REVERT),
   373  		})
   374  	}
   375  
   376  	//cfg.State.CreateAccount(cfg.Origin)
   377  	// set the receiver's (the executing contract) code for execution.
   378  	cfg.State.SetCode(destination, code)
   379  	vmenv.Call(sender, destination, nil, gas, cfg.Value)
   380  
   381  	b.Run(name, func(b *testing.B) {
   382  		b.ReportAllocs()
   383  		for i := 0; i < b.N; i++ {
   384  			vmenv.Call(sender, destination, nil, gas, cfg.Value)
   385  		}
   386  	})
   387  }
   388  
   389  // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG
   390  // 55 ms
   391  func BenchmarkSimpleLoop(b *testing.B) {
   392  	staticCallIdentity := []byte{
   393  		byte(vm.JUMPDEST), //  [ count ]
   394  		// push args for the call
   395  		byte(vm.PUSH1), 0, // out size
   396  		byte(vm.DUP1),       // out offset
   397  		byte(vm.DUP1),       // out insize
   398  		byte(vm.DUP1),       // in offset
   399  		byte(vm.PUSH1), 0x4, // address of identity
   400  		byte(vm.GAS), // gas
   401  		byte(vm.STATICCALL),
   402  		byte(vm.POP),      // pop return value
   403  		byte(vm.PUSH1), 0, // jumpdestination
   404  		byte(vm.JUMP),
   405  	}
   406  
   407  	callIdentity := []byte{
   408  		byte(vm.JUMPDEST), //  [ count ]
   409  		// push args for the call
   410  		byte(vm.PUSH1), 0, // out size
   411  		byte(vm.DUP1),       // out offset
   412  		byte(vm.DUP1),       // out insize
   413  		byte(vm.DUP1),       // in offset
   414  		byte(vm.DUP1),       // value
   415  		byte(vm.PUSH1), 0x4, // address of identity
   416  		byte(vm.GAS), // gas
   417  		byte(vm.CALL),
   418  		byte(vm.POP),      // pop return value
   419  		byte(vm.PUSH1), 0, // jumpdestination
   420  		byte(vm.JUMP),
   421  	}
   422  
   423  	callInexistant := []byte{
   424  		byte(vm.JUMPDEST), //  [ count ]
   425  		// push args for the call
   426  		byte(vm.PUSH1), 0, // out size
   427  		byte(vm.DUP1),        // out offset
   428  		byte(vm.DUP1),        // out insize
   429  		byte(vm.DUP1),        // in offset
   430  		byte(vm.DUP1),        // value
   431  		byte(vm.PUSH1), 0xff, // address of existing contract
   432  		byte(vm.GAS), // gas
   433  		byte(vm.CALL),
   434  		byte(vm.POP),      // pop return value
   435  		byte(vm.PUSH1), 0, // jumpdestination
   436  		byte(vm.JUMP),
   437  	}
   438  
   439  	callEOA := []byte{
   440  		byte(vm.JUMPDEST), //  [ count ]
   441  		// push args for the call
   442  		byte(vm.PUSH1), 0, // out size
   443  		byte(vm.DUP1),        // out offset
   444  		byte(vm.DUP1),        // out insize
   445  		byte(vm.DUP1),        // in offset
   446  		byte(vm.DUP1),        // value
   447  		byte(vm.PUSH1), 0xE0, // address of EOA
   448  		byte(vm.GAS), // gas
   449  		byte(vm.CALL),
   450  		byte(vm.POP),      // pop return value
   451  		byte(vm.PUSH1), 0, // jumpdestination
   452  		byte(vm.JUMP),
   453  	}
   454  
   455  	loopingCode := []byte{
   456  		byte(vm.JUMPDEST), //  [ count ]
   457  		// push args for the call
   458  		byte(vm.PUSH1), 0, // out size
   459  		byte(vm.DUP1),       // out offset
   460  		byte(vm.DUP1),       // out insize
   461  		byte(vm.DUP1),       // in offset
   462  		byte(vm.PUSH1), 0x4, // address of identity
   463  		byte(vm.GAS), // gas
   464  
   465  		byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP),
   466  		byte(vm.PUSH1), 0, // jumpdestination
   467  		byte(vm.JUMP),
   468  	}
   469  
   470  	callRevertingContractWithInput := []byte{
   471  		byte(vm.JUMPDEST), //
   472  		// push args for the call
   473  		byte(vm.PUSH1), 0, // out size
   474  		byte(vm.DUP1),        // out offset
   475  		byte(vm.PUSH1), 0x20, // in size
   476  		byte(vm.PUSH1), 0x00, // in offset
   477  		byte(vm.PUSH1), 0x00, // value
   478  		byte(vm.PUSH1), 0xEE, // address of reverting contract
   479  		byte(vm.GAS), // gas
   480  		byte(vm.CALL),
   481  		byte(vm.POP),      // pop return value
   482  		byte(vm.PUSH1), 0, // jumpdestination
   483  		byte(vm.JUMP),
   484  	}
   485  
   486  	//tracer := logger.NewJSONLogger(nil, os.Stdout)
   487  	//Execute(loopingCode, nil, &Config{
   488  	//	EVMConfig: vm.Config{
   489  	//		Debug:  true,
   490  	//		Tracer: tracer,
   491  	//	}})
   492  	// 100M gas
   493  	benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b)
   494  	benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b)
   495  	benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b)
   496  	benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b)
   497  	benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b)
   498  	benchmarkNonModifyingCode(100000000, callRevertingContractWithInput, "call-reverting-100M", "", b)
   499  
   500  	//benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b)
   501  	//benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b)
   502  }
   503  
   504  // TestEip2929Cases contains various testcases that are used for
   505  // EIP-2929 about gas repricings
   506  func TestEip2929Cases(t *testing.T) {
   507  	t.Skip("Test only useful for generating documentation")
   508  	id := 1
   509  	prettyPrint := func(comment string, code []byte) {
   510  		instrs := make([]string, 0)
   511  		it := asm.NewInstructionIterator(code)
   512  		for it.Next() {
   513  			if it.Arg() != nil && 0 < len(it.Arg()) {
   514  				instrs = append(instrs, fmt.Sprintf("%v %#x", it.Op(), it.Arg()))
   515  			} else {
   516  				instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
   517  			}
   518  		}
   519  		ops := strings.Join(instrs, ", ")
   520  		fmt.Printf("### Case %d\n\n", id)
   521  		id++
   522  		fmt.Printf("%v\n\nBytecode: \n```\n%#x\n```\nOperations: \n```\n%v\n```\n\n",
   523  			comment,
   524  			code, ops)
   525  		Execute(code, nil, &Config{
   526  			EVMConfig: vm.Config{
   527  				Debug:     true,
   528  				Tracer:    logger.NewMarkdownLogger(nil, os.Stdout),
   529  				ExtraEips: []int{2929},
   530  			},
   531  		})
   532  	}
   533  
   534  	{ // First eip testcase
   535  		code := []byte{
   536  			// Three checks against a precompile
   537  			byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP),
   538  			byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP),
   539  			byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP),
   540  			// Three checks against a non-precompile
   541  			byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP),
   542  			byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP),
   543  			byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP),
   544  			// Same three checks (should be cheaper)
   545  			byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP),
   546  			byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP),
   547  			byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP),
   548  			// Check the origin, and the 'this'
   549  			byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP),
   550  			byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP),
   551  
   552  			byte(vm.STOP),
   553  		}
   554  		prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+
   555  			"and later checks the same operations twice against some non-precompiles. "+
   556  			"Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code)
   557  	}
   558  
   559  	{ // EXTCODECOPY
   560  		code := []byte{
   561  			// extcodecopy( 0xff,0,0,0,0)
   562  			byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
   563  			byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY),
   564  			// extcodecopy( 0xff,0,0,0,0)
   565  			byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
   566  			byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY),
   567  			// extcodecopy( this,0,0,0,0)
   568  			byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
   569  			byte(vm.ADDRESS), byte(vm.EXTCODECOPY),
   570  
   571  			byte(vm.STOP),
   572  		}
   573  		prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+
   574  			"and then does `extcodecopy( this,0,0,0,0)`.", code)
   575  	}
   576  
   577  	{ // SLOAD + SSTORE
   578  		code := []byte{
   579  
   580  			// Add slot `0x1` to access list
   581  			byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list)
   582  			// Write to `0x1` which is already in access list
   583  			byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11)
   584  			// Write to `0x2` which is not in access list
   585  			byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
   586  			// Write again to `0x2`
   587  			byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
   588  			// Read slot in access list (0x2)
   589  			byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2)
   590  			// Read slot in access list (0x1)
   591  			byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1)
   592  		}
   593  		prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+
   594  			"`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code)
   595  	}
   596  	{ // Call variants
   597  		code := []byte{
   598  			// identity precompile
   599  			byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   600  			byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP),
   601  
   602  			// random account - call 1
   603  			byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   604  			byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP),
   605  
   606  			// random account - call 2
   607  			byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   608  			byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP),
   609  		}
   610  		prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+
   611  			"account (cheap)", code)
   612  	}
   613  }
   614  
   615  // TestColdAccountAccessCost test that the cold account access cost is reported
   616  // correctly
   617  // see: https://github.com/ethereum/go-ethereum/issues/22649
   618  func TestColdAccountAccessCost(t *testing.T) {
   619  	for i, tc := range []struct {
   620  		code []byte
   621  		step int
   622  		want uint64
   623  	}{
   624  		{ // EXTCODEHASH(0xff)
   625  			code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)},
   626  			step: 1,
   627  			want: 2600,
   628  		},
   629  		{ // BALANCE(0xff)
   630  			code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)},
   631  			step: 1,
   632  			want: 2600,
   633  		},
   634  		{ // CALL(0xff)
   635  			code: []byte{
   636  				byte(vm.PUSH1), 0x0,
   637  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   638  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP),
   639  			},
   640  			step: 7,
   641  			want: 2855,
   642  		},
   643  		{ // CALLCODE(0xff)
   644  			code: []byte{
   645  				byte(vm.PUSH1), 0x0,
   646  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   647  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP),
   648  			},
   649  			step: 7,
   650  			want: 2855,
   651  		},
   652  		{ // DELEGATECALL(0xff)
   653  			code: []byte{
   654  				byte(vm.PUSH1), 0x0,
   655  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   656  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP),
   657  			},
   658  			step: 6,
   659  			want: 2855,
   660  		},
   661  		{ // STATICCALL(0xff)
   662  			code: []byte{
   663  				byte(vm.PUSH1), 0x0,
   664  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   665  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP),
   666  			},
   667  			step: 6,
   668  			want: 2855,
   669  		},
   670  		{ // SELFDESTRUCT(0xff)
   671  			code: []byte{
   672  				byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT),
   673  			},
   674  			step: 1,
   675  			want: 7600,
   676  		},
   677  	} {
   678  		tracer := logger.NewStructLogger(nil)
   679  		Execute(tc.code, nil, &Config{
   680  			EVMConfig: vm.Config{
   681  				Debug:  true,
   682  				Tracer: tracer,
   683  			},
   684  		})
   685  		have := tracer.StructLogs()[tc.step].GasCost
   686  		if want := tc.want; have != want {
   687  			for ii, op := range tracer.StructLogs() {
   688  				t.Logf("%d: %v %d", ii, op.OpName(), op.GasCost)
   689  			}
   690  			t.Fatalf("tescase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want)
   691  		}
   692  	}
   693  }