abi_test.go 51 KB

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