abi_test.go 48 KB

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