abi_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. "fmt"
  20. "log"
  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. // formatSilceOutput add padding to the value and adds a size
  29. func formatSliceOutput(v ...[]byte) []byte {
  30. off := common.LeftPadBytes(big.NewInt(int64(len(v))).Bytes(), 32)
  31. output := append(off, make([]byte, 0, len(v)*32)...)
  32. for _, value := range v {
  33. output = append(output, common.LeftPadBytes(value, 32)...)
  34. }
  35. return output
  36. }
  37. // quick helper padding
  38. func pad(input []byte, size int, left bool) []byte {
  39. if left {
  40. return common.LeftPadBytes(input, size)
  41. }
  42. return common.RightPadBytes(input, size)
  43. }
  44. func TestTypeCheck(t *testing.T) {
  45. for i, test := range []struct {
  46. typ string
  47. input interface{}
  48. err error
  49. }{
  50. {"uint", big.NewInt(1), nil},
  51. {"int", big.NewInt(1), nil},
  52. {"uint30", big.NewInt(1), nil},
  53. {"uint30", uint8(1), varErr(reflect.Ptr, reflect.Uint8)},
  54. {"uint16", uint16(1), nil},
  55. {"uint16", uint8(1), varErr(reflect.Uint16, reflect.Uint8)},
  56. {"uint16[]", []uint16{1, 2, 3}, nil},
  57. {"uint16[]", [3]uint16{1, 2, 3}, nil},
  58. {"uint16[]", []uint32{1, 2, 3}, typeErr(formatSliceString(reflect.Uint16, -1), formatSliceString(reflect.Uint32, -1))},
  59. {"uint16[3]", [3]uint32{1, 2, 3}, typeErr(formatSliceString(reflect.Uint16, 3), formatSliceString(reflect.Uint32, 3))},
  60. {"uint16[3]", [4]uint16{1, 2, 3}, typeErr(formatSliceString(reflect.Uint16, 3), formatSliceString(reflect.Uint16, 4))},
  61. {"uint16[3]", []uint16{1, 2, 3}, nil},
  62. {"uint16[3]", []uint16{1, 2, 3, 4}, typeErr(formatSliceString(reflect.Uint16, 3), formatSliceString(reflect.Uint16, 4))},
  63. {"address[]", []common.Address{common.Address{1}}, nil},
  64. {"address[1]", []common.Address{common.Address{1}}, nil},
  65. {"address[1]", [1]common.Address{common.Address{1}}, nil},
  66. {"address[2]", [1]common.Address{common.Address{1}}, typeErr(formatSliceString(reflect.Array, 2), formatSliceString(reflect.Array, 1))},
  67. {"bytes32", [32]byte{}, nil},
  68. {"bytes32", [33]byte{}, typeErr(formatSliceString(reflect.Uint8, 32), formatSliceString(reflect.Uint8, 33))},
  69. {"bytes32", common.Hash{1}, nil},
  70. {"bytes31", [31]byte{}, nil},
  71. {"bytes31", [32]byte{}, typeErr(formatSliceString(reflect.Uint8, 31), formatSliceString(reflect.Uint8, 32))},
  72. {"bytes", []byte{0, 1}, nil},
  73. {"bytes", [2]byte{0, 1}, nil},
  74. {"bytes", common.Hash{1}, nil},
  75. {"string", "hello world", nil},
  76. {"bytes32[]", [][32]byte{[32]byte{}}, nil},
  77. } {
  78. typ, err := NewType(test.typ)
  79. if err != nil {
  80. t.Fatal("unexpected parse error:", err)
  81. }
  82. err = typeCheck(typ, reflect.ValueOf(test.input))
  83. if err != nil && test.err == nil {
  84. t.Errorf("%d failed. Expected no err but got: %v", i, err)
  85. continue
  86. }
  87. if err == nil && test.err != nil {
  88. t.Errorf("%d failed. Expected err: %v but got none", i, test.err)
  89. continue
  90. }
  91. if err != nil && test.err != nil && err.Error() != test.err.Error() {
  92. t.Errorf("%d failed. Expected err: '%v' got err: '%v'", i, test.err, err)
  93. }
  94. }
  95. }
  96. func TestPack(t *testing.T) {
  97. for i, test := range []struct {
  98. typ string
  99. input interface{}
  100. output []byte
  101. }{
  102. {"uint16", uint16(2), pad([]byte{2}, 32, true)},
  103. {"uint16[]", []uint16{1, 2}, formatSliceOutput([]byte{1}, []byte{2})},
  104. {"uint256[]", []*big.Int{big.NewInt(1), big.NewInt(2)}, formatSliceOutput([]byte{1}, []byte{2})},
  105. {"address[]", []common.Address{common.Address{1}, common.Address{2}}, formatSliceOutput(pad([]byte{1}, 20, false), pad([]byte{2}, 20, false))},
  106. {"bytes32[]", []common.Hash{common.Hash{1}, common.Hash{2}}, formatSliceOutput(pad([]byte{1}, 32, false), pad([]byte{2}, 32, false))},
  107. } {
  108. typ, err := NewType(test.typ)
  109. if err != nil {
  110. t.Fatal("unexpected parse error:", err)
  111. }
  112. output, err := typ.pack(reflect.ValueOf(test.input))
  113. if err != nil {
  114. t.Fatal("unexpected pack error:", err)
  115. }
  116. if !bytes.Equal(output, test.output) {
  117. t.Errorf("%d failed. Expected bytes: '%x' Got: '%x'", i, test.output, output)
  118. }
  119. }
  120. }
  121. func TestMethodPack(t *testing.T) {
  122. abi, err := JSON(strings.NewReader(jsondata2))
  123. if err != nil {
  124. t.Fatal(err)
  125. }
  126. sig := abi.Methods["slice"].Id()
  127. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  128. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  129. sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...)
  130. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  131. packed, err := abi.Pack("slice", []uint32{1, 2})
  132. if err != nil {
  133. t.Error(err)
  134. }
  135. if !bytes.Equal(packed, sig) {
  136. t.Errorf("expected %x got %x", sig, packed)
  137. }
  138. var addrA, addrB = common.Address{1}, common.Address{2}
  139. sig = abi.Methods["sliceAddress"].Id()
  140. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  141. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  142. sig = append(sig, common.LeftPadBytes(addrA[:], 32)...)
  143. sig = append(sig, common.LeftPadBytes(addrB[:], 32)...)
  144. packed, err = abi.Pack("sliceAddress", []common.Address{addrA, addrB})
  145. if err != nil {
  146. t.Fatal(err)
  147. }
  148. if !bytes.Equal(packed, sig) {
  149. t.Errorf("expected %x got %x", sig, packed)
  150. }
  151. var addrC, addrD = common.Address{3}, common.Address{4}
  152. sig = abi.Methods["sliceMultiAddress"].Id()
  153. sig = append(sig, common.LeftPadBytes([]byte{64}, 32)...)
  154. sig = append(sig, common.LeftPadBytes([]byte{160}, 32)...)
  155. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  156. sig = append(sig, common.LeftPadBytes(addrA[:], 32)...)
  157. sig = append(sig, common.LeftPadBytes(addrB[:], 32)...)
  158. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  159. sig = append(sig, common.LeftPadBytes(addrC[:], 32)...)
  160. sig = append(sig, common.LeftPadBytes(addrD[:], 32)...)
  161. packed, err = abi.Pack("sliceMultiAddress", []common.Address{addrA, addrB}, []common.Address{addrC, addrD})
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. if !bytes.Equal(packed, sig) {
  166. t.Errorf("expected %x got %x", sig, packed)
  167. }
  168. sig = abi.Methods["slice256"].Id()
  169. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  170. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  171. sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...)
  172. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  173. packed, err = abi.Pack("slice256", []*big.Int{big.NewInt(1), big.NewInt(2)})
  174. if err != nil {
  175. t.Error(err)
  176. }
  177. if !bytes.Equal(packed, sig) {
  178. t.Errorf("expected %x got %x", sig, packed)
  179. }
  180. }
  181. const jsondata = `
  182. [
  183. { "type" : "function", "name" : "balance", "const" : true },
  184. { "type" : "function", "name" : "send", "const" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }
  185. ]`
  186. const jsondata2 = `
  187. [
  188. { "type" : "function", "name" : "balance", "const" : true },
  189. { "type" : "function", "name" : "send", "const" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
  190. { "type" : "function", "name" : "test", "const" : false, "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
  191. { "type" : "function", "name" : "string", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
  192. { "type" : "function", "name" : "bool", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
  193. { "type" : "function", "name" : "address", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
  194. { "type" : "function", "name" : "uint64[2]", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
  195. { "type" : "function", "name" : "uint64[]", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
  196. { "type" : "function", "name" : "foo", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
  197. { "type" : "function", "name" : "bar", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
  198. { "type" : "function", "name" : "slice", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
  199. { "type" : "function", "name" : "slice256", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
  200. { "type" : "function", "name" : "sliceAddress", "const" : false, "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
  201. { "type" : "function", "name" : "sliceMultiAddress", "const" : false, "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] }
  202. ]`
  203. func TestReader(t *testing.T) {
  204. Uint256, _ := NewType("uint256")
  205. exp := ABI{
  206. Methods: map[string]Method{
  207. "balance": Method{
  208. "balance", true, nil, nil,
  209. },
  210. "send": Method{
  211. "send", false, []Argument{
  212. Argument{"amount", Uint256, false},
  213. }, nil,
  214. },
  215. },
  216. }
  217. abi, err := JSON(strings.NewReader(jsondata))
  218. if err != nil {
  219. t.Error(err)
  220. }
  221. // deep equal fails for some reason
  222. t.Skip()
  223. if !reflect.DeepEqual(abi, exp) {
  224. t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp)
  225. }
  226. }
  227. func TestTestNumbers(t *testing.T) {
  228. abi, err := JSON(strings.NewReader(jsondata2))
  229. if err != nil {
  230. t.Error(err)
  231. t.FailNow()
  232. }
  233. if _, err := abi.Pack("balance"); err != nil {
  234. t.Error(err)
  235. }
  236. if _, err := abi.Pack("balance", 1); err == nil {
  237. t.Error("expected error for balance(1)")
  238. }
  239. if _, err := abi.Pack("doesntexist", nil); err == nil {
  240. t.Errorf("doesntexist shouldn't exist")
  241. }
  242. if _, err := abi.Pack("doesntexist", 1); err == nil {
  243. t.Errorf("doesntexist(1) shouldn't exist")
  244. }
  245. if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
  246. t.Error(err)
  247. }
  248. i := new(int)
  249. *i = 1000
  250. if _, err := abi.Pack("send", i); err == nil {
  251. t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
  252. }
  253. if _, err := abi.Pack("test", uint32(1000)); err != nil {
  254. t.Error(err)
  255. }
  256. }
  257. func TestTestString(t *testing.T) {
  258. abi, err := JSON(strings.NewReader(jsondata2))
  259. if err != nil {
  260. t.Error(err)
  261. t.FailNow()
  262. }
  263. if _, err := abi.Pack("string", "hello world"); err != nil {
  264. t.Error(err)
  265. }
  266. }
  267. func TestTestBool(t *testing.T) {
  268. abi, err := JSON(strings.NewReader(jsondata2))
  269. if err != nil {
  270. t.Error(err)
  271. t.FailNow()
  272. }
  273. if _, err := abi.Pack("bool", true); err != nil {
  274. t.Error(err)
  275. }
  276. }
  277. func TestTestSlice(t *testing.T) {
  278. abi, err := JSON(strings.NewReader(jsondata2))
  279. if err != nil {
  280. t.Error(err)
  281. t.FailNow()
  282. }
  283. slice := make([]uint64, 2)
  284. if _, err := abi.Pack("uint64[2]", slice); err != nil {
  285. t.Error(err)
  286. }
  287. if _, err := abi.Pack("uint64[]", slice); err != nil {
  288. t.Error(err)
  289. }
  290. }
  291. func TestMethodSignature(t *testing.T) {
  292. String, _ := NewType("string")
  293. m := Method{"foo", false, []Argument{Argument{"bar", String, false}, Argument{"baz", String, false}}, nil}
  294. exp := "foo(string,string)"
  295. if m.Sig() != exp {
  296. t.Error("signature mismatch", exp, "!=", m.Sig())
  297. }
  298. idexp := crypto.Keccak256([]byte(exp))[:4]
  299. if !bytes.Equal(m.Id(), idexp) {
  300. t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
  301. }
  302. uintt, _ := NewType("uint")
  303. m = Method{"foo", false, []Argument{Argument{"bar", uintt, false}}, nil}
  304. exp = "foo(uint256)"
  305. if m.Sig() != exp {
  306. t.Error("signature mismatch", exp, "!=", m.Sig())
  307. }
  308. }
  309. func TestOldPack(t *testing.T) {
  310. abi, err := JSON(strings.NewReader(jsondata2))
  311. if err != nil {
  312. t.Error(err)
  313. t.FailNow()
  314. }
  315. sig := crypto.Keccak256([]byte("foo(uint32)"))[:4]
  316. sig = append(sig, make([]byte, 32)...)
  317. sig[35] = 10
  318. packed, err := abi.Pack("foo", uint32(10))
  319. if err != nil {
  320. t.Error(err)
  321. t.FailNow()
  322. }
  323. if !bytes.Equal(packed, sig) {
  324. t.Errorf("expected %x got %x", sig, packed)
  325. }
  326. }
  327. func TestMultiPack(t *testing.T) {
  328. abi, err := JSON(strings.NewReader(jsondata2))
  329. if err != nil {
  330. t.Error(err)
  331. t.FailNow()
  332. }
  333. sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
  334. sig = append(sig, make([]byte, 64)...)
  335. sig[35] = 10
  336. sig[67] = 11
  337. packed, err := abi.Pack("bar", uint32(10), uint16(11))
  338. if err != nil {
  339. t.Error(err)
  340. t.FailNow()
  341. }
  342. if !bytes.Equal(packed, sig) {
  343. t.Errorf("expected %x got %x", sig, packed)
  344. }
  345. }
  346. func ExampleJSON() {
  347. const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
  348. abi, err := JSON(strings.NewReader(definition))
  349. if err != nil {
  350. log.Fatalln(err)
  351. }
  352. out, err := abi.Pack("isBar", common.HexToAddress("01"))
  353. if err != nil {
  354. log.Fatalln(err)
  355. }
  356. fmt.Printf("%x\n", out)
  357. // Output:
  358. // 1f2c40920000000000000000000000000000000000000000000000000000000000000001
  359. }
  360. func TestInputVariableInputLength(t *testing.T) {
  361. const definition = `[
  362. { "type" : "function", "name" : "strOne", "const" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
  363. { "type" : "function", "name" : "bytesOne", "const" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
  364. { "type" : "function", "name" : "strTwo", "const" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
  365. ]`
  366. abi, err := JSON(strings.NewReader(definition))
  367. if err != nil {
  368. t.Fatal(err)
  369. }
  370. // test one string
  371. strin := "hello world"
  372. strpack, err := abi.Pack("strOne", strin)
  373. if err != nil {
  374. t.Error(err)
  375. }
  376. offset := make([]byte, 32)
  377. offset[31] = 32
  378. length := make([]byte, 32)
  379. length[31] = byte(len(strin))
  380. value := common.RightPadBytes([]byte(strin), 32)
  381. exp := append(offset, append(length, value...)...)
  382. // ignore first 4 bytes of the output. This is the function identifier
  383. strpack = strpack[4:]
  384. if !bytes.Equal(strpack, exp) {
  385. t.Errorf("expected %x, got %x\n", exp, strpack)
  386. }
  387. // test one bytes
  388. btspack, err := abi.Pack("bytesOne", []byte(strin))
  389. if err != nil {
  390. t.Error(err)
  391. }
  392. // ignore first 4 bytes of the output. This is the function identifier
  393. btspack = btspack[4:]
  394. if !bytes.Equal(btspack, exp) {
  395. t.Errorf("expected %x, got %x\n", exp, btspack)
  396. }
  397. // test two strings
  398. str1 := "hello"
  399. str2 := "world"
  400. str2pack, err := abi.Pack("strTwo", str1, str2)
  401. if err != nil {
  402. t.Error(err)
  403. }
  404. offset1 := make([]byte, 32)
  405. offset1[31] = 64
  406. length1 := make([]byte, 32)
  407. length1[31] = byte(len(str1))
  408. value1 := common.RightPadBytes([]byte(str1), 32)
  409. offset2 := make([]byte, 32)
  410. offset2[31] = 128
  411. length2 := make([]byte, 32)
  412. length2[31] = byte(len(str2))
  413. value2 := common.RightPadBytes([]byte(str2), 32)
  414. exp2 := append(offset1, offset2...)
  415. exp2 = append(exp2, append(length1, value1...)...)
  416. exp2 = append(exp2, append(length2, value2...)...)
  417. // ignore first 4 bytes of the output. This is the function identifier
  418. str2pack = str2pack[4:]
  419. if !bytes.Equal(str2pack, exp2) {
  420. t.Errorf("expected %x, got %x\n", exp, str2pack)
  421. }
  422. // test two strings, first > 32, second < 32
  423. str1 = strings.Repeat("a", 33)
  424. str2pack, err = abi.Pack("strTwo", str1, str2)
  425. if err != nil {
  426. t.Error(err)
  427. }
  428. offset1 = make([]byte, 32)
  429. offset1[31] = 64
  430. length1 = make([]byte, 32)
  431. length1[31] = byte(len(str1))
  432. value1 = common.RightPadBytes([]byte(str1), 64)
  433. offset2[31] = 160
  434. exp2 = append(offset1, offset2...)
  435. exp2 = append(exp2, append(length1, value1...)...)
  436. exp2 = append(exp2, append(length2, value2...)...)
  437. // ignore first 4 bytes of the output. This is the function identifier
  438. str2pack = str2pack[4:]
  439. if !bytes.Equal(str2pack, exp2) {
  440. t.Errorf("expected %x, got %x\n", exp, str2pack)
  441. }
  442. // test two strings, first > 32, second >32
  443. str1 = strings.Repeat("a", 33)
  444. str2 = strings.Repeat("a", 33)
  445. str2pack, err = abi.Pack("strTwo", str1, str2)
  446. if err != nil {
  447. t.Error(err)
  448. }
  449. offset1 = make([]byte, 32)
  450. offset1[31] = 64
  451. length1 = make([]byte, 32)
  452. length1[31] = byte(len(str1))
  453. value1 = common.RightPadBytes([]byte(str1), 64)
  454. offset2 = make([]byte, 32)
  455. offset2[31] = 160
  456. length2 = make([]byte, 32)
  457. length2[31] = byte(len(str2))
  458. value2 = common.RightPadBytes([]byte(str2), 64)
  459. exp2 = append(offset1, offset2...)
  460. exp2 = append(exp2, append(length1, value1...)...)
  461. exp2 = append(exp2, append(length2, value2...)...)
  462. // ignore first 4 bytes of the output. This is the function identifier
  463. str2pack = str2pack[4:]
  464. if !bytes.Equal(str2pack, exp2) {
  465. t.Errorf("expected %x, got %x\n", exp, str2pack)
  466. }
  467. }
  468. func TestDefaultFunctionParsing(t *testing.T) {
  469. const definition = `[{ "name" : "balance" }]`
  470. abi, err := JSON(strings.NewReader(definition))
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. if _, ok := abi.Methods["balance"]; !ok {
  475. t.Error("expected 'balance' to be present")
  476. }
  477. }
  478. func TestBareEvents(t *testing.T) {
  479. const definition = `[
  480. { "type" : "event", "name" : "balance" },
  481. { "type" : "event", "name" : "name" }]`
  482. abi, err := JSON(strings.NewReader(definition))
  483. if err != nil {
  484. t.Fatal(err)
  485. }
  486. if len(abi.Events) != 2 {
  487. t.Error("expected 2 events")
  488. }
  489. if _, ok := abi.Events["balance"]; !ok {
  490. t.Error("expected 'balance' event to be present")
  491. }
  492. if _, ok := abi.Events["name"]; !ok {
  493. t.Error("expected 'name' event to be present")
  494. }
  495. }
  496. func TestMultiReturnWithStruct(t *testing.T) {
  497. const definition = `[
  498. { "name" : "multi", "const" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  499. abi, err := JSON(strings.NewReader(definition))
  500. if err != nil {
  501. t.Fatal(err)
  502. }
  503. // using buff to make the code readable
  504. buff := new(bytes.Buffer)
  505. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  506. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  507. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  508. stringOut := "hello"
  509. buff.Write(common.RightPadBytes([]byte(stringOut), 32))
  510. var inter struct {
  511. Int *big.Int
  512. String string
  513. }
  514. err = abi.Unpack(&inter, "multi", buff.Bytes())
  515. if err != nil {
  516. t.Error(err)
  517. }
  518. if inter.Int == nil || inter.Int.Cmp(big.NewInt(1)) != 0 {
  519. t.Error("expected Int to be 1 got", inter.Int)
  520. }
  521. if inter.String != stringOut {
  522. t.Error("expected String to be", stringOut, "got", inter.String)
  523. }
  524. var reversed struct {
  525. String string
  526. Int *big.Int
  527. }
  528. err = abi.Unpack(&reversed, "multi", buff.Bytes())
  529. if err != nil {
  530. t.Error(err)
  531. }
  532. if reversed.Int == nil || reversed.Int.Cmp(big.NewInt(1)) != 0 {
  533. t.Error("expected Int to be 1 got", reversed.Int)
  534. }
  535. if reversed.String != stringOut {
  536. t.Error("expected String to be", stringOut, "got", reversed.String)
  537. }
  538. }
  539. func TestMultiReturnWithSlice(t *testing.T) {
  540. const definition = `[
  541. { "name" : "multi", "const" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  542. abi, err := JSON(strings.NewReader(definition))
  543. if err != nil {
  544. t.Fatal(err)
  545. }
  546. // using buff to make the code readable
  547. buff := new(bytes.Buffer)
  548. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  549. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  550. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  551. stringOut := "hello"
  552. buff.Write(common.RightPadBytes([]byte(stringOut), 32))
  553. var inter []interface{}
  554. err = abi.Unpack(&inter, "multi", buff.Bytes())
  555. if err != nil {
  556. t.Error(err)
  557. }
  558. if len(inter) != 2 {
  559. t.Fatal("expected 2 results got", len(inter))
  560. }
  561. if num, ok := inter[0].(*big.Int); !ok || num.Cmp(big.NewInt(1)) != 0 {
  562. t.Error("expected index 0 to be 1 got", num)
  563. }
  564. if str, ok := inter[1].(string); !ok || str != stringOut {
  565. t.Error("expected index 1 to be", stringOut, "got", str)
  566. }
  567. }
  568. func TestMarshalArrays(t *testing.T) {
  569. const definition = `[
  570. { "name" : "bytes32", "const" : false, "outputs": [ { "type": "bytes32" } ] },
  571. { "name" : "bytes10", "const" : false, "outputs": [ { "type": "bytes10" } ] }
  572. ]`
  573. abi, err := JSON(strings.NewReader(definition))
  574. if err != nil {
  575. t.Fatal(err)
  576. }
  577. output := common.LeftPadBytes([]byte{1}, 32)
  578. var bytes10 [10]byte
  579. err = abi.Unpack(&bytes10, "bytes32", output)
  580. if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
  581. t.Error("expected error or bytes32 not be assignable to bytes10:", err)
  582. }
  583. var bytes32 [32]byte
  584. err = abi.Unpack(&bytes32, "bytes32", output)
  585. if err != nil {
  586. t.Error("didn't expect error:", err)
  587. }
  588. if !bytes.Equal(bytes32[:], output) {
  589. t.Error("expected bytes32[31] to be 1 got", bytes32[31])
  590. }
  591. type (
  592. B10 [10]byte
  593. B32 [32]byte
  594. )
  595. var b10 B10
  596. err = abi.Unpack(&b10, "bytes32", output)
  597. if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
  598. t.Error("expected error or bytes32 not be assignable to bytes10:", err)
  599. }
  600. var b32 B32
  601. err = abi.Unpack(&b32, "bytes32", output)
  602. if err != nil {
  603. t.Error("didn't expect error:", err)
  604. }
  605. if !bytes.Equal(b32[:], output) {
  606. t.Error("expected bytes32[31] to be 1 got", bytes32[31])
  607. }
  608. output[10] = 1
  609. var shortAssignLong [32]byte
  610. err = abi.Unpack(&shortAssignLong, "bytes10", output)
  611. if err != nil {
  612. t.Error("didn't expect error:", err)
  613. }
  614. if !bytes.Equal(output, shortAssignLong[:]) {
  615. t.Errorf("expected %x to be %x", shortAssignLong, output)
  616. }
  617. }
  618. func TestUnmarshal(t *testing.T) {
  619. const definition = `[
  620. { "name" : "int", "const" : false, "outputs": [ { "type": "uint256" } ] },
  621. { "name" : "bool", "const" : false, "outputs": [ { "type": "bool" } ] },
  622. { "name" : "bytes", "const" : false, "outputs": [ { "type": "bytes" } ] },
  623. { "name" : "fixed", "const" : false, "outputs": [ { "type": "bytes32" } ] },
  624. { "name" : "multi", "const" : false, "outputs": [ { "type": "bytes" }, { "type": "bytes" } ] },
  625. { "name" : "addressSliceSingle", "const" : false, "outputs": [ { "type": "address[]" } ] },
  626. { "name" : "addressSliceDouble", "const" : false, "outputs": [ { "name": "a", "type": "address[]" }, { "name": "b", "type": "address[]" } ] },
  627. { "name" : "mixedBytes", "const" : true, "outputs": [ { "name": "a", "type": "bytes" }, { "name": "b", "type": "bytes32" } ] }]`
  628. abi, err := JSON(strings.NewReader(definition))
  629. if err != nil {
  630. t.Fatal(err)
  631. }
  632. buff := new(bytes.Buffer)
  633. // marshal int
  634. var Int *big.Int
  635. err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  636. if err != nil {
  637. t.Error(err)
  638. }
  639. if Int == nil || Int.Cmp(big.NewInt(1)) != 0 {
  640. t.Error("expected Int to be 1 got", Int)
  641. }
  642. // marshal bool
  643. var Bool bool
  644. err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  645. if err != nil {
  646. t.Error(err)
  647. }
  648. if !Bool {
  649. t.Error("expected Bool to be true")
  650. }
  651. // marshal dynamic bytes max length 32
  652. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  653. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  654. bytesOut := common.RightPadBytes([]byte("hello"), 32)
  655. buff.Write(bytesOut)
  656. var Bytes []byte
  657. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  658. if err != nil {
  659. t.Error(err)
  660. }
  661. if !bytes.Equal(Bytes, bytesOut) {
  662. t.Errorf("expected %x got %x", bytesOut, Bytes)
  663. }
  664. // marshall dynamic bytes max length 64
  665. buff.Reset()
  666. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  667. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  668. bytesOut = common.RightPadBytes([]byte("hello"), 64)
  669. buff.Write(bytesOut)
  670. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  671. if err != nil {
  672. t.Error(err)
  673. }
  674. if !bytes.Equal(Bytes, bytesOut) {
  675. t.Errorf("expected %x got %x", bytesOut, Bytes)
  676. }
  677. // marshall dynamic bytes max length 63
  678. buff.Reset()
  679. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  680. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000003f"))
  681. bytesOut = common.RightPadBytes([]byte("hello"), 63)
  682. buff.Write(bytesOut)
  683. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  684. if err != nil {
  685. t.Error(err)
  686. }
  687. if !bytes.Equal(Bytes, bytesOut) {
  688. t.Errorf("expected %x got %x", bytesOut, Bytes)
  689. }
  690. // marshal dynamic bytes output empty
  691. err = abi.Unpack(&Bytes, "bytes", nil)
  692. if err == nil {
  693. t.Error("expected error")
  694. }
  695. // marshal dynamic bytes length 5
  696. buff.Reset()
  697. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  698. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  699. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  700. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  701. if err != nil {
  702. t.Error(err)
  703. }
  704. if !bytes.Equal(Bytes, []byte("hello")) {
  705. t.Errorf("expected %x got %x", bytesOut, Bytes)
  706. }
  707. // marshal dynamic bytes length 5
  708. buff.Reset()
  709. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  710. var hash common.Hash
  711. err = abi.Unpack(&hash, "fixed", buff.Bytes())
  712. if err != nil {
  713. t.Error(err)
  714. }
  715. helloHash := common.BytesToHash(common.RightPadBytes([]byte("hello"), 32))
  716. if hash != helloHash {
  717. t.Errorf("Expected %x to equal %x", hash, helloHash)
  718. }
  719. // marshal error
  720. buff.Reset()
  721. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  722. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  723. if err == nil {
  724. t.Error("expected error")
  725. }
  726. err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
  727. if err == nil {
  728. t.Error("expected error")
  729. }
  730. // marshal mixed bytes
  731. buff.Reset()
  732. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  733. fixed := common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")
  734. buff.Write(fixed)
  735. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  736. bytesOut = common.RightPadBytes([]byte("hello"), 32)
  737. buff.Write(bytesOut)
  738. var out []interface{}
  739. err = abi.Unpack(&out, "mixedBytes", buff.Bytes())
  740. if err != nil {
  741. t.Fatal("didn't expect error:", err)
  742. }
  743. if !bytes.Equal(bytesOut, out[0].([]byte)) {
  744. t.Errorf("expected %x, got %x", bytesOut, out[0])
  745. }
  746. if !bytes.Equal(fixed, out[1].([]byte)) {
  747. t.Errorf("expected %x, got %x", fixed, out[1])
  748. }
  749. // marshal address slice
  750. buff.Reset()
  751. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) // offset
  752. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  753. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  754. var outAddr []common.Address
  755. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  756. if err != nil {
  757. t.Fatal("didn't expect error:", err)
  758. }
  759. if len(outAddr) != 1 {
  760. t.Fatal("expected 1 item, got", len(outAddr))
  761. }
  762. if outAddr[0] != (common.Address{1}) {
  763. t.Errorf("expected %x, got %x", common.Address{1}, outAddr[0])
  764. }
  765. // marshal multiple address slice
  766. buff.Reset()
  767. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // offset
  768. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // offset
  769. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  770. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  771. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // size
  772. buff.Write(common.Hex2Bytes("0000000000000000000000000200000000000000000000000000000000000000"))
  773. buff.Write(common.Hex2Bytes("0000000000000000000000000300000000000000000000000000000000000000"))
  774. var outAddrStruct struct {
  775. A []common.Address
  776. B []common.Address
  777. }
  778. err = abi.Unpack(&outAddrStruct, "addressSliceDouble", buff.Bytes())
  779. if err != nil {
  780. t.Fatal("didn't expect error:", err)
  781. }
  782. if len(outAddrStruct.A) != 1 {
  783. t.Fatal("expected 1 item, got", len(outAddrStruct.A))
  784. }
  785. if outAddrStruct.A[0] != (common.Address{1}) {
  786. t.Errorf("expected %x, got %x", common.Address{1}, outAddrStruct.A[0])
  787. }
  788. if len(outAddrStruct.B) != 2 {
  789. t.Fatal("expected 1 item, got", len(outAddrStruct.B))
  790. }
  791. if outAddrStruct.B[0] != (common.Address{2}) {
  792. t.Errorf("expected %x, got %x", common.Address{2}, outAddrStruct.B[0])
  793. }
  794. if outAddrStruct.B[1] != (common.Address{3}) {
  795. t.Errorf("expected %x, got %x", common.Address{3}, outAddrStruct.B[1])
  796. }
  797. // marshal invalid address slice
  798. buff.Reset()
  799. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000100"))
  800. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  801. if err == nil {
  802. t.Fatal("expected error:", err)
  803. }
  804. }