mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-14 16:51:03 +00:00
Merge remote-tracking branch 'origin/master' into gav-xcm-v3
This commit is contained in:
@@ -1,52 +0,0 @@
|
||||
[package]
|
||||
name = "pallet-asset-tx-payment"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
license = "Apache-2.0"
|
||||
homepage = "https://substrate.io"
|
||||
repository = "https://github.com/paritytech/cumulus/"
|
||||
description = "pallet to manage transaction payments in assets"
|
||||
readme = "README.md"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
# Substrate dependencies
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
# Other dependencies
|
||||
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0.101", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
smallvec = "1.4.1"
|
||||
serde_json = "1.0.41"
|
||||
|
||||
pallet-assets = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-authorship = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-storage = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde",
|
||||
"codec/std",
|
||||
"sp-std/std",
|
||||
"sp-runtime/std",
|
||||
"frame-support/std",
|
||||
"frame-system/std",
|
||||
"sp-io/std",
|
||||
"sp-core/std",
|
||||
"pallet-transaction-payment/std",
|
||||
]
|
||||
try-runtime = ["frame-support/try-runtime"]
|
||||
@@ -1,21 +0,0 @@
|
||||
# pallet-asset-tx-payment
|
||||
|
||||
## Asset Transaction Payment Pallet
|
||||
|
||||
This pallet allows runtimes that include it to pay for transactions in assets other than the
|
||||
native token of the chain.
|
||||
|
||||
### Overview
|
||||
It does this by extending transactions to include an optional `AssetId` that specifies the asset
|
||||
to be used for payment (defaulting to the native token on `None`). It expects an
|
||||
[`OnChargeAssetTransaction`] implementation analogously to [`pallet-transaction-payment`]. The
|
||||
included [`FungiblesAdapter`] (implementing [`OnChargeAssetTransaction`]) determines the fee
|
||||
amount by converting the fee calculated by [`pallet-transaction-payment`] into the desired
|
||||
asset.
|
||||
|
||||
### Integration
|
||||
This pallet wraps FRAME's transaction payment pallet and functions as a replacement. This means
|
||||
you should include both pallets in your `construct_runtime` macro, but only include this
|
||||
pallet's [`SignedExtension`] ([`ChargeAssetTxPayment`]).
|
||||
|
||||
License: Apache-2.0
|
||||
@@ -1,295 +0,0 @@
|
||||
// Copyright (C) 2021 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.
|
||||
|
||||
//! # Asset Transaction Payment Pallet
|
||||
//!
|
||||
//! This pallet allows runtimes that include it to pay for transactions in assets other than the
|
||||
//! main token of the chain.
|
||||
//!
|
||||
//! ## Overview
|
||||
//! It does this by extending transactions to include an optional `AssetId` that specifies the asset
|
||||
//! to be used for payment (defaulting to the native token on `None`). It expects an
|
||||
//! [`OnChargeAssetTransaction`] implementation analogously to [`pallet-transaction-payment`]. The
|
||||
//! included [`FungiblesAdapter`] (implementing [`OnChargeAssetTransaction`]) determines the fee
|
||||
//! amount by converting the fee calculated by [`pallet-transaction-payment`] into the desired
|
||||
//! asset.
|
||||
//!
|
||||
//! ## Integration
|
||||
//! This pallet wraps FRAME's transaction payment pallet and functions as a replacement. This means
|
||||
//! you should include both pallets in your `construct_runtime` macro, but only include this
|
||||
//! pallet's [`SignedExtension`] ([`ChargeAssetTxPayment`]).
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use sp_std::prelude::*;
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
use frame_support::{
|
||||
dispatch::DispatchResult,
|
||||
traits::{
|
||||
tokens::{
|
||||
fungibles::{Balanced, CreditOf, Inspect},
|
||||
WithdrawConsequence,
|
||||
},
|
||||
IsType,
|
||||
},
|
||||
weights::{DispatchInfo, PostDispatchInfo},
|
||||
DefaultNoBound,
|
||||
};
|
||||
use pallet_transaction_payment::OnChargeTransaction;
|
||||
use scale_info::TypeInfo;
|
||||
use sp_runtime::{
|
||||
traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SignedExtension, Zero},
|
||||
transaction_validity::{
|
||||
InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,
|
||||
},
|
||||
FixedPointOperand,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
mod payment;
|
||||
pub use payment::*;
|
||||
|
||||
// Type aliases used for interaction with `OnChargeTransaction`.
|
||||
pub(crate) type OnChargeTransactionOf<T> =
|
||||
<T as pallet_transaction_payment::Config>::OnChargeTransaction;
|
||||
// Balance type alias.
|
||||
pub(crate) type BalanceOf<T> = <OnChargeTransactionOf<T> as OnChargeTransaction<T>>::Balance;
|
||||
// Liquity info type alias.
|
||||
pub(crate) type LiquidityInfoOf<T> =
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::LiquidityInfo;
|
||||
|
||||
// Type alias used for interaction with fungibles (assets).
|
||||
// Balance type alias.
|
||||
pub(crate) type AssetBalanceOf<T> =
|
||||
<<T as Config>::Fungibles as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
|
||||
/// Asset id type alias.
|
||||
pub(crate) type AssetIdOf<T> =
|
||||
<<T as Config>::Fungibles as Inspect<<T as frame_system::Config>::AccountId>>::AssetId;
|
||||
|
||||
// Type aliases used for interaction with `OnChargeAssetTransaction`.
|
||||
// Balance type alias.
|
||||
pub(crate) type ChargeAssetBalanceOf<T> =
|
||||
<<T as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<T>>::Balance;
|
||||
// Asset id type alias.
|
||||
pub(crate) type ChargeAssetIdOf<T> =
|
||||
<<T as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<T>>::AssetId;
|
||||
// Liquity info type alias.
|
||||
pub(crate) type ChargeAssetLiquidityOf<T> =
|
||||
<<T as Config>::OnChargeAssetTransaction as OnChargeAssetTransaction<T>>::LiquidityInfo;
|
||||
|
||||
/// Used to pass the initial payment info from pre- to post-dispatch.
|
||||
#[derive(Encode, Decode, DefaultNoBound, TypeInfo)]
|
||||
pub enum InitialPayment<T: Config> {
|
||||
/// No initial fee was payed.
|
||||
Nothing,
|
||||
/// The initial fee was payed in the native currency.
|
||||
Native(LiquidityInfoOf<T>),
|
||||
/// The initial fee was payed in an asset.
|
||||
Asset(CreditOf<T::AccountId, T::Fungibles>),
|
||||
}
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
|
||||
use frame_support::pallet_prelude::*;
|
||||
use frame_system::pallet_prelude::*;
|
||||
|
||||
#[pallet::config]
|
||||
pub trait Config: frame_system::Config + pallet_transaction_payment::Config {
|
||||
/// The fungibles instance used to pay for transactions in assets.
|
||||
type Fungibles: Balanced<Self::AccountId>;
|
||||
/// The actual transaction charging logic that charges the fees.
|
||||
type OnChargeAssetTransaction: OnChargeAssetTransaction<Self>;
|
||||
}
|
||||
|
||||
#[pallet::pallet]
|
||||
#[pallet::generate_store(pub(super) trait Store)]
|
||||
pub struct Pallet<T>(_);
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
|
||||
|
||||
#[pallet::call]
|
||||
impl<T: Config> Pallet<T> {}
|
||||
}
|
||||
|
||||
/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
|
||||
/// in the queue. Allows paying via both `Currency` as well as `fungibles::Balanced`.
|
||||
///
|
||||
/// Wraps the transaction logic in [`pallet_transaction_payment`] and extends it with assets.
|
||||
/// An asset id of `None` falls back to the underlying transaction payment via the native currency.
|
||||
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
|
||||
#[scale_info(skip_type_params(T))]
|
||||
pub struct ChargeAssetTxPayment<T: Config> {
|
||||
#[codec(compact)]
|
||||
tip: BalanceOf<T>,
|
||||
asset_id: Option<ChargeAssetIdOf<T>>,
|
||||
}
|
||||
|
||||
impl<T: Config> ChargeAssetTxPayment<T>
|
||||
where
|
||||
T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
AssetBalanceOf<T>: Send + Sync + FixedPointOperand,
|
||||
BalanceOf<T>: Send + Sync + FixedPointOperand + IsType<ChargeAssetBalanceOf<T>>,
|
||||
ChargeAssetIdOf<T>: Send + Sync,
|
||||
CreditOf<T::AccountId, T::Fungibles>: IsType<ChargeAssetLiquidityOf<T>>,
|
||||
{
|
||||
/// utility constructor. Used only in client/factory code.
|
||||
pub fn from(tip: BalanceOf<T>, asset_id: Option<ChargeAssetIdOf<T>>) -> Self {
|
||||
Self { tip, asset_id }
|
||||
}
|
||||
|
||||
/// Fee withdrawal logic that dispatches to either `OnChargeAssetTransaction` or `OnChargeTransaction`.
|
||||
fn withdraw_fee(
|
||||
&self,
|
||||
who: &T::AccountId,
|
||||
call: &T::Call,
|
||||
info: &DispatchInfoOf<T::Call>,
|
||||
len: usize,
|
||||
) -> Result<(BalanceOf<T>, InitialPayment<T>), TransactionValidityError> {
|
||||
let fee = pallet_transaction_payment::Pallet::<T>::compute_fee(len as u32, info, self.tip);
|
||||
debug_assert!(self.tip <= fee, "tip should be included in the computed fee");
|
||||
if fee.is_zero() {
|
||||
Ok((fee, InitialPayment::Nothing))
|
||||
} else if let Some(asset_id) = self.asset_id {
|
||||
T::OnChargeAssetTransaction::withdraw_fee(
|
||||
who,
|
||||
call,
|
||||
info,
|
||||
asset_id,
|
||||
fee.into(),
|
||||
self.tip.into(),
|
||||
)
|
||||
.map(|i| (fee, InitialPayment::Asset(i.into())))
|
||||
} else {
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::withdraw_fee(
|
||||
who, call, info, fee, self.tip,
|
||||
)
|
||||
.map(|i| (fee, InitialPayment::Native(i)))
|
||||
.map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> sp_std::fmt::Debug for ChargeAssetTxPayment<T> {
|
||||
#[cfg(feature = "std")]
|
||||
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
|
||||
write!(f, "ChargeAssetTxPayment<{:?}, {:?}>", self.tip, self.asset_id.encode())
|
||||
}
|
||||
#[cfg(not(feature = "std"))]
|
||||
fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> SignedExtension for ChargeAssetTxPayment<T>
|
||||
where
|
||||
T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
|
||||
AssetBalanceOf<T>: Send + Sync + FixedPointOperand,
|
||||
BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand + IsType<ChargeAssetBalanceOf<T>>,
|
||||
ChargeAssetIdOf<T>: Send + Sync,
|
||||
CreditOf<T::AccountId, T::Fungibles>: IsType<ChargeAssetLiquidityOf<T>>,
|
||||
{
|
||||
const IDENTIFIER: &'static str = "ChargeAssetTxPayment";
|
||||
type AccountId = T::AccountId;
|
||||
type Call = T::Call;
|
||||
type AdditionalSigned = ();
|
||||
type Pre = (
|
||||
// tip
|
||||
BalanceOf<T>,
|
||||
// who paid the fee
|
||||
Self::AccountId,
|
||||
// imbalance resulting from withdrawing the fee
|
||||
InitialPayment<T>,
|
||||
);
|
||||
|
||||
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(
|
||||
&self,
|
||||
who: &Self::AccountId,
|
||||
call: &Self::Call,
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> TransactionValidity {
|
||||
use pallet_transaction_payment::ChargeTransactionPayment;
|
||||
let (fee, _) = self.withdraw_fee(who, call, info, len)?;
|
||||
let priority = ChargeTransactionPayment::<T>::get_priority(info, len, self.tip, fee);
|
||||
Ok(ValidTransaction { priority, ..Default::default() })
|
||||
}
|
||||
|
||||
fn pre_dispatch(
|
||||
self,
|
||||
who: &Self::AccountId,
|
||||
call: &Self::Call,
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
) -> Result<Self::Pre, TransactionValidityError> {
|
||||
let (_fee, initial_payment) = self.withdraw_fee(who, call, info, len)?;
|
||||
Ok((self.tip, who.clone(), initial_payment))
|
||||
}
|
||||
|
||||
fn post_dispatch(
|
||||
pre: Self::Pre,
|
||||
info: &DispatchInfoOf<Self::Call>,
|
||||
post_info: &PostDispatchInfoOf<Self::Call>,
|
||||
len: usize,
|
||||
_result: &DispatchResult,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
let (tip, who, initial_payment) = pre;
|
||||
let actual_fee = pallet_transaction_payment::Pallet::<T>::compute_actual_fee(
|
||||
len as u32, info, post_info, tip,
|
||||
);
|
||||
match initial_payment {
|
||||
InitialPayment::Native(already_withdrawn) => {
|
||||
<OnChargeTransactionOf<T> as OnChargeTransaction<T>>::correct_and_deposit_fee(
|
||||
&who,
|
||||
info,
|
||||
post_info,
|
||||
actual_fee,
|
||||
tip,
|
||||
already_withdrawn,
|
||||
)?;
|
||||
},
|
||||
InitialPayment::Asset(already_withdrawn) => {
|
||||
T::OnChargeAssetTransaction::correct_and_deposit_fee(
|
||||
&who,
|
||||
info,
|
||||
post_info,
|
||||
actual_fee.into(),
|
||||
tip.into(),
|
||||
already_withdrawn.into(),
|
||||
)?;
|
||||
},
|
||||
InitialPayment::Nothing => {
|
||||
debug_assert!(
|
||||
actual_fee.is_zero(),
|
||||
"actual fee should be zero if initial fee was zero."
|
||||
);
|
||||
debug_assert!(tip.is_zero(), "tip should be zero if initial fee was zero.");
|
||||
},
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
// Copyright (C) 2021 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.
|
||||
|
||||
///! Traits and default implementation for paying transaction fees in assets.
|
||||
use super::*;
|
||||
use crate::Config;
|
||||
|
||||
use codec::FullCodec;
|
||||
use frame_support::{
|
||||
traits::{
|
||||
fungibles::{Balanced, CreditOf, Inspect},
|
||||
tokens::BalanceConversion,
|
||||
},
|
||||
unsigned::TransactionValidityError,
|
||||
};
|
||||
use scale_info::TypeInfo;
|
||||
use sp_runtime::{
|
||||
traits::{
|
||||
AtLeast32BitUnsigned, DispatchInfoOf, MaybeSerializeDeserialize, One, PostDispatchInfoOf,
|
||||
},
|
||||
transaction_validity::InvalidTransaction,
|
||||
};
|
||||
use sp_std::{fmt::Debug, marker::PhantomData};
|
||||
|
||||
/// Handle withdrawing, refunding and depositing of transaction fees.
|
||||
pub trait OnChargeAssetTransaction<T: Config> {
|
||||
/// The underlying integer type in which fees are calculated.
|
||||
type Balance: AtLeast32BitUnsigned
|
||||
+ FullCodec
|
||||
+ Copy
|
||||
+ MaybeSerializeDeserialize
|
||||
+ Debug
|
||||
+ Default
|
||||
+ TypeInfo;
|
||||
/// The type used to identify the assets used for transaction payment.
|
||||
type AssetId: FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default + Eq + TypeInfo;
|
||||
/// The type used to store the intermediate values between pre- and post-dispatch.
|
||||
type LiquidityInfo;
|
||||
|
||||
/// Before the transaction is executed the payment of the transaction fees needs to be secured.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
call: &T::Call,
|
||||
dispatch_info: &DispatchInfoOf<T::Call>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError>;
|
||||
|
||||
/// After the transaction was executed the actual fee can be calculated.
|
||||
/// This function should refund any overpaid fees and optionally deposit
|
||||
/// the corrected amount.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn correct_and_deposit_fee(
|
||||
who: &T::AccountId,
|
||||
dispatch_info: &DispatchInfoOf<T::Call>,
|
||||
post_info: &PostDispatchInfoOf<T::Call>,
|
||||
corrected_fee: Self::Balance,
|
||||
tip: Self::Balance,
|
||||
already_withdrawn: Self::LiquidityInfo,
|
||||
) -> Result<(), TransactionValidityError>;
|
||||
}
|
||||
|
||||
/// Allows specifying what to do with the withdrawn asset fees.
|
||||
pub trait HandleCredit<AccountId, B: Balanced<AccountId>> {
|
||||
/// Implement to determine what to do with the withdrawn asset fees.
|
||||
/// Default for `CreditOf` from the assets pallet is to burn and
|
||||
/// decrease total issuance.
|
||||
fn handle_credit(credit: CreditOf<AccountId, B>);
|
||||
}
|
||||
|
||||
/// Default implementation that just drops the credit according to the `OnDrop` in the underlying
|
||||
/// imbalance type.
|
||||
impl<A, B: Balanced<A>> HandleCredit<A, B> for () {
|
||||
fn handle_credit(_credit: CreditOf<A, B>) {}
|
||||
}
|
||||
|
||||
/// Implements the asset transaction for a balance to asset converter (implementing
|
||||
/// [`BalanceConversion`]) and a credit handler (implementing [`HandleCredit`]).
|
||||
///
|
||||
/// The credit handler is given the complete fee in terms of the asset used for the transaction.
|
||||
pub struct FungiblesAdapter<CON, HC>(PhantomData<(CON, HC)>);
|
||||
|
||||
/// Default implementation for a runtime instantiating this pallet, a balance to asset converter and
|
||||
/// a credit handler.
|
||||
impl<T, CON, HC> OnChargeAssetTransaction<T> for FungiblesAdapter<CON, HC>
|
||||
where
|
||||
T: Config,
|
||||
CON: BalanceConversion<BalanceOf<T>, AssetIdOf<T>, AssetBalanceOf<T>>,
|
||||
HC: HandleCredit<T::AccountId, T::Fungibles>,
|
||||
AssetIdOf<T>: FullCodec + Copy + MaybeSerializeDeserialize + Debug + Default + Eq + TypeInfo,
|
||||
{
|
||||
type Balance = BalanceOf<T>;
|
||||
type AssetId = AssetIdOf<T>;
|
||||
type LiquidityInfo = CreditOf<T::AccountId, T::Fungibles>;
|
||||
|
||||
/// Withdraw the predicted fee from the transaction origin.
|
||||
///
|
||||
/// Note: The `fee` already includes the `tip`.
|
||||
fn withdraw_fee(
|
||||
who: &T::AccountId,
|
||||
_call: &T::Call,
|
||||
_info: &DispatchInfoOf<T::Call>,
|
||||
asset_id: Self::AssetId,
|
||||
fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
) -> Result<Self::LiquidityInfo, TransactionValidityError> {
|
||||
// We don't know the precision of the underlying asset. Because the converted fee could be
|
||||
// less than one (e.g. 0.5) but gets rounded down by integer division we introduce a minimum
|
||||
// fee.
|
||||
let min_converted_fee = if fee.is_zero() { Zero::zero() } else { One::one() };
|
||||
let converted_fee = CON::to_asset_balance(fee, asset_id)
|
||||
.map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))?
|
||||
.max(min_converted_fee);
|
||||
let can_withdraw = <T::Fungibles as Inspect<T::AccountId>>::can_withdraw(
|
||||
asset_id.into(),
|
||||
who,
|
||||
converted_fee,
|
||||
);
|
||||
if !matches!(can_withdraw, WithdrawConsequence::Success) {
|
||||
return Err(InvalidTransaction::Payment.into())
|
||||
}
|
||||
<T::Fungibles as Balanced<T::AccountId>>::withdraw(asset_id.into(), who, converted_fee)
|
||||
.map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))
|
||||
}
|
||||
|
||||
/// Hand the fee and the tip over to the `[HandleCredit]` implementation.
|
||||
/// Since the predicted fee might have been too high, parts of the fee may be refunded.
|
||||
///
|
||||
/// Note: The `corrected_fee` already includes the `tip`.
|
||||
fn correct_and_deposit_fee(
|
||||
who: &T::AccountId,
|
||||
_dispatch_info: &DispatchInfoOf<T::Call>,
|
||||
_post_info: &PostDispatchInfoOf<T::Call>,
|
||||
corrected_fee: Self::Balance,
|
||||
_tip: Self::Balance,
|
||||
paid: Self::LiquidityInfo,
|
||||
) -> Result<(), TransactionValidityError> {
|
||||
let min_converted_fee = if corrected_fee.is_zero() { Zero::zero() } else { One::one() };
|
||||
// Convert the corrected fee into the asset used for payment.
|
||||
let converted_fee = CON::to_asset_balance(corrected_fee, paid.asset().into())
|
||||
.map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })?
|
||||
.max(min_converted_fee);
|
||||
// Calculate how much refund we should return.
|
||||
let (final_fee, refund) = paid.split(converted_fee);
|
||||
// Refund to the account that paid the fees. If this fails, the account might have dropped
|
||||
// below the existential balance. In that case we don't refund anything.
|
||||
let _ = <T::Fungibles as Balanced<T::AccountId>>::resolve(who, refund);
|
||||
// Handle the final fee, e.g. by transferring to the block author or burning.
|
||||
HC::handle_credit(final_fee);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,636 +0,0 @@
|
||||
// Copyright (C) 2021 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.
|
||||
|
||||
use super::*;
|
||||
use crate as pallet_asset_tx_payment;
|
||||
|
||||
use frame_support::{
|
||||
assert_ok,
|
||||
pallet_prelude::*,
|
||||
parameter_types,
|
||||
traits::{fungibles::Mutate, FindAuthor},
|
||||
weights::{
|
||||
DispatchClass, DispatchInfo, PostDispatchInfo, Weight, WeightToFeeCoefficient,
|
||||
WeightToFeeCoefficients, WeightToFeePolynomial,
|
||||
},
|
||||
ConsensusEngineId,
|
||||
};
|
||||
use frame_system as system;
|
||||
use frame_system::EnsureRoot;
|
||||
use pallet_balances::Call as BalancesCall;
|
||||
use pallet_transaction_payment::CurrencyAdapter;
|
||||
use smallvec::smallvec;
|
||||
use sp_core::H256;
|
||||
use sp_runtime::{
|
||||
testing::Header,
|
||||
traits::{BlakeTwo256, ConvertInto, IdentityLookup, StaticLookup},
|
||||
Perbill,
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
|
||||
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
|
||||
type Block = frame_system::mocking::MockBlock<Runtime>;
|
||||
type Balance = u64;
|
||||
type AccountId = u64;
|
||||
|
||||
frame_support::construct_runtime!(
|
||||
pub enum Runtime where
|
||||
Block = Block,
|
||||
NodeBlock = Block,
|
||||
UncheckedExtrinsic = UncheckedExtrinsic,
|
||||
{
|
||||
System: system::{Pallet, Call, Config, Storage, Event<T>},
|
||||
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
|
||||
TransactionPayment: pallet_transaction_payment::{Pallet, Storage},
|
||||
Assets: pallet_assets::{Pallet, Call, Storage, Event<T>},
|
||||
Authorship: pallet_authorship::{Pallet, Call, Storage},
|
||||
AssetTxPayment: pallet_asset_tx_payment::{Pallet},
|
||||
}
|
||||
);
|
||||
|
||||
const CALL: &<Runtime as frame_system::Config>::Call =
|
||||
&Call::Balances(BalancesCall::transfer { dest: 2, value: 69 });
|
||||
|
||||
thread_local! {
|
||||
static EXTRINSIC_BASE_WEIGHT: RefCell<u64> = RefCell::new(0);
|
||||
}
|
||||
|
||||
pub struct BlockWeights;
|
||||
impl Get<frame_system::limits::BlockWeights> for BlockWeights {
|
||||
fn get() -> frame_system::limits::BlockWeights {
|
||||
frame_system::limits::BlockWeights::builder()
|
||||
.base_block(0)
|
||||
.for_class(DispatchClass::all(), |weights| {
|
||||
weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()).into();
|
||||
})
|
||||
.for_class(DispatchClass::non_mandatory(), |weights| {
|
||||
weights.max_total = 1024.into();
|
||||
})
|
||||
.build_or_panic()
|
||||
}
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const BlockHashCount: u64 = 250;
|
||||
pub static TransactionByteFee: u64 = 1;
|
||||
pub static WeightToFee: u64 = 1;
|
||||
}
|
||||
|
||||
impl frame_system::Config for Runtime {
|
||||
type BaseCallFilter = frame_support::traits::Everything;
|
||||
type BlockWeights = BlockWeights;
|
||||
type BlockLength = ();
|
||||
type DbWeight = ();
|
||||
type Origin = Origin;
|
||||
type Index = u64;
|
||||
type BlockNumber = u64;
|
||||
type Call = Call;
|
||||
type Hash = H256;
|
||||
type Hashing = BlakeTwo256;
|
||||
type AccountId = AccountId;
|
||||
type Lookup = IdentityLookup<Self::AccountId>;
|
||||
type Header = Header;
|
||||
type Event = Event;
|
||||
type BlockHashCount = BlockHashCount;
|
||||
type Version = ();
|
||||
type PalletInfo = PalletInfo;
|
||||
type AccountData = pallet_balances::AccountData<u64>;
|
||||
type OnNewAccount = ();
|
||||
type OnKilledAccount = ();
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = ();
|
||||
type OnSetCode = ();
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const ExistentialDeposit: u64 = 10;
|
||||
pub const MaxReserves: u32 = 50;
|
||||
}
|
||||
|
||||
impl pallet_balances::Config for Runtime {
|
||||
type Balance = Balance;
|
||||
type Event = Event;
|
||||
type DustRemoval = ();
|
||||
type ExistentialDeposit = ExistentialDeposit;
|
||||
type AccountStore = System;
|
||||
type MaxLocks = ();
|
||||
type WeightInfo = ();
|
||||
type MaxReserves = MaxReserves;
|
||||
type ReserveIdentifier = [u8; 8];
|
||||
}
|
||||
|
||||
impl WeightToFeePolynomial for WeightToFee {
|
||||
type Balance = u64;
|
||||
|
||||
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
|
||||
smallvec![WeightToFeeCoefficient {
|
||||
degree: 1,
|
||||
coeff_frac: Perbill::zero(),
|
||||
coeff_integer: WEIGHT_TO_FEE.with(|v| *v.borrow()),
|
||||
negative: false,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const OperationalFeeMultiplier: u8 = 5;
|
||||
}
|
||||
|
||||
impl pallet_transaction_payment::Config for Runtime {
|
||||
type OnChargeTransaction = CurrencyAdapter<Balances, ()>;
|
||||
type TransactionByteFee = TransactionByteFee;
|
||||
type WeightToFee = WeightToFee;
|
||||
type FeeMultiplierUpdate = ();
|
||||
type OperationalFeeMultiplier = OperationalFeeMultiplier;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub const AssetDeposit: u64 = 2;
|
||||
pub const MetadataDeposit: u64 = 0;
|
||||
pub const StringLimit: u32 = 20;
|
||||
}
|
||||
|
||||
impl pallet_assets::Config for Runtime {
|
||||
type Event = Event;
|
||||
type Balance = Balance;
|
||||
type AssetId = u32;
|
||||
type Currency = Balances;
|
||||
type ForceOrigin = EnsureRoot<AccountId>;
|
||||
type AssetDeposit = AssetDeposit;
|
||||
type MetadataDepositBase = MetadataDeposit;
|
||||
type MetadataDepositPerByte = MetadataDeposit;
|
||||
type ApprovalDeposit = MetadataDeposit;
|
||||
type StringLimit = StringLimit;
|
||||
type Freezer = ();
|
||||
type Extra = ();
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
pub struct HardcodedAuthor;
|
||||
const BLOCK_AUTHOR: AccountId = 1234;
|
||||
impl FindAuthor<AccountId> for HardcodedAuthor {
|
||||
fn find_author<'a, I>(_: I) -> Option<AccountId>
|
||||
where
|
||||
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
|
||||
{
|
||||
Some(BLOCK_AUTHOR)
|
||||
}
|
||||
}
|
||||
|
||||
impl pallet_authorship::Config for Runtime {
|
||||
type FindAuthor = HardcodedAuthor;
|
||||
type UncleGenerations = ();
|
||||
type FilterUncle = ();
|
||||
type EventHandler = ();
|
||||
}
|
||||
|
||||
pub struct CreditToBlockAuthor;
|
||||
impl HandleCredit<AccountId, Assets> for CreditToBlockAuthor {
|
||||
fn handle_credit(credit: CreditOf<AccountId, Assets>) {
|
||||
let author = pallet_authorship::Pallet::<Runtime>::author();
|
||||
// TODO: what to do in case paying the author fails (e.g. because `fee < min_balance`)
|
||||
// default: drop the result which will trigger the `OnDrop` of the imbalance.
|
||||
let _ = <Assets as Balanced<AccountId>>::resolve(&author, credit);
|
||||
}
|
||||
}
|
||||
|
||||
impl Config for Runtime {
|
||||
type Fungibles = Assets;
|
||||
type OnChargeAssetTransaction = FungiblesAdapter<
|
||||
pallet_assets::BalanceToAssetBalance<Balances, Runtime, ConvertInto>,
|
||||
CreditToBlockAuthor,
|
||||
>;
|
||||
}
|
||||
|
||||
pub struct ExtBuilder {
|
||||
balance_factor: u64,
|
||||
base_weight: u64,
|
||||
byte_fee: u64,
|
||||
weight_to_fee: u64,
|
||||
}
|
||||
|
||||
impl Default for ExtBuilder {
|
||||
fn default() -> Self {
|
||||
Self { balance_factor: 1, base_weight: 0, byte_fee: 1, weight_to_fee: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtBuilder {
|
||||
pub fn base_weight(mut self, base_weight: u64) -> Self {
|
||||
self.base_weight = base_weight;
|
||||
self
|
||||
}
|
||||
pub fn balance_factor(mut self, factor: u64) -> Self {
|
||||
self.balance_factor = factor;
|
||||
self
|
||||
}
|
||||
fn set_constants(&self) {
|
||||
EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow_mut() = self.base_weight);
|
||||
TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee);
|
||||
WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
|
||||
}
|
||||
pub fn build(self) -> sp_io::TestExternalities {
|
||||
self.set_constants();
|
||||
let mut t = frame_system::GenesisConfig::default().build_storage::<Runtime>().unwrap();
|
||||
pallet_balances::GenesisConfig::<Runtime> {
|
||||
balances: if self.balance_factor > 0 {
|
||||
vec![
|
||||
(1, 10 * self.balance_factor),
|
||||
(2, 20 * self.balance_factor),
|
||||
(3, 30 * self.balance_factor),
|
||||
(4, 40 * self.balance_factor),
|
||||
(5, 50 * self.balance_factor),
|
||||
(6, 60 * self.balance_factor),
|
||||
]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
}
|
||||
.assimilate_storage(&mut t)
|
||||
.unwrap();
|
||||
t.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// create a transaction info struct from weight. Handy to avoid building the whole struct.
|
||||
pub fn info_from_weight(w: Weight) -> DispatchInfo {
|
||||
// pays_fee: Pays::Yes -- class: DispatchClass::Normal
|
||||
DispatchInfo { weight: w, ..Default::default() }
|
||||
}
|
||||
|
||||
fn post_info_from_weight(w: Weight) -> PostDispatchInfo {
|
||||
PostDispatchInfo { actual_weight: Some(w), pays_fee: Default::default() }
|
||||
}
|
||||
|
||||
fn info_from_pays(p: Pays) -> DispatchInfo {
|
||||
DispatchInfo { pays_fee: p, ..Default::default() }
|
||||
}
|
||||
|
||||
fn post_info_from_pays(p: Pays) -> PostDispatchInfo {
|
||||
PostDispatchInfo { actual_weight: None, pays_fee: p }
|
||||
}
|
||||
|
||||
fn default_post_info() -> PostDispatchInfo {
|
||||
PostDispatchInfo { actual_weight: None, pays_fee: Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_in_native_possible() {
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(5)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let len = 10;
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, None)
|
||||
.pre_dispatch(&1, CALL, &info_from_weight(5), len)
|
||||
.unwrap();
|
||||
let initial_balance = 10 * balance_factor;
|
||||
assert_eq!(Balances::free_balance(1), initial_balance - 5 - 5 - 10);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(5),
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
assert_eq!(Balances::free_balance(1), initial_balance - 5 - 5 - 10);
|
||||
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(5 /* tipped */, None)
|
||||
.pre_dispatch(&2, CALL, &info_from_weight(100), len)
|
||||
.unwrap();
|
||||
let initial_balance_for_2 = 20 * balance_factor;
|
||||
assert_eq!(Balances::free_balance(2), initial_balance_for_2 - 5 - 10 - 100 - 5);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(100),
|
||||
&post_info_from_weight(50),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
assert_eq!(Balances::free_balance(2), initial_balance_for_2 - 5 - 10 - 50 - 5);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_in_asset_possible() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(base_weight)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
Origin::root(),
|
||||
asset_id,
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 1;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id, &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.unwrap();
|
||||
// assert that native balance is not used
|
||||
assert_eq!(Balances::free_balance(caller), 10 * balance_factor);
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee);
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), 0);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(weight),
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee);
|
||||
// check that the block author gets rewarded
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), fee);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_payment_without_fee() {
|
||||
let base_weight = 5;
|
||||
let balance_factor = 100;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(balance_factor)
|
||||
.base_weight(base_weight)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
Origin::root(),
|
||||
asset_id,
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 1;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id, &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.unwrap();
|
||||
// assert that native balance is not used
|
||||
assert_eq!(Balances::free_balance(caller), 10 * balance_factor);
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee);
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), 0);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(weight),
|
||||
&post_info_from_pays(Pays::No),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
// caller should be refunded
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
// check that the block author did not get rewarded
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_transaction_payment_with_tip_and_refund() {
|
||||
let base_weight = 5;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.base_weight(base_weight)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
Origin::root(),
|
||||
asset_id,
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 2;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 1000;
|
||||
assert_ok!(Assets::mint_into(asset_id, &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 100;
|
||||
let tip = 5;
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee_with_tip =
|
||||
(base_weight + weight + len as u64 + tip) * min_balance / ExistentialDeposit::get();
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(tip, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.unwrap();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee_with_tip);
|
||||
|
||||
let final_weight = 50;
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(weight),
|
||||
&post_info_from_weight(final_weight),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
let final_fee =
|
||||
fee_with_tip - (weight - final_weight) * min_balance / ExistentialDeposit::get();
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - (final_fee));
|
||||
assert_eq!(Assets::balance(asset_id, BLOCK_AUTHOR), final_fee);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payment_from_account_with_only_assets() {
|
||||
let base_weight = 5;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.base_weight(base_weight)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
Origin::root(),
|
||||
asset_id,
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 333;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id, &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
// assert that native balance is not necessary
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.unwrap();
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
// check that fee was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(weight),
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - fee);
|
||||
assert_eq!(Balances::free_balance(caller), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payment_only_with_existing_sufficient_asset() {
|
||||
let base_weight = 5;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.base_weight(base_weight)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
let asset_id = 1;
|
||||
let caller = 1;
|
||||
let weight = 5;
|
||||
let len = 10;
|
||||
// pre_dispatch fails for non-existent asset
|
||||
assert!(ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.is_err());
|
||||
|
||||
// create the non-sufficient asset
|
||||
let min_balance = 2;
|
||||
assert_ok!(Assets::force_create(
|
||||
Origin::root(),
|
||||
asset_id,
|
||||
42, /* owner */
|
||||
false, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
// pre_dispatch fails for non-sufficient asset
|
||||
assert!(ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_fee_is_never_zero_if_input_fee_is_not() {
|
||||
let base_weight = 1;
|
||||
ExtBuilder::default()
|
||||
.balance_factor(100)
|
||||
.base_weight(base_weight)
|
||||
.build()
|
||||
.execute_with(|| {
|
||||
// create the asset
|
||||
let asset_id = 1;
|
||||
let min_balance = 1;
|
||||
assert_ok!(Assets::force_create(
|
||||
Origin::root(),
|
||||
asset_id,
|
||||
42, /* owner */
|
||||
true, /* is_sufficient */
|
||||
min_balance
|
||||
));
|
||||
|
||||
// mint into the caller account
|
||||
let caller = 333;
|
||||
let beneficiary = <Runtime as system::Config>::Lookup::unlookup(caller);
|
||||
let balance = 100;
|
||||
assert_ok!(Assets::mint_into(asset_id, &beneficiary, balance));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
let weight = 1;
|
||||
let len = 1;
|
||||
// we convert the from weight to fee based on the ratio between asset min balance and
|
||||
// existential deposit
|
||||
let fee = (base_weight + weight + len as u64) * min_balance / ExistentialDeposit::get();
|
||||
// naive fee calculation would round down to zero
|
||||
assert_eq!(fee, 0);
|
||||
{
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_pays(Pays::No), len)
|
||||
.unwrap();
|
||||
// `Pays::No` still implies no fees
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_pays(Pays::No),
|
||||
&post_info_from_pays(Pays::No),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance);
|
||||
}
|
||||
let pre = ChargeAssetTxPayment::<Runtime>::from(0, Some(asset_id))
|
||||
.pre_dispatch(&caller, CALL, &info_from_weight(weight), len)
|
||||
.unwrap();
|
||||
// check that at least one coin was charged in the given asset
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - 1);
|
||||
|
||||
assert_ok!(ChargeAssetTxPayment::<Runtime>::post_dispatch(
|
||||
pre,
|
||||
&info_from_weight(weight),
|
||||
&default_post_info(),
|
||||
len,
|
||||
&Ok(())
|
||||
));
|
||||
assert_eq!(Assets::balance(asset_id, caller), balance - 1);
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "cumulus-pallet-aura-ext"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
description = "AURA consensus extension pallet for parachains"
|
||||
|
||||
[dependencies]
|
||||
@@ -19,7 +19,7 @@ sp-application-crypto = { git = "https://github.com/paritytech/substrate", defau
|
||||
# Other Dependencies
|
||||
codec = { package = "parity-scale-codec", version = "2.3.0", default-features = false, features = ["derive"]}
|
||||
scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0.101", optional = true, features = ["derive"] }
|
||||
serde = { version = "1.0.132", optional = true, features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cumulus-pallet-parachain-system = { path = "../parachain-system" }
|
||||
|
||||
@@ -1,62 +1,64 @@
|
||||
[package]
|
||||
authors = ['Anonymous']
|
||||
description = 'Simple staking pallet with a fixed stake.'
|
||||
edition = '2018'
|
||||
homepage = 'https://substrate.io'
|
||||
license = 'Apache-2.0'
|
||||
name = 'pallet-collator-selection'
|
||||
readme = 'README.md'
|
||||
repository = 'https://github.com/paritytech/cumulus/'
|
||||
version = '3.0.0'
|
||||
authors = ["Anonymous"]
|
||||
description = "Simple staking pallet with a fixed stake."
|
||||
edition = "2021"
|
||||
homepage = "https://substrate.io"
|
||||
license = "Apache-2.0"
|
||||
name = "pallet-collator-selection"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/paritytech/cumulus/"
|
||||
version = "3.0.0"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ['x86_64-unknown-linux-gnu']
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
log = { version = "0.4.0", default-features = false }
|
||||
codec = { default-features = false, features = ['derive'], package = 'parity-scale-codec', version = '2.3.0' }
|
||||
codec = { default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.0" }
|
||||
rand = { version = "0.7.2", default-features = false }
|
||||
scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0.119", default-features = false }
|
||||
serde = { version = "1.0.132", default-features = false }
|
||||
|
||||
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-staking = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-authorship = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-session = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-staking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-authorship = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-session = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[dev-dependencies]
|
||||
sp-core = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-io = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-tracing = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-runtime = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-timestamp = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-consensus-aura = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-balances = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-aura = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-aura = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[features]
|
||||
default = ['std']
|
||||
default = ["std"]
|
||||
runtime-benchmarks = [
|
||||
'frame-benchmarking',
|
||||
'frame-support/runtime-benchmarks',
|
||||
'frame-system/runtime-benchmarks',
|
||||
"frame-benchmarking/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
"frame-system/runtime-benchmarks",
|
||||
]
|
||||
std = [
|
||||
'codec/std',
|
||||
'log/std',
|
||||
'scale-info/std',
|
||||
'rand/std',
|
||||
'sp-runtime/std',
|
||||
'sp-staking/std',
|
||||
'sp-std/std',
|
||||
'frame-support/std',
|
||||
'frame-system/std',
|
||||
'frame-benchmarking/std',
|
||||
'pallet-authorship/std',
|
||||
'pallet-session/std',
|
||||
"codec/std",
|
||||
"log/std",
|
||||
"scale-info/std",
|
||||
"rand/std",
|
||||
"sp-runtime/std",
|
||||
"sp-staking/std",
|
||||
"sp-std/std",
|
||||
"frame-support/std",
|
||||
"frame-system/std",
|
||||
"frame-benchmarking/std",
|
||||
"pallet-authorship/std",
|
||||
"pallet-session/std",
|
||||
]
|
||||
|
||||
try-runtime = [ "frame-support/try-runtime" ]
|
||||
|
||||
@@ -88,7 +88,7 @@ fn register_validators<T: Config + session::Config>(count: u32) {
|
||||
let validators = (0..count).map(|c| validator::<T>(c)).collect::<Vec<_>>();
|
||||
|
||||
for (who, keys) in validators {
|
||||
<session::Module<T>>::set_keys(RawOrigin::Signed(who).into(), keys, vec![]).unwrap();
|
||||
<session::Pallet<T>>::set_keys(RawOrigin::Signed(who).into(), keys, Vec::new()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,10 +157,10 @@ benchmarks! {
|
||||
let bond: BalanceOf<T> = T::Currency::minimum_balance() * 2u32.into();
|
||||
T::Currency::make_free_balance_be(&caller, bond.clone());
|
||||
|
||||
<session::Module<T>>::set_keys(
|
||||
<session::Pallet<T>>::set_keys(
|
||||
RawOrigin::Signed(caller.clone()).into(),
|
||||
keys::<T>(c + 1),
|
||||
vec![]
|
||||
Vec::new()
|
||||
).unwrap();
|
||||
|
||||
}: _(RawOrigin::Signed(caller.clone()))
|
||||
|
||||
@@ -78,6 +78,7 @@ impl system::Config for Test {
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = SS58Prefix;
|
||||
type OnSetCode = ();
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
@@ -145,7 +146,7 @@ impl From<UintAuthorityId> for MockSessionKeys {
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
pub static SessionHandlerCollators: Vec<u64> = vec![];
|
||||
pub static SessionHandlerCollators: Vec<u64> = Vec::new();
|
||||
pub static SessionChangeBlock: u64 = 0;
|
||||
}
|
||||
|
||||
@@ -224,21 +225,21 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
sp_tracing::try_init_simple();
|
||||
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
|
||||
let invulnerables = vec![1, 2];
|
||||
let keys = invulnerables
|
||||
.iter()
|
||||
.map(|i| (*i, *i, MockSessionKeys { aura: UintAuthorityId(*i) }))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let balances = pallet_balances::GenesisConfig::<Test> {
|
||||
balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)],
|
||||
};
|
||||
let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)];
|
||||
let keys = balances
|
||||
.iter()
|
||||
.map(|&(i, _)| (i, i, MockSessionKeys { aura: UintAuthorityId(i) }))
|
||||
.collect::<Vec<_>>();
|
||||
let collator_selection = collator_selection::GenesisConfig::<Test> {
|
||||
desired_candidates: 2,
|
||||
candidacy_bond: 10,
|
||||
invulnerables,
|
||||
};
|
||||
let session = pallet_session::GenesisConfig::<Test> { keys };
|
||||
balances.assimilate_storage(&mut t).unwrap();
|
||||
pallet_balances::GenesisConfig::<Test> { balances }
|
||||
.assimilate_storage(&mut t)
|
||||
.unwrap();
|
||||
// collator selection must be initialized before session.
|
||||
collator_selection.assimilate_storage(&mut t).unwrap();
|
||||
session.assimilate_storage(&mut t).unwrap();
|
||||
@@ -249,6 +250,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
pub fn initialize_to_block(n: u64) {
|
||||
for i in System::block_number() + 1..=n {
|
||||
System::set_block_number(i);
|
||||
<AllPallets as frame_support::traits::OnInitialize<u64>>::on_initialize(i);
|
||||
<AllPalletsWithSystem as frame_support::traits::OnInitialize<u64>>::on_initialize(i);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ fn register_as_candidate_works() {
|
||||
// given
|
||||
assert_eq!(CollatorSelection::desired_candidates(), 2);
|
||||
assert_eq!(CollatorSelection::candidacy_bond(), 10);
|
||||
assert_eq!(CollatorSelection::candidates(), vec![]);
|
||||
assert_eq!(CollatorSelection::candidates(), Vec::new());
|
||||
assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]);
|
||||
|
||||
// take two endowed, non-invulnerables accounts.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "cumulus-pallet-dmp-queue"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
# Other dependencies
|
||||
|
||||
@@ -307,7 +307,7 @@ pub mod pallet {
|
||||
id, remaining, required,
|
||||
));
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
// Cannot be an `else` here since the `maybe_enqueue_page` may have changed.
|
||||
@@ -371,6 +371,7 @@ mod tests {
|
||||
impl_version: 1,
|
||||
apis: sp_version::create_apis_vec!([]),
|
||||
transaction_version: 1,
|
||||
state_version: 1,
|
||||
};
|
||||
pub const ParachainId: ParaId = ParaId::new(200);
|
||||
pub const ReservedXcmpWeight: Weight = 0;
|
||||
@@ -403,6 +404,7 @@ mod tests {
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = ();
|
||||
type OnSetCode = ();
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -475,7 +477,7 @@ mod tests {
|
||||
Xcm(vec![Transact {
|
||||
origin_kind: OriginKind::Native,
|
||||
require_weight_at_most: weight,
|
||||
call: vec![].into(),
|
||||
call: Vec::new().into(),
|
||||
}])
|
||||
}
|
||||
|
||||
@@ -506,7 +508,7 @@ mod tests {
|
||||
new_test_ext().execute_with(|| {
|
||||
let weight_used = handle_messages(&[], 1000);
|
||||
assert_eq!(weight_used, 0);
|
||||
assert_eq!(take_trace(), vec![]);
|
||||
assert_eq!(take_trace(), Vec::new());
|
||||
assert!(queue_is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "cumulus-pallet-parachain-system"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
description = "Base pallet for cumulus-based parachains"
|
||||
|
||||
[dependencies]
|
||||
@@ -32,7 +32,7 @@ sp-externalities = { git = "https://github.com/paritytech/substrate", default-fe
|
||||
# Other Dependencies
|
||||
codec = { package = "parity-scale-codec", version = "2.3.0", default-features = false, features = ["derive"]}
|
||||
scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0.101", optional = true, features = ["derive"] }
|
||||
serde = { version = "1.0.132", optional = true, features = ["derive"] }
|
||||
log = { version = "0.4.14", default-features = false }
|
||||
environmental = { version = "1.1.2", default-features = false }
|
||||
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
name = "cumulus-pallet-parachain-system-proc-macro"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
description = "Proc macros provided by the parachain-system pallet"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = "1.0.73"
|
||||
proc-macro2 = "1.0.27"
|
||||
syn = "1.0.81"
|
||||
proc-macro2 = "1.0.36"
|
||||
quote = "1.0.9"
|
||||
proc-macro-crate = "1.0.0"
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ use cumulus_primitives_core::{
|
||||
OutboundHrmpMessage, ParaId, PersistedValidationData, UpwardMessage, UpwardMessageSender,
|
||||
XcmpMessageHandler, XcmpMessageSource,
|
||||
};
|
||||
use cumulus_primitives_parachain_inherent::ParachainInherentData;
|
||||
use cumulus_primitives_parachain_inherent::{MessageQueueChain, ParachainInherentData};
|
||||
use frame_support::{
|
||||
dispatch::{DispatchError, DispatchResult},
|
||||
ensure,
|
||||
@@ -46,7 +46,7 @@ use frame_system::{ensure_none, ensure_root};
|
||||
use polkadot_parachain::primitives::RelayChainBlockNumber;
|
||||
use relay_state_snapshot::MessagingStateSnapshot;
|
||||
use sp_runtime::{
|
||||
traits::{BlakeTwo256, Block as BlockT, BlockNumberProvider, Hash},
|
||||
traits::{Block as BlockT, BlockNumberProvider, Hash},
|
||||
transaction_validity::{
|
||||
InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
|
||||
ValidTransaction,
|
||||
@@ -236,8 +236,9 @@ pub mod pallet {
|
||||
HrmpWatermark::<T>::kill();
|
||||
UpwardMessages::<T>::kill();
|
||||
HrmpOutboundMessages::<T>::kill();
|
||||
CustomValidationHeadData::<T>::kill();
|
||||
|
||||
weight += T::DbWeight::get().writes(5);
|
||||
weight += T::DbWeight::get().writes(6);
|
||||
|
||||
// Here, in `on_initialize` we must report the weight for both `on_initialize` and
|
||||
// `on_finalize`.
|
||||
@@ -567,6 +568,12 @@ pub mod pallet {
|
||||
#[pallet::storage]
|
||||
pub(super) type AuthorizedUpgrade<T: Config> = StorageValue<_, T::Hash>;
|
||||
|
||||
/// A custom head data that should be returned as result of `validate_block`.
|
||||
///
|
||||
/// See [`Pallet::set_custom_validation_head_data`] for more information.
|
||||
#[pallet::storage]
|
||||
pub(super) type CustomValidationHeadData<T: Config> = StorageValue<_, Vec<u8>, OptionQuery>;
|
||||
|
||||
#[pallet::inherent]
|
||||
impl<T: Config> ProvideInherent for Pallet<T> {
|
||||
type Call = Call<T>;
|
||||
@@ -609,7 +616,7 @@ pub mod pallet {
|
||||
if let Ok(hash) = Self::validate_authorized_upgrade(code) {
|
||||
return Ok(ValidTransaction {
|
||||
priority: 100,
|
||||
requires: vec![],
|
||||
requires: Vec::new(),
|
||||
provides: vec![hash.as_ref().to_vec()],
|
||||
longevity: TransactionLongevity::max_value(),
|
||||
propagate: true,
|
||||
@@ -692,6 +699,9 @@ impl<T: Config> Pallet<T> {
|
||||
/// import, this is a no-op.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics while validating the `PoV` on the relay chain if the [`PersistedValidationData`]
|
||||
/// passed by the block author was incorrect.
|
||||
fn validate_validation_data(validation_data: &PersistedValidationData) {
|
||||
validate_block::with_validation_params(|params| {
|
||||
assert_eq!(
|
||||
@@ -714,8 +724,10 @@ impl<T: Config> Pallet<T> {
|
||||
/// Checks if the sequence of the messages is valid, dispatches them and communicates the
|
||||
/// number of processed messages to the collator via a storage update.
|
||||
///
|
||||
/// **Panics** if it turns out that after processing all messages the Message Queue Chain
|
||||
/// hash doesn't match the expected.
|
||||
/// # Panics
|
||||
///
|
||||
/// If it turns out that after processing all messages the Message Queue Chain
|
||||
/// hash doesn't match the expected.
|
||||
fn process_inbound_downward_messages(
|
||||
expected_dmq_mqc_head: relay_chain::Hash,
|
||||
downward_messages: Vec<InboundDownwardMessage>,
|
||||
@@ -738,7 +750,7 @@ impl<T: Config> Pallet<T> {
|
||||
weight_used += T::DmpMessageHandler::handle_dmp_messages(message_iter, max_weight);
|
||||
<LastDmqMqcHead<T>>::put(&dmq_head);
|
||||
|
||||
Self::deposit_event(Event::DownwardMessagesProcessed(weight_used, dmq_head.0));
|
||||
Self::deposit_event(Event::DownwardMessagesProcessed(weight_used, dmq_head.head()));
|
||||
}
|
||||
|
||||
// After hashing each message in the message queue chain submitted by the collator, we
|
||||
@@ -746,7 +758,7 @@ impl<T: Config> Pallet<T> {
|
||||
//
|
||||
// A mismatch means that at least some of the submitted messages were altered, omitted or
|
||||
// added improperly.
|
||||
assert_eq!(dmq_head.0, expected_dmq_mqc_head);
|
||||
assert_eq!(dmq_head.head(), expected_dmq_mqc_head);
|
||||
|
||||
ProcessedDownwardMessages::<T>::put(dm_count);
|
||||
|
||||
@@ -907,6 +919,22 @@ impl<T: Config> Pallet<T> {
|
||||
new_validation_code: NewValidationCode::<T>::get().map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a custom head data that should be returned as result of `validate_block`.
|
||||
///
|
||||
/// This will overwrite the head data that is returned as result of `validate_block` while
|
||||
/// validating a `PoV` on the relay chain. Normally the head data that is being returned
|
||||
/// by `validate_block` is the header of the block that is validated, thus it can be
|
||||
/// enacted as the new best block. However, for features like forking it can be useful
|
||||
/// to overwrite the head data with a custom header.
|
||||
///
|
||||
/// # Attention
|
||||
///
|
||||
/// This should only be used when you are sure what you are doing as this can brick
|
||||
/// your Parachain.
|
||||
pub fn set_custom_validation_head_data(head_data: Vec<u8>) {
|
||||
CustomValidationHeadData::<T>::put(head_data);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ParachainSetCode<T>(sp_std::marker::PhantomData<T>);
|
||||
@@ -917,43 +945,6 @@ impl<T: Config> frame_system::SetCode<T> for ParachainSetCode<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// This struct provides ability to extend a message queue chain (MQC) and compute a new head.
|
||||
///
|
||||
/// MQC is an instance of a [hash chain] applied to a message queue. Using a hash chain it's
|
||||
/// possible to represent a sequence of messages using only a single hash.
|
||||
///
|
||||
/// A head for an empty chain is agreed to be a zero hash.
|
||||
///
|
||||
/// [hash chain]: https://en.wikipedia.org/wiki/Hash_chain
|
||||
#[derive(Default, Clone, codec::Encode, codec::Decode, scale_info::TypeInfo)]
|
||||
struct MessageQueueChain(relay_chain::Hash);
|
||||
|
||||
impl MessageQueueChain {
|
||||
fn extend_hrmp(&mut self, horizontal_message: &InboundHrmpMessage) -> &mut Self {
|
||||
let prev_head = self.0;
|
||||
self.0 = BlakeTwo256::hash_of(&(
|
||||
prev_head,
|
||||
horizontal_message.sent_at,
|
||||
BlakeTwo256::hash_of(&horizontal_message.data),
|
||||
));
|
||||
self
|
||||
}
|
||||
|
||||
fn extend_downward(&mut self, downward_message: &InboundDownwardMessage) -> &mut Self {
|
||||
let prev_head = self.0;
|
||||
self.0 = BlakeTwo256::hash_of(&(
|
||||
prev_head,
|
||||
downward_message.sent_at,
|
||||
BlakeTwo256::hash_of(&downward_message.msg),
|
||||
));
|
||||
self
|
||||
}
|
||||
|
||||
fn head(&self) -> relay_chain::Hash {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> Pallet<T> {
|
||||
pub fn send_upward_message(message: UpwardMessage) -> Result<u32, MessageSendError> {
|
||||
// Check if the message fits into the relay-chain constraints.
|
||||
@@ -1008,7 +999,7 @@ pub trait CheckInherents<Block: BlockT> {
|
||||
) -> frame_support::inherent::CheckInherentsResult;
|
||||
}
|
||||
|
||||
/// Implements [`BlockNumberProvider`] that returns relaychain block number fetched from
|
||||
/// Implements [`BlockNumberProvider`] that returns relay chain block number fetched from
|
||||
/// validation data.
|
||||
/// NTOE: When validation data is not available (e.g. within on_initialize), 0 will be returned.
|
||||
pub struct RelaychainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);
|
||||
|
||||
@@ -33,7 +33,10 @@ use frame_system::{InitKind, RawOrigin};
|
||||
use hex_literal::hex;
|
||||
use relay_chain::v1::HrmpChannelId;
|
||||
use sp_core::H256;
|
||||
use sp_runtime::{testing::Header, traits::IdentityLookup};
|
||||
use sp_runtime::{
|
||||
testing::Header,
|
||||
traits::{BlakeTwo256, IdentityLookup},
|
||||
};
|
||||
use sp_version::RuntimeVersion;
|
||||
use std::cell::RefCell;
|
||||
|
||||
@@ -63,6 +66,7 @@ parameter_types! {
|
||||
impl_version: 1,
|
||||
apis: sp_version::create_apis_vec!([]),
|
||||
transaction_version: 1,
|
||||
state_version: 1,
|
||||
};
|
||||
pub const ParachainId: ParaId = ParaId::new(200);
|
||||
pub const ReservedXcmpWeight: Weight = 0;
|
||||
@@ -92,6 +96,7 @@ impl frame_system::Config for Test {
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = ();
|
||||
type OnSetCode = ParachainSetCode<Self>;
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
impl Config for Test {
|
||||
type Event = Event;
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! The actual implementation of the validate block functionality.
|
||||
|
||||
use frame_support::traits::{ExecuteBlock, ExtrinsicCall, Get, IsSubType};
|
||||
use sp_runtime::traits::{Block as BlockT, Extrinsic, HashFor, Header as HeaderT, NumberFor};
|
||||
use sp_runtime::traits::{Block as BlockT, Extrinsic, HashFor, Header as HeaderT};
|
||||
|
||||
use sp_io::KillStorageResult;
|
||||
use sp_std::prelude::*;
|
||||
@@ -26,13 +26,13 @@ use polkadot_parachain::primitives::{HeadData, ValidationParams, ValidationResul
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
use sp_core::storage::ChildInfo;
|
||||
use sp_core::storage::{ChildInfo, StateVersion};
|
||||
use sp_externalities::{set_and_run_with_externalities, Externalities};
|
||||
use sp_trie::MemoryDB;
|
||||
|
||||
type TrieBackend<B> = sp_state_machine::TrieBackend<MemoryDB<HashFor<B>>, HashFor<B>>;
|
||||
|
||||
type Ext<'a, B> = sp_state_machine::Ext<'a, HashFor<B>, NumberFor<B>, TrieBackend<B>>;
|
||||
type Ext<'a, B> = sp_state_machine::Ext<'a, HashFor<B>, TrieBackend<B>>;
|
||||
|
||||
fn with_externalities<F: FnOnce(&mut dyn Externalities) -> R, R>(f: F) -> R {
|
||||
sp_externalities::with_externalities(f).expect("Environmental externalities not set.")
|
||||
@@ -68,7 +68,7 @@ where
|
||||
|
||||
// Uncompress
|
||||
let mut db = MemoryDB::default();
|
||||
let root = match sp_trie::decode_compact::<sp_trie::Layout<HashFor<B>>, _, _>(
|
||||
let root = match sp_trie::decode_compact::<sp_trie::LayoutV1<HashFor<B>>, _, _>(
|
||||
&mut db,
|
||||
storage_proof.iter_compact_encoded_nodes(),
|
||||
Some(parent_head.state_root()),
|
||||
@@ -89,7 +89,6 @@ where
|
||||
sp_io::storage::host_clear.replace_implementation(host_storage_clear),
|
||||
sp_io::storage::host_root.replace_implementation(host_storage_root),
|
||||
sp_io::storage::host_clear_prefix.replace_implementation(host_storage_clear_prefix),
|
||||
sp_io::storage::host_changes_root.replace_implementation(host_storage_changes_root),
|
||||
sp_io::storage::host_append.replace_implementation(host_storage_append),
|
||||
sp_io::storage::host_next_key.replace_implementation(host_storage_next_key),
|
||||
sp_io::storage::host_start_transaction
|
||||
@@ -162,6 +161,13 @@ where
|
||||
let horizontal_messages = crate::HrmpOutboundMessages::<PSC>::get();
|
||||
let hrmp_watermark = crate::HrmpWatermark::<PSC>::get();
|
||||
|
||||
let head_data =
|
||||
if let Some(custom_head_data) = crate::CustomValidationHeadData::<PSC>::get() {
|
||||
HeadData(custom_head_data)
|
||||
} else {
|
||||
head_data
|
||||
};
|
||||
|
||||
ValidationResult {
|
||||
head_data,
|
||||
new_validation_code: new_validation_code.map(Into::into),
|
||||
@@ -215,8 +221,8 @@ fn host_storage_clear(key: &[u8]) {
|
||||
with_externalities(|ext| ext.place_storage(key.to_vec(), None))
|
||||
}
|
||||
|
||||
fn host_storage_root() -> Vec<u8> {
|
||||
with_externalities(|ext| ext.storage_root())
|
||||
fn host_storage_root(version: StateVersion) -> Vec<u8> {
|
||||
with_externalities(|ext| ext.storage_root(version))
|
||||
}
|
||||
|
||||
fn host_storage_clear_prefix(prefix: &[u8], limit: Option<u32>) -> KillStorageResult {
|
||||
@@ -229,10 +235,6 @@ fn host_storage_clear_prefix(prefix: &[u8], limit: Option<u32>) -> KillStorageRe
|
||||
})
|
||||
}
|
||||
|
||||
fn host_storage_changes_root(parent_hash: &[u8]) -> Option<Vec<u8>> {
|
||||
with_externalities(|ext| ext.storage_changes_root(parent_hash).ok().flatten())
|
||||
}
|
||||
|
||||
fn host_storage_append(key: &[u8], value: Vec<u8>) {
|
||||
with_externalities(|ext| ext.storage_append(key.to_vec(), value))
|
||||
}
|
||||
@@ -325,9 +327,9 @@ fn host_default_child_storage_clear_prefix(
|
||||
})
|
||||
}
|
||||
|
||||
fn host_default_child_storage_root(storage_key: &[u8]) -> Vec<u8> {
|
||||
fn host_default_child_storage_root(storage_key: &[u8], version: StateVersion) -> Vec<u8> {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
with_externalities(|ext| ext.child_storage_root(&child_info))
|
||||
with_externalities(|ext| ext.child_storage_root(&child_info, version))
|
||||
}
|
||||
|
||||
fn host_default_child_storage_next_key(storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
use codec::{Decode, Encode};
|
||||
use cumulus_primitives_core::{ParachainBlockData, PersistedValidationData};
|
||||
use cumulus_test_client::{
|
||||
runtime::{Block, Hash, Header, UncheckedExtrinsic, WASM_BINARY},
|
||||
generate_extrinsic,
|
||||
runtime::{Block, Hash, Header, TestPalletCall, UncheckedExtrinsic, WASM_BINARY},
|
||||
transfer, BlockData, BuildParachainBlockData, Client, DefaultTestClientBuilderExt, HeadData,
|
||||
InitBlockBuilder, TestClientBuilder, TestClientBuilderExt, ValidationParams,
|
||||
};
|
||||
@@ -26,11 +27,11 @@ use sp_keyring::AccountKeyring::*;
|
||||
use sp_runtime::{generic::BlockId, traits::Header as HeaderT};
|
||||
use std::{env, process::Command};
|
||||
|
||||
fn call_validate_block(
|
||||
fn call_validate_block_encoded_header(
|
||||
parent_head: Header,
|
||||
block_data: ParachainBlockData<Block>,
|
||||
relay_parent_storage_root: Hash,
|
||||
) -> cumulus_test_client::ExecutorResult<Header> {
|
||||
) -> cumulus_test_client::ExecutorResult<Vec<u8>> {
|
||||
cumulus_test_client::validate_block(
|
||||
ValidationParams {
|
||||
block_data: BlockData(block_data.encode()),
|
||||
@@ -40,7 +41,16 @@ fn call_validate_block(
|
||||
},
|
||||
&WASM_BINARY.expect("You need to build the WASM binaries to run the tests!"),
|
||||
)
|
||||
.map(|v| Header::decode(&mut &v.head_data.0[..]).expect("Decodes `Header`."))
|
||||
.map(|v| v.head_data.0)
|
||||
}
|
||||
|
||||
fn call_validate_block(
|
||||
parent_head: Header,
|
||||
block_data: ParachainBlockData<Block>,
|
||||
relay_parent_storage_root: Hash,
|
||||
) -> cumulus_test_client::ExecutorResult<Header> {
|
||||
call_validate_block_encoded_header(parent_head, block_data, relay_parent_storage_root)
|
||||
.map(|v| Header::decode(&mut &v[..]).expect("Decodes `Header`."))
|
||||
}
|
||||
|
||||
fn create_test_client() -> (Client, Header) {
|
||||
@@ -92,7 +102,7 @@ fn validate_block_no_extra_extrinsics() {
|
||||
|
||||
let (client, parent_head) = create_test_client();
|
||||
let TestBlockData { block, validation_data } =
|
||||
build_block_with_witness(&client, vec![], parent_head.clone(), Default::default());
|
||||
build_block_with_witness(&client, Vec::new(), parent_head.clone(), Default::default());
|
||||
let header = block.header().clone();
|
||||
|
||||
let res_header =
|
||||
@@ -126,6 +136,43 @@ fn validate_block_with_extra_extrinsics() {
|
||||
assert_eq!(header, res_header);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_block_returns_custom_head_data() {
|
||||
sp_tracing::try_init_simple();
|
||||
|
||||
let expected_header = vec![1, 3, 3, 7, 4, 5, 6];
|
||||
|
||||
let (client, parent_head) = create_test_client();
|
||||
let extra_extrinsics = vec![
|
||||
transfer(&client, Alice, Bob, 69),
|
||||
generate_extrinsic(
|
||||
&client,
|
||||
Charlie,
|
||||
TestPalletCall::set_custom_validation_head_data {
|
||||
custom_header: expected_header.clone(),
|
||||
},
|
||||
),
|
||||
transfer(&client, Bob, Charlie, 100),
|
||||
];
|
||||
|
||||
let TestBlockData { block, validation_data } = build_block_with_witness(
|
||||
&client,
|
||||
extra_extrinsics,
|
||||
parent_head.clone(),
|
||||
Default::default(),
|
||||
);
|
||||
let header = block.header().clone();
|
||||
assert_ne!(expected_header, header.encode());
|
||||
|
||||
let res_header = call_validate_block_encoded_header(
|
||||
parent_head,
|
||||
block,
|
||||
validation_data.relay_parent_storage_root,
|
||||
)
|
||||
.expect("Calls `validate_block`");
|
||||
assert_eq!(expected_header, res_header);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_block_invalid_parent_hash() {
|
||||
sp_tracing::try_init_simple();
|
||||
@@ -133,7 +180,7 @@ fn validate_block_invalid_parent_hash() {
|
||||
if env::var("RUN_TEST").is_ok() {
|
||||
let (client, parent_head) = create_test_client();
|
||||
let TestBlockData { block, validation_data } =
|
||||
build_block_with_witness(&client, vec![], parent_head.clone(), Default::default());
|
||||
build_block_with_witness(&client, Vec::new(), parent_head.clone(), Default::default());
|
||||
let (mut header, extrinsics, witness) = block.deconstruct();
|
||||
header.set_parent_hash(Hash::from_low_u64_be(1));
|
||||
|
||||
@@ -159,7 +206,7 @@ fn validate_block_fails_on_invalid_validation_data() {
|
||||
if env::var("RUN_TEST").is_ok() {
|
||||
let (client, parent_head) = create_test_client();
|
||||
let TestBlockData { block, .. } =
|
||||
build_block_with_witness(&client, vec![], parent_head.clone(), Default::default());
|
||||
build_block_with_witness(&client, Vec::new(), parent_head.clone(), Default::default());
|
||||
|
||||
call_validate_block(parent_head, block, Hash::random()).unwrap_err();
|
||||
} else {
|
||||
@@ -184,7 +231,7 @@ fn check_inherent_fails_on_validate_block_as_expected() {
|
||||
|
||||
let TestBlockData { block, validation_data } = build_block_with_witness(
|
||||
&client,
|
||||
vec![],
|
||||
Vec::new(),
|
||||
parent_head.clone(),
|
||||
RelayStateSproofBuilder { current_slot: 1337.into(), ..Default::default() },
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "cumulus-pallet-session-benchmarking"
|
||||
version = "3.0.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
homepage = "https://substrate.io"
|
||||
repository = "https://github.com/paritytech/cumulus/"
|
||||
@@ -13,21 +13,23 @@ readme = "README.md"
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-session = { default-features = false, git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
parity-scale-codec = { version = "2.3.1", default-features = false }
|
||||
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-session = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
runtime-benchmarks = [
|
||||
'frame-benchmarking',
|
||||
'frame-support/runtime-benchmarks',
|
||||
'frame-system/runtime-benchmarks',
|
||||
"frame-benchmarking/runtime-benchmarks",
|
||||
"frame-support/runtime-benchmarks",
|
||||
"frame-system/runtime-benchmarks",
|
||||
]
|
||||
std = [
|
||||
"parity-scale-codec/std",
|
||||
"sp-std/std",
|
||||
"sp-runtime/std",
|
||||
"frame-system/std",
|
||||
|
||||
@@ -18,9 +18,10 @@
|
||||
#![cfg(feature = "runtime-benchmarks")]
|
||||
use sp_std::{prelude::*, vec};
|
||||
|
||||
use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller};
|
||||
use frame_benchmarking::{benchmarks, whitelisted_caller};
|
||||
use frame_system::RawOrigin;
|
||||
use pallet_session::*;
|
||||
use parity_scale_codec::Decode;
|
||||
pub struct Pallet<T: Config>(pallet_session::Pallet<T>);
|
||||
pub trait Config: pallet_session::Config {}
|
||||
|
||||
@@ -28,17 +29,15 @@ benchmarks! {
|
||||
set_keys {
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
frame_system::Pallet::<T>::inc_providers(&caller);
|
||||
let keys = T::Keys::default();
|
||||
let keys = T::Keys::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap();
|
||||
let proof: Vec<u8> = vec![0,1,2,3];
|
||||
}: _(RawOrigin::Signed(caller), keys, proof)
|
||||
|
||||
purge_keys {
|
||||
let caller: T::AccountId = whitelisted_caller();
|
||||
frame_system::Pallet::<T>::inc_providers(&caller);
|
||||
let keys = T::Keys::default();
|
||||
let keys = T::Keys::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap();
|
||||
let proof: Vec<u8> = vec![0,1,2,3];
|
||||
let _t = pallet_session::Pallet::<T>::set_keys(RawOrigin::Signed(caller.clone()).into(), keys, proof);
|
||||
}: _(RawOrigin::Signed(caller))
|
||||
|
||||
}
|
||||
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test, extra = false,);
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
name = "cumulus-pallet-xcm"
|
||||
version = "0.1.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "2.3.0", default-features = false, features = ["derive"] }
|
||||
scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0.101", optional = true, features = ["derive"] }
|
||||
serde = { version = "1.0.132", optional = true, features = ["derive"] }
|
||||
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
|
||||
sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "cumulus-pallet-xcmp-queue"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
# Other dependencies
|
||||
@@ -25,11 +25,11 @@ xcm-executor = { git = "https://github.com/paritytech/polkadot", default-feature
|
||||
cumulus-primitives-core = { path = "../../primitives/core", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
sp-core = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-io = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
cumulus-pallet-parachain-system = { path = "../parachain-system" }
|
||||
xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "master" }
|
||||
pallet-balances = { git = 'https://github.com/paritytech/substrate', branch = "master" }
|
||||
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[features]
|
||||
default = [ "std" ]
|
||||
|
||||
+256
-75
@@ -25,6 +25,8 @@
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub mod migration;
|
||||
|
||||
#[cfg(test)]
|
||||
mod mock;
|
||||
|
||||
@@ -36,7 +38,7 @@ use cumulus_primitives_core::{
|
||||
relay_chain::BlockNumber as RelayBlockNumber, ChannelStatus, GetChannelInfo, MessageSendError,
|
||||
ParaId, XcmpMessageFormat, XcmpMessageHandler, XcmpMessageSource,
|
||||
};
|
||||
use frame_support::weights::Weight;
|
||||
use frame_support::weights::{constants::WEIGHT_PER_MILLIS, Weight};
|
||||
use rand_chacha::{
|
||||
rand_core::{RngCore, SeedableRng},
|
||||
ChaChaRng,
|
||||
@@ -48,6 +50,11 @@ use xcm::{latest::prelude::*, VersionedXcm, WrapVersion, MAX_XCM_DECODE_DEPTH};
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
/// Index used to identify overweight XCMs.
|
||||
pub type OverweightIndex = u64;
|
||||
|
||||
const LOG_TARGET: &str = "xcmp_queue";
|
||||
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
@@ -56,6 +63,7 @@ pub mod pallet {
|
||||
|
||||
#[pallet::pallet]
|
||||
#[pallet::generate_store(pub(super) trait Store)]
|
||||
#[pallet::storage_version(migration::STORAGE_VERSION)]
|
||||
pub struct Pallet<T>(_);
|
||||
|
||||
#[pallet::config]
|
||||
@@ -70,22 +78,17 @@ pub mod pallet {
|
||||
|
||||
/// Means of converting an `Xcm` into a `VersionedXcm`.
|
||||
type VersionWrapper: WrapVersion;
|
||||
}
|
||||
|
||||
impl Default for QueueConfigData {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
suspend_threshold: 2,
|
||||
drop_threshold: 5,
|
||||
resume_threshold: 1,
|
||||
threshold_weight: 100_000,
|
||||
weight_restrict_decay: 2,
|
||||
}
|
||||
}
|
||||
/// The origin that is allowed to execute overweight messages.
|
||||
type ExecuteOverweightOrigin: EnsureOrigin<Self::Origin>;
|
||||
}
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
|
||||
fn on_runtime_upgrade() -> Weight {
|
||||
migration::migrate_to_latest::<T>()
|
||||
}
|
||||
|
||||
fn on_idle(_now: T::BlockNumber, max_weight: Weight) -> Weight {
|
||||
// on_idle processes additional messages with any remaining block weight.
|
||||
Self::service_xcmp_queue(max_weight)
|
||||
@@ -93,7 +96,40 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
#[pallet::call]
|
||||
impl<T: Config> Pallet<T> {}
|
||||
impl<T: Config> Pallet<T> {
|
||||
/// Services a single overweight XCM.
|
||||
///
|
||||
/// - `origin`: Must pass `ExecuteOverweightOrigin`.
|
||||
/// - `index`: The index of the overweight XCM to service
|
||||
/// - `weight_limit`: The amount of weight that XCM execution may take.
|
||||
///
|
||||
/// Errors:
|
||||
/// - `BadOverweightIndex`: XCM under `index` is not found in the `Overweight` storage map.
|
||||
/// - `BadXcm`: XCM under `index` cannot be properly decoded into a valid XCM format.
|
||||
/// - `WeightOverLimit`: XCM execution may use greater `weight_limit`.
|
||||
///
|
||||
/// Events:
|
||||
/// - `OverweightServiced`: On success.
|
||||
#[pallet::weight(weight_limit.saturating_add(1_000_000))]
|
||||
pub fn service_overweight(
|
||||
origin: OriginFor<T>,
|
||||
index: OverweightIndex,
|
||||
weight_limit: Weight,
|
||||
) -> DispatchResultWithPostInfo {
|
||||
T::ExecuteOverweightOrigin::ensure_origin(origin)?;
|
||||
|
||||
let (sender, sent_at, data) =
|
||||
Overweight::<T>::get(index).ok_or(Error::<T>::BadOverweightIndex)?;
|
||||
let xcm =
|
||||
VersionedXcm::<T::Call>::decode_all_with_depth_limit(MAX_XCM_DECODE_DEPTH, &data)
|
||||
.map_err(|_| Error::<T>::BadXcm)?;
|
||||
let used = Self::handle_xcm_message(sender, sent_at, xcm, weight_limit)
|
||||
.map_err(|_| Error::<T>::WeightOverLimit)?;
|
||||
Overweight::<T>::remove(index);
|
||||
Self::deposit_event(Event::OverweightServiced(index, used));
|
||||
Ok(Some(used.saturating_add(1_000_000)).into())
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
@@ -110,6 +146,10 @@ pub mod pallet {
|
||||
UpwardMessageSent(Option<T::Hash>),
|
||||
/// An HRMP message was sent to a sibling parachain.
|
||||
XcmpMessageSent(Option<T::Hash>),
|
||||
/// An XCM exceeded the individual message weight budget.
|
||||
OverweightEnqueued(ParaId, RelayBlockNumber, OverweightIndex, Weight),
|
||||
/// An XCM from the overweight queue was executed with the given actual weight used.
|
||||
OverweightServiced(OverweightIndex, Weight),
|
||||
}
|
||||
|
||||
#[pallet::error]
|
||||
@@ -120,15 +160,16 @@ pub mod pallet {
|
||||
BadXcmOrigin,
|
||||
/// Bad XCM data.
|
||||
BadXcm,
|
||||
/// Bad overweight index.
|
||||
BadOverweightIndex,
|
||||
/// Provided weight is possibly not enough to execute the message.
|
||||
WeightOverLimit,
|
||||
}
|
||||
|
||||
/// Status of the inbound XCMP channels.
|
||||
#[pallet::storage]
|
||||
pub(super) type InboundXcmpStatus<T: Config> = StorageValue<
|
||||
_,
|
||||
Vec<(ParaId, InboundStatus, Vec<(RelayBlockNumber, XcmpMessageFormat)>)>,
|
||||
ValueQuery,
|
||||
>;
|
||||
pub(super) type InboundXcmpStatus<T: Config> =
|
||||
StorageValue<_, Vec<InboundChannelDetails>, ValueQuery>;
|
||||
|
||||
/// Inbound aggregate XCMP messages. It can only be one per ParaId/block.
|
||||
#[pallet::storage]
|
||||
@@ -150,7 +191,7 @@ pub mod pallet {
|
||||
/// The bool is true if there is a signal message waiting to be sent.
|
||||
#[pallet::storage]
|
||||
pub(super) type OutboundXcmpStatus<T: Config> =
|
||||
StorageValue<_, Vec<(ParaId, OutboundStatus, bool, u16, u16)>, ValueQuery>;
|
||||
StorageValue<_, Vec<OutboundChannelDetails>, ValueQuery>;
|
||||
|
||||
// The new way of doing it:
|
||||
/// The messages outbound in a given XCMP channel.
|
||||
@@ -166,20 +207,84 @@ pub mod pallet {
|
||||
/// The configuration which controls the dynamics of the outbound queue.
|
||||
#[pallet::storage]
|
||||
pub(super) type QueueConfig<T: Config> = StorageValue<_, QueueConfigData, ValueQuery>;
|
||||
|
||||
/// The messages that exceeded max individual message weight budget.
|
||||
///
|
||||
/// These message stay in this storage map until they are manually dispatched via
|
||||
/// `service_overweight`.
|
||||
#[pallet::storage]
|
||||
pub(super) type Overweight<T: Config> =
|
||||
StorageMap<_, Twox64Concat, OverweightIndex, (ParaId, RelayBlockNumber, Vec<u8>)>;
|
||||
|
||||
/// The number of overweight messages ever recorded in `Overweight`. Also doubles as the next
|
||||
/// available free overweight index.
|
||||
#[pallet::storage]
|
||||
pub(super) type OverweightCount<T: Config> = StorageValue<_, OverweightIndex, ValueQuery>;
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
pub enum InboundStatus {
|
||||
pub enum InboundState {
|
||||
Ok,
|
||||
Suspended,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
pub enum OutboundStatus {
|
||||
pub enum OutboundState {
|
||||
Ok,
|
||||
Suspended,
|
||||
}
|
||||
|
||||
/// Struct containing detailed information about the inbound channel.
|
||||
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
|
||||
pub struct InboundChannelDetails {
|
||||
/// The `ParaId` of the parachain that this channel is connected with.
|
||||
sender: ParaId,
|
||||
/// The state of the channel.
|
||||
state: InboundState,
|
||||
/// The ordered metadata of each inbound message.
|
||||
///
|
||||
/// Contains info about the relay block number that the message was sent at, and the format
|
||||
/// of the incoming message.
|
||||
message_metadata: Vec<(RelayBlockNumber, XcmpMessageFormat)>,
|
||||
}
|
||||
|
||||
/// Struct containing detailed information about the outbound channel.
|
||||
#[derive(Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
|
||||
pub struct OutboundChannelDetails {
|
||||
/// The `ParaId` of the parachain that this channel is connected with.
|
||||
recipient: ParaId,
|
||||
/// The state of the channel.
|
||||
state: OutboundState,
|
||||
/// Whether or not any signals exist in this channel.
|
||||
signals_exist: bool,
|
||||
/// The index of the first outbound message.
|
||||
first_index: u16,
|
||||
/// The index of the last outbound message.
|
||||
last_index: u16,
|
||||
}
|
||||
|
||||
impl OutboundChannelDetails {
|
||||
pub fn new(recipient: ParaId) -> OutboundChannelDetails {
|
||||
OutboundChannelDetails {
|
||||
recipient,
|
||||
state: OutboundState::Ok,
|
||||
signals_exist: false,
|
||||
first_index: 0,
|
||||
last_index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_signals(mut self) -> OutboundChannelDetails {
|
||||
self.signals_exist = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_suspended_state(mut self) -> OutboundChannelDetails {
|
||||
self.state = OutboundState::Suspended;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
|
||||
pub struct QueueConfigData {
|
||||
/// The number of pages of messages which must be in the queue for the other side to be told to
|
||||
@@ -196,6 +301,22 @@ pub struct QueueConfigData {
|
||||
/// The speed to which the available weight approaches the maximum weight. A lower number
|
||||
/// results in a faster progression. A value of 1 makes the entire weight available initially.
|
||||
weight_restrict_decay: Weight,
|
||||
/// The maximum amount of weight any individual message may consume. Messages above this weight
|
||||
/// go into the overweight queue and may only be serviced explicitly.
|
||||
xcmp_max_individual_weight: Weight,
|
||||
}
|
||||
|
||||
impl Default for QueueConfigData {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
suspend_threshold: 2,
|
||||
drop_threshold: 5,
|
||||
resume_threshold: 1,
|
||||
threshold_weight: 100_000,
|
||||
weight_restrict_decay: 2,
|
||||
xcmp_max_individual_weight: 20 * WEIGHT_PER_MILLIS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, TypeInfo)]
|
||||
@@ -242,13 +363,13 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
|
||||
let mut s = <OutboundXcmpStatus<T>>::get();
|
||||
let index = s.iter().position(|item| item.0 == recipient).unwrap_or_else(|| {
|
||||
s.push((recipient, OutboundStatus::Ok, false, 0, 0));
|
||||
let index = s.iter().position(|item| item.recipient == recipient).unwrap_or_else(|| {
|
||||
s.push(OutboundChannelDetails::new(recipient));
|
||||
s.len() - 1
|
||||
});
|
||||
let have_active = s[index].4 > s[index].3;
|
||||
let have_active = s[index].last_index > s[index].first_index;
|
||||
let appended = have_active &&
|
||||
<OutboundXcmpMessages<T>>::mutate(recipient, s[index].4 - 1, |s| {
|
||||
<OutboundXcmpMessages<T>>::mutate(recipient, s[index].last_index - 1, |s| {
|
||||
if XcmpMessageFormat::decode_and_advance_with_depth_limit(
|
||||
MAX_XCM_DECODE_DEPTH,
|
||||
&mut &s[..],
|
||||
@@ -263,15 +384,15 @@ impl<T: Config> Pallet<T> {
|
||||
return true
|
||||
});
|
||||
if appended {
|
||||
Ok((s[index].4 - s[index].3 - 1) as u32)
|
||||
Ok((s[index].last_index - s[index].first_index - 1) as u32)
|
||||
} else {
|
||||
// Need to add a new page.
|
||||
let page_index = s[index].4;
|
||||
s[index].4 += 1;
|
||||
let page_index = s[index].last_index;
|
||||
s[index].last_index += 1;
|
||||
let mut new_page = format.encode();
|
||||
new_page.extend_from_slice(&data[..]);
|
||||
<OutboundXcmpMessages<T>>::insert(recipient, page_index, new_page);
|
||||
let r = (s[index].4 - s[index].3 - 1) as u32;
|
||||
let r = (s[index].last_index - s[index].first_index - 1) as u32;
|
||||
<OutboundXcmpStatus<T>>::put(s);
|
||||
Ok(r)
|
||||
}
|
||||
@@ -281,10 +402,10 @@ impl<T: Config> Pallet<T> {
|
||||
/// block.
|
||||
fn send_signal(dest: ParaId, signal: ChannelSignal) -> Result<(), ()> {
|
||||
let mut s = <OutboundXcmpStatus<T>>::get();
|
||||
if let Some(index) = s.iter().position(|item| item.0 == dest) {
|
||||
s[index].2 = true;
|
||||
if let Some(index) = s.iter().position(|item| item.recipient == dest) {
|
||||
s[index].signals_exist = true;
|
||||
} else {
|
||||
s.push((dest, OutboundStatus::Ok, true, 0, 0));
|
||||
s.push(OutboundChannelDetails::new(dest).with_signals());
|
||||
}
|
||||
<SignalMessages<T>>::mutate(dest, |page| {
|
||||
if page.is_empty() {
|
||||
@@ -366,6 +487,7 @@ impl<T: Config> Pallet<T> {
|
||||
sender: ParaId,
|
||||
(sent_at, format): (RelayBlockNumber, XcmpMessageFormat),
|
||||
max_weight: Weight,
|
||||
max_individual_weight: Weight,
|
||||
) -> (Weight, bool) {
|
||||
let data = <InboundXcmpMessages<T>>::get(sender, sent_at);
|
||||
let mut last_remaining_fragments;
|
||||
@@ -382,7 +504,22 @@ impl<T: Config> Pallet<T> {
|
||||
let weight = max_weight - weight_used;
|
||||
match Self::handle_xcm_message(sender, sent_at, xcm, weight) {
|
||||
Ok(used) => weight_used = weight_used.saturating_add(used),
|
||||
Err(XcmError::TooMuchWeightRequired) => {
|
||||
Err(XcmError::WeightLimitReached(required))
|
||||
if required > max_individual_weight =>
|
||||
{
|
||||
// overweight - add to overweight queue and continue with message
|
||||
// execution consuming the message.
|
||||
let msg_len = last_remaining_fragments
|
||||
.len()
|
||||
.saturating_sub(remaining_fragments.len());
|
||||
let overweight_xcm = last_remaining_fragments[..msg_len].to_vec();
|
||||
let index = Self::stash_overweight(sender, sent_at, overweight_xcm);
|
||||
let e = Event::OverweightEnqueued(sender, sent_at, index, required);
|
||||
Self::deposit_event(e);
|
||||
},
|
||||
Err(XcmError::WeightLimitReached(required))
|
||||
if required <= max_weight =>
|
||||
{
|
||||
// That message didn't get processed this time because of being
|
||||
// too heavy. We leave it around for next time and bail.
|
||||
remaining_fragments = last_remaining_fragments;
|
||||
@@ -438,6 +575,22 @@ impl<T: Config> Pallet<T> {
|
||||
(weight_used, is_empty)
|
||||
}
|
||||
|
||||
/// Puts a given XCM into the list of overweight messages, allowing it to be executed later.
|
||||
fn stash_overweight(
|
||||
sender: ParaId,
|
||||
sent_at: RelayBlockNumber,
|
||||
xcm: Vec<u8>,
|
||||
) -> OverweightIndex {
|
||||
let index = <Self as Store>::OverweightCount::mutate(|count| {
|
||||
let index = *count;
|
||||
*count += 1;
|
||||
index
|
||||
});
|
||||
|
||||
<Self as Store>::Overweight::insert(index, (sender, sent_at, xcm));
|
||||
index
|
||||
}
|
||||
|
||||
/// Service the incoming XCMP message queue attempting to execute up to `max_weight` execution
|
||||
/// weight of messages.
|
||||
///
|
||||
@@ -471,8 +624,13 @@ impl<T: Config> Pallet<T> {
|
||||
return 0
|
||||
}
|
||||
|
||||
let QueueConfigData { resume_threshold, threshold_weight, weight_restrict_decay, .. } =
|
||||
<QueueConfig<T>>::get();
|
||||
let QueueConfigData {
|
||||
resume_threshold,
|
||||
threshold_weight,
|
||||
weight_restrict_decay,
|
||||
xcmp_max_individual_weight,
|
||||
..
|
||||
} = <QueueConfig<T>>::get();
|
||||
|
||||
let mut shuffled = Self::create_shuffle(status.len());
|
||||
let mut weight_used = 0;
|
||||
@@ -491,7 +649,7 @@ impl<T: Config> Pallet<T> {
|
||||
max_weight.saturating_sub(weight_used) >= threshold_weight
|
||||
{
|
||||
let index = shuffled[shuffle_index];
|
||||
let sender = status[index].0;
|
||||
let sender = status[index].sender;
|
||||
|
||||
if weight_available != max_weight {
|
||||
// Get incrementally closer to freeing up max_weight for message execution over the
|
||||
@@ -508,34 +666,38 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
let weight_processed = if status[index].2.is_empty() {
|
||||
let weight_processed = if status[index].message_metadata.is_empty() {
|
||||
debug_assert!(false, "channel exists in status; there must be messages; qed");
|
||||
0
|
||||
} else {
|
||||
// Process up to one block's worth for now.
|
||||
let weight_remaining = weight_available.saturating_sub(weight_used);
|
||||
let (weight_processed, is_empty) =
|
||||
Self::process_xcmp_message(sender, status[index].2[0], weight_remaining);
|
||||
let (weight_processed, is_empty) = Self::process_xcmp_message(
|
||||
sender,
|
||||
status[index].message_metadata[0],
|
||||
weight_remaining,
|
||||
xcmp_max_individual_weight,
|
||||
);
|
||||
if is_empty {
|
||||
status[index].2.remove(0);
|
||||
status[index].message_metadata.remove(0);
|
||||
}
|
||||
weight_processed
|
||||
};
|
||||
weight_used += weight_processed;
|
||||
|
||||
if status[index].2.len() as u32 <= resume_threshold &&
|
||||
status[index].1 == InboundStatus::Suspended
|
||||
if status[index].message_metadata.len() as u32 <= resume_threshold &&
|
||||
status[index].state == InboundState::Suspended
|
||||
{
|
||||
// Resume
|
||||
let r = Self::send_signal(sender, ChannelSignal::Resume);
|
||||
debug_assert!(r.is_ok(), "WARNING: Failed sending resume into suspended channel");
|
||||
status[index].1 = InboundStatus::Ok;
|
||||
status[index].state = InboundState::Ok;
|
||||
}
|
||||
|
||||
// If there are more and we're making progress, we process them after we've given the
|
||||
// other channels a look in. If we've still not unlocked all weight, then we set them
|
||||
// up for processing a second time anyway.
|
||||
if !status[index].2.is_empty() &&
|
||||
if !status[index].message_metadata.is_empty() &&
|
||||
(weight_processed > 0 || weight_available != max_weight)
|
||||
{
|
||||
if shuffle_index + 1 == shuffled.len() {
|
||||
@@ -548,7 +710,7 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
|
||||
// Only retain the senders that have non-empty queues.
|
||||
status.retain(|item| !item.2.is_empty());
|
||||
status.retain(|item| !item.message_metadata.is_empty());
|
||||
|
||||
<InboundXcmpStatus<T>>::put(status);
|
||||
weight_used
|
||||
@@ -556,28 +718,28 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
fn suspend_channel(target: ParaId) {
|
||||
<OutboundXcmpStatus<T>>::mutate(|s| {
|
||||
if let Some(index) = s.iter().position(|item| item.0 == target) {
|
||||
let ok = s[index].1 == OutboundStatus::Ok;
|
||||
if let Some(index) = s.iter().position(|item| item.recipient == target) {
|
||||
let ok = s[index].state == OutboundState::Ok;
|
||||
debug_assert!(ok, "WARNING: Attempt to suspend channel that was not Ok.");
|
||||
s[index].1 = OutboundStatus::Suspended;
|
||||
s[index].state = OutboundState::Suspended;
|
||||
} else {
|
||||
s.push((target, OutboundStatus::Suspended, false, 0, 0));
|
||||
s.push(OutboundChannelDetails::new(target).with_suspended_state());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn resume_channel(target: ParaId) {
|
||||
<OutboundXcmpStatus<T>>::mutate(|s| {
|
||||
if let Some(index) = s.iter().position(|item| item.0 == target) {
|
||||
let suspended = s[index].1 == OutboundStatus::Suspended;
|
||||
if let Some(index) = s.iter().position(|item| item.recipient == target) {
|
||||
let suspended = s[index].state == OutboundState::Suspended;
|
||||
debug_assert!(
|
||||
suspended,
|
||||
"WARNING: Attempt to resume channel that was not suspended."
|
||||
);
|
||||
if s[index].3 == s[index].4 {
|
||||
if s[index].first_index == s[index].last_index {
|
||||
s.remove(index);
|
||||
} else {
|
||||
s[index].1 = OutboundStatus::Ok;
|
||||
s[index].state = OutboundState::Ok;
|
||||
}
|
||||
} else {
|
||||
debug_assert!(false, "WARNING: Attempt to resume channel that was not suspended.");
|
||||
@@ -619,11 +781,12 @@ impl<T: Config> XcmpMessageHandler for Pallet<T> {
|
||||
}
|
||||
} else {
|
||||
// Record the fact we received it.
|
||||
match status.binary_search_by_key(&sender, |item| item.0) {
|
||||
match status.binary_search_by_key(&sender, |item| item.sender) {
|
||||
Ok(i) => {
|
||||
let count = status[i].2.len();
|
||||
if count as u32 >= suspend_threshold && status[i].1 == InboundStatus::Ok {
|
||||
status[i].1 = InboundStatus::Suspended;
|
||||
let count = status[i].message_metadata.len();
|
||||
if count as u32 >= suspend_threshold && status[i].state == InboundState::Ok
|
||||
{
|
||||
status[i].state = InboundState::Suspended;
|
||||
let r = Self::send_signal(sender, ChannelSignal::Suspend);
|
||||
if r.is_err() {
|
||||
log::warn!(
|
||||
@@ -632,7 +795,7 @@ impl<T: Config> XcmpMessageHandler for Pallet<T> {
|
||||
}
|
||||
}
|
||||
if (count as u32) < drop_threshold {
|
||||
status[i].2.push((sent_at, format));
|
||||
status[i].message_metadata.push((sent_at, format));
|
||||
} else {
|
||||
debug_assert!(
|
||||
false,
|
||||
@@ -640,7 +803,11 @@ impl<T: Config> XcmpMessageHandler for Pallet<T> {
|
||||
);
|
||||
}
|
||||
},
|
||||
Err(_) => status.push((sender, InboundStatus::Ok, vec![(sent_at, format)])),
|
||||
Err(_) => status.push(InboundChannelDetails {
|
||||
sender,
|
||||
state: InboundState::Ok,
|
||||
message_metadata: vec![(sent_at, format)],
|
||||
}),
|
||||
}
|
||||
// Queue the payload for later execution.
|
||||
<InboundXcmpMessages<T>>::insert(sender, sent_at, data_ref);
|
||||
@@ -664,47 +831,53 @@ impl<T: Config> XcmpMessageSource for Pallet<T> {
|
||||
let mut result = Vec::with_capacity(max_message_count);
|
||||
|
||||
for status in statuses.iter_mut() {
|
||||
let (para_id, outbound_status, mut signalling, mut begin, mut end) = *status;
|
||||
let OutboundChannelDetails {
|
||||
recipient: para_id,
|
||||
state: outbound_state,
|
||||
mut signals_exist,
|
||||
mut first_index,
|
||||
mut last_index,
|
||||
} = *status;
|
||||
|
||||
if result.len() == max_message_count {
|
||||
// We check this condition in the beginning of the loop so that we don't include
|
||||
// a message where the limit is 0.
|
||||
break
|
||||
}
|
||||
if outbound_status == OutboundStatus::Suspended {
|
||||
if outbound_state == OutboundState::Suspended {
|
||||
continue
|
||||
}
|
||||
let (max_size_now, max_size_ever) = match T::ChannelInfo::get_channel_status(para_id) {
|
||||
ChannelStatus::Closed => {
|
||||
// This means that there is no such channel anymore. Nothing to be done but
|
||||
// swallow the messages and discard the status.
|
||||
for i in begin..end {
|
||||
for i in first_index..last_index {
|
||||
<OutboundXcmpMessages<T>>::remove(para_id, i);
|
||||
}
|
||||
if signalling {
|
||||
if signals_exist {
|
||||
<SignalMessages<T>>::remove(para_id);
|
||||
}
|
||||
*status = (para_id, OutboundStatus::Ok, false, 0, 0);
|
||||
*status = OutboundChannelDetails::new(para_id);
|
||||
continue
|
||||
},
|
||||
ChannelStatus::Full => continue,
|
||||
ChannelStatus::Ready(n, e) => (n, e),
|
||||
};
|
||||
|
||||
let page = if signalling {
|
||||
let page = if signals_exist {
|
||||
let page = <SignalMessages<T>>::get(para_id);
|
||||
if page.len() < max_size_now {
|
||||
<SignalMessages<T>>::remove(para_id);
|
||||
signalling = false;
|
||||
signals_exist = false;
|
||||
page
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
} else if end > begin {
|
||||
let page = <OutboundXcmpMessages<T>>::get(para_id, begin);
|
||||
} else if last_index > first_index {
|
||||
let page = <OutboundXcmpMessages<T>>::get(para_id, first_index);
|
||||
if page.len() < max_size_now {
|
||||
<OutboundXcmpMessages<T>>::remove(para_id, begin);
|
||||
begin += 1;
|
||||
<OutboundXcmpMessages<T>>::remove(para_id, first_index);
|
||||
first_index += 1;
|
||||
page
|
||||
} else {
|
||||
continue
|
||||
@@ -712,9 +885,9 @@ impl<T: Config> XcmpMessageSource for Pallet<T> {
|
||||
} else {
|
||||
continue
|
||||
};
|
||||
if begin == end {
|
||||
begin = 0;
|
||||
end = 0;
|
||||
if first_index == last_index {
|
||||
first_index = 0;
|
||||
last_index = 0;
|
||||
}
|
||||
|
||||
if page.len() > max_size_ever {
|
||||
@@ -726,7 +899,13 @@ impl<T: Config> XcmpMessageSource for Pallet<T> {
|
||||
result.push((para_id, page));
|
||||
}
|
||||
|
||||
*status = (para_id, outbound_status, signalling, begin, end);
|
||||
*status = OutboundChannelDetails {
|
||||
recipient: para_id,
|
||||
state: outbound_state,
|
||||
signals_exist,
|
||||
first_index,
|
||||
last_index,
|
||||
};
|
||||
}
|
||||
|
||||
// Sort the outbound messages by ascending recipient para id to satisfy the acceptance
|
||||
@@ -741,7 +920,9 @@ impl<T: Config> XcmpMessageSource for Pallet<T> {
|
||||
//
|
||||
// To mitigate this we shift all processed elements towards the end of the vector using
|
||||
// `rotate_left`. To get intuition how it works see the examples in its rustdoc.
|
||||
statuses.retain(|x| x.1 == OutboundStatus::Suspended || x.2 || x.3 < x.4);
|
||||
statuses.retain(|x| {
|
||||
x.state == OutboundState::Suspended || x.signals_exist || x.first_index < x.last_index
|
||||
});
|
||||
|
||||
// old_status_len must be >= status.len() since we never add anything to status.
|
||||
let pruned = old_statuses_len - statuses.len();
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// Copyright 2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Polkadot.
|
||||
|
||||
// Polkadot 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.
|
||||
|
||||
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! A module that is responsible for migration of storage.
|
||||
|
||||
use crate::{Config, Pallet, Store};
|
||||
use frame_support::{pallet_prelude::*, traits::StorageVersion, weights::Weight};
|
||||
|
||||
/// The current storage version.
|
||||
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
|
||||
|
||||
/// Migrates the pallet storage to the most recent version, checking and setting the
|
||||
/// `StorageVersion`.
|
||||
pub fn migrate_to_latest<T: Config>() -> Weight {
|
||||
let mut weight = 0;
|
||||
|
||||
if StorageVersion::get::<Pallet<T>>() == 0 {
|
||||
weight += migrate_to_v1::<T>();
|
||||
StorageVersion::new(1).put::<Pallet<T>>();
|
||||
}
|
||||
|
||||
weight
|
||||
}
|
||||
|
||||
mod v0 {
|
||||
use super::*;
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
#[derive(Encode, Decode, Debug)]
|
||||
pub struct QueueConfigData {
|
||||
pub suspend_threshold: u32,
|
||||
pub drop_threshold: u32,
|
||||
pub resume_threshold: u32,
|
||||
pub threshold_weight: Weight,
|
||||
pub weight_restrict_decay: Weight,
|
||||
}
|
||||
|
||||
impl Default for QueueConfigData {
|
||||
fn default() -> Self {
|
||||
QueueConfigData {
|
||||
suspend_threshold: 2,
|
||||
drop_threshold: 5,
|
||||
resume_threshold: 1,
|
||||
threshold_weight: 100_000,
|
||||
weight_restrict_decay: 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Migrates `QueueConfigData` from v0 (without the `xcmp_max_individual_weight` field) to v1 (with
|
||||
/// max individual weight).
|
||||
/// Uses the `Default` implementation of `QueueConfigData` to choose a value for
|
||||
/// `xcmp_max_individual_weight`.
|
||||
///
|
||||
/// NOTE: Only use this function if you know what you're doing. Default to using
|
||||
/// `migrate_to_latest`.
|
||||
pub fn migrate_to_v1<T: Config>() -> Weight {
|
||||
let translate = |pre: v0::QueueConfigData| -> super::QueueConfigData {
|
||||
super::QueueConfigData {
|
||||
suspend_threshold: pre.suspend_threshold,
|
||||
drop_threshold: pre.drop_threshold,
|
||||
resume_threshold: pre.resume_threshold,
|
||||
threshold_weight: pre.threshold_weight,
|
||||
weight_restrict_decay: pre.weight_restrict_decay,
|
||||
xcmp_max_individual_weight: super::QueueConfigData::default()
|
||||
.xcmp_max_individual_weight,
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(_) = <Pallet<T> as Store>::QueueConfig::translate(|pre| pre.map(translate)) {
|
||||
log::error!(
|
||||
target: super::LOG_TARGET,
|
||||
"unexpected error when performing translation of the QueueConfig type during storage upgrade to v1"
|
||||
);
|
||||
}
|
||||
|
||||
T::DbWeight::get().reads_writes(1, 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::mock::{new_test_ext, Test};
|
||||
|
||||
#[test]
|
||||
fn test_migration_to_v1() {
|
||||
let v0 = v0::QueueConfigData {
|
||||
suspend_threshold: 5,
|
||||
drop_threshold: 12,
|
||||
resume_threshold: 3,
|
||||
threshold_weight: 333_333,
|
||||
weight_restrict_decay: 1,
|
||||
};
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
// Put the v0 version in the state
|
||||
frame_support::storage::unhashed::put_raw(
|
||||
&crate::QueueConfig::<Test>::hashed_key(),
|
||||
&v0.encode(),
|
||||
);
|
||||
|
||||
migrate_to_v1::<Test>();
|
||||
|
||||
let v1 = crate::QueueConfig::<Test>::get();
|
||||
|
||||
assert_eq!(v0.suspend_threshold, v1.suspend_threshold);
|
||||
assert_eq!(v0.drop_threshold, v1.drop_threshold);
|
||||
assert_eq!(v0.resume_threshold, v1.resume_threshold);
|
||||
assert_eq!(v0.threshold_weight, v1.threshold_weight);
|
||||
assert_eq!(v0.weight_restrict_decay, v1.weight_restrict_decay);
|
||||
assert_eq!(v1.xcmp_max_individual_weight, 20_000_000_000);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
use super::*;
|
||||
use crate as xcmp_queue;
|
||||
use frame_support::parameter_types;
|
||||
use frame_system::EnsureRoot;
|
||||
use sp_core::H256;
|
||||
use sp_runtime::{
|
||||
testing::Header,
|
||||
@@ -75,6 +76,7 @@ impl frame_system::Config for Test {
|
||||
type SystemWeightInfo = ();
|
||||
type SS58Prefix = SS58Prefix;
|
||||
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Test>;
|
||||
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
parameter_types! {
|
||||
@@ -160,6 +162,7 @@ impl Config for Test {
|
||||
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
|
||||
type ChannelInfo = ParachainSystem;
|
||||
type VersionWrapper = ();
|
||||
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
|
||||
}
|
||||
|
||||
pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
|
||||
use super::*;
|
||||
use cumulus_primitives_core::XcmpMessageHandler;
|
||||
use mock::{new_test_ext, Test, XcmpQueue};
|
||||
use frame_support::assert_noop;
|
||||
use mock::{new_test_ext, Origin, Test, XcmpQueue};
|
||||
|
||||
#[test]
|
||||
fn one_message_does_not_panic() {
|
||||
@@ -30,6 +31,7 @@ fn one_message_does_not_panic() {
|
||||
|
||||
#[test]
|
||||
#[should_panic = "Invalid incoming blob message data"]
|
||||
#[cfg(debug_assertions)]
|
||||
fn bad_message_is_handled() {
|
||||
new_test_ext().execute_with(|| {
|
||||
let bad_data = vec![
|
||||
@@ -40,12 +42,13 @@ fn bad_message_is_handled() {
|
||||
InboundXcmpMessages::<Test>::insert(ParaId::from(1000), 1, bad_data);
|
||||
let format = XcmpMessageFormat::ConcatenatedEncodedBlob;
|
||||
// This should exit with an error.
|
||||
XcmpQueue::process_xcmp_message(1000.into(), (1, format), 10_000_000_000);
|
||||
XcmpQueue::process_xcmp_message(1000.into(), (1, format), 10_000_000_000, 10_000_000_000);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic = "Invalid incoming blob message data"]
|
||||
#[cfg(debug_assertions)]
|
||||
fn other_bad_message_is_handled() {
|
||||
new_test_ext().execute_with(|| {
|
||||
let bad_data = vec![
|
||||
@@ -56,6 +59,26 @@ fn other_bad_message_is_handled() {
|
||||
InboundXcmpMessages::<Test>::insert(ParaId::from(1000), 1, bad_data);
|
||||
let format = XcmpMessageFormat::ConcatenatedEncodedBlob;
|
||||
// This should exit with an error.
|
||||
XcmpQueue::process_xcmp_message(1000.into(), (1, format), 10_000_000_000);
|
||||
XcmpQueue::process_xcmp_message(1000.into(), (1, format), 10_000_000_000, 10_000_000_000);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_overweight_unknown() {
|
||||
new_test_ext().execute_with(|| {
|
||||
assert_noop!(
|
||||
XcmpQueue::service_overweight(Origin::root(), 0, 1000),
|
||||
Error::<Test>::BadOverweightIndex,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_overweight_bad_xcm_format() {
|
||||
new_test_ext().execute_with(|| {
|
||||
let bad_xcm = vec![255];
|
||||
Overweight::<Test>::insert(0, (ParaId::from(1000), 0, bad_xcm));
|
||||
|
||||
assert_noop!(XcmpQueue::service_overweight(Origin::root(), 0, 1000), Error::<Test>::BadXcm);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user