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