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

            
19
use ethereum::{TransactionAction, TransactionSignature};
20
use frame_support::{
21
	parameter_types,
22
	traits::{ConstU32, FindAuthor, InstanceFilter},
23
	weights::Weight,
24
	ConsensusEngineId, PalletId,
25
};
26
use frame_system::{pallet_prelude::BlockNumberFor, EnsureRoot};
27
use pallet_evm::{AddressMapping, EnsureAddressTruncated, FeeCalculator};
28
use rlp::RlpStream;
29
use sp_core::{hashing::keccak_256, H160, H256, U256};
30
use sp_runtime::{
31
	traits::{BlakeTwo256, IdentityLookup},
32
	AccountId32, BuildStorage,
33
};
34

            
35
use super::*;
36
use pallet_ethereum::{IntermediateStateRoot, PostLogContent};
37
use sp_runtime::{
38
	traits::DispatchInfoOf,
39
	transaction_validity::{TransactionValidity, TransactionValidityError},
40
};
41

            
42
pub type BlockNumber = BlockNumberFor<Test>;
43

            
44
type Block = frame_system::mocking::MockBlock<Test>;
45

            
46
2330
frame_support::construct_runtime! {
47
	pub enum Test
48
	{
49
		System: frame_system,
50
		Balances: pallet_balances,
51
		Timestamp: pallet_timestamp,
52
		EVM: pallet_evm,
53
		Ethereum: pallet_ethereum,
54
		EthereumXcm: crate,
55
		Proxy: pallet_proxy,
56
	}
57
4126
}
58

            
59
parameter_types! {
60
	pub const BlockHashCount: u32 = 250;
61
	pub BlockWeights: frame_system::limits::BlockWeights =
62
		frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 1));
