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
#![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 moonbeam_runtime::{
26
	asset_config::AssetRegistrarMetadata, currency::GLMR, xcm_config::AssetType, AccountId,
27
	AssetId, AssetManager, AsyncBacking, AuthorInherent, Balance, Ethereum, InflationInfo,
28
	ParachainStaking, Range, Runtime, RuntimeCall, RuntimeEvent, System, TransactionConverter,
29
	UncheckedExtrinsic, HOURS,
30
};
31
use nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID};
32
use polkadot_parachain::primitives::HeadData;
33
use sp_consensus_slots::Slot;
34
use sp_core::{Encode, H160};
35
use sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem, Perbill, Percent};
36

            
37
use std::collections::BTreeMap;
38

            
39
use fp_rpc::ConvertTransaction;
40

            
41
// A valid signed Alice transfer.
42
pub const VALID_ETH_TX: &str =
43
	"02f869820501808085e8d4a51000825208943cd0a705a2dc65e5b1e1205896baa2be8a07c6e00180c\
44
	001a061087911e877a5802142a89a40d231d50913db399eb50839bb2d04e612b22ec8a01aa313efdf2\
45
	793bea76da6813bda611444af16a6207a8cfef2d9c8aa8f8012f7";
46

            
47
// An invalid signed Alice transfer with a gas limit artifically set to 0.
48
pub const INVALID_ETH_TX: &str =
49
	"f8628085174876e800809412cb274aad8251c875c0bf6872b67d9983e53fdd01801ba011110796057\
50
	0e2d49fcc2afbc582e1abd3eeb027242b92abcebcec7cdefab63ea001732f6fac84acdd5b096554230\
51
	75003e7f07430652c3d6722e18f50b3d34e29";
