github.com/core-coin/go-core/v2@v2.1.9/accounts/abi/abi_test.go (about)

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