1
// Copyright 2019-2022 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU 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
// Moonbeam 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 General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Test utilities
18
use crate::{ProxyPrecompile, ProxyPrecompileCall};
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{Everything, InstanceFilter},
22
	weights::Weight,
23
};
24
use pallet_evm::{EnsureAddressNever, EnsureAddressOrigin, SubstrateBlockHashMapping};
25
use precompile_utils::{
26
	precompile_set::{
27
		AddressU64, CallableByContract, CallableByPrecompile, OnlyFrom, PrecompileAt,
28
		PrecompileSetBuilder, RevertPrecompile, SubcallWithMaxNesting,
29
	},
30
	testing::MockAccount,
31
};
32
use scale_info::TypeInfo;
33
use sp_core::{ConstU32, H160, H256, U256};
34
use sp_io;
35
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
36
use sp_runtime::{
37
	codec::{Decode, Encode, MaxEncodedLen},
38
	BuildStorage,
39
};
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43

            
44
type Block = frame_system::mocking::MockBlockU32<Runtime>;
45

            
46
966
construct_runtime!(
47
	pub enum Runtime	{
48
		System: frame_system,
49
		Balances: pallet_balances,
50
		Evm: pallet_evm,
51
		Timestamp: pallet_timestamp,
52
		Proxy: pallet_proxy,
53
	}
54
1306
);
55

            
56
parameter_types! {
57
	pub const BlockHashCount: u32 = 250;
58
	pub const SS58Prefix: u8 = 42;
59
}
60
impl frame_system::Config for Runtime {
61
	type BaseCallFilter = Everything;
62
	type DbWeight = ();
63
	type RuntimeOrigin = RuntimeOrigin;
64
	type RuntimeTask = RuntimeTask;
65
	type Nonce = u64;
66
	type Block = Block;
67
	type RuntimeCall = RuntimeCall;
68
	type Hash = H256;
69
	type Hashing = BlakeTwo256;
70
	type AccountId = AccountId;
71
	type Lookup = IdentityLookup<Self::AccountId>;
72
	type RuntimeEvent = RuntimeEvent;
73
	type BlockHashCount = BlockHashCount;
74
	type Version = ();
75
	type PalletInfo = PalletInfo;
76
	type AccountData = pallet_balances::AccountData<Balance>;
77
	type OnNewAccount = ();
78
	type OnKilledAccount = ();
79
	type SystemWeightInfo = ();
80
	type BlockWeights = ();
81
	type BlockLength = ();
82
	type SS58Prefix = SS58Prefix;
83
	type OnSetCode = ();
84
	type MaxConsumers = frame_support::traits::ConstU32<16>;
85
	type SingleBlockMigrations = ();
86
	type MultiBlockMigrator = ();
87
	type PreInherents = ();
88
	type PostInherents = ();
89
	type PostTransactions = ();
90
}
91
parameter_types! {
92
	pub const ExistentialDeposit: u128 = 0;
93
}
94
impl pallet_balances::Config for Runtime {
95
	type MaxReserves = ();
96
	type ReserveIdentifier = ();
97
	type MaxLocks = ();
98
	type Balance = Balance;
99
	type RuntimeEvent = RuntimeEvent;
100
	type DustRemoval = ();
101
	type ExistentialDeposit = ExistentialDeposit;
102
	type AccountStore = System;
103
	type WeightInfo = ();
104
	type RuntimeHoldReason = ();
105
	type FreezeIdentifier = ();
106
	type MaxFreezes = ();
107
	type RuntimeFreezeReason = ();
108
}
109

            
110
pub type Precompiles<R> = PrecompileSetBuilder<
111
	R,
112
	(
113
		PrecompileAt<
114
			AddressU64<1>,
115
			ProxyPrecompile<R>,
116
			(
117
				SubcallWithMaxNesting<1>,
118
				CallableByContract<crate::OnlyIsProxyAndProxy<R>>,
119
				// Batch is the only precompile allowed to call Proxy.
120
				CallableByPrecompile<OnlyFrom<AddressU64<2>>>,
121
			),
122
		>,
123
		RevertPrecompile<AddressU64<2>>,
124
	),
125
>;
126

            
127
pub type PCall = ProxyPrecompileCall<Runtime>;
128

            
129
pub struct EnsureAddressAlways;
130
impl<OuterOrigin> EnsureAddressOrigin<OuterOrigin> for EnsureAddressAlways {
131
	type Success = ();
132

            
133
	fn try_address_origin(
134
		_address: &H160,
135
		_origin: OuterOrigin,
136
	) -> Result<Self::Success, OuterOrigin> {
137
		Ok(())
138
	}
139

            
140
1
	fn ensure_address_origin(
141
1
		_address: &H160,
142
1
		_origin: OuterOrigin,
143
1
	) -> Result<Self::Success, sp_runtime::traits::BadOrigin> {
144
1
		Ok(())
145
1
	}
146
}
147

            
148
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
149
/// Block storage limit in bytes. Set to 40 KB.
150
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
151

            
152
parameter_types! {
153
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
154
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
155
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
156
	pub GasLimitPovSizeRatio: u64 = {
157
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
158
		block_gas_limit.saturating_div(MAX_POV_SIZE)
159
	};
160
	pub GasLimitStorageGrowthRatio: u64 = {
161
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
162
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
163
	};
164
}
165
impl pallet_evm::Config for Runtime {
166
	type FeeCalculator = ();
167
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
168
	type WeightPerGas = WeightPerGas;
169
	type CallOrigin = EnsureAddressAlways;
170
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
171
	type AddressMapping = AccountId;
172
	type Currency = Balances;
173
	type RuntimeEvent = RuntimeEvent;
174
	type Runner = pallet_evm::runner::stack::Runner<Self>;
175
	type PrecompilesType = Precompiles<Self>;
176
	type PrecompilesValue = PrecompilesValue;
177
	type ChainId = ();
178
	type OnChargeTransaction = ();
179
	type BlockGasLimit = BlockGasLimit;
180
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
181
	type FindAuthor = ();
182
	type OnCreate = ();
183
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
184
	type SuicideQuickClearLimit = ConstU32<0>;
185
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
186
	type Timestamp = Timestamp;
187
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
188
}
189

            
190
parameter_types! {
191
	pub const MinimumPeriod: u64 = 5;
192
}
193
impl pallet_timestamp::Config for Runtime {
194
	type Moment = u64;
195
	type OnTimestampSet = ();
196
	type MinimumPeriod = MinimumPeriod;
197
	type WeightInfo = ();
198
}
199

            
200
#[repr(u8)]
201
#[derive(
202
3
	Debug, Eq, PartialEq, Ord, PartialOrd, Decode, MaxEncodedLen, Encode, Clone, Copy, TypeInfo,
