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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// This file is part of Frontier.

// Copyright (c) Moonsong Labs.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg(test)]

// #[precompile_utils::precompile] need this
extern crate alloc;

use std::{cell::RefCell, rc::Rc};

// Substrate
use frame_support::{
	construct_runtime, derive_impl, parameter_types, traits::Everything, weights::Weight,
};
use sp_core::{H160, H256, U256};
use sp_runtime::{
	traits::{BlakeTwo256, IdentityLookup},
	BuildStorage, Perbill,
};
// Frontier
use fp_evm::{ExitReason, ExitRevert, PrecompileFailure, PrecompileHandle};
use pallet_evm::{CodeMetadata, EnsureAddressNever, EnsureAddressRoot};
use precompile_utils::{
	precompile_set::*,
	solidity::{codec::Writer, revert::revert},
	testing::*,
	EvmResult,
};

pub type AccountId = MockAccount;
pub type Balance = u128;

construct_runtime!(
	pub enum Runtime {
		System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
		Balances: pallet_balances::{Pallet, Call, Storage, Event<T>},
		Evm: pallet_evm::{Pallet, Call, Storage, Event<T>},
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
	}
);

parameter_types! {
	pub const BlockHashCount: u32 = 250;
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
	pub const MaximumBlockLength: u32 = 2 * 1024;
	pub const AvailableBlockRatio: Perbill = Perbill::one();
	pub const SS58Prefix: u8 = 42;
}

#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type BaseCallFilter = Everything;
	type BlockWeights = ();
	type BlockLength = ();
	type RuntimeOrigin = RuntimeOrigin;
	type RuntimeCall = RuntimeCall;
	type RuntimeTask = RuntimeTask;
	type Nonce = u64;
	type Hash = H256;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
	type Lookup = IdentityLookup<Self::AccountId>;
	type Block = frame_system::mocking::MockBlock<Self>;
	type BlockHashCount = BlockHashCount;
	type DbWeight = ();
	type Version = ();
	type PalletInfo = PalletInfo;
	type AccountData = pallet_balances::AccountData<Balance>;
	type OnNewAccount = ();
	type OnKilledAccount = ();
	type SystemWeightInfo = ();
	type SS58Prefix = SS58Prefix;
	type OnSetCode = ();
	type MaxConsumers = frame_support::traits::ConstU32<16>;
}

parameter_types! {
	pub const ExistentialDeposit: u128 = 0;
}
impl pallet_balances::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type RuntimeHoldReason = RuntimeHoldReason;
	type RuntimeFreezeReason = RuntimeFreezeReason;
	type WeightInfo = ();
	type Balance = Balance;
	type DustRemoval = ();
	type ExistentialDeposit = ExistentialDeposit;
	type AccountStore = System;
	type ReserveIdentifier = [u8; 8];
	type FreezeIdentifier = RuntimeFreezeReason;
	type MaxLocks = ();
	type MaxReserves = ();
	type MaxFreezes = ();
	type DoneSlashHandler = ();
}

#[derive(Debug, Clone)]
pub struct MockPrecompile;

#[precompile_utils::precompile]
impl MockPrecompile {
	// a3cab0dd
	#[precompile::public("subcall()")]
	fn subcall(handle: &mut impl PrecompileHandle) -> EvmResult {
		match handle.call(
			handle.code_address(),
			None,
			// calls subcallLayer2()
			Writer::new_with_selector(0x0b93381bu32).build(),
			None,
			false,
			&evm::Context {
				caller: handle.code_address(),
				address: handle.code_address(),
				apparent_value: 0.into(),
			},
		) {
			(ExitReason::Succeed(_), _) => Ok(()),
			(ExitReason::Revert(_), v) => Err(PrecompileFailure::Revert {
				exit_status: ExitRevert::Reverted,
				output: v,
			}),
			_ => Err(revert("unexpected error")),
		}
	}

	// 0b93381b
	#[precompile::public("success()")]
	fn success(_: &mut impl PrecompileHandle) -> EvmResult {
		Ok(())
	}
}

#[derive(Default)]
struct MockPrecompileHandle {
	contracts_being_constructed: Vec<H160>,
}
impl MockPrecompileHandle {
	fn with_contracts_being_constructed(mut self, contracts_being_constructed: Vec<H160>) -> Self {
		self.contracts_being_constructed = contracts_being_constructed;
		self
	}
}
impl PrecompileHandle for MockPrecompileHandle {
	fn call(
		&mut self,
		_: H160,
		_: Option<evm::Transfer>,
		_: Vec<u8>,
		_: Option<u64>,
		_: bool,
		_: &evm::Context,
	) -> (ExitReason, Vec<u8>) {
		unimplemented!()
	}

