pallet_evm_tracker/
create_contract.rs

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
//! Contract creation allow list implementations

use crate::traits::{AccountIdFor, MaybeIntoEthCall, MaybeIntoEvmCall};
use codec::{Decode, Encode};
use domain_runtime_primitives::{EthereumAccountId, ERR_CONTRACT_CREATION_NOT_ALLOWED};
use frame_support::pallet_prelude::{PhantomData, TypeInfo};
use frame_system::pallet_prelude::{OriginFor, RuntimeCallFor};
use pallet_ethereum::{Transaction as EthereumTransaction, TransactionAction};
use scale_info::prelude::fmt;
use sp_core::Get;
use sp_runtime::impl_tx_ext_default;
use sp_runtime::traits::{
    AsSystemOriginSigner, DispatchInfoOf, Dispatchable, TransactionExtension, ValidateResult,
};
use sp_runtime::transaction_validity::{
    InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
    ValidTransaction,
};
use sp_weights::Weight;
use subspace_runtime_primitives::utility::{nested_utility_call_iter, MaybeIntoUtilityCall};

/// Rejects contracts that can't be created under the current allow list.
/// Returns false if the call is a contract call, and the account is *not* allowed to call it.
/// Otherwise, returns true.
pub fn is_create_contract_allowed<Runtime>(
    call: &RuntimeCallFor<Runtime>,
    signer: &EthereumAccountId,
) -> bool
where
    Runtime: frame_system::Config<AccountId = EthereumAccountId>
        + pallet_ethereum::Config
        + pallet_evm::Config
        + pallet_utility::Config
        + crate::Config,
    RuntimeCallFor<Runtime>:
        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeIntoUtilityCall<Runtime>,
    for<'block> &'block RuntimeCallFor<Runtime>:
        From<&'block <Runtime as pallet_utility::Config>::RuntimeCall>,
    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
{
    // If the account is allowed to create contracts, or it's not a contract call, return true.
    // Only enters allocating code if this account can't create contracts.
    crate::Pallet::<Runtime>::is_allowed_to_create_contracts(signer)
        || !is_create_contract::<Runtime>(call)
}

/// If anyone is allowed to create contracts, allows contracts. Otherwise, rejects contracts.
/// Returns false if the call is a contract call, and there is a specific (possibly empty) allow
/// list. Otherwise, returns true.
pub fn is_create_unsigned_contract_allowed<Runtime>(call: &RuntimeCallFor<Runtime>) -> bool
where
    Runtime: frame_system::Config
        + pallet_ethereum::Config
        + pallet_evm::Config
        + pallet_utility::Config
        + crate::Config,
    RuntimeCallFor<Runtime>:
        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeIntoUtilityCall<Runtime>,
    for<'block> &'block RuntimeCallFor<Runtime>:
        From<&'block <Runtime as pallet_utility::Config>::RuntimeCall>,
    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
{
    // If any account is allowed to create contracts, or it's not a contract call, return true.
    // Only enters allocating code if there is a contract creation filter.
    crate::Pallet::<Runtime>::is_allowed_to_create_unsigned_contracts()
        || !is_create_contract::<Runtime>(call)
}

/// Returns true if the call is a contract creation call.
pub fn is_create_contract<Runtime>(call: &RuntimeCallFor<Runtime>) -> bool
where
    Runtime: frame_system::Config
        + pallet_ethereum::Config
        + pallet_evm::Config
        + pallet_utility::Config,
    RuntimeCallFor<Runtime>:
        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeIntoUtilityCall<Runtime>,
    for<'block> &'block RuntimeCallFor<Runtime>:
        From<&'block <Runtime as pallet_utility::Config>::RuntimeCall>,
    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
{
    for call in nested_utility_call_iter::<Runtime>(call) {
        if let Some(call) = call.maybe_into_eth_call() {
            match call {
                pallet_ethereum::Call::transact {
                    transaction: EthereumTransaction::Legacy(transaction),
                    ..
                } => {
                    if transaction.action == TransactionAction::Create {
                        return true;
                    }
                }
                pallet_ethereum::Call::transact {
                    transaction: EthereumTransaction::EIP2930(transaction),
                    ..
                } => {
                    if transaction.action == TransactionAction::Create {
                        return true;
                    }
                }
                pallet_ethereum::Call::transact {
                    transaction: EthereumTransaction::EIP1559(transaction),
                    ..
                } => {
                    if transaction.action == TransactionAction::Create {
                        return true;
                    }
                }
                // Inconclusive, other calls might create contracts.
                _ => {}
            }
        }

        if let Some(pallet_evm::Call::create { .. } | pallet_evm::Call::create2 { .. }) =
            call.maybe_into_evm_call()
        {
            return true;
        }
    }

    false
}

