event_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // Copyright 2016 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. "encoding/json"
  21. "math/big"
  22. "reflect"
  23. "strings"
  24. "testing"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/stretchr/testify/assert"
  28. "github.com/stretchr/testify/require"
  29. )
  30. var jsonEventTransfer = []byte(`{
  31. "anonymous": false,
  32. "inputs": [
  33. {
  34. "indexed": true, "name": "from", "type": "address"
  35. }, {
  36. "indexed": true, "name": "to", "type": "address"
  37. }, {
  38. "indexed": false, "name": "value", "type": "uint256"
  39. }],
  40. "name": "Transfer",
  41. "type": "event"
  42. }`)
  43. var jsonEventPledge = []byte(`{
  44. "anonymous": false,
  45. "inputs": [{
  46. "indexed": false, "name": "who", "type": "address"
  47. }, {
  48. "indexed": false, "name": "wad", "type": "uint128"
  49. }, {
  50. "indexed": false, "name": "currency", "type": "bytes3"
  51. }],
  52. "name": "Pledge",
  53. "type": "event"
  54. }`)
  55. var jsonEventMixedCase = []byte(`{
  56. "anonymous": false,
  57. "inputs": [{
  58. "indexed": false, "name": "value", "type": "uint256"
  59. }, {
  60. "indexed": false, "name": "_value", "type": "uint256"
  61. }, {
  62. "indexed": false, "name": "Value", "type": "uint256"
  63. }],
  64. "name": "MixedCase",
  65. "type": "event"
  66. }`)
  67. // 1000000
  68. var transferData1 = "00000000000000000000000000000000000000000000000000000000000f4240"
  69. // "0x00Ce0d46d924CC8437c806721496599FC3FFA268", 2218516807680, "usd"
  70. var pledgeData1 = "00000000000000000000000000ce0d46d924cc8437c806721496599fc3ffa2680000000000000000000000000000000000000000000000000000020489e800007573640000000000000000000000000000000000000000000000000000000000"
  71. // 1000000,2218516807680,1000001
  72. var mixedCaseData1 = "00000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000020489e8000000000000000000000000000000000000000000000000000000000000000f4241"
  73. func TestEventId(t *testing.T) {
  74. var table = []struct {
  75. definition string
  76. expectations map[string]common.Hash
  77. }{
  78. {
  79. definition: `[
  80. { "type" : "event", "name" : "Balance", "inputs": [{ "name" : "in", "type": "uint256" }] },
  81. { "type" : "event", "name" : "Check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] }
  82. ]`,
  83. expectations: map[string]common.Hash{
  84. "Balance": crypto.Keccak256Hash([]byte("Balance(uint256)")),
  85. "Check": crypto.Keccak256Hash([]byte("Check(address,uint256)")),
  86. },
  87. },
  88. }
  89. for _, test := range table {
  90. abi, err := JSON(strings.NewReader(test.definition))
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. for name, event := range abi.Events {
  95. if event.ID() != test.expectations[name] {
  96. t.Errorf("expected id to be %x, got %x", test.expectations[name], event.ID())
  97. }
  98. }
  99. }
  100. }
  101. func TestEventString(t *testing.T) {
  102. var table = []struct {
  103. definition string
  104. expectations map[string]string
  105. }{
  106. {
  107. definition: `[
  108. { "type" : "event", "name" : "Balance", "inputs": [{ "name" : "in", "type": "uint256" }] },
  109. { "type" : "event", "name" : "Check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] },
  110. { "type" : "event", "name" : "Transfer", "inputs": [{ "name": "from", "type": "address", "indexed": true }, { "name": "to", "type": "address", "indexed": true }, { "name": "value", "type": "uint256" }] }
  111. ]`,
  112. expectations: map[string]string{
  113. "Balance": "event Balance(uint256 in)",
  114. "Check": "event Check(address t, uint256 b)",
  115. "Transfer": "event Transfer(address indexed from, address indexed to, uint256 value)",
  116. },
  117. },
  118. }
  119. for _, test := range table {
  120. abi, err := JSON(strings.NewReader(test.definition))
  121. if err != nil {
  122. t.Fatal(err)
  123. }
  124. for name, event := range abi.Events {
  125. if event.String() != test.expectations[name] {
  126. t.Errorf("expected string to be %s, got %s", test.expectations[name], event.String())
  127. }
  128. }
  129. }
  130. }
  131. // TestEventMultiValueWithArrayUnpack verifies that array fields will be counted after parsing array.
  132. func TestEventMultiValueWithArrayUnpack(t *testing.T) {
  133. definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": false, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
  134. type testStruct struct {
  135. Value1 [2]uint8
  136. Value2 uint8
  137. }
  138. abi, err := JSON(strings.NewReader(definition))
  139. require.NoError(t, err)
  140. var b bytes.Buffer
  141. var i uint8 = 1
  142. for ; i <= 3; i++ {
  143. b.Write(packNum(reflect.ValueOf(i)))
  144. }
  145. var rst testStruct
  146. require.NoError(t, abi.Unpack(&rst, "test", b.Bytes()))
  147. require.Equal(t, [2]uint8{1, 2}, rst.Value1)
  148. require.Equal(t, uint8(3), rst.Value2)
  149. }
  150. func TestEventTupleUnpack(t *testing.T) {
  151. type EventTransfer struct {
  152. Value *big.Int
  153. }
  154. type EventTransferWithTag struct {
  155. // this is valid because `value` is not exportable,
  156. // so value is only unmarshalled into `Value1`.
  157. value *big.Int
  158. Value1 *big.Int `abi:"value"`
  159. }
  160. type BadEventTransferWithSameFieldAndTag struct {
  161. Value *big.Int
  162. Value1 *big.Int `abi:"value"`
  163. }
  164. type BadEventTransferWithDuplicatedTag struct {
  165. Value1 *big.Int `abi:"value"`
  166. Value2 *big.Int `abi:"value"`
  167. }
  168. type BadEventTransferWithEmptyTag struct {
  169. Value *big.Int `abi:""`
  170. }
  171. type EventPledge struct {
  172. Who common.Address
  173. Wad *big.Int
  174. Currency [3]byte
  175. }
  176. type BadEventPledge struct {
  177. Who string
  178. Wad int
  179. Currency [3]byte
  180. }
  181. type EventMixedCase struct {
  182. Value1 *big.Int `abi:"value"`
  183. Value2 *big.Int `abi:"_value"`
  184. Value3 *big.Int `abi:"Value"`
  185. }
  186. bigint := new(big.Int)
  187. bigintExpected := big.NewInt(1000000)
  188. bigintExpected2 := big.NewInt(2218516807680)
  189. bigintExpected3 := big.NewInt(1000001)
  190. addr := common.HexToAddress("0x00Ce0d46d924CC8437c806721496599FC3FFA268")
  191. var testCases = []struct {
  192. data string
  193. dest interface{}
  194. expected interface{}
  195. jsonLog []byte
  196. error string
  197. name string
  198. }{{
  199. transferData1,
  200. &EventTransfer{},
  201. &EventTransfer{Value: bigintExpected},
  202. jsonEventTransfer,
  203. "",
  204. "Can unpack ERC20 Transfer event into structure",
  205. }, {
  206. transferData1,
  207. &[]interface{}{&bigint},
  208. &[]interface{}{&bigintExpected},
  209. jsonEventTransfer,
  210. "",
  211. "Can unpack ERC20 Transfer event into slice",
  212. }, {
  213. transferData1,
  214. &EventTransferWithTag{},
  215. &EventTransferWithTag{Value1: bigintExpected},
  216. jsonEventTransfer,
  217. "",
  218. "Can unpack ERC20 Transfer event into structure with abi: tag",
  219. }, {
  220. transferData1,
  221. &BadEventTransferWithDuplicatedTag{},
  222. &BadEventTransferWithDuplicatedTag{},
  223. jsonEventTransfer,
  224. "struct: abi tag in 'Value2' already mapped",
  225. "Can not unpack ERC20 Transfer event with duplicated abi tag",
  226. }, {
  227. transferData1,
  228. &BadEventTransferWithSameFieldAndTag{},
  229. &BadEventTransferWithSameFieldAndTag{},
  230. jsonEventTransfer,
  231. "abi: multiple variables maps to the same abi field 'value'",
  232. "Can not unpack ERC20 Transfer event with a field and a tag mapping to the same abi variable",
  233. }, {
  234. transferData1,
  235. &BadEventTransferWithEmptyTag{},
  236. &BadEventTransferWithEmptyTag{},
  237. jsonEventTransfer,
  238. "struct: abi tag in 'Value' is empty",
  239. "Can not unpack ERC20 Transfer event with an empty tag",
  240. }, {
  241. pledgeData1,
  242. &EventPledge{},
  243. &EventPledge{
  244. addr,
  245. bigintExpected2,
  246. [3]byte{'u', 's', 'd'}},
  247. jsonEventPledge,
  248. "",
  249. "Can unpack Pledge event into structure",
  250. }, {
  251. pledgeData1,
  252. &[]interface{}{&common.Address{}, &bigint, &[3]byte{}},
  253. &[]interface{}{
  254. &addr,
  255. &bigintExpected2,
  256. &[3]byte{'u', 's', 'd'}},
  257. jsonEventPledge,
  258. "",
  259. "Can unpack Pledge event into slice",
  260. }, {
  261. pledgeData1,
  262. &[3]interface{}{&common.Address{}, &bigint, &[3]byte{}},
  263. &[3]interface{}{
  264. &addr,
  265. &bigintExpected2,
  266. &[3]byte{'u', 's', 'd'}},
  267. jsonEventPledge,
  268. "",
  269. "Can unpack Pledge event into an array",
  270. }, {
  271. pledgeData1,
  272. &[]interface{}{new(int), 0, 0},
  273. &[]interface{}{},
  274. jsonEventPledge,
  275. "abi: cannot unmarshal common.Address in to int",
  276. "Can not unpack Pledge event into slice with wrong types",
  277. }, {
  278. pledgeData1,
  279. &BadEventPledge{},
  280. &BadEventPledge{},
  281. jsonEventPledge,
  282. "abi: cannot unmarshal common.Address in to string",
  283. "Can not unpack Pledge event into struct with wrong filed types",
  284. }, {
  285. pledgeData1,
  286. &[]interface{}{common.Address{}, new(big.Int)},
  287. &[]interface{}{},
  288. jsonEventPledge,
  289. "abi: insufficient number of elements in the list/array for unpack, want 3, got 2",
  290. "Can not unpack Pledge event into too short slice",
  291. }, {
  292. pledgeData1,
  293. new(map[string]interface{}),
  294. &[]interface{}{},
  295. jsonEventPledge,
  296. "abi: cannot unmarshal tuple into map[string]interface {}",
  297. "Can not unpack Pledge event into map",
  298. }, {
  299. mixedCaseData1,
  300. &EventMixedCase{},
  301. &EventMixedCase{Value1: bigintExpected, Value2: bigintExpected2, Value3: bigintExpected3},
  302. jsonEventMixedCase,
  303. "",
  304. "Can unpack abi variables with mixed case",
  305. }}
  306. for _, tc := range testCases {
  307. assert := assert.New(t)
  308. tc := tc
  309. t.Run(tc.name, func(t *testing.T) {
  310. err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert)
  311. if tc.error == "" {
  312. assert.Nil(err, "Should be able to unpack event data.")
  313. assert.Equal(tc.expected, tc.dest, tc.name)
  314. } else {
  315. assert.EqualError(err, tc.error, tc.name)
  316. }
  317. })
  318. }
  319. }
  320. func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error {
  321. data, err := hex.DecodeString(hexData)
  322. assert.NoError(err, "Hex data should be a correct hex-string")
  323. var e Event
  324. assert.NoError(json.Unmarshal(jsonEvent, &e), "Should be able to unmarshal event ABI")
  325. a := ABI{Events: map[string]Event{"e": e}}
  326. return a.Unpack(dest, "e", data)
  327. }
  328. /*
  329. Taken from
  330. https://github.com/ethereum/go-ethereum/pull/15568
  331. */
  332. type testResult struct {
  333. Values [2]*big.Int
  334. Value1 *big.Int
  335. Value2 *big.Int
  336. }
  337. type testCase struct {
  338. definition string
  339. want testResult
  340. }
  341. func (tc testCase) encoded(intType, arrayType Type) []byte {
  342. var b bytes.Buffer
  343. if tc.want.Value1 != nil {
  344. val, _ := intType.pack(reflect.ValueOf(tc.want.Value1))
  345. b.Write(val)
  346. }
  347. if !reflect.DeepEqual(tc.want.Values, [2]*big.Int{nil, nil}) {
  348. val, _ := arrayType.pack(reflect.ValueOf(tc.want.Values))
  349. b.Write(val)
  350. }
  351. if tc.want.Value2 != nil {
  352. val, _ := intType.pack(reflect.ValueOf(tc.want.Value2))
  353. b.Write(val)
  354. }
  355. return b.Bytes()
  356. }
  357. // TestEventUnpackIndexed verifies that indexed field will be skipped by event decoder.
  358. func TestEventUnpackIndexed(t *testing.T) {
  359. definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
  360. type testStruct struct {
  361. Value1 uint8
  362. Value2 uint8
  363. }
  364. abi, err := JSON(strings.NewReader(definition))
  365. require.NoError(t, err)
  366. var b bytes.Buffer
  367. b.Write(packNum(reflect.ValueOf(uint8(8))))
  368. var rst testStruct
  369. require.NoError(t, abi.Unpack(&rst, "test", b.Bytes()))
  370. require.Equal(t, uint8(0), rst.Value1)
  371. require.Equal(t, uint8(8), rst.Value2)
  372. }
  373. // TestEventIndexedWithArrayUnpack verifies that decoder will not overlow when static array is indexed input.
  374. func TestEventIndexedWithArrayUnpack(t *testing.T) {
  375. definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"string"}]}]`
  376. type testStruct struct {
  377. Value1 [2]uint8
  378. Value2 string
  379. }
  380. abi, err := JSON(strings.NewReader(definition))
  381. require.NoError(t, err)
  382. var b bytes.Buffer
  383. stringOut := "abc"
  384. // number of fields that will be encoded * 32
  385. b.Write(packNum(reflect.ValueOf(32)))
  386. b.Write(packNum(reflect.ValueOf(len(stringOut))))
  387. b.Write(common.RightPadBytes([]byte(stringOut), 32))
  388. var rst testStruct
  389. require.NoError(t, abi.Unpack(&rst, "test", b.Bytes()))
  390. require.Equal(t, [2]uint8{0, 0}, rst.Value1)
  391. require.Equal(t, stringOut, rst.Value2)
  392. }