github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/core/vm/runtime/runtime_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 runtime
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"os"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/accounts/abi"
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/consensus"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/core/asm"
    32  	"github.com/ethereum/go-ethereum/core/rawdb"
    33  	"github.com/ethereum/go-ethereum/core/state"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/core/vm"
    36  	"github.com/ethereum/go-ethereum/eth/tracers"
    37  	"github.com/ethereum/go-ethereum/params"
    38  )
    39  
    40  func TestDefaults(t *testing.T) {
    41  	cfg := new(Config)
    42  	setDefaults(cfg)
    43  
    44  	if cfg.Difficulty == nil {
    45  		t.Error("expected difficulty to be non nil")
    46  	}
    47  
    48  	if cfg.Time == nil {
    49  		t.Error("expected time to be non nil")
    50  	}
    51  	if cfg.GasLimit == 0 {
    52  		t.Error("didn't expect gaslimit to be zero")
    53  	}
    54  	if cfg.GasPrice == nil {
    55  		t.Error("expected time to be non nil")
    56  	}
    57  	if cfg.Value == nil {
    58  		t.Error("expected time to be non nil")
    59  	}
    60  	if cfg.GetHashFn == nil {
    61  		t.Error("expected time to be non nil")
    62  	}
    63  	if cfg.BlockNumber == nil {
    64  		t.Error("expected block number to be non nil")
    65  	}
    66  }
    67  
    68  func TestEVM(t *testing.T) {
    69  	defer func() {
    70  		if r := recover(); r != nil {
    71  			t.Fatalf("crashed with: %v", r)
    72  		}
    73  	}()
    74  
    75  	Execute([]byte{
    76  		byte(vm.DIFFICULTY),
    77  		byte(vm.TIMESTAMP),
    78  		byte(vm.GASLIMIT),
    79  		byte(vm.PUSH1),
    80  		byte(vm.ORIGIN),
    81  		byte(vm.BLOCKHASH),
    82  		byte(vm.COINBASE),
    83  	}, nil, nil)
    84  }
    85  
    86  func TestExecute(t *testing.T) {
    87  	ret, _, err := Execute([]byte{
    88  		byte(vm.PUSH1), 10,
    89  		byte(vm.PUSH1), 0,
    90  		byte(vm.MSTORE),
    91  		byte(vm.PUSH1), 32,
    92  		byte(vm.PUSH1), 0,
    93  		byte(vm.RETURN),
    94  	}, nil, nil)
    95  	if err != nil {
    96  		t.Fatal("didn't expect error", err)
    97  	}
    98  
    99  	num := new(big.Int).SetBytes(ret)
   100  	if num.Cmp(big.NewInt(10)) != 0 {
   101  		t.Error("Expected 10, got", num)
   102  	}
   103  }
   104  
   105  func TestCall(t *testing.T) {
   106  	state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   107  	address := common.HexToAddress("0x0a")
   108  	state.SetCode(address, []byte{
   109  		byte(vm.PUSH1), 10,
   110  		byte(vm.PUSH1), 0,
   111  		byte(vm.MSTORE),
   112  		byte(vm.PUSH1), 32,
   113  		byte(vm.PUSH1), 0,
   114  		byte(vm.RETURN),
   115  	})
   116  
   117  	ret, _, err := Call(address, nil, &Config{State: state})
   118  	if err != nil {
   119  		t.Fatal("didn't expect error", err)
   120  	}
   121  
   122  	num := new(big.Int).SetBytes(ret)
   123  	if num.Cmp(big.NewInt(10)) != 0 {
   124  		t.Error("Expected 10, got", num)
   125  	}
   126  }
   127  
   128  func BenchmarkCall(b *testing.B) {
   129  	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"}]`
   130  
   131  	var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056")
   132  
   133  	abi, err := abi.JSON(strings.NewReader(definition))
   134  	if err != nil {
   135  		b.Fatal(err)
   136  	}
   137  
   138  	cpurchase, err := abi.Pack("confirmPurchase")
   139  	if err != nil {
   140  		b.Fatal(err)
   141  	}
   142  	creceived, err := abi.Pack("confirmReceived")
   143  	if err != nil {
   144  		b.Fatal(err)
   145  	}
   146  	refund, err := abi.Pack("refund")
   147  	if err != nil {
   148  		b.Fatal(err)
   149  	}
   150  
   151  	b.ResetTimer()
   152  	for i := 0; i < b.N; i++ {
   153  		for j := 0; j < 400; j++ {
   154  			Execute(code, cpurchase, nil)
   155  			Execute(code, creceived, nil)
   156  			Execute(code, refund, nil)
   157  		}
   158  	}
   159  }
   160  func benchmarkEVM_Create(bench *testing.B, code string) {
   161  	var (
   162  		statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   163  		sender     = common.BytesToAddress([]byte("sender"))
   164  		receiver   = common.BytesToAddress([]byte("receiver"))
   165  	)
   166  
   167  	statedb.CreateAccount(sender)
   168  	statedb.SetCode(receiver, common.FromHex(code))
   169  	runtimeConfig := Config{
   170  		Origin:      sender,
   171  		State:       statedb,
   172  		GasLimit:    10000000,
   173  		Difficulty:  big.NewInt(0x200000),
   174  		Time:        new(big.Int).SetUint64(0),
   175  		Coinbase:    common.Address{},
   176  		BlockNumber: new(big.Int).SetUint64(1),
   177  		ChainConfig: &params.ChainConfig{
   178  			ChainID:             big.NewInt(1),
   179  			HomesteadBlock:      new(big.Int),
   180  			ByzantiumBlock:      new(big.Int),
   181  			ConstantinopleBlock: new(big.Int),
   182  			DAOForkBlock:        new(big.Int),
   183  			DAOForkSupport:      false,
   184  			EIP150Block:         new(big.Int),
   185  			EIP155Block:         new(big.Int),
   186  			EIP158Block:         new(big.Int),
   187  		},
   188  		EVMConfig: vm.Config{},
   189  	}
   190  	// Warm up the intpools and stuff
   191  	bench.ResetTimer()
   192  	for i := 0; i < bench.N; i++ {
   193  		Call(receiver, []byte{}, &runtimeConfig)
   194  	}
   195  	bench.StopTimer()
   196  }
   197  
   198  func BenchmarkEVM_CREATE_500(bench *testing.B) {
   199  	// initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
   200  	benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
   201  }
   202  func BenchmarkEVM_CREATE2_500(bench *testing.B) {
   203  	// initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
   204  	benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
   205  }
   206  func BenchmarkEVM_CREATE_1200(bench *testing.B) {
   207  	// initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
   208  	benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
   209  }
   210  func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
   211  	// initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
   212  	benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
   213  }
   214  
   215  func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
   216  	header := types.Header{
   217  		Coinbase:   common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
   218  		Number:     big.NewInt(int64(n)),
   219  		ParentHash: parentHash,
   220  		Time:       1000,
   221  		Nonce:      types.BlockNonce{0x1},
   222  		Extra:      []byte{},
   223  		Difficulty: big.NewInt(0),
   224  		GasLimit:   100000,
   225  	}
   226  	return &header
   227  }
   228  
   229  type dummyChain struct {
   230  	counter int
   231  }
   232  
   233  // Engine retrieves the chain's consensus engine.
   234  func (d *dummyChain) Engine() consensus.Engine {
   235  	return nil
   236  }
   237  
   238  // GetHeader returns the hash corresponding to their hash.
   239  func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
   240  	d.counter++
   241  	parentHash := common.Hash{}
   242  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   243  	copy(parentHash[:], s)
   244  
   245  	//parentHash := common.Hash{byte(n - 1)}
   246  	//fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
   247  	return fakeHeader(n, parentHash)
   248  }
   249  
   250  // TestBlockhash tests the blockhash operation. It's a bit special, since it internally
   251  // requires access to a chain reader.
   252  func TestBlockhash(t *testing.T) {
   253  	// Current head
   254  	n := uint64(1000)
   255  	parentHash := common.Hash{}
   256  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   257  	copy(parentHash[:], s)
   258  	header := fakeHeader(n, parentHash)
   259  
   260  	// This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
   261  	// then iteratively fetches all blockhashes back to n-260.
   262  	// It returns
   263  	// 1. the first (should be zero)
   264  	// 2. the second (should be the parent hash)
   265  	// 3. the last non-zero hash
   266  	// By making the chain reader return hashes which correlate to the number, we can
   267  	// verify that it obtained the right hashes where it should
   268  
   269  	/*
   270  
   271  		pragma solidity ^0.5.3;
   272  		contract Hasher{
   273  
   274  			function test() public view returns (bytes32, bytes32, bytes32){
   275  				uint256 x = block.number;
   276  				bytes32 first;
   277  				bytes32 last;
   278  				bytes32 zero;
   279  				zero = blockhash(x); // Should be zeroes
   280  				first = blockhash(x-1);
   281  				for(uint256 i = 2 ; i < 260; i++){
   282  					bytes32 hash = blockhash(x - i);
   283  					if (uint256(hash) != 0){
   284  						last = hash;
   285  					}
   286  				}
   287  				return (zero, first, last);
   288  			}
   289  		}
   290  
   291  	*/
   292  	// The contract above
   293  	data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
   294  	// The method call to 'test()'
   295  	input := common.Hex2Bytes("f8a8fd6d")
   296  	chain := &dummyChain{}
   297  	ret, _, err := Execute(data, input, &Config{
   298  		GetHashFn:   core.GetHashFn(header, chain),
   299  		BlockNumber: new(big.Int).Set(header.Number),
   300  	})
   301  	if err != nil {
   302  		t.Fatalf("expected no error, got %v", err)
   303  	}
   304  	if len(ret) != 96 {
   305  		t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
   306  	}
   307  
   308  	zero := new(big.Int).SetBytes(ret[0:32])
   309  	first := new(big.Int).SetBytes(ret[32:64])
   310  	last := new(big.Int).SetBytes(ret[64:96])
   311  	if zero.BitLen() != 0 {
   312  		t.Fatalf("expected zeroes, got %x", ret[0:32])
   313  	}
   314  	if first.Uint64() != 999 {
   315  		t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
   316  	}
   317  	if last.Uint64() != 744 {
   318  		t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
   319  	}
   320  	if exp, got := 255, chain.counter; exp != got {
   321  		t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
   322  	}
   323  }
   324  
   325  type stepCounter struct {
   326  	inner *vm.JSONLogger
   327  	steps int
   328  }
   329  
   330  func (s *stepCounter) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   331  }
   332  
   333  func (s *stepCounter) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
   334  }
   335  
   336  func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {}
   337  
   338  func (s *stepCounter) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   339  	s.steps++
   340  	// Enable this for more output
   341  	//s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err)
   342  }
   343  
   344  // benchmarkNonModifyingCode benchmarks code, but if the code modifies the
   345  // state, this should not be used, since it does not reset the state between runs.
   346  func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) {
   347  	cfg := new(Config)
   348  	setDefaults(cfg)
   349  	cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   350  	cfg.GasLimit = gas
   351  	if len(tracerCode) > 0 {
   352  		tracer, err := tracers.New(tracerCode, new(tracers.Context))
   353  		if err != nil {
   354  			b.Fatal(err)
   355  		}
   356  		cfg.EVMConfig = vm.Config{
   357  			Debug:  true,
   358  			Tracer: tracer,
   359  		}
   360  	}
   361  	var (
   362  		destination = common.BytesToAddress([]byte("contract"))
   363  		vmenv       = NewEnv(cfg)
   364  		sender      = vm.AccountRef(cfg.Origin)
   365  	)
   366  	cfg.State.CreateAccount(destination)
   367  	eoa := common.HexToAddress("E0")
   368  	{
   369  		cfg.State.CreateAccount(eoa)
   370  		cfg.State.SetNonce(eoa, 100)
   371  	}
   372  	reverting := common.HexToAddress("EE")
   373  	{
   374  		cfg.State.CreateAccount(reverting)
   375  		cfg.State.SetCode(reverting, []byte{
   376  			byte(vm.PUSH1), 0x00,
   377  			byte(vm.PUSH1), 0x00,
   378  			byte(vm.REVERT),
   379  		})
   380  	}
   381  
   382  	//cfg.State.CreateAccount(cfg.Origin)
   383  	// set the receiver's (the executing contract) code for execution.
   384  	cfg.State.SetCode(destination, code)
   385  	vmenv.Call(sender, destination, nil, gas, cfg.Value)
   386  
   387  	b.Run(name, func(b *testing.B) {
   388  		b.ReportAllocs()
   389  		for i := 0; i < b.N; i++ {
   390  			vmenv.Call(sender, destination, nil, gas, cfg.Value)
   391  		}
   392  	})
   393  }
   394  
   395  // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG
   396  // 55 ms
   397  func BenchmarkSimpleLoop(b *testing.B) {
   398  
   399  	staticCallIdentity := []byte{
   400  		byte(vm.JUMPDEST), //  [ count ]
   401  		// push args for the call
   402  		byte(vm.PUSH1), 0, // out size
   403  		byte(vm.DUP1),       // out offset
   404  		byte(vm.DUP1),       // out insize
   405  		byte(vm.DUP1),       // in offset
   406  		byte(vm.PUSH1), 0x4, // address of identity
   407  		byte(vm.GAS), // gas
   408  		byte(vm.STATICCALL),
   409  		byte(vm.POP),      // pop return value
   410  		byte(vm.PUSH1), 0, // jumpdestination
   411  		byte(vm.JUMP),
   412  	}
   413  
   414  	callIdentity := []byte{
   415  		byte(vm.JUMPDEST), //  [ count ]
   416  		// push args for the call
   417  		byte(vm.PUSH1), 0, // out size
   418  		byte(vm.DUP1),       // out offset
   419  		byte(vm.DUP1),       // out insize
   420  		byte(vm.DUP1),       // in offset
   421  		byte(vm.DUP1),       // value
   422  		byte(vm.PUSH1), 0x4, // address of identity
   423  		byte(vm.GAS), // gas
   424  		byte(vm.CALL),
   425  		byte(vm.POP),      // pop return value
   426  		byte(vm.PUSH1), 0, // jumpdestination
   427  		byte(vm.JUMP),
   428  	}
   429  
   430  	callInexistant := []byte{
   431  		byte(vm.JUMPDEST), //  [ count ]
   432  		// push args for the call
   433  		byte(vm.PUSH1), 0, // out size
   434  		byte(vm.DUP1),        // out offset
   435  		byte(vm.DUP1),        // out insize
   436  		byte(vm.DUP1),        // in offset
   437  		byte(vm.DUP1),        // value
   438  		byte(vm.PUSH1), 0xff, // address of existing contract
   439  		byte(vm.GAS), // gas
   440  		byte(vm.CALL),
   441  		byte(vm.POP),      // pop return value
   442  		byte(vm.PUSH1), 0, // jumpdestination
   443  		byte(vm.JUMP),
   444  	}
   445  
   446  	callEOA := []byte{
   447  		byte(vm.JUMPDEST), //  [ count ]
   448  		// push args for the call
   449  		byte(vm.PUSH1), 0, // out size
   450  		byte(vm.DUP1),        // out offset
   451  		byte(vm.DUP1),        // out insize
   452  		byte(vm.DUP1),        // in offset
   453  		byte(vm.DUP1),        // value
   454  		byte(vm.PUSH1), 0xE0, // address of EOA
   455  		byte(vm.GAS), // gas
   456  		byte(vm.CALL),
   457  		byte(vm.POP),      // pop return value
   458  		byte(vm.PUSH1), 0, // jumpdestination
   459  		byte(vm.JUMP),
   460  	}
   461  
   462  	loopingCode := []byte{
   463  		byte(vm.JUMPDEST), //  [ count ]
   464  		// push args for the call
   465  		byte(vm.PUSH1), 0, // out size
   466  		byte(vm.DUP1),       // out offset
   467  		byte(vm.DUP1),       // out insize
   468  		byte(vm.DUP1),       // in offset
   469  		byte(vm.PUSH1), 0x4, // address of identity
   470  		byte(vm.GAS), // gas
   471  
   472  		byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP),
   473  		byte(vm.PUSH1), 0, // jumpdestination
   474  		byte(vm.JUMP),
   475  	}
   476  
   477  	calllRevertingContractWithInput := []byte{
   478  		byte(vm.JUMPDEST), //
   479  		// push args for the call
   480  		byte(vm.PUSH1), 0, // out size
   481  		byte(vm.DUP1),        // out offset
   482  		byte(vm.PUSH1), 0x20, // in size
   483  		byte(vm.PUSH1), 0x00, // in offset
   484  		byte(vm.PUSH1), 0x00, // value
   485  		byte(vm.PUSH1), 0xEE, // address of reverting contract
   486  		byte(vm.GAS), // gas
   487  		byte(vm.CALL),
   488  		byte(vm.POP),      // pop return value
   489  		byte(vm.PUSH1), 0, // jumpdestination
   490  		byte(vm.JUMP),
   491  	}
   492  
   493  	//tracer := vm.NewJSONLogger(nil, os.Stdout)
   494  	//Execute(loopingCode, nil, &Config{
   495  	//	EVMConfig: vm.Config{
   496  	//		Debug:  true,
   497  	//		Tracer: tracer,
   498  	//	}})
   499  	// 100M gas
   500  	benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b)
   501  	benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b)
   502  	benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b)
   503  	benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b)
   504  	benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b)
   505  	benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", "", b)
   506  
   507  	//benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b)
   508  	//benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b)
   509  }
   510  
   511  // TestEip2929Cases contains various testcases that are used for
   512  // EIP-2929 about gas repricings
   513  func TestEip2929Cases(t *testing.T) {
   514  
   515  	id := 1
   516  	prettyPrint := func(comment string, code []byte) {
   517  
   518  		instrs := make([]string, 0)
   519  		it := asm.NewInstructionIterator(code)
   520  		for it.Next() {
   521  			if it.Arg() != nil && 0 < len(it.Arg()) {
   522  				instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg()))
   523  			} else {
   524  				instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
   525  			}
   526  		}
   527  		ops := strings.Join(instrs, ", ")
   528  		fmt.Printf("### Case %d\n\n", id)
   529  		id++
   530  		fmt.Printf("%v\n\nBytecode: \n```\n0x%x\n```\nOperations: \n```\n%v\n```\n\n",
   531  			comment,
   532  			code, ops)
   533  		Execute(code, nil, &Config{
   534  			EVMConfig: vm.Config{
   535  				Debug:     true,
   536  				Tracer:    vm.NewMarkdownLogger(nil, os.Stdout),
   537  				ExtraEips: []int{2929},
   538  			},
   539  		})
   540  	}
   541  
   542  	{ // First eip testcase
   543  		code := []byte{
   544  			// Three checks against a precompile
   545  			byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP),
   546  			byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP),
   547  			byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP),
   548  			// Three checks against a non-precompile
   549  			byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP),
   550  			byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP),
   551  			byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP),
   552  			// Same three checks (should be cheaper)
   553  			byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP),
   554  			byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP),
   555  			byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP),
   556  			// Check the origin, and the 'this'
   557  			byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP),
   558  			byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP),
   559  
   560  			byte(vm.STOP),
   561  		}
   562  		prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+
   563  			"and later checks the same operations twice against some non-precompiles. "+
   564  			"Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code)
   565  	}
   566  
   567  	{ // EXTCODECOPY
   568  		code := []byte{
   569  			// extcodecopy( 0xff,0,0,0,0)
   570  			byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
   571  			byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY),
   572  			// extcodecopy( 0xff,0,0,0,0)
   573  			byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
   574  			byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY),
   575  			// extcodecopy( this,0,0,0,0)
   576  			byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
   577  			byte(vm.ADDRESS), byte(vm.EXTCODECOPY),
   578  
   579  			byte(vm.STOP),
   580  		}
   581  		prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+
   582  			"and then does `extcodecopy( this,0,0,0,0)`.", code)
   583  	}
   584  
   585  	{ // SLOAD + SSTORE
   586  		code := []byte{
   587  
   588  			// Add slot `0x1` to access list
   589  			byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list)
   590  			// Write to `0x1` which is already in access list
   591  			byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11)
   592  			// Write to `0x2` which is not in access list
   593  			byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
   594  			// Write again to `0x2`
   595  			byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
   596  			// Read slot in access list (0x2)
   597  			byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2)
   598  			// Read slot in access list (0x1)
   599  			byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1)
   600  		}
   601  		prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+
   602  			"`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code)
   603  	}
   604  	{ // Call variants
   605  		code := []byte{
   606  			// identity precompile
   607  			byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   608  			byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP),
   609  
   610  			// random account - call 1
   611  			byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   612  			byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP),
   613  
   614  			// random account - call 2
   615  			byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   616  			byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP),
   617  		}
   618  		prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+
   619  			"account (cheap)", code)
   620  	}
   621  }
   622  
   623  // TestColdAccountAccessCost test that the cold account access cost is reported
   624  // correctly
   625  // see: https://github.com/ethereum/go-ethereum/issues/22649
   626  func TestColdAccountAccessCost(t *testing.T) {
   627  	for i, tc := range []struct {
   628  		code []byte
   629  		step int
   630  		want uint64
   631  	}{
   632  		{ // EXTCODEHASH(0xff)
   633  			code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)},
   634  			step: 1,
   635  			want: 2600,
   636  		},
   637  		{ // BALANCE(0xff)
   638  			code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)},
   639  			step: 1,
   640  			want: 2600,
   641  		},
   642  		{ // CALL(0xff)
   643  			code: []byte{
   644  				byte(vm.PUSH1), 0x0,
   645  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   646  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP),
   647  			},
   648  			step: 7,
   649  			want: 2855,
   650  		},
   651  		{ // CALLCODE(0xff)
   652  			code: []byte{
   653  				byte(vm.PUSH1), 0x0,
   654  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   655  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP),
   656  			},
   657  			step: 7,
   658  			want: 2855,
   659  		},
   660  		{ // DELEGATECALL(0xff)
   661  			code: []byte{
   662  				byte(vm.PUSH1), 0x0,
   663  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   664  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP),
   665  			},
   666  			step: 6,
   667  			want: 2855,
   668  		},
   669  		{ // STATICCALL(0xff)
   670  			code: []byte{
   671  				byte(vm.PUSH1), 0x0,
   672  				byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
   673  				byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP),
   674  			},
   675  			step: 6,
   676  			want: 2855,
   677  		},
   678  		{ // SELFDESTRUCT(0xff)
   679  			code: []byte{
   680  				byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT),
   681  			},
   682  			step: 1,
   683  			want: 7600,
   684  		},
   685  	} {
   686  		tracer := vm.NewStructLogger(nil)
   687  		Execute(tc.code, nil, &Config{
   688  			EVMConfig: vm.Config{
   689  				Debug:  true,
   690  				Tracer: tracer,
   691  			},
   692  		})
   693  		have := tracer.StructLogs()[tc.step].GasCost
   694  		if want := tc.want; have != want {
   695  			for ii, op := range tracer.StructLogs() {
   696  				t.Logf("%d: %v %d", ii, op.OpName(), op.GasCost)
   697  			}
   698  			t.Fatalf("tescase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want)
   699  		}
   700  	}
   701  }
   702  
   703  func TestRuntimeJSTracer(t *testing.T) {
   704  	jsTracers := []string{
   705  		`{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0,
   706  	step: function() { this.steps++}, 
   707  	fault: function() {}, 
   708  	result: function() { 
   709  		return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 
   710  	}, 
   711  	enter: function(frame) { 
   712  		this.enters++; 
   713  		this.enterGas = frame.getGas();
   714  	}, 
   715  	exit: function(res) { 
   716  		this.exits++; 
   717  		this.gasUsed = res.getGasUsed();
   718  	}}`,
   719  		`{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0,
   720  	fault: function() {}, 
   721  	result: function() { 
   722  		return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 
   723  	}, 
   724  	enter: function(frame) { 
   725  		this.enters++; 
   726  		this.enterGas = frame.getGas();
   727  	}, 
   728  	exit: function(res) { 
   729  		this.exits++; 
   730  		this.gasUsed = res.getGasUsed();
   731  	}}`}
   732  	tests := []struct {
   733  		code []byte
   734  		// One result per tracer
   735  		results []string
   736  	}{
   737  		{
   738  			// CREATE
   739  			code: []byte{
   740  				// Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes)
   741  				byte(vm.PUSH5),
   742  				// Init code: PUSH1 0, PUSH1 0, RETURN (3 steps)
   743  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN),
   744  				byte(vm.PUSH1), 0,
   745  				byte(vm.MSTORE),
   746  				// length, offset, value
   747  				byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0,
   748  				byte(vm.CREATE),
   749  				byte(vm.POP),
   750  			},
   751  			results: []string{`"1,1,4294935775,6,12"`, `"1,1,4294935775,6,0"`},
   752  		},
   753  		{
   754  			// CREATE2
   755  			code: []byte{
   756  				// Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes)
   757  				byte(vm.PUSH5),
   758  				// Init code: PUSH1 0, PUSH1 0, RETURN (3 steps)
   759  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN),
   760  				byte(vm.PUSH1), 0,
   761  				byte(vm.MSTORE),
   762  				// salt, length, offset, value
   763  				byte(vm.PUSH1), 1, byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0,
   764  				byte(vm.CREATE2),
   765  				byte(vm.POP),
   766  			},
   767  			results: []string{`"1,1,4294935766,6,13"`, `"1,1,4294935766,6,0"`},
   768  		},
   769  		{
   770  			// CALL
   771  			code: []byte{
   772  				// outsize, outoffset, insize, inoffset
   773  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0,
   774  				byte(vm.PUSH1), 0, // value
   775  				byte(vm.PUSH1), 0xbb, //address
   776  				byte(vm.GAS), // gas
   777  				byte(vm.CALL),
   778  				byte(vm.POP),
   779  			},
   780  			results: []string{`"1,1,4294964716,6,13"`, `"1,1,4294964716,6,0"`},
   781  		},
   782  		{
   783  			// CALLCODE
   784  			code: []byte{
   785  				// outsize, outoffset, insize, inoffset
   786  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0,
   787  				byte(vm.PUSH1), 0, // value
   788  				byte(vm.PUSH1), 0xcc, //address
   789  				byte(vm.GAS), // gas
   790  				byte(vm.CALLCODE),
   791  				byte(vm.POP),
   792  			},
   793  			results: []string{`"1,1,4294964716,6,13"`, `"1,1,4294964716,6,0"`},
   794  		},
   795  		{
   796  			// STATICCALL
   797  			code: []byte{
   798  				// outsize, outoffset, insize, inoffset
   799  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0,
   800  				byte(vm.PUSH1), 0xdd, //address
   801  				byte(vm.GAS), // gas
   802  				byte(vm.STATICCALL),
   803  				byte(vm.POP),
   804  			},
   805  			results: []string{`"1,1,4294964719,6,12"`, `"1,1,4294964719,6,0"`},
   806  		},
   807  		{
   808  			// DELEGATECALL
   809  			code: []byte{
   810  				// outsize, outoffset, insize, inoffset
   811  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0,
   812  				byte(vm.PUSH1), 0xee, //address
   813  				byte(vm.GAS), // gas
   814  				byte(vm.DELEGATECALL),
   815  				byte(vm.POP),
   816  			},
   817  			results: []string{`"1,1,4294964719,6,12"`, `"1,1,4294964719,6,0"`},
   818  		},
   819  		{
   820  			// CALL self-destructing contract
   821  			code: []byte{
   822  				// outsize, outoffset, insize, inoffset
   823  				byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0,
   824  				byte(vm.PUSH1), 0, // value
   825  				byte(vm.PUSH1), 0xff, //address
   826  				byte(vm.GAS), // gas
   827  				byte(vm.CALL),
   828  				byte(vm.POP),
   829  			},
   830  			results: []string{`"2,2,0,5003,12"`, `"2,2,0,5003,0"`},
   831  		},
   832  	}
   833  	calleeCode := []byte{
   834  		byte(vm.PUSH1), 0,
   835  		byte(vm.PUSH1), 0,
   836  		byte(vm.RETURN),
   837  	}
   838  	depressedCode := []byte{
   839  		byte(vm.PUSH1), 0xaa,
   840  		byte(vm.SELFDESTRUCT),
   841  	}
   842  	main := common.HexToAddress("0xaa")
   843  	for i, jsTracer := range jsTracers {
   844  		for j, tc := range tests {
   845  			statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   846  			statedb.SetCode(main, tc.code)
   847  			statedb.SetCode(common.HexToAddress("0xbb"), calleeCode)
   848  			statedb.SetCode(common.HexToAddress("0xcc"), calleeCode)
   849  			statedb.SetCode(common.HexToAddress("0xdd"), calleeCode)
   850  			statedb.SetCode(common.HexToAddress("0xee"), calleeCode)
   851  			statedb.SetCode(common.HexToAddress("0xff"), depressedCode)
   852  
   853  			tracer, err := tracers.New(jsTracer, new(tracers.Context))
   854  			if err != nil {
   855  				t.Fatal(err)
   856  			}
   857  			_, _, err = Call(main, nil, &Config{
   858  				State: statedb,
   859  				EVMConfig: vm.Config{
   860  					Debug:  true,
   861  					Tracer: tracer,
   862  				}})
   863  			if err != nil {
   864  				t.Fatal("didn't expect error", err)
   865  			}
   866  			res, err := tracer.GetResult()
   867  			if err != nil {
   868  				t.Fatal(err)
   869  			}
   870  			if have, want := string(res), tc.results[i]; have != want {
   871  				t.Errorf("wrong result for tracer %d testcase %d, have \n%v\nwant\n%v\n", i, j, have, want)
   872  			}
   873  		}
   874  	}
   875  }
   876  
   877  func TestJSTracerCreateTx(t *testing.T) {
   878  	jsTracer := `
   879  	{enters: 0, exits: 0,
   880  	step: function() {},
   881  	fault: function() {},
   882  	result: function() { return [this.enters, this.exits].join(",") },
   883  	enter: function(frame) { this.enters++ },
   884  	exit: function(res) { this.exits++ }}`
   885  	code := []byte{byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN)}
   886  
   887  	statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   888  	tracer, err := tracers.New(jsTracer, new(tracers.Context))
   889  	if err != nil {
   890  		t.Fatal(err)
   891  	}
   892  	_, _, _, err = Create(code, &Config{
   893  		State: statedb,
   894  		EVMConfig: vm.Config{
   895  			Debug:  true,
   896  			Tracer: tracer,
   897  		}})
   898  	if err != nil {
   899  		t.Fatal(err)
   900  	}
   901  
   902  	res, err := tracer.GetResult()
   903  	if err != nil {
   904  		t.Fatal(err)
   905  	}
   906  	if have, want := string(res), `"0,0"`; have != want {
   907  		t.Errorf("wrong result for tracer, have \n%v\nwant\n%v\n", have, want)
   908  	}
   909  }
   910  
   911  func BenchmarkTracerStepVsCallFrame(b *testing.B) {
   912  	// Simply pushes and pops some values in a loop
   913  	code := []byte{
   914  		byte(vm.JUMPDEST),
   915  		byte(vm.PUSH1), 0,
   916  		byte(vm.PUSH1), 0,
   917  		byte(vm.POP),
   918  		byte(vm.POP),
   919  		byte(vm.PUSH1), 0, // jumpdestination
   920  		byte(vm.JUMP),
   921  	}
   922  
   923  	stepTracer := `
   924  	{
   925  	step: function() {},
   926  	fault: function() {},
   927  	result: function() {},
   928  	}`
   929  	callFrameTracer := `
   930  	{
   931  	enter: function() {},
   932  	exit: function() {},
   933  	fault: function() {},
   934  	result: function() {},
   935  	}`
   936  
   937  	benchmarkNonModifyingCode(10000000, code, "tracer-step-10M", stepTracer, b)
   938  	benchmarkNonModifyingCode(10000000, code, "tracer-call-frame-10M", callFrameTracer, b)
   939  }