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