Revert "FRAME: Create TransactionExtension as a replacement for SignedExtension (#2280)" (#3665)

This PR reverts #2280 which introduced `TransactionExtension` to replace
`SignedExtension`.

As a result of the discussion
[here](https://github.com/paritytech/polkadot-sdk/pull/3623#issuecomment-1986789700),
the changes will be reverted for now with plans to reintroduce the
concept in the future.

---------

Signed-off-by: georgepisaltu <george.pisaltu@parity.io>
This commit is contained in:
georgepisaltu
2024-03-13 16:10:59 +02:00
committed by GitHub
parent 60ac5a723c
commit bbd51ce867
350 changed files with 15826 additions and 24304 deletions
@@ -19,8 +19,7 @@ use crate::{pallet_prelude::BlockNumberFor, Config, Pallet};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::{
impl_tx_ext_default,
traits::{TransactionExtension, TransactionExtensionBase, Zero},
traits::{DispatchInfoOf, SignedExtension, Zero},
transaction_validity::TransactionValidityError,
};
@@ -47,26 +46,30 @@ impl<T: Config + Send + Sync> sp_std::fmt::Debug for CheckGenesis<T> {
}
impl<T: Config + Send + Sync> CheckGenesis<T> {
/// Creates new `TransactionExtension` to check genesis hash.
/// Creates new `SignedExtension` to check genesis hash.
pub fn new() -> Self {
Self(sp_std::marker::PhantomData)
}
}
impl<T: Config + Send + Sync> TransactionExtensionBase for CheckGenesis<T> {
impl<T: Config + Send + Sync> SignedExtension for CheckGenesis<T> {
type AccountId = T::AccountId;
type Call = <T as Config>::RuntimeCall;
type AdditionalSigned = T::Hash;
type Pre = ();
const IDENTIFIER: &'static str = "CheckGenesis";
type Implicit = T::Hash;
fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
Ok(<Pallet<T>>::block_hash(BlockNumberFor::<T>::zero()))
}
fn weight(&self) -> sp_weights::Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_genesis()
fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
self.validate(who, call, info, len).map(|_| ())
}
}
impl<T: Config + Send + Sync, Context> TransactionExtension<T::RuntimeCall, Context>
for CheckGenesis<T>
{
type Val = ();
type Pre = ();
impl_tx_ext_default!(T::RuntimeCall; Context; validate prepare);
}
@@ -20,12 +20,10 @@ use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::{
generic::Era,
impl_tx_ext_default,
traits::{
DispatchInfoOf, SaturatedConversion, TransactionExtension, TransactionExtensionBase,
ValidateResult,
traits::{DispatchInfoOf, SaturatedConversion, SignedExtension},
transaction_validity::{
InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,
},
transaction_validity::{InvalidTransaction, TransactionValidityError, ValidTransaction},
};
/// Check for transaction mortality.
@@ -56,11 +54,29 @@ impl<T: Config + Send + Sync> sp_std::fmt::Debug for CheckMortality<T> {
}
}
impl<T: Config + Send + Sync> TransactionExtensionBase for CheckMortality<T> {
impl<T: Config + Send + Sync> SignedExtension for CheckMortality<T> {
type AccountId = T::AccountId;
type Call = T::RuntimeCall;
type AdditionalSigned = T::Hash;
type Pre = ();
const IDENTIFIER: &'static str = "CheckMortality";
type Implicit = T::Hash;
fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
fn validate(
&self,
_who: &Self::AccountId,
_call: &Self::Call,
_info: &DispatchInfoOf<Self::Call>,
_len: usize,
) -> TransactionValidity {
let current_u64 = <Pallet<T>>::block_number().saturated_into::<u64>();
let valid_till = self.0.death(current_u64);
Ok(ValidTransaction {
longevity: valid_till.saturating_sub(current_u64),
..Default::default()
})
}
fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
let current_u64 = <Pallet<T>>::block_number().saturated_into::<u64>();
let n = self.0.birth(current_u64).saturated_into::<BlockNumberFor<T>>();
if !<BlockHash<T>>::contains_key(n) {
@@ -69,38 +85,16 @@ impl<T: Config + Send + Sync> TransactionExtensionBase for CheckMortality<T> {
Ok(<Pallet<T>>::block_hash(n))
}
}
fn weight(&self) -> sp_weights::Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_mortality()
}
}
impl<T: Config + Send + Sync, Context> TransactionExtension<T::RuntimeCall, Context>
for CheckMortality<T>
{
type Pre = ();
type Val = ();
fn validate(
&self,
origin: <T as Config>::RuntimeOrigin,
_call: &T::RuntimeCall,
_info: &DispatchInfoOf<T::RuntimeCall>,
_len: usize,
_context: &mut Context,
_self_implicit: Self::Implicit,
_inherited_implication: &impl Encode,
) -> ValidateResult<Self::Val, T::RuntimeCall> {
let current_u64 = <Pallet<T>>::block_number().saturated_into::<u64>();
let valid_till = self.0.death(current_u64);
Ok((
ValidTransaction {
longevity: valid_till.saturating_sub(current_u64),
..Default::default()
},
(),
origin,
))
fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
self.validate(who, call, info, len).map(|_| ())
}
impl_tx_ext_default!(T::RuntimeCall; Context; prepare);
}
#[cfg(test)]
@@ -112,21 +106,23 @@ mod tests {
weights::Weight,
};
use sp_core::H256;
use sp_runtime::traits::DispatchTransaction;
#[test]
fn signed_ext_check_era_should_work() {
new_test_ext().execute_with(|| {
// future
assert_eq!(
CheckMortality::<Test>::from(Era::mortal(4, 2)).implicit().err().unwrap(),
CheckMortality::<Test>::from(Era::mortal(4, 2))
.additional_signed()
.err()
.unwrap(),
InvalidTransaction::AncientBirthBlock.into(),
);
// correct
System::set_block_number(13);
<BlockHash<Test>>::insert(12, H256::repeat_byte(1));
assert!(CheckMortality::<Test>::from(Era::mortal(4, 12)).implicit().is_ok());
assert!(CheckMortality::<Test>::from(Era::mortal(4, 12)).additional_signed().is_ok());
})
}
@@ -146,10 +142,7 @@ mod tests {
System::set_block_number(17);
<BlockHash<Test>>::insert(16, H256::repeat_byte(1));
assert_eq!(
ext.validate_only(Some(1).into(), CALL, &normal, len).unwrap().0.longevity,
15
);
assert_eq!(ext.validate(&1, CALL, &normal, len).unwrap().longevity, 15);
})
}
}
@@ -17,14 +17,13 @@
use crate::Config;
use codec::{Decode, Encode};
use frame_support::{traits::OriginTrait, DefaultNoBound};
use frame_support::{dispatch::DispatchInfo, DefaultNoBound};
use scale_info::TypeInfo;
use sp_runtime::{
impl_tx_ext_default,
traits::{
transaction_extension::TransactionExtensionBase, DispatchInfoOf, TransactionExtension,
traits::{DispatchInfoOf, Dispatchable, SignedExtension},
transaction_validity::{
InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,
},
transaction_validity::InvalidTransaction,
};
use sp_std::{marker::PhantomData, prelude::*};
@@ -46,82 +45,66 @@ impl<T: Config + Send + Sync> sp_std::fmt::Debug for CheckNonZeroSender<T> {
}
impl<T: Config + Send + Sync> CheckNonZeroSender<T> {
/// Create new `TransactionExtension` to check runtime version.
/// Create new `SignedExtension` to check runtime version.
pub fn new() -> Self {
Self(sp_std::marker::PhantomData)
}
}
impl<T: Config + Send + Sync> TransactionExtensionBase for CheckNonZeroSender<T> {
const IDENTIFIER: &'static str = "CheckNonZeroSender";
type Implicit = ();
fn weight(&self) -> sp_weights::Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_non_zero_sender()
}
}
impl<T: Config + Send + Sync, Context> TransactionExtension<T::RuntimeCall, Context>
for CheckNonZeroSender<T>
impl<T: Config + Send + Sync> SignedExtension for CheckNonZeroSender<T>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
{
type Val = ();
type AccountId = T::AccountId;
type Call = T::RuntimeCall;
type AdditionalSigned = ();
type Pre = ();
const IDENTIFIER: &'static str = "CheckNonZeroSender";
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
Ok(())
}
fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
self.validate(who, call, info, len).map(|_| ())
}
fn validate(
&self,
origin: <T as Config>::RuntimeOrigin,
_call: &T::RuntimeCall,
_info: &DispatchInfoOf<T::RuntimeCall>,
who: &Self::AccountId,
_call: &Self::Call,
_info: &DispatchInfoOf<Self::Call>,
_len: usize,
_context: &mut Context,
_self_implicit: Self::Implicit,
_inherited_implication: &impl Encode,
) -> sp_runtime::traits::ValidateResult<Self::Val, T::RuntimeCall> {
if let Some(who) = origin.as_system_signer() {
if who.using_encoded(|d| d.iter().all(|x| *x == 0)) {
return Err(InvalidTransaction::BadSigner.into())
}
) -> TransactionValidity {
if who.using_encoded(|d| d.iter().all(|x| *x == 0)) {
return Err(TransactionValidityError::Invalid(InvalidTransaction::BadSigner))
}
Ok((Default::default(), (), origin))
Ok(ValidTransaction::default())
}
impl_tx_ext_default!(T::RuntimeCall; Context; prepare);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::{new_test_ext, Test, CALL};
use frame_support::{assert_ok, dispatch::DispatchInfo};
use sp_runtime::{traits::DispatchTransaction, TransactionValidityError};
use frame_support::{assert_noop, assert_ok};
#[test]
fn zero_account_ban_works() {
new_test_ext().execute_with(|| {
let info = DispatchInfo::default();
let len = 0_usize;
assert_eq!(
CheckNonZeroSender::<Test>::new()
.validate_only(Some(0).into(), CALL, &info, len)
.unwrap_err(),
TransactionValidityError::from(InvalidTransaction::BadSigner)
assert_noop!(
CheckNonZeroSender::<Test>::new().validate(&0, CALL, &info, len),
InvalidTransaction::BadSigner
);
assert_ok!(CheckNonZeroSender::<Test>::new().validate_only(
Some(1).into(),
CALL,
&info,
len
));
})
}
#[test]
fn unsigned_origin_works() {
new_test_ext().execute_with(|| {
let info = DispatchInfo::default();
let len = 0_usize;
assert_ok!(CheckNonZeroSender::<Test>::new().validate_only(
None.into(),
CALL,
&info,
len
));
assert_ok!(CheckNonZeroSender::<Test>::new().validate(&1, CALL, &info, len));
})
}
}
@@ -15,19 +15,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{AccountInfo, Config};
use crate::Config;
use codec::{Decode, Encode};
use frame_support::dispatch::DispatchInfo;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{
AsSystemOriginSigner, DispatchInfoOf, Dispatchable, One, TransactionExtension,
TransactionExtensionBase, ValidateResult, Zero,
},
traits::{DispatchInfoOf, Dispatchable, One, SignedExtension, Zero},
transaction_validity::{
InvalidTransaction, TransactionLongevity, TransactionValidityError, ValidTransaction,
InvalidTransaction, TransactionLongevity, TransactionValidity, TransactionValidityError,
ValidTransaction,
},
Saturating,
};
use sp_std::vec;
@@ -61,78 +58,75 @@ impl<T: Config> sp_std::fmt::Debug for CheckNonce<T> {
}
}
impl<T: Config> TransactionExtensionBase for CheckNonce<T> {
const IDENTIFIER: &'static str = "CheckNonce";
type Implicit = ();
fn weight(&self) -> sp_weights::Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_nonce()
}
}
impl<T: Config, Context> TransactionExtension<T::RuntimeCall, Context> for CheckNonce<T>
impl<T: Config> SignedExtension for CheckNonce<T>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo>,
<T::RuntimeCall as Dispatchable>::RuntimeOrigin: AsSystemOriginSigner<T::AccountId> + Clone,
{
type Val = Option<(T::AccountId, AccountInfo<T::Nonce, T::AccountData>)>;
type AccountId = T::AccountId;
type Call = T::RuntimeCall;
type AdditionalSigned = ();
type Pre = ();
const IDENTIFIER: &'static str = "CheckNonce";
fn validate(
&self,
origin: <T as Config>::RuntimeOrigin,
_call: &T::RuntimeCall,
_info: &DispatchInfoOf<T::RuntimeCall>,
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
Ok(())
}
fn pre_dispatch(
self,
who: &Self::AccountId,
_call: &Self::Call,
_info: &DispatchInfoOf<Self::Call>,
_len: usize,
_context: &mut Context,
_self_implicit: Self::Implicit,
_inherited_implication: &impl Encode,
) -> ValidateResult<Self::Val, T::RuntimeCall> {
let Some(who) = origin.as_system_origin_signer() else {
return Ok((Default::default(), None, origin))
};
let account = crate::Account::<T>::get(who);
) -> Result<(), TransactionValidityError> {
let mut account = crate::Account::<T>::get(who);
if account.providers.is_zero() && account.sufficients.is_zero() {
// Nonce storage not paid for
return Err(InvalidTransaction::Payment.into())
}
if self.0 != account.nonce {
return Err(if self.0 < account.nonce {
InvalidTransaction::Stale
} else {
InvalidTransaction::Future
}
.into())
}
account.nonce += T::Nonce::one();
crate::Account::<T>::insert(who, account);
Ok(())
}
fn validate(
&self,
who: &Self::AccountId,
_call: &Self::Call,
_info: &DispatchInfoOf<Self::Call>,
_len: usize,
) -> TransactionValidity {
let account = crate::Account::<T>::get(who);
if account.providers.is_zero() && account.sufficients.is_zero() {
// Nonce storage not paid for
return InvalidTransaction::Payment.into()
}
if self.0 < account.nonce {
return Err(InvalidTransaction::Stale.into())
return InvalidTransaction::Stale.into()
}
let provides = vec![Encode::encode(&(who.clone(), self.0))];
let provides = vec![Encode::encode(&(who, self.0))];
let requires = if account.nonce < self.0 {
vec![Encode::encode(&(who.clone(), self.0.saturating_sub(One::one())))]
vec![Encode::encode(&(who, self.0 - One::one()))]
} else {
vec![]
};
let validity = ValidTransaction {
Ok(ValidTransaction {
priority: 0,
requires,
provides,
longevity: TransactionLongevity::max_value(),
propagate: true,
};
Ok((validity, Some((who.clone(), account)), origin))
}
fn prepare(
self,
val: Self::Val,
_origin: &T::RuntimeOrigin,
_call: &T::RuntimeCall,
_info: &DispatchInfoOf<T::RuntimeCall>,
_len: usize,
_context: &Context,
) -> Result<Self::Pre, TransactionValidityError> {
let Some((who, mut account)) = val else { return Ok(()) };
// `self.0 < account.nonce` already checked in `validate`.
if self.0 > account.nonce {
return Err(InvalidTransaction::Future.into())
}
account.nonce.saturating_inc();
crate::Account::<T>::insert(who, account);
Ok(())
})
}
}
@@ -140,8 +134,7 @@ where
mod tests {
use super::*;
use crate::mock::{new_test_ext, Test, CALL};
use frame_support::assert_ok;
use sp_runtime::traits::DispatchTransaction;
use frame_support::{assert_noop, assert_ok};
#[test]
fn signed_ext_check_nonce_works() {
@@ -159,33 +152,22 @@ mod tests {
let info = DispatchInfo::default();
let len = 0_usize;
// stale
assert_eq!(
CheckNonce::<Test>(0)
.validate_only(Some(1).into(), CALL, &info, len,)
.unwrap_err(),
TransactionValidityError::Invalid(InvalidTransaction::Stale)
assert_noop!(
CheckNonce::<Test>(0).validate(&1, CALL, &info, len),
InvalidTransaction::Stale
);
assert_eq!(
CheckNonce::<Test>(0)
.validate_and_prepare(Some(1).into(), CALL, &info, len)
.unwrap_err(),
InvalidTransaction::Stale.into()
assert_noop!(
CheckNonce::<Test>(0).pre_dispatch(&1, CALL, &info, len),
InvalidTransaction::Stale
);
// correct
assert_ok!(CheckNonce::<Test>(1).validate_only(Some(1).into(), CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).validate_and_prepare(
Some(1).into(),
CALL,
&info,
len
));
assert_ok!(CheckNonce::<Test>(1).validate(&1, CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).pre_dispatch(&1, CALL, &info, len));
// future
assert_ok!(CheckNonce::<Test>(5).validate_only(Some(1).into(), CALL, &info, len));
assert_eq!(
CheckNonce::<Test>(5)
.validate_and_prepare(Some(1).into(), CALL, &info, len)
.unwrap_err(),
InvalidTransaction::Future.into()
assert_ok!(CheckNonce::<Test>(5).validate(&1, CALL, &info, len));
assert_noop!(
CheckNonce::<Test>(5).pre_dispatch(&1, CALL, &info, len),
InvalidTransaction::Future
);
})
}
@@ -216,44 +198,20 @@ mod tests {
let info = DispatchInfo::default();
let len = 0_usize;
// Both providers and sufficients zero
assert_eq!(
CheckNonce::<Test>(1)
.validate_only(Some(1).into(), CALL, &info, len)
.unwrap_err(),
TransactionValidityError::Invalid(InvalidTransaction::Payment)
assert_noop!(
CheckNonce::<Test>(1).validate(&1, CALL, &info, len),
InvalidTransaction::Payment
);
assert_eq!(
CheckNonce::<Test>(1)
.validate_and_prepare(Some(1).into(), CALL, &info, len)
.unwrap_err(),
TransactionValidityError::Invalid(InvalidTransaction::Payment)
assert_noop!(
CheckNonce::<Test>(1).pre_dispatch(&1, CALL, &info, len),
InvalidTransaction::Payment
);
// Non-zero providers
assert_ok!(CheckNonce::<Test>(1).validate_only(Some(2).into(), CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).validate_and_prepare(
Some(2).into(),
CALL,
&info,
len
));
assert_ok!(CheckNonce::<Test>(1).validate(&2, CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).pre_dispatch(&2, CALL, &info, len));
// Non-zero sufficients
assert_ok!(CheckNonce::<Test>(1).validate_only(Some(3).into(), CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).validate_and_prepare(
Some(3).into(),
CALL,
&info,
len
));
})
}
#[test]
fn unsigned_check_nonce_works() {
new_test_ext().execute_with(|| {
let info = DispatchInfo::default();
let len = 0_usize;
assert_ok!(CheckNonce::<Test>(1).validate_only(None.into(), CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).validate_and_prepare(None.into(), CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).validate(&3, CALL, &info, len));
assert_ok!(CheckNonce::<Test>(1).pre_dispatch(&3, CALL, &info, len));
})
}
}
@@ -19,8 +19,7 @@ use crate::{Config, Pallet};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::{
impl_tx_ext_default,
traits::{transaction_extension::TransactionExtensionBase, TransactionExtension},
traits::{DispatchInfoOf, SignedExtension},
transaction_validity::TransactionValidityError,
};
@@ -47,26 +46,30 @@ impl<T: Config + Send + Sync> sp_std::fmt::Debug for CheckSpecVersion<T> {
}
impl<T: Config + Send + Sync> CheckSpecVersion<T> {
/// Create new `TransactionExtension` to check runtime version.
/// Create new `SignedExtension` to check runtime version.
pub fn new() -> Self {
Self(sp_std::marker::PhantomData)
}
}
impl<T: Config + Send + Sync> TransactionExtensionBase for CheckSpecVersion<T> {
impl<T: Config + Send + Sync> SignedExtension for CheckSpecVersion<T> {
type AccountId = T::AccountId;
type Call = <T as Config>::RuntimeCall;
type AdditionalSigned = u32;
type Pre = ();
const IDENTIFIER: &'static str = "CheckSpecVersion";
type Implicit = u32;
fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
Ok(<Pallet<T>>::runtime_version().spec_version)
}
fn weight(&self) -> sp_weights::Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_spec_version()
fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
self.validate(who, call, info, len).map(|_| ())
}
}
impl<T: Config + Send + Sync, Context> TransactionExtension<<T as Config>::RuntimeCall, Context>
for CheckSpecVersion<T>
{
type Val = ();
type Pre = ();
impl_tx_ext_default!(<T as Config>::RuntimeCall; Context; validate prepare);
}
@@ -19,8 +19,7 @@ use crate::{Config, Pallet};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::{
impl_tx_ext_default,
traits::{transaction_extension::TransactionExtensionBase, TransactionExtension},
traits::{DispatchInfoOf, SignedExtension},
transaction_validity::TransactionValidityError,
};
@@ -47,26 +46,29 @@ impl<T: Config + Send + Sync> sp_std::fmt::Debug for CheckTxVersion<T> {
}
impl<T: Config + Send + Sync> CheckTxVersion<T> {
/// Create new `TransactionExtension` to check transaction version.
/// Create new `SignedExtension` to check transaction version.
pub fn new() -> Self {
Self(sp_std::marker::PhantomData)
}
}
impl<T: Config + Send + Sync> TransactionExtensionBase for CheckTxVersion<T> {
impl<T: Config + Send + Sync> SignedExtension for CheckTxVersion<T> {
type AccountId = T::AccountId;
type Call = <T as Config>::RuntimeCall;
type AdditionalSigned = u32;
type Pre = ();
const IDENTIFIER: &'static str = "CheckTxVersion";
type Implicit = u32;
fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
Ok(<Pallet<T>>::runtime_version().transaction_version)
}
fn weight(&self) -> sp_weights::Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_tx_version()
fn pre_dispatch(
self,
who: &Self::AccountId,
call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
self.validate(who, call, info, len).map(|_| ())
}
}
impl<T: Config + Send + Sync, Context> TransactionExtension<<T as Config>::RuntimeCall, Context>
for CheckTxVersion<T>
{
type Val = ();
type Pre = ();
impl_tx_ext_default!(<T as Config>::RuntimeCall; Context; validate prepare);
}
@@ -23,12 +23,9 @@ use frame_support::{
};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{
DispatchInfoOf, Dispatchable, PostDispatchInfoOf, TransactionExtension,
TransactionExtensionBase, ValidateResult,
},
transaction_validity::{InvalidTransaction, TransactionValidityError},
DispatchResult, ValidTransaction,
traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SignedExtension},
transaction_validity::{InvalidTransaction, TransactionValidity, TransactionValidityError},
DispatchResult,
};
use sp_weights::Weight;
@@ -103,44 +100,40 @@ where
}
}
/// Creates new `TransactionExtension` to check weight of the extrinsic.
/// Creates new `SignedExtension` to check weight of the extrinsic.
pub fn new() -> Self {
Self(Default::default())
}
/// Do the validate checks. This can be applied to both signed and unsigned.
///
/// It only checks that the block weight and length limit will not exceed.
///
/// Returns the transaction validity and the next block length, to be used in `prepare`.
pub fn do_validate(
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
) -> Result<(ValidTransaction, u32), TransactionValidityError> {
// ignore the next length. If they return `Ok`, then it is below the limit.
let next_len = Self::check_block_length(info, len)?;
// during validation we skip block limit check. Since the `validate_transaction`
// call runs on an empty block anyway, by this we prevent `on_initialize` weight
// consumption from causing false negatives.
Self::check_extrinsic_weight(info)?;
Ok((Default::default(), next_len))
}
/// Do the pre-dispatch checks. This can be applied to both signed and unsigned.
///
/// It checks and notes the new weight and length.
pub fn do_prepare(
pub fn do_pre_dispatch(
info: &DispatchInfoOf<T::RuntimeCall>,
next_len: u32,
len: usize,
) -> Result<(), TransactionValidityError> {
let next_len = Self::check_block_length(info, len)?;
let next_weight = Self::check_block_weight(info)?;
// Extrinsic weight already checked in `validate`.
Self::check_extrinsic_weight(info)?;
crate::AllExtrinsicsLen::<T>::put(next_len);
crate::BlockWeight::<T>::put(next_weight);
Ok(())
}
/// Do the validate checks. This can be applied to both signed and unsigned.
///
/// It only checks that the block weight and length limit will not exceed.
pub fn do_validate(info: &DispatchInfoOf<T::RuntimeCall>, len: usize) -> TransactionValidity {
// ignore the next length. If they return `Ok`, then it is below the limit.
let _ = Self::check_block_length(info, len)?;
// during validation we skip block limit check. Since the `validate_transaction`
// call runs on an empty block anyway, by this we prevent `on_initialize` weight
// consumption from causing false negatives.
Self::check_extrinsic_weight(info)?;
Ok(Default::default())
}
}
pub fn calculate_consumed_weight<Call>(
@@ -208,55 +201,62 @@ where
Ok(all_weight)
}
impl<T: Config + Send + Sync> TransactionExtensionBase for CheckWeight<T> {
const IDENTIFIER: &'static str = "CheckWeight";
type Implicit = ();
fn weight(&self) -> Weight {
<T::ExtensionsWeightInfo as super::WeightInfo>::check_weight()
}
}
impl<T: Config + Send + Sync, Context> TransactionExtension<T::RuntimeCall, Context>
for CheckWeight<T>
impl<T: Config + Send + Sync> SignedExtension for CheckWeight<T>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
type AccountId = T::AccountId;
type Call = T::RuntimeCall;
type AdditionalSigned = ();
type Pre = ();
type Val = u32; /* next block length */
const IDENTIFIER: &'static str = "CheckWeight";
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
Ok(())
}
fn pre_dispatch(
self,
_who: &Self::AccountId,
_call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<(), TransactionValidityError> {
Self::do_pre_dispatch(info, len)
}
fn validate(
&self,
origin: T::RuntimeOrigin,
_call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
_who: &Self::AccountId,
_call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
_context: &mut Context,
_self_implicit: Self::Implicit,
_inherited_implication: &impl Encode,
) -> ValidateResult<Self::Val, T::RuntimeCall> {
let (validity, next_len) = Self::do_validate(info, len)?;
Ok((validity, next_len, origin))
) -> TransactionValidity {
Self::do_validate(info, len)
}
fn prepare(
self,
val: Self::Val,
_origin: &T::RuntimeOrigin,
_call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
_len: usize,
_context: &Context,
) -> Result<Self::Pre, TransactionValidityError> {
Self::do_prepare(info, val)
fn pre_dispatch_unsigned(
_call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<(), TransactionValidityError> {
Self::do_pre_dispatch(info, len)
}
fn validate_unsigned(
_call: &Self::Call,
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> TransactionValidity {
Self::do_validate(info, len)
}
fn post_dispatch(
_pre: Self::Pre,
info: &DispatchInfoOf<T::RuntimeCall>,
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
_pre: Option<Self::Pre>,
info: &DispatchInfoOf<Self::Call>,
post_info: &PostDispatchInfoOf<Self::Call>,
_len: usize,
_result: &DispatchResult,
_context: &Context,
) -> Result<(), TransactionValidityError> {
let unspent = post_info.calc_unspent(info);
if unspent.any_gt(Weight::zero()) {
@@ -301,7 +301,6 @@ mod tests {
AllExtrinsicsLen, BlockWeight, DispatchClass,
};
use frame_support::{assert_err, assert_ok, dispatch::Pays, weights::Weight};
use sp_runtime::traits::DispatchTransaction;
use sp_std::marker::PhantomData;
fn block_weights() -> crate::limits::BlockWeights {
@@ -339,8 +338,7 @@ mod tests {
}
check(|max, len| {
let next_len = CheckWeight::<Test>::check_block_length(max, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(max, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(max, len));
assert_eq!(System::block_weight().total(), Weight::MAX);
assert!(System::block_weight().total().ref_time() > block_weight_limit().ref_time());
});
@@ -421,11 +419,9 @@ mod tests {
let len = 0_usize;
let next_len = CheckWeight::<Test>::check_block_length(&max_normal, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(&max_normal, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max_normal, len));
assert_eq!(System::block_weight().total(), Weight::from_parts(768, 0));
let next_len = CheckWeight::<Test>::check_block_length(&rest_operational, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(&rest_operational, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&rest_operational, len));
assert_eq!(block_weight_limit(), Weight::from_parts(1024, u64::MAX));
assert_eq!(System::block_weight().total(), block_weight_limit().set_proof_size(0));
// Checking single extrinsic should not take current block weight into account.
@@ -447,12 +443,10 @@ mod tests {
let len = 0_usize;
let next_len = CheckWeight::<Test>::check_block_length(&rest_operational, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(&rest_operational, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&rest_operational, len));
// Extra 20 here from block execution + base extrinsic weight
assert_eq!(System::block_weight().total(), Weight::from_parts(266, 0));
let next_len = CheckWeight::<Test>::check_block_length(&max_normal, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(&max_normal, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max_normal, len));
assert_eq!(block_weight_limit(), Weight::from_parts(1024, u64::MAX));
assert_eq!(System::block_weight().total(), block_weight_limit().set_proof_size(0));
});
@@ -475,19 +469,16 @@ mod tests {
};
let len = 0_usize;
let next_len = CheckWeight::<Test>::check_block_length(&dispatch_normal, len).unwrap();
assert_err!(
CheckWeight::<Test>::do_prepare(&dispatch_normal, next_len),
CheckWeight::<Test>::do_pre_dispatch(&dispatch_normal, len),
InvalidTransaction::ExhaustsResources
);
let next_len =
CheckWeight::<Test>::check_block_length(&dispatch_operational, len).unwrap();
// Thank goodness we can still do an operational transaction to possibly save the
// blockchain.
assert_ok!(CheckWeight::<Test>::do_prepare(&dispatch_operational, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&dispatch_operational, len));
// Not too much though
assert_err!(
CheckWeight::<Test>::do_prepare(&dispatch_operational, next_len),
CheckWeight::<Test>::do_pre_dispatch(&dispatch_operational, len),
InvalidTransaction::ExhaustsResources
);
// Even with full block, validity of single transaction should be correct.
@@ -512,35 +503,21 @@ mod tests {
current_weight.set(normal_limit, DispatchClass::Normal)
});
// will not fit.
assert_eq!(
CheckWeight::<Test>(PhantomData)
.validate_and_prepare(Some(1).into(), CALL, &normal, len)
.unwrap_err(),
InvalidTransaction::ExhaustsResources.into()
assert_err!(
CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &normal, len),
InvalidTransaction::ExhaustsResources
);
// will fit.
assert_ok!(CheckWeight::<Test>(PhantomData).validate_and_prepare(
Some(1).into(),
CALL,
&op,
len
));
assert_ok!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &op, len));
// likewise for length limit.
let len = 100_usize;
AllExtrinsicsLen::<Test>::put(normal_length_limit());
assert_eq!(
CheckWeight::<Test>(PhantomData)
.validate_and_prepare(Some(1).into(), CALL, &normal, len)
.unwrap_err(),
InvalidTransaction::ExhaustsResources.into()
assert_err!(
CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &normal, len),
InvalidTransaction::ExhaustsResources
);
assert_ok!(CheckWeight::<Test>(PhantomData).validate_and_prepare(
Some(1).into(),
CALL,
&op,
len
));
assert_ok!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &op, len));
})
}
@@ -551,12 +528,7 @@ mod tests {
let normal_limit = normal_weight_limit().ref_time() as usize;
let reset_check_weight = |tx, s, f| {
AllExtrinsicsLen::<Test>::put(0);
let r = CheckWeight::<Test>(PhantomData).validate_and_prepare(
Some(1).into(),
CALL,
tx,
s,
);
let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, tx, s);
if f {
assert!(r.is_err())
} else {
@@ -599,12 +571,7 @@ mod tests {
BlockWeight::<Test>::mutate(|current_weight| {
current_weight.set(s, DispatchClass::Normal)
});
let r = CheckWeight::<Test>(PhantomData).validate_and_prepare(
Some(1).into(),
CALL,
i,
len,
);
let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, i, len);
if f {
assert!(r.is_err())
} else {
@@ -637,22 +604,18 @@ mod tests {
.set(Weight::from_parts(256, 0) - base_extrinsic, DispatchClass::Normal);
});
let pre = CheckWeight::<Test>(PhantomData)
.validate_and_prepare(Some(1).into(), CALL, &info, len)
.unwrap()
.0;
let pre = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap();
assert_eq!(
BlockWeight::<Test>::get().total(),
info.weight + Weight::from_parts(256, 0)
);
assert_ok!(CheckWeight::<Test>::post_dispatch(
pre,
Some(pre),
&info,
&post_info,
len,
&Ok(()),
&()
&Ok(())
));
assert_eq!(
BlockWeight::<Test>::get().total(),
@@ -676,10 +639,7 @@ mod tests {
current_weight.set(Weight::from_parts(128, 0), DispatchClass::Normal);
});
let pre = CheckWeight::<Test>(PhantomData)
.validate_and_prepare(Some(1).into(), CALL, &info, len)
.unwrap()
.0;
let pre = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap();
assert_eq!(
BlockWeight::<Test>::get().total(),
info.weight +
@@ -688,12 +648,11 @@ mod tests {
);
assert_ok!(CheckWeight::<Test>::post_dispatch(
pre,
Some(pre),
&info,
&post_info,
len,
&Ok(()),
&()
&Ok(())
));
assert_eq!(
BlockWeight::<Test>::get().total(),
@@ -713,12 +672,7 @@ mod tests {
// Initial weight from `weights.base_block`
assert_eq!(System::block_weight().total(), weights.base_block);
assert_ok!(CheckWeight::<Test>(PhantomData).validate_and_prepare(
Some(1).into(),
CALL,
&free,
len
));
assert_ok!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &free, len));
assert_eq!(
System::block_weight().total(),
weights.get(DispatchClass::Normal).base_extrinsic + weights.base_block
@@ -742,11 +696,9 @@ mod tests {
let len = 0_usize;
let next_len = CheckWeight::<Test>::check_block_length(&max_normal, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(&max_normal, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&max_normal, len));
assert_eq!(System::block_weight().total(), Weight::from_parts(768, 0));
let next_len = CheckWeight::<Test>::check_block_length(&mandatory, len).unwrap();
assert_ok!(CheckWeight::<Test>::do_prepare(&mandatory, next_len));
assert_ok!(CheckWeight::<Test>::do_pre_dispatch(&mandatory, len));
assert_eq!(block_weight_limit(), Weight::from_parts(1024, u64::MAX));
assert_eq!(System::block_weight().total(), Weight::from_parts(1024 + 768, 0));
assert_eq!(CheckWeight::<Test>::check_extrinsic_weight(&mandatory), Ok(()));
@@ -22,6 +22,3 @@ pub mod check_nonce;
pub mod check_spec_version;
pub mod check_tx_version;
pub mod check_weight;
pub mod weights;
pub use weights::WeightInfo;
@@ -1,196 +0,0 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Autogenerated weights for `frame_system_extensions`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2024-03-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `runner-bn-ce5rx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024`
// Executed Command:
// ./target/production/substrate-node
// benchmark
// pallet
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=frame_system_extensions
// --no-storage-info
// --no-median-slopes
// --no-min-squares
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=4096
// --output=./substrate/frame/system/src/extensions/weights.rs
// --header=./substrate/HEADER-APACHE2
// --template=./substrate/.maintain/frame-weight-template.hbs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]
use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use core::marker::PhantomData;
/// Weight functions needed for `frame_system_extensions`.
pub trait WeightInfo {
fn check_genesis() -> Weight;
fn check_mortality() -> Weight;
fn check_non_zero_sender() -> Weight;
fn check_nonce() -> Weight;
fn check_spec_version() -> Weight;
fn check_tx_version() -> Weight;
fn check_weight() -> Weight;
}
/// Weights for `frame_system_extensions` using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: crate::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `System::BlockHash` (r:1 w:0)
/// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`)
fn check_genesis() -> Weight {
// Proof Size summary in bytes:
// Measured: `54`
// Estimated: `3509`
// Minimum execution time: 3_876_000 picoseconds.
Weight::from_parts(4_160_000, 3509)
.saturating_add(T::DbWeight::get().reads(1_u64))
}
/// Storage: `System::BlockHash` (r:1 w:0)
/// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`)
fn check_mortality() -> Weight {
// Proof Size summary in bytes:
// Measured: `92`
// Estimated: `3509`
// Minimum execution time: 6_296_000 picoseconds.
Weight::from_parts(6_523_000, 3509)
.saturating_add(T::DbWeight::get().reads(1_u64))
}
fn check_non_zero_sender() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 449_000 picoseconds.
Weight::from_parts(527_000, 0)
}
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn check_nonce() -> Weight {
// Proof Size summary in bytes:
// Measured: `101`
// Estimated: `3593`
// Minimum execution time: 5_689_000 picoseconds.
Weight::from_parts(6_000_000, 3593)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
fn check_spec_version() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 399_000 picoseconds.
Weight::from_parts(461_000, 0)
}
fn check_tx_version() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 390_000 picoseconds.
Weight::from_parts(439_000, 0)
}
/// Storage: `System::AllExtrinsicsLen` (r:1 w:1)
/// Proof: `System::AllExtrinsicsLen` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`)
fn check_weight() -> Weight {
// Proof Size summary in bytes:
// Measured: `24`
// Estimated: `1489`
// Minimum execution time: 4_375_000 picoseconds.
Weight::from_parts(4_747_000, 1489)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
}
// For backwards compatibility and tests.
impl WeightInfo for () {
/// Storage: `System::BlockHash` (r:1 w:0)
/// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`)
fn check_genesis() -> Weight {
// Proof Size summary in bytes:
// Measured: `54`
// Estimated: `3509`
// Minimum execution time: 3_876_000 picoseconds.
Weight::from_parts(4_160_000, 3509)
.saturating_add(RocksDbWeight::get().reads(1_u64))
}
/// Storage: `System::BlockHash` (r:1 w:0)
/// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`)
fn check_mortality() -> Weight {
// Proof Size summary in bytes:
// Measured: `92`
// Estimated: `3509`
// Minimum execution time: 6_296_000 picoseconds.
Weight::from_parts(6_523_000, 3509)
.saturating_add(RocksDbWeight::get().reads(1_u64))
}
fn check_non_zero_sender() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 449_000 picoseconds.
Weight::from_parts(527_000, 0)
}
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn check_nonce() -> Weight {
// Proof Size summary in bytes:
// Measured: `101`
// Estimated: `3593`
// Minimum execution time: 5_689_000 picoseconds.
Weight::from_parts(6_000_000, 3593)
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
fn check_spec_version() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 399_000 picoseconds.
Weight::from_parts(461_000, 0)
}
fn check_tx_version() -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 390_000 picoseconds.
Weight::from_parts(439_000, 0)
}
/// Storage: `System::AllExtrinsicsLen` (r:1 w:1)
/// Proof: `System::AllExtrinsicsLen` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`)
fn check_weight() -> Weight {
// Proof Size summary in bytes:
// Measured: `24`
// Estimated: `1489`
// Minimum execution time: 4_375_000 picoseconds.
Weight::from_parts(4_747_000, 1489)
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
}