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
#![allow(dead_code)]
18

            
19
use cumulus_primitives_parachain_inherent::ParachainInherentData;
20
use fp_evm::GenesisAccount;
21
use frame_support::{
22
	assert_ok,
23
	traits::{OnFinalize, OnInitialize},
24
};
25
pub use moonriver_runtime::{
26
	currency::MOVR, AccountId, AsyncBacking, AuthorInherent, Balance, Ethereum, InflationInfo,
27
	ParachainStaking, Range, Runtime, RuntimeCall, RuntimeEvent, System, TransactionConverter,
28
	UncheckedExtrinsic, HOURS,
29
};
30
use nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID};
31
use polkadot_parachain::primitives::HeadData;
32
use sp_consensus_slots::Slot;
33
use sp_core::{Encode, H160};
34
use sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem, Perbill, Percent};
35

            
36
use cumulus_pallet_parachain_system::MessagingStateSnapshot;
37
use cumulus_primitives_core::relay_chain::{AbridgedHostConfiguration, AsyncBackingParams};
38
use cumulus_primitives_core::AbridgedHrmpChannel;
39
use fp_rpc::ConvertTransaction;
40
use moonriver_runtime::bridge_config::XcmOverPolkadotInstance;
41
use moonriver_runtime::{EvmForeignAssets, XcmWeightTrader};
42
use pallet_transaction_payment::Multiplier;
43
use std::collections::BTreeMap;
44
use xcm::latest::{InteriorLocation, Location};
45

            
46
10
pub fn existential_deposit() -> u128 {
47
10
	<Runtime as pallet_balances::Config>::ExistentialDeposit::get()
48
10
}
49

            
50
/// Returns mock AbridgedHostConfiguration for ParachainSystem tests
51
58
pub fn mock_abridged_host_config() -> AbridgedHostConfiguration {
52
58
	AbridgedHostConfiguration {
53
58
		max_code_size: 3_145_728,
54
58
		max_head_data_size: 20_480,
55
58
		max_upward_queue_count: 174_762,
56
58
		max_upward_queue_size: 1_048_576,
57
58
		max_upward_message_size: 65_531,
58
58
		max_upward_message_num_per_candidate: 16,
59
58
		hrmp_max_message_num_per_candidate: 10,
60
58
		validation_upgrade_cooldown: 6,
61
58
		validation_upgrade_delay: 6,
62
58
		async_backing_params: AsyncBackingParams {
63
58
			max_candidate_depth: 3,
64
58
			allowed_ancestry_len: 2,
65
58
		},
66
58
	}
67
58
}
68

            
69
// A valid signed Alice transfer.
70
pub const VALID_ETH_TX: &str =
71
	"02f86d8205018085174876e80085e8d4a5100082520894f24ff3a9cf04c71dbc94d0b566f7a27b9456\
72
	6cac8080c001a0e1094e1a52520a75c0255db96132076dd0f1263089f838bea548cbdbfc64a4d19f031c\
73
	92a8cb04e2d68d20a6158d542a07ac440cc8d07b6e36af02db046d92df";
74

            
75
// An invalid signed Alice transfer with a gas limit artifically set to 0.
76
pub const INVALID_ETH_TX: &str =
77
	"f86180843b9aca00809412cb274aad8251c875c0bf6872b67d9983e53fdd01801ca00e28ba2dd3c5a\
78
	3fd467d4afd7aefb4a34b373314fff470bb9db743a84d674a0aa06e5994f2d07eafe1c37b4ce5471ca\
79
	ecec29011f6f5bf0b1a552c55ea348df35f";
