abi_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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 string
  49. }{
  50. {"uint", big.NewInt(1), ""},
  51. {"int", big.NewInt(1), ""},
  52. {"uint30", big.NewInt(1), ""},
  53. {"uint30", uint8(1), "abi: cannot use uint8 as type ptr as argument"},
  54. {"uint16", uint16(1), ""},
  55. {"uint16", uint8(1), "abi: cannot use uint8 as type uint16 as argument"},
  56. {"uint16[]", []uint16{1, 2, 3}, ""},
  57. {"uint16[]", [3]uint16{1, 2, 3}, ""},
  58. {"uint16[]", []uint32{1, 2, 3}, "abi: cannot use []uint32 as type []uint16 as argument"},
  59. {"uint16[3]", [3]uint32{1, 2, 3}, "abi: cannot use [3]uint32 as type [3]uint16 as argument"},
  60. {"uint16[3]", [4]uint16{1, 2, 3}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"},
  61. {"uint16[3]", []uint16{1, 2, 3}, ""},
  62. {"uint16[3]", []uint16{1, 2, 3, 4}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"},
  63. {"address[]", []common.Address{common.Address{1}}, ""},
  64. {"address[1]", []common.Address{common.Address{1}}, ""},
  65. {"address[1]", [1]common.Address{common.Address{1}}, ""},
  66. {"address[2]", [1]common.Address{common.Address{1}}, "abi: cannot use [1]array as type [2]array as argument"},
  67. {"bytes32", [32]byte{}, ""},
  68. {"bytes32", [33]byte{}, "abi: cannot use [33]uint8 as type [32]uint8 as argument"},
  69. {"bytes32", common.Hash{1}, ""},
  70. {"bytes31", [31]byte{}, ""},
  71. {"bytes31", [32]byte{}, "abi: cannot use [32]uint8 as type [31]uint8 as argument"},
  72. {"bytes", []byte{0, 1}, ""},
  73. {"bytes", [2]byte{0, 1}, ""},
  74. {"bytes", common.Hash{1}, ""},
  75. {"string", "hello world", ""},
  76. {"bytes32[]", [][32]byte{[32]byte{}}, ""},
  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 && len(test.err) == 0 {
  84. t.Errorf("%d failed. Expected no err but got: %v", i, err)
  85. continue
  86. }
  87. if err == nil && len(test.err) != 0 {
  88. t.Errorf("%d failed. Expected err: %v but got none", i, test.err)
  89. continue
  90. }
  91. if err != nil && len(test.err) != 0 && err.Error() != test.err {
  92. t.Errorf("%d failed. Expected err: '%v' got err: '%v'", i, test.err, err)
  93. }
  94. }
  95. }
  96. func TestSimpleMethodUnpack(t *testing.T) {
  97. for i, test := range []struct {
  98. def string // definition of the **output** ABI params
  99. marshalledOutput []byte // evm return data
  100. expectedOut interface{} // the expected output
  101. outVar string // the output variable (e.g. uint32, *big.Int, etc)
  102. err string // empty or error if expected
  103. }{
  104. {
  105. `[ { "type": "uint32" } ]`,
  106. pad([]byte{1}, 32, true),
  107. uint32(1),
  108. "uint32",
  109. "",
  110. },
  111. {
  112. `[ { "type": "uint32" } ]`,
  113. pad([]byte{1}, 32, true),
  114. nil,
  115. "uint16",
  116. "abi: cannot unmarshal uint32 in to uint16",
  117. },
  118. {
  119. `[ { "type": "uint17" } ]`,
  120. pad([]byte{1}, 32, true),
  121. nil,
  122. "uint16",
  123. "abi: cannot unmarshal *big.Int in to uint16",
  124. },
  125. {
  126. `[ { "type": "uint17" } ]`,
  127. pad([]byte{1}, 32, true),
  128. big.NewInt(1),
  129. "*big.Int",
  130. "",
  131. },
  132. {
  133. `[ { "type": "int32" } ]`,
  134. pad([]byte{1}, 32, true),
  135. int32(1),
  136. "int32",
  137. "",
  138. },
  139. {
  140. `[ { "type": "int32" } ]`,
  141. pad([]byte{1}, 32, true),
  142. nil,
  143. "int16",
  144. "abi: cannot unmarshal int32 in to int16",
  145. },
  146. {
  147. `[ { "type": "int17" } ]`,
  148. pad([]byte{1}, 32, true),
  149. nil,
  150. "int16",
  151. "abi: cannot unmarshal *big.Int in to int16",
  152. },
  153. {
  154. `[ { "type": "int17" } ]`,
  155. pad([]byte{1}, 32, true),
  156. big.NewInt(1),
  157. "*big.Int",
  158. "",
  159. },
  160. {
  161. `[ { "type": "address" } ]`,
  162. pad(pad([]byte{1}, 20, false), 32, true),
  163. common.Address{1},
  164. "address",
  165. "",
  166. },
  167. {
  168. `[ { "type": "bytes32" } ]`,
  169. pad([]byte{1}, 32, false),
  170. pad([]byte{1}, 32, false),
  171. "bytes",
  172. "",
  173. },
  174. {
  175. `[ { "type": "bytes32" } ]`,
  176. pad([]byte{1}, 32, false),
  177. pad([]byte{1}, 32, false),
  178. "hash",
  179. "",
  180. },
  181. {
  182. `[ { "type": "bytes32" } ]`,
  183. pad([]byte{1}, 32, false),
  184. pad([]byte{1}, 32, false),
  185. "interface",
  186. "",
  187. },
  188. } {
  189. abiDefinition := fmt.Sprintf(`[{ "name" : "method", "outputs": %s}]`, test.def)
  190. abi, err := JSON(strings.NewReader(abiDefinition))
  191. if err != nil {
  192. t.Errorf("%d failed. %v", i, err)
  193. continue
  194. }
  195. var outvar interface{}
  196. switch test.outVar {
  197. case "uint8":
  198. var v uint8
  199. err = abi.Unpack(&v, "method", test.marshalledOutput)
  200. outvar = v
  201. case "uint16":
  202. var v uint16
  203. err = abi.Unpack(&v, "method", test.marshalledOutput)
  204. outvar = v
  205. case "uint32":
  206. var v uint32
  207. err = abi.Unpack(&v, "method", test.marshalledOutput)
  208. outvar = v
  209. case "uint64":
  210. var v uint64
  211. err = abi.Unpack(&v, "method", test.marshalledOutput)
  212. outvar = v
  213. case "int8":
  214. var v int8
  215. err = abi.Unpack(&v, "method", test.marshalledOutput)
  216. outvar = v
  217. case "int16":
  218. var v int16
  219. err = abi.Unpack(&v, "method", test.marshalledOutput)
  220. outvar = v
  221. case "int32":
  222. var v int32
  223. err = abi.Unpack(&v, "method", test.marshalledOutput)
  224. outvar = v
  225. case "int64":
  226. var v int64
  227. err = abi.Unpack(&v, "method", test.marshalledOutput)
  228. outvar = v
  229. case "*big.Int":
  230. var v *big.Int
  231. err = abi.Unpack(&v, "method", test.marshalledOutput)
  232. outvar = v
  233. case "address":
  234. var v common.Address
  235. err = abi.Unpack(&v, "method", test.marshalledOutput)
  236. outvar = v
  237. case "bytes":
  238. var v []byte
  239. err = abi.Unpack(&v, "method", test.marshalledOutput)
  240. outvar = v
  241. case "hash":
  242. var v common.Hash
  243. err = abi.Unpack(&v, "method", test.marshalledOutput)
  244. outvar = v
  245. case "interface":
  246. err = abi.Unpack(&outvar, "method", test.marshalledOutput)
  247. default:
  248. t.Errorf("unsupported type '%v' please add it to the switch statement in this test", test.outVar)
  249. continue
  250. }
  251. if err != nil && len(test.err) == 0 {
  252. t.Errorf("%d failed. Expected no err but got: %v", i, err)
  253. continue
  254. }
  255. if err == nil && len(test.err) != 0 {
  256. t.Errorf("%d failed. Expected err: %v but got none", i, test.err)
  257. continue
  258. }
  259. if err != nil && len(test.err) != 0 && err.Error() != test.err {
  260. t.Errorf("%d failed. Expected err: '%v' got err: '%v'", i, test.err, err)
  261. continue
  262. }
  263. if err == nil {
  264. // bit of an ugly hack for hash type but I don't feel like finding a proper solution
  265. if test.outVar == "hash" {
  266. tmp := outvar.(common.Hash) // without assignment it's unaddressable
  267. outvar = tmp[:]
  268. }
  269. if !reflect.DeepEqual(test.expectedOut, outvar) {
  270. t.Errorf("%d failed. Output error: expected %v, got %v", i, test.expectedOut, outvar)
  271. }
  272. }
  273. }
  274. }
  275. func TestUnpackSetInterfaceSlice(t *testing.T) {
  276. var (
  277. var1 = new(uint8)
  278. var2 = new(uint8)
  279. )
  280. out := []interface{}{var1, var2}
  281. abi, err := JSON(strings.NewReader(`[{"type":"function", "name":"ints", "outputs":[{"type":"uint8"}, {"type":"uint8"}]}]`))
  282. if err != nil {
  283. t.Fatal(err)
  284. }
  285. marshalledReturn := append(pad([]byte{1}, 32, true), pad([]byte{2}, 32, true)...)
  286. err = abi.Unpack(&out, "ints", marshalledReturn)
  287. if err != nil {
  288. t.Fatal(err)
  289. }
  290. if *var1 != 1 {
  291. t.Error("expected var1 to be 1, got", *var1)
  292. }
  293. if *var2 != 2 {
  294. t.Error("expected var2 to be 2, got", *var2)
  295. }
  296. out = []interface{}{var1}
  297. err = abi.Unpack(&out, "ints", marshalledReturn)
  298. expErr := "abi: cannot marshal in to slices of unequal size (require: 2, got: 1)"
  299. if err == nil || err.Error() != expErr {
  300. t.Error("expected err:", expErr, "Got:", err)
  301. }
  302. }
  303. func TestPack(t *testing.T) {
  304. for i, test := range []struct {
  305. typ string
  306. input interface{}
  307. output []byte
  308. }{
  309. {"uint16", uint16(2), pad([]byte{2}, 32, true)},
  310. {"uint16[]", []uint16{1, 2}, formatSliceOutput([]byte{1}, []byte{2})},
  311. {"bytes20", [20]byte{1}, pad([]byte{1}, 32, false)},
  312. {"uint256[]", []*big.Int{big.NewInt(1), big.NewInt(2)}, formatSliceOutput([]byte{1}, []byte{2})},
  313. {"address[]", []common.Address{common.Address{1}, common.Address{2}}, formatSliceOutput(pad([]byte{1}, 20, false), pad([]byte{2}, 20, false))},
  314. {"bytes32[]", []common.Hash{common.Hash{1}, common.Hash{2}}, formatSliceOutput(pad([]byte{1}, 32, false), pad([]byte{2}, 32, false))},
  315. } {
  316. typ, err := NewType(test.typ)
  317. if err != nil {
  318. t.Fatal("unexpected parse error:", err)
  319. }
  320. output, err := typ.pack(reflect.ValueOf(test.input))
  321. if err != nil {
  322. t.Fatal("unexpected pack error:", err)
  323. }
  324. if !bytes.Equal(output, test.output) {
  325. t.Errorf("%d failed. Expected bytes: '%x' Got: '%x'", i, test.output, output)
  326. }
  327. }
  328. }
  329. func TestMethodPack(t *testing.T) {
  330. abi, err := JSON(strings.NewReader(jsondata2))
  331. if err != nil {
  332. t.Fatal(err)
  333. }
  334. sig := abi.Methods["slice"].Id()
  335. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  336. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  337. sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...)
  338. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  339. packed, err := abi.Pack("slice", []uint32{1, 2})
  340. if err != nil {
  341. t.Error(err)
  342. }
  343. if !bytes.Equal(packed, sig) {
  344. t.Errorf("expected %x got %x", sig, packed)
  345. }
  346. var addrA, addrB = common.Address{1}, common.Address{2}
  347. sig = abi.Methods["sliceAddress"].Id()
  348. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  349. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  350. sig = append(sig, common.LeftPadBytes(addrA[:], 32)...)
  351. sig = append(sig, common.LeftPadBytes(addrB[:], 32)...)
  352. packed, err = abi.Pack("sliceAddress", []common.Address{addrA, addrB})
  353. if err != nil {
  354. t.Fatal(err)
  355. }
  356. if !bytes.Equal(packed, sig) {
  357. t.Errorf("expected %x got %x", sig, packed)
  358. }
  359. var addrC, addrD = common.Address{3}, common.Address{4}
  360. sig = abi.Methods["sliceMultiAddress"].Id()
  361. sig = append(sig, common.LeftPadBytes([]byte{64}, 32)...)
  362. sig = append(sig, common.LeftPadBytes([]byte{160}, 32)...)
  363. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  364. sig = append(sig, common.LeftPadBytes(addrA[:], 32)...)
  365. sig = append(sig, common.LeftPadBytes(addrB[:], 32)...)
  366. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  367. sig = append(sig, common.LeftPadBytes(addrC[:], 32)...)
  368. sig = append(sig, common.LeftPadBytes(addrD[:], 32)...)
  369. packed, err = abi.Pack("sliceMultiAddress", []common.Address{addrA, addrB}, []common.Address{addrC, addrD})
  370. if err != nil {
  371. t.Fatal(err)
  372. }
  373. if !bytes.Equal(packed, sig) {
  374. t.Errorf("expected %x got %x", sig, packed)
  375. }
  376. sig = abi.Methods["slice256"].Id()
  377. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  378. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  379. sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...)
  380. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  381. packed, err = abi.Pack("slice256", []*big.Int{big.NewInt(1), big.NewInt(2)})
  382. if err != nil {
  383. t.Error(err)
  384. }
  385. if !bytes.Equal(packed, sig) {
  386. t.Errorf("expected %x got %x", sig, packed)
  387. }
  388. }
  389. const jsondata = `
  390. [
  391. { "type" : "function", "name" : "balance", "constant" : true },
  392. { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }
  393. ]`
  394. const jsondata2 = `
  395. [
  396. { "type" : "function", "name" : "balance", "constant" : true },
  397. { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
  398. { "type" : "function", "name" : "test", "constant" : false, "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
  399. { "type" : "function", "name" : "string", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
  400. { "type" : "function", "name" : "bool", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
  401. { "type" : "function", "name" : "address", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
  402. { "type" : "function", "name" : "uint64[2]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
  403. { "type" : "function", "name" : "uint64[]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
  404. { "type" : "function", "name" : "foo", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
  405. { "type" : "function", "name" : "bar", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
  406. { "type" : "function", "name" : "slice", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
  407. { "type" : "function", "name" : "slice256", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
  408. { "type" : "function", "name" : "sliceAddress", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
  409. { "type" : "function", "name" : "sliceMultiAddress", "constant" : false, "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] }
  410. ]`
  411. func TestReader(t *testing.T) {
  412. Uint256, _ := NewType("uint256")
  413. exp := ABI{
  414. Methods: map[string]Method{
  415. "balance": Method{
  416. "balance", true, nil, nil,
  417. },
  418. "send": Method{
  419. "send", false, []Argument{
  420. Argument{"amount", Uint256, false},
  421. }, nil,
  422. },
  423. },
  424. }
  425. abi, err := JSON(strings.NewReader(jsondata))
  426. if err != nil {
  427. t.Error(err)
  428. }
  429. // deep equal fails for some reason
  430. t.Skip()
  431. if !reflect.DeepEqual(abi, exp) {
  432. t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp)
  433. }
  434. }
  435. func TestTestNumbers(t *testing.T) {
  436. abi, err := JSON(strings.NewReader(jsondata2))
  437. if err != nil {
  438. t.Error(err)
  439. t.FailNow()
  440. }
  441. if _, err := abi.Pack("balance"); err != nil {
  442. t.Error(err)
  443. }
  444. if _, err := abi.Pack("balance", 1); err == nil {
  445. t.Error("expected error for balance(1)")
  446. }
  447. if _, err := abi.Pack("doesntexist", nil); err == nil {
  448. t.Errorf("doesntexist shouldn't exist")
  449. }
  450. if _, err := abi.Pack("doesntexist", 1); err == nil {
  451. t.Errorf("doesntexist(1) shouldn't exist")
  452. }
  453. if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
  454. t.Error(err)
  455. }
  456. i := new(int)
  457. *i = 1000
  458. if _, err := abi.Pack("send", i); err == nil {
  459. t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
  460. }
  461. if _, err := abi.Pack("test", uint32(1000)); err != nil {
  462. t.Error(err)
  463. }
  464. }
  465. func TestTestString(t *testing.T) {
  466. abi, err := JSON(strings.NewReader(jsondata2))
  467. if err != nil {
  468. t.Error(err)
  469. t.FailNow()
  470. }
  471. if _, err := abi.Pack("string", "hello world"); err != nil {
  472. t.Error(err)
  473. }
  474. }
  475. func TestTestBool(t *testing.T) {
  476. abi, err := JSON(strings.NewReader(jsondata2))
  477. if err != nil {
  478. t.Error(err)
  479. t.FailNow()
  480. }
  481. if _, err := abi.Pack("bool", true); err != nil {
  482. t.Error(err)
  483. }
  484. }
  485. func TestTestSlice(t *testing.T) {
  486. abi, err := JSON(strings.NewReader(jsondata2))
  487. if err != nil {
  488. t.Error(err)
  489. t.FailNow()
  490. }
  491. slice := make([]uint64, 2)
  492. if _, err := abi.Pack("uint64[2]", slice); err != nil {
  493. t.Error(err)
  494. }
  495. if _, err := abi.Pack("uint64[]", slice); err != nil {
  496. t.Error(err)
  497. }
  498. }
  499. func TestMethodSignature(t *testing.T) {
  500. String, _ := NewType("string")
  501. m := Method{"foo", false, []Argument{Argument{"bar", String, false}, Argument{"baz", String, false}}, nil}
  502. exp := "foo(string,string)"
  503. if m.Sig() != exp {
  504. t.Error("signature mismatch", exp, "!=", m.Sig())
  505. }
  506. idexp := crypto.Keccak256([]byte(exp))[:4]
  507. if !bytes.Equal(m.Id(), idexp) {
  508. t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
  509. }
  510. uintt, _ := NewType("uint")
  511. m = Method{"foo", false, []Argument{Argument{"bar", uintt, false}}, nil}
  512. exp = "foo(uint256)"
  513. if m.Sig() != exp {
  514. t.Error("signature mismatch", exp, "!=", m.Sig())
  515. }
  516. }
  517. func TestMultiPack(t *testing.T) {
  518. abi, err := JSON(strings.NewReader(jsondata2))
  519. if err != nil {
  520. t.Error(err)
  521. t.FailNow()
  522. }
  523. sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
  524. sig = append(sig, make([]byte, 64)...)
  525. sig[35] = 10
  526. sig[67] = 11
  527. packed, err := abi.Pack("bar", uint32(10), uint16(11))
  528. if err != nil {
  529. t.Error(err)
  530. t.FailNow()
  531. }
  532. if !bytes.Equal(packed, sig) {
  533. t.Errorf("expected %x got %x", sig, packed)
  534. }
  535. }
  536. func ExampleJSON() {
  537. const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
  538. abi, err := JSON(strings.NewReader(definition))
  539. if err != nil {
  540. log.Fatalln(err)
  541. }
  542. out, err := abi.Pack("isBar", common.HexToAddress("01"))
  543. if err != nil {
  544. log.Fatalln(err)
  545. }
  546. fmt.Printf("%x\n", out)
  547. // Output:
  548. // 1f2c40920000000000000000000000000000000000000000000000000000000000000001
  549. }
  550. func TestInputVariableInputLength(t *testing.T) {
  551. const definition = `[
  552. { "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
  553. { "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
  554. { "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
  555. ]`
  556. abi, err := JSON(strings.NewReader(definition))
  557. if err != nil {
  558. t.Fatal(err)
  559. }
  560. // test one string
  561. strin := "hello world"
  562. strpack, err := abi.Pack("strOne", strin)
  563. if err != nil {
  564. t.Error(err)
  565. }
  566. offset := make([]byte, 32)
  567. offset[31] = 32
  568. length := make([]byte, 32)
  569. length[31] = byte(len(strin))
  570. value := common.RightPadBytes([]byte(strin), 32)
  571. exp := append(offset, append(length, value...)...)
  572. // ignore first 4 bytes of the output. This is the function identifier
  573. strpack = strpack[4:]
  574. if !bytes.Equal(strpack, exp) {
  575. t.Errorf("expected %x, got %x\n", exp, strpack)
  576. }
  577. // test one bytes
  578. btspack, err := abi.Pack("bytesOne", []byte(strin))
  579. if err != nil {
  580. t.Error(err)
  581. }
  582. // ignore first 4 bytes of the output. This is the function identifier
  583. btspack = btspack[4:]
  584. if !bytes.Equal(btspack, exp) {
  585. t.Errorf("expected %x, got %x\n", exp, btspack)
  586. }
  587. // test two strings
  588. str1 := "hello"
  589. str2 := "world"
  590. str2pack, err := abi.Pack("strTwo", str1, str2)
  591. if err != nil {
  592. t.Error(err)
  593. }
  594. offset1 := make([]byte, 32)
  595. offset1[31] = 64
  596. length1 := make([]byte, 32)
  597. length1[31] = byte(len(str1))
  598. value1 := common.RightPadBytes([]byte(str1), 32)
  599. offset2 := make([]byte, 32)
  600. offset2[31] = 128
  601. length2 := make([]byte, 32)
  602. length2[31] = byte(len(str2))
  603. value2 := common.RightPadBytes([]byte(str2), 32)
  604. exp2 := append(offset1, offset2...)
  605. exp2 = append(exp2, append(length1, value1...)...)
  606. exp2 = append(exp2, append(length2, value2...)...)
  607. // ignore first 4 bytes of the output. This is the function identifier
  608. str2pack = str2pack[4:]
  609. if !bytes.Equal(str2pack, exp2) {
  610. t.Errorf("expected %x, got %x\n", exp, str2pack)
  611. }
  612. // test two strings, first > 32, second < 32
  613. str1 = strings.Repeat("a", 33)
  614. str2pack, err = abi.Pack("strTwo", str1, str2)
  615. if err != nil {
  616. t.Error(err)
  617. }
  618. offset1 = make([]byte, 32)
  619. offset1[31] = 64
  620. length1 = make([]byte, 32)
  621. length1[31] = byte(len(str1))
  622. value1 = common.RightPadBytes([]byte(str1), 64)
  623. offset2[31] = 160
  624. exp2 = append(offset1, offset2...)
  625. exp2 = append(exp2, append(length1, value1...)...)
  626. exp2 = append(exp2, append(length2, value2...)...)
  627. // ignore first 4 bytes of the output. This is the function identifier
  628. str2pack = str2pack[4:]
  629. if !bytes.Equal(str2pack, exp2) {
  630. t.Errorf("expected %x, got %x\n", exp, str2pack)
  631. }
  632. // test two strings, first > 32, second >32
  633. str1 = strings.Repeat("a", 33)
  634. str2 = strings.Repeat("a", 33)
  635. str2pack, err = abi.Pack("strTwo", str1, str2)
  636. if err != nil {
  637. t.Error(err)
  638. }
  639. offset1 = make([]byte, 32)
  640. offset1[31] = 64
  641. length1 = make([]byte, 32)
  642. length1[31] = byte(len(str1))
  643. value1 = common.RightPadBytes([]byte(str1), 64)
  644. offset2 = make([]byte, 32)
  645. offset2[31] = 160
  646. length2 = make([]byte, 32)
  647. length2[31] = byte(len(str2))
  648. value2 = common.RightPadBytes([]byte(str2), 64)
  649. exp2 = append(offset1, offset2...)
  650. exp2 = append(exp2, append(length1, value1...)...)
  651. exp2 = append(exp2, append(length2, value2...)...)
  652. // ignore first 4 bytes of the output. This is the function identifier
  653. str2pack = str2pack[4:]
  654. if !bytes.Equal(str2pack, exp2) {
  655. t.Errorf("expected %x, got %x\n", exp, str2pack)
  656. }
  657. }
  658. func TestDefaultFunctionParsing(t *testing.T) {
  659. const definition = `[{ "name" : "balance" }]`
  660. abi, err := JSON(strings.NewReader(definition))
  661. if err != nil {
  662. t.Fatal(err)
  663. }
  664. if _, ok := abi.Methods["balance"]; !ok {
  665. t.Error("expected 'balance' to be present")
  666. }
  667. }
  668. func TestBareEvents(t *testing.T) {
  669. const definition = `[
  670. { "type" : "event", "name" : "balance" },
  671. { "type" : "event", "name" : "name" }]`
  672. abi, err := JSON(strings.NewReader(definition))
  673. if err != nil {
  674. t.Fatal(err)
  675. }
  676. if len(abi.Events) != 2 {
  677. t.Error("expected 2 events")
  678. }
  679. if _, ok := abi.Events["balance"]; !ok {
  680. t.Error("expected 'balance' event to be present")
  681. }
  682. if _, ok := abi.Events["name"]; !ok {
  683. t.Error("expected 'name' event to be present")
  684. }
  685. }
  686. func TestMultiReturnWithStruct(t *testing.T) {
  687. const definition = `[
  688. { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  689. abi, err := JSON(strings.NewReader(definition))
  690. if err != nil {
  691. t.Fatal(err)
  692. }
  693. // using buff to make the code readable
  694. buff := new(bytes.Buffer)
  695. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  696. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  697. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  698. stringOut := "hello"
  699. buff.Write(common.RightPadBytes([]byte(stringOut), 32))
  700. var inter struct {
  701. Int *big.Int
  702. String string
  703. }
  704. err = abi.Unpack(&inter, "multi", buff.Bytes())
  705. if err != nil {
  706. t.Error(err)
  707. }
  708. if inter.Int == nil || inter.Int.Cmp(big.NewInt(1)) != 0 {
  709. t.Error("expected Int to be 1 got", inter.Int)
  710. }
  711. if inter.String != stringOut {
  712. t.Error("expected String to be", stringOut, "got", inter.String)
  713. }
  714. var reversed struct {
  715. String string
  716. Int *big.Int
  717. }
  718. err = abi.Unpack(&reversed, "multi", buff.Bytes())
  719. if err != nil {
  720. t.Error(err)
  721. }
  722. if reversed.Int == nil || reversed.Int.Cmp(big.NewInt(1)) != 0 {
  723. t.Error("expected Int to be 1 got", reversed.Int)
  724. }
  725. if reversed.String != stringOut {
  726. t.Error("expected String to be", stringOut, "got", reversed.String)
  727. }
  728. }
  729. func TestMultiReturnWithSlice(t *testing.T) {
  730. const definition = `[
  731. { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  732. abi, err := JSON(strings.NewReader(definition))
  733. if err != nil {
  734. t.Fatal(err)
  735. }
  736. // using buff to make the code readable
  737. buff := new(bytes.Buffer)
  738. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  739. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  740. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  741. stringOut := "hello"
  742. buff.Write(common.RightPadBytes([]byte(stringOut), 32))
  743. var inter []interface{}
  744. err = abi.Unpack(&inter, "multi", buff.Bytes())
  745. if err != nil {
  746. t.Error(err)
  747. }
  748. if len(inter) != 2 {
  749. t.Fatal("expected 2 results got", len(inter))
  750. }
  751. if num, ok := inter[0].(*big.Int); !ok || num.Cmp(big.NewInt(1)) != 0 {
  752. t.Error("expected index 0 to be 1 got", num)
  753. }
  754. if str, ok := inter[1].(string); !ok || str != stringOut {
  755. t.Error("expected index 1 to be", stringOut, "got", str)
  756. }
  757. }
  758. func TestMarshalArrays(t *testing.T) {
  759. const definition = `[
  760. { "name" : "bytes32", "constant" : false, "outputs": [ { "type": "bytes32" } ] },
  761. { "name" : "bytes10", "constant" : false, "outputs": [ { "type": "bytes10" } ] }
  762. ]`
  763. abi, err := JSON(strings.NewReader(definition))
  764. if err != nil {
  765. t.Fatal(err)
  766. }
  767. output := common.LeftPadBytes([]byte{1}, 32)
  768. var bytes10 [10]byte
  769. err = abi.Unpack(&bytes10, "bytes32", output)
  770. if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
  771. t.Error("expected error or bytes32 not be assignable to bytes10:", err)
  772. }
  773. var bytes32 [32]byte
  774. err = abi.Unpack(&bytes32, "bytes32", output)
  775. if err != nil {
  776. t.Error("didn't expect error:", err)
  777. }
  778. if !bytes.Equal(bytes32[:], output) {
  779. t.Error("expected bytes32[31] to be 1 got", bytes32[31])
  780. }
  781. type (
  782. B10 [10]byte
  783. B32 [32]byte
  784. )
  785. var b10 B10
  786. err = abi.Unpack(&b10, "bytes32", output)
  787. if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
  788. t.Error("expected error or bytes32 not be assignable to bytes10:", err)
  789. }
  790. var b32 B32
  791. err = abi.Unpack(&b32, "bytes32", output)
  792. if err != nil {
  793. t.Error("didn't expect error:", err)
  794. }
  795. if !bytes.Equal(b32[:], output) {
  796. t.Error("expected bytes32[31] to be 1 got", bytes32[31])
  797. }
  798. output[10] = 1
  799. var shortAssignLong [32]byte
  800. err = abi.Unpack(&shortAssignLong, "bytes10", output)
  801. if err != nil {
  802. t.Error("didn't expect error:", err)
  803. }
  804. if !bytes.Equal(output, shortAssignLong[:]) {
  805. t.Errorf("expected %x to be %x", shortAssignLong, output)
  806. }
  807. }
  808. func TestUnmarshal(t *testing.T) {
  809. const definition = `[
  810. { "name" : "int", "constant" : false, "outputs": [ { "type": "uint256" } ] },
  811. { "name" : "bool", "constant" : false, "outputs": [ { "type": "bool" } ] },
  812. { "name" : "bytes", "constant" : false, "outputs": [ { "type": "bytes" } ] },
  813. { "name" : "fixed", "constant" : false, "outputs": [ { "type": "bytes32" } ] },
  814. { "name" : "multi", "constant" : false, "outputs": [ { "type": "bytes" }, { "type": "bytes" } ] },
  815. { "name" : "addressSliceSingle", "constant" : false, "outputs": [ { "type": "address[]" } ] },
  816. { "name" : "addressSliceDouble", "constant" : false, "outputs": [ { "name": "a", "type": "address[]" }, { "name": "b", "type": "address[]" } ] },
  817. { "name" : "mixedBytes", "constant" : true, "outputs": [ { "name": "a", "type": "bytes" }, { "name": "b", "type": "bytes32" } ] }]`
  818. abi, err := JSON(strings.NewReader(definition))
  819. if err != nil {
  820. t.Fatal(err)
  821. }
  822. buff := new(bytes.Buffer)
  823. // marshal int
  824. var Int *big.Int
  825. err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  826. if err != nil {
  827. t.Error(err)
  828. }
  829. if Int == nil || Int.Cmp(big.NewInt(1)) != 0 {
  830. t.Error("expected Int to be 1 got", Int)
  831. }
  832. // marshal bool
  833. var Bool bool
  834. err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  835. if err != nil {
  836. t.Error(err)
  837. }
  838. if !Bool {
  839. t.Error("expected Bool to be true")
  840. }
  841. // marshal dynamic bytes max length 32
  842. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  843. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  844. bytesOut := common.RightPadBytes([]byte("hello"), 32)
  845. buff.Write(bytesOut)
  846. var Bytes []byte
  847. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  848. if err != nil {
  849. t.Error(err)
  850. }
  851. if !bytes.Equal(Bytes, bytesOut) {
  852. t.Errorf("expected %x got %x", bytesOut, Bytes)
  853. }
  854. // marshall dynamic bytes max length 64
  855. buff.Reset()
  856. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  857. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  858. bytesOut = common.RightPadBytes([]byte("hello"), 64)
  859. buff.Write(bytesOut)
  860. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  861. if err != nil {
  862. t.Error(err)
  863. }
  864. if !bytes.Equal(Bytes, bytesOut) {
  865. t.Errorf("expected %x got %x", bytesOut, Bytes)
  866. }
  867. // marshall dynamic bytes max length 63
  868. buff.Reset()
  869. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  870. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000003f"))
  871. bytesOut = common.RightPadBytes([]byte("hello"), 63)
  872. buff.Write(bytesOut)
  873. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  874. if err != nil {
  875. t.Error(err)
  876. }
  877. if !bytes.Equal(Bytes, bytesOut) {
  878. t.Errorf("expected %x got %x", bytesOut, Bytes)
  879. }
  880. // marshal dynamic bytes output empty
  881. err = abi.Unpack(&Bytes, "bytes", nil)
  882. if err == nil {
  883. t.Error("expected error")
  884. }
  885. // marshal dynamic bytes length 5
  886. buff.Reset()
  887. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  888. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  889. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  890. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  891. if err != nil {
  892. t.Error(err)
  893. }
  894. if !bytes.Equal(Bytes, []byte("hello")) {
  895. t.Errorf("expected %x got %x", bytesOut, Bytes)
  896. }
  897. // marshal dynamic bytes length 5
  898. buff.Reset()
  899. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  900. var hash common.Hash
  901. err = abi.Unpack(&hash, "fixed", buff.Bytes())
  902. if err != nil {
  903. t.Error(err)
  904. }
  905. helloHash := common.BytesToHash(common.RightPadBytes([]byte("hello"), 32))
  906. if hash != helloHash {
  907. t.Errorf("Expected %x to equal %x", hash, helloHash)
  908. }
  909. // marshal error
  910. buff.Reset()
  911. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  912. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  913. if err == nil {
  914. t.Error("expected error")
  915. }
  916. err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
  917. if err == nil {
  918. t.Error("expected error")
  919. }
  920. // marshal mixed bytes
  921. buff.Reset()
  922. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  923. fixed := common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")
  924. buff.Write(fixed)
  925. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  926. bytesOut = common.RightPadBytes([]byte("hello"), 32)
  927. buff.Write(bytesOut)
  928. var out []interface{}
  929. err = abi.Unpack(&out, "mixedBytes", buff.Bytes())
  930. if err != nil {
  931. t.Fatal("didn't expect error:", err)
  932. }
  933. if !bytes.Equal(bytesOut, out[0].([]byte)) {
  934. t.Errorf("expected %x, got %x", bytesOut, out[0])
  935. }
  936. if !bytes.Equal(fixed, out[1].([]byte)) {
  937. t.Errorf("expected %x, got %x", fixed, out[1])
  938. }
  939. // marshal address slice
  940. buff.Reset()
  941. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) // offset
  942. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  943. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  944. var outAddr []common.Address
  945. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  946. if err != nil {
  947. t.Fatal("didn't expect error:", err)
  948. }
  949. if len(outAddr) != 1 {
  950. t.Fatal("expected 1 item, got", len(outAddr))
  951. }
  952. if outAddr[0] != (common.Address{1}) {
  953. t.Errorf("expected %x, got %x", common.Address{1}, outAddr[0])
  954. }
  955. // marshal multiple address slice
  956. buff.Reset()
  957. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // offset
  958. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // offset
  959. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  960. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  961. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // size
  962. buff.Write(common.Hex2Bytes("0000000000000000000000000200000000000000000000000000000000000000"))
  963. buff.Write(common.Hex2Bytes("0000000000000000000000000300000000000000000000000000000000000000"))
  964. var outAddrStruct struct {
  965. A []common.Address
  966. B []common.Address
  967. }
  968. err = abi.Unpack(&outAddrStruct, "addressSliceDouble", buff.Bytes())
  969. if err != nil {
  970. t.Fatal("didn't expect error:", err)
  971. }
  972. if len(outAddrStruct.A) != 1 {
  973. t.Fatal("expected 1 item, got", len(outAddrStruct.A))
  974. }
  975. if outAddrStruct.A[0] != (common.Address{1}) {
  976. t.Errorf("expected %x, got %x", common.Address{1}, outAddrStruct.A[0])
  977. }
  978. if len(outAddrStruct.B) != 2 {
  979. t.Fatal("expected 1 item, got", len(outAddrStruct.B))
  980. }
  981. if outAddrStruct.B[0] != (common.Address{2}) {
  982. t.Errorf("expected %x, got %x", common.Address{2}, outAddrStruct.B[0])
  983. }
  984. if outAddrStruct.B[1] != (common.Address{3}) {
  985. t.Errorf("expected %x, got %x", common.Address{3}, outAddrStruct.B[1])
  986. }
  987. // marshal invalid address slice
  988. buff.Reset()
  989. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000100"))
  990. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  991. if err == nil {
  992. t.Fatal("expected error:", err)
  993. }
  994. }