52

            
53
3
pub fn rpc_run_to_block(n: u32) {
54
6
	while System::block_number() < n {
55
3
		Ethereum::on_finalize(System::block_number());
56
3
		System::set_block_number(System::block_number() + 1);
57
3
		Ethereum::on_initialize(System::block_number());
58
3
	}
59
3
}
60

            
61
/// Utility function that advances the chain to the desired block number.
62
/// If an author is provided, that author information is injected to all the blocks in the meantime.
63
8
pub fn run_to_block(n: u32, author: Option<NimbusId>) {
64
8
	// Finalize the first block
65
8
	Ethereum::on_finalize(System::block_number());
66
16208
	while System::block_number() < n {
67
		// Set the new block number and author
68
16200
		match author {
69
16200
			Some(ref author) => {
70
16200
				let pre_digest = Digest {
71
16200
					logs: vec![DigestItem::PreRuntime(NIMBUS_ENGINE_ID, author.encode())],
72
16200
				};
73
16200
				System::reset_events();
74
16200
				System::initialize(
75
16200
					&(System::block_number() + 1),
76
16200
					&System::parent_hash(),
77
16200
					&pre_digest,
78
16200
				);
79
16200
			}
80
			None => {
81
				System::set_block_number(System::block_number() + 1);
82
			}
83
		}
84

            
85
16200
		increase_last_relay_slot_number(1);
86
16200

            
87
16200
		// Initialize the new block
88
16200
		AuthorInherent::on_initialize(System::block_number());
89
16200
		ParachainStaking::on_initialize(System::block_number());
90
16200
		Ethereum::on_initialize(System::block_number());
91
16200

            
92
16200
		// Finalize the block
93
16200
		Ethereum::on_finalize(System::block_number());
94
16200
		ParachainStaking::on_finalize(System::block_number());
95
	}
96
8
}
97

            
98
3
pub fn last_event() -> RuntimeEvent {
99
3
	System::events().pop().expect("Event expected").event
100
3
}
101

            
102
// Helper function to give a simple evm context suitable for tests.
103
// We can remove this once https://github.com/rust-blockchain/evm/pull/35
104
// is in our dependency graph.
105
pub fn evm_test_context() -> fp_evm::Context {
106
	fp_evm::Context {
107
		address: Default::default(),
108
		caller: Default::default(),
109
		apparent_value: From::from(0),
110
	}
111
}
112

            
113
// Test struct with the purpose of initializing xcm assets
114
#[derive(Clone)]
115
pub struct XcmAssetInitialization {
116
	pub asset_type: AssetType,
117
	pub metadata: AssetRegistrarMetadata,
118
	pub balances: Vec<(AccountId, Balance)>,
119
	pub is_sufficient: bool,
120
}
121

            
122
pub struct ExtBuilder {
123
	// endowed accounts with balances
124
	balances: Vec<(AccountId, Balance)>,
125
	// [collator, amount]
126
	collators: Vec<(AccountId, Balance)>,
127
	// [delegator, collator, nomination_amount]
128
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
129
	// per-round inflation config
130
	inflation: InflationInfo<Balance>,
131
	// AuthorId -> AccountId mappings
132
	mappings: Vec<(NimbusId, AccountId)>,
133
	// Crowdloan fund
134
	crowdloan_fund: Balance,
135
	// Chain id
136
	chain_id: u64,
137
	// EVM genesis accounts
138
	evm_accounts: BTreeMap<H160, GenesisAccount>,
139
	// [assettype, metadata, Vec<Account, Balance,>, is_sufficient]
140
	xcm_assets: Vec<XcmAssetInitialization>,
141
	safe_xcm_version: Option<u32>,
142
}
143

            
144
impl Default for ExtBuilder {
145
61
	fn default() -> ExtBuilder {
146
61
		ExtBuilder {
147
61
			balances: vec![],
148
61
			delegations: vec![],
149
61
			collators: vec![],
150
61
			inflation: InflationInfo {
151
61
				expect: Range {
152
61
					min: 100_000 * GLMR,
153
61
					ideal: 200_000 * GLMR,
154
61
					max: 500_000 * GLMR,
155
61
				},
156
61
				// not used
157
61
				annual: Range {
158
61
					min: Perbill::from_percent(50),
159
61
					ideal: Perbill::from_percent(50),
160
61
					max: Perbill::from_percent(50),
161
61
				},
162
61
				// unrealistically high parameterization, only for testing
163
61
				round: Range {
164
61
					min: Perbill::from_percent(5),
165
61
					ideal: Perbill::from_percent(5),
166
61
					max: Perbill::from_percent(5),
167
61
				},
168
61
			},
169
61
			mappings: vec![],
170
61
			crowdloan_fund: 0,
171
61
			chain_id: CHAIN_ID,
172
61
			evm_accounts: BTreeMap::new(),
173
61
			xcm_assets: vec![],
174
61
			safe_xcm_version: None,
175
61
		}
176
61
	}
177
}
178

            
179
impl ExtBuilder {
180
2
	pub fn with_evm_accounts(mut self, accounts: BTreeMap<H160, GenesisAccount>) -> Self {
181
2
		self.evm_accounts = accounts;
182
2
		self
183
2
	}
184

            
185
42
	pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
186
42
		self.balances = balances;
187
42
		self
188
42
	}
189

            
190
17
	pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
191
17
		self.collators = collators;
192
17
		self
193
17
	}
194

            
195
7
	pub fn with_delegations(mut self, delegations: Vec<(AccountId, AccountId, Balance)>) -> Self {
196
7
		self.delegations = delegations
197
7
			.into_iter()
198
8
			.map(|d| (d.0, d.1, d.2, Percent::zero()))
199
7
			.collect();
200
7
		self
201
7
	}
202

            
203
6
	pub fn with_crowdloan_fund(mut self, crowdloan_fund: Balance) -> Self {
204
6
		self.crowdloan_fund = crowdloan_fund;
205
6
		self
206
6
	}
207

            
208
16
	pub fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
