github.com/theQRL/go-zond@v0.1.1/core/vm/instructions_test.go (about)

     1  // Copyright 2017 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 vm
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"math/big"
    24  	"os"
    25  	"strings"
    26  	"testing"
    27  
    28  	"github.com/theQRL/go-zond/common"
    29  	"github.com/theQRL/go-zond/common/math"
    30  	"github.com/theQRL/go-zond/core/rawdb"
    31  	"github.com/theQRL/go-zond/core/state"
    32  	"github.com/theQRL/go-zond/core/types"
    33  	"github.com/theQRL/go-zond/crypto"
    34  	"github.com/theQRL/go-zond/params"
    35  	"github.com/holiman/uint256"
    36  )
    37  
    38  type TwoOperandTestcase struct {
    39  	X        string
    40  	Y        string
    41  	Expected string
    42  }
    43  
    44  type twoOperandParams struct {
    45  	x string
    46  	y string
    47  }
    48  
    49  var alphabetSoup = "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
    50  var commonParams []*twoOperandParams
    51  var twoOpMethods map[string]executionFunc
    52  
    53  type contractRef struct {
    54  	addr common.Address
    55  }
    56  
    57  func (c contractRef) Address() common.Address {
    58  	return c.addr
    59  }
    60  
    61  func init() {
    62  	// Params is a list of common edgecases that should be used for some common tests
    63  	params := []string{
    64  		"0000000000000000000000000000000000000000000000000000000000000000", // 0
    65  		"0000000000000000000000000000000000000000000000000000000000000001", // +1
    66  		"0000000000000000000000000000000000000000000000000000000000000005", // +5
    67  		"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe", // + max -1
    68  		"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // + max
    69  		"8000000000000000000000000000000000000000000000000000000000000000", // - max
    70  		"8000000000000000000000000000000000000000000000000000000000000001", // - max+1
    71  		"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb", // - 5
    72  		"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // - 1
    73  	}
    74  	// Params are combined so each param is used on each 'side'
    75  	commonParams = make([]*twoOperandParams, len(params)*len(params))
    76  	for i, x := range params {
    77  		for j, y := range params {
    78  			commonParams[i*len(params)+j] = &twoOperandParams{x, y}
    79  		}
    80  	}
    81  	twoOpMethods = map[string]executionFunc{
    82  		"add":     opAdd,
    83  		"sub":     opSub,
    84  		"mul":     opMul,
    85  		"div":     opDiv,
    86  		"sdiv":    opSdiv,
    87  		"mod":     opMod,
    88  		"smod":    opSmod,
    89  		"exp":     opExp,
    90  		"signext": opSignExtend,
    91  		"lt":      opLt,
    92  		"gt":      opGt,
    93  		"slt":     opSlt,
    94  		"sgt":     opSgt,
    95  		"eq":      opEq,
    96  		"and":     opAnd,
    97  		"or":      opOr,
    98  		"xor":     opXor,
    99  		"byte":    opByte,
   100  		"shl":     opSHL,
   101  		"shr":     opSHR,
   102  		"sar":     opSAR,
   103  	}
   104  }
   105  
   106  func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFunc, name string) {
   107  	var (
   108  		env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   109  		stack          = newstack()
   110  		pc             = uint64(0)
   111  		evmInterpreter = env.interpreter
   112  	)
   113  
   114  	for i, test := range tests {
   115  		x := new(uint256.Int).SetBytes(common.Hex2Bytes(test.X))
   116  		y := new(uint256.Int).SetBytes(common.Hex2Bytes(test.Y))
   117  		expected := new(uint256.Int).SetBytes(common.Hex2Bytes(test.Expected))
   118  		stack.push(x)
   119  		stack.push(y)
   120  		opFn(&pc, evmInterpreter, &ScopeContext{nil, stack, nil})
   121  		if len(stack.data) != 1 {
   122  			t.Errorf("Expected one item on stack after %v, got %d: ", name, len(stack.data))
   123  		}
   124  		actual := stack.pop()
   125  
   126  		if actual.Cmp(expected) != 0 {
   127  			t.Errorf("Testcase %v %d, %v(%x, %x): expected  %x, got %x", name, i, name, x, y, expected, actual)
   128  		}
   129  	}
   130  }
   131  
   132  func TestByteOp(t *testing.T) {
   133  	tests := []TwoOperandTestcase{
   134  		{"ABCDEF0908070605040302010000000000000000000000000000000000000000", "00", "AB"},
   135  		{"ABCDEF0908070605040302010000000000000000000000000000000000000000", "01", "CD"},
   136  		{"00CDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff", "00", "00"},
   137  		{"00CDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff", "01", "CD"},
   138  		{"0000000000000000000000000000000000000000000000000000000000102030", "1F", "30"},
   139  		{"0000000000000000000000000000000000000000000000000000000000102030", "1E", "20"},
   140  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "20", "00"},
   141  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "FFFFFFFFFFFFFFFF", "00"},
   142  	}
   143  	testTwoOperandOp(t, tests, opByte, "byte")
   144  }
   145  
   146  func TestSHL(t *testing.T) {
   147  	// Testcases from https://github.com/ethereum/EIPs/blob/master/EIPS/eip-145.md#shl-shift-left
   148  	tests := []TwoOperandTestcase{
   149  		{"0000000000000000000000000000000000000000000000000000000000000001", "01", "0000000000000000000000000000000000000000000000000000000000000002"},
   150  		{"0000000000000000000000000000000000000000000000000000000000000001", "ff", "8000000000000000000000000000000000000000000000000000000000000000"},
   151  		{"0000000000000000000000000000000000000000000000000000000000000001", "0100", "0000000000000000000000000000000000000000000000000000000000000000"},
   152  		{"0000000000000000000000000000000000000000000000000000000000000001", "0101", "0000000000000000000000000000000000000000000000000000000000000000"},
   153  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "00", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   154  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "01", "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},
   155  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "ff", "8000000000000000000000000000000000000000000000000000000000000000"},
   156  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0100", "0000000000000000000000000000000000000000000000000000000000000000"},
   157  		{"0000000000000000000000000000000000000000000000000000000000000000", "01", "0000000000000000000000000000000000000000000000000000000000000000"},
   158  		{"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "01", "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"},
   159  	}
   160  	testTwoOperandOp(t, tests, opSHL, "shl")
   161  }
   162  
   163  func TestSHR(t *testing.T) {
   164  	// Testcases from https://github.com/ethereum/EIPs/blob/master/EIPS/eip-145.md#shr-logical-shift-right
   165  	tests := []TwoOperandTestcase{
   166  		{"0000000000000000000000000000000000000000000000000000000000000001", "00", "0000000000000000000000000000000000000000000000000000000000000001"},
   167  		{"0000000000000000000000000000000000000000000000000000000000000001", "01", "0000000000000000000000000000000000000000000000000000000000000000"},
   168  		{"8000000000000000000000000000000000000000000000000000000000000000", "01", "4000000000000000000000000000000000000000000000000000000000000000"},
   169  		{"8000000000000000000000000000000000000000000000000000000000000000", "ff", "0000000000000000000000000000000000000000000000000000000000000001"},
   170  		{"8000000000000000000000000000000000000000000000000000000000000000", "0100", "0000000000000000000000000000000000000000000000000000000000000000"},
   171  		{"8000000000000000000000000000000000000000000000000000000000000000", "0101", "0000000000000000000000000000000000000000000000000000000000000000"},
   172  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "00", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   173  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "01", "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   174  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "ff", "0000000000000000000000000000000000000000000000000000000000000001"},
   175  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0100", "0000000000000000000000000000000000000000000000000000000000000000"},
   176  		{"0000000000000000000000000000000000000000000000000000000000000000", "01", "0000000000000000000000000000000000000000000000000000000000000000"},
   177  	}
   178  	testTwoOperandOp(t, tests, opSHR, "shr")
   179  }
   180  
   181  func TestSAR(t *testing.T) {
   182  	// Testcases from https://github.com/ethereum/EIPs/blob/master/EIPS/eip-145.md#sar-arithmetic-shift-right
   183  	tests := []TwoOperandTestcase{
   184  		{"0000000000000000000000000000000000000000000000000000000000000001", "00", "0000000000000000000000000000000000000000000000000000000000000001"},
   185  		{"0000000000000000000000000000000000000000000000000000000000000001", "01", "0000000000000000000000000000000000000000000000000000000000000000"},
   186  		{"8000000000000000000000000000000000000000000000000000000000000000", "01", "c000000000000000000000000000000000000000000000000000000000000000"},
   187  		{"8000000000000000000000000000000000000000000000000000000000000000", "ff", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   188  		{"8000000000000000000000000000000000000000000000000000000000000000", "0100", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   189  		{"8000000000000000000000000000000000000000000000000000000000000000", "0101", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   190  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "00", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   191  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "01", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   192  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "ff", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   193  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0100", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
   194  		{"0000000000000000000000000000000000000000000000000000000000000000", "01", "0000000000000000000000000000000000000000000000000000000000000000"},
   195  		{"4000000000000000000000000000000000000000000000000000000000000000", "fe", "0000000000000000000000000000000000000000000000000000000000000001"},
   196  		{"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "f8", "000000000000000000000000000000000000000000000000000000000000007f"},
   197  		{"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "fe", "0000000000000000000000000000000000000000000000000000000000000001"},
   198  		{"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "ff", "0000000000000000000000000000000000000000000000000000000000000000"},
   199  		{"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0100", "0000000000000000000000000000000000000000000000000000000000000000"},
   200  	}
   201  
   202  	testTwoOperandOp(t, tests, opSAR, "sar")
   203  }
   204  
   205  func TestAddMod(t *testing.T) {
   206  	var (
   207  		env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   208  		stack          = newstack()
   209  		evmInterpreter = NewEVMInterpreter(env)
   210  		pc             = uint64(0)
   211  	)
   212  	tests := []struct {
   213  		x        string
   214  		y        string
   215  		z        string
   216  		expected string
   217  	}{
   218  		{"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
   219  			"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
   220  			"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
   221  			"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
   222  		},
   223  	}
   224  	// x + y = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd
   225  	// in 256 bit repr, fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd
   226  
   227  	for i, test := range tests {
   228  		x := new(uint256.Int).SetBytes(common.Hex2Bytes(test.x))
   229  		y := new(uint256.Int).SetBytes(common.Hex2Bytes(test.y))
   230  		z := new(uint256.Int).SetBytes(common.Hex2Bytes(test.z))
   231  		expected := new(uint256.Int).SetBytes(common.Hex2Bytes(test.expected))
   232  		stack.push(z)
   233  		stack.push(y)
   234  		stack.push(x)
   235  		opAddmod(&pc, evmInterpreter, &ScopeContext{nil, stack, nil})
   236  		actual := stack.pop()
   237  		if actual.Cmp(expected) != 0 {
   238  			t.Errorf("Testcase %d, expected  %x, got %x", i, expected, actual)
   239  		}
   240  	}
   241  }
   242  
   243  // utility function to fill the json-file with testcases
   244  // Enable this test to generate the 'testcases_xx.json' files
   245  func TestWriteExpectedValues(t *testing.T) {
   246  	t.Skip("Enable this test to create json test cases.")
   247  
   248  	// getResult is a convenience function to generate the expected values
   249  	getResult := func(args []*twoOperandParams, opFn executionFunc) []TwoOperandTestcase {
   250  		var (
   251  			env         = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   252  			stack       = newstack()
   253  			pc          = uint64(0)
   254  			interpreter = env.interpreter
   255  		)
   256  		result := make([]TwoOperandTestcase, len(args))
   257  		for i, param := range args {
   258  			x := new(uint256.Int).SetBytes(common.Hex2Bytes(param.x))
   259  			y := new(uint256.Int).SetBytes(common.Hex2Bytes(param.y))
   260  			stack.push(x)
   261  			stack.push(y)
   262  			opFn(&pc, interpreter, &ScopeContext{nil, stack, nil})
   263  			actual := stack.pop()
   264  			result[i] = TwoOperandTestcase{param.x, param.y, fmt.Sprintf("%064x", actual)}
   265  		}
   266  		return result
   267  	}
   268  
   269  	for name, method := range twoOpMethods {
   270  		data, err := json.Marshal(getResult(commonParams, method))
   271  		if err != nil {
   272  			t.Fatal(err)
   273  		}
   274  		_ = os.WriteFile(fmt.Sprintf("testdata/testcases_%v.json", name), data, 0644)
   275  		if err != nil {
   276  			t.Fatal(err)
   277  		}
   278  	}
   279  }
   280  
   281  // TestJsonTestcases runs through all the testcases defined as json-files
   282  func TestJsonTestcases(t *testing.T) {
   283  	for name := range twoOpMethods {
   284  		data, err := os.ReadFile(fmt.Sprintf("testdata/testcases_%v.json", name))
   285  		if err != nil {
   286  			t.Fatal("Failed to read file", err)
   287  		}
   288  		var testcases []TwoOperandTestcase
   289  		json.Unmarshal(data, &testcases)
   290  		testTwoOperandOp(t, testcases, twoOpMethods[name], name)
   291  	}
   292  }
   293  
   294  func opBenchmark(bench *testing.B, op executionFunc, args ...string) {
   295  	var (
   296  		env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   297  		stack          = newstack()
   298  		scope          = &ScopeContext{nil, stack, nil}
   299  		evmInterpreter = NewEVMInterpreter(env)
   300  	)
   301  
   302  	env.interpreter = evmInterpreter
   303  	// convert args
   304  	intArgs := make([]*uint256.Int, len(args))
   305  	for i, arg := range args {
   306  		intArgs[i] = new(uint256.Int).SetBytes(common.Hex2Bytes(arg))
   307  	}
   308  	pc := uint64(0)
   309  	bench.ResetTimer()
   310  	for i := 0; i < bench.N; i++ {
   311  		for _, arg := range intArgs {
   312  			stack.push(arg)
   313  		}
   314  		op(&pc, evmInterpreter, scope)
   315  		stack.pop()
   316  	}
   317  	bench.StopTimer()
   318  
   319  	for i, arg := range args {
   320  		want := new(uint256.Int).SetBytes(common.Hex2Bytes(arg))
   321  		if have := intArgs[i]; !want.Eq(have) {
   322  			bench.Fatalf("input #%d mutated, have %x want %x", i, have, want)
   323  		}
   324  	}
   325  }
   326  
   327  func BenchmarkOpAdd64(b *testing.B) {
   328  	x := "ffffffff"
   329  	y := "fd37f3e2bba2c4f"
   330  
   331  	opBenchmark(b, opAdd, x, y)
   332  }
   333  
   334  func BenchmarkOpAdd128(b *testing.B) {
   335  	x := "ffffffffffffffff"
   336  	y := "f5470b43c6549b016288e9a65629687"
   337  
   338  	opBenchmark(b, opAdd, x, y)
   339  }
   340  
   341  func BenchmarkOpAdd256(b *testing.B) {
   342  	x := "0802431afcbce1fc194c9eaa417b2fb67dc75a95db0bc7ec6b1c8af11df6a1da9"
   343  	y := "a1f5aac137876480252e5dcac62c354ec0d42b76b0642b6181ed099849ea1d57"
   344  
   345  	opBenchmark(b, opAdd, x, y)
   346  }
   347  
   348  func BenchmarkOpSub64(b *testing.B) {
   349  	x := "51022b6317003a9d"
   350  	y := "a20456c62e00753a"
   351  
   352  	opBenchmark(b, opSub, x, y)
   353  }
   354  
   355  func BenchmarkOpSub128(b *testing.B) {
   356  	x := "4dde30faaacdc14d00327aac314e915d"
   357  	y := "9bbc61f5559b829a0064f558629d22ba"
   358  
   359  	opBenchmark(b, opSub, x, y)
   360  }
   361  
   362  func BenchmarkOpSub256(b *testing.B) {
   363  	x := "4bfcd8bb2ac462735b48a17580690283980aa2d679f091c64364594df113ea37"
   364  	y := "97f9b1765588c4e6b69142eb00d20507301545acf3e1238c86c8b29be227d46e"
   365  
   366  	opBenchmark(b, opSub, x, y)
   367  }
   368  
   369  func BenchmarkOpMul(b *testing.B) {
   370  	x := alphabetSoup
   371  	y := alphabetSoup
   372  
   373  	opBenchmark(b, opMul, x, y)
   374  }
   375  
   376  func BenchmarkOpDiv256(b *testing.B) {
   377  	x := "ff3f9014f20db29ae04af2c2d265de17"
   378  	y := "fe7fb0d1f59dfe9492ffbf73683fd1e870eec79504c60144cc7f5fc2bad1e611"
   379  	opBenchmark(b, opDiv, x, y)
   380  }
   381  
   382  func BenchmarkOpDiv128(b *testing.B) {
   383  	x := "fdedc7f10142ff97"
   384  	y := "fbdfda0e2ce356173d1993d5f70a2b11"
   385  	opBenchmark(b, opDiv, x, y)
   386  }
   387  
   388  func BenchmarkOpDiv64(b *testing.B) {
   389  	x := "fcb34eb3"
   390  	y := "f97180878e839129"
   391  	opBenchmark(b, opDiv, x, y)
   392  }
   393  
   394  func BenchmarkOpSdiv(b *testing.B) {
   395  	x := "ff3f9014f20db29ae04af2c2d265de17"
   396  	y := "fe7fb0d1f59dfe9492ffbf73683fd1e870eec79504c60144cc7f5fc2bad1e611"
   397  
   398  	opBenchmark(b, opSdiv, x, y)
   399  }
   400  
   401  func BenchmarkOpMod(b *testing.B) {
   402  	x := alphabetSoup
   403  	y := alphabetSoup
   404  
   405  	opBenchmark(b, opMod, x, y)
   406  }
   407  
   408  func BenchmarkOpSmod(b *testing.B) {
   409  	x := alphabetSoup
   410  	y := alphabetSoup
   411  
   412  	opBenchmark(b, opSmod, x, y)
   413  }
   414  
   415  func BenchmarkOpExp(b *testing.B) {
   416  	x := alphabetSoup
   417  	y := alphabetSoup
   418  
   419  	opBenchmark(b, opExp, x, y)
   420  }
   421  
   422  func BenchmarkOpSignExtend(b *testing.B) {
   423  	x := alphabetSoup
   424  	y := alphabetSoup
   425  
   426  	opBenchmark(b, opSignExtend, x, y)
   427  }
   428  
   429  func BenchmarkOpLt(b *testing.B) {
   430  	x := alphabetSoup
   431  	y := alphabetSoup
   432  
   433  	opBenchmark(b, opLt, x, y)
   434  }
   435  
   436  func BenchmarkOpGt(b *testing.B) {
   437  	x := alphabetSoup
   438  	y := alphabetSoup
   439  
   440  	opBenchmark(b, opGt, x, y)
   441  }
   442  
   443  func BenchmarkOpSlt(b *testing.B) {
   444  	x := alphabetSoup
   445  	y := alphabetSoup
   446  
   447  	opBenchmark(b, opSlt, x, y)
   448  }
   449  
   450  func BenchmarkOpSgt(b *testing.B) {
   451  	x := alphabetSoup
   452  	y := alphabetSoup
   453  
   454  	opBenchmark(b, opSgt, x, y)
   455  }
   456  
   457  func BenchmarkOpEq(b *testing.B) {
   458  	x := alphabetSoup
   459  	y := alphabetSoup
   460  
   461  	opBenchmark(b, opEq, x, y)
   462  }
   463  func BenchmarkOpEq2(b *testing.B) {
   464  	x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff"
   465  	y := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201fffffffe"
   466  	opBenchmark(b, opEq, x, y)
   467  }
   468  func BenchmarkOpAnd(b *testing.B) {
   469  	x := alphabetSoup
   470  	y := alphabetSoup
   471  
   472  	opBenchmark(b, opAnd, x, y)
   473  }
   474  
   475  func BenchmarkOpOr(b *testing.B) {
   476  	x := alphabetSoup
   477  	y := alphabetSoup
   478  
   479  	opBenchmark(b, opOr, x, y)
   480  }
   481  
   482  func BenchmarkOpXor(b *testing.B) {
   483  	x := alphabetSoup
   484  	y := alphabetSoup
   485  
   486  	opBenchmark(b, opXor, x, y)
   487  }
   488  
   489  func BenchmarkOpByte(b *testing.B) {
   490  	x := alphabetSoup
   491  	y := alphabetSoup
   492  
   493  	opBenchmark(b, opByte, x, y)
   494  }
   495  
   496  func BenchmarkOpAddmod(b *testing.B) {
   497  	x := alphabetSoup
   498  	y := alphabetSoup
   499  	z := alphabetSoup
   500  
   501  	opBenchmark(b, opAddmod, x, y, z)
   502  }
   503  
   504  func BenchmarkOpMulmod(b *testing.B) {
   505  	x := alphabetSoup
   506  	y := alphabetSoup
   507  	z := alphabetSoup
   508  
   509  	opBenchmark(b, opMulmod, x, y, z)
   510  }
   511  
   512  func BenchmarkOpSHL(b *testing.B) {
   513  	x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff"
   514  	y := "ff"
   515  
   516  	opBenchmark(b, opSHL, x, y)
   517  }
   518  func BenchmarkOpSHR(b *testing.B) {
   519  	x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff"
   520  	y := "ff"
   521  
   522  	opBenchmark(b, opSHR, x, y)
   523  }
   524  func BenchmarkOpSAR(b *testing.B) {
   525  	x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff"
   526  	y := "ff"
   527  
   528  	opBenchmark(b, opSAR, x, y)
   529  }
   530  func BenchmarkOpIsZero(b *testing.B) {
   531  	x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff"
   532  	opBenchmark(b, opIszero, x)
   533  }
   534  
   535  func TestOpMstore(t *testing.T) {
   536  	var (
   537  		env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   538  		stack          = newstack()
   539  		mem            = NewMemory()
   540  		evmInterpreter = NewEVMInterpreter(env)
   541  	)
   542  
   543  	env.interpreter = evmInterpreter
   544  	mem.Resize(64)
   545  	pc := uint64(0)
   546  	v := "abcdef00000000000000abba000000000deaf000000c0de00100000000133700"
   547  	stack.push(new(uint256.Int).SetBytes(common.Hex2Bytes(v)))
   548  	stack.push(new(uint256.Int))
   549  	opMstore(&pc, evmInterpreter, &ScopeContext{mem, stack, nil})
   550  	if got := common.Bytes2Hex(mem.GetCopy(0, 32)); got != v {
   551  		t.Fatalf("Mstore fail, got %v, expected %v", got, v)
   552  	}
   553  	stack.push(new(uint256.Int).SetUint64(0x1))
   554  	stack.push(new(uint256.Int))
   555  	opMstore(&pc, evmInterpreter, &ScopeContext{mem, stack, nil})
   556  	if common.Bytes2Hex(mem.GetCopy(0, 32)) != "0000000000000000000000000000000000000000000000000000000000000001" {
   557  		t.Fatalf("Mstore failed to overwrite previous value")
   558  	}
   559  }
   560  
   561  func BenchmarkOpMstore(bench *testing.B) {
   562  	var (
   563  		env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   564  		stack          = newstack()
   565  		mem            = NewMemory()
   566  		evmInterpreter = NewEVMInterpreter(env)
   567  	)
   568  
   569  	env.interpreter = evmInterpreter
   570  	mem.Resize(64)
   571  	pc := uint64(0)
   572  	memStart := new(uint256.Int)
   573  	value := new(uint256.Int).SetUint64(0x1337)
   574  
   575  	bench.ResetTimer()
   576  	for i := 0; i < bench.N; i++ {
   577  		stack.push(value)
   578  		stack.push(memStart)
   579  		opMstore(&pc, evmInterpreter, &ScopeContext{mem, stack, nil})
   580  	}
   581  }
   582  
   583  func TestOpTstore(t *testing.T) {
   584  	var (
   585  		statedb, _     = state.New(types.EmptyRootHash, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   586  		env            = NewEVM(BlockContext{}, TxContext{}, statedb, params.TestChainConfig, Config{})
   587  		stack          = newstack()
   588  		mem            = NewMemory()
   589  		evmInterpreter = NewEVMInterpreter(env)
   590  		caller         = common.Address{}
   591  		to             = common.Address{1}
   592  		contractRef    = contractRef{caller}
   593  		contract       = NewContract(contractRef, AccountRef(to), new(big.Int), 0)
   594  		scopeContext   = ScopeContext{mem, stack, contract}
   595  		value          = common.Hex2Bytes("abcdef00000000000000abba000000000deaf000000c0de00100000000133700")
   596  	)
   597  
   598  	// Add a stateObject for the caller and the contract being called
   599  	statedb.CreateAccount(caller)
   600  	statedb.CreateAccount(to)
   601  
   602  	env.interpreter = evmInterpreter
   603  	pc := uint64(0)
   604  	// push the value to the stack
   605  	stack.push(new(uint256.Int).SetBytes(value))
   606  	// push the location to the stack
   607  	stack.push(new(uint256.Int))
   608  	opTstore(&pc, evmInterpreter, &scopeContext)
   609  	// there should be no elements on the stack after TSTORE
   610  	if stack.len() != 0 {
   611  		t.Fatal("stack wrong size")
   612  	}
   613  	// push the location to the stack
   614  	stack.push(new(uint256.Int))
   615  	opTload(&pc, evmInterpreter, &scopeContext)
   616  	// there should be one element on the stack after TLOAD
   617  	if stack.len() != 1 {
   618  		t.Fatal("stack wrong size")
   619  	}
   620  	val := stack.peek()
   621  	if !bytes.Equal(val.Bytes(), value) {
   622  		t.Fatal("incorrect element read from transient storage")
   623  	}
   624  }
   625  
   626  func BenchmarkOpKeccak256(bench *testing.B) {
   627  	var (
   628  		env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   629  		stack          = newstack()
   630  		mem            = NewMemory()
   631  		evmInterpreter = NewEVMInterpreter(env)
   632  	)
   633  	env.interpreter = evmInterpreter
   634  	mem.Resize(32)
   635  	pc := uint64(0)
   636  	start := new(uint256.Int)
   637  
   638  	bench.ResetTimer()
   639  	for i := 0; i < bench.N; i++ {
   640  		stack.push(uint256.NewInt(32))
   641  		stack.push(start)
   642  		opKeccak256(&pc, evmInterpreter, &ScopeContext{mem, stack, nil})
   643  	}
   644  }
   645  
   646  func TestCreate2Addreses(t *testing.T) {
   647  	type testcase struct {
   648  		origin   string
   649  		salt     string
   650  		code     string
   651  		expected string
   652  	}
   653  
   654  	for i, tt := range []testcase{
   655  		{
   656  			origin:   "0x0000000000000000000000000000000000000000",
   657  			salt:     "0x0000000000000000000000000000000000000000",
   658  			code:     "0x00",
   659  			expected: "0x4d1a2e2bb4f88f0250f26ffff098b0b30b26bf38",
   660  		},
   661  		{
   662  			origin:   "0xdeadbeef00000000000000000000000000000000",
   663  			salt:     "0x0000000000000000000000000000000000000000",
   664  			code:     "0x00",
   665  			expected: "0xB928f69Bb1D91Cd65274e3c79d8986362984fDA3",
   666  		},
   667  		{
   668  			origin:   "0xdeadbeef00000000000000000000000000000000",
   669  			salt:     "0xfeed000000000000000000000000000000000000",
   670  			code:     "0x00",
   671  			expected: "0xD04116cDd17beBE565EB2422F2497E06cC1C9833",
   672  		},
   673  		{
   674  			origin:   "0x0000000000000000000000000000000000000000",
   675  			salt:     "0x0000000000000000000000000000000000000000",
   676  			code:     "0xdeadbeef",
   677  			expected: "0x70f2b2914A2a4b783FaEFb75f459A580616Fcb5e",
   678  		},
   679  		{
   680  			origin:   "0x00000000000000000000000000000000deadbeef",
   681  			salt:     "0xcafebabe",
   682  			code:     "0xdeadbeef",
   683  			expected: "0x60f3f640a8508fC6a86d45DF051962668E1e8AC7",
   684  		},
   685  		{
   686  			origin:   "0x00000000000000000000000000000000deadbeef",
   687  			salt:     "0xcafebabe",
   688  			code:     "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
   689  			expected: "0x1d8bfDC5D46DC4f61D6b6115972536eBE6A8854C",
   690  		},
   691  		{
   692  			origin:   "0x0000000000000000000000000000000000000000",
   693  			salt:     "0x0000000000000000000000000000000000000000",
   694  			code:     "0x",
   695  			expected: "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0",
   696  		},
   697  	} {
   698  		origin := common.BytesToAddress(common.FromHex(tt.origin))
   699  		salt := common.BytesToHash(common.FromHex(tt.salt))
   700  		code := common.FromHex(tt.code)
   701  		codeHash := crypto.Keccak256(code)
   702  		address := crypto.CreateAddress2(origin, salt, codeHash)
   703  		/*
   704  			stack          := newstack()
   705  			// salt, but we don't need that for this test
   706  			stack.push(big.NewInt(int64(len(code)))) //size
   707  			stack.push(big.NewInt(0)) // memstart
   708  			stack.push(big.NewInt(0)) // value
   709  			gas, _ := gasCreate2(params.GasTable{}, nil, nil, stack, nil, 0)
   710  			fmt.Printf("Example %d\n* address `0x%x`\n* salt `0x%x`\n* init_code `0x%x`\n* gas (assuming no mem expansion): `%v`\n* result: `%s`\n\n", i,origin, salt, code, gas, address.String())
   711  		*/
   712  		expected := common.BytesToAddress(common.FromHex(tt.expected))
   713  		if !bytes.Equal(expected.Bytes(), address.Bytes()) {
   714  			t.Errorf("test %d: expected %s, got %s", i, expected.String(), address.String())
   715  		}
   716  	}
   717  }
   718  
   719  func TestRandom(t *testing.T) {
   720  	type testcase struct {
   721  		name   string
   722  		random common.Hash
   723  	}
   724  
   725  	for _, tt := range []testcase{
   726  		{name: "empty hash", random: common.Hash{}},
   727  		{name: "1", random: common.Hash{0}},
   728  		{name: "emptyCodeHash", random: types.EmptyCodeHash},
   729  		{name: "hash(0x010203)", random: crypto.Keccak256Hash([]byte{0x01, 0x02, 0x03})},
   730  	} {
   731  		var (
   732  			env            = NewEVM(BlockContext{Random: &tt.random}, TxContext{}, nil, params.TestChainConfig, Config{})
   733  			stack          = newstack()
   734  			pc             = uint64(0)
   735  			evmInterpreter = env.interpreter
   736  		)
   737  		opRandom(&pc, evmInterpreter, &ScopeContext{nil, stack, nil})
   738  		if len(stack.data) != 1 {
   739  			t.Errorf("Expected one item on stack after %v, got %d: ", tt.name, len(stack.data))
   740  		}
   741  		actual := stack.pop()
   742  		expected, overflow := uint256.FromBig(new(big.Int).SetBytes(tt.random.Bytes()))
   743  		if overflow {
   744  			t.Errorf("Testcase %v: invalid overflow", tt.name)
   745  		}
   746  		if actual.Cmp(expected) != 0 {
   747  			t.Errorf("Testcase %v: expected  %x, got %x", tt.name, expected, actual)
   748  		}
   749  	}
   750  }
   751  
   752  func TestBlobHash(t *testing.T) {
   753  	type testcase struct {
   754  		name   string
   755  		idx    uint64
   756  		expect common.Hash
   757  		hashes []common.Hash
   758  	}
   759  	var (
   760  		zero  = common.Hash{0}
   761  		one   = common.Hash{1}
   762  		two   = common.Hash{2}
   763  		three = common.Hash{3}
   764  	)
   765  	for _, tt := range []testcase{
   766  		{name: "[{1}]", idx: 0, expect: one, hashes: []common.Hash{one}},
   767  		{name: "[1,{2},3]", idx: 2, expect: three, hashes: []common.Hash{one, two, three}},
   768  		{name: "out-of-bounds (empty)", idx: 10, expect: zero, hashes: []common.Hash{}},
   769  		{name: "out-of-bounds", idx: 25, expect: zero, hashes: []common.Hash{one, two, three}},
   770  		{name: "out-of-bounds (nil)", idx: 25, expect: zero, hashes: nil},
   771  	} {
   772  		var (
   773  			env            = NewEVM(BlockContext{}, TxContext{BlobHashes: tt.hashes}, nil, params.TestChainConfig, Config{})
   774  			stack          = newstack()
   775  			pc             = uint64(0)
   776  			evmInterpreter = env.interpreter
   777  		)
   778  		stack.push(uint256.NewInt(tt.idx))
   779  		opBlobHash(&pc, evmInterpreter, &ScopeContext{nil, stack, nil})
   780  		if len(stack.data) != 1 {
   781  			t.Errorf("Expected one item on stack after %v, got %d: ", tt.name, len(stack.data))
   782  		}
   783  		actual := stack.pop()
   784  		expected, overflow := uint256.FromBig(new(big.Int).SetBytes(tt.expect.Bytes()))
   785  		if overflow {
   786  			t.Errorf("Testcase %v: invalid overflow", tt.name)
   787  		}
   788  		if actual.Cmp(expected) != 0 {
   789  			t.Errorf("Testcase %v: expected  %x, got %x", tt.name, expected, actual)
   790  		}
   791  	}
   792  }
   793  
   794  func TestOpMCopy(t *testing.T) {
   795  	// Test cases from https://eips.ethereum.org/EIPS/eip-5656#test-cases
   796  	for i, tc := range []struct {
   797  		dst, src, len string
   798  		pre           string
   799  		want          string
   800  		wantGas       uint64
   801  	}{
   802  		{ // MCOPY 0 32 32 - copy 32 bytes from offset 32 to offset 0.
   803  			dst: "0x0", src: "0x20", len: "0x20",
   804  			pre:     "0000000000000000000000000000000000000000000000000000000000000000 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
   805  			want:    "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
   806  			wantGas: 6,
   807  		},
   808  
   809  		{ // MCOPY 0 0 32 - copy 32 bytes from offset 0 to offset 0.
   810  			dst: "0x0", src: "0x0", len: "0x20",
   811  			pre:     "0101010101010101010101010101010101010101010101010101010101010101",
   812  			want:    "0101010101010101010101010101010101010101010101010101010101010101",
   813  			wantGas: 6,
   814  		},
   815  		{ // MCOPY 0 1 8 - copy 8 bytes from offset 1 to offset 0 (overlapping).
   816  			dst: "0x0", src: "0x1", len: "0x8",
   817  			pre:     "000102030405060708 000000000000000000000000000000000000000000000000",
   818  			want:    "010203040506070808 000000000000000000000000000000000000000000000000",
   819  			wantGas: 6,
   820  		},
   821  		{ // MCOPY 1 0 8 - copy 8 bytes from offset 0 to offset 1 (overlapping).
   822  			dst: "0x1", src: "0x0", len: "0x8",
   823  			pre:     "000102030405060708 000000000000000000000000000000000000000000000000",
   824  			want:    "000001020304050607 000000000000000000000000000000000000000000000000",
   825  			wantGas: 6,
   826  		},
   827  		// Tests below are not in the EIP, but maybe should be added
   828  		{ // MCOPY 0xFFFFFFFFFFFF 0xFFFFFFFFFFFF 0 - copy zero bytes from out-of-bounds index(overlapping).
   829  			dst: "0xFFFFFFFFFFFF", src: "0xFFFFFFFFFFFF", len: "0x0",
   830  			pre:     "11",
   831  			want:    "11",
   832  			wantGas: 3,
   833  		},
   834  		{ // MCOPY 0xFFFFFFFFFFFF 0 0 - copy zero bytes from start of mem to out-of-bounds.
   835  			dst: "0xFFFFFFFFFFFF", src: "0x0", len: "0x0",
   836  			pre:     "11",
   837  			want:    "11",
   838  			wantGas: 3,
   839  		},
   840  		{ // MCOPY 0 0xFFFFFFFFFFFF 0 - copy zero bytes from out-of-bounds to start of mem
   841  			dst: "0x0", src: "0xFFFFFFFFFFFF", len: "0x0",
   842  			pre:     "11",
   843  			want:    "11",
   844  			wantGas: 3,
   845  		},
   846  		{ // MCOPY - copy 1 from space outside of uint64  space
   847  			dst: "0x0", src: "0x10000000000000000", len: "0x1",
   848  			pre: "0",
   849  		},
   850  		{ // MCOPY - copy 1 from 0 to space outside of uint64
   851  			dst: "0x10000000000000000", src: "0x0", len: "0x1",
   852  			pre: "0",
   853  		},
   854  		{ // MCOPY - copy nothing from 0 to space outside of uint64
   855  			dst: "0x10000000000000000", src: "0x0", len: "0x0",
   856  			pre:     "",
   857  			want:    "",
   858  			wantGas: 3,
   859  		},
   860  		{ // MCOPY - copy 1 from 0x20 to 0x10, with no prior allocated mem
   861  			dst: "0x10", src: "0x20", len: "0x1",
   862  			pre: "",
   863  			// 64 bytes
   864  			want:    "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
   865  			wantGas: 12,
   866  		},
   867  		{ // MCOPY - copy 1 from 0x19 to 0x10, with no prior allocated mem
   868  			dst: "0x10", src: "0x19", len: "0x1",
   869  			pre: "",
   870  			// 32 bytes
   871  			want:    "0x0000000000000000000000000000000000000000000000000000000000000000",
   872  			wantGas: 9,
   873  		},
   874  	} {
   875  		var (
   876  			env            = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{})
   877  			stack          = newstack()
   878  			pc             = uint64(0)
   879  			evmInterpreter = env.interpreter
   880  		)
   881  		data := common.FromHex(strings.ReplaceAll(tc.pre, " ", ""))
   882  		// Set pre
   883  		mem := NewMemory()
   884  		mem.Resize(uint64(len(data)))
   885  		mem.Set(0, uint64(len(data)), data)
   886  		// Push stack args
   887  		len, _ := uint256.FromHex(tc.len)
   888  		src, _ := uint256.FromHex(tc.src)
   889  		dst, _ := uint256.FromHex(tc.dst)
   890  
   891  		stack.push(len)
   892  		stack.push(src)
   893  		stack.push(dst)
   894  		wantErr := (tc.wantGas == 0)
   895  		// Calc mem expansion
   896  		var memorySize uint64
   897  		if memSize, overflow := memoryMcopy(stack); overflow {
   898  			if wantErr {
   899  				continue
   900  			}
   901  			t.Errorf("overflow")
   902  		} else {
   903  			var overflow bool
   904  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   905  				t.Error(ErrGasUintOverflow)
   906  			}
   907  		}
   908  		// and the dynamic cost
   909  		var haveGas uint64
   910  		if dynamicCost, err := gasMcopy(env, nil, stack, mem, memorySize); err != nil {
   911  			t.Error(err)
   912  		} else {
   913  			haveGas = GasFastestStep + dynamicCost
   914  		}
   915  		// Expand mem
   916  		if memorySize > 0 {
   917  			mem.Resize(memorySize)
   918  		}
   919  		// Do the copy
   920  		opMcopy(&pc, evmInterpreter, &ScopeContext{mem, stack, nil})
   921  		want := common.FromHex(strings.ReplaceAll(tc.want, " ", ""))
   922  		if have := mem.store; !bytes.Equal(want, have) {
   923  			t.Errorf("case %d: \nwant: %#x\nhave: %#x\n", i, want, have)
   924  		}
   925  		wantGas := tc.wantGas
   926  		if haveGas != wantGas {
   927  			t.Errorf("case %d: gas wrong, want %d have %d\n", i, wantGas, haveGas)
   928  		}
   929  	}
   930  }