	fn record_cost(&mut self, _: u64) -> Result<(), evm::ExitError> {
		Ok(())
	}

	fn record_external_cost(
		&mut self,
		_ref_time: Option<u64>,
		_proof_size: Option<u64>,
		_storage_growth: Option<u64>,
	) -> Result<(), fp_evm::ExitError> {
		Ok(())
	}

	fn refund_external_cost(&mut self, _ref_time: Option<u64>, _proof_size: Option<u64>) {}

	fn remaining_gas(&self) -> u64 {
		0
	}

	fn log(&mut self, _: H160, _: Vec<H256>, _: Vec<u8>) -> Result<(), evm::ExitError> {
		unimplemented!()
	}

	fn code_address(&self) -> H160 {
		unimplemented!()
	}

	fn input(&self) -> &[u8] {
		unimplemented!()
	}

	fn context(&self) -> &evm::Context {
		unimplemented!()
	}

	fn origin(&self) -> H160 {
		Alice.into()
	}

	fn is_static(&self) -> bool {
		true
	}

	fn gas_limit(&self) -> Option<u64> {
		unimplemented!()
	}

	fn is_contract_being_constructed(&self, address: H160) -> bool {
		self.contracts_being_constructed.contains(&address)
	}
}

pub type Precompiles<R> = PrecompileSetBuilder<
	R,
	(
		PrecompileAt<AddressU64<1>, MockPrecompile>,
		PrecompileAt<AddressU64<2>, MockPrecompile, CallableByContract>,
		PrecompileAt<AddressU64<3>, MockPrecompile, CallableByPrecompile>,
		PrecompileAt<AddressU64<4>, MockPrecompile, SubcallWithMaxNesting<1>>,
	),
>;

pub type PCall = MockPrecompileCall;

const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;

parameter_types! {
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
	pub GasLimitPovSizeRatio: u64 = {
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
		block_gas_limit.saturating_div(MAX_POV_SIZE)
	};
}

impl pallet_evm::Config for Runtime {
	type AccountProvider = pallet_evm::FrameSystemAccountProvider<Self>;
	type FeeCalculator = ();
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
	type WeightPerGas = WeightPerGas;
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
	type CallOrigin = EnsureAddressRoot<AccountId>;
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
	type AddressMapping = AccountId;
	type Currency = Balances;
	type RuntimeEvent = RuntimeEvent;
	type PrecompilesType = Precompiles<Runtime>;
	type PrecompilesValue = PrecompilesValue;
	type ChainId = ();
	type BlockGasLimit = BlockGasLimit;
	type Runner = pallet_evm::runner::stack::Runner<Self>;
	type OnChargeTransaction = ();
	type OnCreate = ();
	type FindAuthor = ();
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
	type GasLimitStorageGrowthRatio = ();
	type Timestamp = Timestamp;
	type CreateInnerOriginFilter = ();
	type CreateOriginFilter = ();
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
}

parameter_types! {
	pub const MinimumPeriod: u64 = 5;
}
impl pallet_timestamp::Config for Runtime {
	type Moment = u64;
	type OnTimestampSet = ();
	type MinimumPeriod = MinimumPeriod;
	type WeightInfo = ();
}

#[derive(Default)]
struct ExtBuilder {}

impl ExtBuilder {
	fn build(self) -> sp_io::TestExternalities {
		let t = frame_system::GenesisConfig::<Runtime>::default()
			.build_storage()
			.expect("Frame system builds valid default genesis config");

		let mut ext = sp_io::TestExternalities::new(t);
		ext.execute_with(|| {
			System::set_block_number(1);
		});
		ext
	}
}

fn precompiles() -> Precompiles<Runtime> {
	PrecompilesValue::get()
}

#[test]
fn default_checks_succeed_when_called_by_eoa() {
	ExtBuilder::default().build().execute_with(|| {
		precompiles()
			.prepare_test(Alice, H160::from_low_u64_be(1), PCall::success {})
			.with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall"))
			.execute_returns(())
	})
}