63
}
64

            
65
impl frame_system::Config for Test {
66
	type BaseCallFilter = frame_support::traits::Everything;
67
	type BlockWeights = ();
68
	type BlockLength = ();
69
	type DbWeight = ();
70
	type RuntimeOrigin = RuntimeOrigin;
71
	type RuntimeTask = RuntimeTask;
72
	type Nonce = u64;
73
	type Block = Block;
74
	type Hash = H256;
75
	type RuntimeCall = RuntimeCall;
76
	type Hashing = BlakeTwo256;
77
	type AccountId = AccountId32;
78
	type Lookup = IdentityLookup<Self::AccountId>;
79
	type RuntimeEvent = RuntimeEvent;
80
	type BlockHashCount = BlockHashCount;
81
	type Version = ();
82
	type PalletInfo = PalletInfo;
83
	type AccountData = pallet_balances::AccountData<u64>;
84
	type OnNewAccount = ();
85
	type OnKilledAccount = ();
86
	type SystemWeightInfo = ();
87
	type SS58Prefix = ();
88
	type OnSetCode = ();
89
	type MaxConsumers = ConstU32<16>;
90
	type SingleBlockMigrations = ();
91
	type MultiBlockMigrator = ();
92
	type PreInherents = ();
93
	type PostInherents = ();
94
	type PostTransactions = ();
95
}
96

            
97
parameter_types! {
98
	// For weight estimation, we assume that the most locks on an individual account will be 50.
99
	// This number may need to be adjusted in the future if this assumption no longer holds true.
100
	pub const MaxLocks: u32 = 50;
101
	pub const ExistentialDeposit: u64 = 500;
102
}
103

            
104
impl pallet_balances::Config for Test {
105
	type MaxLocks = MaxLocks;
106
	type Balance = u64;
107
	type RuntimeEvent = RuntimeEvent;
108
	type DustRemoval = ();
109
	type ExistentialDeposit = ExistentialDeposit;
110
	type AccountStore = System;
111
	type WeightInfo = ();
112
	type MaxReserves = ();
113
	type ReserveIdentifier = ();
114
	type RuntimeHoldReason = ();
115
	type FreezeIdentifier = ();
116
	type MaxFreezes = ();
117
	type RuntimeFreezeReason = ();
118
}
119

            
120
parameter_types! {
121
	pub const MinimumPeriod: u64 = 6000 / 2;
122
}
123

            
124
impl pallet_timestamp::Config for Test {
125
	type Moment = u64;
126
	type OnTimestampSet = ();
127
	type MinimumPeriod = MinimumPeriod;
128
	type WeightInfo = ();
129
}
130

            
131
pub struct FixedGasPrice;
132
impl FeeCalculator for FixedGasPrice {
133
38
	fn min_gas_price() -> (U256, Weight) {
134
38
		(1.into(), Weight::zero())
135
38
	}
136
}
137

            
138
pub struct FindAuthorTruncated;
139
impl FindAuthor<H160> for FindAuthorTruncated {
140
43
	fn find_author<'a, I>(_digests: I) -> Option<H160>
141
43
	where
142
43
		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
143
43
	{
144
43
		Some(address_build(0).address)
145
43
	}
146
}
147

            
148
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
149
/// Block storage limit in bytes. Set to 40 KB.
150
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
151

            
152
parameter_types! {
153
	pub const TransactionByteFee: u64 = 1;
154
	pub const ChainId: u64 = 42;
155
	pub const EVMModuleId: PalletId = PalletId(*b"py/evmpa");
156
	pub const BlockGasLimit: U256 = U256::MAX;
157
	pub WeightPerGas: Weight = Weight::from_parts(1, 0);
158
	pub GasLimitPovSizeRatio: u64 = {
159
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
160
		block_gas_limit.saturating_div(MAX_POV_SIZE)
161
	};
162
	pub GasLimitStorageGrowthRatio: u64 = {
163
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
164
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
165
	};
166
}
167

            
168
pub struct HashedAddressMapping;
169

            
170
impl AddressMapping<AccountId32> for HashedAddressMapping {
171
188
	fn into_account_id(address: H160) -> AccountId32 {
172
188
		let mut data = [0u8; 32];
173
188
		data[0..20].copy_from_slice(&address[..]);
174
188
		AccountId32::from(Into::<[u8; 32]>::into(data))
175
188
	}
176
}
177

            
178
impl pallet_evm::Config for Test {
179
	type FeeCalculator = FixedGasPrice;
180
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
181
	type WeightPerGas = WeightPerGas;
182
	type CallOrigin = EnsureAddressTruncated;
183
	type WithdrawOrigin = EnsureAddressTruncated;
184
	type AddressMapping = HashedAddressMapping;
185
	type Currency = Balances;
186
	type RuntimeEvent = RuntimeEvent;
187
	type PrecompilesType = ();
188
	type PrecompilesValue = ();
189
	type Runner = pallet_evm::runner::stack::Runner<Self>;
190
	type ChainId = ChainId;
191
	type BlockGasLimit = BlockGasLimit;
192
	type OnChargeTransaction = ();
193
	type FindAuthor = FindAuthorTruncated;
194
	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
195
	type OnCreate = ();
196
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
197
	type SuicideQuickClearLimit = ConstU32<0>;
198
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
199
	type Timestamp = Timestamp;
200
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Test>;
201
}
202

            
203
parameter_types! {
204
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
205
}
206

            
207
impl pallet_ethereum::Config for Test {
208
	type RuntimeEvent = RuntimeEvent;
209
	type StateRoot = IntermediateStateRoot<Self>;
210
	type PostLogContent = PostBlockAndTxnHashes;
211
	type ExtraDataLength = ConstU32<30>;
212
}
213

            
214
parameter_types! {
215
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 1);
216
}
217

            
218
#[derive(
219
	Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
