1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright 2019-2022 PureStake Inc.
// This file is part of Moonbeam.

// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Moonbeam is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.

#![cfg_attr(not(feature = "std"), no_std)]

use account::SYSTEM_ACCOUNT_SIZE;
use evm::ExitReason;
use fp_evm::{Context, PrecompileFailure, PrecompileHandle, Transfer};
use frame_support::dispatch::{GetDispatchInfo, PostDispatchInfo};
use pallet_balances::Call as BalancesCall;
use pallet_evm::AddressMapping;
use pallet_proxy::Call as ProxyCall;
use pallet_proxy::Pallet as ProxyPallet;
use precompile_utils::precompile_set::{self, AddressType, SelectorFilter};
use precompile_utils::prelude::*;
use sp_core::{Get, H160, U256};
use sp_runtime::{
	codec::Decode,
	traits::{ConstU32, Dispatchable, StaticLookup, Zero},
};
use sp_std::marker::PhantomData;

#[cfg(test)]
pub mod mock;
#[cfg(test)]
mod tests;

#[derive(Debug)]
pub struct OnlyIsProxy<Runtime>(PhantomData<Runtime>);

impl<Runtime> SelectorFilter for OnlyIsProxy<Runtime>
where
	Runtime:
		pallet_proxy::Config + pallet_evm::Config + frame_system::Config + pallet_balances::Config,
	<<Runtime as pallet_proxy::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
		From<Option<Runtime::AccountId>>,
	<Runtime as pallet_proxy::Config>::ProxyType: Decode + EvmProxyCallFilter,
	<Runtime as frame_system::Config>::RuntimeCall:
		Dispatchable<PostInfo = PostDispatchInfo> + GetDispatchInfo,
	<<Runtime as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
		From<Option<Runtime::AccountId>>,
	<Runtime as frame_system::Config>::RuntimeCall:
		From<ProxyCall<Runtime>> + From<BalancesCall<Runtime>>,
	<Runtime as pallet_balances::Config<()>>::Balance: TryFrom<U256> + Into<U256>,
{
	fn is_allowed(_caller: H160, selector: Option<u32>) -> bool {
		match selector {
			None => false,
			Some(selector) => {
				ProxyPrecompileCall::<Runtime>::is_proxy_selectors().contains(&selector)
			}
		}
	}

	fn description() -> String {
		"Allowed for all callers only for selector 'is_proxy'".into()
	}
}

#[derive(Debug)]
pub struct OnlyIsProxyAndProxy<Runtime>(PhantomData<Runtime>);

impl<Runtime> SelectorFilter for OnlyIsProxyAndProxy<Runtime>
where
	Runtime:
		pallet_proxy::Config + pallet_evm::Config + frame_system::Config + pallet_balances::Config,
	<<Runtime as pallet_proxy::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
		From<Option<Runtime::AccountId>>,
	<Runtime as pallet_proxy::Config>::ProxyType: Decode + EvmProxyCallFilter,
	<Runtime as frame_system::Config>::RuntimeCall:
		Dispatchable<PostInfo = PostDispatchInfo> + GetDispatchInfo,
	<<Runtime as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
		From<Option<Runtime::AccountId>>,
	<Runtime as frame_system::Config>::RuntimeCall:
		From<ProxyCall<Runtime>> + From<BalancesCall<Runtime>>,
	<Runtime as pallet_balances::Config<()>>::Balance: TryFrom<U256> + Into<U256>,
{
	fn is_allowed(_caller: H160, selector: Option<u32>) -> bool {
		match selector {
			None => false,
			Some(selector) => {
				ProxyPrecompileCall::<Runtime>::is_proxy_selectors().contains(&selector)
					|| ProxyPrecompileCall::<Runtime>::proxy_selectors().contains(&selector)
					|| ProxyPrecompileCall::<Runtime>::proxy_force_type_selectors()
						.contains(&selector)
			}
		}
	}

	fn description() -> String {
		"Allowed for all callers only for selectors 'is_proxy', 'proxy', 'proxy_force_type'".into()
	}
}

pub const CALL_DATA_LIMIT: u32 = 2u32.pow(16);

type GetCallDataLimit = ConstU32<CALL_DATA_LIMIT>;

pub struct EvmSubCall {
	pub to: Address,
	pub value: U256,
	pub call_data: BoundedBytes<ConstU32<CALL_DATA_LIMIT>>,
}

