github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/core/vm/runtime/runtime_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package runtime
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"os"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/zhiqiangxu/go-ethereum/accounts/abi"
    28  	"github.com/zhiqiangxu/go-ethereum/common"
    29  	"github.com/zhiqiangxu/go-ethereum/consensus"
    30  	"github.com/zhiqiangxu/go-ethereum/core"
    31  	"github.com/zhiqiangxu/go-ethereum/core/asm"
    32  	"github.com/zhiqiangxu/go-ethereum/core/rawdb"
    33  	"github.com/zhiqiangxu/go-ethereum/core/state"
    34  	"github.com/zhiqiangxu/go-ethereum/core/types"
    35  	"github.com/zhiqiangxu/go-ethereum/core/vm"
    36  	"github.com/zhiqiangxu/go-ethereum/params"
    37  )
    38  
    39  func TestDefaults(t *testing.T) {
    40  	cfg := new(Config)
    41  	setDefaults(cfg)
    42  
    43  	if cfg.Difficulty == nil {
    44  		t.Error("expected difficulty to be non nil")
    45  	}
    46  
    47  	if cfg.Time == nil {
    48  		t.Error("expected time to be non nil")
    49  	}
    50  	if cfg.GasLimit == 0 {
    51  		t.Error("didn't expect gaslimit to be zero")
    52  	}
    53  	if cfg.GasPrice == nil {
    54  		t.Error("expected time to be non nil")
    55  	}
    56  	if cfg.Value == nil {
    57  		t.Error("expected time to be non nil")
    58  	}
    59  	if cfg.GetHashFn == nil {
    60  		t.Error("expected time to be non nil")
    61  	}
    62  	if cfg.BlockNumber == nil {
    63  		t.Error("expected block number to be non nil")
    64  	}
    65  }
    66  
    67  func TestEVM(t *testing.T) {
    68  	defer func() {
    69  		if r := recover(); r != nil {
    70  			t.Fatalf("crashed with: %v", r)
    71  		}
    72  	}()
    73  
    74  	Execute([]byte{
    75  		byte(vm.DIFFICULTY),
    76  		byte(vm.TIMESTAMP),
    77  		byte(vm.GASLIMIT),
    78  		byte(vm.PUSH1),
    79  		byte(vm.ORIGIN),
    80  		byte(vm.BLOCKHASH),
    81  		byte(vm.COINBASE),
    82  	}, nil, nil)
    83  }
    84  
    85  func TestExecute(t *testing.T) {
    86  	ret, _, err := Execute([]byte{
    87  		byte(vm.PUSH1), 10,
    88  		byte(vm.PUSH1), 0,
    89  		byte(vm.MSTORE),
    90  		byte(vm.PUSH1), 32,
    91  		byte(vm.PUSH1), 0,
    92  		byte(vm.RETURN),
    93  	}, nil, nil)
    94  	if err != nil {
    95  		t.Fatal("didn't expect error", err)
    96  	}
    97  
    98  	num := new(big.Int).SetBytes(ret)
    99  	if num.Cmp(big.NewInt(10)) != 0 {
   100  		t.Error("Expected 10, got", num)
   101  	}
   102  }
   103  
   104  func TestCall(t *testing.T) {
   105  	state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   106  	address := common.HexToAddress("0x0a")
   107  	state.SetCode(address, []byte{
   108  		byte(vm.PUSH1), 10,
   109  		byte(vm.PUSH1), 0,
   110  		byte(vm.MSTORE),
   111  		byte(vm.PUSH1), 32,
   112  		byte(vm.PUSH1), 0,
   113  		byte(vm.RETURN),
   114  	})
   115  
   116  	ret, _, err := Call(address, nil, &Config{State: state})
   117  	if err != nil {
   118  		t.Fatal("didn't expect error", err)
   119  	}
   120  
   121  	num := new(big.Int).SetBytes(ret)
   122  	if num.Cmp(big.NewInt(10)) != 0 {
   123  		t.Error("Expected 10, got", num)
   124  	}
   125  }
   126  
   127  func BenchmarkCall(b *testing.B) {
   128  	var definition = `[{"constant":true,"inputs":[],"name":"seller","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"abort","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"refund","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"buyer","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"confirmReceived","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"state","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":false,"inputs":[],"name":"confirmPurchase","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[],"name":"Aborted","type":"event"},{"anonymous":false,"inputs":[],"name":"PurchaseConfirmed","type":"event"},{"anonymous":false,"inputs":[],"name":"ItemReceived","type":"event"},{"anonymous":false,"inputs":[],"name":"Refunded","type":"event"}]`
   129  
   130  	var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056")
   131  
   132  	abi, err := abi.JSON(strings.NewReader(definition))
   133  	if err != nil {
   134  		b.Fatal(err)
   135  	}
   136  
   137  	cpurchase, err := abi.Pack("confirmPurchase")
   138  	if err != nil {
   139  		b.Fatal(err)
   140  	}
   141  	creceived, err := abi.Pack("confirmReceived")
   142  	if err != nil {
   143  		b.Fatal(err)
   144  	}
   145  	refund, err := abi.Pack("refund")
   146  	if err != nil {
   147  		b.Fatal(err)
   148  	}
   149  
   150  	b.ResetTimer()
   151  	for i := 0; i < b.N; i++ {
   152  		for j := 0; j < 400; j++ {
   153  			Execute(code, cpurchase, nil)
   154  			Execute(code, creceived, nil)
   155  			Execute(code, refund, nil)
   156  		}
   157  	}
   158  }
   159  func benchmarkEVM_Create(bench *testing.B, code string) {
   160  	var (
   161  		statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   162  		sender     = common.BytesToAddress([]byte("sender"))
   163  		receiver   = common.BytesToAddress([]byte("receiver"))
   164  	)
   165  
   166  	statedb.CreateAccount(sender)
   167  	statedb.SetCode(receiver, common.FromHex(code))
   168  	runtimeConfig := Config{
   169  		Origin:      sender,
   170  		State:       statedb,
   171  		GasLimit:    10000000,
   172  		Difficulty:  big.NewInt(0x200000),
   173  		Time:        new(big.Int).SetUint64(0),
   174  		Coinbase:    common.Address{},
   175  		BlockNumber: new(big.Int).SetUint64(1),
   176  		ChainConfig: &params.ChainConfig{
   177  			ChainID:             big.NewInt(1),
   178  			HomesteadBlock:      new(big.Int),
   179  			ByzantiumBlock:      new(big.Int),
   180  			ConstantinopleBlock: new(big.Int),
   181  			DAOForkBlock:        new(big.Int),
   182  			DAOForkSupport:      false,
   183  			EIP150Block:         new(big.Int),
   184  			EIP155Block:         new(big.Int),
   185  			EIP158Block:         new(big.Int),
   186  		},
   187  		EVMConfig: vm.Config{},
   188  	}
   189  	// Warm up the intpools and stuff
   190  	bench.ResetTimer()
   191  	for i := 0; i < bench.N; i++ {
   192  		Call(receiver, []byte{}, &runtimeConfig)
   193  	}
   194  	bench.StopTimer()
   195  }
   196  
   197  func BenchmarkEVM_CREATE_500(bench *testing.B) {
   198  	// initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
   199  	benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
   200  }
   201  func BenchmarkEVM_CREATE2_500(bench *testing.B) {
   202  	// initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
   203  	benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
   204  }
   205  func BenchmarkEVM_CREATE_1200(bench *testing.B) {
   206  	// initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
   207  	benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
   208  }
   209  func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
   210  	// initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
   211  	benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
   212  }
   213  
   214  func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
   215  	header := types.Header{
   216  		Coinbase:   common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
   217  		Number:     big.NewInt(int64(n)),
   218  		ParentHash: parentHash,
   219  		Time:       1000,
   220  		Nonce:      types.BlockNonce{0x1},
   221  		Extra:      []byte{},
   222  		Difficulty: big.NewInt(0),
   223  		GasLimit:   100000,
   224  	}
   225  	return &header
   226  }
   227  
   228  type dummyChain struct {
   229  	counter int
   230  }
   231  
   232  // Engine retrieves the chain's consensus engine.
   233  func (d *dummyChain) Engine() consensus.Engine {
   234  	return nil
   235  }
   236  
   237  // GetHeader returns the hash corresponding to their hash.
   238  func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
   239  	d.counter++
   240  	parentHash := common.Hash{}
   241  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   242  	copy(parentHash[:], s)
   243  
   244  	//parentHash := common.Hash{byte(n - 1)}
   245  	//fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
   246  	return fakeHeader(n, parentHash)
   247  }
   248  
   249  // TestBlockhash tests the blockhash operation. It's a bit special, since it internally
   250  // requires access to a chain reader.
   251  func TestBlockhash(t *testing.T) {
   252  	// Current head
   253  	n := uint64(1000)
   254  	parentHash := common.Hash{}
   255  	s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
   256  	copy(parentHash[:], s)
   257  	header := fakeHeader(n, parentHash)
   258  
   259  	// This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
   260  	// then iteratively fetches all blockhashes back to n-260.
   261  	// It returns
   262  	// 1. the first (should be zero)
   263  	// 2. the second (should be the parent hash)
   264  	// 3. the last non-zero hash
   265  	// By making the chain reader return hashes which correlate to the number, we can
   266  	// verify that it obtained the right hashes where it should
   267  
   268  	/*
   269  
   270  		pragma solidity ^0.5.3;
   271  		contract Hasher{
   272  
   273  			function test() public view returns (bytes32, bytes32, bytes32){
   274  				uint256 x = block.number;
   275  				bytes32 first;
   276  				bytes32 last;
   277  				bytes32 zero;
   278  				zero = blockhash(x); // Should be zeroes
   279  				first = blockhash(x-1);
   280  				for(uint256 i = 2 ; i < 260; i++){
   281  					bytes32 hash = blockhash(x - i);
   282  					if (uint256(hash) != 0){
   283  						last = hash;
   284  					}
   285  				}
   286  				return (zero, first, last);
   287  			}
   288  		}
   289  
   290  	*/
   291  	// The contract above
   292  	data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
   293  	// The method call to 'test()'
   294  	input := common.Hex2Bytes("f8a8fd6d")
   295  	chain := &dummyChain{}
   296  	ret, _, err := Execute(data, input, &Config{
   297  		GetHashFn:   core.GetHashFn(header, chain),
   298  		BlockNumber: new(big.Int).Set(header.Number),
   299  	})
   300  	if err != nil {
   301  		t.Fatalf("expected no error, got %v", err)
   302  	}
   303  	if len(ret) != 96 {
   304  		t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
   305  	}
   306  
   307  	zero := new(big.Int).SetBytes(ret[0:32])
   308  	first := new(big.Int).SetBytes(ret[32:64])
   309  	last := new(big.Int).SetBytes(ret[64:96])
   310  	if zero.BitLen() != 0 {
   311  		t.Fatalf("expected zeroes, got %x", ret[0:32])
   312  	}
   313  	if first.Uint64() != 999 {
   314  		t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
   315  	}
   316  	if last.Uint64() != 744 {
   317  		t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
   318  	}
   319  	if exp, got := 255, chain.counter; exp != got {
   320  		t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
   321  	}
   322  }
   323  
   324  // BenchmarkSimpleLoop test a pretty simple loop which loops
   325  // 1M (1 048 575) times.
   326  // Takes about 200 ms
   327  func BenchmarkSimpleLoop(b *testing.B) {
   328  	// 0xfffff = 1048575 loops
   329  	code := []byte{
   330  		byte(vm.PUSH3), 0x0f, 0xff, 0xff,
   331  		byte(vm.JUMPDEST), //  [ count ]
   332  		byte(vm.PUSH1), 1, // [count, 1]
   333  		byte(vm.SWAP1),    // [1, count]
   334  		byte(vm.SUB),      // [ count -1 ]
   335  		byte(vm.DUP1),     //  [ count -1 , count-1]
   336  		byte(vm.PUSH1), 4, // [count-1, count -1, label]
   337  		byte(vm.JUMPI), // [ 0 ]
   338  		byte(vm.STOP),
   339  	}
   340  	//tracer := vm.NewJSONLogger(nil, os.Stdout)
   341  	//Execute(code, nil, &Config{
   342  	//	EVMConfig: vm.Config{
   343  	//		Debug:  true,
   344  	//		Tracer: tracer,
   345  	//	}})
   346  
   347  	for i := 0; i < b.N; i++ {
   348  		Execute(code, nil, nil)
   349  	}
   350  }
   351  
   352  type stepCounter struct {
   353  	inner *vm.JSONLogger
   354  	steps int
   355  }
   356  
   357  func (s *stepCounter) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   358  	return nil
   359  }
   360  
   361  func (s *stepCounter) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, contract *vm.Contract, depth int, err error) error {
   362  	s.steps++
   363  	// Enable this for more output
   364  	//s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err)
   365  	return nil
   366  }
   367  
   368  func (s *stepCounter) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, contract *vm.Contract, depth int, err error) error {
   369  	return nil
   370  }
   371  
   372  func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
   373  	return nil
   374  }
   375  
   376  func TestJumpSub1024Limit(t *testing.T) {
   377  	state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   378  	address := common.HexToAddress("0x0a")
   379  	// Code is
   380  	// 0 beginsub
   381  	// 1 push 0
   382  	// 3 jumpsub
   383  	//
   384  	// The code recursively calls itself. It should error when the returns-stack
   385  	// grows above 1023
   386  	state.SetCode(address, []byte{
   387  		byte(vm.PUSH1), 3,
   388  		byte(vm.JUMPSUB),
   389  		byte(vm.BEGINSUB),
   390  		byte(vm.PUSH1), 3,
   391  		byte(vm.JUMPSUB),
   392  	})
   393  	tracer := stepCounter{inner: vm.NewJSONLogger(nil, os.Stdout)}
   394  	// Enable 2315
   395  	_, _, err := Call(address, nil, &Config{State: state,
   396  		GasLimit:    20000,
   397  		ChainConfig: params.AllEthashProtocolChanges,
   398  		EVMConfig: vm.Config{
   399  			ExtraEips: []int{2315},
   400  			Debug:     true,
   401  			//Tracer:    vm.NewJSONLogger(nil, os.Stdout),
   402  			Tracer: &tracer,
   403  		}})
   404  	exp := "return stack limit reached"
   405  	if err.Error() != exp {
   406  		t.Fatalf("expected %v, got %v", exp, err)
   407  	}
   408  	if exp, got := 2048, tracer.steps; exp != got {
   409  		t.Fatalf("expected %d steps, got %d", exp, got)
   410  	}
   411  }
   412  
   413  func TestReturnSubShallow(t *testing.T) {
   414  	state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   415  	address := common.HexToAddress("0x0a")
   416  	// The code does returnsub without having anything on the returnstack.
   417  	// It should not panic, but just fail after one step
   418  	state.SetCode(address, []byte{
   419  		byte(vm.PUSH1), 5,
   420  		byte(vm.JUMPSUB),
   421  		byte(vm.RETURNSUB),
   422  		byte(vm.PC),
   423  		byte(vm.BEGINSUB),
   424  		byte(vm.RETURNSUB),
   425  		byte(vm.PC),
   426  	})
   427  	tracer := stepCounter{}
   428  
   429  	// Enable 2315
   430  	_, _, err := Call(address, nil, &Config{State: state,
   431  		GasLimit:    10000,
   432  		ChainConfig: params.AllEthashProtocolChanges,
   433  		EVMConfig: vm.Config{
   434  			ExtraEips: []int{2315},
   435  			Debug:     true,
   436  			Tracer:    &tracer,
   437  		}})
   438  
   439  	exp := "invalid retsub"
   440  	if err.Error() != exp {
   441  		t.Fatalf("expected %v, got %v", exp, err)
   442  	}
   443  	if exp, got := 4, tracer.steps; exp != got {
   444  		t.Fatalf("expected %d steps, got %d", exp, got)
   445  	}
   446  }
   447  
   448  // disabled -- only used for generating markdown
   449  func DisabledTestReturnCases(t *testing.T) {
   450  	cfg := &Config{
   451  		EVMConfig: vm.Config{
   452  			Debug:     true,
   453  			Tracer:    vm.NewMarkdownLogger(nil, os.Stdout),
   454  			ExtraEips: []int{2315},
   455  		},
   456  	}
   457  	// This should fail at first opcode
   458  	Execute([]byte{
   459  		byte(vm.RETURNSUB),
   460  		byte(vm.PC),
   461  		byte(vm.PC),
   462  	}, nil, cfg)
   463  
   464  	// Should also fail
   465  	Execute([]byte{
   466  		byte(vm.PUSH1), 5,
   467  		byte(vm.JUMPSUB),
   468  		byte(vm.RETURNSUB),
   469  		byte(vm.PC),
   470  		byte(vm.BEGINSUB),
   471  		byte(vm.RETURNSUB),
   472  		byte(vm.PC),
   473  	}, nil, cfg)
   474  
   475  	// This should complete
   476  	Execute([]byte{
   477  		byte(vm.PUSH1), 0x4,
   478  		byte(vm.JUMPSUB),
   479  		byte(vm.STOP),
   480  		byte(vm.BEGINSUB),
   481  		byte(vm.PUSH1), 0x9,
   482  		byte(vm.JUMPSUB),
   483  		byte(vm.RETURNSUB),
   484  		byte(vm.BEGINSUB),
   485  		byte(vm.RETURNSUB),
   486  	}, nil, cfg)
   487  }
   488  
   489  // DisabledTestEipExampleCases contains various testcases that are used for the
   490  // EIP examples
   491  // This test is disabled, as it's only used for generating markdown
   492  func DisabledTestEipExampleCases(t *testing.T) {
   493  	cfg := &Config{
   494  		EVMConfig: vm.Config{
   495  			Debug:     true,
   496  			Tracer:    vm.NewMarkdownLogger(nil, os.Stdout),
   497  			ExtraEips: []int{2315},
   498  		},
   499  	}
   500  	prettyPrint := func(comment string, code []byte) {
   501  		instrs := make([]string, 0)
   502  		it := asm.NewInstructionIterator(code)
   503  		for it.Next() {
   504  			if it.Arg() != nil && 0 < len(it.Arg()) {
   505  				instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg()))
   506  			} else {
   507  				instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
   508  			}
   509  		}
   510  		ops := strings.Join(instrs, ", ")
   511  
   512  		fmt.Printf("%v\nBytecode: `0x%x` (`%v`)\n",
   513  			comment,
   514  			code, ops)
   515  		Execute(code, nil, cfg)
   516  	}
   517  
   518  	{ // First eip testcase
   519  		code := []byte{
   520  			byte(vm.PUSH1), 4,
   521  			byte(vm.JUMPSUB),
   522  			byte(vm.STOP),
   523  			byte(vm.BEGINSUB),
   524  			byte(vm.RETURNSUB),
   525  		}
   526  		prettyPrint("This should jump into a subroutine, back out and stop.", code)
   527  	}
   528  
   529  	{
   530  		code := []byte{
   531  			byte(vm.PUSH9), 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8),
   532  			byte(vm.JUMPSUB),
   533  			byte(vm.STOP),
   534  			byte(vm.BEGINSUB),
   535  			byte(vm.PUSH1), 8 + 9,
   536  			byte(vm.JUMPSUB),
   537  			byte(vm.RETURNSUB),
   538  			byte(vm.BEGINSUB),
   539  			byte(vm.RETURNSUB),
   540  		}
   541  		prettyPrint("This should execute fine, going into one two depths of subroutines", code)
   542  	}
   543  	// TODO(@holiman) move this test into an actual test, which not only prints
   544  	// out the trace.
   545  	{
   546  		code := []byte{
   547  			byte(vm.PUSH9), 0x01, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8),
   548  			byte(vm.JUMPSUB),
   549  			byte(vm.STOP),
   550  			byte(vm.BEGINSUB),
   551  			byte(vm.PUSH1), 8 + 9,
   552  			byte(vm.JUMPSUB),
   553  			byte(vm.RETURNSUB),
   554  			byte(vm.BEGINSUB),
   555  			byte(vm.RETURNSUB),
   556  		}
   557  		prettyPrint("This should fail, since the given location is outside of the "+
   558  			"code-range. The code is the same as previous example, except that the "+
   559  			"pushed location is `0x01000000000000000c` instead of `0x0c`.", code)
   560  	}
   561  	{
   562  		// This should fail at first opcode
   563  		code := []byte{
   564  			byte(vm.RETURNSUB),
   565  			byte(vm.PC),
   566  			byte(vm.PC),
   567  		}
   568  		prettyPrint("This should fail at first opcode, due to shallow `return_stack`", code)
   569  
   570  	}
   571  	{
   572  		code := []byte{
   573  			byte(vm.PUSH1), 5, // Jump past the subroutine
   574  			byte(vm.JUMP),
   575  			byte(vm.BEGINSUB),
   576  			byte(vm.RETURNSUB),
   577  			byte(vm.JUMPDEST),
   578  			byte(vm.PUSH1), 3, // Now invoke the subroutine
   579  			byte(vm.JUMPSUB),
   580  		}
   581  		prettyPrint("In this example. the JUMPSUB is on the last byte of code. When the "+
   582  			"subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, "+
   583  			"and not exit with error", code)
   584  	}
   585  
   586  	{
   587  		code := []byte{
   588  			byte(vm.BEGINSUB),
   589  			byte(vm.RETURNSUB),
   590  			byte(vm.STOP),
   591  		}
   592  		prettyPrint("In this example, the code 'walks' into a subroutine, which is not "+
   593  			"allowed, and causes an error", code)
   594  	}
   595  }