unpack_test.go 36 KB

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