Skip to main content

pallet_evm_tracker/
check_nonce.rs

1//! EVM nonce checker extension for the EVM domain runtime.
2
3use crate::Config;
4use core::cmp::max;
5use core::fmt;
6use core::result::Result;
7use domain_runtime_primitives::ERR_EVM_NONCE_OVERFLOW;
8use frame_support::dispatch::DispatchInfo;
9use frame_support::pallet_prelude::{
10    CheckedAdd, InvalidTransaction, TransactionLongevity, TransactionValidityError, TypeInfo,
11    ValidTransaction, Weight,
12};
13use frame_support::sp_runtime::traits::{DispatchInfoOf, One, TransactionExtension};
14use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
15use scale_info::prelude::vec;
16use sp_runtime::traits::{
17    AsSystemOriginSigner, Dispatchable, PostDispatchInfoOf, ValidateResult, Zero,
18};
19use sp_runtime::transaction_validity::TransactionSource;
20use sp_runtime::{DispatchResult, Saturating};
21
22#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo, DecodeWithMemTracking)]
23#[scale_info(skip_type_params(T))]
24pub struct CheckNonce<T: Config>(#[codec(compact)] pub T::Nonce);
25
26impl<T: Config> CheckNonce<T> {
27    /// utility constructor. Used only in client/factory code.
28    pub fn from(nonce: T::Nonce) -> Self {
29        Self(nonce)
30    }
31}
32
33impl<T: Config> fmt::Debug for CheckNonce<T> {
34    #[cfg(feature = "std")]
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "CheckNonce({})", self.0)
37    }
38
39    #[cfg(not(feature = "std"))]
40    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
41        Ok(())
42    }
43}
44
45/// Operation to perform from `validate` to `prepare` in [`frame_system::CheckNonce`] transaction extension.
46#[derive(Debug)]
47pub enum Val<T: frame_system::Config> {
48    /// Account and its nonce to check for.
49    CheckNonce((T::AccountId, T::Nonce)),
50    /// Weight to refund.
51    Refund(Weight),
52}
53
54/// Operation to perform from `prepare` to `post_dispatch_details` in [`frame_system::CheckNonce`] transaction
55/// extension.
56#[derive(Debug)]
57pub enum Pre {
58    /// The transaction extension weight should not be refunded.
59    NonceChecked,
60    /// The transaction extension weight should be refunded.
61    Refund(Weight),
62}
63
64impl<T: Config> TransactionExtension<T::RuntimeCall> for CheckNonce<T>
65where
66    T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
67    <T::RuntimeCall as Dispatchable>::RuntimeOrigin: AsSystemOriginSigner<T::AccountId> + Clone,
68{
69    const IDENTIFIER: &'static str = "CheckNonce";
70    type Implicit = ();
71    type Val = Val<T>;
72    type Pre = Pre;
73
74    fn weight(&self, _: &T::RuntimeCall) -> sp_weights::Weight {
75        // Currently we use the benchmarked weight from `frame_system::CheckNonce`, which does
76        // slightly less work. This extension does one more `max()` and two extra comparisons.
77        // TODO: benchmark evm_tracker::check_nonce() directly and use that weight here.
78        <T::ExtensionsWeightInfo as frame_system::ExtensionsWeightInfo>::check_nonce()
79    }
80
81    fn validate(
82        &self,
83        origin: <T as frame_system::Config>::RuntimeOrigin,
84        call: &T::RuntimeCall,
85        _info: &DispatchInfoOf<T::RuntimeCall>,
86        _len: usize,
87        _self_implicit: Self::Implicit,
88        _inherited_implication: &impl Encode,
89        _source: TransactionSource,
90    ) -> ValidateResult<Self::Val, T::RuntimeCall> {
91        let Some(who) = origin.as_system_origin_signer() else {
92            return Ok((Default::default(), Val::Refund(self.weight(call)), origin));
93        };
94
95        let account = frame_system::Account::<T>::get(who);
96        if account.providers.is_zero() && account.sufficients.is_zero() {
97            // Nonce storage not paid for
98            return Err(InvalidTransaction::Payment.into());
99        }
100        if self.0 < account.nonce {
101            return Err(InvalidTransaction::Stale.into());
102        }
103
104        let provides = vec![Encode::encode(&(who, self.0))];
105        let requires = if account.nonce < self.0 {
106            vec![Encode::encode(&(who, self.0.saturating_sub(One::one())))]
107        } else {
108            vec![]
109        };
110
111        let validity = ValidTransaction {
112            priority: 0,
113            requires,
114            provides,
115            longevity: TransactionLongevity::MAX,
116            propagate: true,
117        };
118
119        Ok((
120            validity,
121            Val::CheckNonce((who.clone(), account.nonce)),
122            origin,
123        ))
124    }
125
126    fn prepare(
127        self,
128        val: Self::Val,
129        _origin: &T::RuntimeOrigin,
130        _call: &T::RuntimeCall,
131        _info: &DispatchInfoOf<T::RuntimeCall>,
132        _len: usize,
133    ) -> Result<Self::Pre, TransactionValidityError> {
134        let (who, mut nonce) = match val {
135            Val::CheckNonce((who, nonce)) => (who, nonce),
136            Val::Refund(weight) => return Ok(Pre::Refund(weight)),
137        };
138
139        // if a sender sends an evm transaction first and substrate transaction
140        // after with same nonce, then reject the second transaction
141        // if sender reverse the transaction types, substrate first and evm second,
142        // evm transaction will be rejected, since substrate updates nonce in pre_dispatch.
143        let account_nonce = if let Some(tracked_nonce) = crate::AccountNonce::<T>::get(who.clone())
144        {
145            max(tracked_nonce.as_u32().into(), nonce)
146        } else {
147            nonce
148        };
149
150        if self.0 != account_nonce {
151            return Err(if self.0 < nonce {
152                InvalidTransaction::Stale
153            } else {
154                InvalidTransaction::Future
155            }
156            .into());
157        }
158        nonce = nonce
159            .checked_add(&T::Nonce::one())
160            .ok_or(InvalidTransaction::Custom(ERR_EVM_NONCE_OVERFLOW))?;
161        frame_system::Account::<T>::mutate(who, |account| account.nonce = nonce);
162        Ok(Pre::NonceChecked)
163    }
164
165    fn post_dispatch_details(
166        pre: Self::Pre,
167        _info: &DispatchInfo,
168        _post_info: &PostDispatchInfoOf<T::RuntimeCall>,
169        _len: usize,
170        _result: &DispatchResult,
171    ) -> Result<Weight, TransactionValidityError> {
172        match pre {
173            Pre::NonceChecked => Ok(Weight::zero()),
174            Pre::Refund(weight) => Ok(weight),
175        }
176    }
177}