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