github.com/ethereum/go-ethereum@v1.14.3/accounts/abi/abi_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 abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/hex"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"reflect"
    26  	"strings"
    27  	"testing"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/math"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  )
    33  
    34  const jsondata = `
    35  [
    36  	{ "type" : "function", "name" : ""},
    37  	{ "type" : "function", "name" : "balance", "stateMutability" : "view" },
    38  	{ "type" : "function", "name" : "send", "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
    39  	{ "type" : "function", "name" : "test", "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
    40  	{ "type" : "function", "name" : "string", "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
    41  	{ "type" : "function", "name" : "bool", "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
    42  	{ "type" : "function", "name" : "address", "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
    43  	{ "type" : "function", "name" : "uint64[2]", "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
    44  	{ "type" : "function", "name" : "uint64[]", "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
    45  	{ "type" : "function", "name" : "int8", "inputs" : [ { "name" : "inputs", "type" : "int8" } ] },
    46  	{ "type" : "function", "name" : "bytes32", "inputs" : [ { "name" : "inputs", "type" : "bytes32" } ] },
    47  	{ "type" : "function", "name" : "foo", "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
    48  	{ "type" : "function", "name" : "bar", "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
    49  	{ "type" : "function", "name" : "slice", "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
    50  	{ "type" : "function", "name" : "slice256", "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
    51  	{ "type" : "function", "name" : "sliceAddress", "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
    52  	{ "type" : "function", "name" : "sliceMultiAddress", "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] },
    53  	{ "type" : "function", "name" : "nestedArray", "inputs" : [ { "name" : "a", "type" : "uint256[2][2]" }, { "name" : "b", "type" : "address[]" } ] },
    54  	{ "type" : "function", "name" : "nestedArray2", "inputs" : [ { "name" : "a", "type" : "uint8[][2]" } ] },
    55  	{ "type" : "function", "name" : "nestedSlice", "inputs" : [ { "name" : "a", "type" : "uint8[][]" } ] },
    56  	{ "type" : "function", "name" : "receive", "inputs" : [ { "name" : "memo", "type" : "bytes" }], "outputs" : [], "payable" : true, "stateMutability" : "payable" },
    57  	{ "type" : "function", "name" : "fixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] },
    58  	{ "type" : "function", "name" : "fixedArrBytes", "stateMutability" : "view", "inputs" : [ { "name" : "bytes", "type" : "bytes" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] },
    59  	{ "type" : "function", "name" : "mixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type" : "uint256[2]" }, { "name" : "dynArr", "type" : "uint256[]" } ] },
    60  	{ "type" : "function", "name" : "doubleFixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type" : "uint256[2]" }, { "name" : "fixedArr2", "type" : "uint256[3]" } ] },
    61  	{ "type" : "function", "name" : "multipleMixedArrStr", "stateMutability" : "view", "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type" : "uint256[2]" }, { "name" : "dynArr", "type" : "uint256[]" }, { "name" : "fixedArr2", "type" : "uint256[3]" } ] },
    62  	{ "type" : "function", "name" : "overloadedNames", "stateMutability" : "view", "inputs": [ { "components": [ { "internalType": "uint256", "name": "_f",	"type": "uint256" }, { "internalType": "uint256", "name": "__f", "type": "uint256"}, { "internalType": "uint256", "name": "f", "type": "uint256"}],"internalType": "struct Overloader.F", "name": "f","type": "tuple"}]}
    63  ]`
    64  
    65  var (
    66  	Uint256, _    = NewType("uint256", "", nil)
    67  	Uint32, _     = NewType("uint32", "", nil)
    68  	Uint16, _     = NewType("uint16", "", nil)
    69  	String, _     = NewType("string", "", nil)
    70  	Bool, _       = NewType("bool", "", nil)
    71  	Bytes, _      = NewType("bytes", "", nil)
    72  	Bytes32, _    = NewType("bytes32", "", nil)
    73  	Address, _    = NewType("address", "", nil)
    74  	Uint64Arr, _  = NewType("uint64[]", "", nil)
    75  	AddressArr, _ = NewType("address[]", "", nil)
    76  	Int8, _       = NewType("int8", "", nil)
    77  	// Special types for testing
    78  	Uint32Arr2, _       = NewType("uint32[2]", "", nil)
    79  	Uint64Arr2, _       = NewType("uint64[2]", "", nil)
    80  	Uint256Arr, _       = NewType("uint256[]", "", nil)
    81  	Uint256Arr2, _      = NewType("uint256[2]", "", nil)
    82  	Uint256Arr3, _      = NewType("uint256[3]", "", nil)
    83  	Uint256ArrNested, _ = NewType("uint256[2][2]", "", nil)
    84  	Uint8ArrNested, _   = NewType("uint8[][2]", "", nil)
    85  	Uint8SliceNested, _ = NewType("uint8[][]", "", nil)
    86  	TupleF, _           = NewType("tuple", "struct Overloader.F", []ArgumentMarshaling{
    87  		{Name: "_f", Type: "uint256"},
    88  		{Name: "__f", Type: "uint256"},
    89  		{Name: "f", Type: "uint256"}})
    90  )
    91  
    92  var methods = map[string]Method{
    93  	"":                    NewMethod("", "", Function, "", false, false, nil, nil),
    94  	"balance":             NewMethod("balance", "balance", Function, "view", false, false, nil, nil),
    95  	"send":                NewMethod("send", "send", Function, "", false, false, []Argument{{"amount", Uint256, false}}, nil),
    96  	"test":                NewMethod("test", "test", Function, "", false, false, []Argument{{"number", Uint32, false}}, nil),
    97  	"string":              NewMethod("string", "string", Function, "", false, false, []Argument{{"inputs", String, false}}, nil),
    98  	"bool":                NewMethod("bool", "bool", Function, "", false, false, []Argument{{"inputs", Bool, false}}, nil),
    99  	"address":             NewMethod("address", "address", Function, "", false, false, []Argument{{"inputs", Address, false}}, nil),
   100  	"uint64[]":            NewMethod("uint64[]", "uint64[]", Function, "", false, false, []Argument{{"inputs", Uint64Arr, false}}, nil),
   101  	"uint64[2]":           NewMethod("uint64[2]", "uint64[2]", Function, "", false, false, []Argument{{"inputs", Uint64Arr2, false}}, nil),
   102  	"int8":                NewMethod("int8", "int8", Function, "", false, false, []Argument{{"inputs", Int8, false}}, nil),
   103  	"bytes32":             NewMethod("bytes32", "bytes32", Function, "", false, false, []Argument{{"inputs", Bytes32, false}}, nil),
   104  	"foo":                 NewMethod("foo", "foo", Function, "", false, false, []Argument{{"inputs", Uint32, false}}, nil),
   105  	"bar":                 NewMethod("bar", "bar", Function, "", false, false, []Argument{{"inputs", Uint32, false}, {"string", Uint16, false}}, nil),
   106  	"slice":               NewMethod("slice", "slice", Function, "", false, false, []Argument{{"inputs", Uint32Arr2, false}}, nil),
   107  	"slice256":            NewMethod("slice256", "slice256", Function, "", false, false, []Argument{{"inputs", Uint256Arr2, false}}, nil),
   108  	"sliceAddress":        NewMethod("sliceAddress", "sliceAddress", Function, "", false, false, []Argument{{"inputs", AddressArr, false}}, nil),
   109  	"sliceMultiAddress":   NewMethod("sliceMultiAddress", "sliceMultiAddress", Function, "", false, false, []Argument{{"a", AddressArr, false}, {"b", AddressArr, false}}, nil),
   110  	"nestedArray":         NewMethod("nestedArray", "nestedArray", Function, "", false, false, []Argument{{"a", Uint256ArrNested, false}, {"b", AddressArr, false}}, nil),
   111  	"nestedArray2":        NewMethod("nestedArray2", "nestedArray2", Function, "", false, false, []Argument{{"a", Uint8ArrNested, false}}, nil),
   112  	"nestedSlice":         NewMethod("nestedSlice", "nestedSlice", Function, "", false, false, []Argument{{"a", Uint8SliceNested, false}}, nil),
   113  	"receive":             NewMethod("receive", "receive", Function, "payable", false, true, []Argument{{"memo", Bytes, false}}, []Argument{}),
   114  	"fixedArrStr":         NewMethod("fixedArrStr", "fixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr", Uint256Arr2, false}}, nil),
   115  	"fixedArrBytes":       NewMethod("fixedArrBytes", "fixedArrBytes", Function, "view", false, false, []Argument{{"bytes", Bytes, false}, {"fixedArr", Uint256Arr2, false}}, nil),
   116  	"mixedArrStr":         NewMethod("mixedArrStr", "mixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr", Uint256Arr2, false}, {"dynArr", Uint256Arr, false}}, nil),
   117  	"doubleFixedArrStr":   NewMethod("doubleFixedArrStr", "doubleFixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr1", Uint256Arr2, false}, {"fixedArr2", Uint256Arr3, false}}, nil),
   118  	"multipleMixedArrStr": NewMethod("multipleMixedArrStr", "multipleMixedArrStr", Function, "view", false, false, []Argument{{"str", String, false}, {"fixedArr1", Uint256Arr2, false}, {"dynArr", Uint256Arr, false}, {"fixedArr2", Uint256Arr3, false}}, nil),
   119  	"overloadedNames":     NewMethod("overloadedNames", "overloadedNames", Function, "view", false, false, []Argument{{"f", TupleF, false}}, nil),
   120  }
   121  
   122  func TestReader(t *testing.T) {
   123  	t.Parallel()
   124  	abi := ABI{
   125  		Methods: methods,
   126  	}
   127  
   128  	exp, err := JSON(strings.NewReader(jsondata))
   129  	if err != nil {
   130  		t.Fatal(err)
   131  	}
   132  
   133  	for name, expM := range exp.Methods {
   134  		gotM, exist := abi.Methods[name]
   135  		if !exist {
   136  			t.Errorf("Missing expected method %v", name)
   137  		}
   138  		if !reflect.DeepEqual(gotM, expM) {
   139  			t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM)
   140  		}
   141  	}
   142  
   143  	for name, gotM := range abi.Methods {
   144  		expM, exist := exp.Methods[name]
   145  		if !exist {
   146  			t.Errorf("Found extra method %v", name)
   147  		}
   148  		if !reflect.DeepEqual(gotM, expM) {
   149  			t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM)
   150  		}
   151  	}
   152  }
   153  
   154  func TestInvalidABI(t *testing.T) {
   155  	t.Parallel()
   156  	json := `[{ "type" : "function", "name" : "", "constant" : fals }]`
   157  	_, err := JSON(strings.NewReader(json))
   158  	if err == nil {
   159  		t.Fatal("invalid json should produce error")
   160  	}
   161  	json2 := `[{ "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "typ" : "uint256" } ] }]`
   162  	_, err = JSON(strings.NewReader(json2))
   163  	if err == nil {
   164  		t.Fatal("invalid json should produce error")
   165  	}
   166  }
   167  
   168  // TestConstructor tests a constructor function.
   169  // The test is based on the following contract:
   170  //
   171  //	contract TestConstructor {
   172  //		constructor(uint256 a, uint256 b) public{}
   173  //	}
   174  func TestConstructor(t *testing.T) {
   175  	t.Parallel()
   176  	json := `[{	"inputs": [{"internalType": "uint256","name": "a","type": "uint256"	},{	"internalType": "uint256","name": "b","type": "uint256"}],"stateMutability": "nonpayable","type": "constructor"}]`
   177  	method := NewMethod("", "", Constructor, "nonpayable", false, false, []Argument{{"a", Uint256, false}, {"b", Uint256, false}}, nil)
   178  	// Test from JSON
   179  	abi, err := JSON(strings.NewReader(json))
   180  	if err != nil {
   181  		t.Fatal(err)
   182  	}
   183  	if !reflect.DeepEqual(abi.Constructor, method) {
   184  		t.Error("Missing expected constructor")
   185  	}
   186  	// Test pack/unpack
   187  	packed, err := abi.Pack("", big.NewInt(1), big.NewInt(2))
   188  	if err != nil {
   189  		t.Error(err)
   190  	}
   191  	unpacked, err := abi.Constructor.Inputs.Unpack(packed)
   192  	if err != nil {
   193  		t.Error(err)
   194  	}
   195  
   196  	if !reflect.DeepEqual(unpacked[0], big.NewInt(1)) {
   197  		t.Error("Unable to pack/unpack from constructor")
   198  	}
   199  	if !reflect.DeepEqual(unpacked[1], big.NewInt(2)) {
   200  		t.Error("Unable to pack/unpack from constructor")
   201  	}
   202  }
   203  
   204  func TestTestNumbers(t *testing.T) {
   205  	t.Parallel()
   206  	abi, err := JSON(strings.NewReader(jsondata))
   207  	if err != nil {
   208  		t.Fatal(err)
   209  	}
   210  
   211  	if _, err := abi.Pack("balance"); err != nil {
   212  		t.Error(err)
   213  	}
   214  
   215  	if _, err := abi.Pack("balance", 1); err == nil {
   216  		t.Error("expected error for balance(1)")
   217  	}
   218  
   219  	if _, err := abi.Pack("doesntexist", nil); err == nil {
   220  		t.Errorf("doesntexist shouldn't exist")
   221  	}
   222  
   223  	if _, err := abi.Pack("doesntexist", 1); err == nil {
   224  		t.Errorf("doesntexist(1) shouldn't exist")
   225  	}
   226  
   227  	if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
   228  		t.Error(err)
   229  	}
   230  
   231  	i := new(int)
   232  	*i = 1000
   233  	if _, err := abi.Pack("send", i); err == nil {
   234  		t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
   235  	}
   236  
   237  	if _, err := abi.Pack("test", uint32(1000)); err != nil {
   238  		t.Error(err)
   239  	}
   240  }
   241  
   242  func TestMethodSignature(t *testing.T) {
   243  	t.Parallel()
   244  	m := NewMethod("foo", "foo", Function, "", false, false, []Argument{{"bar", String, false}, {"baz", String, false}}, nil)
   245  	exp := "foo(string,string)"
   246  	if m.Sig != exp {
   247  		t.Error("signature mismatch", exp, "!=", m.Sig)
   248  	}
   249  
   250  	idexp := crypto.Keccak256([]byte(exp))[:4]
   251  	if !bytes.Equal(m.ID, idexp) {
   252  		t.Errorf("expected ids to match %x != %x", m.ID, idexp)
   253  	}
   254  
   255  	m = NewMethod("foo", "foo", Function, "", false, false, []Argument{{"bar", Uint256, false}}, nil)
   256  	exp = "foo(uint256)"
   257  	if m.Sig != exp {
   258  		t.Error("signature mismatch", exp, "!=", m.Sig)
   259  	}
   260  
   261  	// Method with tuple arguments
   262  	s, _ := NewType("tuple", "", []ArgumentMarshaling{
   263  		{Name: "a", Type: "int256"},
   264  		{Name: "b", Type: "int256[]"},
   265  		{Name: "c", Type: "tuple[]", Components: []ArgumentMarshaling{
   266  			{Name: "x", Type: "int256"},
   267  			{Name: "y", Type: "int256"},
   268  		}},
   269  		{Name: "d", Type: "tuple[2]", Components: []ArgumentMarshaling{
   270  			{Name: "x", Type: "int256"},
   271  			{Name: "y", Type: "int256"},
   272  		}},
   273  	})
   274  	m = NewMethod("foo", "foo", Function, "", false, false, []Argument{{"s", s, false}, {"bar", String, false}}, nil)
   275  	exp = "foo((int256,int256[],(int256,int256)[],(int256,int256)[2]),string)"
   276  	if m.Sig != exp {
   277  		t.Error("signature mismatch", exp, "!=", m.Sig)
   278  	}
   279  }
   280  
   281  func TestOverloadedMethodSignature(t *testing.T) {
   282  	t.Parallel()
   283  	json := `[{"constant":true,"inputs":[{"name":"i","type":"uint256"},{"name":"j","type":"uint256"}],"name":"foo","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"name":"i","type":"uint256"}],"name":"foo","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"i","type":"uint256"}],"name":"bar","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"i","type":"uint256"},{"indexed":false,"name":"j","type":"uint256"}],"name":"bar","type":"event"}]`
   284  	abi, err := JSON(strings.NewReader(json))
   285  	if err != nil {
   286  		t.Fatal(err)
   287  	}
   288  	check := func(name string, expect string, method bool) {
   289  		if method {
   290  			if abi.Methods[name].Sig != expect {
   291  				t.Fatalf("The signature of overloaded method mismatch, want %s, have %s", expect, abi.Methods[name].Sig)
   292  			}
   293  		} else {
   294  			if abi.Events[name].Sig != expect {
   295  				t.Fatalf("The signature of overloaded event mismatch, want %s, have %s", expect, abi.Events[name].Sig)
   296  			}
   297  		}
   298  	}
   299  	check("foo", "foo(uint256,uint256)", true)
   300  	check("foo0", "foo(uint256)", true)
   301  	check("bar", "bar(uint256)", false)
   302  	check("bar0", "bar(uint256,uint256)", false)
   303  }
   304  
   305  func TestCustomErrors(t *testing.T) {
   306  	t.Parallel()
   307  	json := `[{ "inputs": [	{ "internalType": "uint256", "name": "", "type": "uint256" } ],"name": "MyError", "type": "error"} ]`
   308  	abi, err := JSON(strings.NewReader(json))
   309  	if err != nil {
   310  		t.Fatal(err)
   311  	}
   312  	check := func(name string, expect string) {
   313  		if abi.Errors[name].Sig != expect {
   314  			t.Fatalf("The signature of overloaded method mismatch, want %s, have %s", expect, abi.Methods[name].Sig)
   315  		}
   316  	}
   317  	check("MyError", "MyError(uint256)")
   318  }
   319  
   320  func TestMultiPack(t *testing.T) {
   321  	t.Parallel()
   322  	abi, err := JSON(strings.NewReader(jsondata))
   323  	if err != nil {
   324  		t.Fatal(err)
   325  	}
   326  
   327  	sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
   328  	sig = append(sig, make([]byte, 64)...)
   329  	sig[35] = 10
   330  	sig[67] = 11
   331  
   332  	packed, err := abi.Pack("bar", uint32(10), uint16(11))
   333  	if err != nil {
   334  		t.Fatal(err)
   335  	}
   336  	if !bytes.Equal(packed, sig) {
   337  		t.Errorf("expected %x got %x", sig, packed)
   338  	}
   339  }
   340  
   341  func ExampleJSON() {
   342  	const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
   343  
   344  	abi, err := JSON(strings.NewReader(definition))
   345  	if err != nil {
   346  		panic(err)
   347  	}
   348  	out, err := abi.Pack("isBar", common.HexToAddress("01"))
   349  	if err != nil {
   350  		panic(err)
   351  	}
   352  
   353  	fmt.Printf("%x\n", out)
   354  	// Output:
   355  	// 1f2c40920000000000000000000000000000000000000000000000000000000000000001
   356  }
   357  
   358  func TestInputVariableInputLength(t *testing.T) {
   359  	t.Parallel()
   360  	const definition = `[
   361  	{ "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
   362  	{ "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
   363  	{ "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
   364  	]`
   365  
   366  	abi, err := JSON(strings.NewReader(definition))
   367  	if err != nil {
   368  		t.Fatal(err)
   369  	}
   370  
   371  	// test one string
   372  	strin := "hello world"
   373  	strpack, err := abi.Pack("strOne", strin)
   374  	if err != nil {
   375  		t.Error(err)
   376  	}
   377  
   378  	offset := make([]byte, 32)
   379  	offset[31] = 32
   380  	length := make([]byte, 32)
   381  	length[31] = byte(len(strin))
   382  	value := common.RightPadBytes([]byte(strin), 32)
   383  	exp := append(offset, append(length, value...)...)
   384  
   385  	// ignore first 4 bytes of the output. This is the function identifier
   386  	strpack = strpack[4:]
   387  	if !bytes.Equal(strpack, exp) {
   388  		t.Errorf("expected %x, got %x\n", exp, strpack)
   389  	}
   390  
   391  	// test one bytes
   392  	btspack, err := abi.Pack("bytesOne", []byte(strin))
   393  	if err != nil {
   394  		t.Error(err)
   395  	}
   396  	// ignore first 4 bytes of the output. This is the function identifier
   397  	btspack = btspack[4:]
   398  	if !bytes.Equal(btspack, exp) {
   399  		t.Errorf("expected %x, got %x\n", exp, btspack)
   400  	}
   401  
   402  	//  test two strings
   403  	str1 := "hello"
   404  	str2 := "world"
   405  	str2pack, err := abi.Pack("strTwo", str1, str2)
   406  	if err != nil {
   407  		t.Error(err)
   408  	}
   409  
   410  	offset1 := make([]byte, 32)
   411  	offset1[31] = 64
   412  	length1 := make([]byte, 32)
   413  	length1[31] = byte(len(str1))
   414  	value1 := common.RightPadBytes([]byte(str1), 32)
   415  
   416  	offset2 := make([]byte, 32)
   417  	offset2[31] = 128
   418  	length2 := make([]byte, 32)
   419  	length2[31] = byte(len(str2))
   420  	value2 := common.RightPadBytes([]byte(str2), 32)
   421  
   422  	exp2 := append(offset1, offset2...)
   423  	exp2 = append(exp2, append(length1, value1...)...)
   424  	exp2 = append(exp2, append(length2, value2...)...)
   425  
   426  	// ignore first 4 bytes of the output. This is the function identifier
   427  	str2pack = str2pack[4:]
   428  	if !bytes.Equal(str2pack, exp2) {
   429  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   430  	}
   431  
   432  	// test two strings, first > 32, second < 32
   433  	str1 = strings.Repeat("a", 33)
   434  	str2pack, err = abi.Pack("strTwo", str1, str2)
   435  	if err != nil {
   436  		t.Error(err)
   437  	}
   438  
   439  	offset1 = make([]byte, 32)
   440  	offset1[31] = 64
   441  	length1 = make([]byte, 32)
   442  	length1[31] = byte(len(str1))
   443  	value1 = common.RightPadBytes([]byte(str1), 64)
   444  	offset2[31] = 160
   445  
   446  	exp2 = append(offset1, offset2...)
   447  	exp2 = append(exp2, append(length1, value1...)...)
   448  	exp2 = append(exp2, append(length2, value2...)...)
   449  
   450  	// ignore first 4 bytes of the output. This is the function identifier
   451  	str2pack = str2pack[4:]
   452  	if !bytes.Equal(str2pack, exp2) {
   453  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   454  	}
   455  
   456  	// test two strings, first > 32, second >32
   457  	str1 = strings.Repeat("a", 33)
   458  	str2 = strings.Repeat("a", 33)
   459  	str2pack, err = abi.Pack("strTwo", str1, str2)
   460  	if err != nil {
   461  		t.Error(err)
   462  	}
   463  
   464  	offset1 = make([]byte, 32)
   465  	offset1[31] = 64
   466  	length1 = make([]byte, 32)
   467  	length1[31] = byte(len(str1))
   468  	value1 = common.RightPadBytes([]byte(str1), 64)
   469  
   470  	offset2 = make([]byte, 32)
   471  	offset2[31] = 160
   472  	length2 = make([]byte, 32)
   473  	length2[31] = byte(len(str2))
   474  	value2 = common.RightPadBytes([]byte(str2), 64)
   475  
   476  	exp2 = append(offset1, offset2...)
   477  	exp2 = append(exp2, append(length1, value1...)...)
   478  	exp2 = append(exp2, append(length2, value2...)...)
   479  
   480  	// ignore first 4 bytes of the output. This is the function identifier
   481  	str2pack = str2pack[4:]
   482  	if !bytes.Equal(str2pack, exp2) {
   483  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   484  	}
   485  }
   486  
   487  func TestInputFixedArrayAndVariableInputLength(t *testing.T) {
   488  	t.Parallel()
   489  	abi, err := JSON(strings.NewReader(jsondata))
   490  	if err != nil {
   491  		t.Error(err)
   492  	}
   493  
   494  	// test string, fixed array uint256[2]
   495  	strin := "hello world"
   496  	arrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   497  	fixedArrStrPack, err := abi.Pack("fixedArrStr", strin, arrin)
   498  	if err != nil {
   499  		t.Error(err)
   500  	}
   501  
   502  	// generate expected output
   503  	offset := make([]byte, 32)
   504  	offset[31] = 96
   505  	length := make([]byte, 32)
   506  	length[31] = byte(len(strin))
   507  	strvalue := common.RightPadBytes([]byte(strin), 32)
   508  	arrinvalue1 := common.LeftPadBytes(arrin[0].Bytes(), 32)
   509  	arrinvalue2 := common.LeftPadBytes(arrin[1].Bytes(), 32)
   510  	exp := append(offset, arrinvalue1...)
   511  	exp = append(exp, arrinvalue2...)
   512  	exp = append(exp, append(length, strvalue...)...)
   513  
   514  	// ignore first 4 bytes of the output. This is the function identifier
   515  	fixedArrStrPack = fixedArrStrPack[4:]
   516  	if !bytes.Equal(fixedArrStrPack, exp) {
   517  		t.Errorf("expected %x, got %x\n", exp, fixedArrStrPack)
   518  	}
   519  
   520  	// test byte array, fixed array uint256[2]
   521  	bytesin := []byte(strin)
   522  	arrin = [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   523  	fixedArrBytesPack, err := abi.Pack("fixedArrBytes", bytesin, arrin)
   524  	if err != nil {
   525  		t.Error(err)
   526  	}
   527  
   528  	// generate expected output
   529  	offset = make([]byte, 32)
   530  	offset[31] = 96
   531  	length = make([]byte, 32)
   532  	length[31] = byte(len(strin))
   533  	strvalue = common.RightPadBytes([]byte(strin), 32)
   534  	arrinvalue1 = common.LeftPadBytes(arrin[0].Bytes(), 32)
   535  	arrinvalue2 = common.LeftPadBytes(arrin[1].Bytes(), 32)
   536  	exp = append(offset, arrinvalue1...)
   537  	exp = append(exp, arrinvalue2...)
   538  	exp = append(exp, append(length, strvalue...)...)
   539  
   540  	// ignore first 4 bytes of the output. This is the function identifier
   541  	fixedArrBytesPack = fixedArrBytesPack[4:]
   542  	if !bytes.Equal(fixedArrBytesPack, exp) {
   543  		t.Errorf("expected %x, got %x\n", exp, fixedArrBytesPack)
   544  	}
   545  
   546  	// test string, fixed array uint256[2], dynamic array uint256[]
   547  	strin = "hello world"
   548  	fixedarrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   549  	dynarrin := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   550  	mixedArrStrPack, err := abi.Pack("mixedArrStr", strin, fixedarrin, dynarrin)
   551  	if err != nil {
   552  		t.Error(err)
   553  	}
   554  
   555  	// generate expected output
   556  	stroffset := make([]byte, 32)
   557  	stroffset[31] = 128
   558  	strlength := make([]byte, 32)
   559  	strlength[31] = byte(len(strin))
   560  	strvalue = common.RightPadBytes([]byte(strin), 32)
   561  	fixedarrinvalue1 := common.LeftPadBytes(fixedarrin[0].Bytes(), 32)
   562  	fixedarrinvalue2 := common.LeftPadBytes(fixedarrin[1].Bytes(), 32)
   563  	dynarroffset := make([]byte, 32)
   564  	dynarroffset[31] = byte(160 + ((len(strin)/32)+1)*32)
   565  	dynarrlength := make([]byte, 32)
   566  	dynarrlength[31] = byte(len(dynarrin))
   567  	dynarrinvalue1 := common.LeftPadBytes(dynarrin[0].Bytes(), 32)
   568  	dynarrinvalue2 := common.LeftPadBytes(dynarrin[1].Bytes(), 32)
   569  	dynarrinvalue3 := common.LeftPadBytes(dynarrin[2].Bytes(), 32)
   570  	exp = append(stroffset, fixedarrinvalue1...)
   571  	exp = append(exp, fixedarrinvalue2...)
   572  	exp = append(exp, dynarroffset...)
   573  	exp = append(exp, append(strlength, strvalue...)...)
   574  	dynarrarg := append(dynarrlength, dynarrinvalue1...)
   575  	dynarrarg = append(dynarrarg, dynarrinvalue2...)
   576  	dynarrarg = append(dynarrarg, dynarrinvalue3...)
   577  	exp = append(exp, dynarrarg...)
   578  
   579  	// ignore first 4 bytes of the output. This is the function identifier
   580  	mixedArrStrPack = mixedArrStrPack[4:]
   581  	if !bytes.Equal(mixedArrStrPack, exp) {
   582  		t.Errorf("expected %x, got %x\n", exp, mixedArrStrPack)
   583  	}
   584  
   585  	// test string, fixed array uint256[2], fixed array uint256[3]
   586  	strin = "hello world"
   587  	fixedarrin1 := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   588  	fixedarrin2 := [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   589  	doubleFixedArrStrPack, err := abi.Pack("doubleFixedArrStr", strin, fixedarrin1, fixedarrin2)
   590  	if err != nil {
   591  		t.Error(err)
   592  	}
   593  
   594  	// generate expected output
   595  	stroffset = make([]byte, 32)
   596  	stroffset[31] = 192
   597  	strlength = make([]byte, 32)
   598  	strlength[31] = byte(len(strin))
   599  	strvalue = common.RightPadBytes([]byte(strin), 32)
   600  	fixedarrin1value1 := common.LeftPadBytes(fixedarrin1[0].Bytes(), 32)
   601  	fixedarrin1value2 := common.LeftPadBytes(fixedarrin1[1].Bytes(), 32)
   602  	fixedarrin2value1 := common.LeftPadBytes(fixedarrin2[0].Bytes(), 32)
   603  	fixedarrin2value2 := common.LeftPadBytes(fixedarrin2[1].Bytes(), 32)
   604  	fixedarrin2value3 := common.LeftPadBytes(fixedarrin2[2].Bytes(), 32)
   605  	exp = append(stroffset, fixedarrin1value1...)
   606  	exp = append(exp, fixedarrin1value2...)
   607  	exp = append(exp, fixedarrin2value1...)
   608  	exp = append(exp, fixedarrin2value2...)
   609  	exp = append(exp, fixedarrin2value3...)
   610  	exp = append(exp, append(strlength, strvalue...)...)
   611  
   612  	// ignore first 4 bytes of the output. This is the function identifier
   613  	doubleFixedArrStrPack = doubleFixedArrStrPack[4:]
   614  	if !bytes.Equal(doubleFixedArrStrPack, exp) {
   615  		t.Errorf("expected %x, got %x\n", exp, doubleFixedArrStrPack)
   616  	}
   617  
   618  	// test string, fixed array uint256[2], dynamic array uint256[], fixed array uint256[3]
   619  	strin = "hello world"
   620  	fixedarrin1 = [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   621  	dynarrin = []*big.Int{big.NewInt(1), big.NewInt(2)}
   622  	fixedarrin2 = [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   623  	multipleMixedArrStrPack, err := abi.Pack("multipleMixedArrStr", strin, fixedarrin1, dynarrin, fixedarrin2)
   624  	if err != nil {
   625  		t.Error(err)
   626  	}
   627  
   628  	// generate expected output
   629  	stroffset = make([]byte, 32)
   630  	stroffset[31] = 224
   631  	strlength = make([]byte, 32)
   632  	strlength[31] = byte(len(strin))
   633  	strvalue = common.RightPadBytes([]byte(strin), 32)
   634  	fixedarrin1value1 = common.LeftPadBytes(fixedarrin1[0].Bytes(), 32)
   635  	fixedarrin1value2 = common.LeftPadBytes(fixedarrin1[1].Bytes(), 32)
   636  	dynarroffset = math.U256Bytes(big.NewInt(int64(256 + ((len(strin)/32)+1)*32)))
   637  	dynarrlength = make([]byte, 32)
   638  	dynarrlength[31] = byte(len(dynarrin))
   639  	dynarrinvalue1 = common.LeftPadBytes(dynarrin[0].Bytes(), 32)
   640  	dynarrinvalue2 = common.LeftPadBytes(dynarrin[1].Bytes(), 32)
   641  	fixedarrin2value1 = common.LeftPadBytes(fixedarrin2[0].Bytes(), 32)
   642  	fixedarrin2value2 = common.LeftPadBytes(fixedarrin2[1].Bytes(), 32)
   643  	fixedarrin2value3 = common.LeftPadBytes(fixedarrin2[2].Bytes(), 32)
   644  	exp = append(stroffset, fixedarrin1value1...)
   645  	exp = append(exp, fixedarrin1value2...)
   646  	exp = append(exp, dynarroffset...)
   647  	exp = append(exp, fixedarrin2value1...)
   648  	exp = append(exp, fixedarrin2value2...)
   649  	exp = append(exp, fixedarrin2value3...)
   650  	exp = append(exp, append(strlength, strvalue...)...)
   651  	dynarrarg = append(dynarrlength, dynarrinvalue1...)
   652  	dynarrarg = append(dynarrarg, dynarrinvalue2...)
   653  	exp = append(exp, dynarrarg...)
   654  
   655  	// ignore first 4 bytes of the output. This is the function identifier
   656  	multipleMixedArrStrPack = multipleMixedArrStrPack[4:]
   657  	if !bytes.Equal(multipleMixedArrStrPack, exp) {
   658  		t.Errorf("expected %x, got %x\n", exp, multipleMixedArrStrPack)
   659  	}
   660  }
   661  
   662  func TestDefaultFunctionParsing(t *testing.T) {
   663  	t.Parallel()
   664  	const definition = `[{ "name" : "balance", "type" : "function" }]`
   665  
   666  	abi, err := JSON(strings.NewReader(definition))
   667  	if err != nil {
   668  		t.Fatal(err)
   669  	}
   670  
   671  	if _, ok := abi.Methods["balance"]; !ok {
   672  		t.Error("expected 'balance' to be present")
   673  	}
   674  }
   675  
   676  func TestBareEvents(t *testing.T) {
   677  	t.Parallel()
   678  	const definition = `[
   679  	{ "type" : "event", "name" : "balance" },
   680  	{ "type" : "event", "name" : "anon", "anonymous" : true},
   681  	{ "type" : "event", "name" : "args", "inputs" : [{ "indexed":false, "name":"arg0", "type":"uint256" }, { "indexed":true, "name":"arg1", "type":"address" }] },
   682  	{ "type" : "event", "name" : "tuple", "inputs" : [{ "indexed":false, "name":"t", "type":"tuple", "components":[{"name":"a", "type":"uint256"}] }, { "indexed":true, "name":"arg1", "type":"address" }] }
   683  	]`
   684  
   685  	tuple, _ := NewType("tuple", "", []ArgumentMarshaling{{Name: "a", Type: "uint256"}})
   686  
   687  	expectedEvents := map[string]struct {
   688  		Anonymous bool
   689  		Args      []Argument
   690  	}{
   691  		"balance": {false, nil},
   692  		"anon":    {true, nil},
   693  		"args": {false, []Argument{
   694  			{Name: "arg0", Type: Uint256, Indexed: false},
   695  			{Name: "arg1", Type: Address, Indexed: true},
   696  		}},
   697  		"tuple": {false, []Argument{
   698  			{Name: "t", Type: tuple, Indexed: false},
   699  			{Name: "arg1", Type: Address, Indexed: true},
   700  		}},
   701  	}
   702  
   703  	abi, err := JSON(strings.NewReader(definition))
   704  	if err != nil {
   705  		t.Fatal(err)
   706  	}
   707  
   708  	if len(abi.Events) != len(expectedEvents) {
   709  		t.Fatalf("invalid number of events after parsing, want %d, got %d", len(expectedEvents), len(abi.Events))
   710  	}
   711  
   712  	for name, exp := range expectedEvents {
   713  		got, ok := abi.Events[name]
   714  		if !ok {
   715  			t.Errorf("could not found event %s", name)
   716  			continue
   717  		}
   718  		if got.Anonymous != exp.Anonymous {
   719  			t.Errorf("invalid anonymous indication for event %s, want %v, got %v", name, exp.Anonymous, got.Anonymous)
   720  		}
   721  		if len(got.Inputs) != len(exp.Args) {
   722  			t.Errorf("invalid number of args, want %d, got %d", len(exp.Args), len(got.Inputs))
   723  			continue
   724  		}
   725  		for i, arg := range exp.Args {
   726  			if arg.Name != got.Inputs[i].Name {
   727  				t.Errorf("events[%s].Input[%d] has an invalid name, want %s, got %s", name, i, arg.Name, got.Inputs[i].Name)
   728  			}
   729  			if arg.Indexed != got.Inputs[i].Indexed {
   730  				t.Errorf("events[%s].Input[%d] has an invalid indexed indication, want %v, got %v", name, i, arg.Indexed, got.Inputs[i].Indexed)
   731  			}
   732  			if arg.Type.T != got.Inputs[i].Type.T {
   733  				t.Errorf("events[%s].Input[%d] has an invalid type, want %x, got %x", name, i, arg.Type.T, got.Inputs[i].Type.T)
   734  			}
   735  		}
   736  	}
   737  }
   738  
   739  // TestUnpackEvent is based on this contract:
   740  //
   741  //	contract T {
   742  //		event received(address sender, uint amount, bytes memo);
   743  //		event receivedAddr(address sender);
   744  //		function receive(bytes memo) external payable {
   745  //			received(msg.sender, msg.value, memo);
   746  //			receivedAddr(msg.sender);
   747  //		}
   748  //	}
   749  //
   750  // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
   751  //
   752  //	receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
   753  func TestUnpackEvent(t *testing.T) {
   754  	t.Parallel()
   755  	const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   756  	abi, err := JSON(strings.NewReader(abiJSON))
   757  	if err != nil {
   758  		t.Fatal(err)
   759  	}
   760  
   761  	const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   762  	data, err := hex.DecodeString(hexdata)
   763  	if err != nil {
   764  		t.Fatal(err)
   765  	}
   766  	if len(data)%32 == 0 {
   767  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   768  	}
   769  
   770  	type ReceivedEvent struct {
   771  		Sender common.Address
   772  		Amount *big.Int
   773  		Memo   []byte
   774  	}
   775  	var ev ReceivedEvent
   776  
   777  	err = abi.UnpackIntoInterface(&ev, "received", data)
   778  	if err != nil {
   779  		t.Error(err)
   780  	}
   781  
   782  	type ReceivedAddrEvent struct {
   783  		Sender common.Address
   784  	}
   785  	var receivedAddrEv ReceivedAddrEvent
   786  	err = abi.UnpackIntoInterface(&receivedAddrEv, "receivedAddr", data)
   787  	if err != nil {
   788  		t.Error(err)
   789  	}
   790  }
   791  
   792  func TestUnpackEventIntoMap(t *testing.T) {
   793  	t.Parallel()
   794  	const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   795  	abi, err := JSON(strings.NewReader(abiJSON))
   796  	if err != nil {
   797  		t.Fatal(err)
   798  	}
   799  
   800  	const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   801  	data, err := hex.DecodeString(hexdata)
   802  	if err != nil {
   803  		t.Fatal(err)
   804  	}
   805  	if len(data)%32 == 0 {
   806  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   807  	}
   808  
   809  	receivedMap := map[string]interface{}{}
   810  	expectedReceivedMap := map[string]interface{}{
   811  		"sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   812  		"amount": big.NewInt(1),
   813  		"memo":   []byte{88},
   814  	}
   815  	if err := abi.UnpackIntoMap(receivedMap, "received", data); err != nil {
   816  		t.Error(err)
   817  	}
   818  	if len(receivedMap) != 3 {
   819  		t.Error("unpacked `received` map expected to have length 3")
   820  	}
   821  	if receivedMap["sender"] != expectedReceivedMap["sender"] {
   822  		t.Error("unpacked `received` map does not match expected map")
   823  	}
   824  	if receivedMap["amount"].(*big.Int).Cmp(expectedReceivedMap["amount"].(*big.Int)) != 0 {
   825  		t.Error("unpacked `received` map does not match expected map")
   826  	}
   827  	if !bytes.Equal(receivedMap["memo"].([]byte), expectedReceivedMap["memo"].([]byte)) {
   828  		t.Error("unpacked `received` map does not match expected map")
   829  	}
   830  
   831  	receivedAddrMap := map[string]interface{}{}
   832  	if err = abi.UnpackIntoMap(receivedAddrMap, "receivedAddr", data); err != nil {
   833  		t.Error(err)
   834  	}
   835  	if len(receivedAddrMap) != 1 {
   836  		t.Error("unpacked `receivedAddr` map expected to have length 1")
   837  	}
   838  	if receivedAddrMap["sender"] != expectedReceivedMap["sender"] {
   839  		t.Error("unpacked `receivedAddr` map does not match expected map")
   840  	}
   841  }
   842  
   843  func TestUnpackMethodIntoMap(t *testing.T) {
   844  	t.Parallel()
   845  	const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"send","outputs":[{"name":"amount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"get","outputs":[{"name":"hash","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"function"}]`
   846  	abi, err := JSON(strings.NewReader(abiJSON))
   847  	if err != nil {
   848  		t.Fatal(err)
   849  	}
   850  	const hexdata = `00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000015800000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000158000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001580000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000015800000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000158`
   851  	data, err := hex.DecodeString(hexdata)
   852  	if err != nil {
   853  		t.Fatal(err)
   854  	}
   855  	if len(data)%32 != 0 {
   856  		t.Errorf("len(data) is %d, want a multiple of 32", len(data))
   857  	}
   858  
   859  	// Tests a method with no outputs
   860  	receiveMap := map[string]interface{}{}
   861  	if err = abi.UnpackIntoMap(receiveMap, "receive", data); err != nil {
   862  		t.Error(err)
   863  	}
   864  	if len(receiveMap) > 0 {
   865  		t.Error("unpacked `receive` map expected to have length 0")
   866  	}
   867  
   868  	// Tests a method with only outputs
   869  	sendMap := map[string]interface{}{}
   870  	if err = abi.UnpackIntoMap(sendMap, "send", data); err != nil {
   871  		t.Error(err)
   872  	}
   873  	if len(sendMap) != 1 {
   874  		t.Error("unpacked `send` map expected to have length 1")
   875  	}
   876  	if sendMap["amount"].(*big.Int).Cmp(big.NewInt(1)) != 0 {
   877  		t.Error("unpacked `send` map expected `amount` value of 1")
   878  	}
   879  
   880  	// Tests a method with outputs and inputs
   881  	getMap := map[string]interface{}{}
   882  	if err = abi.UnpackIntoMap(getMap, "get", data); err != nil {
   883  		t.Error(err)
   884  	}
   885  	if len(getMap) != 1 {
   886  		t.Error("unpacked `get` map expected to have length 1")
   887  	}
   888  	expectedBytes := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 88, 0}
   889  	if !bytes.Equal(getMap["hash"].([]byte), expectedBytes) {
   890  		t.Errorf("unpacked `get` map expected `hash` value of %v", expectedBytes)
   891  	}
   892  }
   893  
   894  func TestUnpackIntoMapNamingConflict(t *testing.T) {
   895  	t.Parallel()
   896  	// Two methods have the same name
   897  	var abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"get","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"send","outputs":[{"name":"amount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"get","outputs":[{"name":"hash","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"function"}]`
   898  	abi, err := JSON(strings.NewReader(abiJSON))
   899  	if err != nil {
   900  		t.Fatal(err)
   901  	}
   902  	var hexdata = `00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   903  	data, err := hex.DecodeString(hexdata)
   904  	if err != nil {
   905  		t.Fatal(err)
   906  	}
   907  	if len(data)%32 == 0 {
   908  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   909  	}
   910  	getMap := map[string]interface{}{}
   911  	if err = abi.UnpackIntoMap(getMap, "get", data); err == nil {
   912  		t.Error("naming conflict between two methods; error expected")
   913  	}
   914  
   915  	// Two events have the same name
   916  	abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"received","type":"event"}]`
   917  	abi, err = JSON(strings.NewReader(abiJSON))
   918  	if err != nil {
   919  		t.Fatal(err)
   920  	}
   921  	hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   922  	data, err = hex.DecodeString(hexdata)
   923  	if err != nil {
   924  		t.Fatal(err)
   925  	}
   926  	if len(data)%32 == 0 {
   927  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   928  	}
   929  	receivedMap := map[string]interface{}{}
   930  	if err = abi.UnpackIntoMap(receivedMap, "received", data); err != nil {
   931  		t.Error("naming conflict between two events; no error expected")
   932  	}
   933  
   934  	// Method and event have the same name
   935  	abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"received","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   936  	abi, err = JSON(strings.NewReader(abiJSON))
   937  	if err != nil {
   938  		t.Fatal(err)
   939  	}
   940  	if len(data)%32 == 0 {
   941  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   942  	}
   943  	if err = abi.UnpackIntoMap(receivedMap, "received", data); err == nil {
   944  		t.Error("naming conflict between an event and a method; error expected")
   945  	}
   946  
   947  	// Conflict is case sensitive
   948  	abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"received","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"Received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]`
   949  	abi, err = JSON(strings.NewReader(abiJSON))
   950  	if err != nil {
   951  		t.Fatal(err)
   952  	}
   953  	if len(data)%32 == 0 {
   954  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   955  	}
   956  	expectedReceivedMap := map[string]interface{}{
   957  		"sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   958  		"amount": big.NewInt(1),
   959  		"memo":   []byte{88},
   960  	}
   961  	if err = abi.UnpackIntoMap(receivedMap, "Received", data); err != nil {
   962  		t.Error(err)
   963  	}
   964  	if len(receivedMap) != 3 {
   965  		t.Error("unpacked `received` map expected to have length 3")
   966  	}
   967  	if receivedMap["sender"] != expectedReceivedMap["sender"] {
   968  		t.Error("unpacked `received` map does not match expected map")
   969  	}
   970  	if receivedMap["amount"].(*big.Int).Cmp(expectedReceivedMap["amount"].(*big.Int)) != 0 {
   971  		t.Error("unpacked `received` map does not match expected map")
   972  	}
   973  	if !bytes.Equal(receivedMap["memo"].([]byte), expectedReceivedMap["memo"].([]byte)) {
   974  		t.Error("unpacked `received` map does not match expected map")
   975  	}
   976  }
   977  
   978  func TestABI_MethodById(t *testing.T) {
   979  	t.Parallel()
   980  	abi, err := JSON(strings.NewReader(jsondata))
   981  	if err != nil {
   982  		t.Fatal(err)
   983  	}
   984  	for name, m := range abi.Methods {
   985  		a := fmt.Sprintf("%v", m)
   986  		m2, err := abi.MethodById(m.ID)
   987  		if err != nil {
   988  			t.Fatalf("Failed to look up ABI method: %v", err)
   989  		}
   990  		b := fmt.Sprintf("%v", m2)
   991  		if a != b {
   992  			t.Errorf("Method %v (id %x) not 'findable' by id in ABI", name, m.ID)
   993  		}
   994  	}
   995  	// test unsuccessful lookups
   996  	if _, err = abi.MethodById(crypto.Keccak256()); err == nil {
   997  		t.Error("Expected error: no method with this id")
   998  	}
   999  	// Also test empty
  1000  	if _, err := abi.MethodById([]byte{0x00}); err == nil {
  1001  		t.Errorf("Expected error, too short to decode data")
  1002  	}
  1003  	if _, err := abi.MethodById([]byte{}); err == nil {
  1004  		t.Errorf("Expected error, too short to decode data")
  1005  	}
  1006  	if _, err := abi.MethodById(nil); err == nil {
  1007  		t.Errorf("Expected error, nil is short to decode data")
  1008  	}
  1009  }
  1010  
  1011  func TestABI_EventById(t *testing.T) {
  1012  	t.Parallel()
  1013  	tests := []struct {
  1014  		name  string
  1015  		json  string
  1016  		event string
  1017  	}{
  1018  		{
  1019  			name: "",
  1020  			json: `[
  1021  			{"type":"event","name":"received","anonymous":false,"inputs":[
  1022  				{"indexed":false,"name":"sender","type":"address"},
  1023  				{"indexed":false,"name":"amount","type":"uint256"},
  1024  				{"indexed":false,"name":"memo","type":"bytes"}
  1025  				]
  1026  			}]`,
  1027  			event: "received(address,uint256,bytes)",
  1028  		}, {
  1029  			name: "",
  1030  			json: `[
  1031  				{ "constant": true, "inputs": [], "name": "name", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1032  				{ "constant": false, "inputs": [ { "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "approve", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" },
  1033  				{ "constant": true, "inputs": [], "name": "totalSupply", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1034  				{ "constant": false, "inputs": [ { "name": "_from", "type": "address" }, { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" },
  1035  				{ "constant": true, "inputs": [], "name": "decimals", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1036  				{ "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1037  				{ "constant": true, "inputs": [], "name": "symbol", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1038  				{ "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" },
  1039  				{ "constant": true, "inputs": [ { "name": "_owner", "type": "address" }, { "name": "_spender", "type": "address" } ], "name": "allowance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" },
  1040  				{ "payable": true, "stateMutability": "payable", "type": "fallback" },
  1041  				{ "anonymous": false, "inputs": [ { "indexed": true, "name": "owner", "type": "address" }, { "indexed": true, "name": "spender", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" },
  1042  				{ "anonymous": false, "inputs": [ { "indexed": true, "name": "from", "type": "address" }, { "indexed": true, "name": "to", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }
  1043  			]`,
  1044  			event: "Transfer(address,address,uint256)",
  1045  		},
  1046  	}
  1047  
  1048  	for testnum, test := range tests {
  1049  		abi, err := JSON(strings.NewReader(test.json))
  1050  		if err != nil {
  1051  			t.Error(err)
  1052  		}
  1053  
  1054  		topic := test.event
  1055  		topicID := crypto.Keccak256Hash([]byte(topic))
  1056  
  1057  		event, err := abi.EventByID(topicID)
  1058  		if err != nil {
  1059  			t.Fatalf("Failed to look up ABI method: %v, test #%d", err, testnum)
  1060  		}
  1061  		if event == nil {
  1062  			t.Errorf("We should find a event for topic %s, test #%d", topicID.Hex(), testnum)
  1063  		} else if event.ID != topicID {
  1064  			t.Errorf("Event id %s does not match topic %s, test #%d", event.ID.Hex(), topicID.Hex(), testnum)
  1065  		}
  1066  
  1067  		unknowntopicID := crypto.Keccak256Hash([]byte("unknownEvent"))
  1068  		unknownEvent, err := abi.EventByID(unknowntopicID)
  1069  		if err == nil {
  1070  			t.Errorf("EventByID should return an error if a topic is not found, test #%d", testnum)
  1071  		}
  1072  		if unknownEvent != nil {
  1073  			t.Errorf("We should not find any event for topic %s, test #%d", unknowntopicID.Hex(), testnum)
  1074  		}
  1075  	}
  1076  }
  1077  
  1078  func TestABI_ErrorByID(t *testing.T) {
  1079  	t.Parallel()
  1080  	abi, err := JSON(strings.NewReader(`[
  1081  		{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"MyError1","type":"error"},
  1082  		{"inputs":[{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"string","name":"b","type":"string"},{"internalType":"address","name":"c","type":"address"}],"internalType":"struct MyError.MyStruct","name":"x","type":"tuple"},{"internalType":"address","name":"y","type":"address"},{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"string","name":"b","type":"string"},{"internalType":"address","name":"c","type":"address"}],"internalType":"struct MyError.MyStruct","name":"z","type":"tuple"}],"name":"MyError2","type":"error"},
  1083  		{"inputs":[{"internalType":"uint256[]","name":"x","type":"uint256[]"}],"name":"MyError3","type":"error"}
  1084  	]`))
  1085  	if err != nil {
  1086  		t.Fatal(err)
  1087  	}
  1088  	for name, m := range abi.Errors {
  1089  		a := fmt.Sprintf("%v", &m)
  1090  		var id [4]byte
  1091  		copy(id[:], m.ID[:4])
  1092  		m2, err := abi.ErrorByID(id)
  1093  		if err != nil {
  1094  			t.Fatalf("Failed to look up ABI error: %v", err)
  1095  		}
  1096  		b := fmt.Sprintf("%v", m2)
  1097  		if a != b {
  1098  			t.Errorf("Error %v (id %x) not 'findable' by id in ABI", name, id)
  1099  		}
  1100  	}
  1101  	// test unsuccessful lookups
  1102  	if _, err = abi.ErrorByID([4]byte{}); err == nil {
  1103  		t.Error("Expected error: no error with this id")
  1104  	}
  1105  }
  1106  
  1107  // TestDoubleDuplicateMethodNames checks that if transfer0 already exists, there won't be a name
  1108  // conflict and that the second transfer method will be renamed transfer1.
  1109  func TestDoubleDuplicateMethodNames(t *testing.T) {
  1110  	t.Parallel()
  1111  	abiJSON := `[{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"}],"name":"transfer0","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"},{"name":"customFallback","type":"string"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]`
  1112  	contractAbi, err := JSON(strings.NewReader(abiJSON))
  1113  	if err != nil {
  1114  		t.Fatal(err)
  1115  	}
  1116  	if _, ok := contractAbi.Methods["transfer"]; !ok {
  1117  		t.Fatalf("Could not find original method")
  1118  	}
  1119  	if _, ok := contractAbi.Methods["transfer0"]; !ok {
  1120  		t.Fatalf("Could not find duplicate method")
  1121  	}
  1122  	if _, ok := contractAbi.Methods["transfer1"]; !ok {
  1123  		t.Fatalf("Could not find duplicate method")
  1124  	}
  1125  	if _, ok := contractAbi.Methods["transfer2"]; ok {
  1126  		t.Fatalf("Should not have found extra method")
  1127  	}
  1128  }
  1129  
  1130  // TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name
  1131  // conflict and that the second send event will be renamed send1.
  1132  // The test runs the abi of the following contract.
  1133  //
  1134  //	contract DuplicateEvent {
  1135  //		event send(uint256 a);
  1136  //		event send0();
  1137  //		event send();
  1138  //	}
  1139  func TestDoubleDuplicateEventNames(t *testing.T) {
  1140  	t.Parallel()
  1141  	abiJSON := `[{"anonymous": false,"inputs": [{"indexed": false,"internalType": "uint256","name": "a","type": "uint256"}],"name": "send","type": "event"},{"anonymous": false,"inputs": [],"name": "send0","type": "event"},{	"anonymous": false,	"inputs": [],"name": "send","type": "event"}]`
  1142  	contractAbi, err := JSON(strings.NewReader(abiJSON))
  1143  	if err != nil {
  1144  		t.Fatal(err)
  1145  	}
  1146  	if _, ok := contractAbi.Events["send"]; !ok {
  1147  		t.Fatalf("Could not find original event")
  1148  	}
  1149  	if _, ok := contractAbi.Events["send0"]; !ok {
  1150  		t.Fatalf("Could not find duplicate event")
  1151  	}
  1152  	if _, ok := contractAbi.Events["send1"]; !ok {
  1153  		t.Fatalf("Could not find duplicate event")
  1154  	}
  1155  	if _, ok := contractAbi.Events["send2"]; ok {
  1156  		t.Fatalf("Should not have found extra event")
  1157  	}
  1158  }
  1159  
  1160  // TestUnnamedEventParam checks that an event with unnamed parameters is
  1161  // correctly handled.
  1162  // The test runs the abi of the following contract.
  1163  //
  1164  //	contract TestEvent {
  1165  //		event send(uint256, uint256);
  1166  //	}
  1167  func TestUnnamedEventParam(t *testing.T) {
  1168  	t.Parallel()
  1169  	abiJSON := `[{ "anonymous": false, "inputs": [{	"indexed": false,"internalType": "uint256",	"name": "","type": "uint256"},{"indexed": false,"internalType": "uint256","name": "","type": "uint256"}],"name": "send","type": "event"}]`
  1170  	contractAbi, err := JSON(strings.NewReader(abiJSON))
  1171  	if err != nil {
  1172  		t.Fatal(err)
  1173  	}
  1174  
  1175  	event, ok := contractAbi.Events["send"]
  1176  	if !ok {
  1177  		t.Fatalf("Could not find event")
  1178  	}
  1179  	if event.Inputs[0].Name != "arg0" {
  1180  		t.Fatalf("Could not find input")
  1181  	}
  1182  	if event.Inputs[1].Name != "arg1" {
  1183  		t.Fatalf("Could not find input")
  1184  	}
  1185  }
  1186  
  1187  func TestUnpackRevert(t *testing.T) {
  1188  	t.Parallel()
  1189  
  1190  	var cases = []struct {
  1191  		input     string
  1192  		expect    string
  1193  		expectErr error
  1194  	}{
  1195  		{"", "", errors.New("invalid data for unpacking")},
  1196  		{"08c379a1", "", errors.New("invalid data for unpacking")},
  1197  		{"08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000", "revert reason", nil},
  1198  		{"4e487b710000000000000000000000000000000000000000000000000000000000000000", "generic panic", nil},
  1199  		{"4e487b7100000000000000000000000000000000000000000000000000000000000000ff", "unknown panic code: 0xff", nil},
  1200  	}
  1201  	for index, c := range cases {
  1202  		index, c := index, c
  1203  		t.Run(fmt.Sprintf("case %d", index), func(t *testing.T) {
  1204  			t.Parallel()
  1205  			got, err := UnpackRevert(common.Hex2Bytes(c.input))
  1206  			if c.expectErr != nil {
  1207  				if err == nil {
  1208  					t.Fatalf("Expected non-nil error")
  1209  				}
  1210  				if err.Error() != c.expectErr.Error() {
  1211  					t.Fatalf("Expected error mismatch, want %v, got %v", c.expectErr, err)
  1212  				}
  1213  				return
  1214  			}
  1215  			if c.expect != got {
  1216  				t.Fatalf("Output mismatch, want %v, got %v", c.expect, got)
  1217  			}
  1218  		})
  1219  	}
  1220  }