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::{
20
	construct_runtime, parameter_types,
21
	traits::{ConstU32, EqualPrivilegeOnly, Everything, SortedMembers, VoteTally},
22
	weights::Weight,
23
};
24
use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy, RawOrigin};
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot};
26
use pallet_referenda::{impl_tracksinfo_get, Curve, TrackInfo};
27
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
28
use precompile_utils::{precompile_set::*, testing::*};
29
use scale_info::TypeInfo;
30
use sp_core::H256;
31
use sp_runtime::{
32
	traits::{BlakeTwo256, IdentityLookup},
33
	BuildStorage, Perbill,
34
};
35
use sp_std::convert::{TryFrom, TryInto};
36

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

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

            
42
// Configure a mock runtime to test the pallet.
43
557
construct_runtime!(
44
	pub enum Runtime
45
	{
46
		System: frame_system,
47
		Balances: pallet_balances,
48
		Evm: pallet_evm,
49
		Timestamp: pallet_timestamp,
50
		Preimage: pallet_preimage,
51
		Scheduler: pallet_scheduler,
52
		Referenda: pallet_referenda,
53
	}
54
1010
);
55

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

            
95
parameter_types! {
96
	pub const ExistentialDeposit: u128 = 0;
97
}
98
impl pallet_balances::Config for Runtime {
99
	type MaxReserves = ();
100
	type ReserveIdentifier = [u8; 4];
101
	type MaxLocks = ();
102
	type Balance = Balance;
103
	type RuntimeEvent = RuntimeEvent;
104
	type DustRemoval = ();
105
	type ExistentialDeposit = ExistentialDeposit;
106
	type AccountStore = System;
107
	type WeightInfo = ();
108
	type RuntimeHoldReason = ();
109
	type FreezeIdentifier = ();
110
	type MaxFreezes = ();
111
	type RuntimeFreezeReason = ();
112
}
113

            
114
pub type TestPrecompiles<R> = PrecompileSetBuilder<
115
	R,
116
	(
117
		PrecompileAt<AddressU64<1>, ReferendaPrecompile<R, GovOrigin>>,
118
		RevertPrecompile<AddressU64<2>>,
119
	),
