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