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
use super::*;
18
use frame_support::{
19
	assert_noop,
20
	dispatch::{Pays, PostDispatchInfo},
21
	traits::ConstU32,
22
	weights::Weight,
23
	BoundedVec,
24
};
25
use sp_runtime::{DispatchError, DispatchErrorWithPostInfo};
26
use xcm_primitives::{EthereumXcmFee, EthereumXcmTransaction, EthereumXcmTransactionV1};
27

            
28
// 	pragma solidity ^0.6.6;
29
// 	contract Test {
30
// 		function foo() external pure returns (bool) {
31
// 			return true;
32
// 		}
33
// 		function bar() external pure {
34
// 			require(false, "error_msg");
35
// 		}
36
// 	}
37
const CONTRACT: &str = "608060405234801561001057600080fd5b50610113806100206000396000f3fe6080604052\
38
						348015600f57600080fd5b506004361060325760003560e01c8063c2985578146037578063\
39
						febb0f7e146057575b600080fd5b603d605f565b6040518082151515158152602001915050\
40
						60405180910390f35b605d6068565b005b60006001905090565b600060db576040517f08c3\
41
						79a00000000000000000000000000000000000000000000000000000000081526004018080\
42
						602001828103825260098152602001807f6572726f725f6d73670000000000000000000000\
43
						00000000000000000000000081525060200191505060405180910390fd5b56fea264697066\
44
						7358221220fde68a3968e0e99b16fabf9b2997a78218b32214031f8e07e2c502daf603a69e\
45
						64736f6c63430006060033";
46

            
47
8
fn xcm_evm_transfer_eip_1559_transaction(destination: H160, value: U256) -> EthereumXcmTransaction {
48
8
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
49
8
		fee_payment: EthereumXcmFee::Auto,
50
8
		gas_limit: U256::from(0x5208),
51
8
		action: ethereum::TransactionAction::Call(destination),
52
8
		value,
53
8
		input:
54
8
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
55
8
				vec![],
56
8
			)
57
8
			.unwrap(),
58
8
		access_list: None,
59
8
	})
60
8
}
61

            
62
2
fn xcm_evm_call_eip_1559_transaction(destination: H160, input: Vec<u8>) -> EthereumXcmTransaction {
63
2
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
64
2
		fee_payment: EthereumXcmFee::Auto,
65
2
		gas_limit: U256::from(0x100000),
66
2
		action: ethereum::TransactionAction::Call(destination),
67
2
		value: U256::zero(),
68
2
		input:
69
2
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
70
2
				input,
71
2
			)
72
2
			.unwrap(),
73
2
		access_list: None,
74
2
	})
75
2
}
76

            
77
1
fn xcm_erc20_creation_eip_1559_transaction() -> EthereumXcmTransaction {
78
1
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
79
1
		fee_payment: EthereumXcmFee::Auto,
80
1

            
81
1
		gas_limit: U256::from(0x100000),
82
1
		action: ethereum::TransactionAction::Create,
83
1
		value: U256::zero(),
84
1
		input:
85
1
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
86
1
				hex::decode(CONTRACT).unwrap(),
87
1
			)
88
1
			.unwrap(),
89
1
		access_list: None,
90
1
	})
