1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Copyright 2015-2020 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Contract event.

use alloc::collections::BTreeMap;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use sha3::{Digest, Keccak256};

#[cfg(not(feature = "std"))]
use crate::no_std_prelude::*;
use crate::{
	decode, decode_validate, encode, signature::long_signature, Error, EventParam, Hash, Log, LogParam, ParamType,
	RawLog, RawTopicFilter, Result, Token, Topic, TopicFilter,
};

/// Contract event.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
	/// Event name.
	#[cfg_attr(feature = "serde", serde(deserialize_with = "crate::util::sanitize_name::deserialize"))]
	pub name: String,
	/// Event input.
	pub inputs: Vec<EventParam>,
	/// If anonymous, event cannot be found using `from` filter.
	pub anonymous: bool,
}

impl Event {
	/// Returns names of all params.
	fn params_names(&self) -> Vec<String> {
		self.inputs.iter().map(|p| p.name.clone()).collect()
	}

	/// Returns types of all params.
	fn param_types(&self) -> Vec<ParamType> {
		self.inputs.iter().map(|p| p.kind.clone()).collect()
	}

	/// Returns all params of the event.
	fn indexed_params(&self, indexed: bool) -> Vec<EventParam> {
		self.inputs.iter().filter(|p| p.indexed == indexed).cloned().collect()
	}

	/// Event signature
	pub fn signature(&self) -> Hash {
		long_signature(&self.name, &self.param_types())
	}

	/// Creates topic filter
	pub fn filter(&self, raw: RawTopicFilter) -> Result<TopicFilter> {
		fn convert_token(token: Token, kind: &ParamType) -> Result<Hash> {
			if !token.type_check(kind) {
				return Err(Error::InvalidData);
			}
			let encoded = encode(&[token]);
			if encoded.len() == 32 {
				let mut data = [0u8; 32];
				data.copy_from_slice(&encoded);
				Ok(data.into())
			} else {
				Ok(Hash::from_slice(Keccak256::digest(&encoded).as_slice()))
			}
		}

		fn convert_topic(topic: Topic<Token>, kind: Option<&ParamType>) -> Result<Topic<Hash>> {
			match topic {
				Topic::Any => Ok(Topic::Any),
				Topic::OneOf(tokens) => match kind {
					None => Err(Error::InvalidData),
					Some(kind) => {
						let topics =
							tokens.into_iter().map(|token| convert_token(token, kind)).collect::<Result<Vec<_>>>()?;
						Ok(Topic::OneOf(topics))
					}
				},
				Topic::This(token) => match kind {
					None => Err(Error::InvalidData),
					Some(kind) => Ok(Topic::This(convert_token(token, kind)?)),
				},
			}
		}

		let kinds: Vec<_> = self.indexed_params(true).into_iter().map(|param| param.kind).collect();
		let result = if self.anonymous {
			TopicFilter {
				topic0: convert_topic(raw.topic0, kinds.get(0))?,
				topic1: convert_topic(raw.topic1, kinds.get(1))?,
				topic2: convert_topic(raw.topic2, kinds.get(2))?,
				topic3: Topic::Any,
			}
		} else {
			TopicFilter {
				topic0: Topic::This(self.signature()),
				topic1: convert_topic(raw.topic0, kinds.get(0))?,
				topic2: convert_topic(raw.topic1, kinds.get(1))?,
				topic3: convert_topic(raw.topic2, kinds.get(2))?,
			}
		};

		Ok(result)
	}

	// Converts param types for indexed parameters to bytes32 where appropriate
	// This applies to strings, arrays, structs and bytes to follow the encoding of
	// these indexed param types according to
	// https://solidity.readthedocs.io/en/develop/abi-spec.html#encoding-of-indexed-event-parameters
	fn convert_topic_param_type(&self, kind: &ParamType) -> ParamType {
		match kind {
			ParamType::String
			| ParamType::Bytes
			| ParamType::Array(_)
			| ParamType::FixedArray(_, _)
			| ParamType::Tuple(_) => ParamType::FixedBytes(32),
			_ => kind.clone(),
		}
	}

	fn parse_log_inner<F: Fn(&[ParamType], &[u8]) -> Result<Vec<Token>>>(&self, log: RawLog, decode: F) -> Result<Log> {
		let topics = log.topics;
		let data = log.data;
		let topics_len = topics.len();
		// obtains all params info
		let topic_params = self.indexed_params(true);
		let data_params = self.indexed_params(false);
		// then take first topic if event is not anonymous
		let to_skip = if self.anonymous {
			0
		} else {
			// verify
			let event_signature = topics.get(0).ok_or(Error::InvalidData)?;
			if event_signature != &self.signature() {
				return Err(Error::InvalidData);
			}
			1
		};

		let topic_types =
			topic_params.iter().map(|p| self.convert_topic_param_type(&p.kind)).collect::<Vec<ParamType>>();

		let flat_topics = topics.into_iter().skip(to_skip).flat_map(|t| t.as_ref().to_vec()).collect::<Vec<u8>>();

		let topic_tokens = decode(&topic_types, &flat_topics)?;

		// topic may be only a 32 bytes encoded token
		if topic_tokens.len() != topics_len - to_skip {
			return Err(Error::InvalidData);
		}

		let topics_named_tokens = topic_params.into_iter().map(|p| p.name).zip(topic_tokens.into_iter());

		let data_types = data_params.iter().map(|p| p.kind.clone()).collect::<Vec<ParamType>>();

		let data_tokens = decode(&data_types, &data)?;

		let data_named_tokens = data_params.into_iter().map(|p| p.name).zip(data_tokens.into_iter());

		let named_tokens = topics_named_tokens.chain(data_named_tokens).collect::<BTreeMap<String, Token>>();

		let decoded_params = self
			.params_names()
			.into_iter()
			.map(|name| LogParam { name: name.clone(), value: named_tokens[&name].clone() })
			.collect();

		let result = Log { params: decoded_params };

		Ok(result)
	}