203
)]
204
pub enum ProxyType {
205
6
	Any = 0,
206
24
	Something = 1,
207
3
	Nothing = 2,
208
}
209

            
210
impl std::default::Default for ProxyType {
211
	fn default() -> Self {
212
		ProxyType::Any
213
	}
214
}
215

            
216
impl crate::EvmProxyCallFilter for ProxyType {
217
2
	fn is_evm_proxy_call_allowed(
218
2
		&self,
219
2
		_call: &crate::EvmSubCall,
220
2
		_recipient_has_code: bool,
221
2
		_gas: u64,
222
2
	) -> precompile_utils::EvmResult<bool> {
223
2
		Ok(match self {
224
1
			Self::Any => true,
225
			Self::Something => true,
226
1
			Self::Nothing => false,
227
		})
228
2
	}
229
}
230

            
231
impl InstanceFilter<RuntimeCall> for ProxyType {
232
1
	fn filter(&self, _: &RuntimeCall) -> bool {
233
1
		true
234
1
	}
235

            
236
	fn is_superset(&self, o: &Self) -> bool {
237
		(*self as u8) > (*o as u8)
238
	}
239
}
240

            
241
parameter_types! {
242
	pub const ProxyDepositBase: u64 = 100;
243
	pub const ProxyDepositFactor: u64 = 1;
244
	pub const MaxProxies: u32 = 5;
245
	pub const MaxPending: u32 = 5;
246
}
247
impl pallet_proxy::Config for Runtime {
248
	type RuntimeEvent = RuntimeEvent;
249
	type RuntimeCall = RuntimeCall;
250
	type Currency = Balances;
251
	type ProxyType = ProxyType;
252
	type ProxyDepositBase = ProxyDepositBase;
253
	type ProxyDepositFactor = ProxyDepositFactor;
254
	type MaxProxies = MaxProxies;
255
	type WeightInfo = ();
256
	type MaxPending = MaxPending;
257
	type CallHasher = BlakeTwo256;
258
	type AnnouncementDepositBase = ();
259
	type AnnouncementDepositFactor = ();
260
}
261

            
262
/// Build test externalities, prepopulated with data for testing democracy precompiles
263
pub(crate) struct ExtBuilder {
264
	/// Endowed accounts with balances
265
	balances: Vec<(AccountId, Balance)>,
266
}
267

            
268
impl Default for ExtBuilder {
269
28
	fn default() -> ExtBuilder {
270
28
		ExtBuilder { balances: vec![] }
271
28
	}
272
}
273

            
274
impl ExtBuilder {
275
	/// Fund some accounts before starting the test
276
25
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
277
25
		self.balances = balances;
278
25
		self
279
25
	}
280

            
281
	/// Build the test externalities for use in tests
282
28
	pub(crate) fn build(self) -> sp_io::TestExternalities {
283
28
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
284
28
			.build_storage()
285
28
			.expect("Frame system builds valid default genesis config");
286
28

            
287
28
		pallet_balances::GenesisConfig::<Runtime> {
288
28
			balances: self.balances.clone(),
289
28
		}
290
28
		.assimilate_storage(&mut t)
291
28
		.expect("Pallet balances storage can be assimilated");
292
28

            
293
28
		let mut ext = sp_io::TestExternalities::new(t);
294
28
		ext.execute_with(|| {
295
28
			System::set_block_number(1);
296
28
		});
297
28
		ext
298
28
	}
299
}
300

            
301
3
pub(crate) fn events() -> Vec<RuntimeEvent> {
302
3
	System::events()
303
3
		.into_iter()
304
10
		.map(|r| r.event)
305
3
		.collect::<Vec<_>>()
306
3
}
307

            
308
/// Panics if an event is not found in the system log of events
309
#[macro_export]
310
macro_rules! assert_event_emitted {
311
	($event:expr) => {
312
		match &$event {
313
			e => {
314
				assert!(
315
					crate::mock::events().iter().find(|x| *x == e).is_some(),
316
					"Event {:?} was not found in events: \n {:#?}",
317
					e,
318
					crate::mock::events()
319
				);
320
			}
321
		}
322
	};
323
}
324

            
325
// Panics if an event is found in the system log of events
326
#[macro_export]
327
macro_rules! assert_event_not_emitted {
328
	($event:expr) => {
329
		match &$event {
330
			e => {
331
				assert!(
332
					crate::mock::events().iter().find(|x| *x == e).is_none(),
333
					"Event {:?} was found in events: \n {:?}",
334
					e,
335
					crate::mock::events()
336
				);
337
			}
338
		}
339
	};
340
}