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 fp_evm::GenesisAccount;
20
use frame_support::{
21
	assert_ok,
22
	traits::{OnFinalize, OnInitialize},
23
};
24
pub use moonbeam_runtime::{
25
	currency::GLMR, AccountId, AsyncBacking, AuthorInherent, Balance, Ethereum, InflationInfo,
26
	ParachainStaking, Range, Runtime, RuntimeCall, RuntimeEvent, System, TransactionConverter,
27
	UncheckedExtrinsic, HOURS,
28
};
29
use nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID};
30
use polkadot_parachain::primitives::HeadData;
31
use sp_consensus_slots::Slot;
32
use sp_core::{Encode, H160};
33
use sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem, Perbill, Percent};
34

            
35
use cumulus_pallet_parachain_system::{
36
	parachain_inherent::{BasicParachainInherentData, InboundMessagesData},
37
	MessagingStateSnapshot,
38
};
39
use cumulus_primitives_core::relay_chain::{AbridgedHostConfiguration, AsyncBackingParams};
40
use cumulus_primitives_core::AbridgedHrmpChannel;
41
use fp_rpc::ConvertTransaction;
42
use moonbeam_runtime::bridge_config::XcmOverKusamaInstance;
43
use moonbeam_runtime::{EvmForeignAssets, XcmWeightTrader};
44
use std::collections::BTreeMap;
45
use xcm::latest::{InteriorLocation, Location};
46

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

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

            
70
// A valid signed Alice transfer.
71
pub const VALID_ETH_TX: &str =
72
	"02f869820501808085e8d4a51000825208943cd0a705a2dc65e5b1e1205896baa2be8a07c6e00180c\
73
	001a061087911e877a5802142a89a40d231d50913db399eb50839bb2d04e612b22ec8a01aa313efdf2\
74
	793bea76da6813bda611444af16a6207a8cfef2d9c8aa8f8012f7";
75

            
76
// An invalid signed Alice transfer with a gas limit artifically set to 0.
77
pub const INVALID_ETH_TX: &str =
78
	"f8628085174876e800809412cb274aad8251c875c0bf6872b67d9983e53fdd01801ba011110796057\
79
	0e2d49fcc2afbc582e1abd3eeb027242b92abcebcec7cdefab63ea001732f6fac84acdd5b096554230\
80
	75003e7f07430652c3d6722e18f50b3d34e29";
81

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

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

            
112
16198
		increase_last_relay_slot_number(1);
113

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

            
118
		// Finalize the block
119
16198
		ParachainStaking::on_finalize(System::block_number());
120
	}
121
8
}
122

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

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

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

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

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

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

            
216
37
	pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
217
37
		self.balances = balances;
218
37
		self
219
37
	}
220

            
221
11
	pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
222
11
		self.collators = collators;
223
11
		self
224
11
	}
225

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

            
234
	pub fn with_crowdloan_fund(mut self, crowdloan_fund: Balance) -> Self {
235
		self.crowdloan_fund = crowdloan_fund;
236
		self
237
	}
238

            
239
10
	pub fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
240
10
		self.mappings = mappings;
241
10
		self
242
10
	}
243

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

            
249
	pub fn with_evm_native_foreign_assets(mut self) -> Self {
250
		self.evm_native_foreign_assets = true;
251
		self
252
	}
253

            
254
7
	pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
255
7
		self.safe_xcm_version = Some(safe_xcm_version);
256
7
		self
257
7
	}
258

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

            
267
	#[allow(dead_code)]
268
	pub fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
269
		self.inflation = inflation;
270
		self
271
	}
