github.com/kapoio/go-kapoio@v1.9.7/accounts/abi/abi_test.go (about)

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