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::{ConstU32, EnsureOrigin, Everything, Nothing, OriginTrait, PalletInfo as _},
22
	weights::{RuntimeDbWeight, Weight},
23
};
24
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, GasWeightMapping};
25
use precompile_utils::{
26
	mock_account,
27
	precompile_set::*,
28
	testing::{AddressInPrefixedSet, MockAccount},
29
};
30
use sp_core::{H256, U256};
31
use sp_io;
32
use sp_runtime::traits::{BlakeTwo256, IdentityLookup, TryConvert};
33
use sp_runtime::BuildStorage;
34
use xcm::latest::Error as XcmError;
35
use xcm_builder::AllowUnpaidExecutionFrom;
36
use xcm_builder::FixedWeightBounds;
37
use xcm_builder::IsConcrete;
38
use xcm_builder::SovereignSignedViaLocation;
39
use xcm_executor::{
40
	traits::{ConvertLocation, TransactAsset, WeightTrader},
41
	AssetsInHolding,
42
};
43
use Junctions::Here;
44

            
45
pub type AccountId = MockAccount;
46
pub type Balance = u128;
47

            
48
type Block = frame_system::mocking::MockBlockU32<Runtime>;
49

            
50
// Configure a mock runtime to test the pallet.
51
199
construct_runtime!(
52
	pub enum Runtime	{
53
		System: frame_system,
54
		Balances: pallet_balances,
55
		Evm: pallet_evm,
56
		Timestamp: pallet_timestamp,
57
		PolkadotXcm: pallet_xcm,
58
	}
59
251
);
60

            
61
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
62
2
mock_account!(ParentAccount, |_| MockAccount::from_u64(3));
63
// use simple encoding for parachain accounts.
64
mock_account!(
65
	SiblingParachainAccount(u32),
66
2
	|v: SiblingParachainAccount| { AddressInPrefixedSet(0xffffffff, v.0 as u128).into() }
67
);
68

            
69
use frame_system::RawOrigin as SystemRawOrigin;
70
use xcm::latest::Junction;
71
pub struct MockAccountToAccountKey20<Origin, AccountId>(PhantomData<(Origin, AccountId)>);
72

            
73
impl<Origin: OriginTrait + Clone, AccountId: Into<H160>> TryConvert<Origin, Location>
74
	for MockAccountToAccountKey20<Origin, AccountId>
75
where
76
	Origin::PalletsOrigin: From<SystemRawOrigin<AccountId>>
77
		+ TryInto<SystemRawOrigin<AccountId>, Error = Origin::PalletsOrigin>,
78
{
79
4
	fn try_convert(o: Origin) -> Result<Location, Origin> {
80
4
		o.try_with_caller(|caller| match caller.try_into() {
81
4
			Ok(SystemRawOrigin::Signed(who)) => {
82
4
				let account_h160: H160 = who.into();
83
4
				Ok(Junction::AccountKey20 {
84
4
					network: None,
85
4
					key: account_h160.into(),
86
4
				}
87
4
				.into())
88
			}
89
			Ok(other) => Err(other.into()),
90
			Err(other) => Err(other),
91
4
		})
92
4
	}
93
}
94

            
95
pub struct MockParentMultilocationToAccountConverter;
96
impl ConvertLocation<AccountId> for MockParentMultilocationToAccountConverter {
97
2
	fn convert_location(location: &Location) -> Option<AccountId> {
98
1
		match location {
99
			Location {
100
				parents: 1,
101
				interior: Here,
102
1
			} => Some(ParentAccount.into()),
103
1
			_ => None,
104
		}
105
2
	}
106
}
107

            
108
pub struct MockParachainMultilocationToAccountConverter;
109
impl ConvertLocation<AccountId> for MockParachainMultilocationToAccountConverter {
110
3
	fn convert_location(location: &Location) -> Option<AccountId> {
111
3
		match location.unpack() {
112
1
			(1, [Parachain(id)]) => Some(SiblingParachainAccount(*id).into()),
113
2
			_ => None,
114
		}
115
3
	}
116
}
117

            
118
pub type LocationToAccountId = (
119
	MockParachainMultilocationToAccountConverter,
120
	MockParentMultilocationToAccountConverter,
121
	xcm_builder::AccountKey20Aliases<LocalNetworkId, AccountId>,
122
);
123

            
124
pub struct AccountIdToLocation;
125
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
126
	fn convert(account: AccountId) -> Location {
127
		let as_h160: H160 = account.into();
128
		Location::new(
129
			0,
130
			[AccountKey20 {
131
				network: None,
132
				key: as_h160.as_fixed_bytes().clone(),
133
			}],
134
		)
135
	}