220
)]
221
pub enum ProxyType {
222
4
	NotAllowed = 0,
223
9
	Any = 1,
224
}
225

            
226
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
227

            
228
impl InstanceFilter<RuntimeCall> for ProxyType {
229
	fn filter(&self, _c: &RuntimeCall) -> bool {
230
		match self {
231
			ProxyType::NotAllowed => false,
232
			ProxyType::Any => true,
233
		}
234
	}
235
	fn is_superset(&self, _o: &Self) -> bool {
236
		false
237
	}
238
}
239

            
240
impl Default for ProxyType {
241
	fn default() -> Self {
242
		Self::NotAllowed
243
	}
244
}
245

            
246
parameter_types! {
247
	pub const ProxyCost: u64 = 1;
248
}
249

            
250
impl pallet_proxy::Config for Test {
251
	type RuntimeEvent = RuntimeEvent;
252
	type RuntimeCall = RuntimeCall;
253
	type Currency = Balances;
254
	type ProxyType = ProxyType;
255
	type ProxyDepositBase = ProxyCost;
256
	type ProxyDepositFactor = ProxyCost;
257
	type MaxProxies = ConstU32<32>;
258
	type WeightInfo = pallet_proxy::weights::SubstrateWeight<Test>;
259
	type MaxPending = ConstU32<32>;
260
	type CallHasher = BlakeTwo256;
261
	type AnnouncementDepositBase = ProxyCost;
262
	type AnnouncementDepositFactor = ProxyCost;
263
}
264

            
265
pub struct EthereumXcmEnsureProxy;
266
impl xcm_primitives::EnsureProxy<AccountId32> for EthereumXcmEnsureProxy {
267
13
	fn ensure_ok(delegator: AccountId32, delegatee: AccountId32) -> Result<(), &'static str> {
268
13
		let f = |x: &pallet_proxy::ProxyDefinition<AccountId32, ProxyType, BlockNumber>| -> bool {
269
9
			x.delegate == delegatee && (x.proxy_type == ProxyType::Any)
270
9
		};
271
13
		Proxy::proxies(delegator)
272
13
			.0
273
13
			.into_iter()
274
13
			.find(f)
275
13
			.map(|_| ())
276
13
			.ok_or("proxy error: expected `ProxyType::Any`")
277
13
	}
278
}
279

            
280
impl crate::Config for Test {
281
	type RuntimeEvent = RuntimeEvent;
282
	type InvalidEvmTransactionError = pallet_ethereum::InvalidTransactionWrapper;
283
	type ValidatedTransaction = pallet_ethereum::ValidatedTransaction<Self>;
284
	type XcmEthereumOrigin = crate::EnsureXcmEthereumTransaction;
285
	type ReservedXcmpWeight = ReservedXcmpWeight;
286
	type EnsureProxy = EthereumXcmEnsureProxy;
287
	type ControllerOrigin = EnsureRoot<AccountId32>;
288
	type ForceOrigin = EnsureRoot<AccountId32>;
289
}
290

            
291
impl fp_self_contained::SelfContainedCall for RuntimeCall {
292
	type SignedInfo = H160;
293

            
294
	fn is_self_contained(&self) -> bool {
295
		match self {
296
			RuntimeCall::Ethereum(call) => call.is_self_contained(),
297
			_ => false,
298
		}
299
	}
300

            
301
	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
302
		match self {
303
			RuntimeCall::Ethereum(call) => call.check_self_contained(),
304
			_ => None,
305
		}
306
	}
307

            
308
	fn validate_self_contained(
309
		&self,
310
		info: &Self::SignedInfo,
311
		dispatch_info: &DispatchInfoOf<RuntimeCall>,
312
		len: usize,
313
	) -> Option<TransactionValidity> {
314
		match self {
315
			RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
316
			_ => None,
317
		}
318
	}
319

            
320
	fn pre_dispatch_self_contained(
321
		&self,
322
		info: &Self::SignedInfo,
323
		dispatch_info: &DispatchInfoOf<RuntimeCall>,
324
		len: usize,
325
	) -> Option<Result<(), TransactionValidityError>> {
326
		match self {
327
			RuntimeCall::Ethereum(call) => {
328
				call.pre_dispatch_self_contained(info, dispatch_info, len)
329
			}
330
			_ => None,
331
		}
332
	}
333

            
334
	fn apply_self_contained(
335
		self,
336
		info: Self::SignedInfo,
337
	) -> Option<sp_runtime::DispatchResultWithInfo<sp_runtime::traits::PostDispatchInfoOf<Self>>> {
338
		use sp_runtime::traits::Dispatchable as _;
339
		match self {
340
			call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
341
				Some(call.dispatch(RuntimeOrigin::from(
342
					pallet_ethereum::RawOrigin::EthereumTransaction(info),
343
				)))
344
			}
345
			_ => None,
346
		}
347
	}
