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::{
27
	EthereumXcmFee, EthereumXcmTransaction, EthereumXcmTransactionV1, ManualEthereumXcmFee,
28
};
29

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

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

            
64
2
fn xcm_evm_call_eip_legacy_transaction(
65
2
	destination: H160,
66
2
	input: Vec<u8>,
67
2
) -> EthereumXcmTransaction {
68
2
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
69
2
		fee_payment: EthereumXcmFee::Manual(ManualEthereumXcmFee {
70
2
			gas_price: Some(U256::from(1)),
71
2
			max_fee_per_gas: None,
72
2
		}),
73
2
		gas_limit: U256::from(0x100000),
74
2
		action: ethereum::TransactionAction::Call(destination),
75
2
		value: U256::zero(),
76
2
		input:
77
2
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
78
2
				input,
79
2
			)
80
2
			.unwrap(),
81
2
		access_list: None,
82
2
	})
83
2
}
84

            
85
1
fn xcm_erc20_creation_legacy_transaction() -> EthereumXcmTransaction {
86
1
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
87
1
		fee_payment: EthereumXcmFee::Manual(ManualEthereumXcmFee {
88
1
			gas_price: Some(U256::from(1)),
89
1
			max_fee_per_gas: None,
90
1
		}),
91
1
		gas_limit: U256::from(0x100000),
92
1
		action: ethereum::TransactionAction::Create,
93
1
		value: U256::zero(),
94
1
		input:
95
1
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
96
1
				hex::decode(CONTRACT).unwrap(),
97
1
			)
98
1
			.unwrap(),
99
1
		access_list: None,
100
1
	})
