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