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