120
>;
121

            
122
pub type PCall = ReferendaPrecompileCall<Runtime, GovOrigin>;
123

            
124
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
125
/// Block storage limit in bytes. Set to 40 KB.
126
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
127

            
128
parameter_types! {
129
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
130
	pub PrecompilesValue: TestPrecompiles<Runtime> = TestPrecompiles::new();
131
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
132
	pub GasLimitPovSizeRatio: u64 = {
133
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
134
		block_gas_limit.saturating_div(MAX_POV_SIZE)
135
	};
136
	pub GasLimitStorageGrowthRatio: u64 = {
137
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
138
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
139
	};
140
}
141

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

            
167
parameter_types! {
168
	pub const MinimumPeriod: u64 = 5;
169
}
170
impl pallet_timestamp::Config for Runtime {
171
	type Moment = u64;
172
	type OnTimestampSet = ();
173
	type MinimumPeriod = MinimumPeriod;
174
	type WeightInfo = ();
175
}
176

            
177
impl pallet_preimage::Config for Runtime {
178
	type RuntimeEvent = RuntimeEvent;
179
	type WeightInfo = ();
180
	type Currency = Balances;
181
	type ManagerOrigin = EnsureRoot<AccountId>;
182
	type Consideration = ();
183
}
184
impl pallet_scheduler::Config for Runtime {
185
	type RuntimeEvent = RuntimeEvent;
186
	type RuntimeOrigin = RuntimeOrigin;
187
	type PalletsOrigin = OriginCaller;
188
	type RuntimeCall = RuntimeCall;
189
	type MaximumWeight = MaximumBlockWeight;
190
	type ScheduleOrigin = EnsureRoot<AccountId>;
191
	type MaxScheduledPerBlock = ConstU32<100>;
192
	type WeightInfo = ();
193
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
194
	type Preimages = Preimage;
195
}
196

            
197
10
parameter_types! {
198
10
	pub static AlarmInterval: u32 = 1;
199
10
}
200
pub struct OneToFive;
201
impl SortedMembers<AccountId> for OneToFive {
202
1
	fn sorted_members() -> Vec<AccountId> {
203
1
		vec![
204
1
			Alice.into(),
205
1
			Bob.into(),
206
1
			Charlie.into(),
207
1
			David.into(),
208
1
			Zero.into(),
209
1
		]
210
1
	}
211
	#[cfg(feature = "runtime-benchmarks")]
212
	fn add(_m: &AccountId) {}
213
}
214

            
215
pub struct TestTracksInfo;
216
impl TracksInfo<u128, u32> for TestTracksInfo {
217
	type Id = u8;
218
	type RuntimeOrigin = <RuntimeOrigin as OriginTrait>::PalletsOrigin;
219
10
	fn tracks() -> &'static [(Self::Id, TrackInfo<u128, u32>)] {
220
10
		static DATA: [(u8, TrackInfo<u128, u32>); 2] = [
221
10
			(
222
10
				0u8,
223
10
				TrackInfo {
224
10
					name: "root",
225
10
					max_deciding: 1,
226
10
					decision_deposit: 10,
227
10
					prepare_period: 4,
228
10
					decision_period: 4,
229
10
					confirm_period: 2,
230
10
					min_enactment_period: 4,
231
10
					min_approval: Curve::LinearDecreasing {
232
10
						length: Perbill::from_percent(100),
233
10
						floor: Perbill::from_percent(50),
234
10
						ceil: Perbill::from_percent(100),
235
10
					},
236
10
					min_support: Curve::LinearDecreasing {
237
10
						length: Perbill::from_percent(100),
238
10
						floor: Perbill::from_percent(0),
239
10
						ceil: Perbill::from_percent(100),
240
10
					},
241
10
				},
242
10
			),
243
10
			(
244
10
				1u8,
245
10
				TrackInfo {
246
10
					name: "none",
247
10
					max_deciding: 3,
248
10
					decision_deposit: 1,
249
10
					prepare_period: 2,
250
10
					decision_period: 2,
251
10
					confirm_period: 1,
252
10
					min_enactment_period: 2,
253
10
					min_approval: Curve::LinearDecreasing {
254
10
						length: Perbill::from_percent(100),
255
10
						floor: Perbill::from_percent(95),
256
10
						ceil: Perbill::from_percent(100),
257
10
					},
258
10
					min_support: Curve::LinearDecreasing {
259
10
						length: Perbill::from_percent(100),
260
10
						floor: Perbill::from_percent(90),
261
10
						ceil: Perbill::from_percent(100),
262
10
					},
263
10
				},
264
10
			),
265
10
		];
266
10
		&DATA[..]
267
10
	}
268
5
	fn track_for(id: &Self::RuntimeOrigin) -> Result<Self::Id, ()> {
269
5
		if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) {
270
5
			match system_origin {
271
5
				frame_system::RawOrigin::Root => Ok(0),
272
				frame_system::RawOrigin::None => Ok(1),
273
				_ => Err(()),
274
			}
275
		} else {
276
			Err(())
277
		}
278
5
	}
