github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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 "fmt" 22 "log" 23 "math/big" 24 "reflect" 25 "strings" 26 "testing" 27 28 "github.com/ethereumproject/go-ethereum/common" 29 "github.com/ethereumproject/go-ethereum/crypto" 30 ) 31 32 // formatSilceOutput add padding to the value and adds a size 33 func formatSliceOutput(v ...[]byte) []byte { 34 off := common.LeftPadBytes(big.NewInt(int64(len(v))).Bytes(), 32) 35 output := append(off, make([]byte, 0, len(v)*32)...) 36 37 for _, value := range v { 38 output = append(output, common.LeftPadBytes(value, 32)...) 39 } 40 return output 41 } 42 43 // quick helper padding 44 func pad(input []byte, size int, left bool) []byte { 45 if left { 46 return common.LeftPadBytes(input, size) 47 } 48 return common.RightPadBytes(input, size) 49 } 50 51 func TestTypeCheck(t *testing.T) { 52 for i, test := range []struct { 53 typ string 54 input interface{} 55 err string 56 }{ 57 {"uint", big.NewInt(1), ""}, 58 {"int", big.NewInt(1), ""}, 59 {"uint30", big.NewInt(1), ""}, 60 {"uint30", uint8(1), "abi: cannot use uint8 as type ptr as argument"}, 61 {"uint16", uint16(1), ""}, 62 {"uint16", uint8(1), "abi: cannot use uint8 as type uint16 as argument"}, 63 {"uint16[]", []uint16{1, 2, 3}, ""}, 64 {"uint16[]", [3]uint16{1, 2, 3}, ""}, 65 {"uint16[]", []uint32{1, 2, 3}, "abi: cannot use []uint32 as type []uint16 as argument"}, 66 {"uint16[3]", [3]uint32{1, 2, 3}, "abi: cannot use [3]uint32 as type [3]uint16 as argument"}, 67 {"uint16[3]", [4]uint16{1, 2, 3}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"}, 68 {"uint16[3]", []uint16{1, 2, 3}, ""}, 69 {"uint16[3]", []uint16{1, 2, 3, 4}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"}, 70 {"address[]", []common.Address{{1}}, ""}, 71 {"address[1]", []common.Address{{1}}, ""}, 72 {"address[1]", [1]common.Address{{1}}, ""}, 73 {"address[2]", [1]common.Address{{1}}, "abi: cannot use [1]array as type [2]array as argument"}, 74 {"bytes32", [32]byte{}, ""}, 75 {"bytes32", [33]byte{}, "abi: cannot use [33]uint8 as type [32]uint8 as argument"}, 76 {"bytes32", common.Hash{1}, ""}, 77 {"bytes31", [31]byte{}, ""}, 78 {"bytes31", [32]byte{}, "abi: cannot use [32]uint8 as type [31]uint8 as argument"}, 79 {"bytes", []byte{0, 1}, ""}, 80 {"bytes", [2]byte{0, 1}, ""}, 81 {"bytes", common.Hash{1}, ""}, 82 {"string", "hello world", ""}, 83 {"bytes32[]", [][32]byte{{}}, ""}, 84 } { 85 typ, err := NewType(test.typ) 86 if err != nil { 87 t.Fatal("unexpected parse error:", err) 88 } 89 90 err = typeCheck(typ, reflect.ValueOf(test.input)) 91 if err != nil && len(test.err) == 0 { 92 t.Errorf("%d failed. Expected no err but got: %v", i, err) 93 continue 94 } 95 if err == nil && len(test.err) != 0 { 96 t.Errorf("%d failed. Expected err: %v but got none", i, test.err) 97 continue 98 } 99 100 if err != nil && len(test.err) != 0 && err.Error() != test.err { 101 t.Errorf("%d failed. Expected err: '%v' got err: '%v'", i, test.err, err) 102 } 103 } 104 } 105 106 func TestSimpleMethodUnpack(t *testing.T) { 107 for i, test := range []struct { 108 def string // definition of the **output** ABI params 109 marshalledOutput []byte // evm return data 110 expectedOut interface{} // the expected output 111 outVar string // the output variable (e.g. uint32, *big.Int, etc) 112 err string // empty or error if expected 113 }{ 114 { 115 `[ { "type": "uint32" } ]`, 116 pad([]byte{1}, 32, true), 117 uint32(1), 118 "uint32", 119 "", 120 }, 121 { 122 `[ { "type": "uint32" } ]`, 123 pad([]byte{1}, 32, true), 124 nil, 125 "uint16", 126 "abi: cannot unmarshal uint32 in to uint16", 127 }, 128 { 129 `[ { "type": "uint17" } ]`, 130 pad([]byte{1}, 32, true), 131 nil, 132 "uint16", 133 "abi: cannot unmarshal *big.Int in to uint16", 134 }, 135 { 136 `[ { "type": "uint17" } ]`, 137 pad([]byte{1}, 32, true), 138 big.NewInt(1), 139 "*big.Int", 140 "", 141 }, 142 143 { 144 `[ { "type": "int32" } ]`, 145 pad([]byte{1}, 32, true), 146 int32(1), 147 "int32", 148 "", 149 }, 150 { 151 `[ { "type": "int32" } ]`, 152 pad([]byte{1}, 32, true), 153 nil, 154 "int16", 155 "abi: cannot unmarshal int32 in to int16", 156 }, 157 { 158 `[ { "type": "int17" } ]`, 159 pad([]byte{1}, 32, true), 160 nil, 161 "int16", 162 "abi: cannot unmarshal *big.Int in to int16", 163 }, 164 { 165 `[ { "type": "int17" } ]`, 166 pad([]byte{1}, 32, true), 167 big.NewInt(1), 168 "*big.Int", 169 "", 170 }, 171 172 { 173 `[ { "type": "address" } ]`, 174 pad(pad([]byte{1}, 20, false), 32, true), 175 common.Address{1}, 176 "address", 177 "", 178 }, 179 { 180 `[ { "type": "bytes32" } ]`, 181 pad([]byte{1}, 32, false), 182 pad([]byte{1}, 32, false), 183 "bytes", 184 "", 185 }, 186 { 187 `[ { "type": "bytes32" } ]`, 188 pad([]byte{1}, 32, false), 189 pad([]byte{1}, 32, false), 190 "hash", 191 "", 192 }, 193 { 194 `[ { "type": "bytes32" } ]`, 195 pad([]byte{1}, 32, false), 196 pad([]byte{1}, 32, false), 197 "interface", 198 "", 199 }, 200 } { 201 abiDefinition := fmt.Sprintf(`[{ "name" : "method", "outputs": %s}]`, test.def) 202 abi, err := JSON(strings.NewReader(abiDefinition)) 203 if err != nil { 204 t.Errorf("%d failed. %v", i, err) 205 continue 206 } 207 208 var outvar interface{} 209 switch test.outVar { 210 case "uint8": 211 var v uint8 212 err = abi.Unpack(&v, "method", test.marshalledOutput) 213 outvar = v 214 case "uint16": 215 var v uint16 216 err = abi.Unpack(&v, "method", test.marshalledOutput) 217 outvar = v 218 case "uint32": 219 var v uint32 220 err = abi.Unpack(&v, "method", test.marshalledOutput) 221 outvar = v 222 case "uint64": 223 var v uint64 224 err = abi.Unpack(&v, "method", test.marshalledOutput) 225 outvar = v 226 case "int8": 227 var v int8 228 err = abi.Unpack(&v, "method", test.marshalledOutput) 229 outvar = v 230 case "int16": 231 var v int16 232 err = abi.Unpack(&v, "method", test.marshalledOutput) 233 outvar = v 234 case "int32": 235 var v int32 236 err = abi.Unpack(&v, "method", test.marshalledOutput) 237 outvar = v 238 case "int64": 239 var v int64 240 err = abi.Unpack(&v, "method", test.marshalledOutput) 241 outvar = v 242 case "*big.Int": 243 var v *big.Int 244 err = abi.Unpack(&v, "method", test.marshalledOutput) 245 outvar = v 246 case "address": 247 var v common.Address 248 err = abi.Unpack(&v, "method", test.marshalledOutput) 249 outvar = v 250 case "bytes": 251 var v []byte 252 err = abi.Unpack(&v, "method", test.marshalledOutput) 253 outvar = v 254 case "hash": 255 var v common.Hash 256 err = abi.Unpack(&v, "method", test.marshalledOutput) 257 outvar = v 258 case "interface": 259 err = abi.Unpack(&outvar, "method", test.marshalledOutput) 260 default: 261 t.Errorf("unsupported type '%v' please add it to the switch statement in this test", test.outVar) 262 continue 263 } 264 265 if err != nil && len(test.err) == 0 { 266 t.Errorf("%d failed. Expected no err but got: %v", i, err) 267 continue 268 } 269 if err == nil && len(test.err) != 0 { 270 t.Errorf("%d failed. Expected err: %v but got none", i, test.err) 271 continue 272 } 273 if err != nil && len(test.err) != 0 && err.Error() != test.err { 274 t.Errorf("%d failed. Expected err: '%v' got err: '%v'", i, test.err, err) 275 continue 276 } 277 278 if err == nil { 279 // bit of an ugly hack for hash type but I don't feel like finding a proper solution 280 if test.outVar == "hash" { 281 tmp := outvar.(common.Hash) // without assignment it's unaddressable 282 outvar = tmp[:] 283 } 284 285 if !reflect.DeepEqual(test.expectedOut, outvar) { 286 t.Errorf("%d failed. Output error: expected %v, got %v", i, test.expectedOut, outvar) 287 } 288 } 289 } 290 } 291 292 func TestUnpackSetInterfaceSlice(t *testing.T) { 293 var ( 294 var1 = new(uint8) 295 var2 = new(uint8) 296 ) 297 out := []interface{}{var1, var2} 298 abi, err := JSON(strings.NewReader(`[{"type":"function", "name":"ints", "outputs":[{"type":"uint8"}, {"type":"uint8"}]}]`)) 299 if err != nil { 300 t.Fatal(err) 301 } 302 marshalledReturn := append(pad([]byte{1}, 32, true), pad([]byte{2}, 32, true)...) 303 err = abi.Unpack(&out, "ints", marshalledReturn) 304 if err != nil { 305 t.Fatal(err) 306 } 307 if *var1 != 1 { 308 t.Error("expected var1 to be 1, got", *var1) 309 } 310 if *var2 != 2 { 311 t.Error("expected var2 to be 2, got", *var2) 312 } 313 314 out = []interface{}{var1} 315 err = abi.Unpack(&out, "ints", marshalledReturn) 316 317 expErr := "abi: cannot marshal in to slices of unequal size (require: 2, got: 1)" 318 if err == nil || err.Error() != expErr { 319 t.Error("expected err:", expErr, "Got:", err) 320 } 321 } 322 323 func TestPack(t *testing.T) { 324 for i, test := range []struct { 325 typ string 326 327 input interface{} 328 output []byte 329 }{ 330 {"uint16", uint16(2), pad([]byte{2}, 32, true)}, 331 {"uint16[]", []uint16{1, 2}, formatSliceOutput([]byte{1}, []byte{2})}, 332 {"bytes20", [20]byte{1}, pad([]byte{1}, 32, false)}, 333 {"uint256[]", []*big.Int{big.NewInt(1), big.NewInt(2)}, formatSliceOutput([]byte{1}, []byte{2})}, 334 {"address[]", []common.Address{{1}, {2}}, formatSliceOutput(pad([]byte{1}, 20, false), pad([]byte{2}, 20, false))}, 335 {"bytes32[]", []common.Hash{{1}, {2}}, formatSliceOutput(pad([]byte{1}, 32, false), pad([]byte{2}, 32, false))}, 336 } { 337 typ, err := NewType(test.typ) 338 if err != nil { 339 t.Fatal("unexpected parse error:", err) 340 } 341 342 output, err := typ.pack(reflect.ValueOf(test.input)) 343 if err != nil { 344 t.Fatal("unexpected pack error:", err) 345 } 346 347 if !bytes.Equal(output, test.output) { 348 t.Errorf("%d failed. Expected bytes: '%x' Got: '%x'", i, test.output, output) 349 } 350 } 351 } 352 353 func TestMethodPack(t *testing.T) { 354 abi, err := JSON(strings.NewReader(jsondata2)) 355 if err != nil { 356 t.Fatal(err) 357 } 358 359 sig := abi.Methods["slice"].Id() 360 sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...) 361 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 362 sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...) 363 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 364 365 packed, err := abi.Pack("slice", []uint32{1, 2}) 366 if err != nil { 367 t.Error(err) 368 } 369 370 if !bytes.Equal(packed, sig) { 371 t.Errorf("expected %x got %x", sig, packed) 372 } 373 374 var addrA, addrB = common.Address{1}, common.Address{2} 375 sig = abi.Methods["sliceAddress"].Id() 376 sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...) 377 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 378 sig = append(sig, common.LeftPadBytes(addrA[:], 32)...) 379 sig = append(sig, common.LeftPadBytes(addrB[:], 32)...) 380 381 packed, err = abi.Pack("sliceAddress", []common.Address{addrA, addrB}) 382 if err != nil { 383 t.Fatal(err) 384 } 385 if !bytes.Equal(packed, sig) { 386 t.Errorf("expected %x got %x", sig, packed) 387 } 388 389 var addrC, addrD = common.Address{3}, common.Address{4} 390 sig = abi.Methods["sliceMultiAddress"].Id() 391 sig = append(sig, common.LeftPadBytes([]byte{64}, 32)...) 392 sig = append(sig, common.LeftPadBytes([]byte{160}, 32)...) 393 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 394 sig = append(sig, common.LeftPadBytes(addrA[:], 32)...) 395 sig = append(sig, common.LeftPadBytes(addrB[:], 32)...) 396 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 397 sig = append(sig, common.LeftPadBytes(addrC[:], 32)...) 398 sig = append(sig, common.LeftPadBytes(addrD[:], 32)...) 399 400 packed, err = abi.Pack("sliceMultiAddress", []common.Address{addrA, addrB}, []common.Address{addrC, addrD}) 401 if err != nil { 402 t.Fatal(err) 403 } 404 if !bytes.Equal(packed, sig) { 405 t.Errorf("expected %x got %x", sig, packed) 406 } 407 408 sig = abi.Methods["slice256"].Id() 409 sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...) 410 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 411 sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...) 412 sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...) 413 414 packed, err = abi.Pack("slice256", []*big.Int{big.NewInt(1), big.NewInt(2)}) 415 if err != nil { 416 t.Error(err) 417 } 418 419 if !bytes.Equal(packed, sig) { 420 t.Errorf("expected %x got %x", sig, packed) 421 } 422 } 423 424 const jsondata = ` 425 [ 426 { "type" : "function", "name" : "balance", "constant" : true }, 427 { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] } 428 ]` 429 430 const jsondata2 = ` 431 [ 432 { "type" : "function", "name" : "balance", "constant" : true }, 433 { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }, 434 { "type" : "function", "name" : "test", "constant" : false, "inputs" : [ { "name" : "number", "type" : "uint32" } ] }, 435 { "type" : "function", "name" : "string", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "string" } ] }, 436 { "type" : "function", "name" : "bool", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "bool" } ] }, 437 { "type" : "function", "name" : "address", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address" } ] }, 438 { "type" : "function", "name" : "uint64[2]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] }, 439 { "type" : "function", "name" : "uint64[]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] }, 440 { "type" : "function", "name" : "foo", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] }, 441 { "type" : "function", "name" : "bar", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] }, 442 { "type" : "function", "name" : "slice", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] }, 443 { "type" : "function", "name" : "slice256", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] }, 444 { "type" : "function", "name" : "sliceAddress", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] }, 445 { "type" : "function", "name" : "sliceMultiAddress", "constant" : false, "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] } 446 ]` 447 448 func TestReader(t *testing.T) { 449 Uint256, _ := NewType("uint256") 450 exp := ABI{ 451 Methods: map[string]Method{ 452 "balance": { 453 "balance", true, nil, nil, 454 }, 455 "send": { 456 "send", false, []Argument{ 457 {"amount", Uint256, false}, 458 }, nil, 459 }, 460 }, 461 } 462 463 abi, err := JSON(strings.NewReader(jsondata)) 464 if err != nil { 465 t.Error(err) 466 } 467 468 // deep equal fails for some reason 469 t.Skip() 470 if !reflect.DeepEqual(abi, exp) { 471 t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp) 472 } 473 } 474 475 func TestTestNumbers(t *testing.T) { 476 abi, err := JSON(strings.NewReader(jsondata2)) 477 if err != nil { 478 t.Error(err) 479 t.FailNow() 480 } 481 482 if _, err := abi.Pack("balance"); err != nil { 483 t.Error(err) 484 } 485 486 if _, err := abi.Pack("balance", 1); err == nil { 487 t.Error("expected error for balance(1)") 488 } 489 490 if _, err := abi.Pack("doesntexist", nil); err == nil { 491 t.Errorf("doesntexist shouldn't exist") 492 } 493 494 if _, err := abi.Pack("doesntexist", 1); err == nil { 495 t.Errorf("doesntexist(1) shouldn't exist") 496 } 497 498 if _, err := abi.Pack("send", big.NewInt(1000)); err != nil { 499 t.Error(err) 500 } 501 502 i := new(int) 503 *i = 1000 504 if _, err := abi.Pack("send", i); err == nil { 505 t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int") 506 } 507 508 if _, err := abi.Pack("test", uint32(1000)); err != nil { 509 t.Error(err) 510 } 511 } 512 513 func TestTestString(t *testing.T) { 514 abi, err := JSON(strings.NewReader(jsondata2)) 515 if err != nil { 516 t.Error(err) 517 t.FailNow() 518 } 519 520 if _, err := abi.Pack("string", "hello world"); err != nil { 521 t.Error(err) 522 } 523 } 524 525 func TestTestBool(t *testing.T) { 526 abi, err := JSON(strings.NewReader(jsondata2)) 527 if err != nil { 528 t.Error(err) 529 t.FailNow() 530 } 531 532 if _, err := abi.Pack("bool", true); err != nil { 533 t.Error(err) 534 } 535 } 536 537 func TestTestSlice(t *testing.T) { 538 abi, err := JSON(strings.NewReader(jsondata2)) 539 if err != nil { 540 t.Error(err) 541 t.FailNow() 542 } 543 544 slice := make([]uint64, 2) 545 if _, err := abi.Pack("uint64[2]", slice); err != nil { 546 t.Error(err) 547 } 548 549 if _, err := abi.Pack("uint64[]", slice); err != nil { 550 t.Error(err) 551 } 552 } 553 554 func TestMethodSignature(t *testing.T) { 555 String, _ := NewType("string") 556 m := Method{"foo", false, []Argument{{"bar", String, false}, {"baz", String, false}}, nil} 557 exp := "foo(string,string)" 558 if m.Sig() != exp { 559 t.Error("signature mismatch", exp, "!=", m.Sig()) 560 } 561 562 idexp := crypto.Keccak256([]byte(exp))[:4] 563 if !bytes.Equal(m.Id(), idexp) { 564 t.Errorf("expected ids to match %x != %x", m.Id(), idexp) 565 } 566 567 uintt, _ := NewType("uint") 568 m = Method{"foo", false, []Argument{{"bar", uintt, false}}, nil} 569 exp = "foo(uint256)" 570 if m.Sig() != exp { 571 t.Error("signature mismatch", exp, "!=", m.Sig()) 572 } 573 } 574 575 func TestMultiPack(t *testing.T) { 576 abi, err := JSON(strings.NewReader(jsondata2)) 577 if err != nil { 578 t.Error(err) 579 t.FailNow() 580 } 581 582 sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4] 583 sig = append(sig, make([]byte, 64)...) 584 sig[35] = 10 585 sig[67] = 11 586 587 packed, err := abi.Pack("bar", uint32(10), uint16(11)) 588 if err != nil { 589 t.Error(err) 590 t.FailNow() 591 } 592 593 if !bytes.Equal(packed, sig) { 594 t.Errorf("expected %x got %x", sig, packed) 595 } 596 } 597 598 func ExampleJSON() { 599 const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]` 600 601 abi, err := JSON(strings.NewReader(definition)) 602 if err != nil { 603 log.Fatalln(err) 604 } 605 out, err := abi.Pack("isBar", common.HexToAddress("01")) 606 if err != nil { 607 log.Fatalln(err) 608 } 609 610 fmt.Printf("%x\n", out) 611 // Output: 612 // 1f2c40920000000000000000000000000000000000000000000000000000000000000001 613 } 614 615 func TestInputVariableInputLength(t *testing.T) { 616 const definition = `[ 617 { "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] }, 618 { "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] }, 619 { "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] } 620 ]` 621 622 abi, err := JSON(strings.NewReader(definition)) 623 if err != nil { 624 t.Fatal(err) 625 } 626 627 // test one string 628 strin := "hello world" 629 strpack, err := abi.Pack("strOne", strin) 630 if err != nil { 631 t.Error(err) 632 } 633 634 offset := make([]byte, 32) 635 offset[31] = 32 636 length := make([]byte, 32) 637 length[31] = byte(len(strin)) 638 value := common.RightPadBytes([]byte(strin), 32) 639 exp := append(offset, append(length, value...)...) 640 641 // ignore first 4 bytes of the output. This is the function identifier 642 strpack = strpack[4:] 643 if !bytes.Equal(strpack, exp) { 644 t.Errorf("expected %x, got %x\n", exp, strpack) 645 } 646 647 // test one bytes 648 btspack, err := abi.Pack("bytesOne", []byte(strin)) 649 if err != nil { 650 t.Error(err) 651 } 652 // ignore first 4 bytes of the output. This is the function identifier 653 btspack = btspack[4:] 654 if !bytes.Equal(btspack, exp) { 655 t.Errorf("expected %x, got %x\n", exp, btspack) 656 } 657 658 // test two strings 659 str1 := "hello" 660 str2 := "world" 661 str2pack, err := abi.Pack("strTwo", str1, str2) 662 if err != nil { 663 t.Error(err) 664 } 665 666 offset1 := make([]byte, 32) 667 offset1[31] = 64 668 length1 := make([]byte, 32) 669 length1[31] = byte(len(str1)) 670 value1 := common.RightPadBytes([]byte(str1), 32) 671 672 offset2 := make([]byte, 32) 673 offset2[31] = 128 674 length2 := make([]byte, 32) 675 length2[31] = byte(len(str2)) 676 value2 := common.RightPadBytes([]byte(str2), 32) 677 678 exp2 := append(offset1, offset2...) 679 exp2 = append(exp2, append(length1, value1...)...) 680 exp2 = append(exp2, append(length2, value2...)...) 681 682 // ignore first 4 bytes of the output. This is the function identifier 683 str2pack = str2pack[4:] 684 if !bytes.Equal(str2pack, exp2) { 685 t.Errorf("expected %x, got %x\n", exp, str2pack) 686 } 687 688 // test two strings, first > 32, second < 32 689 str1 = strings.Repeat("a", 33) 690 str2pack, err = abi.Pack("strTwo", str1, str2) 691 if err != nil { 692 t.Error(err) 693 } 694 695 offset1 = make([]byte, 32) 696 offset1[31] = 64 697 length1 = make([]byte, 32) 698 length1[31] = byte(len(str1)) 699 value1 = common.RightPadBytes([]byte(str1), 64) 700 offset2[31] = 160 701 702 exp2 = append(offset1, offset2...) 703 exp2 = append(exp2, append(length1, value1...)...) 704 exp2 = append(exp2, append(length2, value2...)...) 705 706 // ignore first 4 bytes of the output. This is the function identifier 707 str2pack = str2pack[4:] 708 if !bytes.Equal(str2pack, exp2) { 709 t.Errorf("expected %x, got %x\n", exp, str2pack) 710 } 711 712 // test two strings, first > 32, second >32 713 str1 = strings.Repeat("a", 33) 714 str2 = strings.Repeat("a", 33) 715 str2pack, err = abi.Pack("strTwo", str1, str2) 716 if err != nil { 717 t.Error(err) 718 } 719 720 offset1 = make([]byte, 32) 721 offset1[31] = 64 722 length1 = make([]byte, 32) 723 length1[31] = byte(len(str1)) 724 value1 = common.RightPadBytes([]byte(str1), 64) 725 726 offset2 = make([]byte, 32) 727 offset2[31] = 160 728 length2 = make([]byte, 32) 729 length2[31] = byte(len(str2)) 730 value2 = common.RightPadBytes([]byte(str2), 64) 731 732 exp2 = append(offset1, offset2...) 733 exp2 = append(exp2, append(length1, value1...)...) 734 exp2 = append(exp2, append(length2, value2...)...) 735 736 // ignore first 4 bytes of the output. This is the function identifier 737 str2pack = str2pack[4:] 738 if !bytes.Equal(str2pack, exp2) { 739 t.Errorf("expected %x, got %x\n", exp, str2pack) 740 } 741 } 742 743 func TestDefaultFunctionParsing(t *testing.T) { 744 const definition = `[{ "name" : "balance" }]` 745 746 abi, err := JSON(strings.NewReader(definition)) 747 if err != nil { 748 t.Fatal(err) 749 } 750 751 if _, ok := abi.Methods["balance"]; !ok { 752 t.Error("expected 'balance' to be present") 753 } 754 } 755 756 func TestBareEvents(t *testing.T) { 757 const definition = `[ 758 { "type" : "event", "name" : "balance" }, 759 { "type" : "event", "name" : "name" }]` 760 761 abi, err := JSON(strings.NewReader(definition)) 762 if err != nil { 763 t.Fatal(err) 764 } 765 766 if len(abi.Events) != 2 { 767 t.Error("expected 2 events") 768 } 769 770 if _, ok := abi.Events["balance"]; !ok { 771 t.Error("expected 'balance' event to be present") 772 } 773 774 if _, ok := abi.Events["name"]; !ok { 775 t.Error("expected 'name' event to be present") 776 } 777 } 778 779 func TestMultiReturnWithStruct(t *testing.T) { 780 const definition = `[ 781 { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]` 782 783 abi, err := JSON(strings.NewReader(definition)) 784 if err != nil { 785 t.Fatal(err) 786 } 787 788 // using buff to make the code readable 789 buff := new(bytes.Buffer) 790 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) 791 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) 792 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005")) 793 stringOut := "hello" 794 buff.Write(common.RightPadBytes([]byte(stringOut), 32)) 795 796 var inter struct { 797 Int *big.Int 798 String string 799 } 800 err = abi.Unpack(&inter, "multi", buff.Bytes()) 801 if err != nil { 802 t.Error(err) 803 } 804 805 if inter.Int == nil || inter.Int.Cmp(big.NewInt(1)) != 0 { 806 t.Error("expected Int to be 1 got", inter.Int) 807 } 808 809 if inter.String != stringOut { 810 t.Error("expected String to be", stringOut, "got", inter.String) 811 } 812 813 var reversed struct { 814 String string 815 Int *big.Int 816 } 817 818 err = abi.Unpack(&reversed, "multi", buff.Bytes()) 819 if err != nil { 820 t.Error(err) 821 } 822 823 if reversed.Int == nil || reversed.Int.Cmp(big.NewInt(1)) != 0 { 824 t.Error("expected Int to be 1 got", reversed.Int) 825 } 826 827 if reversed.String != stringOut { 828 t.Error("expected String to be", stringOut, "got", reversed.String) 829 } 830 } 831 832 func TestMultiReturnWithSlice(t *testing.T) { 833 const definition = `[ 834 { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]` 835 836 abi, err := JSON(strings.NewReader(definition)) 837 if err != nil { 838 t.Fatal(err) 839 } 840 841 // using buff to make the code readable 842 buff := new(bytes.Buffer) 843 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) 844 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) 845 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005")) 846 stringOut := "hello" 847 buff.Write(common.RightPadBytes([]byte(stringOut), 32)) 848 849 var inter []interface{} 850 err = abi.Unpack(&inter, "multi", buff.Bytes()) 851 if err != nil { 852 t.Error(err) 853 } 854 855 if len(inter) != 2 { 856 t.Fatal("expected 2 results got", len(inter)) 857 } 858 859 if num, ok := inter[0].(*big.Int); !ok || num.Cmp(big.NewInt(1)) != 0 { 860 t.Error("expected index 0 to be 1 got", num) 861 } 862 863 if str, ok := inter[1].(string); !ok || str != stringOut { 864 t.Error("expected index 1 to be", stringOut, "got", str) 865 } 866 } 867 868 func TestMarshalArrays(t *testing.T) { 869 const definition = `[ 870 { "name" : "bytes32", "constant" : false, "outputs": [ { "type": "bytes32" } ] }, 871 { "name" : "bytes10", "constant" : false, "outputs": [ { "type": "bytes10" } ] } 872 ]` 873 874 abi, err := JSON(strings.NewReader(definition)) 875 if err != nil { 876 t.Fatal(err) 877 } 878 879 output := common.LeftPadBytes([]byte{1}, 32) 880 881 var bytes10 [10]byte 882 err = abi.Unpack(&bytes10, "bytes32", output) 883 if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" { 884 t.Error("expected error or bytes32 not be assignable to bytes10:", err) 885 } 886 887 var bytes32 [32]byte 888 err = abi.Unpack(&bytes32, "bytes32", output) 889 if err != nil { 890 t.Error("didn't expect error:", err) 891 } 892 if !bytes.Equal(bytes32[:], output) { 893 t.Error("expected bytes32[31] to be 1 got", bytes32[31]) 894 } 895 896 type ( 897 B10 [10]byte 898 B32 [32]byte 899 ) 900 901 var b10 B10 902 err = abi.Unpack(&b10, "bytes32", output) 903 if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" { 904 t.Error("expected error or bytes32 not be assignable to bytes10:", err) 905 } 906 907 var b32 B32 908 err = abi.Unpack(&b32, "bytes32", output) 909 if err != nil { 910 t.Error("didn't expect error:", err) 911 } 912 if !bytes.Equal(b32[:], output) { 913 t.Error("expected bytes32[31] to be 1 got", bytes32[31]) 914 } 915 916 output[10] = 1 917 var shortAssignLong [32]byte 918 err = abi.Unpack(&shortAssignLong, "bytes10", output) 919 if err != nil { 920 t.Error("didn't expect error:", err) 921 } 922 if !bytes.Equal(output, shortAssignLong[:]) { 923 t.Errorf("expected %x to be %x", shortAssignLong, output) 924 } 925 } 926 927 func TestUnmarshal(t *testing.T) { 928 const definition = `[ 929 { "name" : "int", "constant" : false, "outputs": [ { "type": "uint256" } ] }, 930 { "name" : "bool", "constant" : false, "outputs": [ { "type": "bool" } ] }, 931 { "name" : "bytes", "constant" : false, "outputs": [ { "type": "bytes" } ] }, 932 { "name" : "fixed", "constant" : false, "outputs": [ { "type": "bytes32" } ] }, 933 { "name" : "multi", "constant" : false, "outputs": [ { "type": "bytes" }, { "type": "bytes" } ] }, 934 { "name" : "addressSliceSingle", "constant" : false, "outputs": [ { "type": "address[]" } ] }, 935 { "name" : "addressSliceDouble", "constant" : false, "outputs": [ { "name": "a", "type": "address[]" }, { "name": "b", "type": "address[]" } ] }, 936 { "name" : "mixedBytes", "constant" : true, "outputs": [ { "name": "a", "type": "bytes" }, { "name": "b", "type": "bytes32" } ] }]` 937 938 abi, err := JSON(strings.NewReader(definition)) 939 if err != nil { 940 t.Fatal(err) 941 } 942 buff := new(bytes.Buffer) 943 944 // marshal int 945 var Int *big.Int 946 err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) 947 if err != nil { 948 t.Error(err) 949 } 950 951 if Int == nil || Int.Cmp(big.NewInt(1)) != 0 { 952 t.Error("expected Int to be 1 got", Int) 953 } 954 955 // marshal bool 956 var Bool bool 957 err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) 958 if err != nil { 959 t.Error(err) 960 } 961 962 if !Bool { 963 t.Error("expected Bool to be true") 964 } 965 966 // marshal dynamic bytes max length 32 967 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 968 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 969 bytesOut := common.RightPadBytes([]byte("hello"), 32) 970 buff.Write(bytesOut) 971 972 var Bytes []byte 973 err = abi.Unpack(&Bytes, "bytes", buff.Bytes()) 974 if err != nil { 975 t.Error(err) 976 } 977 978 if !bytes.Equal(Bytes, bytesOut) { 979 t.Errorf("expected %x got %x", bytesOut, Bytes) 980 } 981 982 // marshall dynamic bytes max length 64 983 buff.Reset() 984 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 985 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) 986 bytesOut = common.RightPadBytes([]byte("hello"), 64) 987 buff.Write(bytesOut) 988 989 err = abi.Unpack(&Bytes, "bytes", buff.Bytes()) 990 if err != nil { 991 t.Error(err) 992 } 993 994 if !bytes.Equal(Bytes, bytesOut) { 995 t.Errorf("expected %x got %x", bytesOut, Bytes) 996 } 997 998 // marshall dynamic bytes max length 63 999 buff.Reset() 1000 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 1001 buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000003f")) 1002 bytesOut = common.RightPadBytes([]byte("hello"), 63) 1003 buff.Write(bytesOut) 1004 1005 err = abi.Unpack(&Bytes, "bytes", buff.Bytes()) 1006 if err != nil { 1007 t.Error(err) 1008 } 1009 1010 if !bytes.Equal(Bytes, bytesOut) { 1011 t.Errorf("expected %x got %x", bytesOut, Bytes) 1012 } 1013 1014 // marshal dynamic bytes output empty 1015 err = abi.Unpack(&Bytes, "bytes", nil) 1016 if err == nil { 1017 t.Error("expected error") 1018 } 1019 1020 // marshal dynamic bytes length 5 1021 buff.Reset() 1022 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 1023 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005")) 1024 buff.Write(common.RightPadBytes([]byte("hello"), 32)) 1025 1026 err = abi.Unpack(&Bytes, "bytes", buff.Bytes()) 1027 if err != nil { 1028 t.Error(err) 1029 } 1030 1031 if !bytes.Equal(Bytes, []byte("hello")) { 1032 t.Errorf("expected %x got %x", bytesOut, Bytes) 1033 } 1034 1035 // marshal dynamic bytes length 5 1036 buff.Reset() 1037 buff.Write(common.RightPadBytes([]byte("hello"), 32)) 1038 1039 var hash common.Hash 1040 err = abi.Unpack(&hash, "fixed", buff.Bytes()) 1041 if err != nil { 1042 t.Error(err) 1043 } 1044 1045 helloHash := common.BytesToHash(common.RightPadBytes([]byte("hello"), 32)) 1046 if hash != helloHash { 1047 t.Errorf("Expected %x to equal %x", hash, helloHash) 1048 } 1049 1050 // marshal error 1051 buff.Reset() 1052 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 1053 err = abi.Unpack(&Bytes, "bytes", buff.Bytes()) 1054 if err == nil { 1055 t.Error("expected error") 1056 } 1057 1058 err = abi.Unpack(&Bytes, "multi", make([]byte, 64)) 1059 if err == nil { 1060 t.Error("expected error") 1061 } 1062 1063 // marshal mixed bytes 1064 buff.Reset() 1065 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) 1066 fixed := common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001") 1067 buff.Write(fixed) 1068 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) 1069 bytesOut = common.RightPadBytes([]byte("hello"), 32) 1070 buff.Write(bytesOut) 1071 1072 var out []interface{} 1073 err = abi.Unpack(&out, "mixedBytes", buff.Bytes()) 1074 if err != nil { 1075 t.Fatal("didn't expect error:", err) 1076 } 1077 1078 if !bytes.Equal(bytesOut, out[0].([]byte)) { 1079 t.Errorf("expected %x, got %x", bytesOut, out[0]) 1080 } 1081 1082 if !bytes.Equal(fixed, out[1].([]byte)) { 1083 t.Errorf("expected %x, got %x", fixed, out[1]) 1084 } 1085 1086 // marshal address slice 1087 buff.Reset() 1088 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) // offset 1089 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size 1090 buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000")) 1091 1092 var outAddr []common.Address 1093 err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes()) 1094 if err != nil { 1095 t.Fatal("didn't expect error:", err) 1096 } 1097 1098 if len(outAddr) != 1 { 1099 t.Fatal("expected 1 item, got", len(outAddr)) 1100 } 1101 1102 if outAddr[0] != (common.Address{1}) { 1103 t.Errorf("expected %x, got %x", common.Address{1}, outAddr[0]) 1104 } 1105 1106 // marshal multiple address slice 1107 buff.Reset() 1108 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // offset 1109 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // offset 1110 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size 1111 buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000")) 1112 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // size 1113 buff.Write(common.Hex2Bytes("0000000000000000000000000200000000000000000000000000000000000000")) 1114 buff.Write(common.Hex2Bytes("0000000000000000000000000300000000000000000000000000000000000000")) 1115 1116 var outAddrStruct struct { 1117 A []common.Address 1118 B []common.Address 1119 } 1120 err = abi.Unpack(&outAddrStruct, "addressSliceDouble", buff.Bytes()) 1121 if err != nil { 1122 t.Fatal("didn't expect error:", err) 1123 } 1124 1125 if len(outAddrStruct.A) != 1 { 1126 t.Fatal("expected 1 item, got", len(outAddrStruct.A)) 1127 } 1128 1129 if outAddrStruct.A[0] != (common.Address{1}) { 1130 t.Errorf("expected %x, got %x", common.Address{1}, outAddrStruct.A[0]) 1131 } 1132 1133 if len(outAddrStruct.B) != 2 { 1134 t.Fatal("expected 1 item, got", len(outAddrStruct.B)) 1135 } 1136 1137 if outAddrStruct.B[0] != (common.Address{2}) { 1138 t.Errorf("expected %x, got %x", common.Address{2}, outAddrStruct.B[0]) 1139 } 1140 if outAddrStruct.B[1] != (common.Address{3}) { 1141 t.Errorf("expected %x, got %x", common.Address{3}, outAddrStruct.B[1]) 1142 } 1143 1144 // marshal invalid address slice 1145 buff.Reset() 1146 buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000100")) 1147 1148 err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes()) 1149 if err == nil { 1150 t.Fatal("expected error:", err) 1151 } 1152 }