209
16
		self.mappings = mappings;
210
16
		self
211
16
	}
212

            
213
8
	pub fn with_xcm_assets(mut self, xcm_assets: Vec<XcmAssetInitialization>) -> Self {
214
8
		self.xcm_assets = xcm_assets;
215
8
		self
216
8
	}
217

            
218
7
	pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
219
7
		self.safe_xcm_version = Some(safe_xcm_version);
220
7
		self
221
7
	}
222

            
223
	#[allow(dead_code)]
224
	pub fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
225
		self.inflation = inflation;
226
		self
227
	}
228

            
229
61
	pub fn build(self) -> sp_io::TestExternalities {
230
61
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
231
61
			.build_storage()
232
61
			.unwrap();
233
61

            
234
61
		pallet_balances::GenesisConfig::<Runtime> {
235
61
			balances: self.balances,
236
61
		}
237
61
		.assimilate_storage(&mut t)
238
61
		.unwrap();
239
61

            
240
61
		pallet_parachain_staking::GenesisConfig::<Runtime> {
241
61
			candidates: self.collators,
242
61
			delegations: self.delegations,
243
61
			inflation_config: self.inflation,
244
61
			collator_commission: Perbill::from_percent(20),
245
61
			parachain_bond_reserve_percent: Percent::from_percent(30),
246
61
			blocks_per_round: 6 * HOURS,
247
61
			num_selected_candidates: 8,
248
61
		}
249
61
		.assimilate_storage(&mut t)
250
61
		.unwrap();
251
61

            
252
61
		pallet_crowdloan_rewards::GenesisConfig::<Runtime> {
253
61
			funded_amount: self.crowdloan_fund,
254
61
		}
255
61
		.assimilate_storage(&mut t)
256
61
		.unwrap();
257
61

            
258
61
		pallet_author_mapping::GenesisConfig::<Runtime> {
259
61
			mappings: self.mappings,
260
61
		}
261
61
		.assimilate_storage(&mut t)
262
61
		.unwrap();
263
61

            
264
61
		let genesis_config = pallet_evm_chain_id::GenesisConfig::<Runtime> {
265
61
			chain_id: self.chain_id,
266
61
			..Default::default()
267
61
		};
268
61
		genesis_config.assimilate_storage(&mut t).unwrap();
269
61

            
270
61
		let genesis_config = pallet_evm::GenesisConfig::<Runtime> {
271
61
			accounts: self.evm_accounts,
272
61
			..Default::default()
273
61
		};
274
61
		genesis_config.assimilate_storage(&mut t).unwrap();
275
61

            
276
61
		let genesis_config = pallet_ethereum::GenesisConfig::<Runtime> {
277
61
			..Default::default()
278
61
		};
279
61
		genesis_config.assimilate_storage(&mut t).unwrap();
280
61

            
281
61
		let genesis_config = pallet_xcm::GenesisConfig::<Runtime> {
282
61
			safe_xcm_version: self.safe_xcm_version,
283
61
			..Default::default()
284
61
		};
285
61
		genesis_config.assimilate_storage(&mut t).unwrap();
286
61

            
287
61
		let mut ext = sp_io::TestExternalities::new(t);
288
61
		let xcm_assets = self.xcm_assets.clone();
289
61
		ext.execute_with(|| {
290
			// If any xcm assets specified, we register them here
291
69
			for xcm_asset_initialization in xcm_assets {
292
8
				let asset_id: AssetId = xcm_asset_initialization.asset_type.clone().into();
293
8
				AssetManager::register_foreign_asset(
294
8
					root_origin(),
295
8
					xcm_asset_initialization.asset_type,
296
8
					xcm_asset_initialization.metadata,
297
8
					1,
298
8
					xcm_asset_initialization.is_sufficient,
299
8
				)
300
8
				.unwrap();
301
16
				for (account, balance) in xcm_asset_initialization.balances {
302
8
					moonbeam_runtime::Assets::mint(
303
8
						origin_of(AssetManager::account_id()),
304
8
						asset_id.into(),
305
8
						account,
306
8
						balance,
307
8
					)
308
8
					.unwrap();
309
8
				}
310
			}
311
61
			System::set_block_number(1);
312
61
		});
313
61
		ext
314
61
	}
