event_test.go 12 KB

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