event_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. // TestEventMultiValueWithArrayUnpack verifies that array fields will be counted after parsing array.
  102. func TestEventMultiValueWithArrayUnpack(t *testing.T) {
  103. definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": false, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
  104. type testStruct struct {
  105. Value1 [2]uint8
  106. Value2 uint8
  107. }
  108. abi, err := JSON(strings.NewReader(definition))
  109. require.NoError(t, err)
  110. var b bytes.Buffer
  111. var i uint8 = 1
  112. for ; i <= 3; i++ {
  113. b.Write(packNum(reflect.ValueOf(i)))
  114. }
  115. var rst testStruct
  116. require.NoError(t, abi.Unpack(&rst, "test", b.Bytes()))
  117. require.Equal(t, [2]uint8{1, 2}, rst.Value1)
  118. require.Equal(t, uint8(3), rst.Value2)
  119. }
  120. func TestEventTupleUnpack(t *testing.T) {
  121. type EventTransfer struct {
  122. Value *big.Int
  123. }
  124. type EventTransferWithTag struct {
  125. // this is valid because `value` is not exportable,
  126. // so value is only unmarshalled into `Value1`.
  127. value *big.Int
  128. Value1 *big.Int `abi:"value"`
  129. }
  130. type BadEventTransferWithSameFieldAndTag struct {
  131. Value *big.Int
  132. Value1 *big.Int `abi:"value"`
  133. }
  134. type BadEventTransferWithDuplicatedTag struct {
  135. Value1 *big.Int `abi:"value"`
  136. Value2 *big.Int `abi:"value"`
  137. }
  138. type BadEventTransferWithEmptyTag struct {
  139. Value *big.Int `abi:""`
  140. }
  141. type EventPledge struct {
  142. Who common.Address
  143. Wad *big.Int
  144. Currency [3]byte
  145. }
  146. type BadEventPledge struct {
  147. Who string
  148. Wad int
  149. Currency [3]byte
  150. }
  151. type EventMixedCase struct {
  152. Value1 *big.Int `abi:"value"`
  153. Value2 *big.Int `abi:"_value"`
  154. Value3 *big.Int `abi:"Value"`
  155. }
  156. bigint := new(big.Int)
  157. bigintExpected := big.NewInt(1000000)
  158. bigintExpected2 := big.NewInt(2218516807680)
  159. bigintExpected3 := big.NewInt(1000001)
  160. addr := common.HexToAddress("0x00Ce0d46d924CC8437c806721496599FC3FFA268")
  161. var testCases = []struct {
  162. data string
  163. dest interface{}
  164. expected interface{}
  165. jsonLog []byte
  166. error string
  167. name string
  168. }{{
  169. transferData1,
  170. &EventTransfer{},
  171. &EventTransfer{Value: bigintExpected},
  172. jsonEventTransfer,
  173. "",
  174. "Can unpack ERC20 Transfer event into structure",
  175. }, {
  176. transferData1,
  177. &[]interface{}{&bigint},
  178. &[]interface{}{&bigintExpected},
  179. jsonEventTransfer,
  180. "",
  181. "Can unpack ERC20 Transfer event into slice",
  182. }, {
  183. transferData1,
  184. &EventTransferWithTag{},
  185. &EventTransferWithTag{Value1: bigintExpected},
  186. jsonEventTransfer,
  187. "",
  188. "Can unpack ERC20 Transfer event into structure with abi: tag",
  189. }, {
  190. transferData1,
  191. &BadEventTransferWithDuplicatedTag{},
  192. &BadEventTransferWithDuplicatedTag{},
  193. jsonEventTransfer,
  194. "struct: abi tag in 'Value2' already mapped",
  195. "Can not unpack ERC20 Transfer event with duplicated abi tag",
  196. }, {
  197. transferData1,
  198. &BadEventTransferWithSameFieldAndTag{},
  199. &BadEventTransferWithSameFieldAndTag{},
  200. jsonEventTransfer,
  201. "abi: multiple variables maps to the same abi field 'value'",
  202. "Can not unpack ERC20 Transfer event with a field and a tag mapping to the same abi variable",
  203. }, {
  204. transferData1,
  205. &BadEventTransferWithEmptyTag{},
  206. &BadEventTransferWithEmptyTag{},
  207. jsonEventTransfer,
  208. "struct: abi tag in 'Value' is empty",
  209. "Can not unpack ERC20 Transfer event with an empty tag",
  210. }, {
  211. pledgeData1,
  212. &EventPledge{},
  213. &EventPledge{
  214. addr,
  215. bigintExpected2,
  216. [3]byte{'u', 's', 'd'}},
  217. jsonEventPledge,
  218. "",
  219. "Can unpack Pledge event into structure",
  220. }, {
  221. pledgeData1,
  222. &[]interface{}{&common.Address{}, &bigint, &[3]byte{}},
  223. &[]interface{}{
  224. &addr,
  225. &bigintExpected2,
  226. &[3]byte{'u', 's', 'd'}},
  227. jsonEventPledge,
  228. "",
  229. "Can unpack Pledge event into slice",
  230. }, {
  231. pledgeData1,
  232. &[3]interface{}{&common.Address{}, &bigint, &[3]byte{}},
  233. &[3]interface{}{
  234. &addr,
  235. &bigintExpected2,
  236. &[3]byte{'u', 's', 'd'}},
  237. jsonEventPledge,
  238. "",
  239. "Can unpack Pledge event into an array",
  240. }, {
  241. pledgeData1,
  242. &[]interface{}{new(int), 0, 0},
  243. &[]interface{}{},
  244. jsonEventPledge,
  245. "abi: cannot unmarshal common.Address in to int",
  246. "Can not unpack Pledge event into slice with wrong types",
  247. }, {
  248. pledgeData1,
  249. &BadEventPledge{},
  250. &BadEventPledge{},
  251. jsonEventPledge,
  252. "abi: cannot unmarshal common.Address in to string",
  253. "Can not unpack Pledge event into struct with wrong filed types",
  254. }, {
  255. pledgeData1,
  256. &[]interface{}{common.Address{}, new(big.Int)},
  257. &[]interface{}{},
  258. jsonEventPledge,
  259. "abi: insufficient number of elements in the list/array for unpack, want 3, got 2",
  260. "Can not unpack Pledge event into too short slice",
  261. }, {
  262. pledgeData1,
  263. new(map[string]interface{}),
  264. &[]interface{}{},
  265. jsonEventPledge,
  266. "abi: cannot unmarshal tuple into map[string]interface {}",
  267. "Can not unpack Pledge event into map",
  268. }, {
  269. mixedCaseData1,
  270. &EventMixedCase{},
  271. &EventMixedCase{Value1: bigintExpected, Value2: bigintExpected2, Value3: bigintExpected3},
  272. jsonEventMixedCase,
  273. "",
  274. "Can unpack abi variables with mixed case",
  275. }}
  276. for _, tc := range testCases {
  277. assert := assert.New(t)
  278. tc := tc
  279. t.Run(tc.name, func(t *testing.T) {
  280. err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert)
  281. if tc.error == "" {
  282. assert.Nil(err, "Should be able to unpack event data.")
  283. assert.Equal(tc.expected, tc.dest, tc.name)
  284. } else {
  285. assert.EqualError(err, tc.error, tc.name)
  286. }
  287. })
  288. }
  289. }
  290. func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error {
  291. data, err := hex.DecodeString(hexData)
  292. assert.NoError(err, "Hex data should be a correct hex-string")
  293. var e Event
  294. assert.NoError(json.Unmarshal(jsonEvent, &e), "Should be able to unmarshal event ABI")
  295. a := ABI{Events: map[string]Event{"e": e}}
  296. return a.Unpack(dest, "e", data)
  297. }
  298. /*
  299. Taken from
  300. https://github.com/ethereum/go-ethereum/pull/15568
  301. */
  302. type testResult struct {
  303. Values [2]*big.Int
  304. Value1 *big.Int
  305. Value2 *big.Int
  306. }
  307. type testCase struct {
  308. definition string
  309. want testResult
  310. }
  311. func (tc testCase) encoded(intType, arrayType Type) []byte {
  312. var b bytes.Buffer
  313. if tc.want.Value1 != nil {
  314. val, _ := intType.pack(reflect.ValueOf(tc.want.Value1))
  315. b.Write(val)
  316. }
  317. if !reflect.DeepEqual(tc.want.Values, [2]*big.Int{nil, nil}) {
  318. val, _ := arrayType.pack(reflect.ValueOf(tc.want.Values))
  319. b.Write(val)
  320. }
  321. if tc.want.Value2 != nil {
  322. val, _ := intType.pack(reflect.ValueOf(tc.want.Value2))
  323. b.Write(val)
  324. }
  325. return b.Bytes()
  326. }
  327. // TestEventUnpackIndexed verifies that indexed field will be skipped by event decoder.
  328. func TestEventUnpackIndexed(t *testing.T) {
  329. definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
  330. type testStruct struct {
  331. Value1 uint8
  332. Value2 uint8
  333. }
  334. abi, err := JSON(strings.NewReader(definition))
  335. require.NoError(t, err)
  336. var b bytes.Buffer
  337. b.Write(packNum(reflect.ValueOf(uint8(8))))
  338. var rst testStruct
  339. require.NoError(t, abi.Unpack(&rst, "test", b.Bytes()))
  340. require.Equal(t, uint8(0), rst.Value1)
  341. require.Equal(t, uint8(8), rst.Value2)
  342. }
  343. // TestEventIndexedWithArrayUnpack verifies that decoder will not overlow when static array is indexed input.
  344. func TestEventIndexedWithArrayUnpack(t *testing.T) {
  345. definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"string"}]}]`
  346. type testStruct struct {
  347. Value1 [2]uint8
  348. Value2 string
  349. }
  350. abi, err := JSON(strings.NewReader(definition))
  351. require.NoError(t, err)
  352. var b bytes.Buffer
  353. stringOut := "abc"
  354. // number of fields that will be encoded * 32
  355. b.Write(packNum(reflect.ValueOf(32)))
  356. b.Write(packNum(reflect.ValueOf(len(stringOut))))
  357. b.Write(common.RightPadBytes([]byte(stringOut), 32))
  358. var rst testStruct
  359. require.NoError(t, abi.Unpack(&rst, "test", b.Bytes()))
  360. require.Equal(t, [2]uint8{0, 0}, rst.Value1)
  361. require.Equal(t, stringOut, rst.Value2)
  362. }