80

            
81
3
pub fn rpc_run_to_block(n: u32) {
82
6
	while System::block_number() < n {
83
3
		Ethereum::on_finalize(System::block_number());
84
3
		System::set_block_number(System::block_number() + 1);
85
3
		Ethereum::on_initialize(System::block_number());
86
3
	}
87
3
}
88

            
89
/// Utility function that advances the chain to the desired block number.
90
/// If an author is provided, that author information is injected to all the blocks in the meantime.
91
9
pub fn run_to_block(n: u32, author: Option<NimbusId>) {
92
6607
	while System::block_number() < n {
93
		// Set the new block number and author
94
6598
		match author {
95
6598
			Some(ref author) => {
96
6598
				let pre_digest = Digest {
97
6598
					logs: vec![DigestItem::PreRuntime(NIMBUS_ENGINE_ID, author.encode())],
98
6598
				};
99
6598
				System::reset_events();
100
6598
				System::initialize(
101
6598
					&(System::block_number() + 1),
102
6598
					&System::parent_hash(),
103
6598
					&pre_digest,
104
6598
				);
105
6598
			}
106
			None => {
107
				System::set_block_number(System::block_number() + 1);
108
			}
109
		}
110

            
111
6598
		increase_last_relay_slot_number(1);
112

            
113
		// Initialize the new block
114
6598
		AuthorInherent::on_initialize(System::block_number());
115
6598
		ParachainStaking::on_initialize(System::block_number());
116

            
117
		// Finalize the block
118
6598
		ParachainStaking::on_finalize(System::block_number());
119
	}
120
9
}
121

            
122
1
pub fn last_event() -> RuntimeEvent {
123
1
	System::events().pop().expect("Event expected").event
124
1
}
125

            
126
// Helper function to give a simple evm context suitable for tests.
127
// We can remove this once https://github.com/rust-blockchain/evm/pull/35
128
// is in our dependency graph.
129
pub fn evm_test_context() -> fp_evm::Context {
130
	fp_evm::Context {
131
		address: Default::default(),
132
		caller: Default::default(),
133
		apparent_value: From::from(0),
134
	}
135
}
136

            
137
// Test struct with the purpose of initializing xcm assets
138
#[derive(Clone)]
139
pub struct XcmAssetInitialization {
140
	pub asset_id: u128,
141
	pub xcm_location: xcm::v5::Location,
142
	pub decimals: u8,
143
	pub name: &'static str,
144
	pub symbol: &'static str,
145
	pub balances: Vec<(AccountId, Balance)>,
146
}
147

            
148
pub struct ExtBuilder {
149
	// endowed accounts with balances
150
	balances: Vec<(AccountId, Balance)>,
151
	// [collator, amount]
152
	collators: Vec<(AccountId, Balance)>,
153
	// [delegator, collator, nomination_amount]
154
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
155
	// per-round inflation config
156
	inflation: InflationInfo<Balance>,
157
	// AuthorId -> AccoutId mappings
158
	mappings: Vec<(NimbusId, AccountId)>,
159
	// Crowdloan fund
160
	crowdloan_fund: Balance,
161
	// Chain id
162
	chain_id: u64,
163
	// EVM genesis accounts
164
	evm_accounts: BTreeMap<H160, GenesisAccount>,
165
	// [assettype, metadata, Vec<Account, Balance,>, is_sufficient]
166
	xcm_assets: Vec<XcmAssetInitialization>,
167
	safe_xcm_version: Option<u32>,
168
	opened_bridges: Vec<(Location, InteriorLocation, Option<bp_moonbeam::LaneId>)>,
169
}
170

            
171
impl Default for ExtBuilder {
172
58
	fn default() -> ExtBuilder {
173
58
		ExtBuilder {
174
58
			balances: vec![],
175
58
			delegations: vec![],
176
58
			collators: vec![],
177
58
			inflation: InflationInfo {
178
58
				expect: Range {
179
58
					min: 100_000 * MOVR,
180
58
					ideal: 200_000 * MOVR,
181
58
					max: 500_000 * MOVR,
182
58
				},
183
58
				// not used
184
58
				annual: Range {
185
58
					min: Perbill::from_percent(50),
186
58
					ideal: Perbill::from_percent(50),
187
58
					max: Perbill::from_percent(50),
188
58
				},
189
58
				// unrealistically high parameterization, only for testing
190
58
				round: Range {
191
58
					min: Perbill::from_percent(5),
192
58
					ideal: Perbill::from_percent(5),
193
58
					max: Perbill::from_percent(5),
194
58
				},
195
58
			},
196
58
			mappings: vec![],
197
58
			crowdloan_fund: 0,
198
58
			chain_id: CHAIN_ID,
199
58
			evm_accounts: BTreeMap::new(),
200
58
			xcm_assets: vec![],
201
58
			safe_xcm_version: None,
202
58
			opened_bridges: vec![],
203
58
		}
204
58
	}
205
}
206

            
207
impl ExtBuilder {
208
2
	pub fn with_evm_accounts(mut self, accounts: BTreeMap<H160, GenesisAccount>) -> Self {
209
2
		self.evm_accounts = accounts;
210
2
		self
211
2
	}
212

            
213
35
	pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
214
35
		self.balances = balances;
215
35
		self
216
35
	}