136
}
137

            
138
parameter_types! {
139
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
140
	pub LocalNetworkId: Option<NetworkId> = None;
141
}
142

            
143
parameter_types! {
144
	pub const BlockHashCount: u32 = 250;
145
	pub const SS58Prefix: u8 = 42;
146
	pub const MockDbWeight: RuntimeDbWeight = RuntimeDbWeight {
147
		read: 1,
148
		write: 5,
149
	};
150
}
151

            
152
impl frame_system::Config for Runtime {
153
	type BaseCallFilter = Everything;
154
	type DbWeight = MockDbWeight;
155
	type RuntimeOrigin = RuntimeOrigin;
156
	type RuntimeTask = RuntimeTask;
157
	type Nonce = u64;
158
	type Block = Block;
159
	type RuntimeCall = RuntimeCall;
160
	type Hash = H256;
161
	type Hashing = BlakeTwo256;
162
	type AccountId = AccountId;
163
	type Lookup = IdentityLookup<Self::AccountId>;
164
	type RuntimeEvent = RuntimeEvent;
165
	type BlockHashCount = BlockHashCount;
166
	type Version = ();
167
	type PalletInfo = PalletInfo;
168
	type AccountData = pallet_balances::AccountData<Balance>;
169
	type OnNewAccount = ();
170
	type OnKilledAccount = ();
171
	type SystemWeightInfo = ();
172
	type BlockWeights = ();
173
	type BlockLength = ();
174
	type SS58Prefix = SS58Prefix;
175
	type OnSetCode = ();
176
	type MaxConsumers = frame_support::traits::ConstU32<16>;
177
	type SingleBlockMigrations = ();
178
	type MultiBlockMigrator = ();
179
	type PreInherents = ();
180
	type PostInherents = ();
181
	type PostTransactions = ();
182
}
183
parameter_types! {
184
	pub const ExistentialDeposit: u128 = 0;
185
}
186
impl pallet_balances::Config for Runtime {
187
	type MaxReserves = ();
188
	type ReserveIdentifier = ();
189
	type MaxLocks = ();
190
	type Balance = Balance;
191
	type RuntimeEvent = RuntimeEvent;
192
	type DustRemoval = ();
193
	type ExistentialDeposit = ExistentialDeposit;
194
	type AccountStore = System;
195
	type WeightInfo = ();
196
	type RuntimeHoldReason = ();
197
	type FreezeIdentifier = ();
198
	type MaxFreezes = ();
199
	type RuntimeFreezeReason = ();
200
}
201

            
202
parameter_types! {
203
	pub MatcherLocation: Location = Location::here();
204
}
205
pub type LocalOriginToLocation = MockAccountToAccountKey20<RuntimeOrigin, AccountId>;
206
impl pallet_xcm::Config for Runtime {
207
	type RuntimeEvent = RuntimeEvent;
208
	type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
209
	type XcmRouter = TestSendXcm;
210
	type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
211
	type XcmExecuteFilter = frame_support::traits::Everything;
212
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
213
	// Do not allow teleports
214
	type XcmTeleportFilter = Everything;
215
	type XcmReserveTransferFilter = Everything;
216
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
217
	type UniversalLocation = Ancestry;
218
	type RuntimeOrigin = RuntimeOrigin;
219
	type RuntimeCall = RuntimeCall;
220
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
221
	// We use a custom one to test runtime ugprades
222
	type AdvertisedXcmVersion = ();
223
	type Currency = Balances;
224
	type CurrencyMatcher = IsConcrete<MatcherLocation>;
225
	type TrustedLockers = ();
226
	type SovereignAccountOf = ();
227
	type MaxLockers = ConstU32<8>;
228
	type WeightInfo = pallet_xcm::TestWeightInfo;
229
	type MaxRemoteLockConsumers = ConstU32<0>;
230
	type RemoteLockConsumerIdentifier = ();
231
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
232
}
233
pub type Precompiles<R> = PrecompileSetBuilder<
234
	R,
