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