217

            
218
9
	pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
219
9
		self.collators = collators;
220
9
		self
221
9
	}
222

            
223
7
	pub fn with_delegations(mut self, delegations: Vec<(AccountId, AccountId, Balance)>) -> Self {
224
7
		self.delegations = delegations
225
7
			.into_iter()
226
8
			.map(|d| (d.0, d.1, d.2, Percent::zero()))
227
7
			.collect();
228
7
		self
229
7
	}
230

            
231
	pub fn with_crowdloan_fund(mut self, crowdloan_fund: Balance) -> Self {
232
		self.crowdloan_fund = crowdloan_fund;
233
		self
234
	}
235

            
236
8
	pub fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
237
8
		self.mappings = mappings;
238
8
		self
239
8
	}
240

            
241
	#[allow(dead_code)]
242
	pub fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
243
		self.inflation = inflation;
244
		self
245
	}
246

            
247
4
	pub fn with_xcm_assets(mut self, xcm_assets: Vec<XcmAssetInitialization>) -> Self {
248
4
		self.xcm_assets = xcm_assets;
249
4
		self
250
4
	}
251

            
252
5
	pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
253
5
		self.safe_xcm_version = Some(safe_xcm_version);
254
5
		self
255
5
	}
256

            
257
2
	pub fn with_open_bridges(
258
2
		mut self,
259
2
		opened_bridges: Vec<(Location, InteriorLocation, Option<bp_moonbeam::LaneId>)>,
260
2
	) -> Self {
261
2
		self.opened_bridges = opened_bridges;
262
2
		self
263
2
	}