/// A trait to filter if an evm subcall is allowed to be executed by a proxy account.
/// This trait should be implemented by the `ProxyType` type configured in pallet proxy.
pub trait EvmProxyCallFilter: Sized + Send + Sync {
	/// If returns `false`, then the subcall will not be executed and the evm transaction will
	/// revert with error message "CallFiltered".
	fn is_evm_proxy_call_allowed(
		&self,
		_call: &EvmSubCall,
		_recipient_has_code: bool,
		_gas: u64,
	) -> EvmResult<bool> {
		Ok(false)
	}
}

/// A precompile to wrap the functionality from pallet-proxy.
pub struct ProxyPrecompile<Runtime>(PhantomData<Runtime>);

#[precompile_utils::precompile]
impl<Runtime> ProxyPrecompile<Runtime>
where
	Runtime:
		pallet_proxy::Config + pallet_evm::Config + frame_system::Config + pallet_balances::Config,
	<<Runtime as pallet_proxy::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
		From<Option<Runtime::AccountId>>,
	<Runtime as pallet_proxy::Config>::ProxyType: Decode + EvmProxyCallFilter,
	<Runtime as frame_system::Config>::RuntimeCall:
		Dispatchable<PostInfo = PostDispatchInfo> + GetDispatchInfo,
	<<Runtime as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
		From<Option<Runtime::AccountId>>,
	<Runtime as frame_system::Config>::RuntimeCall:
		From<ProxyCall<Runtime>> + From<BalancesCall<Runtime>>,
	<Runtime as pallet_balances::Config<()>>::Balance: TryFrom<U256> + Into<U256>,
{
	/// Register a proxy account for the sender that is able to make calls on its behalf.
	/// The dispatch origin for this call must be Signed.
	///
	/// Parameters:
	/// * delegate: The account that the caller would like to make a proxy.
	/// * proxy_type: The permissions allowed for this proxy account.
	/// * delay: The announcement period required of the initial proxy. Will generally be zero.
	#[precompile::public("addProxy(address,uint8,uint32)")]
	fn add_proxy(
		handle: &mut impl PrecompileHandle,
		delegate: Address,
		proxy_type: u8,
		delay: u32,
	) -> EvmResult {
		let delegate = Runtime::AddressMapping::into_account_id(delegate.into());
		let proxy_type = Runtime::ProxyType::decode(&mut proxy_type.to_le_bytes().as_slice())
			.map_err(|_| {
				RevertReason::custom("Failed decoding value to ProxyType").in_field("proxyType")
			})?;
		let delay = delay.into();

		let origin = Runtime::AddressMapping::into_account_id(handle.context().caller);

		// Disallow re-adding proxy via precompile to prevent re-entrancy.
		// See: https://github.com/PureStake/sr-moonbeam/issues/30
		// Note: It is also assumed that EVM calls are only allowed through `Origin::Root` and
		// filtered via CallFilter
		// Proxies:
		// Twox64Concat(8) + AccountId(20) + BoundedVec(ProxyDefinition * MaxProxies) + Balance(16)
		handle.record_db_read::<Runtime>(
			28 + (29 * (<Runtime as pallet_proxy::Config>::MaxProxies::get() as usize)) + 8,
		)?;
		if ProxyPallet::<Runtime>::proxies(&origin)
			.0
			.iter()
			.any(|pd| pd.delegate == delegate)
		{
			return Err(revert("Cannot add more than one proxy"));
		}

		let delegate: <Runtime::Lookup as StaticLookup>::Source =
			Runtime::Lookup::unlookup(delegate.clone());
		let call: ProxyCall<Runtime> = ProxyCall::<Runtime>::add_proxy {
			delegate,
			proxy_type,
			delay,
		}
		.into();

		<RuntimeHelper<Runtime>>::try_dispatch(handle, Some(origin).into(), call, 0)?;

		Ok(())
	}

	/// Unregister a proxy account for the sender.
	/// The dispatch origin for this call must be Signed.
	///
	/// Parameters:
	/// * delegate: The account that the caller would like to remove as a proxy.
	/// * proxy_type: The permissions currently enabled for the removed proxy account.
	/// * delay: The announcement period required of the initial proxy. Will generally be zero.
	#[precompile::public("removeProxy(address,uint8,uint32)")]
	fn remove_proxy(
		handle: &mut impl PrecompileHandle,
		delegate: Address,
		proxy_type: u8,
		delay: u32,
	) -> EvmResult {
		let delegate = Runtime::AddressMapping::into_account_id(delegate.into());
		let proxy_type = Runtime::ProxyType::decode(&mut proxy_type.to_le_bytes().as_slice())
			.map_err(|_| {
				RevertReason::custom("Failed decoding value to ProxyType").in_field("proxyType")
			})?;
		let delay = delay.into();

		let delegate: <Runtime::Lookup as StaticLookup>::Source =
			Runtime::Lookup::unlookup(delegate.clone());
		let origin = Runtime::AddressMapping::into_account_id(handle.context().caller);
		let call: ProxyCall<Runtime> = ProxyCall::<Runtime>::remove_proxy {
			delegate,
			proxy_type,
			delay,
		}
		.into();

		<RuntimeHelper<Runtime>>::try_dispatch(handle, Some(origin).into(), call, 0)?;

		Ok(())
	}

	/// Unregister all proxy accounts for the sender.
	/// The dispatch origin for this call must be Signed.
	/// WARNING: This may be called on accounts created by anonymous, however if done, then the
	/// unreserved fees will be inaccessible. All access to this account will be lost.
	#[precompile::public("removeProxies()")]
	fn remove_proxies(handle: &mut impl PrecompileHandle) -> EvmResult {
		let origin = Runtime::AddressMapping::into_account_id(handle.context().caller);
		let call: ProxyCall<Runtime> = ProxyCall::<Runtime>::remove_proxies {}.into();

		<RuntimeHelper<Runtime>>::try_dispatch(handle, Some(origin).into(), call, 0)?;

		Ok(())
	}

	/// Dispatch the given subcall (`call_to`, `call_data`) from an account that the sender is
	/// authorised for through `add_proxy`.
	///
	/// Parameters:
	/// - `real`: The account that the proxy will make a call on behalf of.
	/// - `call_to`: Recipient of the call to be made by the `real` account.
	/// - `call_data`: Data of the call to be made by the `real` account.
	#[precompile::public("proxy(address,address,bytes)")]
	#[precompile::payable]
	fn proxy(
		handle: &mut impl PrecompileHandle,
		real: Address,
		call_to: Address,
		call_data: BoundedBytes<GetCallDataLimit>,
	) -> EvmResult {
		let evm_subcall = EvmSubCall {
			to: call_to,
			value: handle.context().apparent_value,
			call_data,
		};

		Self::inner_proxy(handle, real, None, evm_subcall)
	}

	/// Dispatch the given subcall (`call_to`, `call_data`) from an account that the sender is
	/// authorised for through `add_proxy`.
	///
	/// Parameters:
	/// - `real`: The account that the proxy will make a call on behalf of.
	/// - `force_proxy_type`: Specify the exact proxy type to be used and checked for this call.
	/// - `call_to`: Recipient of the call to be made by the `real` account.
	/// - `call_data`: Data of the call to be made by the `real` account.
	#[precompile::public("proxyForceType(address,uint8,address,bytes)")]
	#[precompile::public("proxy_force_type(address,uint8,address,bytes)")]
	#[precompile::payable]
	fn proxy_force_type(
		handle: &mut impl PrecompileHandle,
		real: Address,
		force_proxy_type: u8,
		call_to: Address,
		call_data: BoundedBytes<GetCallDataLimit>,
	) -> EvmResult {
		let proxy_type = Runtime::ProxyType::decode(&mut force_proxy_type.to_le_bytes().as_slice())
			.map_err(|_| {
				RevertReason::custom("Failed decoding value to ProxyType")
					.in_field("forceProxyType")
			})?;

		let evm_subcall = EvmSubCall {
			to: call_to,
			value: handle.context().apparent_value,
			call_data,
		};

		Self::inner_proxy(handle, real, Some(proxy_type), evm_subcall)
	}

	/// Checks if the caller has an account proxied with a given proxy type
	///
	/// Parameters:
	/// * delegate: The account that the caller has maybe proxied
	/// * proxyType: The permissions allowed for the proxy
	/// * delay: The announcement period required of the initial proxy. Will generally be zero.
	#[precompile::public("isProxy(address,address,uint8,uint32)")]
	#[precompile::view]
	fn is_proxy(
		handle: &mut impl PrecompileHandle,
		real: Address,
		delegate: Address,
		proxy_type: u8,
		delay: u32,
	) -> EvmResult<bool> {
		let delegate = Runtime::AddressMapping::into_account_id(delegate.into());
		let proxy_type = Runtime::ProxyType::decode(&mut proxy_type.to_le_bytes().as_slice())
			.map_err(|_| {
				RevertReason::custom("Failed decoding value to ProxyType").in_field("proxyType")
			})?;
		let delay = delay.into();

		let real = Runtime::AddressMapping::into_account_id(real.into());

		// Proxies:
		// Twox64Concat(8) + AccountId(20) + BoundedVec(ProxyDefinition * MaxProxies) + Balance(16)
		handle.record_db_read::<Runtime>(
			28 + (29 * (<Runtime as pallet_proxy::Config>::MaxProxies::get() as usize)) + 8,
		)?;
		let is_proxy = ProxyPallet::<Runtime>::proxies(real)
			.0
			.iter()
			.any(|pd| pd.delegate == delegate && pd.proxy_type == proxy_type && pd.delay == delay);

		Ok(is_proxy)
	}

	fn inner_proxy(
		handle: &mut impl PrecompileHandle,
		real: Address,
		force_proxy_type: Option<<Runtime as pallet_proxy::Config>::ProxyType>,
		evm_subcall: EvmSubCall,
	) -> EvmResult {
		// Check that we only perform proxy calls on behalf of externally owned accounts
		let AddressType::EOA = precompile_set::get_address_type::<Runtime>(handle, real.into())?
		else {
			return Err(revert("real address must be EOA"));
		};

		// Read proxy
		let real_account_id = Runtime::AddressMapping::into_account_id(real.into());
		let who = Runtime::AddressMapping::into_account_id(handle.context().caller);
		// Proxies:
		// Twox64Concat(8) + AccountId(20) + BoundedVec(ProxyDefinition * MaxProxies) + Balance(16)
		handle.record_db_read::<Runtime>(
			28 + (29 * (<Runtime as pallet_proxy::Config>::MaxProxies::get() as usize)) + 8,
		)?;
		let def =
			pallet_proxy::Pallet::<Runtime>::find_proxy(&real_account_id, &who, force_proxy_type)
				.map_err(|_| RevertReason::custom("Not proxy"))?;
		frame_support::ensure!(def.delay.is_zero(), revert("Unannounced"));

		// Read subcall recipient code
		// AccountCodes: Blake2128(16) + H160(20) + Vec(5)
		// decode_len reads the first 5 bytes to find the payload len under this key
		handle.record_db_read::<Runtime>(41)?;
		let recipient_has_code =
			pallet_evm::AccountCodes::<Runtime>::decode_len(evm_subcall.to.0).unwrap_or(0) > 0;

		// Apply proxy type filter
		frame_support::ensure!(
			def.proxy_type.is_evm_proxy_call_allowed(
				&evm_subcall,
				recipient_has_code,
				handle.remaining_gas()
			)?,
			revert("CallFiltered")
		);

		let EvmSubCall {
			to,
			value,
			call_data,
		} = evm_subcall;
		let address = to.0;

		let sub_context = Context {
			caller: real.0,
			address: address.clone(),
			apparent_value: value,
		};

		let transfer = if value.is_zero() {
			None
		} else {
			let contract_address: Runtime::AccountId =
				Runtime::AddressMapping::into_account_id(handle.context().address);

			// Send back funds received by the precompile.
			RuntimeHelper::<Runtime>::try_dispatch(
				handle,
				Some(contract_address).into(),
				pallet_balances::Call::<Runtime>::transfer_allow_death {
					dest: Runtime::Lookup::unlookup(who),
					value: {
						let balance: <Runtime as pallet_balances::Config<()>>::Balance =
							value.try_into().map_err(|_| PrecompileFailure::Revert {
								exit_status: fp_evm::ExitRevert::Reverted,
								output: sp_std::vec::Vec::new(),
							})?;
						balance
					},
				},
				SYSTEM_ACCOUNT_SIZE,
			)?;

			Some(Transfer {
				source: sub_context.caller,
				target: address.clone(),
				value,
			})
		};

		let (reason, output) = handle.call(
			address,
			transfer,
			call_data.into(),
			Some(handle.remaining_gas()),
			false,
			&sub_context,
		);

		// Return subcall result
		match reason {
			ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }),
			ExitReason::Revert(exit_status) => Err(PrecompileFailure::Revert {
				exit_status,
				output,
			}),
			ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }),
			ExitReason::Succeed(_) => Ok(()),
		}
	}
}