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