235
	(
236
		PrecompileAt<
237
			AddressU64<1>,
238
			XcmUtilsPrecompile<R, XcmConfig>,
239
			CallableByContract<AllExceptXcmExecute<R, XcmConfig>>,
240
		>,
241
	),
242
>;
243

            
244
pub type PCall = XcmUtilsPrecompileCall<Runtime, XcmConfig>;
245

            
246
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
247
/// Block storage limit in bytes. Set to 40 KB.
248
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
249

            
250
parameter_types! {
251
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
252
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
253
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
254
	pub GasLimitPovSizeRatio: u64 = {
255
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
256
		block_gas_limit.saturating_div(MAX_POV_SIZE)
257
	};
258
	pub GasLimitStorageGrowthRatio: u64 = {
259
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
260
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
261
	};
262
}
263

            
264
/// A mapping function that converts Ethereum gas to Substrate weight
265
/// We are mocking this 1-1 to test db read charges too
266
pub struct MockGasWeightMapping;
267
impl GasWeightMapping for MockGasWeightMapping {
268
	fn gas_to_weight(gas: u64, _without_base_weight: bool) -> Weight {
269
		Weight::from_parts(gas, 1)
270
	}
271
15
	fn weight_to_gas(weight: Weight) -> u64 {
272
15
		weight.ref_time().into()
273
15
	}
274
}
275

            
276
impl pallet_evm::Config for Runtime {
277
	type FeeCalculator = ();
278
	type GasWeightMapping = MockGasWeightMapping;
279
	type WeightPerGas = WeightPerGas;
280
	type CallOrigin = EnsureAddressRoot<AccountId>;
281
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
282
	type AddressMapping = AccountId;
283
	type Currency = Balances;
284
	type RuntimeEvent = RuntimeEvent;
285
	type Runner = pallet_evm::runner::stack::Runner<Self>;
286
	type PrecompilesValue = PrecompilesValue;
287
	type PrecompilesType = Precompiles<Self>;
288
	type ChainId = ();
289
	type OnChargeTransaction = ();
290
	type BlockGasLimit = BlockGasLimit;
291
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
292
	type FindAuthor = ();
293
	type OnCreate = ();
294
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
295
	type SuicideQuickClearLimit = ConstU32<0>;
296
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
297
	type Timestamp = Timestamp;
298
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
299
}
300

            
301
parameter_types! {
302
	pub const MinimumPeriod: u64 = 5;
303
}
304
impl pallet_timestamp::Config for Runtime {
305
	type Moment = u64;
306
	type OnTimestampSet = ();
307
	type MinimumPeriod = MinimumPeriod;
308
	type WeightInfo = ();
309
}
310
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
311

            
312
pub struct ConvertOriginToLocal;
313
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
314
	type Success = Location;
315

            
316
	fn try_origin(_: Origin) -> Result<Location, Origin> {
317
		Ok(Location::here())
318
	}
319

            
320
	#[cfg(feature = "runtime-benchmarks")]
321
	fn try_successful_origin() -> Result<Origin, ()> {
322
		Ok(Origin::root())
323
	}
324
}
325

            
326
use sp_std::cell::RefCell;
327
use xcm::latest::opaque;
328
// Simulates sending a XCM message
329
2
thread_local! {
330
2
	pub static SENT_XCM: RefCell<Vec<(Location, opaque::Xcm)>> = RefCell::new(Vec::new());
331
2
}
332
2
pub fn sent_xcm() -> Vec<(Location, opaque::Xcm)> {
333
2
	SENT_XCM.with(|q| (*q.borrow()).clone())
334
2
}
335
pub struct TestSendXcm;
336
impl SendXcm for TestSendXcm {
337
	type Ticket = ();
338

            
339
2
	fn validate(
340
2
		destination: &mut Option<Location>,
341
2
		message: &mut Option<opaque::Xcm>,
342
2
	) -> SendResult<Self::Ticket> {
343
2
		SENT_XCM.with(|q| {
344
2
			q.borrow_mut()
345
2
				.push((destination.clone().unwrap(), message.clone().unwrap()))
346
2
		});
347
2
		Ok(((), Assets::new()))
348
2
	}
349

            
350
2
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
351
2
		Ok(XcmHash::default())
352
2
	}
353
}
354

            
355
pub struct DummyAssetTransactor;
356
impl TransactAsset for DummyAssetTransactor {
357
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
358
		Ok(())
359
	}
