unpack_test.go 36 KB

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