Skip to main content

pallet_evm_tracker/
create_contract.rs

1//! Contract creation allow list implementations
2
3use crate::traits::{AccountIdFor, MaybeIntoEthCall, MaybeIntoEvmCall};
4use crate::weights::pallet_evm_tracker::WeightInfo as SubstrateWeightInfo;
5use crate::{MAXIMUM_NUMBER_OF_CALLS, WeightInfo};
6use domain_runtime_primitives::{ERR_CONTRACT_CREATION_NOT_ALLOWED, EthereumAccountId};
7use frame_support::dispatch::PostDispatchInfo;
8use frame_support::pallet_prelude::{DispatchResult, PhantomData, TypeInfo};
9use frame_system::pallet_prelude::{OriginFor, RuntimeCallFor};
10use pallet_ethereum::{Transaction as EthereumTransaction, TransactionAction};
11use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
12use scale_info::prelude::fmt;
13use sp_runtime::traits::{
14    AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, PostDispatchInfoOf,
15    RefundWeight, TransactionExtension, ValidateResult,
16};
17use sp_runtime::transaction_validity::{
18    InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
19    ValidTransaction,
20};
21use sp_weights::Weight;
22use subspace_runtime_primitives::utility::{MaybeNestedCall, nested_call_iter};
23
24/// Rejects contracts that can't be created under the current allow list.
25/// Returns false if the call is a contract call, and the account is *not* allowed to call it.
26/// Otherwise, returns true.
27pub fn is_create_contract_allowed<Runtime>(
28    call: &RuntimeCallFor<Runtime>,
29    signer: &EthereumAccountId,
30) -> (bool, u32)
31where
32    Runtime: frame_system::Config<AccountId = EthereumAccountId>
33        + pallet_ethereum::Config
34        + pallet_evm::Config
35        + crate::Config,
36    RuntimeCallFor<Runtime>:
37        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeNestedCall<Runtime>,
38    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
39{
40    // If the account is allowed to create contracts, or it's not a contract call, return true.
41    // Only enters allocating code if this account can't create contracts.
42    if crate::Pallet::<Runtime>::is_allowed_to_create_contracts(signer) {
43        return (true, 0);
44    }
45
46    let (is_create, call_count) = is_create_contract::<Runtime>(call);
47    (!is_create, call_count)
48}
49
50/// If anyone is allowed to create contracts, allows contracts. Otherwise, rejects contracts.
51/// Returns false if the call is a contract call, and there is a specific (possibly empty) allow
52/// list. Otherwise, returns true.
53pub fn is_create_unsigned_contract_allowed<Runtime>(call: &RuntimeCallFor<Runtime>) -> (bool, u32)
54where
55    Runtime: frame_system::Config + pallet_ethereum::Config + pallet_evm::Config + crate::Config,
56    RuntimeCallFor<Runtime>:
57        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeNestedCall<Runtime>,
58    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
59{
60    // If any account is allowed to create contracts, or it's not a contract call, return true.
61    // Only enters allocating code if there is a contract creation filter.
62    if crate::Pallet::<Runtime>::is_allowed_to_create_unsigned_contracts() {
63        return (true, 0);
64    }
65
66    let (is_create, call_count) = is_create_contract::<Runtime>(call);
67    (!is_create, call_count)
68}
69
70/// Returns true if the call is a contract creation call.
71pub fn is_create_contract<Runtime>(call: &RuntimeCallFor<Runtime>) -> (bool, u32)
72where
73    Runtime: frame_system::Config + pallet_ethereum::Config + pallet_evm::Config,
74    RuntimeCallFor<Runtime>:
75        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeNestedCall<Runtime>,
76    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
77{
78    let mut call_count = 0;
79    for call in nested_call_iter::<Runtime>(call) {
80        call_count += 1;
81
82        if let Some(call) = call.maybe_into_eth_call() {
83            match call {
84                pallet_ethereum::Call::transact {
85                    transaction: EthereumTransaction::Legacy(transaction),
86                    ..
87                } if transaction.action == TransactionAction::Create => {
88                    return (true, call_count);
89                }
90                pallet_ethereum::Call::transact {
91                    transaction: EthereumTransaction::EIP2930(transaction),
92                    ..
93                } if transaction.action == TransactionAction::Create => {
94                    return (true, call_count);
95                }
96                pallet_ethereum::Call::transact {
97                    transaction: EthereumTransaction::EIP1559(transaction),
98                    ..
99                } if transaction.action == TransactionAction::Create => {
100                    return (true, call_count);
101                }
102                // Inconclusive, other calls might create contracts.
103                _ => {}
104            }
105        }
106
107        if let Some(pallet_evm::Call::create { .. } | pallet_evm::Call::create2 { .. }) =
108            call.maybe_into_evm_call()
109        {
110            return (true, call_count);
111        }
112    }
113
114    (false, call_count)
115}
116
117/// Reject contract creation, unless the account is in the current evm contract allow list.
118#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo, DecodeWithMemTracking)]
119pub struct CheckContractCreation<Runtime>(PhantomData<Runtime>);
120
121impl<Runtime> CheckContractCreation<Runtime> {
122    pub fn new() -> Self {
123        Self(PhantomData)
124    }
125}
126
127impl<Runtime> Default for CheckContractCreation<Runtime> {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl<Runtime> CheckContractCreation<Runtime>
134where
135    Runtime: frame_system::Config<AccountId = EthereumAccountId>
136        + pallet_ethereum::Config
137        + pallet_evm::Config
138        + crate::Config
139        + scale_info::TypeInfo
140        + fmt::Debug
141        + Send
142        + Sync,
143    RuntimeCallFor<Runtime>:
144        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeNestedCall<Runtime>,
145    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
146    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
147        AsSystemOriginSigner<AccountIdFor<Runtime>> + Clone,
148{
149    pub(crate) fn do_validate_unsigned(
150        call: &RuntimeCallFor<Runtime>,
151    ) -> Result<(ValidTransaction, u32), TransactionValidityError> {
152        let (is_allowed, call_count) = is_create_unsigned_contract_allowed::<Runtime>(call);
153        if !is_allowed {
154            Err(InvalidTransaction::Custom(ERR_CONTRACT_CREATION_NOT_ALLOWED).into())
155        } else {
156            Ok((ValidTransaction::default(), call_count))
157        }
158    }
159
160    pub(crate) fn do_validate_signed(
161        origin: &OriginFor<Runtime>,
162        call: &RuntimeCallFor<Runtime>,
163    ) -> Result<(ValidTransaction, u32), TransactionValidityError> {
164        let Some(who) = origin.as_system_origin_signer() else {
165            // Reject unsigned contract creation unless anyone is allowed to create them.
166            return Self::do_validate_unsigned(call);
167        };
168
169        // Reject contract creation unless the account is in the allow list.
170        let (is_allowed, call_count) = is_create_contract_allowed::<Runtime>(call, who);
171        if !is_allowed {
172            Err(InvalidTransaction::Custom(ERR_CONTRACT_CREATION_NOT_ALLOWED).into())
173        } else {
174            Ok((ValidTransaction::default(), call_count))
175        }
176    }
177
178    pub fn get_weights(n: u32) -> Weight {
179        SubstrateWeightInfo::<Runtime>::evm_contract_check_multiple(n)
180            .max(SubstrateWeightInfo::<Runtime>::evm_contract_check_nested(n))
181    }
182}
183
184/// Data passed from prepare to post_dispatch.
185#[derive(Debug)]
186pub enum Pre {
187    /// Refund this exact amount of weight.
188    Refund(Weight),
189}
190
191/// Data passed from validate to prepare.
192#[derive(Debug)]
193pub enum Val {
194    /// Partially refund, based on the actual number of calls.
195    PartialRefund(u32),
196}
197
198// Unsigned calls can't create contracts. Only pallet-evm and pallet-ethereum can create contracts.
199// For pallet-evm all contracts are signed extrinsics, for pallet-ethereum there is only one
200// extrinsic that is self-contained.
201impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>> for CheckContractCreation<Runtime>
202where
203    Runtime: frame_system::Config<AccountId = EthereumAccountId>
204        + pallet_ethereum::Config
205        + pallet_evm::Config
206        + crate::Config
207        + scale_info::TypeInfo
208        + fmt::Debug
209        + Send
210        + Sync,
211    RuntimeCallFor<Runtime>:
212        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeNestedCall<Runtime>,
213    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
214    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
215        AsSystemOriginSigner<AccountIdFor<Runtime>> + Clone,
216    for<'a> &'a mut PostDispatchInfoOf<RuntimeCallFor<Runtime>>: Into<&'a mut PostDispatchInfo>,
217{
218    const IDENTIFIER: &'static str = "CheckContractCreation";
219    type Implicit = ();
220    type Val = Val;
221    type Pre = Pre;
222
223    fn weight(&self, _: &RuntimeCallFor<Runtime>) -> Weight {
224        Self::get_weights(MAXIMUM_NUMBER_OF_CALLS)
225    }
226
227    fn validate(
228        &self,
229        origin: OriginFor<Runtime>,
230        call: &RuntimeCallFor<Runtime>,
231        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
232        _len: usize,
233        _self_implicit: Self::Implicit,
234        _inherited_implication: &impl Encode,
235        _source: TransactionSource,
236    ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
237        let (validity, val) = if origin.as_system_origin_signer().is_some() {
238            let (valid, call_count) = Self::do_validate_signed(&origin, call)?;
239            (valid, Val::PartialRefund(call_count))
240        } else {
241            let (valid, call_count) = Self::do_validate_unsigned(call)?;
242            (valid, Val::PartialRefund(call_count))
243        };
244
245        Ok((validity, val, origin))
246    }
247
248    fn prepare(
249        self,
250        val: Self::Val,
251        _origin: &DispatchOriginOf<RuntimeCallFor<Runtime>>,
252        _call: &RuntimeCallFor<Runtime>,
253        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
254        _len: usize,
255    ) -> Result<Self::Pre, TransactionValidityError> {
256        let pre_dispatch_weights = Self::get_weights(MAXIMUM_NUMBER_OF_CALLS);
257        match val {
258            // Refund any extra call weight
259            // TODO: use frame_system::Pallet::<Runtime>::reclaim_weight when we upgrade to 40.1.0
260            // See <https://github.com/paritytech/polkadot-sdk/blob/292368d05eec5d6649607251ab21ed2c96ebd158/cumulus/pallets/weight-reclaim/src/lib.rs#L178>
261            Val::PartialRefund(calls) => {
262                let actual_weights = Self::get_weights(calls);
263                Ok(Pre::Refund(
264                    pre_dispatch_weights.saturating_sub(actual_weights),
265                ))
266            }
267        }
268    }
269
270    fn post_dispatch_details(
271        pre: Self::Pre,
272        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
273        _post_info: &PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
274        _len: usize,
275        _result: &DispatchResult,
276    ) -> Result<Weight, TransactionValidityError> {
277        let Pre::Refund(weight) = pre;
278        Ok(weight)
279    }
280
281    fn bare_validate(
282        call: &RuntimeCallFor<Runtime>,
283        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
284        _len: usize,
285    ) -> TransactionValidity {
286        Self::do_validate_unsigned(call).map(|(validity, _call_count)| validity)
287    }
288
289    fn bare_validate_and_prepare(
290        call: &RuntimeCallFor<Runtime>,
291        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
292        _len: usize,
293    ) -> Result<(), TransactionValidityError> {
294        Self::do_validate_unsigned(call)?;
295        Ok(())
296    }
297
298    // Weights for bare calls are calculated in the runtime, and excess weight refunded here.
299    fn bare_post_dispatch(
300        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
301        post_info: &mut PostDispatchInfoOf<RuntimeCallFor<Runtime>>,
302        _len: usize,
303        _result: &DispatchResult,
304    ) -> Result<(), TransactionValidityError> {
305        let pre_dispatch_weights = Self::get_weights(MAXIMUM_NUMBER_OF_CALLS);
306        // The number of Ethereum calls in a RuntimeCall is always 1, this is checked by
307        // is_self_contained() in the runtime.
308        let actual_weights = Self::get_weights(1);
309
310        // TODO: use frame_system::Pallet::<Runtime>::reclaim_weight when we upgrade to 40.1.0
311        let unspent = pre_dispatch_weights.saturating_sub(actual_weights);
312
313        // If we overcharged the weight, refund the extra weight.
314        let post_info = Into::<&mut PostDispatchInfo>::into(post_info);
315        if let Some(actual_weight) = post_info.actual_weight
316            && actual_weight.ref_time() >= pre_dispatch_weights.ref_time()
317        {
318            post_info.refund(unspent);
319        }
320
321        Ok(())
322    }
323}