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