	/// Parses `RawLog` and retrieves all log params from it.
	/// Checks, that decoded data is exact as input provided
	pub fn parse_log_validate(&self, log: RawLog) -> Result<Log> {
		self.parse_log_inner(log, decode_validate)
	}

	/// Parses `RawLog` and retrieves all log params from it.
	pub fn parse_log(&self, log: RawLog) -> Result<Log> {
		self.parse_log_inner(log, decode)
	}
}

#[cfg(test)]
mod tests {
	use hex_literal::hex;

	#[cfg(not(feature = "std"))]
	use crate::no_std_prelude::*;
	use crate::{
		log::{Log, RawLog},
		signature::long_signature,
		token::Token,
		Event, EventParam, LogParam, ParamType,
	};

	#[test]
	fn test_decoding_event() {
		let event = Event {
			name: "foo".to_owned(),
			inputs: vec![
				EventParam { name: "a".to_owned(), kind: ParamType::Int(256), indexed: false },
				EventParam { name: "b".to_owned(), kind: ParamType::Int(256), indexed: true },
				EventParam { name: "c".to_owned(), kind: ParamType::Address, indexed: false },
				EventParam { name: "d".to_owned(), kind: ParamType::Address, indexed: true },
				EventParam { name: "e".to_owned(), kind: ParamType::String, indexed: true },
				EventParam {
					name: "f".to_owned(),
					kind: ParamType::Array(Box::new(ParamType::Int(256))),
					indexed: true,
				},
				EventParam {
					name: "g".to_owned(),
					kind: ParamType::FixedArray(Box::new(ParamType::Address), 5),
					indexed: true,
				},
			],
			anonymous: false,
		};

		let log = RawLog {
			topics: vec![
				long_signature(
					"foo",
					&[
						ParamType::Int(256),
						ParamType::Int(256),
						ParamType::Address,
						ParamType::Address,
						ParamType::String,
						ParamType::Array(Box::new(ParamType::Int(256))),
						ParamType::FixedArray(Box::new(ParamType::Address), 5),
					],
				),
				hex!("0000000000000000000000000000000000000000000000000000000000000002").into(),
				hex!("0000000000000000000000001111111111111111111111111111111111111111").into(),
				hex!("00000000000000000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").into(),
				hex!("00000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").into(),
				hex!("00000000000000000ccccccccccccccccccccccccccccccccccccccccccccccc").into(),
			],
			data: hex!(
				"
				0000000000000000000000000000000000000000000000000000000000000003
				0000000000000000000000002222222222222222222222222222222222222222
			"
			)
			.into(),
		};
		let result = event.parse_log(log).unwrap();

		assert_eq!(
			result,
			Log {
				params: [
					("a", Token::Int(hex!("0000000000000000000000000000000000000000000000000000000000000003").into()),),
					("b", Token::Int(hex!("0000000000000000000000000000000000000000000000000000000000000002").into()),),
					("c", Token::Address(hex!("2222222222222222222222222222222222222222").into())),
					("d", Token::Address(hex!("1111111111111111111111111111111111111111").into())),
					(
						"e",
						Token::FixedBytes(
							hex!("00000000000000000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").into()
						)
					),
					(
						"f",
						Token::FixedBytes(
							hex!("00000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").into()
						)
					),
					(
						"g",
						Token::FixedBytes(
							hex!("00000000000000000ccccccccccccccccccccccccccccccccccccccccccccccc").into()
						)
					),
				]
				.iter()
				.cloned()
				.map(|(name, value)| LogParam { name: name.to_string(), value })
				.collect::<Vec<_>>()
			}
		);
	}

	#[test]
	fn parse_log_whole() {
		let correct_event = Event {
			name: "Test".into(),
			inputs: vec![
				EventParam {
					name: "tuple".into(),
					kind: ParamType::Tuple(vec![ParamType::Address, ParamType::Address]),
					indexed: false,
				},
				EventParam { name: "addr".into(), kind: ParamType::Address, indexed: true },
			],
			anonymous: false,
		};
		// swap indexed params
		let mut wrong_event = correct_event.clone();
		wrong_event.inputs[0].indexed = true;
		wrong_event.inputs[1].indexed = false;

		let log = RawLog {
			topics: vec![
				hex!("cf74b4e62f836eeedcd6f92120ffb5afea90e6fa490d36f8b81075e2a7de0cf7").into(),
				hex!("0000000000000000000000000000000000000000000000000000000000012321").into(),
			],
			data: hex!(
				"
			0000000000000000000000000000000000000000000000000000000000012345
			0000000000000000000000000000000000000000000000000000000000054321
			"
			)
			.into(),
		};

		assert!(wrong_event.parse_log(log.clone()).is_ok());
		assert!(wrong_event.parse_log_validate(log.clone()).is_err());
		assert!(correct_event.parse_log_validate(log).is_ok());
	}
}