abi_test.go 46 KB

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