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 super::*;
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{EitherOfDiverse, Everything, SortedMembers},
22
	weights::Weight,
23
};
24
use frame_system::{EnsureRoot, EnsureSignedBy};
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot};
26
use pallet_identity::legacy::IdentityInfo;
27
use precompile_utils::mock_account;
28
use precompile_utils::{
29
	precompile_set::*,
30
	testing::{MockAccount, MockSignature},
31
};
32
use sp_core::{H256, U256};
33
use sp_runtime::{
34
	traits::{BlakeTwo256, IdentityLookup},
35
	BuildStorage, Perbill,
36
};
37

            
38
pub type AccountId = MockAccount;
39
pub type Balance = u128;
40

            
41
type Block = frame_system::mocking::MockBlockU32<Runtime>;
42

            
43
2601
construct_runtime!(
44
	pub enum Runtime	{
45
		System: frame_system,
46
		Balances: pallet_balances,
47
		Evm: pallet_evm,
48
		Timestamp: pallet_timestamp,
49
		Identity: pallet_identity,
50
	}
51
4029
);
52

            
53
parameter_types! {
54
	pub const BlockHashCount: u32 = 250;
55
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
56
	pub const MaximumBlockLength: u32 = 2 * 1024;
57
	pub const AvailableBlockRatio: Perbill = Perbill::one();
58
	pub const SS58Prefix: u8 = 42;
59
}
60

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

            
111
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
112
/// Block storage limit in bytes. Set to 40 KB.
113
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
114

            
115
parameter_types! {
116
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
117
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
118
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
119
	pub GasLimitPovSizeRatio: u64 = {
120
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
121
		block_gas_limit.saturating_div(MAX_POV_SIZE)
122
	};
123
	pub GasLimitStorageGrowthRatio: u64 = {
124
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
125
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
126
	};
127
}
128

            
129
pub type Precompiles<R> = PrecompileSetBuilder<
130
	R,
131
	(PrecompileAt<AddressU64<1>, IdentityPrecompile<R, MaxAdditionalFields>>,),
132
>;
133

            
134
pub type PCall = IdentityPrecompileCall<Runtime, MaxAdditionalFields>;
135

            
136
impl pallet_evm::Config for Runtime {
137
	type FeeCalculator = ();
138
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
139
	type WeightPerGas = WeightPerGas;
140
	type CallOrigin = EnsureAddressRoot<AccountId>;
141
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
142
	type AddressMapping = AccountId;
143
	type Currency = Balances;
144
	type RuntimeEvent = RuntimeEvent;
145
	type Runner = pallet_evm::runner::stack::Runner<Self>;
146
	type PrecompilesType = Precompiles<Runtime>;
147
	type PrecompilesValue = PrecompilesValue;
148
	type ChainId = ();
149
	type OnChargeTransaction = ();
150
	type BlockGasLimit = BlockGasLimit;
151
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
152
	type FindAuthor = ();
153
	type OnCreate = ();
154
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
155
	type SuicideQuickClearLimit = ConstU32<0>;
156
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
157
	type Timestamp = Timestamp;
158
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
159
}
160

            
161
parameter_types! {
162
	pub const MinimumPeriod: u64 = 5;
163
}
164
impl pallet_timestamp::Config for Runtime {
165
	type Moment = u64;
166
	type OnTimestampSet = ();
167
	type MinimumPeriod = MinimumPeriod;
168
	type WeightInfo = ();
169
}
170

            
171
22
mock_account!(RegistrarAndForceOrigin, |_| H160::repeat_byte(0x1C).into());
172
impl SortedMembers<MockAccount> for RegistrarAndForceOrigin {
173
11
	fn sorted_members() -> Vec<MockAccount> {
174
11
		vec![RegistrarAndForceOrigin.into()]
175
11
	}
176
	#[cfg(feature = "runtime-benchmarks")]
177
	fn add(_m: &MockAccount) {}
178
}
179

            
180
type EnsureRegistrarAndForceOriginOrRoot =
181
	EitherOfDiverse<EnsureRoot<AccountId>, EnsureSignedBy<RegistrarAndForceOrigin, AccountId>>;
182

            
183
parameter_types! {
184
	pub const BasicDeposit: u64 = 10;
185
	pub const ByteDeposit: u64 = 10;
186
	pub const SubAccountDeposit: u64 = 10;
187
	pub const MaxSubAccounts: u32 = 2;
188
	pub const MaxAdditionalFields: u32 = 2;
189
	pub const MaxRegistrars: u32 = 20;
190
}
191
impl core::fmt::Debug for MaxAdditionalFields {
192
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
193
		write!(f, "<>")
194
	}
195
}
196
impl pallet_identity::Config for Runtime {
197
	type RuntimeEvent = RuntimeEvent;
198
	type Currency = Balances;
199
	type BasicDeposit = BasicDeposit;
200
	type ByteDeposit = ByteDeposit;
201
	type SubAccountDeposit = SubAccountDeposit;
202
	type MaxSubAccounts = MaxSubAccounts;
203
	type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
204
	type MaxRegistrars = MaxRegistrars;
205
	type Slashed = ();
206
	type RegistrarOrigin = EnsureRegistrarAndForceOriginOrRoot;
207
	type ForceOrigin = EnsureRegistrarAndForceOriginOrRoot;
208
	type OffchainSignature = MockSignature;
209
	type SigningPublicKey = <MockSignature as sp_runtime::traits::Verify>::Signer;
210
	type UsernameAuthorityOrigin = EnsureRoot<Self::AccountId>;
211
	type PendingUsernameExpiration = ConstU32<100>;
212
	type MaxSuffixLength = ConstU32<7>;
213
	type MaxUsernameLength = ConstU32<32>;
214
	type WeightInfo = ();
215
}
216

            
217
pub(crate) struct ExtBuilder {
218
	/// Endowed accounts with balances
219
	balances: Vec<(AccountId, Balance)>,
220
}
221

            
222
impl Default for ExtBuilder {
223
34
	fn default() -> ExtBuilder {
224
34
		ExtBuilder { balances: vec![] }
225
34
	}
226
}
227

            
228
impl ExtBuilder {
229
	/// Fund some accounts before starting the test
230
34
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
231
34
		self.balances = balances;
232
34
		self
233
34
	}
234

            
235
	/// Build the test externalities for use in tests
236
34
	pub(crate) fn build(self) -> sp_io::TestExternalities {
237
34
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
238
34
			.build_storage()
239
34
			.expect("Frame system builds valid default genesis config");
240
34

            
241
34
		pallet_balances::GenesisConfig::<Runtime> {
242
34
			balances: self.balances.clone(),
243
34
		}
244
34
		.assimilate_storage(&mut t)
245
34
		.expect("Pallet balances storage can be assimilated");
246
34

            
247
34
		let mut ext = sp_io::TestExternalities::new(t);
248
34
		ext.execute_with(|| {
249
34
			System::set_block_number(1);
250
34
		});
251
34
		ext
252
34
	}
253
}
254

            
255
20
pub(crate) fn events() -> Vec<RuntimeEvent> {
256
20
	System::events()
257
20
		.into_iter()
258
172
		.map(|r| r.event)
259
20
		.collect::<Vec<_>>()
260
20
}