github.com/ontio/ontology@v1.14.4/vm/evm/runtime/runtime_test.go (about)

     1  // Copyright (C) 2021 The Ontology Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package runtime
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"os"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/accounts/abi"
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/consensus"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/core/asm"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ontio/ontology/common/log"
    34  	"github.com/ontio/ontology/core/store/leveldbstore"
    35  	"github.com/ontio/ontology/core/store/overlaydb"
    36  	"github.com/ontio/ontology/smartcontract/service/native/ong"
    37  	"github.com/ontio/ontology/smartcontract/storage"
    38  	"github.com/ontio/ontology/vm/evm"
    39  	"github.com/ontio/ontology/vm/evm/params"
    40  	"github.com/stretchr/testify/require"
    41  )
    42  
    43  func init() {
    44  	log.InitLog(log.DebugLog, log.Stdout)
    45  }
    46  
    47  func TestDefaults(t *testing.T) {
    48  	cfg := new(Config)
    49  	setDefaults(cfg)
    50  
    51  	if cfg.Difficulty == nil {
    52  		t.Error("expected difficulty to be non nil")
    53  	}
    54  
    55  	if cfg.Time == nil {
    56  		t.Error("expected time to be non nil")
    57  	}
    58  	if cfg.GasLimit == 0 {
    59  		t.Error("didn't expect gaslimit to be zero")
    60  	}
    61  	if cfg.GasPrice == nil {
    62  		t.Error("expected time to be non nil")
    63  	}
    64  	if cfg.Value == nil {
    65  		t.Error("expected time to be non nil")
    66  	}
    67  	if cfg.GetHashFn == nil {
    68  		t.Error("expected time to be non nil")
    69  	}
    70  	if cfg.BlockNumber == nil {
    71  		t.Error("expected block number to be non nil")
    72  	}
    73  }
    74  
    75  func TestEVM(t *testing.T) {
    76  	defer func() {
    77  		if r := recover(); r != nil {
    78  			t.Fatalf("crashed with: %v", r)
    79  		}
    80  	}()
    81  
    82  	_, _, _ = Execute([]byte{
    83  		byte(evm.DIFFICULTY),
    84  		byte(evm.TIMESTAMP),
    85  		byte(evm.GASLIMIT),
    86  		byte(evm.PUSH1),
    87  		byte(evm.ORIGIN),
    88  		byte(evm.BLOCKHASH),
    89  		byte(evm.COINBASE),
    90  	}, nil, nil)
    91  }
    92  
    93  func TestExecute(t *testing.T) {
    94  	ret, _, err := Execute([]byte{
    95  		byte(evm.PUSH1), 10,
    96  		byte(evm.PUSH1), 0,
    97  		byte(evm.MSTORE),
    98  		byte(evm.PUSH1), 32,
    99  		byte(evm.PUSH1), 0,
   100  		byte(evm.RETURN),
   101  	}, nil, nil)
   102  	if err != nil {
   103  		t.Fatal("didn't expect error", err)
   104  	}
   105  
   106  	num := new(big.Int).SetBytes(ret)
   107  	if num.Cmp(big.NewInt(10)) != 0 {
   108  		t.Error("Expected 10, got", num)
   109  	}
   110  }
   111  
   112  func TestCall(t *testing.T) {
   113  	db := storage.NewCacheDB(overlaydb.NewOverlayDB(leveldbstore.NewMemLevelDBStore()))
   114  	statedb := storage.NewStateDB(db, common.Hash{}, common.Hash{}, ong.OngBalanceHandle{})
   115  	address := common.HexToAddress("0x0a")
   116  	statedb.SetCode(address, []byte{
   117  		byte(evm.PUSH1), 10,
   118  		byte(evm.PUSH1), 0,
   119  		byte(evm.MSTORE),
   120  		byte(evm.PUSH1), 32,
   121  		byte(evm.PUSH1), 0,
   122  		byte(evm.RETURN),
   123  	})
   124  
   125  	ret, _, err := Call(address, nil, &Config{State: statedb})
   126  	if err != nil {
   127  		t.Fatal("didn't expect error", err)
   128  	}
   129  
   130  	num := new(big.Int).SetBytes(ret)
   131  	if num.Cmp(big.NewInt(10)) != 0 {
   132  		t.Error("Expected 10, got", num)
   133  	}
   134  }
   135  
   136  func BenchmarkCall(b *testing.B) {
   137  	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"}]`
   138  
   139  	var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056")
   140  
   141  	abi, err := abi.JSON(strings.NewReader(definition))
   142  	if err != nil {
   143  		b.Fatal(err)
   144  	}
   145  
   146  	cpurchase, err := abi.Pack("confirmPurchase")
   147  	if err != nil {
   148  		b.Fatal(err)
   149  	}
   150  	creceived, err := abi.Pack("confirmReceived")
   151  	if err != nil {
   152  		b.Fatal(err)
   153  	}
   154  	refund, err := abi.Pack("refund")
   155  	if err != nil {
   156  		b.Fatal(err)
   157  	}
   158  
   159  	b.ResetTimer()
   160  	for i := 0; i < b.N; i++ {
   161  		for j := 0; j < 400; j++ {
   162  			Execute(code, cpurchase, nil)
   163  			Execute(code, creceived, nil)
   164  			Execute(code, refund, nil)
   165  		}
   166  	}
   167  }
   168  func benchmarkEVM_Create(bench *testing.B, code string) {
   169  	var (
   170  		db       = storage.NewCacheDB(overlaydb.NewOverlayDB(leveldbstore.NewMemLevelDBStore()))
   171  		statedb  = storage.NewStateDB(db, common.Hash{}, common.Hash{}, ong.OngBalanceHandle{})
   172  		sender   = common.BytesToAddress([]byte("sender"))
   173  		receiver = common.BytesToAddress([]byte("receiver"))
   174  	)
   175  
   176  	statedb.CreateAccount(sender)
   177  	statedb.SetCode(receiver, common.FromHex(code))
   178  	runtimeConfig := Config{
   179  		Origin:      sender,
   180  		State:       statedb,
   181  		GasLimit:    10000000,
   182  		Difficulty:  big.NewInt(0x200000),
   183  		Time:        new(big.Int).SetUint64(0),
   184  		Coinbase:    common.Address{},
   185  		BlockNumber: new(big.Int).SetUint64(1),
   186  		ChainConfig: &params.ChainConfig{
   187  			ChainID:             big.NewInt(1),
   188  			HomesteadBlock:      new(big.Int),
   189  			ByzantiumBlock:      new(big.Int),
   190  			ConstantinopleBlock: new(big.Int),
   191  			DAOForkBlock:        new(big.Int),
   192  			DAOForkSupport:      false,
   193  			EIP150Block:         new(big.Int),
   194  			EIP155Block:         new(big.Int),
   195  			EIP158Block:         new(big.Int),
   196  		},
   197  		EVMConfig: evm.Config{},
   198  	}
   199  	// Warm up the intpools and stuff
   200  	bench.ResetTimer()
   201  	for i := 0; i < bench.N; i++ {
   202  		Call(receiver, []byte{}, &runtimeConfig)
   203  	}
   204  	bench.StopTimer()
   205  }
   206  
   207  func BenchmarkEVM_CREATE_500(bench *testing.B) {
   208  	// initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
   209  	benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
   210  }
   211  func BenchmarkEVM_CREATE2_500(bench *testing.B) {
   212  	// initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
   213  	benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
   214  }
   215  func BenchmarkEVM_CREATE_1200(bench *testing.B) {
   216  	// initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
   217  	benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
   218  }
   219  func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
   220  	// initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
   221  	benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
   222  }
   223  
   224  func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
   225  	header := types.Header{
   226  		Coinbase:   common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
   227  		Number:     big.NewInt(int64(n)),
   228  		ParentHash: parentHash,
   229  		Time:       1000,
   230  		Nonce:      types.BlockNonce{0x1},
   231  		Extra:      []byte{},
   232  		Difficulty: big.NewInt(0),
   233  		GasLimit:   100000,
   234  	}
   235  	return &header
   236  }
   237  
   238  type dummyChain struct {
   239  	counter int
   240  }
   241  
   242  // Engine retrieves the chain's consensus engine.
   243  func (d *dummyChain) Engine() consensus.Engine {
   244  	return nil
   245  }
   246  
   247  // GetHeader returns the hash corresponding to their hash.
   248  func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
   249  	d.counter++
   250  	parentHash := common.Hash{}
   251  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   252  	copy(parentHash[:], s)
   253  
   254  	//parentHash := common.Hash{byte(n - 1)}
   255  	//fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
   256  	return fakeHeader(n, parentHash)
   257  }
   258  
   259  // TestBlockhash tests the blockhash operation. It's a bit special, since it internally
   260  // requires access to a chain reader.
   261  func TestBlockhash(t *testing.T) {
   262  	// Current head
   263  	n := uint64(1000)
   264  	parentHash := common.Hash{}
   265  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   266  	copy(parentHash[:], s)
   267  	header := fakeHeader(n, parentHash)
   268  
   269  	// This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
   270  	// then iteratively fetches all blockhashes back to n-260.
   271  	// It returns
   272  	// 1. the first (should be zero)
   273  	// 2. the second (should be the parent hash)
   274  	// 3. the last non-zero hash
   275  	// By making the chain reader return hashes which correlate to the number, we can
   276  	// verify that it obtained the right hashes where it should
   277  
   278  	/*
   279  
   280  		pragma solidity ^0.5.3;
   281  		contract Hasher{
   282  
   283  			function test() public view returns (bytes32, bytes32, bytes32){
   284  				uint256 x = block.number;
   285  				bytes32 first;
   286  				bytes32 last;
   287  				bytes32 zero;
   288  				zero = blockhash(x); // Should be zeroes
   289  				first = blockhash(x-1);
   290  				for(uint256 i = 2 ; i < 260; i++){
   291  					bytes32 hash = blockhash(x - i);
   292  					if (uint256(hash) != 0){
   293  						last = hash;
   294  					}
   295  				}
   296  				return (zero, first, last);
   297  			}
   298  		}
   299  
   300  	*/
   301  	// The contract above
   302  	data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
   303  	// The method call to 'test()'
   304  	input := common.Hex2Bytes("f8a8fd6d")
   305  	chain := &dummyChain{}
   306  	ret, _, err := Execute(data, input, &Config{
   307  		GetHashFn:   core.GetHashFn(header, chain),
   308  		BlockNumber: new(big.Int).Set(header.Number),
   309  	})
   310  	if err != nil {
   311  		t.Fatalf("expected no error, got %v", err)
   312  	}
   313  	if len(ret) != 96 {
   314  		t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
   315  	}
   316  
   317  	zero := new(big.Int).SetBytes(ret[0:32])
   318  	first := new(big.Int).SetBytes(ret[32:64])
   319  	last := new(big.Int).SetBytes(ret[64:96])
   320  	if zero.BitLen() != 0 {
   321  		t.Fatalf("expected zeroes, got %x", ret[0:32])
   322  	}
   323  	if first.Uint64() != 999 {
   324  		t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
   325  	}
   326  	if last.Uint64() != 744 {
   327  		t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
   328  	}
   329  	if exp, got := 255, chain.counter; exp != got {
   330  		t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
   331  	}
   332  }
   333  
   334  type stepCounter struct {
   335  	inner *evm.JSONLogger
   336  	steps int
   337  }
   338  
   339  func (s *stepCounter) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   340  }
   341  
   342  func (s *stepCounter) CaptureState(env *evm.EVM, pc uint64, op evm.OpCode, gas, cost uint64,
   343  	memory *evm.Memory, stack *evm.Stack, rStack *evm.ReturnStack, rData []byte,
   344  	contract *evm.Contract, depth int, err error) {
   345  	s.steps++
   346  	// Enable this for more output
   347  	//s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err)
   348  }
   349  
   350  func (s *stepCounter) CaptureFault(env *evm.EVM, pc uint64, op evm.OpCode, gas, cost uint64,
   351  	memory *evm.Memory, stack *evm.Stack, rStack *evm.ReturnStack, contract *evm.Contract, depth int, err error) {
   352  }
   353  
   354  func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {
   355  }
   356  
   357  func TestJumpSub1024Limit(t *testing.T) {
   358  	db := storage.NewCacheDB(overlaydb.NewOverlayDB(leveldbstore.NewMemLevelDBStore()))
   359  	statedb := storage.NewStateDB(db, common.Hash{}, common.Hash{}, ong.OngBalanceHandle{})
   360  	address := common.HexToAddress("0x0a")
   361  	// Code is
   362  	// 0 beginsub
   363  	// 1 push 0
   364  	// 3 jumpsub
   365  	//
   366  	// The code recursively calls itself. It should error when the returns-stack
   367  	// grows above 1023
   368  	statedb.SetCode(address, []byte{
   369  		byte(evm.PUSH1), 3,
   370  		byte(evm.JUMPSUB),
   371  		byte(evm.BEGINSUB),
   372  		byte(evm.PUSH1), 3,
   373  		byte(evm.JUMPSUB),
   374  	})
   375  	tracer := stepCounter{inner: evm.NewJSONLogger(nil, os.Stdout)}
   376  	// Enable 2315
   377  	_, _, err := Call(address, nil, &Config{State: statedb,
   378  		GasLimit:    20000,
   379  		ChainConfig: params.AllEthashProtocolChanges,
   380  		EVMConfig: evm.Config{
   381  			ExtraEips: []int{2315},
   382  			Debug:     true,
   383  			//Tracer:    evm.NewJSONLogger(nil, os.Stdout),
   384  			Tracer: &tracer,
   385  		}})
   386  	exp := "return stack limit reached"
   387  	if err.Error() != exp {
   388  		t.Fatalf("expected %v, got %v", exp, err)
   389  	}
   390  	if exp, got := 2048, tracer.steps; exp != got {
   391  		t.Fatalf("expected %d steps, got %d", exp, got)
   392  	}
   393  }
   394  
   395  func TestReturnSubShallow(t *testing.T) {
   396  	db := storage.NewCacheDB(overlaydb.NewOverlayDB(leveldbstore.NewMemLevelDBStore()))
   397  	statedb := storage.NewStateDB(db, common.Hash{}, common.Hash{}, ong.OngBalanceHandle{})
   398  	address := common.HexToAddress("0x0a")
   399  	// The code does returnsub without having anything on the returnstack.
   400  	// It should not panic, but just fail after one step
   401  	statedb.SetCode(address, []byte{
   402  		byte(evm.PUSH1), 5,
   403  		byte(evm.JUMPSUB),
   404  		byte(evm.RETURNSUB),
   405  		byte(evm.PC),
   406  		byte(evm.BEGINSUB),
   407  		byte(evm.RETURNSUB),
   408  		byte(evm.PC),
   409  	})
   410  	tracer := stepCounter{}
   411  
   412  	// Enable 2315
   413  	_, _, err := Call(address, nil, &Config{State: statedb,
   414  		GasLimit:    10000,
   415  		ChainConfig: params.AllEthashProtocolChanges,
   416  		EVMConfig: evm.Config{
   417  			ExtraEips: []int{2315},
   418  			Debug:     true,
   419  			Tracer:    &tracer,
   420  		}})
   421  
   422  	exp := "invalid retsub"
   423  	if err.Error() != exp {
   424  		t.Fatalf("expected %v, got %v", exp, err)
   425  	}
   426  	if exp, got := 4, tracer.steps; exp != got {
   427  		t.Fatalf("expected %d steps, got %d", exp, got)
   428  	}
   429  }
   430  
   431  // disabled -- only used for generating markdown
   432  func DisabledTestReturnCases(t *testing.T) {
   433  	cfg := &Config{
   434  		EVMConfig: evm.Config{
   435  			Debug:     true,
   436  			Tracer:    evm.NewMarkdownLogger(nil, os.Stdout),
   437  			ExtraEips: []int{2315},
   438  		},
   439  	}
   440  	// This should fail at first opcode
   441  	Execute([]byte{
   442  		byte(evm.RETURNSUB),
   443  		byte(evm.PC),
   444  		byte(evm.PC),
   445  	}, nil, cfg)
   446  
   447  	// Should also fail
   448  	Execute([]byte{
   449  		byte(evm.PUSH1), 5,
   450  		byte(evm.JUMPSUB),
   451  		byte(evm.RETURNSUB),
   452  		byte(evm.PC),
   453  		byte(evm.BEGINSUB),
   454  		byte(evm.RETURNSUB),
   455  		byte(evm.PC),
   456  	}, nil, cfg)
   457  
   458  	// This should complete
   459  	Execute([]byte{
   460  		byte(evm.PUSH1), 0x4,
   461  		byte(evm.JUMPSUB),
   462  		byte(evm.STOP),
   463  		byte(evm.BEGINSUB),
   464  		byte(evm.PUSH1), 0x9,
   465  		byte(evm.JUMPSUB),
   466  		byte(evm.RETURNSUB),
   467  		byte(evm.BEGINSUB),
   468  		byte(evm.RETURNSUB),
   469  	}, nil, cfg)
   470  }
   471  
   472  // DisabledTestEipExampleCases contains various testcases that are used for the
   473  // EIP examples
   474  // This test is disabled, as it's only used for generating markdown
   475  func DisabledTestEipExampleCases(t *testing.T) {
   476  	cfg := &Config{
   477  		EVMConfig: evm.Config{
   478  			Debug:     true,
   479  			Tracer:    evm.NewMarkdownLogger(nil, os.Stdout),
   480  			ExtraEips: []int{2315},
   481  		},
   482  	}
   483  	prettyPrint := func(comment string, code []byte) {
   484  		instrs := make([]string, 0)
   485  		it := asm.NewInstructionIterator(code)
   486  		for it.Next() {
   487  			if it.Arg() != nil && 0 < len(it.Arg()) {
   488  				instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg()))
   489  			} else {
   490  				instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
   491  			}
   492  		}
   493  		ops := strings.Join(instrs, ", ")
   494  
   495  		fmt.Printf("%v\nBytecode: `0x%x` (`%v`)\n",
   496  			comment,
   497  			code, ops)
   498  		Execute(code, nil, cfg)
   499  	}
   500  
   501  	{ // First eip testcase
   502  		code := []byte{
   503  			byte(evm.PUSH1), 4,
   504  			byte(evm.JUMPSUB),
   505  			byte(evm.STOP),
   506  			byte(evm.BEGINSUB),
   507  			byte(evm.RETURNSUB),
   508  		}
   509  		prettyPrint("This should jump into a subroutine, back out and stop.", code)
   510  	}
   511  
   512  	{
   513  		code := []byte{
   514  			byte(evm.PUSH9), 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8),
   515  			byte(evm.JUMPSUB),
   516  			byte(evm.STOP),
   517  			byte(evm.BEGINSUB),
   518  			byte(evm.PUSH1), 8 + 9,
   519  			byte(evm.JUMPSUB),
   520  			byte(evm.RETURNSUB),
   521  			byte(evm.BEGINSUB),
   522  			byte(evm.RETURNSUB),
   523  		}
   524  		prettyPrint("This should execute fine, going into one two depths of subroutines", code)
   525  	}
   526  	// TODO(@holiman) move this test into an actual test, which not only prints
   527  	// out the trace.
   528  	{
   529  		code := []byte{
   530  			byte(evm.PUSH9), 0x01, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8),
   531  			byte(evm.JUMPSUB),
   532  			byte(evm.STOP),
   533  			byte(evm.BEGINSUB),
   534  			byte(evm.PUSH1), 8 + 9,
   535  			byte(evm.JUMPSUB),
   536  			byte(evm.RETURNSUB),
   537  			byte(evm.BEGINSUB),
   538  			byte(evm.RETURNSUB),
   539  		}
   540  		prettyPrint("This should fail, since the given location is outside of the "+
   541  			"code-range. The code is the same as previous example, except that the "+
   542  			"pushed location is `0x01000000000000000c` instead of `0x0c`.", code)
   543  	}
   544  	{
   545  		// This should fail at first opcode
   546  		code := []byte{
   547  			byte(evm.RETURNSUB),
   548  			byte(evm.PC),
   549  			byte(evm.PC),
   550  		}
   551  		prettyPrint("This should fail at first opcode, due to shallow `return_stack`", code)
   552  
   553  	}
   554  	{
   555  		code := []byte{
   556  			byte(evm.PUSH1), 5, // Jump past the subroutine
   557  			byte(evm.JUMP),
   558  			byte(evm.BEGINSUB),
   559  			byte(evm.RETURNSUB),
   560  			byte(evm.JUMPDEST),
   561  			byte(evm.PUSH1), 3, // Now invoke the subroutine
   562  			byte(evm.JUMPSUB),
   563  		}
   564  		prettyPrint("In this example. the JUMPSUB is on the last byte of code. When the "+
   565  			"subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, "+
   566  			"and not exit with error", code)
   567  	}
   568  
   569  	{
   570  		code := []byte{
   571  			byte(evm.BEGINSUB),
   572  			byte(evm.RETURNSUB),
   573  			byte(evm.STOP),
   574  		}
   575  		prettyPrint("In this example, the code 'walks' into a subroutine, which is not "+
   576  			"allowed, and causes an error", code)
   577  	}
   578  }
   579  
   580  // benchmarkNonModifyingCode benchmarks code, but if the code modifies the
   581  // state, this should not be used, since it does not reset the state between runs.
   582  func benchmarkNonModifyingCode(gas uint64, code []byte, name string, b *testing.B) {
   583  	cfg := new(Config)
   584  	setDefaults(cfg)
   585  	db := storage.NewCacheDB(overlaydb.NewOverlayDB(leveldbstore.NewMemLevelDBStore()))
   586  	cfg.State = storage.NewStateDB(db, common.Hash{}, common.Hash{}, ong.OngBalanceHandle{})
   587  	cfg.GasLimit = gas
   588  	var (
   589  		destination = common.BytesToAddress([]byte("contract"))
   590  		vmenv       = NewEnv(cfg)
   591  		sender      = evm.AccountRef(cfg.Origin)
   592  	)
   593  	cfg.State.CreateAccount(destination)
   594  	eoa := common.HexToAddress("E0")
   595  	{
   596  		cfg.State.CreateAccount(eoa)
   597  		cfg.State.SetNonce(eoa, 100)
   598  	}
   599  	reverting := common.HexToAddress("EE")
   600  	{
   601  		cfg.State.CreateAccount(reverting)
   602  		cfg.State.SetCode(reverting, []byte{
   603  			byte(evm.PUSH1), 0x00,
   604  			byte(evm.PUSH1), 0x00,
   605  			byte(evm.REVERT),
   606  		})
   607  	}
   608  
   609  	//cfg.State.CreateAccount(cfg.Origin)
   610  	// set the receiver's (the executing contract) code for execution.
   611  	cfg.State.SetCode(destination, code)
   612  	vmenv.Call(sender, destination, nil, gas, cfg.Value)
   613  
   614  	b.Run(name, func(b *testing.B) {
   615  		b.ReportAllocs()
   616  		for i := 0; i < b.N; i++ {
   617  			vmenv.Call(sender, destination, nil, gas, cfg.Value)
   618  		}
   619  	})
   620  }
   621  
   622  // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG
   623  // 55 ms
   624  func BenchmarkSimpleLoop(b *testing.B) {
   625  
   626  	staticCallIdentity := []byte{
   627  		byte(evm.JUMPDEST), //  [ count ]
   628  		// push args for the call
   629  		byte(evm.PUSH1), 0, // out size
   630  		byte(evm.DUP1),       // out offset
   631  		byte(evm.DUP1),       // out insize
   632  		byte(evm.DUP1),       // in offset
   633  		byte(evm.PUSH1), 0x4, // address of identity
   634  		byte(evm.GAS), // gas
   635  		byte(evm.STATICCALL),
   636  		byte(evm.POP),      // pop return value
   637  		byte(evm.PUSH1), 0, // jumpdestination
   638  		byte(evm.JUMP),
   639  	}
   640  
   641  	callIdentity := []byte{
   642  		byte(evm.JUMPDEST), //  [ count ]
   643  		// push args for the call
   644  		byte(evm.PUSH1), 0, // out size
   645  		byte(evm.DUP1),       // out offset
   646  		byte(evm.DUP1),       // out insize
   647  		byte(evm.DUP1),       // in offset
   648  		byte(evm.DUP1),       // value
   649  		byte(evm.PUSH1), 0x4, // address of identity
   650  		byte(evm.GAS), // gas
   651  		byte(evm.CALL),
   652  		byte(evm.POP),      // pop return value
   653  		byte(evm.PUSH1), 0, // jumpdestination
   654  		byte(evm.JUMP),
   655  	}
   656  
   657  	callInexistant := []byte{
   658  		byte(evm.JUMPDEST), //  [ count ]
   659  		// push args for the call
   660  		byte(evm.PUSH1), 0, // out size
   661  		byte(evm.DUP1),        // out offset
   662  		byte(evm.DUP1),        // out insize
   663  		byte(evm.DUP1),        // in offset
   664  		byte(evm.DUP1),        // value
   665  		byte(evm.PUSH1), 0xff, // address of existing contract
   666  		byte(evm.GAS), // gas
   667  		byte(evm.CALL),
   668  		byte(evm.POP),      // pop return value
   669  		byte(evm.PUSH1), 0, // jumpdestination
   670  		byte(evm.JUMP),
   671  	}
   672  
   673  	callEOA := []byte{
   674  		byte(evm.JUMPDEST), //  [ count ]
   675  		// push args for the call
   676  		byte(evm.PUSH1), 0, // out size
   677  		byte(evm.DUP1),        // out offset
   678  		byte(evm.DUP1),        // out insize
   679  		byte(evm.DUP1),        // in offset
   680  		byte(evm.DUP1),        // value
   681  		byte(evm.PUSH1), 0xE0, // address of EOA
   682  		byte(evm.GAS), // gas
   683  		byte(evm.CALL),
   684  		byte(evm.POP),      // pop return value
   685  		byte(evm.PUSH1), 0, // jumpdestination
   686  		byte(evm.JUMP),
   687  	}
   688  
   689  	loopingCode := []byte{
   690  		byte(evm.JUMPDEST), //  [ count ]
   691  		// push args for the call
   692  		byte(evm.PUSH1), 0, // out size
   693  		byte(evm.DUP1),       // out offset
   694  		byte(evm.DUP1),       // out insize
   695  		byte(evm.DUP1),       // in offset
   696  		byte(evm.PUSH1), 0x4, // address of identity
   697  		byte(evm.GAS), // gas
   698  
   699  		byte(evm.POP), byte(evm.POP), byte(evm.POP), byte(evm.POP), byte(evm.POP), byte(evm.POP),
   700  		byte(evm.PUSH1), 0, // jumpdestination
   701  		byte(evm.JUMP),
   702  	}
   703  
   704  	calllRevertingContractWithInput := []byte{
   705  		byte(evm.JUMPDEST), //
   706  		// push args for the call
   707  		byte(evm.PUSH1), 0, // out size
   708  		byte(evm.DUP1),        // out offset
   709  		byte(evm.PUSH1), 0x20, // in size
   710  		byte(evm.PUSH1), 0x00, // in offset
   711  		byte(evm.PUSH1), 0x00, // value
   712  		byte(evm.PUSH1), 0xEE, // address of reverting contract
   713  		byte(evm.GAS), // gas
   714  		byte(evm.CALL),
   715  		byte(evm.POP),      // pop return value
   716  		byte(evm.PUSH1), 0, // jumpdestination
   717  		byte(evm.JUMP),
   718  	}
   719  
   720  	//tracer := evm.NewJSONLogger(nil, os.Stdout)
   721  	//Execute(loopingCode, nil, &Config{
   722  	//	EVMConfig: evm.Config{
   723  	//		Debug:  true,
   724  	//		Tracer: tracer,
   725  	//	}})
   726  	// 100M gas
   727  	benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", b)
   728  	benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", b)
   729  	benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", b)
   730  	benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", b)
   731  	benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", b)
   732  	benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", b)
   733  
   734  	//benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b)
   735  	//benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b)
   736  }
   737  
   738  // TestEip2929Cases contains various testcases that are used for
   739  // EIP-2929 about gas repricings
   740  func TestEip2929Cases(t *testing.T) {
   741  
   742  	id := 1
   743  	prettyPrint := func(comment string, code []byte) {
   744  
   745  		instrs := make([]string, 0)
   746  		it := asm.NewInstructionIterator(code)
   747  		for it.Next() {
   748  			if it.Arg() != nil && 0 < len(it.Arg()) {
   749  				instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg()))
   750  			} else {
   751  				instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
   752  			}
   753  		}
   754  		ops := strings.Join(instrs, ", ")
   755  		fmt.Printf("### Case %d\n\n", id)
   756  		id++
   757  		fmt.Printf("%v\n\nBytecode: \n```\n0x%x\n```\nOperations: \n```\n%v\n```\n\n",
   758  			comment,
   759  			code, ops)
   760  		Execute(code, nil, &Config{
   761  			EVMConfig: evm.Config{
   762  				Debug:     true,
   763  				Tracer:    evm.NewMarkdownLogger(nil, os.Stdout),
   764  				ExtraEips: []int{2929},
   765  			},
   766  		})
   767  	}
   768  
   769  	{ // First eip testcase
   770  		code := []byte{
   771  			// Three checks against a precompile
   772  			byte(evm.PUSH1), 1, byte(evm.EXTCODEHASH), byte(evm.POP),
   773  			byte(evm.PUSH1), 2, byte(evm.EXTCODESIZE), byte(evm.POP),
   774  			byte(evm.PUSH1), 3, byte(evm.BALANCE), byte(evm.POP),
   775  			// Three checks against a non-precompile
   776  			byte(evm.PUSH1), 0xf1, byte(evm.EXTCODEHASH), byte(evm.POP),
   777  			byte(evm.PUSH1), 0xf2, byte(evm.EXTCODESIZE), byte(evm.POP),
   778  			byte(evm.PUSH1), 0xf3, byte(evm.BALANCE), byte(evm.POP),
   779  			// Same three checks (should be cheaper)
   780  			byte(evm.PUSH1), 0xf2, byte(evm.EXTCODEHASH), byte(evm.POP),
   781  			byte(evm.PUSH1), 0xf3, byte(evm.EXTCODESIZE), byte(evm.POP),
   782  			byte(evm.PUSH1), 0xf1, byte(evm.BALANCE), byte(evm.POP),
   783  			// Check the origin, and the 'this'
   784  			byte(evm.ORIGIN), byte(evm.BALANCE), byte(evm.POP),
   785  			byte(evm.ADDRESS), byte(evm.BALANCE), byte(evm.POP),
   786  
   787  			byte(evm.STOP),
   788  		}
   789  		prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+
   790  			"and later checks the same operations twice against some non-precompiles. "+
   791  			"Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code)
   792  	}
   793  
   794  	{ // EXTCODECOPY
   795  		code := []byte{
   796  			// extcodecopy( 0xff,0,0,0,0)
   797  			byte(evm.PUSH1), 0x00, byte(evm.PUSH1), 0x00, byte(evm.PUSH1), 0x00, //length, codeoffset, memoffset
   798  			byte(evm.PUSH1), 0xff, byte(evm.EXTCODECOPY),
   799  			// extcodecopy( 0xff,0,0,0,0)
   800  			byte(evm.PUSH1), 0x00, byte(evm.PUSH1), 0x00, byte(evm.PUSH1), 0x00, //length, codeoffset, memoffset
   801  			byte(evm.PUSH1), 0xff, byte(evm.EXTCODECOPY),
   802  			// extcodecopy( this,0,0,0,0)
   803  			byte(evm.PUSH1), 0x00, byte(evm.PUSH1), 0x00, byte(evm.PUSH1), 0x00, //length, codeoffset, memoffset
   804  			byte(evm.ADDRESS), byte(evm.EXTCODECOPY),
   805  
   806  			byte(evm.STOP),
   807  		}
   808  		prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+
   809  			"and then does `extcodecopy( this,0,0,0,0)`.", code)
   810  	}
   811  
   812  	{ // SLOAD + SSTORE
   813  		code := []byte{
   814  
   815  			// Add slot `0x1` to access list
   816  			byte(evm.PUSH1), 0x01, byte(evm.SLOAD), byte(evm.POP), // SLOAD( 0x1) (add to access list)
   817  			// Write to `0x1` which is already in access list
   818  			byte(evm.PUSH1), 0x11, byte(evm.PUSH1), 0x01, byte(evm.SSTORE), // SSTORE( loc: 0x01, val: 0x11)
   819  			// Write to `0x2` which is not in access list
   820  			byte(evm.PUSH1), 0x11, byte(evm.PUSH1), 0x02, byte(evm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
   821  			// Write again to `0x2`
   822  			byte(evm.PUSH1), 0x11, byte(evm.PUSH1), 0x02, byte(evm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
   823  			// Read slot in access list (0x2)
   824  			byte(evm.PUSH1), 0x02, byte(evm.SLOAD), // SLOAD( 0x2)
   825  			// Read slot in access list (0x1)
   826  			byte(evm.PUSH1), 0x01, byte(evm.SLOAD), // SLOAD( 0x1)
   827  		}
   828  		prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+
   829  			"`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code)
   830  	}
   831  	{ // Call variants
   832  		code := []byte{
   833  			// identity precompile
   834  			byte(evm.PUSH1), 0x0, byte(evm.DUP1), byte(evm.DUP1), byte(evm.DUP1), byte(evm.DUP1),
   835  			byte(evm.PUSH1), 0x04, byte(evm.PUSH1), 0x0, byte(evm.CALL), byte(evm.POP),
   836  
   837  			// random account - call 1
   838  			byte(evm.PUSH1), 0x0, byte(evm.DUP1), byte(evm.DUP1), byte(evm.DUP1), byte(evm.DUP1),
   839  			byte(evm.PUSH1), 0xff, byte(evm.PUSH1), 0x0, byte(evm.CALL), byte(evm.POP),
   840  
   841  			// random account - call 2
   842  			byte(evm.PUSH1), 0x0, byte(evm.DUP1), byte(evm.DUP1), byte(evm.DUP1), byte(evm.DUP1),
   843  			byte(evm.PUSH1), 0xff, byte(evm.PUSH1), 0x0, byte(evm.STATICCALL), byte(evm.POP),
   844  		}
   845  		prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+
   846  			"account (cheap)", code)
   847  	}
   848  }
   849  
   850  func mkcfg() *Config {
   851  	cfg := new(Config)
   852  	setDefaults(cfg)
   853  
   854  	memback := leveldbstore.NewMemLevelDBStore()
   855  	overlay := overlaydb.NewOverlayDB(memback)
   856  
   857  	cache := storage.NewCacheDB(overlay)
   858  	cfg.State = storage.NewStateDB(cache, common.Hash{}, common.Hash{}, ong.OngBalanceHandle{})
   859  
   860  	cfg.GasLimit = 10000000
   861  	cfg.Origin = common.HexToAddress("0x123456")
   862  
   863  	return cfg
   864  }
   865  
   866  const (
   867  	// // SPDX-License-Identifier: GPL-3.0
   868  	// pragma solidity >0.6.0;
   869  	// contract Storage {
   870  	//  address payable private owner;
   871  	//  uint256 number;
   872  	//  constructor() payable {
   873  	//   owner = payable(msg.sender);
   874  	//  }
   875  	//  function store(uint256 num) public {
   876  	//   number = num;
   877  	//  }
   878  	//  function retrieve() public view returns (uint256){
   879  	//   return number;
   880  	//  }
   881  
   882  	//  function close() public {
   883  	//   selfdestruct(owner);
   884  	//  }
   885  	// }
   886  	StorageBin = "0x6080604052336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610113806100536000396000f3fe6080604052348015600f57600080fd5b5060043610603c5760003560e01c80632e64cec114604157806343d726d614605d5780636057361d146065575b600080fd5b60476090565b6040518082815260200191505060405180910390f35b6063609a565b005b608e60048036036020811015607957600080fd5b810190808035906020019092919050505060d3565b005b6000600154905090565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b806001819055505056fea2646970667358221220d0c72c744e1607d4f5949be99171995482c4e8eda2cd79d0179b06b0795d6e1564736f6c63430007060033"
   887  	StorageABI = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"close\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"retrieve\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"store\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
   888  
   889  	// this is a *real* contract bin compiled with solc
   890  	// callee
   891  	// // SPDX-License-Identifier: GPL-3.0
   892  	// pragma solidity >0.6.0;
   893  	// contract Callee {
   894  	//     address payable private owner;
   895  	//     uint256 number;
   896  	//     constructor() payable {
   897  	//         owner = payable(msg.sender);
   898  	//     }
   899  	//     function store(uint256 num) public {
   900  	//         number = num;
   901  	//     }
   902  
   903  	//     function storedtor (uint256 num) public {
   904  	//         number = num;
   905  	//         selfdestruct(owner);
   906  	//     }
   907  	//     function retrieve() public view returns (uint256){
   908  	//         return number;
   909  	//     }
   910  
   911  	//     function close() public {
   912  	//         selfdestruct(owner);
   913  	//     }
   914  	// }
   915  
   916  	// CalleeABI is the input ABI used to generate the binding from.
   917  	CalleeABI = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"close\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"retrieve\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"store\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"num\",\"type\":\"uint256\"}],\"name\":\"storedtor\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
   918  
   919  	// CalleeBin is the compiled bytecode used for deploying new contracts.
   920  	CalleeBin = "0x6080604052336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610198806100536000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80632e64cec11461005157806343d726d61461006f5780636057361d146100795780638ef9db3d146100a7575b600080fd5b6100596100d5565b6040518082815260200191505060405180910390f35b6100776100df565b005b6100a56004803603602081101561008f57600080fd5b8101908080359060200190929190505050610118565b005b6100d3600480360360208110156100bd57600080fd5b8101908080359060200190929190505050610122565b005b6000600154905090565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b8060018190555050565b8060018190555060008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16fffea2646970667358221220ef7c81ae86fe3b0f53373d74ddee4e9e4333fb42e2566074b7a4357bac25cd8d64736f6c63430007060033"
   921  
   922  	// caller
   923  	// SPDX-License-Identifier: GPL-3.0
   924  	// pragma solidity >0.6.0;
   925  
   926  	// contract Callee {
   927  	//     function store(uint256 num) public{}
   928  	//     function retrieve() public view returns (uint256){}
   929  
   930  	//     function storedtor (uint256 num) public  {}
   931  	// }
   932  
   933  	// contract Caller  {
   934  
   935  	//     Callee st;
   936  
   937  	//     constructor(address _t) payable {
   938  	//         st = Callee(_t);
   939  	//     }
   940  
   941  	//     function getNum() public view returns (uint256 result) {
   942  	//         return st.retrieve();
   943  	//     }
   944  
   945  	//     function setA(uint256 _val) public payable returns (uint256 result) {
   946  	//         st.storedtor(_val);
   947  	//         return _val;
   948  	//     }
   949  
   950  	// }
   951  
   952  	// CallerABI is the input ABI used to generate the binding from.
   953  	CallerABI = "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_t\",\"type\":\"address\"}],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"getNum\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"result\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_val\",\"type\":\"uint256\"}],\"name\":\"setA\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"result\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"}]"
   954  
   955  	// CallerBin is the compiled bytecode used for deploying new contracts.
   956  	CallerBin = "0x60806040526040516102973803806102978339818101604052602081101561002657600080fd5b8101908080519060200190929190505050806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050610210806100876000396000f3fe6080604052600436106100295760003560e01c806367e0badb1461002e578063ee919d5014610059575b600080fd5b34801561003a57600080fd5b5061004361009b565b6040518082815260200191505060405180910390f35b6100856004803603602081101561006f57600080fd5b8101908080359060200190929190505050610144565b6040518082815260200191505060405180910390f35b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16632e64cec16040518163ffffffff1660e01b815260040160206040518083038186803b15801561010457600080fd5b505afa158015610118573d6000803e3d6000fd5b505050506040513d602081101561012e57600080fd5b8101908080519060200190929190505050905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638ef9db3d836040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b1580156101ba57600080fd5b505af11580156101ce573d6000803e3d6000fd5b5050505081905091905056fea26469706673582212204539e1a8dfe53fc5ae35507ba94bcfaa5c20605fe237c6af0dd1137b1ecbbea564736f6c63430007060033"
   957  )
   958  
   959  func TestCreate(t *testing.T) {
   960  	create(t, false)
   961  }
   962  
   963  func TestCreate2(t *testing.T) {
   964  	create(t, true)
   965  }
   966  
   967  func create(t *testing.T, is2 bool) {
   968  	a := require.New(t)
   969  
   970  	cfg := mkcfg()
   971  
   972  	// 1. create
   973  	// 2. set
   974  	// 3. get
   975  	// 4. selfdestruction
   976  	// 5. get again
   977  	var contract *Contract
   978  	// create with value
   979  	cfg.State.AddBalance(cfg.Origin, big.NewInt(1e18))
   980  	cfg.Value = big.NewInt(1e1)
   981  	if is2 {
   982  		contract = Create2Contract(cfg, StorageABI, StorageBin, 0xffff)
   983  	} else {
   984  		contract = CreateContract(cfg, StorageABI, StorageBin)
   985  	}
   986  
   987  	contract.AutoCommit = true
   988  	cfg.Value = big.NewInt(0)
   989  	_, _, err := contract.Call("store", big.NewInt(1024))
   990  	a.Nil(err, "fail")
   991  
   992  	ret, _, err := contract.Call("retrieve")
   993  	a.Nil(err, "fail to retrive")
   994  	a.Equal(big.NewInt(1024), (&big.Int{}).SetBytes(ret), "fail")
   995  
   996  	// before self destruction
   997  	a.Equal(contract.Balance(), big.NewInt(10), "fail")
   998  	a.Equal(contract.BalanceOf(cfg.Origin), big.NewInt(1e18-1e1), "fail")
   999  
  1000  	// self destruction
  1001  	contract.AutoCommit = false
  1002  	contract.Call("close")
  1003  	a.Equal(contract.Balance(), big.NewInt(0), "fail")
  1004  	a.Equal(contract.BalanceOf(cfg.Origin), big.NewInt(1e18), "fail")
  1005  
  1006  	a.True(cfg.State.Suicided[contract.Address])
  1007  	// get again
  1008  	contract.AutoCommit = true
  1009  	ret, _, err = contract.Call("retrieve")
  1010  	a.Nil(err, "fail")
  1011  	a.Equal(big.NewInt(1024), (&big.Int{}).SetBytes(ret), "fail")
  1012  
  1013  	a.False(cfg.State.Suicided[contract.Address])
  1014  	// after commit, storage should be cleaned
  1015  	ret, _, err = contract.Call("retrieve")
  1016  	a.Nil(err, "calling non exist contract will be taken as normal transfer")
  1017  	a.Nil(ret, "fail")
  1018  }
  1019  
  1020  func TestContractChainDelete(t *testing.T) {
  1021  	contractChaindelete(t, false)
  1022  }
  1023  
  1024  func TestContractChainDelete2(t *testing.T) {
  1025  	contractChaindelete(t, true)
  1026  }
  1027  
  1028  func contractChaindelete(t *testing.T, is2 bool) {
  1029  	a := require.New(t)
  1030  
  1031  	cfg := mkcfg()
  1032  
  1033  	var lee *Contract
  1034  	if is2 {
  1035  		lee = Create2Contract(cfg, CalleeABI, CalleeBin, 0xffff)
  1036  	} else {
  1037  		lee = CreateContract(cfg, CalleeABI, CalleeBin)
  1038  	}
  1039  	lee.AutoCommit = true
  1040  	cfg.Value = big.NewInt(0)
  1041  
  1042  	_, _, err := lee.Call("store", big.NewInt(1024))
  1043  	a.Nil(err, "fail to call store")
  1044  
  1045  	ret, _, err := lee.Call("retrieve")
  1046  	a.Nil(err, "fail to call retrieve")
  1047  	a.Equal(big.NewInt(1024), big.NewInt(0).SetBytes(ret), "fail")
  1048  
  1049  	var ler *Contract
  1050  	if is2 {
  1051  		ler = Create2Contract(cfg, CallerABI, CallerBin, 0xffff, lee.Address)
  1052  	} else {
  1053  		ler = CreateContract(cfg, CallerABI, CallerBin, lee.Address)
  1054  	}
  1055  	ler.AutoCommit = true
  1056  
  1057  	ret, _, err = ler.Call("getNum")
  1058  	a.Nil(err, "fail to get caller getNum")
  1059  	a.Equal(big.NewInt(0).SetBytes(ret), big.NewInt(1024), "fail to get callee store")
  1060  
  1061  	// caller set num and callee selfdestruct
  1062  	ler.AutoCommit = true
  1063  	cfg.Value = big.NewInt(0)
  1064  	ret, _, err = ler.Call("setA", big.NewInt(1023))
  1065  	a.Nil(err, "fail to call setA")
  1066  	a.Equal(big.NewInt(0).SetBytes(ret), big.NewInt(1023), "fail")
  1067  	a.False(cfg.State.Suicided[ler.Address], "fail")
  1068  }
  1069  
  1070  func TestCreateOnDeletedAddress(t *testing.T) {
  1071  	a := require.New(t)
  1072  	cfg := mkcfg()
  1073  	c := Create2Contract(cfg, StorageABI, StorageBin, 0xffff)
  1074  	a.NotNil(c, "fail")
  1075  
  1076  	_, _, err := c.Call("store", big.NewInt(0x1234))
  1077  	a.Nil(err, "fail")
  1078  
  1079  	c.AutoCommit = true
  1080  	_, _, err = c.Call("close")
  1081  	a.Nil(err, "fail")
  1082  
  1083  	ret, _, err := c.Call("retrieve")
  1084  	a.Nil(err, "fail")
  1085  	a.Nil(ret, "fail")
  1086  
  1087  	c2 := Create2Contract(cfg, StorageABI, StorageBin, 0xffff)
  1088  	a.NotNil(c2, "fail")
  1089  	a.Equal(c.Address, c2.Address, "create2 should get the same contract address with same salt")
  1090  	ret, _, err = c2.Call("retrieve")
  1091  	a.Nil(err, "fail")
  1092  	a.True((big.NewInt(0).SetBytes(ret).Cmp(big.NewInt(0)) == 0), "should not get previous value 0x1234")
  1093  }