github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/accounts/abi/abi_test.go (about)

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