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