264

            
265
58
	pub fn build(self) -> sp_io::TestExternalities {
266
58
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
267
58
			.build_storage()
268
58
			.unwrap();
269

            
270
58
		parachain_info::GenesisConfig::<Runtime> {
271
58
			parachain_id: <bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID.into(),
272
58
			_config: Default::default(),
273
58
		}
274
58
		.assimilate_storage(&mut t)
275
58
		.unwrap();
276

            
277
58
		pallet_balances::GenesisConfig::<Runtime> {
278
58
			balances: self.balances,
279
58
			dev_accounts: None,
280
58
		}
281
58
		.assimilate_storage(&mut t)
282
58
		.unwrap();
283

            
284
58
		pallet_parachain_staking::GenesisConfig::<Runtime> {
285
58
			candidates: self.collators,
286
58
			delegations: self.delegations,
287
58
			inflation_config: self.inflation,
288
58
			collator_commission: Perbill::from_percent(20),
289
58
			parachain_bond_reserve_percent: Percent::from_percent(30),
290
58
			blocks_per_round: 2 * HOURS,
291
58
			num_selected_candidates: 8,
292
58
		}
293
58
		.assimilate_storage(&mut t)
294
58
		.unwrap();
295

            
296
58
		pallet_author_mapping::GenesisConfig::<Runtime> {
297
58
			mappings: self.mappings,
298
58
		}
299
58
		.assimilate_storage(&mut t)
300
58
		.unwrap();
301

            
302
58
		let genesis_config = pallet_evm_chain_id::GenesisConfig::<Runtime> {
303
58
			chain_id: self.chain_id,
304
58
			..Default::default()
305
58
		};
306
58
		genesis_config.assimilate_storage(&mut t).unwrap();
307

            
308
58
		let genesis_config = pallet_evm::GenesisConfig::<Runtime> {
309
58
			accounts: self.evm_accounts,
310
58
			..Default::default()
311
58
		};
312
58
		genesis_config.assimilate_storage(&mut t).unwrap();
313

            
314
58
		let genesis_config = pallet_ethereum::GenesisConfig::<Runtime> {
315
58
			..Default::default()
316
58
		};
317
58
		genesis_config.assimilate_storage(&mut t).unwrap();
318

            
319
58
		let genesis_config = pallet_xcm::GenesisConfig::<Runtime> {
320
58
			safe_xcm_version: self.safe_xcm_version,
321
58
			..Default::default()
322
58
		};
323
58
		genesis_config.assimilate_storage(&mut t).unwrap();
324

            
325
58
		let genesis_config = pallet_transaction_payment::GenesisConfig::<Runtime> {
326
58
			multiplier: Multiplier::from(10u128),
327
58
			..Default::default()
328
58
		};
329
58
		genesis_config.assimilate_storage(&mut t).unwrap();
330

            
331
58
		let genesis_config = pallet_xcm_bridge::GenesisConfig::<Runtime, XcmOverPolkadotInstance> {
332
58
			opened_bridges: self.opened_bridges,
333
58
			_phantom: Default::default(),
334
58
		};
335
58
		genesis_config.assimilate_storage(&mut t).unwrap();
336

            
337
58
		let mut ext = sp_io::TestExternalities::new(t);
338
58
		let xcm_assets = self.xcm_assets.clone();
339
58
		ext.execute_with(|| {
340
			// Mock host configuration for ParachainSystem
341
58
			cumulus_pallet_parachain_system::HostConfiguration::<Runtime>::put(
342
58
				mock_abridged_host_config(),
343
			);
344

            
345
			// Mock hrmp egress_channels
346
58
			cumulus_pallet_parachain_system::RelevantMessagingState::<Runtime>::put(
347
58
				MessagingStateSnapshot {
348
58
					dmq_mqc_head: Default::default(),
349
58
					relay_dispatch_queue_remaining_capacity: Default::default(),
350
58
					ingress_channels: vec![],
351
58
					egress_channels: vec![(
352
58
						1_000.into(),
353
58
						AbridgedHrmpChannel {
354
58
							max_capacity: u32::MAX,
355
58
							max_total_size: u32::MAX,
356
58
							max_message_size: u32::MAX,
357
58
							msg_count: 0,
358
58
							total_size: 0,
359
58
							mqc_head: None,
360
58
						},
361
58
					)],
362
58
				},
363
			);
364

            
365
			// If any xcm assets specified, we register them here
366
62
			for xcm_asset_initialization in xcm_assets {
367
4
				let asset_id = xcm_asset_initialization.asset_id;
368
4
				EvmForeignAssets::create_foreign_asset(
369
4
					root_origin(),
370
4
					asset_id,
371
4
					xcm_asset_initialization.xcm_location.clone(),
372
4
					xcm_asset_initialization.decimals,
373
4
					xcm_asset_initialization
374
4
						.symbol
375
4
						.as_bytes()
376
4
						.to_vec()
377
4
						.try_into()
378
4
						.expect("too long"),
379
4
					xcm_asset_initialization
380
4
						.name
381
4
						.as_bytes()
382
4
						.to_vec()
383
4
						.try_into()
384
4
						.expect("too long"),
385
				)
386
4
				.expect("fail to create foreign asset");
387

            
388
4
				XcmWeightTrader::add_asset(
389
4
					root_origin(),
390
4
					xcm_asset_initialization.xcm_location,
391
					MOVR,
392
				)
393
4
				.expect("register evm native foreign asset as sufficient");
394

            
395
8
				for (account, balance) in xcm_asset_initialization.balances {
396
4
					if EvmForeignAssets::mint_into(asset_id, account, balance.into()).is_err() {
397
						panic!("fail to mint foreign asset");
398
4
					}
399
				}
400
			}
401
58
			System::set_block_number(1);
402
58
		});
403
58
		ext
404
58
	}
