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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2019-2022 Moonsong Labs.
// Copyright (c) 2023 Parity Technologies (UK) Ltd.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Utility module to interact with solidity file.

use sp_io::hashing::keccak_256;
use std::{
	collections::HashMap,
	fs::File,
	io::{BufRead, BufReader, Read},
};

pub fn check_precompile_implements_solidity_interfaces<F>(
	files: &[&'static str],
	supports_selector: F,
) where
	F: Fn(u32) -> bool,
{
	for file in files {
		for solidity_fn in get_selectors(file) {
			assert_eq!(
				solidity_fn.compute_selector_hex(),
				solidity_fn.docs_selector,
				"documented selector for '{}' did not match in file '{}'",
				solidity_fn.signature(),
				file,
			);

			let selector = solidity_fn.compute_selector();
			if !supports_selector(selector) {
				panic!(
					"precompile don't support selector {selector:x} for function '{}' listed in file\
					{file}",
					solidity_fn.signature(),
				)
			}
		}
	}
}

/// Represents a declared custom type struct within a solidity file
#[derive(Clone, Default, Debug)]
pub struct SolidityStruct {
	/// Struct name
	pub name: String,
	/// List of parameter types
	pub params: Vec<String>,
	/// Is struct an enum
	pub is_enum: bool,
}

impl SolidityStruct {
	/// Returns the representative signature for the solidity struct
	pub fn signature(&self) -> String {
		if self.is_enum {
			"uint8".to_string()
		} else {
			format!("({})", self.params.join(","))
		}
	}
}

/// Represents a declared function within a solidity file
#[derive(Clone, Default)]
pub struct SolidityFunction {
	/// Function name
	pub name: String,
	/// List of function parameter types
	pub args: Vec<String>,
	/// The declared selector in the file
	pub docs_selector: String,
}

impl SolidityFunction {
	/// Returns the representative signature for the solidity function
	pub fn signature(&self) -> String {
		format!("{}({})", self.name, self.args.join(","))
	}

	/// Computes the selector code for the solidity function
	pub fn compute_selector(&self) -> u32 {
		compute_selector(&self.signature())
	}

	/// Computes the selector code as a hex string for the solidity function
	pub fn compute_selector_hex(&self) -> String {
		format!("{:0>8x}", self.compute_selector())
	}
}

/// Computes a solidity selector from a given string
pub fn compute_selector(v: &str) -> u32 {
	let output = keccak_256(v.as_bytes());
	let mut buf = [0u8; 4];
	buf.clone_from_slice(&output[..4]);
	u32::from_be_bytes(buf)
}

/// Returns a list of [SolidityFunction] defined in a solidity file
pub fn get_selectors(filename: &str) -> Vec<SolidityFunction> {
	let file = File::open(filename)
		.unwrap_or_else(|e| panic!("failed opening file '{}': {}", filename, e));
	get_selectors_from_reader(file)
}

/// Attempts to lookup a custom struct and returns its primitive signature
fn try_lookup_custom_type(word: &str, custom_types: &HashMap<String, SolidityStruct>) -> String {
	match word.strip_suffix("[]") {
		Some(word) => {
			if let Some(t) = custom_types.get(word) {
				return format!("{}[]", t.signature());
			}
		}
		None => {
			if let Some(t) = custom_types.get(word) {
				return t.signature();
			}
		}
	};

	word.to_string()
}

fn get_selectors_from_reader<R: Read>(reader: R) -> Vec<SolidityFunction> {
	#[derive(Clone, Copy)]
	enum Stage {
		Start,
		Enum,
		Struct,
		StructParams,
		FnName,
		Args,
	}
	#[derive(Clone, Copy)]
	enum Pair {
		First,
		Second,
	}
	impl Pair {
		fn next(&mut self) {
			*self = match self {
				Pair::First => Pair::Second,
				Pair::Second => Pair::First,
			}
		}
	}

	let reader = BufReader::new(reader);
	let mut functions = vec![];
	let mut custom_types = HashMap::new();
	let mut solidity_struct = SolidityStruct::default();

	let mut stage = Stage::Start;
	let mut pair = Pair::First;
	let mut solidity_fn = SolidityFunction::default();
	for line in reader.lines() {
		let line = line.expect("failed unwrapping line").trim().to_string();
		// identify declared selector
		if line.starts_with("/// @custom:selector ") && matches!(stage, Stage::Start) {
			solidity_fn.docs_selector = line.replace("/// @custom:selector ", "").to_string();
		}

		// skip comments
		if line.starts_with("//") {
			continue;
		}

		for word in line.split(&[';', ',', '(', ')', ' ']) {
			// skip whitespace
			if word.trim().is_empty() {
				continue;
			}
			match (stage, pair, word) {
				// parse custom type enums
				(Stage::Start, Pair::First, "enum") => {
					stage = Stage::Enum;
					pair.next();
				}
				(Stage::Enum, Pair::Second, _) => {
					custom_types.insert(
						word.to_string(),
						SolidityStruct {
							name: word.to_string(),
							is_enum: true,
							params: vec![],
						},
					);
					stage = Stage::Start;
					pair = Pair::First;
				}

				// parse custom type structs
				(Stage::Start, Pair::First, "struct") => {
					stage = Stage::Struct;
					pair.next();
				}
				(Stage::Struct, Pair::Second, _) => {
					solidity_struct.name = word.to_string();
					stage = Stage::StructParams;
					pair.next();
				}
				(Stage::StructParams, Pair::First, "{") => (),
				(Stage::StructParams, Pair::First, "}") => {
					custom_types.insert(solidity_struct.name.clone(), solidity_struct);
					stage = Stage::Start;
					solidity_struct = SolidityStruct::default();
				}
				(Stage::StructParams, Pair::First, _) => {
					let param = try_lookup_custom_type(word, &custom_types);
					solidity_struct.params.push(param);
					pair.next();
				}
				(Stage::StructParams, Pair::Second, _) => {
					pair.next();
				}

				// parse function
				(Stage::Start, Pair::First, "function") => {
					stage = Stage::FnName;
					pair.next();
				}
				(Stage::FnName, Pair::Second, _) => {
					solidity_fn.name = word.to_string();
					stage = Stage::Args;
					pair.next();
				}
				(Stage::Args, Pair::First, "external") => {
					functions.push(solidity_fn);
					stage = Stage::Start;
					pair = Pair::First;
					solidity_fn = SolidityFunction::default()
				}
				(Stage::Args, Pair::First, _) => {
					let mut arg = word.to_string();
					arg = try_lookup_custom_type(&arg, &custom_types);

					solidity_fn.args.push(arg);
					pair.next();
				}
				(Stage::Args, Pair::Second, "memory" | "calldata" | "storage") => (),
				(Stage::Args, Pair::Second, _) => pair.next(),
				_ => {
					stage = Stage::Start;
					pair = Pair::First;
					solidity_fn = SolidityFunction::default()
				}
			}
		}
	}

	functions
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_selectors_are_parsed() {
		let actual = get_selectors("tests/solidity_test.sol")
			.into_iter()
			.map(|sol_fn| {
				(
					sol_fn.compute_selector_hex(),
					sol_fn.docs_selector.clone(),
					sol_fn.signature(),
				)
			})
			.collect::<Vec<_>>();
		let expected = vec![
			(
				String::from("f7af8d91"),
				String::from(""),
				String::from("fnNoArgs()"),
			),
			(
				String::from("d43a9a43"),
				String::from("c4921133"),
				String::from("fnOneArg(address)"),
			),
			(
				String::from("40d6a43d"),
				String::from("67ea837e"),
				String::from("fnTwoArgs(address,uint256)"),
			),
			(
				String::from("cee150c8"),
				String::from("d6b423d9"),
				String::from("fnSameArgs(uint64,uint64)"),
			),
			(
				String::from("c6024207"),
				String::from("b9904a86"),
				String::from("fnOneArgSameLine(uint64)"),
			),
			(
				String::from("fcbc04c3"),
				String::from("28f0c44e"),
				String::from("fnTwoArgsSameLine(uint64,bytes32)"),
			),
			(
				String::from("c590304c"),
				String::from("06f0c1ce"),
				String::from("fnTwoArgsSameLineExternalSplit(uint64,bytes32)"),
			),
			(
				String::from("a19a07e1"),
				String::from("18001a4e"),
				String::from("fnMemoryArrayArgs(address[],uint256[],bytes[])"),
			),
			(
				String::from("ec26cf1c"),
				String::from("1ea61a4e"),
				String::from("fnCalldataArgs(string,bytes[])"),
			),
			(
				String::from("f29f96de"),
				String::from("d8af1a4e"),
				String::from("fnCustomArgs((uint8,bytes[]),bytes[],uint64)"),
			),
			(
				String::from("d751d651"),
				String::from("e8af1642"),
				String::from("fnEnumArgs(uint8,uint64)"),
			),
			(
				String::from("b2c9f1a3"),
				String::from("550c1a4e"),
				String::from(
					"fnCustomArgsMultiple((uint8,bytes[]),(address[],uint256[],bytes[]),bytes[],\
					uint64)",
				),
			),
			(
				String::from("d5363eee"),
				String::from("77af1a40"),
				String::from("fnCustomArrayArgs((uint8,bytes[])[],bytes[])"),
			),
			(
				String::from("b82da727"),
				String::from("80af0a40"),
				String::from(
					"fnCustomComposedArg(((uint8,bytes[]),\
				(address[],uint256[],bytes[])[]),uint64)",
				),
			),
			(
				String::from("586a2193"),
				String::from("97baa040"),
				String::from(
					"fnCustomComposedArrayArg(((uint8,bytes[]),\
				(address[],uint256[],bytes[])[])[],uint64)",
				),
			),
		];

		assert_eq!(expected, actual);
	}
}