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
//! 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::{
28
	AddressMapping, EnsureAddressTruncated, FeeCalculator, FrameSystemAccountProvider,
29
};
30
use rlp::RlpStream;
31
use sp_core::{hashing::keccak_256, H160, H256, U256};
32
use sp_runtime::{
33
	traits::{BlakeTwo256, IdentityLookup},
34
	AccountId32, BuildStorage,
35
};
36

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

            
44
pub type BlockNumber = BlockNumberFor<Test>;
45

            
46
type Block = frame_system::mocking::MockBlock<Test>;
47

            
48
2470
frame_support::construct_runtime! {
49
405
	pub enum Test
50
405
	{
51
405
		System: frame_system,
52
405
		Balances: pallet_balances,
53
405
		Timestamp: pallet_timestamp,
54
405
		EVM: pallet_evm,
55
405
		Ethereum: pallet_ethereum,
56
405
		EthereumXcm: crate,
57
405
		Proxy: pallet_proxy,
58
405
	}
59
2532
}
60

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

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

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

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

            
124
parameter_types! {
125
	pub const MinimumPeriod: u64 = 6000 / 2;
126
}
127

            
128
impl pallet_timestamp::Config for Test {
129
	type Moment = u64;
130
	type OnTimestampSet = ();
131
	type MinimumPeriod = MinimumPeriod;
132
	type WeightInfo = ();
133
}
134

            
135
pub struct FixedGasPrice;
136
impl FeeCalculator for FixedGasPrice {
137
38
	fn min_gas_price() -> (U256, Weight) {
138
38
		(1.into(), Weight::zero())
139
38
	}
140
}
141

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

            
152
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
153
/// Block storage limit in bytes. Set to 40 KB.
154
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
155

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

            
172
pub struct HashedAddressMapping;
173

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

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

            
207
parameter_types! {
208
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
209
}
210

            
211
impl pallet_ethereum::Config for Test {
212
	type RuntimeEvent = RuntimeEvent;
213
	type StateRoot = IntermediateStateRoot<<Test as frame_system::Config>::Version>;
214
	type PostLogContent = PostBlockAndTxnHashes;
215
	type ExtraDataLength = ConstU32<30>;
216
}
217

            
218
parameter_types! {
219
	pub ReservedXcmpWeight: Weight = Weight::from_parts(u64::max_value(), 1);
220
}
221

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

            
230
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {}
231

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

            
244
impl Default for ProxyType {
245
	fn default() -> Self {
246
		Self::NotAllowed
247
	}
248
}
249

            
250
parameter_types! {
251
	pub const ProxyCost: u64 = 1;
252
}
253

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

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

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

            
295
impl fp_self_contained::SelfContainedCall for RuntimeCall {
296
	type SignedInfo = H160;
297

            
298
	fn is_self_contained(&self) -> bool {
299
		match self {
300
			RuntimeCall::Ethereum(call) => call.is_self_contained(),
301
			_ => false,
302
		}
303
	}
304

            
305
	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
306
		match self {
307
			RuntimeCall::Ethereum(call) => call.check_self_contained(),
308
			_ => None,
309
		}
310
	}
311

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

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

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

            
354
pub struct AccountInfo {
355
	pub address: H160,
356
	pub account_id: AccountId32,
357
	pub private_key: H256,
358
}
359

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

            
366
138
	let mut data = [0u8; 32];
367
138
	data[0..20].copy_from_slice(&address[..]);
368
138

            
369
138
	AccountInfo {
370
138
		private_key,
371
138
		account_id: AccountId32::from(Into::<[u8; 32]>::into(data)),
372
138
		address,
373
138
	}
374
138
}
375

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

            
384
43
	let pairs = (0..accounts_len)
385
95
		.map(|i| address_build(i as u8))
386
43
		.collect::<Vec<_>>();
387
43

            
388
43
	let balances: Vec<_> = (0..accounts_len)
389
95
		.map(|i| (pairs[i].account_id.clone(), 10_000_000))
390
43
		.collect();
391
43

            
392
43
	pallet_balances::GenesisConfig::<Test> { balances }
393
43
		.assimilate_storage(&mut ext)
394
43
		.unwrap();
395
43

            
396
43
	(pairs, ext.into())
397
43
}
398

            
399
pub struct LegacyUnsignedTransaction {
400
	pub nonce: U256,
401
	pub gas_price: U256,
402
	pub gas_limit: U256,
403
	pub action: TransactionAction,
404
	pub value: U256,
405
	pub input: Vec<u8>,
406
}
407

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

            
422
1
	fn signing_hash(&self) -> H256 {
423
1
		let mut stream = RlpStream::new();
424
1
		self.signing_rlp_append(&mut stream);
425
1
		H256::from(keccak_256(&stream.out()))
426
1
	}
427

            
428
1
	pub fn sign(&self, key: &H256) -> Transaction {
429
1
		self.sign_with_chain_id(key, ChainId::get())
430
1
	}
431

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

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

            
448
1
		Transaction::Legacy(ethereum::LegacyTransaction {
449
1
			nonce: self.nonce,
450
1
			gas_price: self.gas_price,
451
1
			gas_limit: self.gas_limit,
452
1
			action: self.action,
453
1
			value: self.value,
454
1
			input: self.input.clone(),
455
1
			signature: sig,
456
1
		})
457
1
	}
458
}
459

            
460
pub struct EIP2930UnsignedTransaction {
461
	pub nonce: U256,
462
	pub gas_price: U256,
463
	pub gas_limit: U256,
464
	pub action: TransactionAction,
465
	pub value: U256,
466
	pub input: Vec<u8>,
467
}
468

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

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

            
509
pub struct EIP1559UnsignedTransaction {
510
	pub nonce: U256,
511
	pub max_priority_fee_per_gas: U256,
512
	pub max_fee_per_gas: U256,
513
	pub gas_limit: U256,
514
	pub action: TransactionAction,
515
	pub value: U256,
516
	pub input: Vec<u8>,
517
}
518

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

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