315
}
316

            
317
pub const CHAIN_ID: u64 = 1281;
318
pub const ALICE: [u8; 20] = [4u8; 20];
319
pub const ALICE_NIMBUS: [u8; 32] = [4u8; 32];
320
pub const BOB: [u8; 20] = [5u8; 20];
321
pub const CHARLIE: [u8; 20] = [6u8; 20];
322
pub const DAVE: [u8; 20] = [7u8; 20];
323
pub const EVM_CONTRACT: [u8; 20] = [8u8; 20];
324

            
325
28
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
326
28
	<Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
327
28
}
328

            
329
11
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
330
11
	<Runtime as frame_system::Config>::RuntimeOrigin::none()
331
11
}
332

            
333
21
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
334
21
	<Runtime as frame_system::Config>::RuntimeOrigin::root()
335
21
}
336

            
337
/// Mock the inherent that sets validation data in ParachainSystem, which
338
/// contains the `relay_chain_block_number`, which is used in `author-filter` as a
339
/// source of randomness to filter valid authors at each block.
340
11
pub fn set_parachain_inherent_data() {
341
11
	use cumulus_primitives_core::PersistedValidationData;
342
11
	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
343
11

            
344
11
	let mut relay_sproof = RelayStateSproofBuilder::default();
345
11
	relay_sproof.para_id = 100u32.into();
346
11
	relay_sproof.included_para_head = Some(HeadData(vec![1, 2, 3]));
347
11

            
348
11
	let additional_key_values = vec![(
349
11
		moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW.to_vec(),
350
11
		sp_timestamp::Timestamp::default().encode(),
351
11
	)];
352
11

            
353
11
	relay_sproof.additional_key_values = additional_key_values;
354
11

            
355
11
	let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
356
11

            
357
11
	let vfp = PersistedValidationData {
358
11
		relay_parent_number: 1u32,
359
11
		relay_parent_storage_root,
360
11
		..Default::default()
361
11
	};
362
11
	let parachain_inherent_data = ParachainInherentData {
363
11
		validation_data: vfp,
364
11
		relay_chain_state: relay_chain_state,
365
11
		downward_messages: Default::default(),
366
11
		horizontal_messages: Default::default(),
367
11
	};
368
11
	assert_ok!(RuntimeCall::ParachainSystem(
369
11
		cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
370
11
			data: parachain_inherent_data
371
11
		}
372
11
	)
373
11
	.dispatch(inherent_origin()));
374
11
}
375

            
376
7
pub fn unchecked_eth_tx(raw_hex_tx: &str) -> UncheckedExtrinsic {
377
7
	let converter = TransactionConverter;
378
7
	converter.convert_transaction(ethereum_transaction(raw_hex_tx))
379
7
}
380

            
381
9
pub fn ethereum_transaction(raw_hex_tx: &str) -> pallet_ethereum::Transaction {
382
9
	let bytes = hex::decode(raw_hex_tx).expect("Transaction bytes.");
383
9
	let transaction = ethereum::EnvelopedDecodable::decode(&bytes[..]);
384
9
	assert!(transaction.is_ok());
385
9
	transaction.unwrap()
386
9
}
387

            
388
16202
pub fn increase_last_relay_slot_number(amount: u64) {
389
16202
	let last_relay_slot = u64::from(AsyncBacking::slot_info().unwrap_or_default().0);
390
16202
	frame_support::storage::unhashed::put(
391
16202
		&frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
392
16202
		&((Slot::from(last_relay_slot + amount), 0)),
393
16202
	);
394
16202
}