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
//! A minimal precompile runtime including the pallet-randomness pallet
18
use super::*;
19
use frame_support::{construct_runtime, parameter_types, traits::Everything, weights::Weight};
20
use nimbus_primitives::NimbusId;
21
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot};
22
use precompile_utils::{precompile_set::*, testing::MockAccount};
23
use session_keys_primitives::VrfId;
24
use sp_core::H256;
25
use sp_runtime::{
26
	traits::{BlakeTwo256, IdentityLookup},
27
	BuildStorage, Perbill,
28
};
29
use sp_std::convert::{TryFrom, TryInto};
30

            
31
pub type AccountId = MockAccount;
32
pub type Balance = u128;
33

            
34
type Block = frame_system::mocking::MockBlockU32<Runtime>;
35

            
36
// Configure a mock runtime to test the pallet.
37
1067
construct_runtime!(
38
	pub enum Runtime	{
39
		System: frame_system,
40
		Balances: pallet_balances,
41
		AuthorMapping: pallet_author_mapping,
42
		Evm: pallet_evm,
43
		Timestamp: pallet_timestamp,
44
		Randomness: pallet_randomness,
45
	}
46
1674
);
47

            
48
parameter_types! {
49
	pub const BlockHashCount: u32 = 250;
50
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
51
	pub const MaximumBlockLength: u32 = 2 * 1024;
52
	pub const AvailableBlockRatio: Perbill = Perbill::one();
53
	pub const SS58Prefix: u8 = 42;
54
}
55
impl frame_system::Config for Runtime {
56
	type BaseCallFilter = Everything;
57
	type DbWeight = ();
58
	type RuntimeOrigin = RuntimeOrigin;
59
	type RuntimeTask = RuntimeTask;
60
	type Nonce = u64;
61
	type Block = Block;
62
	type RuntimeCall = RuntimeCall;
63
	type Hash = H256;
64
	type Hashing = BlakeTwo256;
65
	type AccountId = AccountId;
66
	type Lookup = IdentityLookup<Self::AccountId>;
67
	type RuntimeEvent = RuntimeEvent;
68
	type BlockHashCount = BlockHashCount;
69
	type Version = ();
70
	type PalletInfo = PalletInfo;
71
	type AccountData = pallet_balances::AccountData<Balance>;
72
	type OnNewAccount = ();
73
	type OnKilledAccount = ();
74
	type SystemWeightInfo = ();
75
	type BlockWeights = ();
76
	type BlockLength = ();
77
	type SS58Prefix = SS58Prefix;
78
	type OnSetCode = ();
79
	type MaxConsumers = frame_support::traits::ConstU32<16>;
80
	type SingleBlockMigrations = ();
81
	type MultiBlockMigrator = ();
82
	type PreInherents = ();
83
	type PostInherents = ();
84
	type PostTransactions = ();
85
}
86

            
87
parameter_types! {
88
	pub const ExistentialDeposit: u128 = 0;
89
}
90
impl pallet_balances::Config for Runtime {
91
	type MaxReserves = ();
92
	type ReserveIdentifier = [u8; 4];
93
	type MaxLocks = ();
94
	type Balance = Balance;
95
	type RuntimeEvent = RuntimeEvent;
96
	type DustRemoval = ();
97
	type ExistentialDeposit = ExistentialDeposit;
98
	type AccountStore = System;
99
	type WeightInfo = ();
100
	type RuntimeHoldReason = ();
101
	type FreezeIdentifier = ();
102
	type MaxFreezes = ();
103
	type RuntimeFreezeReason = ();
104
}
105

            
106
pub type TestPrecompiles<R> = PrecompileSetBuilder<
107
	R,
108
	(
109
		PrecompileAt<
110
			AddressU64<1>,
111
			RandomnessPrecompile<R>,
112
			(SubcallWithMaxNesting<1>, CallableByContract),
113
		>,
114
		RevertPrecompile<AddressU64<2>>,
115
	),
