github.com/dim4egster/coreth@v0.10.2/accounts/abi/abi_test.go (about)

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