/// Reject contract creation, unless the account is in the current evm contract allow list.
#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
pub struct CheckContractCreation<Runtime>(PhantomData<Runtime>);

impl<Runtime> CheckContractCreation<Runtime> {
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<Runtime> Default for CheckContractCreation<Runtime> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Runtime> CheckContractCreation<Runtime>
where
    Runtime: frame_system::Config<AccountId = EthereumAccountId>
        + pallet_ethereum::Config
        + pallet_evm::Config
        + pallet_utility::Config
        + crate::Config
        + scale_info::TypeInfo
        + fmt::Debug
        + Send
        + Sync,
    RuntimeCallFor<Runtime>:
        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeIntoUtilityCall<Runtime>,
    for<'block> &'block RuntimeCallFor<Runtime>:
        From<&'block <Runtime as pallet_utility::Config>::RuntimeCall>,
    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
        AsSystemOriginSigner<AccountIdFor<Runtime>> + Clone,
{
    fn do_validate_unsigned(call: &RuntimeCallFor<Runtime>) -> TransactionValidity {
        if !is_create_unsigned_contract_allowed::<Runtime>(call) {
            Err(InvalidTransaction::Custom(ERR_CONTRACT_CREATION_NOT_ALLOWED).into())
        } else {
            Ok(ValidTransaction::default())
        }
    }

    fn do_validate(
        origin: &OriginFor<Runtime>,
        call: &RuntimeCallFor<Runtime>,
    ) -> TransactionValidity {
        let Some(who) = origin.as_system_origin_signer() else {
            // Reject unsigned contract creation unless anyone is allowed to create them.
            return Self::do_validate_unsigned(call);
        };
        // Reject contract creation unless the account is in the allow list.
        if !is_create_contract_allowed::<Runtime>(call, who) {
            Err(InvalidTransaction::Custom(ERR_CONTRACT_CREATION_NOT_ALLOWED).into())
        } else {
            Ok(ValidTransaction::default())
        }
    }
}

// Unsigned calls can't create contracts. Only pallet-evm and pallet-ethereum can create contracts.
// For pallet-evm all contracts are signed extrinsics, for pallet-ethereum there is only one
// extrinsic that is self-contained.
impl<Runtime> TransactionExtension<RuntimeCallFor<Runtime>> for CheckContractCreation<Runtime>
where
    Runtime: frame_system::Config<AccountId = EthereumAccountId>
        + pallet_ethereum::Config
        + pallet_evm::Config
        + pallet_utility::Config
        + crate::Config
        + scale_info::TypeInfo
        + fmt::Debug
        + Send
        + Sync,
    RuntimeCallFor<Runtime>:
        MaybeIntoEthCall<Runtime> + MaybeIntoEvmCall<Runtime> + MaybeIntoUtilityCall<Runtime>,
    for<'block> &'block RuntimeCallFor<Runtime>:
        From<&'block <Runtime as pallet_utility::Config>::RuntimeCall>,
    Result<pallet_ethereum::RawOrigin, OriginFor<Runtime>>: From<OriginFor<Runtime>>,
    <RuntimeCallFor<Runtime> as Dispatchable>::RuntimeOrigin:
        AsSystemOriginSigner<AccountIdFor<Runtime>> + Clone,
{
    const IDENTIFIER: &'static str = "CheckContractCreation";
    type Implicit = ();
    type Val = ();
    type Pre = ();

    // TODO: calculate proper weight for this extension
    //  Currently only accounts for storage read
    fn weight(&self, _: &RuntimeCallFor<Runtime>) -> Weight {
        // there will always be one storage read for this call
        <Runtime as frame_system::Config>::DbWeight::get().reads(1)
    }

    fn validate(
        &self,
        origin: OriginFor<Runtime>,
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
        _self_implicit: Self::Implicit,
        _inherited_implication: &impl Encode,
        _source: TransactionSource,
    ) -> ValidateResult<Self::Val, RuntimeCallFor<Runtime>> {
        let validity = Self::do_validate(&origin, call)?;
        Ok((validity, (), origin))
    }

    impl_tx_ext_default!(RuntimeCallFor<Runtime>; prepare);

    fn bare_validate(
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
    ) -> TransactionValidity {
        Self::do_validate_unsigned(call)
    }

    fn bare_validate_and_prepare(
        call: &RuntimeCallFor<Runtime>,
        _info: &DispatchInfoOf<RuntimeCallFor<Runtime>>,
        _len: usize,
    ) -> Result<(), TransactionValidityError> {
        Self::do_validate_unsigned(call)?;
        Ok(())
    }
}