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