405
}
406

            
407
pub const CHAIN_ID: u64 = 1281;
408
pub const ALICE: [u8; 20] = [4u8; 20];
409
pub const ALICE_NIMBUS: [u8; 32] = [4u8; 32];
410
pub const BOB: [u8; 20] = [5u8; 20];
411
pub const CHARLIE: [u8; 20] = [6u8; 20];
412
pub const DAVE: [u8; 20] = [7u8; 20];
413
pub const EVM_CONTRACT: [u8; 20] = [8u8; 20];
414

            
415
18
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
416
18
	<Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
417
18
}
418

            
419
11
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
420
11
	<Runtime as frame_system::Config>::RuntimeOrigin::none()
421
11
}
422

            
423
19
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
424
19
	<Runtime as frame_system::Config>::RuntimeOrigin::root()
425
19
}
426

            
427
/// Mock the inherent that sets validation data in ParachainSystem, which
428
/// contains the `relay_chain_block_number`, which is used in `author-filter` as a
429
/// source of randomness to filter valid authors at each block.
430
11
pub fn set_parachain_inherent_data() {
431
	use cumulus_primitives_core::PersistedValidationData;
432
	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
433

            
434
11
	let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
435
11
	pallet_author_inherent::Author::<Runtime>::put(author);
436

            
437
11
	let mut relay_sproof = RelayStateSproofBuilder::default();
438
11
	relay_sproof.para_id = bp_moonriver::PARACHAIN_ID.into();
439
11
	relay_sproof.included_para_head = Some(HeadData(vec![1, 2, 3]));
440

            
441
11
	let additional_key_values = vec![];
442

            
443
11
	relay_sproof.additional_key_values = additional_key_values;
444

            
445
11
	let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
446

            
447
11
	let vfp = PersistedValidationData {
448
11
		relay_parent_number: 1u32,
449
11
		relay_parent_storage_root,
450
11
		..Default::default()
451
11
	};
452
11
	let parachain_inherent_data = ParachainInherentData {
453
11
		validation_data: vfp,
454
11
		relay_chain_state: relay_chain_state,
455
11
		downward_messages: Default::default(),
456
11
		horizontal_messages: Default::default(),
457
11
		collator_peer_id: Default::default(),
458
11
		relay_parent_descendants: Default::default(),
459
11
	};
460
11
	assert_ok!(RuntimeCall::ParachainSystem(
461
11
		cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
462
11
			data: parachain_inherent_data
463
11
		}
464
11
	)
465
11
	.dispatch(inherent_origin()));
466
11
}
467

            
468
7
pub fn unchecked_eth_tx(raw_hex_tx: &str) -> UncheckedExtrinsic {
469
7
	let converter = TransactionConverter;
470
7
	converter.convert_transaction(ethereum_transaction(raw_hex_tx))
471
7
}
472

            
473
9
pub fn ethereum_transaction(raw_hex_tx: &str) -> pallet_ethereum::Transaction {
474
9
	let bytes = hex::decode(raw_hex_tx).expect("Transaction bytes.");
475
9
	let transaction = ethereum::EnvelopedDecodable::decode(&bytes[..]);
476
9
	assert!(transaction.is_ok());
477
9
	transaction.unwrap()
478
9
}
479

            
480
6600
pub(crate) fn increase_last_relay_slot_number(amount: u64) {
481
6600
	let last_relay_slot = u64::from(AsyncBacking::slot_info().unwrap_or_default().0);
482
6600
	frame_support::storage::unhashed::put(
483
6600
		&frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
484
6600
		&((Slot::from(last_relay_slot + amount), 0)),
485
	);
486
6600
}