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