279
}
280
impl_tracksinfo_get!(TestTracksInfo, u128, u32);
281

            
282
3
#[derive(Encode, Debug, Decode, TypeInfo, Eq, PartialEq, Clone, MaxEncodedLen)]
283
pub struct Tally {
284
	pub ayes: u32,
285
	pub nays: u32,
286
}
287

            
288
impl<Class> VoteTally<u32, Class> for Tally {
289
5
	fn new(_: Class) -> Self {
290
5
		Self { ayes: 0, nays: 0 }
291
5
	}
292

            
293
	fn ayes(&self, _: Class) -> u32 {
294
		self.ayes
295
	}
296

            
297
	fn support(&self, _: Class) -> Perbill {
298
		Perbill::from_percent(self.ayes)
299
	}
300

            
301
	fn approval(&self, _: Class) -> Perbill {
302
		if self.ayes + self.nays > 0 {
303
			Perbill::from_rational(self.ayes, self.ayes + self.nays)
304
		} else {
305
			Perbill::zero()
306
		}
307
	}
308

            
309
	#[cfg(feature = "runtime-benchmarks")]
310
	fn unanimity(_: Class) -> Self {
311
		Self { ayes: 100, nays: 0 }
312
	}
313

            
314
	#[cfg(feature = "runtime-benchmarks")]
315
	fn rejection(_: Class) -> Self {
316
		Self { ayes: 0, nays: 100 }
317
	}
318

            
319
	#[cfg(feature = "runtime-benchmarks")]
320
	fn from_requirements(support: Perbill, approval: Perbill, _: Class) -> Self {
321
		let ayes = support.mul_ceil(100u32);
322
		let nays = ((ayes as u64) * 1_000_000_000u64 / approval.deconstruct() as u64) as u32 - ayes;
323
		Self { ayes, nays }
324
	}
325

            
326
	#[cfg(feature = "runtime-benchmarks")]
327
	fn setup(_: Class, _: Perbill) {}
328
}
329
parameter_types! {
330
	pub const SubmissionDeposit: u128 = 15;
331
}
332
impl pallet_referenda::Config for Runtime {
333
	type WeightInfo = ();
334
	type RuntimeCall = RuntimeCall;
335
	type RuntimeEvent = RuntimeEvent;
336
	type Scheduler = Scheduler;
337
	type Currency = pallet_balances::Pallet<Self>;
338
	type SubmitOrigin = EnsureSigned<AccountId>;
339
	type CancelOrigin = EnsureSignedBy<OneToFive, AccountId>;
340
	type KillOrigin = EnsureRoot<AccountId>;
341
	type Slash = ();
342
	type Votes = u32;
343
	type Tally = Tally;
344
	type SubmissionDeposit = SubmissionDeposit;
345
	type MaxQueued = ConstU32<3>;
346
	type UndecidingTimeout = ConstU32<20>;
347
	type AlarmInterval = AlarmInterval;
348
	type Tracks = TestTracksInfo;
349
	type Preimages = Preimage;
350
}
351

            
352
pub struct GovOrigin;
353
impl FromStr for GovOrigin {
354
	type Err = ();
355
	fn from_str(_s: &str) -> Result<Self, Self::Err> {
356
		Err(())
357
	}
358
}
359

            
360
impl From<GovOrigin> for OriginCaller {
361
	fn from(_o: GovOrigin) -> OriginCaller {
362
		OriginCaller::system(RawOrigin::Root)
363
	}
364
}
365

            
366
/// Externality builder for pallet referenda mock runtime
367
pub(crate) struct ExtBuilder {
368
	/// Balance amounts per AccountId
369
	balances: Vec<(AccountId, Balance)>,
370
}
371

            
372
impl Default for ExtBuilder {
373
4
	fn default() -> ExtBuilder {
374
4
		ExtBuilder {
375
4
			balances: Vec::new(),
376
4
		}
377
4
	}
378
}
379

            
380
impl ExtBuilder {
381
	#[allow(dead_code)]
382
4
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
383
4
		self.balances = balances;
384
4
		self
385
4
	}
386

            
387
	#[allow(dead_code)]
388
4
	pub(crate) fn build(self) -> sp_io::TestExternalities {
389
4
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
390
4
			.build_storage()
391
4
			.expect("Frame system builds valid default genesis config");
392
4

            
393
4
		pallet_balances::GenesisConfig::<Runtime> {
394
4
			balances: self.balances,
395
4
		}
396
4
		.assimilate_storage(&mut t)
397
4
		.expect("Pallet balances storage can be assimilated");
398
4

            
399
4
		let mut ext = sp_io::TestExternalities::new(t);
400
4
		ext.execute_with(|| System::set_block_number(1));
401
4
		ext
402
4
	}
403
}
404

            
405
10
pub(crate) fn events() -> Vec<RuntimeEvent> {
406
10
	System::events()
407
10
		.into_iter()
408
150
		.map(|r| r.event)
409
10
		.collect::<Vec<_>>()
410
10
}