#[test]
fn default_checks_revert_when_called_by_precompile() {
	ExtBuilder::default().build().execute_with(|| {
		precompiles()
			.prepare_test(
				H160::from_low_u64_be(1),
				H160::from_low_u64_be(1),
				PCall::success {},
			)
			.with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall"))
			.execute_reverts(|r| r == b"Function not callable by precompiles")
	})
}

#[test]
fn default_checks_revert_when_called_by_contract() {
	ExtBuilder::default().build().execute_with(|| {
		let _ = pallet_evm::Pallet::<Runtime>::create_account(
			Alice.into(),
			hex_literal::hex!("1460006000fd").to_vec(),
			None,
		);

		precompiles()
			.prepare_test(Alice, H160::from_low_u64_be(1), PCall::success {})
			.with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall"))
			.execute_reverts(|r| r == b"Function not callable by smart contracts")
	})
}

#[test]
fn default_checks_revert_when_doing_subcall() {
	ExtBuilder::default().build().execute_with(|| {
		precompiles()
			.prepare_test(Alice, H160::from_low_u64_be(1), PCall::subcall {})
			.with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall"))
			.execute_reverts(|r| r == b"subcalls disabled for this precompile")
	})
}

#[test]
fn callable_by_contract_works() {
	ExtBuilder::default().build().execute_with(|| {
		let _ = pallet_evm::Pallet::<Runtime>::create_account(
			Alice.into(),
			hex_literal::hex!("1460006000fd").to_vec(),
			None,
		);

		precompiles()
			.prepare_test(Alice, H160::from_low_u64_be(2), PCall::success {})
			.with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall"))
			.execute_returns(())
	})
}

#[test]
fn callable_by_precompile_works() {
	ExtBuilder::default().build().execute_with(|| {
		precompiles()
			.prepare_test(
				H160::from_low_u64_be(3),
				H160::from_low_u64_be(3),
				PCall::success {},
			)
			.with_subcall_handle(|Subcall { .. }| panic!("there should be no subcall"))
			.execute_returns(())
	})
}

#[test]
fn subcalls_works_when_allowed() {
	ExtBuilder::default().build().execute_with(|| {
		let subcall_occured = Rc::new(RefCell::new(false));
		{
			let subcall_occured = Rc::clone(&subcall_occured);
			precompiles()
				.prepare_test(Alice, H160::from_low_u64_be(4), PCall::subcall {})
				.with_subcall_handle(move |Subcall { .. }| {
					*subcall_occured.borrow_mut() = true;
					SubcallOutput::succeed()
				})
				.execute_returns(());
		}
		assert!(*subcall_occured.borrow());
	})
}

#[test]
fn get_address_type_works_for_eoa() {
	ExtBuilder::default().build().execute_with(|| {
		let externally_owned_account: H160 = Alice.into();
		let mut handle = MockPrecompileHandle::default();

		assert_eq!(
			AddressType::EOA,
			get_address_type::<Runtime>(&mut handle, externally_owned_account).expect("OOG")
		);
	})
}

#[test]
fn get_address_type_works_for_precompile() {
	ExtBuilder::default().build().execute_with(|| {
		let precompiles: Vec<H160> = Precompiles::<Runtime>::used_addresses_h160().collect();
		// We expect 4 precompiles
		assert_eq!(precompiles.len(), 4);

		let mut handle = MockPrecompileHandle::default();
		precompiles.iter().cloned().for_each(|precompile| {
			assert_eq!(
				AddressType::Precompile,
				get_address_type::<Runtime>(&mut handle, precompile).expect("OOG")
			);
		});
	})
}

#[test]
fn get_address_type_works_for_smart_contract() {
	ExtBuilder::default().build().execute_with(|| {
		let address = H160::repeat_byte(0x1d);
		pallet_evm::AccountCodesMetadata::<Runtime>::insert(
			address,
			CodeMetadata {
				hash: Default::default(),
				size: 1,
			},
		);

		let mut handle = MockPrecompileHandle::default();
		assert_eq!(
			AddressType::Contract,
			get_address_type::<Runtime>(&mut handle, address).expect("OOG")
		);
	})
}

#[test]
fn get_address_type_works_for_smart_contract_being_constructed() {
	ExtBuilder::default().build().execute_with(|| {
		let contract_being_constucted = H160::repeat_byte(0x1d);
		let mut handle = MockPrecompileHandle::default()
			.with_contracts_being_constructed(vec![contract_being_constucted]);

		assert_eq!(
			AddressType::Contract,
			get_address_type::<Runtime>(&mut handle, contract_being_constucted).expect("OOG")
		);
	})
}