unpack_test.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package abi
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "math/big"
  22. "reflect"
  23. "strconv"
  24. "strings"
  25. "testing"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/stretchr/testify/require"
  28. )
  29. // TestUnpack tests the general pack/unpack tests in packing_test.go
  30. func TestUnpack(t *testing.T) {
  31. for i, test := range packUnpackTests {
  32. t.Run(strconv.Itoa(i)+" "+test.def, func(t *testing.T) {
  33. //Unpack
  34. def := fmt.Sprintf(`[{ "name" : "method", "type": "function", "outputs": %s}]`, test.def)
  35. abi, err := JSON(strings.NewReader(def))
  36. if err != nil {
  37. t.Fatalf("invalid ABI definition %s: %v", def, err)
  38. }
  39. encb, err := hex.DecodeString(test.packed)
  40. if err != nil {
  41. t.Fatalf("invalid hex %s: %v", test.packed, err)
  42. }
  43. outptr := reflect.New(reflect.TypeOf(test.unpacked))
  44. err = abi.Unpack(outptr.Interface(), "method", encb)
  45. if err != nil {
  46. t.Errorf("test %d (%v) failed: %v", i, test.def, err)
  47. return
  48. }
  49. out := outptr.Elem().Interface()
  50. if !reflect.DeepEqual(test.unpacked, out) {
  51. t.Errorf("test %d (%v) failed: expected %v, got %v", i, test.def, test.unpacked, out)
  52. }
  53. })
  54. }
  55. }
  56. type unpackTest struct {
  57. def string // ABI definition JSON
  58. enc string // evm return data
  59. want interface{} // the expected output
  60. err string // empty or error if expected
  61. }
  62. func (test unpackTest) checkError(err error) error {
  63. if err != nil {
  64. if len(test.err) == 0 {
  65. return fmt.Errorf("expected no err but got: %v", err)
  66. } else if err.Error() != test.err {
  67. return fmt.Errorf("expected err: '%v' got err: %q", test.err, err)
  68. }
  69. } else if len(test.err) > 0 {
  70. return fmt.Errorf("expected err: %v but got none", test.err)
  71. }
  72. return nil
  73. }
  74. var unpackTests = []unpackTest{
  75. // Bools
  76. {
  77. def: `[{ "type": "bool" }]`,
  78. enc: "0000000000000000000000000000000000000000000000000001000000000001",
  79. want: false,
  80. err: "abi: improperly encoded boolean value",
  81. },
  82. {
  83. def: `[{ "type": "bool" }]`,
  84. enc: "0000000000000000000000000000000000000000000000000000000000000003",
  85. want: false,
  86. err: "abi: improperly encoded boolean value",
  87. },
  88. // Integers
  89. {
  90. def: `[{"type": "uint32"}]`,
  91. enc: "0000000000000000000000000000000000000000000000000000000000000001",
  92. want: uint16(0),
  93. err: "abi: cannot unmarshal uint32 in to uint16",
  94. },
  95. {
  96. def: `[{"type": "uint17"}]`,
  97. enc: "0000000000000000000000000000000000000000000000000000000000000001",
  98. want: uint16(0),
  99. err: "abi: cannot unmarshal *big.Int in to uint16",
  100. },
  101. {
  102. def: `[{"type": "int32"}]`,
  103. enc: "0000000000000000000000000000000000000000000000000000000000000001",
  104. want: int16(0),
  105. err: "abi: cannot unmarshal int32 in to int16",
  106. },
  107. {
  108. def: `[{"type": "int17"}]`,
  109. enc: "0000000000000000000000000000000000000000000000000000000000000001",
  110. want: int16(0),
  111. err: "abi: cannot unmarshal *big.Int in to int16",
  112. },
  113. {
  114. def: `[{"type": "bytes"}]`,
  115. enc: "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200100000000000000000000000000000000000000000000000000000000000000",
  116. want: [32]byte{1},
  117. },
  118. {
  119. def: `[{"type": "bytes32"}]`,
  120. enc: "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200100000000000000000000000000000000000000000000000000000000000000",
  121. want: []byte(nil),
  122. err: "abi: cannot unmarshal [32]uint8 in to []uint8",
  123. },
  124. {
  125. def: `[{"name":"___","type":"int256"}]`,
  126. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  127. want: struct {
  128. IntOne *big.Int
  129. Intone *big.Int
  130. }{IntOne: big.NewInt(1)},
  131. },
  132. {
  133. def: `[{"name":"int_one","type":"int256"},{"name":"IntOne","type":"int256"}]`,
  134. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  135. want: struct {
  136. Int1 *big.Int
  137. Int2 *big.Int
  138. }{},
  139. err: "abi: multiple outputs mapping to the same struct field 'IntOne'",
  140. },
  141. {
  142. def: `[{"name":"int","type":"int256"},{"name":"Int","type":"int256"}]`,
  143. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  144. want: struct {
  145. Int1 *big.Int
  146. Int2 *big.Int
  147. }{},
  148. err: "abi: multiple outputs mapping to the same struct field 'Int'",
  149. },
  150. {
  151. def: `[{"name":"int","type":"int256"},{"name":"_int","type":"int256"}]`,
  152. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  153. want: struct {
  154. Int1 *big.Int
  155. Int2 *big.Int
  156. }{},
  157. err: "abi: multiple outputs mapping to the same struct field 'Int'",
  158. },
  159. {
  160. def: `[{"name":"Int","type":"int256"},{"name":"_int","type":"int256"}]`,
  161. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  162. want: struct {
  163. Int1 *big.Int
  164. Int2 *big.Int
  165. }{},
  166. err: "abi: multiple outputs mapping to the same struct field 'Int'",
  167. },
  168. {
  169. def: `[{"name":"Int","type":"int256"},{"name":"_","type":"int256"}]`,
  170. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  171. want: struct {
  172. Int1 *big.Int
  173. Int2 *big.Int
  174. }{},
  175. err: "abi: purely underscored output cannot unpack to struct",
  176. },
  177. // Make sure only the first argument is consumed
  178. {
  179. def: `[{"name":"int_one","type":"int256"}]`,
  180. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  181. want: struct {
  182. IntOne *big.Int
  183. }{big.NewInt(1)},
  184. },
  185. {
  186. def: `[{"name":"int__one","type":"int256"}]`,
  187. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  188. want: struct {
  189. IntOne *big.Int
  190. }{big.NewInt(1)},
  191. },
  192. {
  193. def: `[{"name":"int_one_","type":"int256"}]`,
  194. enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002",
  195. want: struct {
  196. IntOne *big.Int
  197. }{big.NewInt(1)},
  198. },
  199. }
  200. // TestLocalUnpackTests runs test specially designed only for unpacking.
  201. // All test cases that can be used to test packing and unpacking should move to packing_test.go
  202. func TestLocalUnpackTests(t *testing.T) {
  203. for i, test := range unpackTests {
  204. t.Run(strconv.Itoa(i), func(t *testing.T) {
  205. //Unpack
  206. def := fmt.Sprintf(`[{ "name" : "method", "type": "function", "outputs": %s}]`, test.def)
  207. abi, err := JSON(strings.NewReader(def))
  208. if err != nil {
  209. t.Fatalf("invalid ABI definition %s: %v", def, err)
  210. }
  211. encb, err := hex.DecodeString(test.enc)
  212. if err != nil {
  213. t.Fatalf("invalid hex %s: %v", test.enc, err)
  214. }
  215. outptr := reflect.New(reflect.TypeOf(test.want))
  216. err = abi.Unpack(outptr.Interface(), "method", encb)
  217. if err := test.checkError(err); err != nil {
  218. t.Errorf("test %d (%v) failed: %v", i, test.def, err)
  219. return
  220. }
  221. out := outptr.Elem().Interface()
  222. if !reflect.DeepEqual(test.want, out) {
  223. t.Errorf("test %d (%v) failed: expected %v, got %v", i, test.def, test.want, out)
  224. }
  225. })
  226. }
  227. }
  228. func TestUnpackSetDynamicArrayOutput(t *testing.T) {
  229. abi, err := JSON(strings.NewReader(`[{"constant":true,"inputs":[],"name":"testDynamicFixedBytes15","outputs":[{"name":"","type":"bytes15[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"testDynamicFixedBytes32","outputs":[{"name":"","type":"bytes32[]"}],"payable":false,"stateMutability":"view","type":"function"}]`))
  230. if err != nil {
  231. t.Fatal(err)
  232. }
  233. var (
  234. marshalledReturn32 = common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000230783132333435363738393000000000000000000000000000000000000000003078303938373635343332310000000000000000000000000000000000000000")
  235. marshalledReturn15 = common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000230783031323334350000000000000000000000000000000000000000000000003078393837363534000000000000000000000000000000000000000000000000")
  236. out32 [][32]byte
  237. out15 [][15]byte
  238. )
  239. // test 32
  240. err = abi.Unpack(&out32, "testDynamicFixedBytes32", marshalledReturn32)
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. if len(out32) != 2 {
  245. t.Fatalf("expected array with 2 values, got %d", len(out32))
  246. }
  247. expected := common.Hex2Bytes("3078313233343536373839300000000000000000000000000000000000000000")
  248. if !bytes.Equal(out32[0][:], expected) {
  249. t.Errorf("expected %x, got %x\n", expected, out32[0])
  250. }
  251. expected = common.Hex2Bytes("3078303938373635343332310000000000000000000000000000000000000000")
  252. if !bytes.Equal(out32[1][:], expected) {
  253. t.Errorf("expected %x, got %x\n", expected, out32[1])
  254. }
  255. // test 15
  256. err = abi.Unpack(&out15, "testDynamicFixedBytes32", marshalledReturn15)
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. if len(out15) != 2 {
  261. t.Fatalf("expected array with 2 values, got %d", len(out15))
  262. }
  263. expected = common.Hex2Bytes("307830313233343500000000000000")
  264. if !bytes.Equal(out15[0][:], expected) {
  265. t.Errorf("expected %x, got %x\n", expected, out15[0])
  266. }
  267. expected = common.Hex2Bytes("307839383736353400000000000000")
  268. if !bytes.Equal(out15[1][:], expected) {
  269. t.Errorf("expected %x, got %x\n", expected, out15[1])
  270. }
  271. }
  272. type methodMultiOutput struct {
  273. Int *big.Int
  274. String string
  275. }
  276. func methodMultiReturn(require *require.Assertions) (ABI, []byte, methodMultiOutput) {
  277. const definition = `[
  278. { "name" : "multi", "type": "function", "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]`
  279. var expected = methodMultiOutput{big.NewInt(1), "hello"}
  280. abi, err := JSON(strings.NewReader(definition))
  281. require.NoError(err)
  282. // using buff to make the code readable
  283. buff := new(bytes.Buffer)
  284. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  285. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  286. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  287. buff.Write(common.RightPadBytes([]byte(expected.String), 32))
  288. return abi, buff.Bytes(), expected
  289. }
  290. func TestMethodMultiReturn(t *testing.T) {
  291. type reversed struct {
  292. String string
  293. Int *big.Int
  294. }
  295. newInterfaceSlice := func(len int) interface{} {
  296. slice := make([]interface{}, len)
  297. return &slice
  298. }
  299. abi, data, expected := methodMultiReturn(require.New(t))
  300. bigint := new(big.Int)
  301. var testCases = []struct {
  302. dest interface{}
  303. expected interface{}
  304. error string
  305. name string
  306. }{{
  307. &methodMultiOutput{},
  308. &expected,
  309. "",
  310. "Can unpack into structure",
  311. }, {
  312. &reversed{},
  313. &reversed{expected.String, expected.Int},
  314. "",
  315. "Can unpack into reversed structure",
  316. }, {
  317. &[]interface{}{&bigint, new(string)},
  318. &[]interface{}{&expected.Int, &expected.String},
  319. "",
  320. "Can unpack into a slice",
  321. }, {
  322. &[2]interface{}{&bigint, new(string)},
  323. &[2]interface{}{&expected.Int, &expected.String},
  324. "",
  325. "Can unpack into an array",
  326. }, {
  327. &[2]interface{}{},
  328. &[2]interface{}{expected.Int, expected.String},
  329. "",
  330. "Can unpack into interface array",
  331. }, {
  332. newInterfaceSlice(2),
  333. &[]interface{}{expected.Int, expected.String},
  334. "",
  335. "Can unpack into interface slice",
  336. }, {
  337. &[]interface{}{new(int), new(int)},
  338. &[]interface{}{&expected.Int, &expected.String},
  339. "abi: cannot unmarshal *big.Int in to int",
  340. "Can not unpack into a slice with wrong types",
  341. }, {
  342. &[]interface{}{new(int)},
  343. &[]interface{}{},
  344. "abi: insufficient number of arguments for unpack, want 2, got 1",
  345. "Can not unpack into a slice with wrong types",
  346. }}
  347. for _, tc := range testCases {
  348. tc := tc
  349. t.Run(tc.name, func(t *testing.T) {
  350. require := require.New(t)
  351. err := abi.Unpack(tc.dest, "multi", data)
  352. if tc.error == "" {
  353. require.Nil(err, "Should be able to unpack method outputs.")
  354. require.Equal(tc.expected, tc.dest)
  355. } else {
  356. require.EqualError(err, tc.error)
  357. }
  358. })
  359. }
  360. }
  361. func TestMultiReturnWithArray(t *testing.T) {
  362. const definition = `[{"name" : "multi", "type": "function", "outputs": [{"type": "uint64[3]"}, {"type": "uint64"}]}]`
  363. abi, err := JSON(strings.NewReader(definition))
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. buff := new(bytes.Buffer)
  368. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000090000000000000000000000000000000000000000000000000000000000000009"))
  369. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000008"))
  370. ret1, ret1Exp := new([3]uint64), [3]uint64{9, 9, 9}
  371. ret2, ret2Exp := new(uint64), uint64(8)
  372. if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
  373. t.Fatal(err)
  374. }
  375. if !reflect.DeepEqual(*ret1, ret1Exp) {
  376. t.Error("array result", *ret1, "!= Expected", ret1Exp)
  377. }
  378. if *ret2 != ret2Exp {
  379. t.Error("int result", *ret2, "!= Expected", ret2Exp)
  380. }
  381. }
  382. func TestMultiReturnWithStringArray(t *testing.T) {
  383. const definition = `[{"name" : "multi", "type": "function", "outputs": [{"name": "","type": "uint256[3]"},{"name": "","type": "address"},{"name": "","type": "string[2]"},{"name": "","type": "bool"}]}]`
  384. abi, err := JSON(strings.NewReader(definition))
  385. if err != nil {
  386. t.Fatal(err)
  387. }
  388. buff := new(bytes.Buffer)
  389. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000005c1b78ea0000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000001a055690d9db80000000000000000000000000000ab1257528b3782fb40d7ed5f72e624b744dffb2f00000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000008457468657265756d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001048656c6c6f2c20457468657265756d2100000000000000000000000000000000"))
  390. temp, _ := big.NewInt(0).SetString("30000000000000000000", 10)
  391. ret1, ret1Exp := new([3]*big.Int), [3]*big.Int{big.NewInt(1545304298), big.NewInt(6), temp}
  392. ret2, ret2Exp := new(common.Address), common.HexToAddress("ab1257528b3782fb40d7ed5f72e624b744dffb2f")
  393. ret3, ret3Exp := new([2]string), [2]string{"Ethereum", "Hello, Ethereum!"}
  394. ret4, ret4Exp := new(bool), false
  395. if err := abi.Unpack(&[]interface{}{ret1, ret2, ret3, ret4}, "multi", buff.Bytes()); err != nil {
  396. t.Fatal(err)
  397. }
  398. if !reflect.DeepEqual(*ret1, ret1Exp) {
  399. t.Error("big.Int array result", *ret1, "!= Expected", ret1Exp)
  400. }
  401. if !reflect.DeepEqual(*ret2, ret2Exp) {
  402. t.Error("address result", *ret2, "!= Expected", ret2Exp)
  403. }
  404. if !reflect.DeepEqual(*ret3, ret3Exp) {
  405. t.Error("string array result", *ret3, "!= Expected", ret3Exp)
  406. }
  407. if !reflect.DeepEqual(*ret4, ret4Exp) {
  408. t.Error("bool result", *ret4, "!= Expected", ret4Exp)
  409. }
  410. }
  411. func TestMultiReturnWithStringSlice(t *testing.T) {
  412. const definition = `[{"name" : "multi", "type": "function", "outputs": [{"name": "","type": "string[]"},{"name": "","type": "uint256[]"}]}]`
  413. abi, err := JSON(strings.NewReader(definition))
  414. if err != nil {
  415. t.Fatal(err)
  416. }
  417. buff := new(bytes.Buffer)
  418. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // output[0] offset
  419. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000120")) // output[1] offset
  420. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // output[0] length
  421. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // output[0][0] offset
  422. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // output[0][1] offset
  423. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000008")) // output[0][0] length
  424. buff.Write(common.Hex2Bytes("657468657265756d000000000000000000000000000000000000000000000000")) // output[0][0] value
  425. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000000b")) // output[0][1] length
  426. buff.Write(common.Hex2Bytes("676f2d657468657265756d000000000000000000000000000000000000000000")) // output[0][1] value
  427. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // output[1] length
  428. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000064")) // output[1][0] value
  429. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000065")) // output[1][1] value
  430. ret1, ret1Exp := new([]string), []string{"ethereum", "go-ethereum"}
  431. ret2, ret2Exp := new([]*big.Int), []*big.Int{big.NewInt(100), big.NewInt(101)}
  432. if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
  433. t.Fatal(err)
  434. }
  435. if !reflect.DeepEqual(*ret1, ret1Exp) {
  436. t.Error("string slice result", *ret1, "!= Expected", ret1Exp)
  437. }
  438. if !reflect.DeepEqual(*ret2, ret2Exp) {
  439. t.Error("uint256 slice result", *ret2, "!= Expected", ret2Exp)
  440. }
  441. }
  442. func TestMultiReturnWithDeeplyNestedArray(t *testing.T) {
  443. // Similar to TestMultiReturnWithArray, but with a special case in mind:
  444. // values of nested static arrays count towards the size as well, and any element following
  445. // after such nested array argument should be read with the correct offset,
  446. // so that it does not read content from the previous array argument.
  447. const definition = `[{"name" : "multi", "type": "function", "outputs": [{"type": "uint64[3][2][4]"}, {"type": "uint64"}]}]`
  448. abi, err := JSON(strings.NewReader(definition))
  449. if err != nil {
  450. t.Fatal(err)
  451. }
  452. buff := new(bytes.Buffer)
  453. // construct the test array, each 3 char element is joined with 61 '0' chars,
  454. // to from the ((3 + 61) * 0.5) = 32 byte elements in the array.
  455. buff.Write(common.Hex2Bytes(strings.Join([]string{
  456. "", //empty, to apply the 61-char separator to the first element as well.
  457. "111", "112", "113", "121", "122", "123",
  458. "211", "212", "213", "221", "222", "223",
  459. "311", "312", "313", "321", "322", "323",
  460. "411", "412", "413", "421", "422", "423",
  461. }, "0000000000000000000000000000000000000000000000000000000000000")))
  462. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000009876"))
  463. ret1, ret1Exp := new([4][2][3]uint64), [4][2][3]uint64{
  464. {{0x111, 0x112, 0x113}, {0x121, 0x122, 0x123}},
  465. {{0x211, 0x212, 0x213}, {0x221, 0x222, 0x223}},
  466. {{0x311, 0x312, 0x313}, {0x321, 0x322, 0x323}},
  467. {{0x411, 0x412, 0x413}, {0x421, 0x422, 0x423}},
  468. }
  469. ret2, ret2Exp := new(uint64), uint64(0x9876)
  470. if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil {
  471. t.Fatal(err)
  472. }
  473. if !reflect.DeepEqual(*ret1, ret1Exp) {
  474. t.Error("array result", *ret1, "!= Expected", ret1Exp)
  475. }
  476. if *ret2 != ret2Exp {
  477. t.Error("int result", *ret2, "!= Expected", ret2Exp)
  478. }
  479. }
  480. func TestUnmarshal(t *testing.T) {
  481. const definition = `[
  482. { "name" : "int", "type": "function", "outputs": [ { "type": "uint256" } ] },
  483. { "name" : "bool", "type": "function", "outputs": [ { "type": "bool" } ] },
  484. { "name" : "bytes", "type": "function", "outputs": [ { "type": "bytes" } ] },
  485. { "name" : "fixed", "type": "function", "outputs": [ { "type": "bytes32" } ] },
  486. { "name" : "multi", "type": "function", "outputs": [ { "type": "bytes" }, { "type": "bytes" } ] },
  487. { "name" : "intArraySingle", "type": "function", "outputs": [ { "type": "uint256[3]" } ] },
  488. { "name" : "addressSliceSingle", "type": "function", "outputs": [ { "type": "address[]" } ] },
  489. { "name" : "addressSliceDouble", "type": "function", "outputs": [ { "name": "a", "type": "address[]" }, { "name": "b", "type": "address[]" } ] },
  490. { "name" : "mixedBytes", "type": "function", "stateMutability" : "view", "outputs": [ { "name": "a", "type": "bytes" }, { "name": "b", "type": "bytes32" } ] }]`
  491. abi, err := JSON(strings.NewReader(definition))
  492. if err != nil {
  493. t.Fatal(err)
  494. }
  495. buff := new(bytes.Buffer)
  496. // marshall mixed bytes (mixedBytes)
  497. p0, p0Exp := []byte{}, common.Hex2Bytes("01020000000000000000")
  498. p1, p1Exp := [32]byte{}, common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000ddeeff")
  499. mixedBytes := []interface{}{&p0, &p1}
  500. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  501. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000ddeeff"))
  502. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000000a"))
  503. buff.Write(common.Hex2Bytes("0102000000000000000000000000000000000000000000000000000000000000"))
  504. err = abi.Unpack(&mixedBytes, "mixedBytes", buff.Bytes())
  505. if err != nil {
  506. t.Error(err)
  507. } else {
  508. if !bytes.Equal(p0, p0Exp) {
  509. t.Errorf("unexpected value unpacked: want %x, got %x", p0Exp, p0)
  510. }
  511. if !bytes.Equal(p1[:], p1Exp) {
  512. t.Errorf("unexpected value unpacked: want %x, got %x", p1Exp, p1)
  513. }
  514. }
  515. // marshal int
  516. var Int *big.Int
  517. err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  518. if err != nil {
  519. t.Error(err)
  520. }
  521. if Int == nil || Int.Cmp(big.NewInt(1)) != 0 {
  522. t.Error("expected Int to be 1 got", Int)
  523. }
  524. // marshal bool
  525. var Bool bool
  526. err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  527. if err != nil {
  528. t.Error(err)
  529. }
  530. if !Bool {
  531. t.Error("expected Bool to be true")
  532. }
  533. // marshal dynamic bytes max length 32
  534. buff.Reset()
  535. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  536. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  537. bytesOut := common.RightPadBytes([]byte("hello"), 32)
  538. buff.Write(bytesOut)
  539. var Bytes []byte
  540. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  541. if err != nil {
  542. t.Error(err)
  543. }
  544. if !bytes.Equal(Bytes, bytesOut) {
  545. t.Errorf("expected %x got %x", bytesOut, Bytes)
  546. }
  547. // marshall dynamic bytes max length 64
  548. buff.Reset()
  549. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  550. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040"))
  551. bytesOut = common.RightPadBytes([]byte("hello"), 64)
  552. buff.Write(bytesOut)
  553. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  554. if err != nil {
  555. t.Error(err)
  556. }
  557. if !bytes.Equal(Bytes, bytesOut) {
  558. t.Errorf("expected %x got %x", bytesOut, Bytes)
  559. }
  560. // marshall dynamic bytes max length 64
  561. buff.Reset()
  562. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  563. buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000003f"))
  564. bytesOut = common.RightPadBytes([]byte("hello"), 64)
  565. buff.Write(bytesOut)
  566. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  567. if err != nil {
  568. t.Error(err)
  569. }
  570. if !bytes.Equal(Bytes, bytesOut[:len(bytesOut)-1]) {
  571. t.Errorf("expected %x got %x", bytesOut[:len(bytesOut)-1], Bytes)
  572. }
  573. // marshal dynamic bytes output empty
  574. err = abi.Unpack(&Bytes, "bytes", nil)
  575. if err == nil {
  576. t.Error("expected error")
  577. }
  578. // marshal dynamic bytes length 5
  579. buff.Reset()
  580. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  581. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
  582. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  583. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  584. if err != nil {
  585. t.Error(err)
  586. }
  587. if !bytes.Equal(Bytes, []byte("hello")) {
  588. t.Errorf("expected %x got %x", bytesOut, Bytes)
  589. }
  590. // marshal dynamic bytes length 5
  591. buff.Reset()
  592. buff.Write(common.RightPadBytes([]byte("hello"), 32))
  593. var hash common.Hash
  594. err = abi.Unpack(&hash, "fixed", buff.Bytes())
  595. if err != nil {
  596. t.Error(err)
  597. }
  598. helloHash := common.BytesToHash(common.RightPadBytes([]byte("hello"), 32))
  599. if hash != helloHash {
  600. t.Errorf("Expected %x to equal %x", hash, helloHash)
  601. }
  602. // marshal error
  603. buff.Reset()
  604. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
  605. err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
  606. if err == nil {
  607. t.Error("expected error")
  608. }
  609. err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
  610. if err == nil {
  611. t.Error("expected error")
  612. }
  613. buff.Reset()
  614. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
  615. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002"))
  616. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000003"))
  617. // marshal int array
  618. var intArray [3]*big.Int
  619. err = abi.Unpack(&intArray, "intArraySingle", buff.Bytes())
  620. if err != nil {
  621. t.Error(err)
  622. }
  623. var testAgainstIntArray [3]*big.Int
  624. testAgainstIntArray[0] = big.NewInt(1)
  625. testAgainstIntArray[1] = big.NewInt(2)
  626. testAgainstIntArray[2] = big.NewInt(3)
  627. for i, Int := range intArray {
  628. if Int.Cmp(testAgainstIntArray[i]) != 0 {
  629. t.Errorf("expected %v, got %v", testAgainstIntArray[i], Int)
  630. }
  631. }
  632. // marshal address slice
  633. buff.Reset()
  634. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) // offset
  635. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  636. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  637. var outAddr []common.Address
  638. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  639. if err != nil {
  640. t.Fatal("didn't expect error:", err)
  641. }
  642. if len(outAddr) != 1 {
  643. t.Fatal("expected 1 item, got", len(outAddr))
  644. }
  645. if outAddr[0] != (common.Address{1}) {
  646. t.Errorf("expected %x, got %x", common.Address{1}, outAddr[0])
  647. }
  648. // marshal multiple address slice
  649. buff.Reset()
  650. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) // offset
  651. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // offset
  652. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // size
  653. buff.Write(common.Hex2Bytes("0000000000000000000000000100000000000000000000000000000000000000"))
  654. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // size
  655. buff.Write(common.Hex2Bytes("0000000000000000000000000200000000000000000000000000000000000000"))
  656. buff.Write(common.Hex2Bytes("0000000000000000000000000300000000000000000000000000000000000000"))
  657. var outAddrStruct struct {
  658. A []common.Address
  659. B []common.Address
  660. }
  661. err = abi.Unpack(&outAddrStruct, "addressSliceDouble", buff.Bytes())
  662. if err != nil {
  663. t.Fatal("didn't expect error:", err)
  664. }
  665. if len(outAddrStruct.A) != 1 {
  666. t.Fatal("expected 1 item, got", len(outAddrStruct.A))
  667. }
  668. if outAddrStruct.A[0] != (common.Address{1}) {
  669. t.Errorf("expected %x, got %x", common.Address{1}, outAddrStruct.A[0])
  670. }
  671. if len(outAddrStruct.B) != 2 {
  672. t.Fatal("expected 1 item, got", len(outAddrStruct.B))
  673. }
  674. if outAddrStruct.B[0] != (common.Address{2}) {
  675. t.Errorf("expected %x, got %x", common.Address{2}, outAddrStruct.B[0])
  676. }
  677. if outAddrStruct.B[1] != (common.Address{3}) {
  678. t.Errorf("expected %x, got %x", common.Address{3}, outAddrStruct.B[1])
  679. }
  680. // marshal invalid address slice
  681. buff.Reset()
  682. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000100"))
  683. err = abi.Unpack(&outAddr, "addressSliceSingle", buff.Bytes())
  684. if err == nil {
  685. t.Fatal("expected error:", err)
  686. }
  687. }
  688. func TestUnpackTuple(t *testing.T) {
  689. const simpleTuple = `[{"name":"tuple","type":"function","outputs":[{"type":"tuple","name":"ret","components":[{"type":"int256","name":"a"},{"type":"int256","name":"b"}]}]}]`
  690. abi, err := JSON(strings.NewReader(simpleTuple))
  691. if err != nil {
  692. t.Fatal(err)
  693. }
  694. buff := new(bytes.Buffer)
  695. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // ret[a] = 1
  696. buff.Write(common.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) // ret[b] = -1
  697. // If the result is single tuple, use struct as return value container directly.
  698. v := struct {
  699. A *big.Int
  700. B *big.Int
  701. }{new(big.Int), new(big.Int)}
  702. err = abi.Unpack(&v, "tuple", buff.Bytes())
  703. if err != nil {
  704. t.Error(err)
  705. } else {
  706. if v.A.Cmp(big.NewInt(1)) != 0 {
  707. t.Errorf("unexpected value unpacked: want %x, got %x", 1, v.A)
  708. }
  709. if v.B.Cmp(big.NewInt(-1)) != 0 {
  710. t.Errorf("unexpected value unpacked: want %x, got %x", -1, v.B)
  711. }
  712. }
  713. // Test nested tuple
  714. const nestedTuple = `[{"name":"tuple","type":"function","outputs":[
  715. {"type":"tuple","name":"s","components":[{"type":"uint256","name":"a"},{"type":"uint256[]","name":"b"},{"type":"tuple[]","name":"c","components":[{"name":"x", "type":"uint256"},{"name":"y","type":"uint256"}]}]},
  716. {"type":"tuple","name":"t","components":[{"name":"x", "type":"uint256"},{"name":"y","type":"uint256"}]},
  717. {"type":"uint256","name":"a"}
  718. ]}]`
  719. abi, err = JSON(strings.NewReader(nestedTuple))
  720. if err != nil {
  721. t.Fatal(err)
  722. }
  723. buff.Reset()
  724. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000080")) // s offset
  725. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000000")) // t.X = 0
  726. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // t.Y = 1
  727. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // a = 1
  728. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // s.A = 1
  729. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000060")) // s.B offset
  730. buff.Write(common.Hex2Bytes("00000000000000000000000000000000000000000000000000000000000000c0")) // s.C offset
  731. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // s.B length
  732. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // s.B[0] = 1
  733. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // s.B[0] = 2
  734. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // s.C length
  735. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // s.C[0].X
  736. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // s.C[0].Y
  737. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000002")) // s.C[1].X
  738. buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) // s.C[1].Y
  739. type T struct {
  740. X *big.Int `abi:"x"`
  741. Z *big.Int `abi:"y"` // Test whether the abi tag works.
  742. }
  743. type S struct {
  744. A *big.Int
  745. B []*big.Int
  746. C []T
  747. }
  748. type Ret struct {
  749. FieldS S `abi:"s"`
  750. FieldT T `abi:"t"`
  751. A *big.Int
  752. }
  753. var ret Ret
  754. var expected = Ret{
  755. FieldS: S{
  756. A: big.NewInt(1),
  757. B: []*big.Int{big.NewInt(1), big.NewInt(2)},
  758. C: []T{
  759. {big.NewInt(1), big.NewInt(2)},
  760. {big.NewInt(2), big.NewInt(1)},
  761. },
  762. },
  763. FieldT: T{
  764. big.NewInt(0), big.NewInt(1),
  765. },
  766. A: big.NewInt(1),
  767. }
  768. err = abi.Unpack(&ret, "tuple", buff.Bytes())
  769. if err != nil {
  770. t.Error(err)
  771. }
  772. if reflect.DeepEqual(ret, expected) {
  773. t.Error("unexpected unpack value")
  774. }
  775. }
  776. func TestOOMMaliciousInput(t *testing.T) {
  777. oomTests := []unpackTest{
  778. {
  779. def: `[{"type": "uint8[]"}]`,
  780. enc: "0000000000000000000000000000000000000000000000000000000000000020" + // offset
  781. "0000000000000000000000000000000000000000000000000000000000000003" + // num elems
  782. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  783. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  784. },
  785. { // Length larger than 64 bits
  786. def: `[{"type": "uint8[]"}]`,
  787. enc: "0000000000000000000000000000000000000000000000000000000000000020" + // offset
  788. "00ffffffffffffffffffffffffffffffffffffffffffffff0000000000000002" + // num elems
  789. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  790. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  791. },
  792. { // Offset very large (over 64 bits)
  793. def: `[{"type": "uint8[]"}]`,
  794. enc: "00ffffffffffffffffffffffffffffffffffffffffffffff0000000000000020" + // offset
  795. "0000000000000000000000000000000000000000000000000000000000000002" + // num elems
  796. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  797. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  798. },
  799. { // Offset very large (below 64 bits)
  800. def: `[{"type": "uint8[]"}]`,
  801. enc: "0000000000000000000000000000000000000000000000007ffffffffff00020" + // offset
  802. "0000000000000000000000000000000000000000000000000000000000000002" + // num elems
  803. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  804. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  805. },
  806. { // Offset negative (as 64 bit)
  807. def: `[{"type": "uint8[]"}]`,
  808. enc: "000000000000000000000000000000000000000000000000f000000000000020" + // offset
  809. "0000000000000000000000000000000000000000000000000000000000000002" + // num elems
  810. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  811. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  812. },
  813. { // Negative length
  814. def: `[{"type": "uint8[]"}]`,
  815. enc: "0000000000000000000000000000000000000000000000000000000000000020" + // offset
  816. "000000000000000000000000000000000000000000000000f000000000000002" + // num elems
  817. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  818. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  819. },
  820. { // Very large length
  821. def: `[{"type": "uint8[]"}]`,
  822. enc: "0000000000000000000000000000000000000000000000000000000000000020" + // offset
  823. "0000000000000000000000000000000000000000000000007fffffffff000002" + // num elems
  824. "0000000000000000000000000000000000000000000000000000000000000001" + // elem 1
  825. "0000000000000000000000000000000000000000000000000000000000000002", // elem 2
  826. },
  827. }
  828. for i, test := range oomTests {
  829. def := fmt.Sprintf(`[{ "name" : "method", "type": "function", "outputs": %s}]`, test.def)
  830. abi, err := JSON(strings.NewReader(def))
  831. if err != nil {
  832. t.Fatalf("invalid ABI definition %s: %v", def, err)
  833. }
  834. encb, err := hex.DecodeString(test.enc)
  835. if err != nil {
  836. t.Fatalf("invalid hex: %s" + test.enc)
  837. }
  838. _, err = abi.Methods["method"].Outputs.UnpackValues(encb)
  839. if err == nil {
  840. t.Fatalf("Expected error on malicious input, test %d", i)
  841. }
  842. }
  843. }