272

            
273
59
	pub fn build(self) -> sp_io::TestExternalities {
274
59
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
275
59
			.build_storage()
276
59
			.unwrap();
277

            
278
59
		parachain_info::GenesisConfig::<Runtime> {
279
59
			parachain_id: <bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID.into(),
280
59
			_config: Default::default(),
281
59
		}
282
59
		.assimilate_storage(&mut t)
283
59
		.unwrap();
284

            
285
59
		pallet_balances::GenesisConfig::<Runtime> {
286
59
			balances: self.balances,
287
59
			dev_accounts: None,
288
59
		}
289
59
		.assimilate_storage(&mut t)
290
59
		.unwrap();
291

            
292
59
		pallet_parachain_staking::GenesisConfig::<Runtime> {
293
59
			candidates: self.collators,
294
59
			delegations: self.delegations,
295
59
			inflation_config: self.inflation,
296
59
			collator_commission: Perbill::from_percent(20),
297
59
			parachain_bond_reserve_percent: Percent::from_percent(30),
298
59
			blocks_per_round: 6 * HOURS,
299
59
			num_selected_candidates: 8,
300
59
		}
301
59
		.assimilate_storage(&mut t)
302
59
		.unwrap();
303

            
304
59
		pallet_author_mapping::GenesisConfig::<Runtime> {
305
59
			mappings: self.mappings,
306
59
		}
307
59
		.assimilate_storage(&mut t)
308
59
		.unwrap();
309

            
310
59
		let genesis_config = pallet_evm_chain_id::GenesisConfig::<Runtime> {
311
59
			chain_id: self.chain_id,
312
59
			..Default::default()
313
59
		};
314
59
		genesis_config.assimilate_storage(&mut t).unwrap();
315

            
316
59
		let genesis_config = pallet_evm::GenesisConfig::<Runtime> {
317
59
			accounts: self.evm_accounts,
318
59
			..Default::default()
319
59
		};
320
59
		genesis_config.assimilate_storage(&mut t).unwrap();
321

            
322
59
		let genesis_config = pallet_ethereum::GenesisConfig::<Runtime> {
323
59
			..Default::default()
324
59
		};
325
59
		genesis_config.assimilate_storage(&mut t).unwrap();
326

            
327
59
		let genesis_config = pallet_xcm::GenesisConfig::<Runtime> {
328
59
			safe_xcm_version: self.safe_xcm_version,
329
59
			..Default::default()
330
59
		};
331
59
		genesis_config.assimilate_storage(&mut t).unwrap();
332

            
333
59
		let genesis_config = pallet_xcm_bridge::GenesisConfig::<Runtime, XcmOverKusamaInstance> {
334
59
			opened_bridges: self.opened_bridges,
335
59
			_phantom: Default::default(),
336
59
		};
337
59
		genesis_config.assimilate_storage(&mut t).unwrap();
338

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

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

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

            
390
4
				XcmWeightTrader::add_asset(
391
4
					root_origin(),
392
4
					xcm_asset_initialization.xcm_location,
393
					GLMR,
394
				)
395
4
				.expect("failed to register asset in weight trader");
396

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

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

            
417
20
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
418
20
	<Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
419
20
}
420

            
421
12
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
422
12
	<Runtime as frame_system::Config>::RuntimeOrigin::none()
423
12
}
424

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

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

            
436
12
	let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
437
12
	pallet_author_inherent::Author::<Runtime>::put(author);
438

            
439
12
	let mut relay_sproof = RelayStateSproofBuilder::default();
440
12
	relay_sproof.para_id = bp_moonbeam::PARACHAIN_ID.into();
441
12
	relay_sproof.included_para_head = Some(HeadData(vec![1, 2, 3]));
442

            
443
12
	let additional_key_values = vec![];
444

            
445
12
	relay_sproof.additional_key_values = additional_key_values;
446

            
447
12
	let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
448

            
449
12
	let vfp = PersistedValidationData {
450
12
		relay_parent_number: 1u32,
451
12
		relay_parent_storage_root,
452
12
		..Default::default()
453
12
	};
454
12
	let data = BasicParachainInherentData {
455
12
		validation_data: vfp,
456
12
		relay_chain_state,
457
12
		collator_peer_id: Default::default(),
458
12
		relay_parent_descendants: Default::default(),
459
12
	};
460

            
461
12
	let inbound_messages_data = InboundMessagesData {
462
12
		downward_messages: Default::default(),
463
12
		horizontal_messages: Default::default(),
464
12
	};
465

            
466
12
	assert_ok!(RuntimeCall::ParachainSystem(
467
12
		cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
468
12
			data,
469
12
			inbound_messages_data
470
12
		}
471
12
	)
472
12
	.dispatch(inherent_origin()));
473
12
}
474

            
475
7
pub fn unchecked_eth_tx(raw_hex_tx: &str) -> UncheckedExtrinsic {
476
7
	let converter = TransactionConverter;
477
7
	converter.convert_transaction(ethereum_transaction(raw_hex_tx))
478
7
}
479

            
480
9
pub fn ethereum_transaction(raw_hex_tx: &str) -> pallet_ethereum::Transaction {
481
9
	let bytes = hex::decode(raw_hex_tx).expect("Transaction bytes.");
482
9
	let transaction = ethereum::EnvelopedDecodable::decode(&bytes[..]);
483
9
	assert!(transaction.is_ok());
484
9
	transaction.unwrap()
485
9
}
486

            
487
16200
pub fn increase_last_relay_slot_number(amount: u64) {
488
16200
	let last_relay_slot = u64::from(AsyncBacking::slot_info().unwrap_or_default().0);
489
16200
	frame_support::storage::unhashed::put(
490
16200
		&frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
491
16200
		&((Slot::from(last_relay_slot + amount), 0)),
492
	);
493
16200
}