360

            
361
1
	fn withdraw_asset(
362
1
		_what: &Asset,
363
1
		_who: &Location,
364
1
		_maybe_context: Option<&XcmContext>,
365
1
	) -> Result<AssetsInHolding, XcmError> {
366
1
		Ok(AssetsInHolding::default())
367
1
	}
368
}
369

            
370
pub struct DummyWeightTrader;
371
impl WeightTrader for DummyWeightTrader {
372
4
	fn new() -> Self {
373
4
		DummyWeightTrader
374
4
	}
375

            
376
1
	fn buy_weight(
377
1
		&mut self,
378
1
		weight: Weight,
379
1
		payment: AssetsInHolding,
380
1
		_context: &XcmContext,
381
1
	) -> Result<AssetsInHolding, XcmError> {
382
1
		let asset_to_charge: Asset = (Location::parent(), weight.ref_time() as u128).into();
383
1
		let unused = payment
384
1
			.checked_sub(asset_to_charge)
385
1
			.map_err(|_| XcmError::TooExpensive)?;
386

            
387
1
		Ok(unused)
388
1
	}
389
}
390

            
391
parameter_types! {
392
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 0u64);
393
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
394

            
395
	pub SelfLocation: Location =
396
		Location::new(1, [Parachain(ParachainId::get().into())]);
397

            
398
	pub SelfReserve: Location = Location::new(
399
		1,
400
		[
401
			Parachain(ParachainId::get().into()),
402
			PalletInstance(<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8)
403
		]);
404
	pub MaxInstructions: u32 = 100;
405

            
406
	pub UniversalLocation: InteriorLocation = Here;
407
	pub Ancestry: InteriorLocation =
408
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainId::get().into())].into();
409

            
410
	pub const MaxAssetsIntoHolding: u32 = 64;
411
}
412

            
413
pub type XcmOriginToTransactDispatchOrigin = (
414
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
415
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
416
	// foreign chains who want to have a local sovereign account on this chain which they control.
417
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
418
);
419
pub struct XcmConfig;
420
impl xcm_executor::Config for XcmConfig {
421
	type RuntimeCall = RuntimeCall;
422
	type XcmSender = TestSendXcm;
423
	type AssetTransactor = DummyAssetTransactor;
424
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
425
	type IsReserve = ();
426
	type IsTeleporter = ();
427
	type UniversalLocation = UniversalLocation;
428
	type Barrier = Barrier;
429
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
430
	type Trader = DummyWeightTrader;
431
	type ResponseHandler = ();
432
	type SubscriptionService = ();
433
	type AssetTrap = ();
434
	type AssetClaims = ();
435
	type CallDispatcher = RuntimeCall;
436
	type AssetLocker = ();
437
	type AssetExchanger = ();
438
	type PalletInstancesInfo = ();
439
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
440
	type FeeManager = ();
441
	type MessageExporter = ();
442
	type UniversalAliases = Nothing;
443
	type SafeCallFilter = Everything;
444
	type Aliasers = Nothing;
445
	type TransactionalProcessor = ();
446
	type HrmpNewChannelOpenRequestHandler = ();
447
	type HrmpChannelAcceptedHandler = ();
448
	type HrmpChannelClosingHandler = ();
449
	type XcmRecorder = ();
450
}
451

            
452
pub(crate) struct ExtBuilder {
453
	// endowed accounts with balances
454
	balances: Vec<(AccountId, Balance)>,
455
}
456

            
457
impl Default for ExtBuilder {
458
10
	fn default() -> ExtBuilder {
459
10
		ExtBuilder { balances: vec![] }
460
10
	}
461
}
462

            
463
impl ExtBuilder {
464
2
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
465
2
		self.balances = balances;
466
2
		self
467
2
	}
468

            
469
10
	pub(crate) fn build(self) -> sp_io::TestExternalities {
470
10
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
471
10
			.build_storage()
472
10
			.expect("Frame system builds valid default genesis config");
473
10

            
474
10
		pallet_balances::GenesisConfig::<Runtime> {
475
10
			balances: self.balances,
476
10
		}
477
10
		.assimilate_storage(&mut t)
478
10
		.expect("Pallet balances storage can be assimilated");
479
10

            
480
10
		let mut ext = sp_io::TestExternalities::new(t);
481
10
		ext.execute_with(|| System::set_block_number(1));
482
10
		ext
483
10
	}
484
}