github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/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  	"log"
    24  	"math/big"
    25  	"os"
    26  	"os/exec"
    27  	"strings"
    28  	"testing"
    29  
    30  	"reflect"
    31  
    32  	"github.com/ShyftNetwork/go-empyrean/common"
    33  	"github.com/ShyftNetwork/go-empyrean/crypto"
    34  )
    35  
    36  const jsondata = `
    37  [
    38  	{ "type" : "function", "name" : "balance", "constant" : true },
    39  	{ "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }
    40  ]`
    41  
    42  const jsondata2 = `
    43  [
    44  	{ "type" : "function", "name" : "balance", "constant" : true },
    45  	{ "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
    46  	{ "type" : "function", "name" : "test", "constant" : false, "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
    47  	{ "type" : "function", "name" : "string", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
    48  	{ "type" : "function", "name" : "bool", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
    49  	{ "type" : "function", "name" : "address", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
    50  	{ "type" : "function", "name" : "uint64[2]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
    51  	{ "type" : "function", "name" : "uint64[]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
    52  	{ "type" : "function", "name" : "foo", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
    53  	{ "type" : "function", "name" : "bar", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
    54  	{ "type" : "function", "name" : "slice", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
    55  	{ "type" : "function", "name" : "slice256", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
    56  	{ "type" : "function", "name" : "sliceAddress", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
    57  	{ "type" : "function", "name" : "sliceMultiAddress", "constant" : false, "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] },
    58  	{ "type" : "function", "name" : "nestedArray", "constant" : false, "inputs" : [ { "name" : "a", "type" : "uint256[2][2]" }, { "name" : "b", "type" : "address[]" } ] },
    59  	{ "type" : "function", "name" : "nestedArray2", "constant" : false, "inputs" : [ { "name" : "a", "type" : "uint8[][2]" } ] },
    60  	{ "type" : "function", "name" : "nestedSlice", "constant" : false, "inputs" : [ { "name" : "a", "type" : "uint8[][]" } ] }
    61  ]`
    62  
    63  func TestMain(m *testing.M) {
    64  	exec.Command("/bin/sh", "../shyft-cli/shyftTestDbClean.sh")
    65  	retCode := m.Run()
    66  	exec.Command("/bin/sh", "../shyft-cli/shyftTestDbClean.sh")
    67  	os.Exit(retCode)
    68  }
    69  
    70  func TestReader(t *testing.T) {
    71  	Uint256, _ := NewType("uint256", nil)
    72  	exp := ABI{
    73  		Methods: map[string]Method{
    74  			"balance": {
    75  				"balance", true, nil, nil,
    76  			},
    77  			"send": {
    78  				"send", false, []Argument{
    79  					{"amount", Uint256, false},
    80  				}, nil,
    81  			},
    82  		},
    83  	}
    84  
    85  	abi, err := JSON(strings.NewReader(jsondata))
    86  	if err != nil {
    87  		t.Error(err)
    88  	}
    89  
    90  	// deep equal fails for some reason
    91  	for name, expM := range exp.Methods {
    92  		gotM, exist := abi.Methods[name]
    93  		if !exist {
    94  			t.Errorf("Missing expected method %v", name)
    95  		}
    96  		if !reflect.DeepEqual(gotM, expM) {
    97  			t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM)
    98  		}
    99  	}
   100  
   101  	for name, gotM := range abi.Methods {
   102  		expM, exist := exp.Methods[name]
   103  		if !exist {
   104  			t.Errorf("Found extra method %v", name)
   105  		}
   106  		if !reflect.DeepEqual(gotM, expM) {
   107  			t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM)
   108  		}
   109  	}
   110  }
   111  
   112  func TestTestNumbers(t *testing.T) {
   113  	abi, err := JSON(strings.NewReader(jsondata2))
   114  	if err != nil {
   115  		t.Error(err)
   116  		t.FailNow()
   117  	}
   118  
   119  	if _, err := abi.Pack("balance"); err != nil {
   120  		t.Error(err)
   121  	}
   122  
   123  	if _, err := abi.Pack("balance", 1); err == nil {
   124  		t.Error("expected error for balance(1)")
   125  	}
   126  
   127  	if _, err := abi.Pack("doesntexist", nil); err == nil {
   128  		t.Errorf("doesntexist shouldn't exist")
   129  	}
   130  
   131  	if _, err := abi.Pack("doesntexist", 1); err == nil {
   132  		t.Errorf("doesntexist(1) shouldn't exist")
   133  	}
   134  
   135  	if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
   136  		t.Error(err)
   137  	}
   138  
   139  	i := new(int)
   140  	*i = 1000
   141  	if _, err := abi.Pack("send", i); err == nil {
   142  		t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
   143  	}
   144  
   145  	if _, err := abi.Pack("test", uint32(1000)); err != nil {
   146  		t.Error(err)
   147  	}
   148  }
   149  
   150  func TestTestString(t *testing.T) {
   151  	abi, err := JSON(strings.NewReader(jsondata2))
   152  	if err != nil {
   153  		t.Error(err)
   154  		t.FailNow()
   155  	}
   156  
   157  	if _, err := abi.Pack("string", "hello world"); err != nil {
   158  		t.Error(err)
   159  	}
   160  }
   161  
   162  func TestTestBool(t *testing.T) {
   163  	abi, err := JSON(strings.NewReader(jsondata2))
   164  	if err != nil {
   165  		t.Error(err)
   166  		t.FailNow()
   167  	}
   168  
   169  	if _, err := abi.Pack("bool", true); err != nil {
   170  		t.Error(err)
   171  	}
   172  }
   173  
   174  func TestTestSlice(t *testing.T) {
   175  	abi, err := JSON(strings.NewReader(jsondata2))
   176  	if err != nil {
   177  		t.Error(err)
   178  		t.FailNow()
   179  	}
   180  
   181  	slice := make([]uint64, 2)
   182  	if _, err := abi.Pack("uint64[2]", slice); err != nil {
   183  		t.Error(err)
   184  	}
   185  
   186  	if _, err := abi.Pack("uint64[]", slice); err != nil {
   187  		t.Error(err)
   188  	}
   189  }
   190  
   191  func TestMethodSignature(t *testing.T) {
   192  	String, _ := NewType("string", nil)
   193  	m := Method{"foo", false, []Argument{{"bar", String, false}, {"baz", String, false}}, nil}
   194  	exp := "foo(string,string)"
   195  	if m.Sig() != exp {
   196  		t.Error("signature mismatch", exp, "!=", m.Sig())
   197  	}
   198  
   199  	idexp := crypto.Keccak256([]byte(exp))[:4]
   200  	if !bytes.Equal(m.Id(), idexp) {
   201  		t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
   202  	}
   203  
   204  	uintt, _ := NewType("uint256", nil)
   205  	m = Method{"foo", false, []Argument{{"bar", uintt, false}}, nil}
   206  	exp = "foo(uint256)"
   207  	if m.Sig() != exp {
   208  		t.Error("signature mismatch", exp, "!=", m.Sig())
   209  	}
   210  
   211  	// Method with tuple arguments
   212  	s, _ := NewType("tuple", []ArgumentMarshaling{
   213  		{Name: "a", Type: "int256"},
   214  		{Name: "b", Type: "int256[]"},
   215  		{Name: "c", Type: "tuple[]", Components: []ArgumentMarshaling{
   216  			{Name: "x", Type: "int256"},
   217  			{Name: "y", Type: "int256"},
   218  		}},
   219  		{Name: "d", Type: "tuple[2]", Components: []ArgumentMarshaling{
   220  			{Name: "x", Type: "int256"},
   221  			{Name: "y", Type: "int256"},
   222  		}},
   223  	})
   224  	m = Method{"foo", false, []Argument{{"s", s, false}, {"bar", String, false}}, nil}
   225  	exp = "foo((int256,int256[],(int256,int256)[],(int256,int256)[2]),string)"
   226  	if m.Sig() != exp {
   227  		t.Error("signature mismatch", exp, "!=", m.Sig())
   228  	}
   229  }
   230  
   231  func TestMultiPack(t *testing.T) {
   232  	abi, err := JSON(strings.NewReader(jsondata2))
   233  	if err != nil {
   234  		t.Error(err)
   235  		t.FailNow()
   236  	}
   237  
   238  	sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
   239  	sig = append(sig, make([]byte, 64)...)
   240  	sig[35] = 10
   241  	sig[67] = 11
   242  
   243  	packed, err := abi.Pack("bar", uint32(10), uint16(11))
   244  	if err != nil {
   245  		t.Error(err)
   246  		t.FailNow()
   247  	}
   248  
   249  	if !bytes.Equal(packed, sig) {
   250  		t.Errorf("expected %x got %x", sig, packed)
   251  	}
   252  }
   253  
   254  func ExampleJSON() {
   255  	const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
   256  
   257  	abi, err := JSON(strings.NewReader(definition))
   258  	if err != nil {
   259  		log.Fatalln(err)
   260  	}
   261  	out, err := abi.Pack("isBar", common.HexToAddress("01"))
   262  	if err != nil {
   263  		log.Fatalln(err)
   264  	}
   265  
   266  	fmt.Printf("%x\n", out)
   267  	// Output:
   268  	// 1f2c40920000000000000000000000000000000000000000000000000000000000000001
   269  }
   270  
   271  func TestInputVariableInputLength(t *testing.T) {
   272  	const definition = `[
   273  	{ "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
   274  	{ "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
   275  	{ "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
   276  	]`
   277  
   278  	abi, err := JSON(strings.NewReader(definition))
   279  	if err != nil {
   280  		t.Fatal(err)
   281  	}
   282  
   283  	// test one string
   284  	strin := "hello world"
   285  	strpack, err := abi.Pack("strOne", strin)
   286  	if err != nil {
   287  		t.Error(err)
   288  	}
   289  
   290  	offset := make([]byte, 32)
   291  	offset[31] = 32
   292  	length := make([]byte, 32)
   293  	length[31] = byte(len(strin))
   294  	value := common.RightPadBytes([]byte(strin), 32)
   295  	exp := append(offset, append(length, value...)...)
   296  
   297  	// ignore first 4 bytes of the output. This is the function identifier
   298  	strpack = strpack[4:]
   299  	if !bytes.Equal(strpack, exp) {
   300  		t.Errorf("expected %x, got %x\n", exp, strpack)
   301  	}
   302  
   303  	// test one bytes
   304  	btspack, err := abi.Pack("bytesOne", []byte(strin))
   305  	if err != nil {
   306  		t.Error(err)
   307  	}
   308  	// ignore first 4 bytes of the output. This is the function identifier
   309  	btspack = btspack[4:]
   310  	if !bytes.Equal(btspack, exp) {
   311  		t.Errorf("expected %x, got %x\n", exp, btspack)
   312  	}
   313  
   314  	//  test two strings
   315  	str1 := "hello"
   316  	str2 := "world"
   317  	str2pack, err := abi.Pack("strTwo", str1, str2)
   318  	if err != nil {
   319  		t.Error(err)
   320  	}
   321  
   322  	offset1 := make([]byte, 32)
   323  	offset1[31] = 64
   324  	length1 := make([]byte, 32)
   325  	length1[31] = byte(len(str1))
   326  	value1 := common.RightPadBytes([]byte(str1), 32)
   327  
   328  	offset2 := make([]byte, 32)
   329  	offset2[31] = 128
   330  	length2 := make([]byte, 32)
   331  	length2[31] = byte(len(str2))
   332  	value2 := common.RightPadBytes([]byte(str2), 32)
   333  
   334  	exp2 := append(offset1, offset2...)
   335  	exp2 = append(exp2, append(length1, value1...)...)
   336  	exp2 = append(exp2, append(length2, value2...)...)
   337  
   338  	// ignore first 4 bytes of the output. This is the function identifier
   339  	str2pack = str2pack[4:]
   340  	if !bytes.Equal(str2pack, exp2) {
   341  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   342  	}
   343  
   344  	// test two strings, first > 32, second < 32
   345  	str1 = strings.Repeat("a", 33)
   346  	str2pack, err = abi.Pack("strTwo", str1, str2)
   347  	if err != nil {
   348  		t.Error(err)
   349  	}
   350  
   351  	offset1 = make([]byte, 32)
   352  	offset1[31] = 64
   353  	length1 = make([]byte, 32)
   354  	length1[31] = byte(len(str1))
   355  	value1 = common.RightPadBytes([]byte(str1), 64)
   356  	offset2[31] = 160
   357  
   358  	exp2 = append(offset1, offset2...)
   359  	exp2 = append(exp2, append(length1, value1...)...)
   360  	exp2 = append(exp2, append(length2, value2...)...)
   361  
   362  	// ignore first 4 bytes of the output. This is the function identifier
   363  	str2pack = str2pack[4:]
   364  	if !bytes.Equal(str2pack, exp2) {
   365  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   366  	}
   367  
   368  	// test two strings, first > 32, second >32
   369  	str1 = strings.Repeat("a", 33)
   370  	str2 = strings.Repeat("a", 33)
   371  	str2pack, err = abi.Pack("strTwo", str1, str2)
   372  	if err != nil {
   373  		t.Error(err)
   374  	}
   375  
   376  	offset1 = make([]byte, 32)
   377  	offset1[31] = 64
   378  	length1 = make([]byte, 32)
   379  	length1[31] = byte(len(str1))
   380  	value1 = common.RightPadBytes([]byte(str1), 64)
   381  
   382  	offset2 = make([]byte, 32)
   383  	offset2[31] = 160
   384  	length2 = make([]byte, 32)
   385  	length2[31] = byte(len(str2))
   386  	value2 = common.RightPadBytes([]byte(str2), 64)
   387  
   388  	exp2 = append(offset1, offset2...)
   389  	exp2 = append(exp2, append(length1, value1...)...)
   390  	exp2 = append(exp2, append(length2, value2...)...)
   391  
   392  	// ignore first 4 bytes of the output. This is the function identifier
   393  	str2pack = str2pack[4:]
   394  	if !bytes.Equal(str2pack, exp2) {
   395  		t.Errorf("expected %x, got %x\n", exp, str2pack)
   396  	}
   397  }
   398  
   399  func TestInputFixedArrayAndVariableInputLength(t *testing.T) {
   400  	const definition = `[
   401  	{ "type" : "function", "name" : "fixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] },
   402  	{ "type" : "function", "name" : "fixedArrBytes", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] },
   403      { "type" : "function", "name" : "mixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type": "uint256[2]" }, { "name" : "dynArr", "type": "uint256[]" } ] },
   404      { "type" : "function", "name" : "doubleFixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type": "uint256[2]" }, { "name" : "fixedArr2", "type": "uint256[3]" } ] },
   405      { "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]" } ] }
   406  	]`
   407  
   408  	abi, err := JSON(strings.NewReader(definition))
   409  	if err != nil {
   410  		t.Error(err)
   411  	}
   412  
   413  	// test string, fixed array uint256[2]
   414  	strin := "hello world"
   415  	arrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   416  	fixedArrStrPack, err := abi.Pack("fixedArrStr", strin, arrin)
   417  	if err != nil {
   418  		t.Error(err)
   419  	}
   420  
   421  	// generate expected output
   422  	offset := make([]byte, 32)
   423  	offset[31] = 96
   424  	length := make([]byte, 32)
   425  	length[31] = byte(len(strin))
   426  	strvalue := common.RightPadBytes([]byte(strin), 32)
   427  	arrinvalue1 := common.LeftPadBytes(arrin[0].Bytes(), 32)
   428  	arrinvalue2 := common.LeftPadBytes(arrin[1].Bytes(), 32)
   429  	exp := append(offset, arrinvalue1...)
   430  	exp = append(exp, arrinvalue2...)
   431  	exp = append(exp, append(length, strvalue...)...)
   432  
   433  	// ignore first 4 bytes of the output. This is the function identifier
   434  	fixedArrStrPack = fixedArrStrPack[4:]
   435  	if !bytes.Equal(fixedArrStrPack, exp) {
   436  		t.Errorf("expected %x, got %x\n", exp, fixedArrStrPack)
   437  	}
   438  
   439  	// test byte array, fixed array uint256[2]
   440  	bytesin := []byte(strin)
   441  	arrin = [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   442  	fixedArrBytesPack, err := abi.Pack("fixedArrBytes", bytesin, arrin)
   443  	if err != nil {
   444  		t.Error(err)
   445  	}
   446  
   447  	// generate expected output
   448  	offset = make([]byte, 32)
   449  	offset[31] = 96
   450  	length = make([]byte, 32)
   451  	length[31] = byte(len(strin))
   452  	strvalue = common.RightPadBytes([]byte(strin), 32)
   453  	arrinvalue1 = common.LeftPadBytes(arrin[0].Bytes(), 32)
   454  	arrinvalue2 = common.LeftPadBytes(arrin[1].Bytes(), 32)
   455  	exp = append(offset, arrinvalue1...)
   456  	exp = append(exp, arrinvalue2...)
   457  	exp = append(exp, append(length, strvalue...)...)
   458  
   459  	// ignore first 4 bytes of the output. This is the function identifier
   460  	fixedArrBytesPack = fixedArrBytesPack[4:]
   461  	if !bytes.Equal(fixedArrBytesPack, exp) {
   462  		t.Errorf("expected %x, got %x\n", exp, fixedArrBytesPack)
   463  	}
   464  
   465  	// test string, fixed array uint256[2], dynamic array uint256[]
   466  	strin = "hello world"
   467  	fixedarrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   468  	dynarrin := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   469  	mixedArrStrPack, err := abi.Pack("mixedArrStr", strin, fixedarrin, dynarrin)
   470  	if err != nil {
   471  		t.Error(err)
   472  	}
   473  
   474  	// generate expected output
   475  	stroffset := make([]byte, 32)
   476  	stroffset[31] = 128
   477  	strlength := make([]byte, 32)
   478  	strlength[31] = byte(len(strin))
   479  	strvalue = common.RightPadBytes([]byte(strin), 32)
   480  	fixedarrinvalue1 := common.LeftPadBytes(fixedarrin[0].Bytes(), 32)
   481  	fixedarrinvalue2 := common.LeftPadBytes(fixedarrin[1].Bytes(), 32)
   482  	dynarroffset := make([]byte, 32)
   483  	dynarroffset[31] = byte(160 + ((len(strin)/32)+1)*32)
   484  	dynarrlength := make([]byte, 32)
   485  	dynarrlength[31] = byte(len(dynarrin))
   486  	dynarrinvalue1 := common.LeftPadBytes(dynarrin[0].Bytes(), 32)
   487  	dynarrinvalue2 := common.LeftPadBytes(dynarrin[1].Bytes(), 32)
   488  	dynarrinvalue3 := common.LeftPadBytes(dynarrin[2].Bytes(), 32)
   489  	exp = append(stroffset, fixedarrinvalue1...)
   490  	exp = append(exp, fixedarrinvalue2...)
   491  	exp = append(exp, dynarroffset...)
   492  	exp = append(exp, append(strlength, strvalue...)...)
   493  	dynarrarg := append(dynarrlength, dynarrinvalue1...)
   494  	dynarrarg = append(dynarrarg, dynarrinvalue2...)
   495  	dynarrarg = append(dynarrarg, dynarrinvalue3...)
   496  	exp = append(exp, dynarrarg...)
   497  
   498  	// ignore first 4 bytes of the output. This is the function identifier
   499  	mixedArrStrPack = mixedArrStrPack[4:]
   500  	if !bytes.Equal(mixedArrStrPack, exp) {
   501  		t.Errorf("expected %x, got %x\n", exp, mixedArrStrPack)
   502  	}
   503  
   504  	// test string, fixed array uint256[2], fixed array uint256[3]
   505  	strin = "hello world"
   506  	fixedarrin1 := [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   507  	fixedarrin2 := [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   508  	doubleFixedArrStrPack, err := abi.Pack("doubleFixedArrStr", strin, fixedarrin1, fixedarrin2)
   509  	if err != nil {
   510  		t.Error(err)
   511  	}
   512  
   513  	// generate expected output
   514  	stroffset = make([]byte, 32)
   515  	stroffset[31] = 192
   516  	strlength = make([]byte, 32)
   517  	strlength[31] = byte(len(strin))
   518  	strvalue = common.RightPadBytes([]byte(strin), 32)
   519  	fixedarrin1value1 := common.LeftPadBytes(fixedarrin1[0].Bytes(), 32)
   520  	fixedarrin1value2 := common.LeftPadBytes(fixedarrin1[1].Bytes(), 32)
   521  	fixedarrin2value1 := common.LeftPadBytes(fixedarrin2[0].Bytes(), 32)
   522  	fixedarrin2value2 := common.LeftPadBytes(fixedarrin2[1].Bytes(), 32)
   523  	fixedarrin2value3 := common.LeftPadBytes(fixedarrin2[2].Bytes(), 32)
   524  	exp = append(stroffset, fixedarrin1value1...)
   525  	exp = append(exp, fixedarrin1value2...)
   526  	exp = append(exp, fixedarrin2value1...)
   527  	exp = append(exp, fixedarrin2value2...)
   528  	exp = append(exp, fixedarrin2value3...)
   529  	exp = append(exp, append(strlength, strvalue...)...)
   530  
   531  	// ignore first 4 bytes of the output. This is the function identifier
   532  	doubleFixedArrStrPack = doubleFixedArrStrPack[4:]
   533  	if !bytes.Equal(doubleFixedArrStrPack, exp) {
   534  		t.Errorf("expected %x, got %x\n", exp, doubleFixedArrStrPack)
   535  	}
   536  
   537  	// test string, fixed array uint256[2], dynamic array uint256[], fixed array uint256[3]
   538  	strin = "hello world"
   539  	fixedarrin1 = [2]*big.Int{big.NewInt(1), big.NewInt(2)}
   540  	dynarrin = []*big.Int{big.NewInt(1), big.NewInt(2)}
   541  	fixedarrin2 = [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}
   542  	multipleMixedArrStrPack, err := abi.Pack("multipleMixedArrStr", strin, fixedarrin1, dynarrin, fixedarrin2)
   543  	if err != nil {
   544  		t.Error(err)
   545  	}
   546  
   547  	// generate expected output
   548  	stroffset = make([]byte, 32)
   549  	stroffset[31] = 224
   550  	strlength = make([]byte, 32)
   551  	strlength[31] = byte(len(strin))
   552  	strvalue = common.RightPadBytes([]byte(strin), 32)
   553  	fixedarrin1value1 = common.LeftPadBytes(fixedarrin1[0].Bytes(), 32)
   554  	fixedarrin1value2 = common.LeftPadBytes(fixedarrin1[1].Bytes(), 32)
   555  	dynarroffset = U256(big.NewInt(int64(256 + ((len(strin)/32)+1)*32)))
   556  	dynarrlength = make([]byte, 32)
   557  	dynarrlength[31] = byte(len(dynarrin))
   558  	dynarrinvalue1 = common.LeftPadBytes(dynarrin[0].Bytes(), 32)
   559  	dynarrinvalue2 = common.LeftPadBytes(dynarrin[1].Bytes(), 32)
   560  	fixedarrin2value1 = common.LeftPadBytes(fixedarrin2[0].Bytes(), 32)
   561  	fixedarrin2value2 = common.LeftPadBytes(fixedarrin2[1].Bytes(), 32)
   562  	fixedarrin2value3 = common.LeftPadBytes(fixedarrin2[2].Bytes(), 32)
   563  	exp = append(stroffset, fixedarrin1value1...)
   564  	exp = append(exp, fixedarrin1value2...)
   565  	exp = append(exp, dynarroffset...)
   566  	exp = append(exp, fixedarrin2value1...)
   567  	exp = append(exp, fixedarrin2value2...)
   568  	exp = append(exp, fixedarrin2value3...)
   569  	exp = append(exp, append(strlength, strvalue...)...)
   570  	dynarrarg = append(dynarrlength, dynarrinvalue1...)
   571  	dynarrarg = append(dynarrarg, dynarrinvalue2...)
   572  	exp = append(exp, dynarrarg...)
   573  
   574  	// ignore first 4 bytes of the output. This is the function identifier
   575  	multipleMixedArrStrPack = multipleMixedArrStrPack[4:]
   576  	if !bytes.Equal(multipleMixedArrStrPack, exp) {
   577  		t.Errorf("expected %x, got %x\n", exp, multipleMixedArrStrPack)
   578  	}
   579  }
   580  
   581  func TestDefaultFunctionParsing(t *testing.T) {
   582  	const definition = `[{ "name" : "balance" }]`
   583  
   584  	abi, err := JSON(strings.NewReader(definition))
   585  	if err != nil {
   586  		t.Fatal(err)
   587  	}
   588  
   589  	if _, ok := abi.Methods["balance"]; !ok {
   590  		t.Error("expected 'balance' to be present")
   591  	}
   592  }
   593  
   594  func TestBareEvents(t *testing.T) {
   595  	const definition = `[
   596  	{ "type" : "event", "name" : "balance" },
   597  	{ "type" : "event", "name" : "anon", "anonymous" : true},
   598  	{ "type" : "event", "name" : "args", "inputs" : [{ "indexed":false, "name":"arg0", "type":"uint256" }, { "indexed":true, "name":"arg1", "type":"address" }] },
   599  	{ "type" : "event", "name" : "tuple", "inputs" : [{ "indexed":false, "name":"t", "type":"tuple", "components":[{"name":"a", "type":"uint256"}] }, { "indexed":true, "name":"arg1", "type":"address" }] }
   600  	]`
   601  
   602  	arg0, _ := NewType("uint256", nil)
   603  	arg1, _ := NewType("address", nil)
   604  	tuple, _ := NewType("tuple", []ArgumentMarshaling{{Name: "a", Type: "uint256"}})
   605  
   606  	expectedEvents := map[string]struct {
   607  		Anonymous bool
   608  		Args      []Argument
   609  	}{
   610  		"balance": {false, nil},
   611  		"anon":    {true, nil},
   612  		"args": {false, []Argument{
   613  			{Name: "arg0", Type: arg0, Indexed: false},
   614  			{Name: "arg1", Type: arg1, Indexed: true},
   615  		}},
   616  		"tuple": {false, []Argument{
   617  			{Name: "t", Type: tuple, Indexed: false},
   618  			{Name: "arg1", Type: arg1, Indexed: true},
   619  		}},
   620  	}
   621  
   622  	abi, err := JSON(strings.NewReader(definition))
   623  	if err != nil {
   624  		t.Fatal(err)
   625  	}
   626  
   627  	if len(abi.Events) != len(expectedEvents) {
   628  		t.Fatalf("invalid number of events after parsing, want %d, got %d", len(expectedEvents), len(abi.Events))
   629  	}
   630  
   631  	for name, exp := range expectedEvents {
   632  		got, ok := abi.Events[name]
   633  		if !ok {
   634  			t.Errorf("could not found event %s", name)
   635  			continue
   636  		}
   637  		if got.Anonymous != exp.Anonymous {
   638  			t.Errorf("invalid anonymous indication for event %s, want %v, got %v", name, exp.Anonymous, got.Anonymous)
   639  		}
   640  		if len(got.Inputs) != len(exp.Args) {
   641  			t.Errorf("invalid number of args, want %d, got %d", len(exp.Args), len(got.Inputs))
   642  			continue
   643  		}
   644  		for i, arg := range exp.Args {
   645  			if arg.Name != got.Inputs[i].Name {
   646  				t.Errorf("events[%s].Input[%d] has an invalid name, want %s, got %s", name, i, arg.Name, got.Inputs[i].Name)
   647  			}
   648  			if arg.Indexed != got.Inputs[i].Indexed {
   649  				t.Errorf("events[%s].Input[%d] has an invalid indexed indication, want %v, got %v", name, i, arg.Indexed, got.Inputs[i].Indexed)
   650  			}
   651  			if arg.Type.T != got.Inputs[i].Type.T {
   652  				t.Errorf("events[%s].Input[%d] has an invalid type, want %x, got %x", name, i, arg.Type.T, got.Inputs[i].Type.T)
   653  			}
   654  		}
   655  	}
   656  }
   657  
   658  // TestUnpackEvent is based on this contract:
   659  //    contract T {
   660  //      event received(address sender, uint amount, bytes memo);
   661  //      event receivedAddr(address sender);
   662  //      function receive(bytes memo) external payable {
   663  //        received(msg.sender, msg.value, memo);
   664  //        receivedAddr(msg.sender);
   665  //      }
   666  //    }
   667  // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
   668  //   receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
   669  func TestUnpackEvent(t *testing.T) {
   670  	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"}]`
   671  	abi, err := JSON(strings.NewReader(abiJSON))
   672  	if err != nil {
   673  		t.Fatal(err)
   674  	}
   675  
   676  	const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158`
   677  	data, err := hex.DecodeString(hexdata)
   678  	if err != nil {
   679  		t.Fatal(err)
   680  	}
   681  	if len(data)%32 == 0 {
   682  		t.Errorf("len(data) is %d, want a non-multiple of 32", len(data))
   683  	}
   684  
   685  	type ReceivedEvent struct {
   686  		Sender common.Address
   687  		Amount *big.Int
   688  		Memo   []byte
   689  	}
   690  	var ev ReceivedEvent
   691  
   692  	err = abi.Unpack(&ev, "received", data)
   693  	if err != nil {
   694  		t.Error(err)
   695  	}
   696  
   697  	type ReceivedAddrEvent struct {
   698  		Sender common.Address
   699  	}
   700  	var receivedAddrEv ReceivedAddrEvent
   701  	err = abi.Unpack(&receivedAddrEv, "receivedAddr", data)
   702  	if err != nil {
   703  		t.Error(err)
   704  	}
   705  }
   706  
   707  func TestABI_MethodById(t *testing.T) {
   708  	const abiJSON = `[
   709  		{"type":"function","name":"receive","constant":false,"inputs":[{"name":"memo","type":"bytes"}],"outputs":[],"payable":true,"stateMutability":"payable"},
   710  		{"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"}]},
   711  		{"type":"function","name":"fixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr","type":"uint256[2]"}]},
   712  		{"type":"function","name":"fixedArrBytes","constant":true,"inputs":[{"name":"str","type":"bytes"},{"name":"fixedArr","type":"uint256[2]"}]},
   713  		{"type":"function","name":"mixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr","type":"uint256[2]"},{"name":"dynArr","type":"uint256[]"}]},
   714  		{"type":"function","name":"doubleFixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr1","type":"uint256[2]"},{"name":"fixedArr2","type":"uint256[3]"}]},
   715  		{"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]"}]},
   716  		{"type":"function","name":"balance","constant":true},
   717  		{"type":"function","name":"send","constant":false,"inputs":[{"name":"amount","type":"uint256"}]},
   718  		{"type":"function","name":"test","constant":false,"inputs":[{"name":"number","type":"uint32"}]},
   719  		{"type":"function","name":"string","constant":false,"inputs":[{"name":"inputs","type":"string"}]},
   720  		{"type":"function","name":"bool","constant":false,"inputs":[{"name":"inputs","type":"bool"}]},
   721  		{"type":"function","name":"address","constant":false,"inputs":[{"name":"inputs","type":"address"}]},
   722  		{"type":"function","name":"uint64[2]","constant":false,"inputs":[{"name":"inputs","type":"uint64[2]"}]},
   723  		{"type":"function","name":"uint64[]","constant":false,"inputs":[{"name":"inputs","type":"uint64[]"}]},
   724  		{"type":"function","name":"foo","constant":false,"inputs":[{"name":"inputs","type":"uint32"}]},
   725  		{"type":"function","name":"bar","constant":false,"inputs":[{"name":"inputs","type":"uint32"},{"name":"string","type":"uint16"}]},
   726  		{"type":"function","name":"_slice","constant":false,"inputs":[{"name":"inputs","type":"uint32[2]"}]},
   727  		{"type":"function","name":"__slice256","constant":false,"inputs":[{"name":"inputs","type":"uint256[2]"}]},
   728  		{"type":"function","name":"sliceAddress","constant":false,"inputs":[{"name":"inputs","type":"address[]"}]},
   729  		{"type":"function","name":"sliceMultiAddress","constant":false,"inputs":[{"name":"a","type":"address[]"},{"name":"b","type":"address[]"}]}
   730  	]
   731  `
   732  	abi, err := JSON(strings.NewReader(abiJSON))
   733  	if err != nil {
   734  		t.Fatal(err)
   735  	}
   736  	for name, m := range abi.Methods {
   737  		a := fmt.Sprintf("%v", m)
   738  		m2, err := abi.MethodById(m.Id())
   739  		if err != nil {
   740  			t.Fatalf("Failed to look up ABI method: %v", err)
   741  		}
   742  		b := fmt.Sprintf("%v", m2)
   743  		if a != b {
   744  			t.Errorf("Method %v (id %v) not 'findable' by id in ABI", name, common.ToHex(m.Id()))
   745  		}
   746  	}
   747  	// Also test empty
   748  	if _, err := abi.MethodById([]byte{0x00}); err == nil {
   749  		t.Errorf("Expected error, too short to decode data")
   750  	}
   751  	if _, err := abi.MethodById([]byte{}); err == nil {
   752  		t.Errorf("Expected error, too short to decode data")
   753  	}
   754  	if _, err := abi.MethodById(nil); err == nil {
   755  		t.Errorf("Expected error, nil is short to decode data")
   756  	}
   757  }