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