116
>;
117

            
118
pub type PCall = RandomnessPrecompileCall<Runtime>;
119

            
120
parameter_types! {
121
	pub PrecompilesValue: TestPrecompiles<Runtime> = TestPrecompiles::new();
122
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
123
	pub const SuicideQuickClearLimit: u32 = 0;
124
}
125

            
126
impl pallet_evm::Config for Runtime {
127
	type FeeCalculator = ();
128
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
129
	type WeightPerGas = WeightPerGas;
130
	type CallOrigin = EnsureAddressRoot<AccountId>;
131
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
132
	type AddressMapping = AccountId;
133
	type Currency = Balances;
134
	type RuntimeEvent = RuntimeEvent;
135
	type Runner = pallet_evm::runner::stack::Runner<Self>;
136
	type PrecompilesType = TestPrecompiles<Runtime>;
137
	type PrecompilesValue = PrecompilesValue;
138
	type ChainId = ();
139
	type OnChargeTransaction = ();
140
	type BlockGasLimit = ();
141
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
142
	type FindAuthor = ();
143
	type OnCreate = ();
144
	type GasLimitPovSizeRatio = ();
145
	type GasLimitStorageGrowthRatio = ();
146
	type Timestamp = Timestamp;
147
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
148
	type SuicideQuickClearLimit = SuicideQuickClearLimit;
149
}
150

            
151
parameter_types! {
152
	pub const MinimumPeriod: u64 = 5;
153
}
154
impl pallet_timestamp::Config for Runtime {
155
	type Moment = u64;
156
	type OnTimestampSet = ();
157
	type MinimumPeriod = MinimumPeriod;
158
	type WeightInfo = ();
159
}
160

            
161
parameter_types! {
162
	pub const DepositAmount: Balance = 100;
163
}
164
impl pallet_author_mapping::Config for Runtime {
165
	type RuntimeEvent = RuntimeEvent;
166
	type DepositCurrency = Balances;
167
	type DepositAmount = DepositAmount;
168
	type Keys = VrfId;
169
	type WeightInfo = ();
170
}
171

            
172
pub struct BabeDataGetter;
173
impl pallet_randomness::GetBabeData<u64, Option<H256>> for BabeDataGetter {
174
4
	fn get_epoch_index() -> u64 {
175
4
		1u64
176
4
	}
177
	fn get_epoch_randomness() -> Option<H256> {
178
		None
179
	}
180
}
181

            
182
parameter_types! {
183
	pub const Deposit: u128 = 10;
184
	pub const MaxRandomWords: u8 = 1;
185
	pub const MinBlockDelay: u32 = 2;
186
	pub const MaxBlockDelay: u32 = 20;
187
}
188
impl pallet_randomness::Config for Runtime {
189
	type RuntimeEvent = RuntimeEvent;
190
	type AddressMapping = AccountId;
191
	type Currency = Balances;
192
	type BabeDataGetter = BabeDataGetter;
193
	type VrfKeyLookup = AuthorMapping;
194
	type Deposit = Deposit;
195
	type MaxRandomWords = MaxRandomWords;
196
	type MinBlockDelay = MinBlockDelay;
197
	type MaxBlockDelay = MaxBlockDelay;
198
	type BlockExpirationDelay = MaxBlockDelay;
199
	type EpochExpirationDelay = MaxBlockDelay;
200
	type WeightInfo = pallet_randomness::weights::SubstrateWeight<Runtime>;
201
}
202

            
203
/// Externality builder for pallet randomness mock runtime
204
pub(crate) struct ExtBuilder {
205
	/// Balance amounts per AccountId
206
	balances: Vec<(AccountId, Balance)>,
207
	/// AuthorId -> AccountId mappings
208
	mappings: Vec<(NimbusId, AccountId)>,
209
}
210

            
211
impl Default for ExtBuilder {
212
18
	fn default() -> ExtBuilder {
213
18
		ExtBuilder {
214
18
			balances: Vec::new(),
215
18
			mappings: Vec::new(),
216
18
		}
217
18
	}
218
}
219

            
220
impl ExtBuilder {
221
	#[allow(dead_code)]
222
12
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
223
12
		self.balances = balances;
224
12
		self
225
12
	}
226

            
227
	#[allow(dead_code)]
228
	pub(crate) fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
229
		self.mappings = mappings;
230
		self
231
	}
232

            
233
	#[allow(dead_code)]
234
18
	pub(crate) fn build(self) -> sp_io::TestExternalities {
235
18
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
236
18
			.build_storage()
237
18
			.expect("Frame system builds valid default genesis config");
238
18

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

            
245
18
		pallet_author_mapping::GenesisConfig::<Runtime> {
246
18
			mappings: self.mappings,
247
18
		}
248
18
		.assimilate_storage(&mut t)
249
18
		.expect("Pallet author mapping's storage can be assimilated");
250
18

            
251
18
		let mut ext = sp_io::TestExternalities::new(t);
252
18
		ext.execute_with(|| System::set_block_number(1));
253
18
		ext
254
18
	}
255
}
256

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

            
264
/// Panics if an event is not found in the system log of events
265
#[macro_export]
266
macro_rules! assert_event_emitted {
267
	($event:expr) => {
268
		match &$event {
269
			e => {
270
				assert!(
271
					crate::mock::events().iter().find(|x| *x == e).is_some(),
272
					"Event {:?} was not found in events: \n {:#?}",
273
					e,
274
					crate::mock::events()
275
				);
276
			}
277
		}
278
	};
279
}