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