abi_test.go 47 KB

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