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