348
}
349

            
350
pub struct AccountInfo {
351
	pub address: H160,
352
	pub account_id: AccountId32,
353
	pub private_key: H256,
354
}
355

            
356
138
fn address_build(seed: u8) -> AccountInfo {
357
138
	let private_key = H256::from_slice(&[(seed + 1) as u8; 32]);
358
138
	let secret_key = libsecp256k1::SecretKey::parse_slice(&private_key[..]).unwrap();
359
138
	let public_key = &libsecp256k1::PublicKey::from_secret_key(&secret_key).serialize()[1..65];
360
138
	let address = H160::from(H256::from(keccak_256(public_key)));
361
138

            
362
138
	let mut data = [0u8; 32];
363
138
	data[0..20].copy_from_slice(&address[..]);
364
138

            
365
138
	AccountInfo {
366
138
		private_key,
367
138
		account_id: AccountId32::from(Into::<[u8; 32]>::into(data)),
368
138
		address,
369
138
	}
370
138
}
371

            
372
// This function basically just builds a genesis storage key/value store according to
373
// our desired mockup.
374
43
pub fn new_test_ext(accounts_len: usize) -> (Vec<AccountInfo>, sp_io::TestExternalities) {
375
43
	// sc_cli::init_logger("");
376
43
	let mut ext = frame_system::GenesisConfig::<Test>::default()
377
43
		.build_storage()
378
43
		.unwrap();
379
43

            
380
43
	let pairs = (0..accounts_len)
381
95
		.map(|i| address_build(i as u8))
382
43
		.collect::<Vec<_>>();
383
43

            
384
43
	let balances: Vec<_> = (0..accounts_len)
385
95
		.map(|i| (pairs[i].account_id.clone(), 10_000_000))
386
43
		.collect();
387
43

            
388
43
	pallet_balances::GenesisConfig::<Test> { balances }
389
43
		.assimilate_storage(&mut ext)
390
43
		.unwrap();
391
43

            
392
43
	(pairs, ext.into())
393
43
}
394

            
395
pub struct LegacyUnsignedTransaction {
396
	pub nonce: U256,
397
	pub gas_price: U256,
398
	pub gas_limit: U256,
399
	pub action: TransactionAction,
400
	pub value: U256,
401
	pub input: Vec<u8>,
402
}
403

            
404
impl LegacyUnsignedTransaction {
405
1
	fn signing_rlp_append(&self, s: &mut RlpStream) {
406
1
		s.begin_list(9);
407
1
		s.append(&self.nonce);
408
1
		s.append(&self.gas_price);
409
1
		s.append(&self.gas_limit);
410
1
		s.append(&self.action);
411
1
		s.append(&self.value);
412
1
		s.append(&self.input);
413
1
		s.append(&ChainId::get());
414
1
		s.append(&0u8);
415
1
		s.append(&0u8);
416
1
	}
417

            
418
1
	fn signing_hash(&self) -> H256 {
419
1
		let mut stream = RlpStream::new();
420
1
		self.signing_rlp_append(&mut stream);
421
1
		H256::from(keccak_256(&stream.out()))
422
1
	}
423

            
424
1
	pub fn sign(&self, key: &H256) -> Transaction {
425
1
		self.sign_with_chain_id(key, ChainId::get())
426
1
	}
427

            
428
1
	pub fn sign_with_chain_id(&self, key: &H256, chain_id: u64) -> Transaction {
429
1
		let hash = self.signing_hash();
430
1
		let msg = libsecp256k1::Message::parse(hash.as_fixed_bytes());
431
1
		let s = libsecp256k1::sign(
432
1
			&msg,
433
1
			&libsecp256k1::SecretKey::parse_slice(&key[..]).unwrap(),
434
1
		);
435
1
		let sig = s.0.serialize();
436
1

            
437
1
		let sig = TransactionSignature::new(
438
1
			s.1.serialize() as u64 % 2 + chain_id * 2 + 35,
439
1
			H256::from_slice(&sig[0..32]),
440
1
			H256::from_slice(&sig[32..64]),
441
1
		)
442
1
		.unwrap();
443
1

            
444
1
		Transaction::Legacy(ethereum::LegacyTransaction {
445
1
			nonce: self.nonce,
446
1
			gas_price: self.gas_price,
447
1
			gas_limit: self.gas_limit,
448
1
			action: self.action,
449
1
			value: self.value,
450
1
			input: self.input.clone(),
451
1
			signature: sig,
452
1
		})
453
1
	}
454
}
455

            
456
pub struct EIP2930UnsignedTransaction {
457
	pub nonce: U256,
458
	pub gas_price: U256,
459
	pub gas_limit: U256,
460
	pub action: TransactionAction,
461
	pub value: U256,
462
	pub input: Vec<u8>,
463
}
464

            
465
impl EIP2930UnsignedTransaction {
466
1
	pub fn sign(&self, secret: &H256, chain_id: Option<u64>) -> Transaction {
467
1
		let secret = {
468
1
			let mut sk: [u8; 32] = [0u8; 32];
469
1
			sk.copy_from_slice(&secret[0..]);
470
1
			libsecp256k1::SecretKey::parse(&sk).unwrap()
471
1
		};
472
1
		let chain_id = chain_id.unwrap_or(ChainId::get());
473
1
		let msg = ethereum::EIP2930TransactionMessage {
474
1
			chain_id,
475
1
			nonce: self.nonce,
476
1
			gas_price: self.gas_price,
477
1
			gas_limit: self.gas_limit,
478
1
			action: self.action,
479
1
			value: self.value,
480
1
			input: self.input.clone(),
481
1
			access_list: vec![],
482
1
		};
483
1
		let signing_message = libsecp256k1::Message::parse_slice(&msg.hash()[..]).unwrap();
484
1

            
485
1
		let (signature, recid) = libsecp256k1::sign(&signing_message, &secret);
486
1
		let rs = signature.serialize();
487
1
		let r = H256::from_slice(&rs[0..32]);
488
1
		let s = H256::from_slice(&rs[32..64]);
489
1
		Transaction::EIP2930(ethereum::EIP2930Transaction {
490
1
			chain_id: msg.chain_id,
491
1
			nonce: msg.nonce,
492
1
			gas_price: msg.gas_price,
493
1
			gas_limit: msg.gas_limit,
494
1
			action: msg.action,
495
1
			value: msg.value,
496
1
			input: msg.input.clone(),
497
1
			access_list: msg.access_list,
498
1
			odd_y_parity: recid.serialize() != 0,
499
1
			r,
500
1
			s,
501
1
		})
502
1
	}
503
}
504

            
505
pub struct EIP1559UnsignedTransaction {
506
	pub nonce: U256,
507
	pub max_priority_fee_per_gas: U256,
508
	pub max_fee_per_gas: U256,
509
	pub gas_limit: U256,
510
	pub action: TransactionAction,
511
	pub value: U256,
512
	pub input: Vec<u8>,
513
}
514

            
515
impl EIP1559UnsignedTransaction {
516
2
	pub fn sign(&self, secret: &H256, chain_id: Option<u64>) -> Transaction {
517
2
		let secret = {
518
2
			let mut sk: [u8; 32] = [0u8; 32];
519
2
			sk.copy_from_slice(&secret[0..]);
520
2
			libsecp256k1::SecretKey::parse(&sk).unwrap()
521
2
		};
522
2
		let chain_id = chain_id.unwrap_or(ChainId::get());
523
2
		let msg = ethereum::EIP1559TransactionMessage {
524
2
			chain_id,
525
2
			nonce: self.nonce,
526
2
			max_priority_fee_per_gas: self.max_priority_fee_per_gas,
527
2
			max_fee_per_gas: self.max_fee_per_gas,
528
2
			gas_limit: self.gas_limit,
529
2
			action: self.action,
530
2
			value: self.value,
531
2
			input: self.input.clone(),
532
2
			access_list: vec![],
533
2
		};
534
2
		let signing_message = libsecp256k1::Message::parse_slice(&msg.hash()[..]).unwrap();
535
2

            
536
2
		let (signature, recid) = libsecp256k1::sign(&signing_message, &secret);
537
2
		let rs = signature.serialize();
538
2
		let r = H256::from_slice(&rs[0..32]);
539
2
		let s = H256::from_slice(&rs[32..64]);
540
2
		Transaction::EIP1559(ethereum::EIP1559Transaction {
541
2
			chain_id: msg.chain_id,
542
2
			nonce: msg.nonce,
543
2
			max_priority_fee_per_gas: msg.max_priority_fee_per_gas,
544
2
			max_fee_per_gas: msg.max_fee_per_gas,
545
2
			gas_limit: msg.gas_limit,
546
2
			action: msg.action,
547
2
			value: msg.value,
548
2
			input: msg.input.clone(),
549
2
			access_list: msg.access_list,
550
2
			odd_y_parity: recid.serialize() != 0,
551
2
			r,
552
2
			s,
553
2
		})
554
2
	}
555
}