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