91
1
}
92

            
93
#[test]
94
1
fn test_transact_xcm_evm_transfer() {
95
1
	let (pairs, mut ext) = new_test_ext(2);
96
1
	let alice = &pairs[0];
97
1
	let bob = &pairs[1];
98
1

            
99
1
	ext.execute_with(|| {
100
1
		let balances_before = System::account(&bob.account_id);
101
1
		EthereumXcm::transact(
102
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
103
1
			xcm_evm_transfer_eip_1559_transaction(bob.address, U256::from(100)),
104
1
		)
105
1
		.expect("Failed to execute transaction");
106
1

            
107
1
		assert_eq!(
108
1
			System::account(&bob.account_id).data.free,
109
1
			balances_before.data.free + 100
110
1
		);
111
1
	});
112
1
}
113

            
114
#[test]
115
1
fn test_transact_xcm_create() {
116
1
	let (pairs, mut ext) = new_test_ext(1);
117
1
	let alice = &pairs[0];
118
1

            
119
1
	ext.execute_with(|| {
120
1
		assert_noop!(
121
1
			EthereumXcm::transact(
122
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
123
1
				xcm_erc20_creation_eip_1559_transaction()
124
1
			),
125
1
			DispatchErrorWithPostInfo {
126
1
				post_info: PostDispatchInfo {
127
1
					actual_weight: Some(Weight::zero()),
128
1
					pays_fee: Pays::Yes,
129
1
				},
130
1
				error: DispatchError::Other("Cannot convert xcm payload to known type"),
131
1
			}
132
1
		);
133
1
	});
134
1
}
135

            
136
#[test]
137
1
fn test_transact_xcm_evm_call_works() {
138
1
	let (pairs, mut ext) = new_test_ext(2);
139
1
	let alice = &pairs[0];
140
1
	let bob = &pairs[1];
141
1

            
142
1
	ext.execute_with(|| {
143
1
		let t = EIP1559UnsignedTransaction {
144
1
			nonce: U256::zero(),
145
1
			max_priority_fee_per_gas: U256::from(1),
146
1
			max_fee_per_gas: U256::from(1),
147
1
			gas_limit: U256::from(0x100000),
148
1
			action: ethereum::TransactionAction::Create,
149
1
			value: U256::zero(),
150
1
			input: hex::decode(CONTRACT).unwrap(),
151
1
		}
152
1
		.sign(&alice.private_key, None);
153
1
		assert_ok!(Ethereum::execute(alice.address, &t, None, None));
154

            
155
1
		let contract_address = hex::decode("32dcab0ef3fb2de2fce1d2e0799d36239671f04a").unwrap();
156
1
		let foo = hex::decode("c2985578").unwrap();
157
1
		let bar = hex::decode("febb0f7e").unwrap();
158
1

            
159
1
		let _ = EthereumXcm::transact(
160
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
161
1
			xcm_evm_call_eip_1559_transaction(H160::from_slice(&contract_address), foo),
162
1
		)
163
1
		.expect("Failed to call `foo`");
164
1

            
165
1
		// Evm call failing still succesfully dispatched
166
1
		let _ = EthereumXcm::transact(
167
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
168
1
			xcm_evm_call_eip_1559_transaction(H160::from_slice(&contract_address), bar),
169
1
		)
170
1
		.expect("Failed to call `bar`");
171
1

            
172
1
		let pending = pallet_ethereum::Pending::<Test>::get();
173
1
		assert!(pending.len() == 2);
174

            
175
		// Transaction is in Pending storage, with nonce 0 and status 1 (evm succeed).
176
1
		let (transaction_0, _, receipt_0) = &pending[0];
177
1
		match (transaction_0, receipt_0) {
178
1
			(&crate::Transaction::EIP1559(ref t), &crate::Receipt::EIP1559(ref r)) => {
179
1
				assert!(t.nonce == U256::from(0u8));
180
1
				assert!(r.status_code == 1u8);
181
			}
182
			_ => unreachable!(),
183
		}
184

            
185
		// Transaction is in Pending storage, with nonce 1 and status 0 (evm failed).
186
1
		let (transaction_1, _, receipt_1) = &pending[1];
187
1
		match (transaction_1, receipt_1) {
188
1
			(&crate::Transaction::EIP1559(ref t), &crate::Receipt::EIP1559(ref r)) => {
189
1
				assert!(t.nonce == U256::from(1u8));
190
1
				assert!(r.status_code == 0u8);
191
			}
192
			_ => unreachable!(),
193
		}
194
1
	});
195
1
}
196

            
197
#[test]
198
1
fn test_transact_xcm_validation_works() {
199
1
	let (pairs, mut ext) = new_test_ext(2);
200
1
	let alice = &pairs[0];
201
1
	let bob = &pairs[1];
202
1

            
203
1
	ext.execute_with(|| {
204
1
		// Not enough gas limit to cover the transaction cost.
205
1
		assert_noop!(
206
1
			EthereumXcm::transact(
207
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
208
1
				EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
209
1
					fee_payment: EthereumXcmFee::Manual(xcm_primitives::ManualEthereumXcmFee {
210
1
						gas_price: Some(U256::from(0)),
211
1
						max_fee_per_gas: None,
212
1
					}),
213
1
					gas_limit: U256::from(0x5207),
214
1
					action: ethereum::TransactionAction::Call(bob.address),
215
1
					value: U256::from(1),
216
1
					input: BoundedVec::<
217
1
						u8,
218
1
						ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>,
219
1
					>::try_from(vec![])
220
1
					.unwrap(),
221
1
					access_list: None,
222
1
				}),
223
1
			),
224
1
			DispatchErrorWithPostInfo {
225
1
				post_info: PostDispatchInfo {
226
1
					actual_weight: Some(Weight::zero()),
227
1
					pays_fee: Pays::Yes,
228
1
				},
229
1
				error: DispatchError::Other("Failed to validate ethereum transaction"),
230
1
			}
231
1
		);
232
1
	});
