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