abi_test.go 51 KB

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