233
1
}
234

            
235
#[test]
236
1
fn test_ensure_transact_xcm_trough_no_proxy_error() {
237
1
	let (pairs, mut ext) = new_test_ext(2);
238
1
	let alice = &pairs[0];
239
1
	let bob = &pairs[1];
240
1

            
241
1
	ext.execute_with(|| {
242
1
		let r = EthereumXcm::transact_through_proxy(
243
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
244
1
			bob.address,
245
1
			xcm_evm_transfer_eip_1559_transaction(bob.address, U256::from(100)),
246
1
		);
247
1
		assert!(r.is_err());
248
1
		assert_eq!(
249
1
			r.unwrap_err().error,
250
1
			sp_runtime::DispatchError::Other("proxy error: expected `ProxyType::Any`"),
251
1
		);
252
1
	});
253
1
}
254

            
255
#[test]
256
1
fn test_ensure_transact_xcm_trough_proxy_error() {
257
1
	let (pairs, mut ext) = new_test_ext(2);
258
1
	let alice = &pairs[0];
259
1
	let bob = &pairs[1];
260
1

            
261
1
	ext.execute_with(|| {
262
1
		let _ = Proxy::add_proxy_delegate(
263
1
			&bob.account_id,
264
1
			alice.account_id.clone(),
265
1
			ProxyType::NotAllowed,
266
1
			0,
267
1
		);
268
1
		let r = EthereumXcm::transact_through_proxy(
269
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
270
1
			bob.address,
271
1
			xcm_evm_transfer_eip_1559_transaction(bob.address, U256::from(100)),
272
1
		);
273
1
		assert!(r.is_err());
274
1
		assert_eq!(
275
1
			r.unwrap_err().error,
276
1
			sp_runtime::DispatchError::Other("proxy error: expected `ProxyType::Any`"),
277
1
		);
278
1
	});
279
1
}
280

            
281
#[test]
282
1
fn test_ensure_transact_xcm_trough_proxy_ok() {
283
1
	let (pairs, mut ext) = new_test_ext(3);
284
1
	let alice = &pairs[0];
285
1
	let bob = &pairs[1];
286
1
	let charlie = &pairs[2];
287
1

            
288
1
	let allowed_proxies = vec![ProxyType::Any];
289

            
290
1
	for proxy in allowed_proxies.into_iter() {
291
1
		ext.execute_with(|| {
292
1
			let _ = Proxy::add_proxy_delegate(&bob.account_id, alice.account_id.clone(), proxy, 0);
293
1
			let alice_before = System::account(&alice.account_id);
294
1
			let bob_before = System::account(&bob.account_id);
295
1
			let charlie_before = System::account(&charlie.account_id);
296
1

            
297
1
			let r = EthereumXcm::transact_through_proxy(
298
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
299
1
				bob.address,
300
1
				xcm_evm_transfer_eip_1559_transaction(charlie.address, U256::from(100)),
301
1
			);
302
1
			// Transact succeeded
303
1
			assert!(r.is_ok());
304

            
305
1
			let alice_after = System::account(&alice.account_id);
306
1
			let bob_after = System::account(&bob.account_id);
307
1
			let charlie_after = System::account(&charlie.account_id);
308
1

            
309
1
			// Alice remains unchanged
310
1
			assert_eq!(alice_before, alice_after);
311

            
312
			// Bob nonce was increased
313
1
			assert_eq!(bob_after.nonce, bob_before.nonce + 1);
314

            
315
			// Bob sent some funds without paying any fees
316
1
			assert_eq!(bob_after.data.free, bob_before.data.free - 100);
317

            
318
			// Charlie receive some funds
319
1
			assert_eq!(charlie_after.data.free, charlie_before.data.free + 100);
320

            
321
			// Clear proxy
322
			let _ =
323
1
				Proxy::remove_proxy_delegate(&bob.account_id, alice.account_id.clone(), proxy, 0);
324
1
		});
325
1
	}
326
1
}
327

            
328
#[test]
329
1
fn test_global_nonce_incr() {
330
1
	let (pairs, mut ext) = new_test_ext(3);
331
1
	let alice = &pairs[0];
332
1
	let bob = &pairs[1];
333
1
	let charlie = &pairs[2];
334
1

            
335
1
	ext.execute_with(|| {
336
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
337

            
338
1
		EthereumXcm::transact(
339
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
340
1
			xcm_evm_transfer_eip_1559_transaction(charlie.address, U256::one()),
341
1
		)
342
1
		.expect("Failed to execute transaction from Alice to Charlie");
343
1

            
344
1
		assert_eq!(EthereumXcm::nonce(), U256::one());
345

            
346
1
		EthereumXcm::transact(
347
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
348
1
			xcm_evm_transfer_eip_1559_transaction(charlie.address, U256::one()),
349
1
		)
350
1
		.expect("Failed to execute transaction from Bob to Charlie");
351
1

            
352
1
		assert_eq!(EthereumXcm::nonce(), U256::from(2));
353
1
	});
354
1
}
355

            
356
#[test]
357
1
fn test_global_nonce_not_incr() {
358
1
	let (pairs, mut ext) = new_test_ext(2);
359
1
	let alice = &pairs[0];
360
1
	let bob = &pairs[1];
361
1

            
362
1
	ext.execute_with(|| {
363
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
364

            
365
1
		let invalid_transaction_cost =
366
1
			EthereumXcmTransaction::V1(
367
1
				EthereumXcmTransactionV1 {
368
1
					fee_payment: EthereumXcmFee::Auto,
369
1
					gas_limit: U256::one(),
370
1
					action: ethereum::TransactionAction::Call(bob.address),
371
1
					value: U256::one(),
372
1
					input: BoundedVec::<
373
1
						u8,
374
1
						ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>,
375
1
					>::try_from(vec![])
376
1
					.unwrap(),
377
1
					access_list: None,
378
1
				},
379
1
			);
380
1

            
381
1
		EthereumXcm::transact(
382
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
383
1
			invalid_transaction_cost,
384
1
		)
385
1
		.expect_err("Failed to execute transaction from Alice to Bob");
386
1

            
387
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
388
1
	});
389
1
}
390

            
391
#[test]
392
1
fn test_transaction_hash_collision() {
393
1
	let (pairs, mut ext) = new_test_ext(3);
394
1
	let alice = &pairs[0];
395
1
	let bob = &pairs[1];
396
1
	let charlie = &pairs[2];
397
1

            
398
1
	ext.execute_with(|| {
399
1
		EthereumXcm::transact(
400
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
401
1
			xcm_evm_transfer_eip_1559_transaction(charlie.address, U256::one()),
402
1
		)
403
1
		.expect("Failed to execute transaction from Alice to Charlie");
404
1

            
405
1
		EthereumXcm::transact(
406
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
407
1
			xcm_evm_transfer_eip_1559_transaction(charlie.address, U256::one()),
408
1
		)
409
1
		.expect("Failed to execute transaction from Bob to Charlie");
410
1

            
411
1
		let mut hashes = pallet_ethereum::Pending::<Test>::get()
412
1
			.iter()
413
2
			.map(|(tx, _, _)| tx.hash())
414
1
			.collect::<Vec<ethereum_types::H256>>();
415
1

            
416
1
		// Holds two transactions hashes
417
1
		assert_eq!(hashes.len(), 2);
418

            
419
1
		hashes.dedup();
420
1

            
421
1
		// Still holds two transactions hashes after removing potential consecutive repeated values.
422
1
		assert_eq!(hashes.len(), 2);
423
1
	});
424
1
}