abi_test.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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 TestPack(t *testing.T) {
  276. for i, test := range []struct {
  277. typ string
  278. input interface{}
  279. output []byte
  280. }{
  281. {"uint16", uint16(2), pad([]byte{2}, 32, true)},
  282. {"uint16[]", []uint16{1, 2}, formatSliceOutput([]byte{1}, []byte{2})},
  283. {"bytes20", [20]byte{1}, pad([]byte{1}, 32, false)},
  284. {"uint256[]", []*big.Int{big.NewInt(1), big.NewInt(2)}, formatSliceOutput([]byte{1}, []byte{2})},
  285. {"address[]", []common.Address{common.Address{1}, common.Address{2}}, formatSliceOutput(pad([]byte{1}, 20, false), pad([]byte{2}, 20, false))},
  286. {"bytes32[]", []common.Hash{common.Hash{1}, common.Hash{2}}, formatSliceOutput(pad([]byte{1}, 32, false), pad([]byte{2}, 32, false))},
  287. } {
  288. typ, err := NewType(test.typ)
  289. if err != nil {
  290. t.Fatal("unexpected parse error:", err)
  291. }
  292. output, err := typ.pack(reflect.ValueOf(test.input))
  293. if err != nil {
  294. t.Fatal("unexpected pack error:", err)
  295. }
  296. if !bytes.Equal(output, test.output) {
  297. t.Errorf("%d failed. Expected bytes: '%x' Got: '%x'", i, test.output, output)
  298. }
  299. }
  300. }
  301. func TestMethodPack(t *testing.T) {
  302. abi, err := JSON(strings.NewReader(jsondata2))
  303. if err != nil {
  304. t.Fatal(err)
  305. }
  306. sig := abi.Methods["slice"].Id()
  307. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  308. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  309. sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...)
  310. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  311. packed, err := abi.Pack("slice", []uint32{1, 2})
  312. if err != nil {
  313. t.Error(err)
  314. }
  315. if !bytes.Equal(packed, sig) {
  316. t.Errorf("expected %x got %x", sig, packed)
  317. }
  318. var addrA, addrB = common.Address{1}, common.Address{2}
  319. sig = abi.Methods["sliceAddress"].Id()
  320. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  321. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  322. sig = append(sig, common.LeftPadBytes(addrA[:], 32)...)
  323. sig = append(sig, common.LeftPadBytes(addrB[:], 32)...)
  324. packed, err = abi.Pack("sliceAddress", []common.Address{addrA, addrB})
  325. if err != nil {
  326. t.Fatal(err)
  327. }
  328. if !bytes.Equal(packed, sig) {
  329. t.Errorf("expected %x got %x", sig, packed)
  330. }
  331. var addrC, addrD = common.Address{3}, common.Address{4}
  332. sig = abi.Methods["sliceMultiAddress"].Id()
  333. sig = append(sig, common.LeftPadBytes([]byte{64}, 32)...)
  334. sig = append(sig, common.LeftPadBytes([]byte{160}, 32)...)
  335. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  336. sig = append(sig, common.LeftPadBytes(addrA[:], 32)...)
  337. sig = append(sig, common.LeftPadBytes(addrB[:], 32)...)
  338. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  339. sig = append(sig, common.LeftPadBytes(addrC[:], 32)...)
  340. sig = append(sig, common.LeftPadBytes(addrD[:], 32)...)
  341. packed, err = abi.Pack("sliceMultiAddress", []common.Address{addrA, addrB}, []common.Address{addrC, addrD})
  342. if err != nil {
  343. t.Fatal(err)
  344. }
  345. if !bytes.Equal(packed, sig) {
  346. t.Errorf("expected %x got %x", sig, packed)
  347. }
  348. sig = abi.Methods["slice256"].Id()
  349. sig = append(sig, common.LeftPadBytes([]byte{32}, 32)...)
  350. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  351. sig = append(sig, common.LeftPadBytes([]byte{1}, 32)...)
  352. sig = append(sig, common.LeftPadBytes([]byte{2}, 32)...)
  353. packed, err = abi.Pack("slice256", []*big.Int{big.NewInt(1), big.NewInt(2)})
  354. if err != nil {
  355. t.Error(err)
  356. }
  357. if !bytes.Equal(packed, sig) {
  358. t.Errorf("expected %x got %x", sig, packed)
  359. }
  360. }
  361. const jsondata = `
  362. [
  363. { "type" : "function", "name" : "balance", "constant" : true },
  364. { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] }
  365. ]`
  366. const jsondata2 = `
  367. [
  368. { "type" : "function", "name" : "balance", "constant" : true },
  369. { "type" : "function", "name" : "send", "constant" : false, "inputs" : [ { "name" : "amount", "type" : "uint256" } ] },
  370. { "type" : "function", "name" : "test", "constant" : false, "inputs" : [ { "name" : "number", "type" : "uint32" } ] },
  371. { "type" : "function", "name" : "string", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "string" } ] },
  372. { "type" : "function", "name" : "bool", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "bool" } ] },
  373. { "type" : "function", "name" : "address", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address" } ] },
  374. { "type" : "function", "name" : "uint64[2]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[2]" } ] },
  375. { "type" : "function", "name" : "uint64[]", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint64[]" } ] },
  376. { "type" : "function", "name" : "foo", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" } ] },
  377. { "type" : "function", "name" : "bar", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32" }, { "name" : "string", "type" : "uint16" } ] },
  378. { "type" : "function", "name" : "slice", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint32[2]" } ] },
  379. { "type" : "function", "name" : "slice256", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "uint256[2]" } ] },
  380. { "type" : "function", "name" : "sliceAddress", "constant" : false, "inputs" : [ { "name" : "inputs", "type" : "address[]" } ] },
  381. { "type" : "function", "name" : "sliceMultiAddress", "constant" : false, "inputs" : [ { "name" : "a", "type" : "address[]" }, { "name" : "b", "type" : "address[]" } ] }
  382. ]`
  383. func TestReader(t *testing.T) {
  384. Uint256, _ := NewType("uint256")
  385. exp := ABI{
  386. Methods: map[string]Method{
  387. "balance": Method{
  388. "balance", true, nil, nil,
  389. },
  390. "send": Method{
  391. "send", false, []Argument{
  392. Argument{"amount", Uint256, false},
  393. }, nil,
  394. },
  395. },
  396. }
  397. abi, err := JSON(strings.NewReader(jsondata))
  398. if err != nil {
  399. t.Error(err)
  400. }
  401. // deep equal fails for some reason
  402. t.Skip()
  403. if !reflect.DeepEqual(abi, exp) {
  404. t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp)
  405. }
  406. }
  407. func TestTestNumbers(t *testing.T) {
  408. abi, err := JSON(strings.NewReader(jsondata2))
  409. if err != nil {
  410. t.Error(err)
  411. t.FailNow()
  412. }
  413. if _, err := abi.Pack("balance"); err != nil {
  414. t.Error(err)
  415. }
  416. if _, err := abi.Pack("balance", 1); err == nil {
  417. t.Error("expected error for balance(1)")
  418. }
  419. if _, err := abi.Pack("doesntexist", nil); err == nil {
  420. t.Errorf("doesntexist shouldn't exist")
  421. }
  422. if _, err := abi.Pack("doesntexist", 1); err == nil {
  423. t.Errorf("doesntexist(1) shouldn't exist")
  424. }
  425. if _, err := abi.Pack("send", big.NewInt(1000)); err != nil {
  426. t.Error(err)
  427. }
  428. i := new(int)
  429. *i = 1000
  430. if _, err := abi.Pack("send", i); err == nil {
  431. t.Errorf("expected send( ptr ) to throw, requires *big.Int instead of *int")
  432. }
  433. if _, err := abi.Pack("test", uint32(1000)); err != nil {
  434. t.Error(err)
  435. }
  436. }
  437. func TestTestString(t *testing.T) {
  438. abi, err := JSON(strings.NewReader(jsondata2))
  439. if err != nil {
  440. t.Error(err)
  441. t.FailNow()
  442. }
  443. if _, err := abi.Pack("string", "hello world"); err != nil {
  444. t.Error(err)
  445. }
  446. }
  447. func TestTestBool(t *testing.T) {
  448. abi, err := JSON(strings.NewReader(jsondata2))
  449. if err != nil {
  450. t.Error(err)
  451. t.FailNow()
  452. }
  453. if _, err := abi.Pack("bool", true); err != nil {
  454. t.Error(err)
  455. }
  456. }
  457. func TestTestSlice(t *testing.T) {
  458. abi, err := JSON(strings.NewReader(jsondata2))
  459. if err != nil {
  460. t.Error(err)
  461. t.FailNow()
  462. }
  463. slice := make([]uint64, 2)
  464. if _, err := abi.Pack("uint64[2]", slice); err != nil {
  465. t.Error(err)
  466. }
  467. if _, err := abi.Pack("uint64[]", slice); err != nil {
  468. t.Error(err)
  469. }
  470. }
  471. func TestMethodSignature(t *testing.T) {
  472. String, _ := NewType("string")
  473. m := Method{"foo", false, []Argument{Argument{"bar", String, false}, Argument{"baz", String, false}}, nil}
  474. exp := "foo(string,string)"
  475. if m.Sig() != exp {
  476. t.Error("signature mismatch", exp, "!=", m.Sig())
  477. }
  478. idexp := crypto.Keccak256([]byte(exp))[:4]
  479. if !bytes.Equal(m.Id(), idexp) {
  480. t.Errorf("expected ids to match %x != %x", m.Id(), idexp)
  481. }
  482. uintt, _ := NewType("uint")
  483. m = Method{"foo", false, []Argument{Argument{"bar", uintt, false}}, nil}
  484. exp = "foo(uint256)"
  485. if m.Sig() != exp {
  486. t.Error("signature mismatch", exp, "!=", m.Sig())
  487. }
  488. }
  489. func TestMultiPack(t *testing.T) {
  490. abi, err := JSON(strings.NewReader(jsondata2))
  491. if err != nil {
  492. t.Error(err)
  493. t.FailNow()
  494. }
  495. sig := crypto.Keccak256([]byte("bar(uint32,uint16)"))[:4]
  496. sig = append(sig, make([]byte, 64)...)
  497. sig[35] = 10
  498. sig[67] = 11
  499. packed, err := abi.Pack("bar", uint32(10), uint16(11))
  500. if err != nil {
  501. t.Error(err)
  502. t.FailNow()
  503. }
  504. if !bytes.Equal(packed, sig) {
  505. t.Errorf("expected %x got %x", sig, packed)
  506. }
  507. }
  508. func ExampleJSON() {
  509. const definition = `[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBar","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
  510. abi, err := JSON(strings.NewReader(definition))
  511. if err != nil {
  512. log.Fatalln(err)
  513. }
  514. out, err := abi.Pack("isBar", common.HexToAddress("01"))
  515. if err != nil {
  516. log.Fatalln(err)
  517. }
  518. fmt.Printf("%x\n", out)
  519. // Output:
  520. // 1f2c40920000000000000000000000000000000000000000000000000000000000000001
  521. }
  522. func TestInputVariableInputLength(t *testing.T) {
  523. const definition = `[
  524. { "type" : "function", "name" : "strOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" } ] },
  525. { "type" : "function", "name" : "bytesOne", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" } ] },
  526. { "type" : "function", "name" : "strTwo", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "str1", "type" : "string" } ] }
  527. ]`
  528. abi, err := JSON(strings.NewReader(definition))
  529. if err != nil {
  530. t.Fatal(err)
  531. }
  532. // test one string
  533. strin := "hello world"
  534. strpack, err := abi.Pack("strOne", strin)
  535. if err != nil {
  536. t.Error(err)
  537. }
  538. offset := make([]byte, 32)
  539. offset[31] = 32
  540. length := make([]byte, 32)
  541. length[31] = byte(len(strin))
  542. value := common.RightPadBytes([]byte(strin), 32)
  543. exp := append(offset, append(length, value...)...)
  544. // ignore first 4 bytes of the output. This is the function identifier
  545. strpack = strpack[4:]
  546. if !bytes.Equal(strpack, exp) {
  547. t.Errorf("expected %x, got %x\n", exp, strpack)
  548. }
  549. // test one bytes
  550. btspack, err := abi.Pack("bytesOne", []byte(strin))
  551. if err != nil {
  552. t.Error(err)
  553. }
  554. // ignore first 4 bytes of the output. This is the function identifier
  555. btspack = btspack[4:]
  556. if !bytes.Equal(btspack, exp) {
  557. t.Errorf("expected %x, got %x\n", exp, btspack)
  558. }
  559. // test two strings
  560. str1 := "hello"
  561. str2 := "world"
  562. str2pack, err := abi.Pack("strTwo", str1, str2)
  563. if err != nil {
  564. t.Error(err)
  565. }
  566. offset1 := make([]byte, 32)
  567. offset1[31] = 64
  568. length1 := make([]byte, 32)
  569. length1[31] = byte(len(str1))
  570. value1 := common.RightPadBytes([]byte(str1), 32)
  571. offset2 := make([]byte, 32)
  572. offset2[31] = 128
  573. length2 := make([]byte, 32)
  574. length2[31] = byte(len(str2))
  575. value2 := common.RightPadBytes([]byte(str2), 32)
  576. exp2 := append(offset1, offset2...)
  577. exp2 = append(exp2, append(length1, value1...)...)
  578. exp2 = append(exp2, append(length2, value2...)...)
  579. // ignore first 4 bytes of the output. This is the function identifier
  580. str2pack = str2pack[4:]
  581. if !bytes.Equal(str2pack, exp2) {
  582. t.Errorf("expected %x, got %x\n", exp, str2pack)
  583. }
  584. // test two strings, first > 32, second < 32
  585. str1 = strings.Repeat("a", 33)
  586. str2pack, err = abi.Pack("strTwo", str1, str2)
  587. if err != nil {
  588. t.Error(err)
  589. }
  590. offset1 = make([]byte, 32)
  591. offset1[31] = 64
  592. length1 = make([]byte, 32)
  593. length1[31] = byte(len(str1))
  594. value1 = common.RightPadBytes([]byte(str1), 64)
  595. offset2[31] = 160
  596. exp2 = append(offset1, offset2...)
  597. exp2 = append(exp2, append(length1, value1...)...)
  598. exp2 = append(exp2, append(length2, value2...)...)
  599. // ignore first 4 bytes of the output. This is the function identifier
  600. str2pack = str2pack[4:]
  601. if !bytes.Equal(str2pack, exp2) {
  602. t.Errorf("expected %x, got %x\n", exp, str2pack)
  603. }
  604. // test two strings, first > 32, second >32
  605. str1 = strings.Repeat("a", 33)
  606. str2 = strings.Repeat("a", 33)
  607. str2pack, err = abi.Pack("strTwo", str1, str2)
  608. if err != nil {
  609. t.Error(err)
  610. }
  611. offset1 = make([]byte, 32)
  612. offset1[31] = 64
  613. length1 = make([]byte, 32)
  614. length1[31] = byte(len(str1))
  615. value1 = common.RightPadBytes([]byte(str1), 64)
  616. offset2 = make([]byte, 32)
  617. offset2[31] = 160
  618. length2 = make([]byte, 32)
  619. length2[31] = byte(len(str2))
  620. value2 = common.RightPadBytes([]byte(str2), 64)
  621. exp2 = append(offset1, offset2...)
  622. exp2 = append(exp2, append(length1, value1...)...)
  623. exp2 = append(exp2, append(length2, value2...)...)
  624. // ignore first 4 bytes of the output. This is the function identifier
  625. str2pack = str2pack[4:]
  626. if !bytes.Equal(str2pack, exp2) {
  627. t.Errorf("expected %x, got %x\n", exp, str2pack)
  628. }
  629. }
  630. func TestDefaultFunctionParsing(t *testing.T) {
  631. const definition = `[{ "name" : "balance" }]`
  632. abi, err := JSON(strings.NewReader(definition))
  633. if err != nil {
  634. t.Fatal(err)
  635. }
  636. if _, ok := abi.Methods["balance"]; !ok {
  637. t.Error("expected 'balance' to be present")
  638. }
  639. }
  640. func TestBareEvents(t *testing.T) {
  641. const definition = `[
  642. { "type" : "event", "name" : "balance" },
  643. { "type" : "event", "name" : "name" }]`
  644. abi, err := JSON(strings.NewReader(definition))
  645. if err != nil {
  646. t.Fatal(err)
  647. }
  648. if len(abi.Events) != 2 {
  649. t.Error("expected 2 events")
  650. }
  651. if _, ok := abi.Events["balance"]; !ok {
  652. t.Error("expected 'balance' event to be present")
  653. }
  654. if _, ok := abi.Events["name"]; !ok {
  655. t.Error("expected 'name' event to be present")
  656. }
  657. }
  658. func TestMultiReturnWithStruct(t *testing.T) {
  659. const definition = `[
  660. { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  661. abi, err := JSON(strings.NewReader(definition))
  662. if err != nil {
  663. t.Fatal(err)
  664. }
  665. // using buff to make the code readable
  666. buff := new(bytes.Buffer)
  667. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  668. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  669. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  670. stringOut := "hello"
  671. buff.Write(common.RightPadBytes([]byte(stringOut), 32))
  672. var inter struct {
  673. Int *big.Int
  674. String string
  675. }
  676. err = abi.Unpack(&inter, "multi", buff.Bytes())
  677. if err != nil {
  678. t.Error(err)
  679. }
  680. if inter.Int == nil || inter.Int.Cmp(big.NewInt(1)) != 0 {
  681. t.Error("expected Int to be 1 got", inter.Int)
  682. }
  683. if inter.String != stringOut {
  684. t.Error("expected String to be", stringOut, "got", inter.String)
  685. }
  686. var reversed struct {
  687. String string
  688. Int *big.Int
  689. }
  690. err = abi.Unpack(&reversed, "multi", buff.Bytes())
  691. if err != nil {
  692. t.Error(err)
  693. }
  694. if reversed.Int == nil || reversed.Int.Cmp(big.NewInt(1)) != 0 {
  695. t.Error("expected Int to be 1 got", reversed.Int)
  696. }
  697. if reversed.String != stringOut {
  698. t.Error("expected String to be", stringOut, "got", reversed.String)
  699. }
  700. }
  701. func TestMultiReturnWithSlice(t *testing.T) {
  702. const definition = `[
  703. { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  704. abi, err := JSON(strings.NewReader(definition))
  705. if err != nil {
  706. t.Fatal(err)
  707. }
  708. // using buff to make the code readable
  709. buff := new(bytes.Buffer)
  710. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  711. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  712. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  713. stringOut := "hello"
  714. buff.Write(common.RightPadBytes([]byte(stringOut), 32))
  715. var inter []interface{}
  716. err = abi.Unpack(&inter, "multi", buff.Bytes())
  717. if err != nil {
  718. t.Error(err)
  719. }
  720. if len(inter) != 2 {
  721. t.Fatal("expected 2 results got", len(inter))
  722. }
  723. if num, ok := inter[0].(*big.Int); !ok || num.Cmp(big.NewInt(1)) != 0 {
  724. t.Error("expected index 0 to be 1 got", num)
  725. }
  726. if str, ok := inter[1].(string); !ok || str != stringOut {
  727. t.Error("expected index 1 to be", stringOut, "got", str)
  728. }
  729. }
  730. func TestMarshalArrays(t *testing.T) {
  731. const definition = `[
  732. { "name" : "bytes32", "constant" : false, "outputs": [ { "type": "bytes32" } ] },
  733. { "name" : "bytes10", "constant" : false, "outputs": [ { "type": "bytes10" } ] }
  734. ]`
  735. abi, err := JSON(strings.NewReader(definition))
  736. if err != nil {
  737. t.Fatal(err)
  738. }
  739. output := common.LeftPadBytes([]byte{1}, 32)
  740. var bytes10 [10]byte
  741. err = abi.Unpack(&bytes10, "bytes32", output)
  742. if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
  743. t.Error("expected error or bytes32 not be assignable to bytes10:", err)
  744. }
  745. var bytes32 [32]byte
  746. err = abi.Unpack(&bytes32, "bytes32", output)
  747. if err != nil {
  748. t.Error("didn't expect error:", err)
  749. }
  750. if !bytes.Equal(bytes32[:], output) {
  751. t.Error("expected bytes32[31] to be 1 got", bytes32[31])
  752. }
  753. type (
  754. B10 [10]byte
  755. B32 [32]byte
  756. )
  757. var b10 B10
  758. err = abi.Unpack(&b10, "bytes32", output)
  759. if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
  760. t.Error("expected error or bytes32 not be assignable to bytes10:", err)
  761. }
  762. var b32 B32
  763. err = abi.Unpack(&b32, "bytes32", output)
  764. if err != nil {
  765. t.Error("didn't expect error:", err)
  766. }
  767. if !bytes.Equal(b32[:], output) {
  768. t.Error("expected bytes32[31] to be 1 got", bytes32[31])
  769. }
  770. output[10] = 1
  771. var shortAssignLong [32]byte
  772. err = abi.Unpack(&shortAssignLong, "bytes10", output)
  773. if err != nil {
  774. t.Error("didn't expect error:", err)
  775. }
  776. if !bytes.Equal(output, shortAssignLong[:]) {
  777. t.Errorf("expected %x to be %x", shortAssignLong, output)
  778. }
  779. }
  780. func TestUnmarshal(t *testing.T) {
  781. const definition = `[
  782. { "name" : "int", "constant" : false, "outputs": [ { "type": "uint256" } ] },
  783. { "name" : "bool", "constant" : false, "outputs": [ { "type": "bool" } ] },
  784. { "name" : "bytes", "constant" : false, "outputs": [ { "type": "bytes" } ] },
  785. { "name" : "fixed", "constant" : false, "outputs": [ { "type": "bytes32" } ] },
  786. { "name" : "multi", "constant" : false, "outputs": [ { "type": "bytes" }, { "type": "bytes" } ] },
  787. { "name" : "addressSliceSingle", "constant" : false, "outputs": [ { "type": "address[]" } ] },
  788. { "name" : "addressSliceDouble", "constant" : false, "outputs": [ { "name": "a", "type": "address[]" }, { "name": "b", "type": "address[]" } ] },
  789. { "name" : "mixedBytes", "constant" : true, "outputs": [ { "name": "a", "type": "bytes" }, { "name": "b", "type": "bytes32" } ] }]`
  790. abi, err := JSON(strings.NewReader(definition))
  791. if err != nil {
  792. t.Fatal(err)
  793. }
  794. buff := new(bytes.Buffer)
  795. // marshal int
  796. var Int *big.Int
  797. err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  798. if err != nil {
  799. t.Error(err)
  800. }
  801. if Int == nil || Int.Cmp(big.NewInt(1)) != 0 {
  802. t.Error("expected Int to be 1 got", Int)
  803. }
  804. // marshal bool
  805. var Bool bool
  806. err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  807. if err != nil {
  808. t.Error(err)
  809. }
  810. if !Bool {
  811. t.Error("expected Bool to be true")
  812. }
  813. // marshal dynamic bytes max length 32
  814. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  815. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  816. bytesOut := common.RightPadBytes([]byte("hello"), 32)
  817. buff.Write(bytesOut)
  818. var Bytes []byte
  819. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  820. if err != nil {
  821. t.Error(err)
  822. }
  823. if !bytes.Equal(Bytes, bytesOut) {
  824. t.Errorf("expected %x got %x", bytesOut, Bytes)
  825. }
  826. // marshall dynamic bytes max length 64
  827. buff.Reset()
  828. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  829. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  830. bytesOut = common.RightPadBytes([]byte("hello"), 64)
  831. buff.Write(bytesOut)
  832. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  833. if err != nil {
  834. t.Error(err)
  835. }
  836. if !bytes.Equal(Bytes, bytesOut) {
  837. t.Errorf("expected %x got %x", bytesOut, Bytes)
  838. }
  839. // marshall dynamic bytes max length 63
  840. buff.Reset()
  841. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  842. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000003f"))
  843. bytesOut = common.RightPadBytes([]byte("hello"), 63)
  844. buff.Write(bytesOut)
  845. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  846. if err != nil {
  847. t.Error(err)
  848. }
  849. if !bytes.Equal(Bytes, bytesOut) {
  850. t.Errorf("expected %x got %x", bytesOut, Bytes)
  851. }
  852. // marshal dynamic bytes output empty
  853. err = abi.Unpack(&Bytes, "bytes", nil)
  854. if err == nil {
  855. t.Error("expected error")
  856. }
  857. // marshal dynamic bytes length 5
  858. buff.Reset()
  859. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  860. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  861. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  862. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  863. if err != nil {
  864. t.Error(err)
  865. }
  866. if !bytes.Equal(Bytes, []byte("hello")) {
  867. t.Errorf("expected %x got %x", bytesOut, Bytes)
  868. }
  869. // marshal dynamic bytes length 5
  870. buff.Reset()
  871. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  872. var hash common.Hash
  873. err = abi.Unpack(&hash, "fixed", buff.Bytes())
  874. if err != nil {
  875. t.Error(err)
  876. }
  877. helloHash := common.BytesToHash(common.RightPadBytes([]byte("hello"), 32))
  878. if hash != helloHash {
  879. t.Errorf("Expected %x to equal %x", hash, helloHash)
  880. }
  881. // marshal error
  882. buff.Reset()
  883. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  884. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  885. if err == nil {
  886. t.Error("expected error")
  887. }
  888. err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
  889. if err == nil {
  890. t.Error("expected error")
  891. }
  892. // marshal mixed bytes
  893. buff.Reset()
  894. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  895. fixed := common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")
  896. buff.Write(fixed)
  897. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  898. bytesOut = common.RightPadBytes([]byte("hello"), 32)
  899. buff.Write(bytesOut)
  900. var out []interface{}
  901. err = abi.Unpack(&out, "mixedBytes", buff.Bytes())
  902. if err != nil {
  903. t.Fatal("didn't expect error:", err)
  904. }
  905. if !bytes.Equal(bytesOut, out[0].([]byte)) {
  906. t.Errorf("expected %x, got %x", bytesOut, out[0])
  907. }
  908. if !bytes.Equal(fixed, out[1].([]byte)) {
  909. t.Errorf("expected %x, got %x", fixed, out[1])
  910. }
  911. // marshal address slice
  912. buff.Reset()
  913. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) // offset
  914. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  915. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  916. var outAddr []common.Address
  917. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  918. if err != nil {
  919. t.Fatal("didn't expect error:", err)
  920. }
  921. if len(outAddr) != 1 {
  922. t.Fatal("expected 1 item, got", len(outAddr))
  923. }
  924. if outAddr[0] != (common.Address{1}) {
  925. t.Errorf("expected %x, got %x", common.Address{1}, outAddr[0])
  926. }
  927. // marshal multiple address slice
  928. buff.Reset()
  929. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // offset
  930. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // offset
  931. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  932. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  933. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // size
  934. buff.Write(common.Hex2Bytes("0000000000000000000000000200000000000000000000000000000000000000"))
  935. buff.Write(common.Hex2Bytes("0000000000000000000000000300000000000000000000000000000000000000"))
  936. var outAddrStruct struct {
  937. A []common.Address
  938. B []common.Address
  939. }
  940. err = abi.Unpack(&outAddrStruct, "addressSliceDouble", buff.Bytes())
  941. if err != nil {
  942. t.Fatal("didn't expect error:", err)
  943. }
  944. if len(outAddrStruct.A) != 1 {
  945. t.Fatal("expected 1 item, got", len(outAddrStruct.A))
  946. }
  947. if outAddrStruct.A[0] != (common.Address{1}) {
  948. t.Errorf("expected %x, got %x", common.Address{1}, outAddrStruct.A[0])
  949. }
  950. if len(outAddrStruct.B) != 2 {
  951. t.Fatal("expected 1 item, got", len(outAddrStruct.B))
  952. }
  953. if outAddrStruct.B[0] != (common.Address{2}) {
  954. t.Errorf("expected %x, got %x", common.Address{2}, outAddrStruct.B[0])
  955. }
  956. if outAddrStruct.B[1] != (common.Address{3}) {
  957. t.Errorf("expected %x, got %x", common.Address{3}, outAddrStruct.B[1])
  958. }
  959. // marshal invalid address slice
  960. buff.Reset()
  961. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000100"))
  962. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  963. if err == nil {
  964. t.Fatal("expected error:", err)
  965. }
  966. }