101
1
}
102

            
103
#[test]
104
1
fn test_transact_xcm_evm_transfer() {
105
1
	let (pairs, mut ext) = new_test_ext(2);
106
1
	let alice = &pairs[0];
107
1
	let bob = &pairs[1];
108
1

            
109
1
	ext.execute_with(|| {
110
1
		let balances_before = System::account(&bob.account_id);
111
1
		EthereumXcm::transact(
112
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
113
1
			xcm_evm_transfer_legacy_transaction(bob.address, U256::from(100)),
114
1
		)
115
1
		.expect("Failed to execute transaction");
116
1

            
117
1
		assert_eq!(
118
1
			System::account(&bob.account_id).data.free,
119
1
			balances_before.data.free + 100
120
1
		);
121
1
	});
122
1
}
123

            
124
#[test]
125
1
fn test_transact_xcm_create() {
126
1
	let (pairs, mut ext) = new_test_ext(1);
127
1
	let alice = &pairs[0];
128
1

            
129
1
	ext.execute_with(|| {
130
1
		assert_noop!(
131
1
			EthereumXcm::transact(
132
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
133
1
				xcm_erc20_creation_legacy_transaction()
134
1
			),
135
1
			DispatchErrorWithPostInfo {
136
1
				post_info: PostDispatchInfo {
137
1
					actual_weight: Some(Weight::zero()),
138
1
					pays_fee: Pays::Yes,
139
1
				},
140
1
				error: DispatchError::Other("Cannot convert xcm payload to known type"),
141
1
			}
142
1
		);
143
1
	});
144
1
}
145

            
146
#[test]
147
1
fn test_transact_xcm_evm_call_works() {
148
1
	let (pairs, mut ext) = new_test_ext(2);
149
1
	let alice = &pairs[0];
150
1
	let bob = &pairs[1];
151
1

            
152
1
	ext.execute_with(|| {
153
1
		let t = LegacyUnsignedTransaction {
154
1
			nonce: U256::zero(),
155
1
			gas_price: U256::from(1),
156
1
			gas_limit: U256::from(0x100000),
157
1
			action: ethereum::TransactionAction::Create,
158
1
			value: U256::zero(),
159
1
			input: hex::decode(CONTRACT).unwrap(),
160
1
		}
161
1
		.sign(&alice.private_key);
162
1
		assert_ok!(Ethereum::execute(alice.address, &t, None, None));
163

            
164
1
		let contract_address = hex::decode("32dcab0ef3fb2de2fce1d2e0799d36239671f04a").unwrap();
165
1
		let foo = hex::decode("c2985578").unwrap();
166
1
		let bar = hex::decode("febb0f7e").unwrap();
167
1

            
168
1
		let _ = EthereumXcm::transact(
169
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
170
1
			xcm_evm_call_eip_legacy_transaction(H160::from_slice(&contract_address), foo),
171
1
		)
172
1
		.expect("Failed to call `foo`");
173
1

            
174
1
		// Evm call failing still succesfully dispatched
175
1
		let _ = EthereumXcm::transact(
176
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
177
1
			xcm_evm_call_eip_legacy_transaction(H160::from_slice(&contract_address), bar),
178
1
		)
179
1
		.expect("Failed to call `bar`");
180
1

            
181
1
		let pending = pallet_ethereum::Pending::<Test>::get();
182
1
		assert!(pending.len() == 2);
183

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

            
194
		// Transaction is in Pending storage, with nonce 1 and status 0 (evm failed).
195
1
		let (transaction_1, _, receipt_1) = &pending[1];
196
1
		match (transaction_1, receipt_1) {
197
1
			(&crate::Transaction::Legacy(ref t), &crate::Receipt::Legacy(ref r)) => {
198
1
				assert!(t.nonce == U256::from(1u8));
199
1
				assert!(r.status_code == 0u8);
200
			}
201
			_ => unreachable!(),
202
		}
203
1
	});
204
1
}
205

            
206
#[test]
207
1
fn test_transact_xcm_validation_works() {
208
1
	let (pairs, mut ext) = new_test_ext(2);
209
1
	let alice = &pairs[0];
210
1
	let bob = &pairs[1];
211
1

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

            
244
#[test]
245
1
fn test_ensure_transact_xcm_trough_no_proxy_error() {
246
1
	let (pairs, mut ext) = new_test_ext(2);
247
1
	let alice = &pairs[0];
248
1
	let bob = &pairs[1];
249
1

            
250
1
	ext.execute_with(|| {
251
1
		let r = EthereumXcm::transact_through_proxy(
252
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
253
1
			bob.address,
254
1
			xcm_evm_transfer_legacy_transaction(bob.address, U256::from(100)),
255
1
		);
256
1
		assert!(r.is_err());
257
1
		assert_eq!(
258
1
			r.unwrap_err().error,
259
1
			sp_runtime::DispatchError::Other("proxy error: expected `ProxyType::Any`"),
260
1
		);
261
1
	});
262
1
}
263

            
264
#[test]
265
1
fn test_ensure_transact_xcm_trough_proxy_error() {
266
1
	let (pairs, mut ext) = new_test_ext(2);
267
1
	let alice = &pairs[0];
268
1
	let bob = &pairs[1];
269
1

            
270
1
	ext.execute_with(|| {
271
1
		let _ = Proxy::add_proxy_delegate(
272
1
			&bob.account_id,
273
1
			alice.account_id.clone(),
274
1
			ProxyType::NotAllowed,
275
1
			0,
276
1
		);
277
1
		let r = EthereumXcm::transact_through_proxy(
278
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
279
1
			bob.address,
280
1
			xcm_evm_transfer_legacy_transaction(bob.address, U256::from(100)),
281
1
		);
282
1
		assert!(r.is_err());
283
1
		assert_eq!(
284
1
			r.unwrap_err().error,
285
1
			sp_runtime::DispatchError::Other("proxy error: expected `ProxyType::Any`"),
286
1
		);
287
1
	});
288
1
}
289

            
290
#[test]
291
1
fn test_ensure_transact_xcm_trough_proxy_ok() {
292
1
	let (pairs, mut ext) = new_test_ext(3);
293
1
	let alice = &pairs[0];
294
1
	let bob = &pairs[1];
295
1
	let charlie = &pairs[2];
296
1

            
297
1
	let allowed_proxies = vec![ProxyType::Any];
298

            
299
1
	for proxy in allowed_proxies.into_iter() {
300
1
		ext.execute_with(|| {
301
1
			let _ = Proxy::add_proxy_delegate(&bob.account_id, alice.account_id.clone(), proxy, 0);
302
1
			let alice_before = System::account(&alice.account_id);
303
1
			let bob_before = System::account(&bob.account_id);
304
1
			let charlie_before = System::account(&charlie.account_id);
305
1

            
306
1
			let r = EthereumXcm::transact_through_proxy(
307
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
308
1
				bob.address,
309
1
				xcm_evm_transfer_legacy_transaction(charlie.address, U256::from(100)),
310
1
			);
311
1
			// Transact succeeded
312
1
			assert!(r.is_ok());
313

            
314
1
			let alice_after = System::account(&alice.account_id);
315
1
			let bob_after = System::account(&bob.account_id);
316
1
			let charlie_after = System::account(&charlie.account_id);
317
1

            
318
1
			// Alice remains unchanged
319
1
			assert_eq!(alice_before, alice_after);
320

            
321
			// Bob nonce was increased
322
1
			assert_eq!(bob_after.nonce, bob_before.nonce + 1);
323

            
324
			// Bob sent some funds without paying any fees
325
1
			assert_eq!(bob_after.data.free, bob_before.data.free - 100);
326

            
327
			// Charlie receive some funds
328
1
			assert_eq!(charlie_after.data.free, charlie_before.data.free + 100);
329

            
330
			// Clear proxy
331
			let _ =
332
1
				Proxy::remove_proxy_delegate(&bob.account_id, alice.account_id.clone(), proxy, 0);
333
1
		});
334
1
	}
335
1
}
336

            
337
#[test]
338
1
fn test_global_nonce_incr() {
339
1
	let (pairs, mut ext) = new_test_ext(3);
340
1
	let alice = &pairs[0];
341
1
	let bob = &pairs[1];
342
1
	let charlie = &pairs[2];
343
1

            
344
1
	ext.execute_with(|| {
345
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
346

            
347
1
		EthereumXcm::transact(
348
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
349
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
350
1
		)
351
1
		.expect("Failed to execute transaction from Alice to Charlie");
352
1

            
353
1
		assert_eq!(EthereumXcm::nonce(), U256::one());
354

            
355
1
		EthereumXcm::transact(
356
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
357
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
358
1
		)
359
1
		.expect("Failed to execute transaction from Bob to Charlie");
360
1

            
361
1
		assert_eq!(EthereumXcm::nonce(), U256::from(2));
362
1
	});
363
1
}
364

            
365
#[test]
366
1
fn test_global_nonce_not_incr() {
367
1
	let (pairs, mut ext) = new_test_ext(2);
368
1
	let alice = &pairs[0];
369
1
	let bob = &pairs[1];
370
1

            
371
1
	ext.execute_with(|| {
372
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
373

            
374
1
		let invalid_transaction_cost =
375
1
			EthereumXcmTransaction::V1(
376
1
				EthereumXcmTransactionV1 {
377
1
					fee_payment: EthereumXcmFee::Auto,
378
1
					gas_limit: U256::one(),
379
1
					action: ethereum::TransactionAction::Call(bob.address),
380
1
					value: U256::one(),
381
1
					input: BoundedVec::<
382
1
						u8,
383
1
						ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>,
384
1
					>::try_from(vec![])
385
1
					.unwrap(),
386
1
					access_list: None,
387
1
				},
388
1
			);
389
1

            
390
1
		EthereumXcm::transact(
391
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
392
1
			invalid_transaction_cost,
393
1
		)
394
1
		.expect_err("Failed to execute transaction from Alice to Bob");
395
1

            
396
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
397
1
	});
398
1
}
399

            
400
#[test]
401
1
fn test_transaction_hash_collision() {
402
1
	let (pairs, mut ext) = new_test_ext(3);
403
1
	let alice = &pairs[0];
404
1
	let bob = &pairs[1];
405
1
	let charlie = &pairs[2];
406
1

            
407
1
	ext.execute_with(|| {
408
1
		EthereumXcm::transact(
409
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
410
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
411
1
		)
412
1
		.expect("Failed to execute transaction from Alice to Charlie");
413
1

            
414
1
		EthereumXcm::transact(
415
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
416
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
417
1
		)
418
1
		.expect("Failed to execute transaction from Bob to Charlie");
419
1

            
420
1
		let mut hashes = pallet_ethereum::Pending::<Test>::get()
421
1
			.iter()
422
2
			.map(|(tx, _, _)| tx.hash())
423
1
			.collect::<Vec<ethereum_types::H256>>();
424
1

            
425
1
		// Holds two transactions hashes
426
1
		assert_eq!(hashes.len(), 2);
427

            
428
1
		hashes.dedup();
429
1

            
430
1
		// Still holds two transactions hashes after removing potential consecutive repeated values.
431
1
		assert_eq!(hashes.len(), 2);
432
1
	});
433
1
}