1
// Copyright 2019-2025 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, FrameSystemAccountProvider};
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
1130
construct_runtime!(
38
79
	pub enum Runtime	{
39
79
		System: frame_system,
40
79
		Balances: pallet_balances,
41
79
		AuthorMapping: pallet_author_mapping,
42
79
		Evm: pallet_evm,
43
79
		Timestamp: pallet_timestamp,
44
79
		Randomness: pallet_randomness,
45
79
	}
46
1131
);
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
	type ExtensionsWeightInfo = ();
86
}
87

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

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

            
120
pub type PCall = RandomnessPrecompileCall<Runtime>;
121

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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