github.com/theQRL/go-zond@v0.2.1/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/theQRL/go-zond/common" 30 "github.com/theQRL/go-zond/common/math" 31 "github.com/theQRL/go-zond/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 address, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000001") 341 out, err := abi.Pack("isBar", address) 342 if err != nil { 343 panic(err) 344 } 345 346 fmt.Printf("%x\n", out) 347 // Output: 348 // 1f2c40920000000000000000000000000000000000000000000000000000000000000001 349 } 350 351 func TestInputVariableInputLength(t *testing.T) { 352 const definition = `[ 353 { "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] }, 354 { "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] }, 355 { "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] } 356 ]` 357 358 abi, err := JSON(strings.NewReader(definition)) 359 if err != nil { 360 t.Fatal(err) 361 } 362 363 // test one string 364 strin := "hello world" 365 strpack, err := abi.Pack("strOne", strin) 366 if err != nil { 367 t.Error(err) 368 } 369 370 offset := make([]byte, 32) 371 offset[31] = 32 372 length := make([]byte, 32) 373 length[31] = byte(len(strin)) 374 value := common.RightPadBytes([]byte(strin), 32) 375 exp := append(offset, append(length, value...)...) 376 377 // ignore first 4 bytes of the output. This is the function identifier 378 strpack = strpack[4:] 379 if !bytes.Equal(strpack, exp) { 380 t.Errorf("expected %x, got %x\n", exp, strpack) 381 } 382 383 // test one bytes 384 btspack, err := abi.Pack("bytesOne", []byte(strin)) 385 if err != nil { 386 t.Error(err) 387 } 388 // ignore first 4 bytes of the output. This is the function identifier 389 btspack = btspack[4:] 390 if !bytes.Equal(btspack, exp) { 391 t.Errorf("expected %x, got %x\n", exp, btspack) 392 } 393 394 // test two strings 395 str1 := "hello" 396 str2 := "world" 397 str2pack, err := abi.Pack("strTwo", str1, str2) 398 if err != nil { 399 t.Error(err) 400 } 401 402 offset1 := make([]byte, 32) 403 offset1[31] = 64 404 length1 := make([]byte, 32) 405 length1[31] = byte(len(str1)) 406 value1 := common.RightPadBytes([]byte(str1), 32) 407 408 offset2 := make([]byte, 32) 409 offset2[31] = 128 410 length2 := make([]byte, 32) 411 length2[31] = byte(len(str2)) 412 value2 := common.RightPadBytes([]byte(str2), 32) 413 414 exp2 := append(offset1, offset2...) 415 exp2 = append(exp2, append(length1, value1...)...) 416 exp2 = append(exp2, append(length2, value2...)...) 417 418 // ignore first 4 bytes of the output. This is the function identifier 419 str2pack = str2pack[4:] 420 if !bytes.Equal(str2pack, exp2) { 421 t.Errorf("expected %x, got %x\n", exp, str2pack) 422 } 423 424 // test two strings, first > 32, second < 32 425 str1 = strings.Repeat("a", 33) 426 str2pack, err = abi.Pack("strTwo", str1, str2) 427 if err != nil { 428 t.Error(err) 429 } 430 431 offset1 = make([]byte, 32) 432 offset1[31] = 64 433 length1 = make([]byte, 32) 434 length1[31] = byte(len(str1)) 435 value1 = common.RightPadBytes([]byte(str1), 64) 436 offset2[31] = 160 437 438 exp2 = append(offset1, offset2...) 439 exp2 = append(exp2, append(length1, value1...)...) 440 exp2 = append(exp2, append(length2, value2...)...) 441 442 // ignore first 4 bytes of the output. This is the function identifier 443 str2pack = str2pack[4:] 444 if !bytes.Equal(str2pack, exp2) { 445 t.Errorf("expected %x, got %x\n", exp, str2pack) 446 } 447 448 // test two strings, first > 32, second >32 449 str1 = strings.Repeat("a", 33) 450 str2 = strings.Repeat("a", 33) 451 str2pack, err = abi.Pack("strTwo", str1, str2) 452 if err != nil { 453 t.Error(err) 454 } 455 456 offset1 = make([]byte, 32) 457 offset1[31] = 64 458 length1 = make([]byte, 32) 459 length1[31] = byte(len(str1)) 460 value1 = common.RightPadBytes([]byte(str1), 64) 461 462 offset2 = make([]byte, 32) 463 offset2[31] = 160 464 length2 = make([]byte, 32) 465 length2[31] = byte(len(str2)) 466 value2 = common.RightPadBytes([]byte(str2), 64) 467 468 exp2 = append(offset1, offset2...) 469 exp2 = append(exp2, append(length1, value1...)...) 470 exp2 = append(exp2, append(length2, value2...)...) 471 472 // ignore first 4 bytes of the output. This is the function identifier 473 str2pack = str2pack[4:] 474 if !bytes.Equal(str2pack, exp2) { 475 t.Errorf("expected %x, got %x\n", exp, str2pack) 476 } 477 } 478 479 func TestInputFixedArrayAndVariableInputLength(t *testing.T) { 480 abi, err := JSON(strings.NewReader(jsondata)) 481 if err != nil { 482 t.Error(err) 483 } 484 485 // test string, fixed array uint256[2] 486 strin := "hello world" 487 arrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)} 488 fixedArrStrPack, err := abi.Pack("fixedArrStr", strin, arrin) 489 if err != nil { 490 t.Error(err) 491 } 492 493 // generate expected output 494 offset := make([]byte, 32) 495 offset[31] = 96 496 length := make([]byte, 32) 497 length[31] = byte(len(strin)) 498 strvalue := common.RightPadBytes([]byte(strin), 32) 499 arrinvalue1 := common.LeftPadBytes(arrin[0].Bytes(), 32) 500 arrinvalue2 := common.LeftPadBytes(arrin[1].Bytes(), 32) 501 exp := append(offset, arrinvalue1...) 502 exp = append(exp, arrinvalue2...) 503 exp = append(exp, append(length, strvalue...)...) 504 505 // ignore first 4 bytes of the output. This is the function identifier 506 fixedArrStrPack = fixedArrStrPack[4:] 507 if !bytes.Equal(fixedArrStrPack, exp) { 508 t.Errorf("expected %x, got %x\n", exp, fixedArrStrPack) 509 } 510 511 // test byte array, fixed array uint256[2] 512 bytesin := []byte(strin) 513 arrin = [2]*big.Int{big.NewInt(1), big.NewInt(2)} 514 fixedArrBytesPack, err := abi.Pack("fixedArrBytes", bytesin, arrin) 515 if err != nil { 516 t.Error(err) 517 } 518 519 // generate expected output 520 offset = make([]byte, 32) 521 offset[31] = 96 522 length = make([]byte, 32) 523 length[31] = byte(len(strin)) 524 strvalue = common.RightPadBytes([]byte(strin), 32) 525 arrinvalue1 = common.LeftPadBytes(arrin[0].Bytes(), 32) 526 arrinvalue2 = common.LeftPadBytes(arrin[1].Bytes(), 32) 527 exp = append(offset, arrinvalue1...) 528 exp = append(exp, arrinvalue2...) 529 exp = append(exp, append(length, strvalue...)...) 530 531 // ignore first 4 bytes of the output. This is the function identifier 532 fixedArrBytesPack = fixedArrBytesPack[4:] 533 if !bytes.Equal(fixedArrBytesPack, exp) { 534 t.Errorf("expected %x, got %x\n", exp, fixedArrBytesPack) 535 } 536 537 // test string, fixed array uint256[2], dynamic array uint256[] 538 strin = "hello world" 539 fixedarrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)} 540 dynarrin := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)} 541 mixedArrStrPack, err := abi.Pack("mixedArrStr", strin, fixedarrin, dynarrin) 542 if err != nil { 543 t.Error(err) 544 } 545 546 // generate expected output 547 stroffset := make([]byte, 32) 548 stroffset[31] = 128 549 strlength := make([]byte, 32) 550 strlength[31] = byte(len(strin)) 551 strvalue = common.RightPadBytes([]byte(strin), 32) 552 fixedarrinvalue1 := common.LeftPadBytes(fixedarrin[0].Bytes(), 32) 553 fixedarrinvalue2 := common.LeftPadBytes(fixedarrin[1].Bytes(), 32) 554 dynarroffset := make([]byte, 32) 555 dynarroffset[31] = byte(160 + ((len(strin)/32)+1)*32) 556 dynarrlength := make([]byte, 32) 557 dynarrlength[31] = byte(len(dynarrin)) 558 dynarrinvalue1 := common.LeftPadBytes(dynarrin[0].Bytes(), 32) 559 dynarrinvalue2 := common.LeftPadBytes(dynarrin[1].Bytes(), 32) 560 dynarrinvalue3 := common.LeftPadBytes(dynarrin[2].Bytes(), 32) 561 exp = append(stroffset, fixedarrinvalue1...) 562 exp = append(exp, fixedarrinvalue2...) 563 exp = append(exp, dynarroffset...) 564 exp = append(exp, append(strlength, strvalue...)...) 565 dynarrarg := append(dynarrlength, dynarrinvalue1...) 566 dynarrarg = append(dynarrarg, dynarrinvalue2...) 567 dynarrarg = append(dynarrarg, dynarrinvalue3...) 568 exp = append(exp, dynarrarg...) 569 570 // ignore first 4 bytes of the output. This is the function identifier 571 mixedArrStrPack = mixedArrStrPack[4:] 572 if !bytes.Equal(mixedArrStrPack, exp) { 573 t.Errorf("expected %x, got %x\n", exp, mixedArrStrPack) 574 } 575 576 // test string, fixed array uint256[2], fixed array uint256[3] 577 strin = "hello world" 578 fixedarrin1 := [2]*big.Int{big.NewInt(1), big.NewInt(2)} 579 fixedarrin2 := [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)} 580 doubleFixedArrStrPack, err := abi.Pack("doubleFixedArrStr", strin, fixedarrin1, fixedarrin2) 581 if err != nil { 582 t.Error(err) 583 } 584 585 // generate expected output 586 stroffset = make([]byte, 32) 587 stroffset[31] = 192 588 strlength = make([]byte, 32) 589 strlength[31] = byte(len(strin)) 590 strvalue = common.RightPadBytes([]byte(strin), 32) 591 fixedarrin1value1 := common.LeftPadBytes(fixedarrin1[0].Bytes(), 32) 592 fixedarrin1value2 := common.LeftPadBytes(fixedarrin1[1].Bytes(), 32) 593 fixedarrin2value1 := common.LeftPadBytes(fixedarrin2[0].Bytes(), 32) 594 fixedarrin2value2 := common.LeftPadBytes(fixedarrin2[1].Bytes(), 32) 595 fixedarrin2value3 := common.LeftPadBytes(fixedarrin2[2].Bytes(), 32) 596 exp = append(stroffset, fixedarrin1value1...) 597 exp = append(exp, fixedarrin1value2...) 598 exp = append(exp, fixedarrin2value1...) 599 exp = append(exp, fixedarrin2value2...) 600 exp = append(exp, fixedarrin2value3...) 601 exp = append(exp, append(strlength, strvalue...)...) 602 603 // ignore first 4 bytes of the output. This is the function identifier 604 doubleFixedArrStrPack = doubleFixedArrStrPack[4:] 605 if !bytes.Equal(doubleFixedArrStrPack, exp) { 606 t.Errorf("expected %x, got %x\n", exp, doubleFixedArrStrPack) 607 } 608 609 // test string, fixed array uint256[2], dynamic array uint256[], fixed array uint256[3] 610 strin = "hello world" 611 fixedarrin1 = [2]*big.Int{big.NewInt(1), big.NewInt(2)} 612 dynarrin = []*big.Int{big.NewInt(1), big.NewInt(2)} 613 fixedarrin2 = [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)} 614 multipleMixedArrStrPack, err := abi.Pack("multipleMixedArrStr", strin, fixedarrin1, dynarrin, fixedarrin2) 615 if err != nil { 616 t.Error(err) 617 } 618 619 // generate expected output 620 stroffset = make([]byte, 32) 621 stroffset[31] = 224 622 strlength = make([]byte, 32) 623 strlength[31] = byte(len(strin)) 624 strvalue = common.RightPadBytes([]byte(strin), 32) 625 fixedarrin1value1 = common.LeftPadBytes(fixedarrin1[0].Bytes(), 32) 626 fixedarrin1value2 = common.LeftPadBytes(fixedarrin1[1].Bytes(), 32) 627 dynarroffset = math.U256Bytes(big.NewInt(int64(256 + ((len(strin)/32)+1)*32))) 628 dynarrlength = make([]byte, 32) 629 dynarrlength[31] = byte(len(dynarrin)) 630 dynarrinvalue1 = common.LeftPadBytes(dynarrin[0].Bytes(), 32) 631 dynarrinvalue2 = common.LeftPadBytes(dynarrin[1].Bytes(), 32) 632 fixedarrin2value1 = common.LeftPadBytes(fixedarrin2[0].Bytes(), 32) 633 fixedarrin2value2 = common.LeftPadBytes(fixedarrin2[1].Bytes(), 32) 634 fixedarrin2value3 = common.LeftPadBytes(fixedarrin2[2].Bytes(), 32) 635 exp = append(stroffset, fixedarrin1value1...) 636 exp = append(exp, fixedarrin1value2...) 637 exp = append(exp, dynarroffset...) 638 exp = append(exp, fixedarrin2value1...) 639 exp = append(exp, fixedarrin2value2...) 640 exp = append(exp, fixedarrin2value3...) 641 exp = append(exp, append(strlength, strvalue...)...) 642 dynarrarg = append(dynarrlength, dynarrinvalue1...) 643 dynarrarg = append(dynarrarg, dynarrinvalue2...) 644 exp = append(exp, dynarrarg...) 645 646 // ignore first 4 bytes of the output. This is the function identifier 647 multipleMixedArrStrPack = multipleMixedArrStrPack[4:] 648 if !bytes.Equal(multipleMixedArrStrPack, exp) { 649 t.Errorf("expected %x, got %x\n", exp, multipleMixedArrStrPack) 650 } 651 } 652 653 func TestDefaultFunctionParsing(t *testing.T) { 654 const definition = `[{ "name" : "balance", "type" : "function" }]` 655 656 abi, err := JSON(strings.NewReader(definition)) 657 if err != nil { 658 t.Fatal(err) 659 } 660 661 if _, ok := abi.Methods["balance"]; !ok { 662 t.Error("expected 'balance' to be present") 663 } 664 } 665 666 func TestBareEvents(t *testing.T) { 667 const definition = `[ 668 { "type" : "event", "name" : "balance" }, 669 { "type" : "event", "name" : "anon", "anonymous" : true}, 670 { "type" : "event", "name" : "args", "inputs" : [{ "indexed":false, "name":"arg0", "type":"uint256" }, { "indexed":true, "name":"arg1", "type":"address" }] }, 671 { "type" : "event", "name" : "tuple", "inputs" : [{ "indexed":false, "name":"t", "type":"tuple", "components":[{"name":"a", "type":"uint256"}] }, { "indexed":true, "name":"arg1", "type":"address" }] } 672 ]` 673 674 tuple, _ := NewType("tuple", "", []ArgumentMarshaling{{Name: "a", Type: "uint256"}}) 675 676 expectedEvents := map[string]struct { 677 Anonymous bool 678 Args []Argument 679 }{ 680 "balance": {false, nil}, 681 "anon": {true, nil}, 682 "args": {false, []Argument{ 683 {Name: "arg0", Type: Uint256, Indexed: false}, 684 {Name: "arg1", Type: Address, Indexed: true}, 685 }}, 686 "tuple": {false, []Argument{ 687 {Name: "t", Type: tuple, Indexed: false}, 688 {Name: "arg1", Type: Address, Indexed: true}, 689 }}, 690 } 691 692 abi, err := JSON(strings.NewReader(definition)) 693 if err != nil { 694 t.Fatal(err) 695 } 696 697 if len(abi.Events) != len(expectedEvents) { 698 t.Fatalf("invalid number of events after parsing, want %d, got %d", len(expectedEvents), len(abi.Events)) 699 } 700 701 for name, exp := range expectedEvents { 702 got, ok := abi.Events[name] 703 if !ok { 704 t.Errorf("could not found event %s", name) 705 continue 706 } 707 if got.Anonymous != exp.Anonymous { 708 t.Errorf("invalid anonymous indication for event %s, want %v, got %v", name, exp.Anonymous, got.Anonymous) 709 } 710 if len(got.Inputs) != len(exp.Args) { 711 t.Errorf("invalid number of args, want %d, got %d", len(exp.Args), len(got.Inputs)) 712 continue 713 } 714 for i, arg := range exp.Args { 715 if arg.Name != got.Inputs[i].Name { 716 t.Errorf("events[%s].Input[%d] has an invalid name, want %s, got %s", name, i, arg.Name, got.Inputs[i].Name) 717 } 718 if arg.Indexed != got.Inputs[i].Indexed { 719 t.Errorf("events[%s].Input[%d] has an invalid indexed indication, want %v, got %v", name, i, arg.Indexed, got.Inputs[i].Indexed) 720 } 721 if arg.Type.T != got.Inputs[i].Type.T { 722 t.Errorf("events[%s].Input[%d] has an invalid type, want %x, got %x", name, i, arg.Type.T, got.Inputs[i].Type.T) 723 } 724 } 725 } 726 } 727 728 // TestUnpackEvent is based on this contract: 729 // 730 // contract T { 731 // event received(address sender, uint amount, bytes memo); 732 // event receivedAddr(address sender); 733 // function receive(bytes memo) external payable { 734 // received(msg.sender, msg.value, memo); 735 // receivedAddr(msg.sender); 736 // } 737 // } 738 // 739 // When receive("X") is called with sender Z00... and value 1, it produces this tx receipt: 740 // 741 // receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} 742 func TestUnpackEvent(t *testing.T) { 743 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"}]` 744 abi, err := JSON(strings.NewReader(abiJSON)) 745 if err != nil { 746 t.Fatal(err) 747 } 748 749 const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158` 750 data, err := hex.DecodeString(hexdata) 751 if err != nil { 752 t.Fatal(err) 753 } 754 if len(data)%32 == 0 { 755 t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) 756 } 757 758 type ReceivedEvent struct { 759 Sender common.Address 760 Amount *big.Int 761 Memo []byte 762 } 763 var ev ReceivedEvent 764 765 err = abi.UnpackIntoInterface(&ev, "received", data) 766 if err != nil { 767 t.Error(err) 768 } 769 770 type ReceivedAddrEvent struct { 771 Sender common.Address 772 } 773 var receivedAddrEv ReceivedAddrEvent 774 err = abi.UnpackIntoInterface(&receivedAddrEv, "receivedAddr", data) 775 if err != nil { 776 t.Error(err) 777 } 778 } 779 780 func TestUnpackEventIntoMap(t *testing.T) { 781 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"}]` 782 abi, err := JSON(strings.NewReader(abiJSON)) 783 if err != nil { 784 t.Fatal(err) 785 } 786 787 const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158` 788 data, err := hex.DecodeString(hexdata) 789 if err != nil { 790 t.Fatal(err) 791 } 792 if len(data)%32 == 0 { 793 t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) 794 } 795 796 sender, _ := common.NewAddressFromString("Z376c47978271565f56DEB45495afa69E59c16Ab2") 797 receivedMap := map[string]interface{}{} 798 expectedReceivedMap := map[string]interface{}{ 799 "sender": sender, 800 "amount": big.NewInt(1), 801 "memo": []byte{88}, 802 } 803 if err := abi.UnpackIntoMap(receivedMap, "received", data); err != nil { 804 t.Error(err) 805 } 806 if len(receivedMap) != 3 { 807 t.Error("unpacked `received` map expected to have length 3") 808 } 809 if receivedMap["sender"] != expectedReceivedMap["sender"] { 810 t.Error("unpacked `received` map does not match expected map") 811 } 812 if receivedMap["amount"].(*big.Int).Cmp(expectedReceivedMap["amount"].(*big.Int)) != 0 { 813 t.Error("unpacked `received` map does not match expected map") 814 } 815 if !bytes.Equal(receivedMap["memo"].([]byte), expectedReceivedMap["memo"].([]byte)) { 816 t.Error("unpacked `received` map does not match expected map") 817 } 818 819 receivedAddrMap := map[string]interface{}{} 820 if err = abi.UnpackIntoMap(receivedAddrMap, "receivedAddr", data); err != nil { 821 t.Error(err) 822 } 823 if len(receivedAddrMap) != 1 { 824 t.Error("unpacked `receivedAddr` map expected to have length 1") 825 } 826 if receivedAddrMap["sender"] != expectedReceivedMap["sender"] { 827 t.Error("unpacked `receivedAddr` map does not match expected map") 828 } 829 } 830 831 func TestUnpackMethodIntoMap(t *testing.T) { 832 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"}]` 833 abi, err := JSON(strings.NewReader(abiJSON)) 834 if err != nil { 835 t.Fatal(err) 836 } 837 const hexdata = `00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000015800000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000158000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001580000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000015800000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000158` 838 data, err := hex.DecodeString(hexdata) 839 if err != nil { 840 t.Fatal(err) 841 } 842 if len(data)%32 != 0 { 843 t.Errorf("len(data) is %d, want a multiple of 32", len(data)) 844 } 845 846 // Tests a method with no outputs 847 receiveMap := map[string]interface{}{} 848 if err = abi.UnpackIntoMap(receiveMap, "receive", data); err != nil { 849 t.Error(err) 850 } 851 if len(receiveMap) > 0 { 852 t.Error("unpacked `receive` map expected to have length 0") 853 } 854 855 // Tests a method with only outputs 856 sendMap := map[string]interface{}{} 857 if err = abi.UnpackIntoMap(sendMap, "send", data); err != nil { 858 t.Error(err) 859 } 860 if len(sendMap) != 1 { 861 t.Error("unpacked `send` map expected to have length 1") 862 } 863 if sendMap["amount"].(*big.Int).Cmp(big.NewInt(1)) != 0 { 864 t.Error("unpacked `send` map expected `amount` value of 1") 865 } 866 867 // Tests a method with outputs and inputs 868 getMap := map[string]interface{}{} 869 if err = abi.UnpackIntoMap(getMap, "get", data); err != nil { 870 t.Error(err) 871 } 872 if len(getMap) != 1 { 873 t.Error("unpacked `get` map expected to have length 1") 874 } 875 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} 876 if !bytes.Equal(getMap["hash"].([]byte), expectedBytes) { 877 t.Errorf("unpacked `get` map expected `hash` value of %v", expectedBytes) 878 } 879 } 880 881 func TestUnpackIntoMapNamingConflict(t *testing.T) { 882 // Two methods have the same name 883 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"}]` 884 abi, err := JSON(strings.NewReader(abiJSON)) 885 if err != nil { 886 t.Fatal(err) 887 } 888 var hexdata = `00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158` 889 data, err := hex.DecodeString(hexdata) 890 if err != nil { 891 t.Fatal(err) 892 } 893 if len(data)%32 == 0 { 894 t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) 895 } 896 getMap := map[string]interface{}{} 897 if err = abi.UnpackIntoMap(getMap, "get", data); err == nil { 898 t.Error("naming conflict between two methods; error expected") 899 } 900 901 // Two events have the same name 902 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"}]` 903 abi, err = JSON(strings.NewReader(abiJSON)) 904 if err != nil { 905 t.Fatal(err) 906 } 907 hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158` 908 data, err = hex.DecodeString(hexdata) 909 if err != nil { 910 t.Fatal(err) 911 } 912 if len(data)%32 == 0 { 913 t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) 914 } 915 receivedMap := map[string]interface{}{} 916 if err = abi.UnpackIntoMap(receivedMap, "received", data); err != nil { 917 t.Error("naming conflict between two events; no error expected") 918 } 919 920 // Method and event have the same name 921 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"}]` 922 abi, err = JSON(strings.NewReader(abiJSON)) 923 if err != nil { 924 t.Fatal(err) 925 } 926 if len(data)%32 == 0 { 927 t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) 928 } 929 if err = abi.UnpackIntoMap(receivedMap, "received", data); err == nil { 930 t.Error("naming conflict between an event and a method; error expected") 931 } 932 933 // Conflict is case sensitive 934 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"}]` 935 abi, err = JSON(strings.NewReader(abiJSON)) 936 if err != nil { 937 t.Fatal(err) 938 } 939 if len(data)%32 == 0 { 940 t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) 941 } 942 sender, _ := common.NewAddressFromString("Z376c47978271565f56DEB45495afa69E59c16Ab2") 943 expectedReceivedMap := map[string]interface{}{ 944 "sender": sender, 945 "amount": big.NewInt(1), 946 "memo": []byte{88}, 947 } 948 if err = abi.UnpackIntoMap(receivedMap, "Received", data); err != nil { 949 t.Error(err) 950 } 951 if len(receivedMap) != 3 { 952 t.Error("unpacked `received` map expected to have length 3") 953 } 954 if receivedMap["sender"] != expectedReceivedMap["sender"] { 955 t.Error("unpacked `received` map does not match expected map") 956 } 957 if receivedMap["amount"].(*big.Int).Cmp(expectedReceivedMap["amount"].(*big.Int)) != 0 { 958 t.Error("unpacked `received` map does not match expected map") 959 } 960 if !bytes.Equal(receivedMap["memo"].([]byte), expectedReceivedMap["memo"].([]byte)) { 961 t.Error("unpacked `received` map does not match expected map") 962 } 963 } 964 965 func TestABI_MethodById(t *testing.T) { 966 abi, err := JSON(strings.NewReader(jsondata)) 967 if err != nil { 968 t.Fatal(err) 969 } 970 for name, m := range abi.Methods { 971 a := fmt.Sprintf("%v", m) 972 m2, err := abi.MethodById(m.ID) 973 if err != nil { 974 t.Fatalf("Failed to look up ABI method: %v", err) 975 } 976 b := fmt.Sprintf("%v", m2) 977 if a != b { 978 t.Errorf("Method %v (id %x) not 'findable' by id in ABI", name, m.ID) 979 } 980 } 981 // test unsuccessful lookups 982 if _, err = abi.MethodById(crypto.Keccak256()); err == nil { 983 t.Error("Expected error: no method with this id") 984 } 985 // Also test empty 986 if _, err := abi.MethodById([]byte{0x00}); err == nil { 987 t.Errorf("Expected error, too short to decode data") 988 } 989 if _, err := abi.MethodById([]byte{}); err == nil { 990 t.Errorf("Expected error, too short to decode data") 991 } 992 if _, err := abi.MethodById(nil); err == nil { 993 t.Errorf("Expected error, nil is short to decode data") 994 } 995 } 996 997 func TestABI_EventById(t *testing.T) { 998 tests := []struct { 999 name string 1000 json string 1001 event string 1002 }{ 1003 { 1004 name: "", 1005 json: `[ 1006 {"type":"event","name":"received","anonymous":false,"inputs":[ 1007 {"indexed":false,"name":"sender","type":"address"}, 1008 {"indexed":false,"name":"amount","type":"uint256"}, 1009 {"indexed":false,"name":"memo","type":"bytes"} 1010 ] 1011 }]`, 1012 event: "received(address,uint256,bytes)", 1013 }, { 1014 name: "", 1015 json: `[ 1016 { "constant": true, "inputs": [], "name": "name", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, 1017 { "constant": false, "inputs": [ { "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "approve", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, 1018 { "constant": true, "inputs": [], "name": "totalSupply", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, 1019 { "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" }, 1020 { "constant": true, "inputs": [], "name": "decimals", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "stateMutability": "view", "type": "function" }, 1021 { "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, 1022 { "constant": true, "inputs": [], "name": "symbol", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, 1023 { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, 1024 { "constant": true, "inputs": [ { "name": "_owner", "type": "address" }, { "name": "_spender", "type": "address" } ], "name": "allowance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, 1025 { "payable": true, "stateMutability": "payable", "type": "fallback" }, 1026 { "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" }, 1027 { "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" } 1028 ]`, 1029 event: "Transfer(address,address,uint256)", 1030 }, 1031 } 1032 1033 for testnum, test := range tests { 1034 abi, err := JSON(strings.NewReader(test.json)) 1035 if err != nil { 1036 t.Error(err) 1037 } 1038 1039 topic := test.event 1040 topicID := crypto.Keccak256Hash([]byte(topic)) 1041 1042 event, err := abi.EventByID(topicID) 1043 if err != nil { 1044 t.Fatalf("Failed to look up ABI method: %v, test #%d", err, testnum) 1045 } 1046 if event == nil { 1047 t.Errorf("We should find a event for topic %s, test #%d", topicID.Hex(), testnum) 1048 } else if event.ID != topicID { 1049 t.Errorf("Event id %s does not match topic %s, test #%d", event.ID.Hex(), topicID.Hex(), testnum) 1050 } 1051 1052 unknowntopicID := crypto.Keccak256Hash([]byte("unknownEvent")) 1053 unknownEvent, err := abi.EventByID(unknowntopicID) 1054 if err == nil { 1055 t.Errorf("EventByID should return an error if a topic is not found, test #%d", testnum) 1056 } 1057 if unknownEvent != nil { 1058 t.Errorf("We should not find any event for topic %s, test #%d", unknowntopicID.Hex(), testnum) 1059 } 1060 } 1061 } 1062 1063 func TestABI_ErrorByID(t *testing.T) { 1064 abi, err := JSON(strings.NewReader(`[ 1065 {"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"MyError1","type":"error"}, 1066 {"inputs":[{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"string","name":"b","type":"string"},{"internalType":"address","name":"c","type":"address"}],"internalType":"struct MyError.MyStruct","name":"x","type":"tuple"},{"internalType":"address","name":"y","type":"address"},{"components":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"string","name":"b","type":"string"},{"internalType":"address","name":"c","type":"address"}],"internalType":"struct MyError.MyStruct","name":"z","type":"tuple"}],"name":"MyError2","type":"error"}, 1067 {"inputs":[{"internalType":"uint256[]","name":"x","type":"uint256[]"}],"name":"MyError3","type":"error"} 1068 ]`)) 1069 if err != nil { 1070 t.Fatal(err) 1071 } 1072 for name, m := range abi.Errors { 1073 a := fmt.Sprintf("%v", &m) 1074 var id [4]byte 1075 copy(id[:], m.ID[:4]) 1076 m2, err := abi.ErrorByID(id) 1077 if err != nil { 1078 t.Fatalf("Failed to look up ABI error: %v", err) 1079 } 1080 b := fmt.Sprintf("%v", m2) 1081 if a != b { 1082 t.Errorf("Error %v (id %x) not 'findable' by id in ABI", name, id) 1083 } 1084 } 1085 // test unsuccessful lookups 1086 if _, err = abi.ErrorByID([4]byte{}); err == nil { 1087 t.Error("Expected error: no error with this id") 1088 } 1089 } 1090 1091 // TestDoubleDuplicateMethodNames checks that if transfer0 already exists, there won't be a name 1092 // conflict and that the second transfer method will be renamed transfer1. 1093 func TestDoubleDuplicateMethodNames(t *testing.T) { 1094 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"}]` 1095 contractAbi, err := JSON(strings.NewReader(abiJSON)) 1096 if err != nil { 1097 t.Fatal(err) 1098 } 1099 if _, ok := contractAbi.Methods["transfer"]; !ok { 1100 t.Fatalf("Could not find original method") 1101 } 1102 if _, ok := contractAbi.Methods["transfer0"]; !ok { 1103 t.Fatalf("Could not find duplicate method") 1104 } 1105 if _, ok := contractAbi.Methods["transfer1"]; !ok { 1106 t.Fatalf("Could not find duplicate method") 1107 } 1108 if _, ok := contractAbi.Methods["transfer2"]; ok { 1109 t.Fatalf("Should not have found extra method") 1110 } 1111 } 1112 1113 // TestDoubleDuplicateEventNames checks that if send0 already exists, there won't be a name 1114 // conflict and that the second send event will be renamed send1. 1115 // The test runs the abi of the following contract. 1116 // 1117 // contract DuplicateEvent { 1118 // event send(uint256 a); 1119 // event send0(); 1120 // event send(); 1121 // } 1122 func TestDoubleDuplicateEventNames(t *testing.T) { 1123 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"}]` 1124 contractAbi, err := JSON(strings.NewReader(abiJSON)) 1125 if err != nil { 1126 t.Fatal(err) 1127 } 1128 if _, ok := contractAbi.Events["send"]; !ok { 1129 t.Fatalf("Could not find original event") 1130 } 1131 if _, ok := contractAbi.Events["send0"]; !ok { 1132 t.Fatalf("Could not find duplicate event") 1133 } 1134 if _, ok := contractAbi.Events["send1"]; !ok { 1135 t.Fatalf("Could not find duplicate event") 1136 } 1137 if _, ok := contractAbi.Events["send2"]; ok { 1138 t.Fatalf("Should not have found extra event") 1139 } 1140 } 1141 1142 // TestUnnamedEventParam checks that an event with unnamed parameters is 1143 // correctly handled. 1144 // The test runs the abi of the following contract. 1145 // 1146 // contract TestEvent { 1147 // event send(uint256, uint256); 1148 // } 1149 func TestUnnamedEventParam(t *testing.T) { 1150 abiJSON := `[{ "anonymous": false, "inputs": [{ "indexed": false,"internalType": "uint256", "name": "","type": "uint256"},{"indexed": false,"internalType": "uint256","name": "","type": "uint256"}],"name": "send","type": "event"}]` 1151 contractAbi, err := JSON(strings.NewReader(abiJSON)) 1152 if err != nil { 1153 t.Fatal(err) 1154 } 1155 1156 event, ok := contractAbi.Events["send"] 1157 if !ok { 1158 t.Fatalf("Could not find event") 1159 } 1160 if event.Inputs[0].Name != "arg0" { 1161 t.Fatalf("Could not find input") 1162 } 1163 if event.Inputs[1].Name != "arg1" { 1164 t.Fatalf("Could not find input") 1165 } 1166 } 1167 1168 func TestUnpackRevert(t *testing.T) { 1169 t.Parallel() 1170 1171 var cases = []struct { 1172 input string 1173 expect string 1174 expectErr error 1175 }{ 1176 {"", "", errors.New("invalid data for unpacking")}, 1177 {"08c379a1", "", errors.New("invalid data for unpacking")}, 1178 {"08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000", "revert reason", nil}, 1179 {"4e487b710000000000000000000000000000000000000000000000000000000000000000", "generic panic", nil}, 1180 {"4e487b7100000000000000000000000000000000000000000000000000000000000000ff", "unknown panic code: 0xff", nil}, 1181 } 1182 for index, c := range cases { 1183 t.Run(fmt.Sprintf("case %d", index), func(t *testing.T) { 1184 got, err := UnpackRevert(common.Hex2Bytes(c.input)) 1185 if c.expectErr != nil { 1186 if err == nil { 1187 t.Fatalf("Expected non-nil error") 1188 } 1189 if err.Error() != c.expectErr.Error() { 1190 t.Fatalf("Expected error mismatch, want %v, got %v", c.expectErr, err) 1191 } 1192 return 1193 } 1194 if c.expect != got { 1195 t.Fatalf("Output mismatch, want %v, got %v", c.expect, got) 1196 } 1197 }) 1198 } 1199 }