abi_test.go 52 KB

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