Merge branch 'master' into gav-xcm-v3

This commit is contained in:
Keith Yeung
2022-09-22 21:36:30 +08:00
203 changed files with 5861 additions and 3564 deletions
+2 -1
View File
@@ -7,7 +7,7 @@ description = "AURA consensus extension pallet for parachains"
[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.2.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.144", optional = true, features = ["derive"] }
# Substrate
@@ -40,3 +40,4 @@ std = [
"sp-runtime/std",
"sp-std/std",
]
try-runtime = ["frame-support/try-runtime"]
+1 -1
View File
@@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
log = { version = "0.4.17", default-features = false }
codec = { default-features = false, features = ["derive"], package = "parity-scale-codec", version = "3.0.0" }
rand = { version = "0.8.5", features = ["std_rng"], default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.2.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.144", default-features = false }
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" }
@@ -44,9 +44,9 @@ macro_rules! whitelist {
};
}
fn assert_last_event<T: Config>(generic_event: <T as Config>::Event) {
fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
let events = frame_system::Pallet::<T>::events();
let system_event: <T as frame_system::Config>::Event = generic_event.into();
let system_event: <T as frame_system::Config>::RuntimeEvent = generic_event.into();
// compare to the last event record
let EventRecord { event, .. } = &events[events.len() - 1];
assert_eq!(event, &system_event);
+3 -4
View File
@@ -77,7 +77,7 @@ pub mod pallet {
pub use crate::weights::WeightInfo;
use core::ops::Div;
use frame_support::{
dispatch::DispatchResultWithPostInfo,
dispatch::{DispatchClass, DispatchResultWithPostInfo},
inherent::Vec,
pallet_prelude::*,
sp_runtime::{
@@ -88,7 +88,6 @@ pub mod pallet {
Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency,
ValidatorRegistration,
},
weights::DispatchClass,
BoundedVec, PalletId,
};
use frame_system::{pallet_prelude::*, Config as SystemConfig};
@@ -112,13 +111,13 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config {
/// Overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The currency mechanism.
type Currency: ReservableCurrency<Self::AccountId>;
/// Origin that can dictate updating parameters of this pallet.
type UpdateOrigin: EnsureOrigin<Self::Origin>;
type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Account Identifier from which the internal Pot is generated.
type PotId: Get<PalletId>;
+6 -6
View File
@@ -59,8 +59,8 @@ impl system::Config for Test {
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Call = Call;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
@@ -68,7 +68,7 @@ impl system::Config for Test {
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
@@ -88,7 +88,7 @@ parameter_types! {
impl pallet_balances::Config for Test {
type Balance = u64;
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
@@ -171,7 +171,7 @@ parameter_types! {
}
impl pallet_session::Config for Test {
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId;
// we don't have stash and controller, thus we don't need the convert as well.
type ValidatorIdOf = IdentityCollator;
@@ -207,7 +207,7 @@ impl ValidatorRegistration<u64> for IsRegistered {
}
impl Config for Test {
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;
type PotId = PotId;
+37 -31
View File
@@ -38,14 +38,14 @@ fn it_should_set_invulnerables() {
new_test_ext().execute_with(|| {
let new_set = vec![1, 2, 3, 4];
assert_ok!(CollatorSelection::set_invulnerables(
Origin::signed(RootAccount::get()),
RuntimeOrigin::signed(RootAccount::get()),
new_set.clone()
));
assert_eq!(CollatorSelection::invulnerables(), new_set);
// cannot set with non-root.
assert_noop!(
CollatorSelection::set_invulnerables(Origin::signed(1), new_set.clone()),
CollatorSelection::set_invulnerables(RuntimeOrigin::signed(1), new_set.clone()),
BadOrigin
);
@@ -53,7 +53,7 @@ fn it_should_set_invulnerables() {
let invulnerables = vec![7];
assert_noop!(
CollatorSelection::set_invulnerables(
Origin::signed(RootAccount::get()),
RuntimeOrigin::signed(RootAccount::get()),
invulnerables.clone()
),
Error::<Test>::ValidatorNotRegistered
@@ -69,13 +69,16 @@ fn set_desired_candidates_works() {
// can set
assert_ok!(CollatorSelection::set_desired_candidates(
Origin::signed(RootAccount::get()),
RuntimeOrigin::signed(RootAccount::get()),
7
));
assert_eq!(CollatorSelection::desired_candidates(), 7);
// rejects bad origin
assert_noop!(CollatorSelection::set_desired_candidates(Origin::signed(1), 8), BadOrigin);
assert_noop!(
CollatorSelection::set_desired_candidates(RuntimeOrigin::signed(1), 8),
BadOrigin
);
});
}
@@ -86,11 +89,14 @@ fn set_candidacy_bond() {
assert_eq!(CollatorSelection::candidacy_bond(), 10);
// can set
assert_ok!(CollatorSelection::set_candidacy_bond(Origin::signed(RootAccount::get()), 7));
assert_ok!(CollatorSelection::set_candidacy_bond(
RuntimeOrigin::signed(RootAccount::get()),
7
));
assert_eq!(CollatorSelection::candidacy_bond(), 7);
// rejects bad origin.
assert_noop!(CollatorSelection::set_candidacy_bond(Origin::signed(1), 8), BadOrigin);
assert_noop!(CollatorSelection::set_candidacy_bond(RuntimeOrigin::signed(1), 8), BadOrigin);
});
}
@@ -102,17 +108,17 @@ fn cannot_register_candidate_if_too_many() {
// can't accept anyone anymore.
assert_noop!(
CollatorSelection::register_as_candidate(Origin::signed(3)),
CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)),
Error::<Test>::TooManyCandidates,
);
// reset desired candidates:
<crate::DesiredCandidates<Test>>::put(1);
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(4)));
// but no more
assert_noop!(
CollatorSelection::register_as_candidate(Origin::signed(5)),
CollatorSelection::register_as_candidate(RuntimeOrigin::signed(5)),
Error::<Test>::TooManyCandidates,
);
})
@@ -123,11 +129,11 @@ fn cannot_unregister_candidate_if_too_few() {
new_test_ext().execute_with(|| {
// reset desired candidates:
<crate::DesiredCandidates<Test>>::put(1);
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(4)));
// can not remove too few
assert_noop!(
CollatorSelection::leave_intent(Origin::signed(4)),
CollatorSelection::leave_intent(RuntimeOrigin::signed(4)),
Error::<Test>::TooFewCandidates,
);
})
@@ -140,7 +146,7 @@ fn cannot_register_as_candidate_if_invulnerable() {
// can't 1 because it is invulnerable.
assert_noop!(
CollatorSelection::register_as_candidate(Origin::signed(1)),
CollatorSelection::register_as_candidate(RuntimeOrigin::signed(1)),
Error::<Test>::AlreadyInvulnerable,
);
})
@@ -151,7 +157,7 @@ fn cannot_register_as_candidate_if_keys_not_registered() {
new_test_ext().execute_with(|| {
// can't 7 because keys not registered.
assert_noop!(
CollatorSelection::register_as_candidate(Origin::signed(7)),
CollatorSelection::register_as_candidate(RuntimeOrigin::signed(7)),
Error::<Test>::ValidatorNotRegistered
);
})
@@ -161,7 +167,7 @@ fn cannot_register_as_candidate_if_keys_not_registered() {
fn cannot_register_dupe_candidate() {
new_test_ext().execute_with(|| {
// can add 3 as candidate
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
let addition = CandidateInfo { who: 3, deposit: 10 };
assert_eq!(CollatorSelection::candidates(), vec![addition]);
assert_eq!(CollatorSelection::last_authored_block(3), 10);
@@ -169,7 +175,7 @@ fn cannot_register_dupe_candidate() {
// but no more
assert_noop!(
CollatorSelection::register_as_candidate(Origin::signed(3)),
CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)),
Error::<Test>::AlreadyCandidate,
);
})
@@ -182,11 +188,11 @@ fn cannot_register_as_candidate_if_poor() {
assert_eq!(Balances::free_balance(&33), 0);
// works
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
// poor
assert_noop!(
CollatorSelection::register_as_candidate(Origin::signed(33)),
CollatorSelection::register_as_candidate(RuntimeOrigin::signed(33)),
BalancesError::<Test>::InsufficientBalance,
);
});
@@ -205,8 +211,8 @@ fn register_as_candidate_works() {
assert_eq!(Balances::free_balance(&3), 100);
assert_eq!(Balances::free_balance(&4), 100);
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(4)));
assert_eq!(Balances::free_balance(&3), 90);
assert_eq!(Balances::free_balance(&4), 90);
@@ -219,21 +225,21 @@ fn register_as_candidate_works() {
fn leave_intent() {
new_test_ext().execute_with(|| {
// register a candidate.
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
assert_eq!(Balances::free_balance(3), 90);
// register too so can leave above min candidates
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(5)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(5)));
assert_eq!(Balances::free_balance(5), 90);
// cannot leave if not candidate.
assert_noop!(
CollatorSelection::leave_intent(Origin::signed(4)),
CollatorSelection::leave_intent(RuntimeOrigin::signed(4)),
Error::<Test>::NotCandidate
);
// bond is returned
assert_ok!(CollatorSelection::leave_intent(Origin::signed(3)));
assert_ok!(CollatorSelection::leave_intent(RuntimeOrigin::signed(3)));
assert_eq!(Balances::free_balance(3), 100);
assert_eq!(CollatorSelection::last_authored_block(3), 0);
});
@@ -247,7 +253,7 @@ fn authorship_event_handler() {
// 4 is the default author.
assert_eq!(Balances::free_balance(4), 100);
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(4)));
// triggers `note_author`
Authorship::on_initialize(1);
@@ -272,7 +278,7 @@ fn fees_edgecases() {
Balances::make_free_balance_be(&CollatorSelection::account_id(), 5);
// 4 is the default author.
assert_eq!(Balances::free_balance(4), 100);
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(4)));
// triggers `note_author`
Authorship::on_initialize(1);
@@ -301,7 +307,7 @@ fn session_management_works() {
assert_eq!(SessionHandlerCollators::get(), vec![1, 2]);
// add a new collator
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
// session won't see this.
assert_eq!(SessionHandlerCollators::get(), vec![1, 2]);
@@ -328,8 +334,8 @@ fn session_management_works() {
fn kick_mechanism() {
new_test_ext().execute_with(|| {
// add a new collator
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(4)));
initialize_to_block(10);
assert_eq!(CollatorSelection::candidates().len(), 2);
initialize_to_block(20);
@@ -353,8 +359,8 @@ fn kick_mechanism() {
fn should_not_kick_mechanism_too_few() {
new_test_ext().execute_with(|| {
// add a new collator
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(5)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(3)));
assert_ok!(CollatorSelection::register_as_candidate(RuntimeOrigin::signed(5)));
initialize_to_block(10);
assert_eq!(CollatorSelection::candidates().len(), 2);
initialize_to_block(20);
+48 -46
View File
@@ -39,91 +39,93 @@ pub trait WeightInfo {
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
fn set_invulnerables(b: u32) -> Weight {
(18_563_000 as Weight)
Weight::from_ref_time(18_563_000 as u64)
// Standard Error: 0
.saturating_add((68_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
.saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
fn set_desired_candidates() -> Weight {
(16_363_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
Weight::from_ref_time(16_363_000 as u64).saturating_add(T::DbWeight::get().writes(1 as u64))
}
fn set_candidacy_bond() -> Weight {
(16_840_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
Weight::from_ref_time(16_840_000 as u64).saturating_add(T::DbWeight::get().writes(1 as u64))
}
fn register_as_candidate(c: u32) -> Weight {
(71_196_000 as Weight)
Weight::from_ref_time(71_196_000 as u64)
// Standard Error: 0
.saturating_add((198_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64))
.saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(2 as u64))
}
fn leave_intent(c: u32) -> Weight {
(55_336_000 as Weight)
Weight::from_ref_time(55_336_000 as u64)
// Standard Error: 0
.saturating_add((151_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(2 as u64))
}
fn note_author() -> Weight {
(71_461_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
Weight::from_ref_time(71_461_000 as u64)
.saturating_add(T::DbWeight::get().reads(3 as u64))
.saturating_add(T::DbWeight::get().writes(4 as u64))
}
fn new_session(r: u32, c: u32) -> Weight {
(0 as Weight)
Weight::from_ref_time(0 as u64)
// Standard Error: 1_010_000
.saturating_add((109_961_000 as Weight).saturating_mul(r as Weight))
.saturating_add(Weight::from_ref_time(109_961_000 as u64).saturating_mul(r as u64))
// Standard Error: 1_010_000
.saturating_add((151_952_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight)))
.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight)))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(r as Weight)))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight)))
.saturating_add(Weight::from_ref_time(151_952_000 as u64).saturating_mul(c as u64))
.saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(r as u64)))
.saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(c as u64)))
.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(r as u64)))
.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(c as u64)))
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
fn set_invulnerables(b: u32) -> Weight {
(18_563_000 as Weight)
Weight::from_ref_time(18_563_000 as u64)
// Standard Error: 0
.saturating_add((68_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
.saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
fn set_desired_candidates() -> Weight {
(16_363_000 as Weight).saturating_add(RocksDbWeight::get().writes(1 as Weight))
Weight::from_ref_time(16_363_000 as u64)
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
fn set_candidacy_bond() -> Weight {
(16_840_000 as Weight).saturating_add(RocksDbWeight::get().writes(1 as Weight))
Weight::from_ref_time(16_840_000 as u64)
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
fn register_as_candidate(c: u32) -> Weight {
(71_196_000 as Weight)
Weight::from_ref_time(71_196_000 as u64)
// Standard Error: 0
.saturating_add((198_000 as Weight).saturating_mul(c as Weight))
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64))
.saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as u64))
}
fn leave_intent(c: u32) -> Weight {
(55_336_000 as Weight)
Weight::from_ref_time(55_336_000 as u64)
// Standard Error: 0
.saturating_add((151_000 as Weight).saturating_mul(c as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as u64))
}
fn note_author() -> Weight {
(71_461_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
Weight::from_ref_time(71_461_000 as u64)
.saturating_add(RocksDbWeight::get().reads(3 as u64))
.saturating_add(RocksDbWeight::get().writes(4 as u64))
}
fn new_session(r: u32, c: u32) -> Weight {
(0 as Weight)
Weight::from_ref_time(0 as u64)
// Standard Error: 1_010_000
.saturating_add((109_961_000 as Weight).saturating_mul(r as Weight))
.saturating_add(Weight::from_ref_time(109_961_000 as u64).saturating_mul(r as u64))
// Standard Error: 1_010_000
.saturating_add((151_952_000 as Weight).saturating_mul(c as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight)))
.saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight)))
.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(r as Weight)))
.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight)))
.saturating_add(Weight::from_ref_time(151_952_000 as u64).saturating_mul(c as u64))
.saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(r as u64)))
.saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(c as u64)))
.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(r as u64)))
.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(c as u64)))
}
}
+2 -1
View File
@@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ], default-features = false }
log = { version = "0.4.17", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.2.0", default-features = false, features = ["derive"] }
# Substrate
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
@@ -42,3 +42,4 @@ std = [
"xcm/std",
"cumulus-primitives-core/std",
]
try-runtime = ["frame-support/try-runtime"]
+110 -86
View File
@@ -24,7 +24,8 @@
use codec::{Decode, DecodeLimit, Encode};
use cumulus_primitives_core::{relay_chain::BlockNumber as RelayBlockNumber, DmpMessageHandler};
use frame_support::{
dispatch::Weight, traits::EnsureOrigin, weights::constants::WEIGHT_PER_MILLIS,
traits::EnsureOrigin,
weights::{constants::WEIGHT_PER_MILLIS, Weight},
};
pub use pallet::*;
use scale_info::TypeInfo;
@@ -43,7 +44,7 @@ pub struct ConfigData {
impl Default for ConfigData {
fn default() -> Self {
Self {
max_individual: 10 * WEIGHT_PER_MILLIS, // 10 ms of execution time maximum by default
max_individual: 10u64 * WEIGHT_PER_MILLIS, // 10 ms of execution time maximum by default
}
}
}
@@ -84,12 +85,12 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type XcmExecutor: ExecuteXcm<Self::Call>;
type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
/// Origin which is allowed to execute overweight messages.
type ExecuteOverweightOrigin: EnsureOrigin<Self::Origin>;
type ExecuteOverweightOrigin: EnsureOrigin<Self::RuntimeOrigin>;
}
/// The configuration.
@@ -140,7 +141,7 @@ pub mod pallet {
///
/// Events:
/// - `OverweightServiced`: On success.
#[pallet::weight(weight_limit.saturating_add(1_000_000))]
#[pallet::weight(weight_limit.saturating_add(Weight::from_ref_time(1_000_000)))]
pub fn service_overweight(
origin: OriginFor<T>,
index: OverweightIndex,
@@ -153,7 +154,7 @@ pub mod pallet {
.map_err(|_| Error::<T>::OverLimit)?;
Overweight::<T>::remove(index);
Self::deposit_event(Event::OverweightServiced { overweight_index: index, weight_used });
Ok(Some(weight_used.saturating_add(1_000_000)).into())
Ok(Some(weight_used.saturating_add(Weight::from_ref_time(1_000_000))).into())
}
}
@@ -189,7 +190,7 @@ pub mod pallet {
/// Exactly equivalent to `service_queue` but expects a mutable `page_index` to be passed
/// in and any changes stored.
fn do_service_queue(limit: Weight, page_index: &mut PageIndexData) -> Weight {
let mut used = 0;
let mut used = Weight::zero();
while page_index.begin_used < page_index.end_used {
let page = Pages::<T>::take(page_index.begin_used);
for (i, &(sent_at, ref data)) in page.iter().enumerate() {
@@ -224,27 +225,27 @@ pub mod pallet {
mut data: &[u8],
) -> Result<Weight, (MessageId, Weight)> {
let message_id = sp_io::hashing::blake2_256(data);
let maybe_msg = VersionedXcm::<T::Call>::decode_all_with_depth_limit(
let maybe_msg = VersionedXcm::<T::RuntimeCall>::decode_all_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut data,
)
.map(Xcm::<T::Call>::try_from);
.map(Xcm::<T::RuntimeCall>::try_from);
match maybe_msg {
Err(_) => {
Self::deposit_event(Event::InvalidFormat { message_id });
Ok(0)
Ok(Weight::zero())
},
Ok(Err(())) => {
Self::deposit_event(Event::UnsupportedVersion { message_id });
Ok(0)
Ok(Weight::zero())
},
Ok(Ok(x)) => {
let outcome = T::XcmExecutor::execute_xcm(Parent, x, message_id, limit);
let outcome = T::XcmExecutor::execute_xcm(Parent, x, message_id, limit.ref_time());
match outcome {
Outcome::Error(XcmError::WeightLimitReached(required)) =>
Err((message_id, required)),
Err((message_id, Weight::from_ref_time(required))),
outcome => {
let weight_used = outcome.weight_used();
let weight_used = Weight::from_ref_time(outcome.weight_used());
Self::deposit_event(Event::ExecutedDownward { message_id, outcome });
Ok(weight_used)
},
@@ -287,7 +288,7 @@ pub mod pallet {
Err((message_id, required_weight)) =>
// Too much weight required right now.
{
if required_weight > config.max_individual {
if required_weight.any_gt(config.max_individual) {
// overweight - add to overweight queue and continue with
// message execution.
let overweight_index = page_index.overweight_count;
@@ -349,11 +350,11 @@ mod tests {
};
use sp_version::RuntimeVersion;
use std::cell::RefCell;
use xcm::latest::{MultiLocation, OriginKind};
use xcm::latest::{MultiLocation, OriginKind, Weight as XCMWeight};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
type Xcm = xcm::latest::Xcm<Call>;
type Xcm = xcm::latest::Xcm<RuntimeCall>;
frame_support::construct_runtime!(
pub enum Test where
@@ -379,15 +380,15 @@ mod tests {
state_version: 1,
};
pub const ParachainId: ParaId = ParaId::new(200);
pub const ReservedXcmpWeight: Weight = 0;
pub const ReservedDmpWeight: Weight = 0;
pub const ReservedXcmpWeight: Weight = Weight::zero();
pub const ReservedDmpWeight: Weight = Weight::zero();
}
type AccountId = u64;
impl frame_system::Config for Test {
type Origin = Origin;
type Call = Call;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
@@ -395,7 +396,7 @@ mod tests {
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type BlockLength = ();
type BlockWeights = ();
@@ -443,7 +444,7 @@ mod tests {
_origin: impl Into<MultiLocation>,
_: Weightless,
_hash: XcmHash,
_weight_limit: Weight,
_weight_limit: XCMWeight,
) -> Outcome {
unreachable!()
}
@@ -454,7 +455,7 @@ mod tests {
}
impl Config for Test {
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = MockExec;
type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
}
@@ -470,7 +471,7 @@ mod tests {
index.end_used,
enqueued
.iter()
.map(|m| (0, VersionedXcm::<Call>::from(m.clone()).encode()))
.map(|m| (0, VersionedXcm::<RuntimeCall>::from(m.clone()).encode()))
.collect::<Vec<_>>(),
);
index.end_used += 1;
@@ -479,11 +480,13 @@ mod tests {
}
fn handle_messages(incoming: &[Xcm], limit: Weight) -> Weight {
let iter = incoming.iter().map(|m| (0, VersionedXcm::<Call>::from(m.clone()).encode()));
let iter = incoming
.iter()
.map(|m| (0, VersionedXcm::<RuntimeCall>::from(m.clone()).encode()));
DmpQueue::handle_dmp_messages(iter, limit)
}
fn msg(weight: Weight) -> Xcm {
fn msg(weight: XCMWeight) -> Xcm {
Xcm(vec![Transact {
origin_kind: OriginKind::Native,
require_weight_at_most: weight,
@@ -491,11 +494,11 @@ mod tests {
}])
}
fn msg_complete(weight: Weight) -> (Xcm, Outcome) {
fn msg_complete(weight: XCMWeight) -> (Xcm, Outcome) {
(msg(weight), Outcome::Complete(weight))
}
fn msg_limit_reached(weight: Weight) -> (Xcm, Outcome) {
fn msg_limit_reached(weight: XCMWeight) -> (Xcm, Outcome) {
(msg(weight), Outcome::Error(XcmError::WeightLimitReached(weight)))
}
@@ -516,8 +519,8 @@ mod tests {
#[test]
fn basic_setup_works() {
new_test_ext().execute_with(|| {
let weight_used = handle_messages(&[], 1000);
assert_eq!(weight_used, 0);
let weight_used = handle_messages(&[], Weight::from_ref_time(1000));
assert_eq!(weight_used, Weight::zero());
assert_eq!(take_trace(), Vec::new());
assert!(queue_is_empty());
});
@@ -527,8 +530,8 @@ mod tests {
fn service_inline_complete_works() {
new_test_ext().execute_with(|| {
let incoming = vec![msg(1000), msg(1001)];
let weight_used = handle_messages(&incoming, 2500);
assert_eq!(weight_used, 2001);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::from_ref_time(2001));
assert_eq!(take_trace(), vec![msg_complete(1000), msg_complete(1001)]);
assert!(queue_is_empty());
});
@@ -539,8 +542,8 @@ mod tests {
new_test_ext().execute_with(|| {
let enqueued = vec![msg(1000), msg(1001), msg(1002)];
enqueue(&enqueued);
let weight_used = handle_messages(&[], 2500);
assert_eq!(weight_used, 2001);
let weight_used = handle_messages(&[], Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::from_ref_time(2001));
assert_eq!(
take_trace(),
vec![msg_complete(1000), msg_complete(1001), msg_limit_reached(1002),]
@@ -552,8 +555,8 @@ mod tests {
fn enqueue_works() {
new_test_ext().execute_with(|| {
let incoming = vec![msg(1000), msg(1001), msg(1002)];
let weight_used = handle_messages(&incoming, 999);
assert_eq!(weight_used, 0);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(999));
assert_eq!(weight_used, Weight::zero());
assert_eq!(
PageIndex::<Test>::get(),
PageIndexData { begin_used: 0, end_used: 1, overweight_count: 0 }
@@ -561,15 +564,15 @@ mod tests {
assert_eq!(Pages::<Test>::get(0).len(), 3);
assert_eq!(take_trace(), vec![msg_limit_reached(1000)]);
let weight_used = handle_messages(&[], 2500);
assert_eq!(weight_used, 2001);
let weight_used = handle_messages(&[], Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::from_ref_time(2001));
assert_eq!(
take_trace(),
vec![msg_complete(1000), msg_complete(1001), msg_limit_reached(1002),]
);
let weight_used = handle_messages(&[], 2500);
assert_eq!(weight_used, 1002);
let weight_used = handle_messages(&[], Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::from_ref_time(1002));
assert_eq!(take_trace(), vec![msg_complete(1002),]);
assert!(queue_is_empty());
});
@@ -579,14 +582,14 @@ mod tests {
fn service_inline_then_enqueue_works() {
new_test_ext().execute_with(|| {
let incoming = vec![msg(1000), msg(1001), msg(1002)];
let weight_used = handle_messages(&incoming, 1500);
assert_eq!(weight_used, 1000);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(1500));
assert_eq!(weight_used, Weight::from_ref_time(1000));
assert_eq!(pages_queued(), 1);
assert_eq!(Pages::<Test>::get(0).len(), 2);
assert_eq!(take_trace(), vec![msg_complete(1000), msg_limit_reached(1001),]);
let weight_used = handle_messages(&[], 2500);
assert_eq!(weight_used, 2003);
let weight_used = handle_messages(&[], Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::from_ref_time(2003));
assert_eq!(take_trace(), vec![msg_complete(1001), msg_complete(1002),]);
assert!(queue_is_empty());
});
@@ -598,8 +601,8 @@ mod tests {
let enqueued = vec![msg(1000), msg(1001)];
let incoming = vec![msg(1002), msg(1003)];
enqueue(&enqueued);
let weight_used = handle_messages(&incoming, 5000);
assert_eq!(weight_used, 4006);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(5000));
assert_eq!(weight_used, Weight::from_ref_time(4006));
assert_eq!(
take_trace(),
vec![
@@ -619,19 +622,19 @@ mod tests {
let enqueued = vec![msg(1000), msg(10001)];
let incoming = vec![msg(1002), msg(1003)];
enqueue(&enqueued);
let weight_used = handle_messages(&incoming, 5000);
assert_eq!(weight_used, 1000);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(5000));
assert_eq!(weight_used, Weight::from_ref_time(1000));
assert_eq!(take_trace(), vec![msg_complete(1000), msg_limit_reached(10001),]);
assert_eq!(pages_queued(), 2);
// 5000 is not enough to process the 10001 blocker, so nothing happens.
let weight_used = handle_messages(&[], 5000);
assert_eq!(weight_used, 0);
let weight_used = handle_messages(&[], Weight::from_ref_time(5000));
assert_eq!(weight_used, Weight::zero());
assert_eq!(take_trace(), vec![msg_limit_reached(10001),]);
// 20000 is now enough to process everything.
let weight_used = handle_messages(&[], 20000);
assert_eq!(weight_used, 12006);
let weight_used = handle_messages(&[], Weight::from_ref_time(20000));
assert_eq!(weight_used, Weight::from_ref_time(12006));
assert_eq!(
take_trace(),
vec![msg_complete(10001), msg_complete(1002), msg_complete(1003),]
@@ -646,8 +649,8 @@ mod tests {
let enqueued = vec![msg(1000), msg(1001)];
let incoming = vec![msg(10002), msg(1003)];
enqueue(&enqueued);
let weight_used = handle_messages(&incoming, 5000);
assert_eq!(weight_used, 2001);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(5000));
assert_eq!(weight_used, Weight::from_ref_time(2001));
assert_eq!(
take_trace(),
vec![msg_complete(1000), msg_complete(1001), msg_limit_reached(10002),]
@@ -655,8 +658,8 @@ mod tests {
assert_eq!(pages_queued(), 1);
// 20000 is now enough to process everything.
let weight_used = handle_messages(&[], 20000);
assert_eq!(weight_used, 11005);
let weight_used = handle_messages(&[], Weight::from_ref_time(20000));
assert_eq!(weight_used, Weight::from_ref_time(11005));
assert_eq!(take_trace(), vec![msg_complete(10002), msg_complete(1003),]);
assert!(queue_is_empty());
});
@@ -668,8 +671,8 @@ mod tests {
let enqueued = vec![msg(1000), msg(1001)];
let incoming = vec![msg(1002), msg(10003)];
enqueue(&enqueued);
let weight_used = handle_messages(&incoming, 5000);
assert_eq!(weight_used, 3003);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(5000));
assert_eq!(weight_used, Weight::from_ref_time(3003));
assert_eq!(
take_trace(),
vec![
@@ -682,8 +685,8 @@ mod tests {
assert_eq!(pages_queued(), 1);
// 20000 is now enough to process everything.
let weight_used = handle_messages(&[], 20000);
assert_eq!(weight_used, 10003);
let weight_used = handle_messages(&[], Weight::from_ref_time(20000));
assert_eq!(weight_used, Weight::from_ref_time(10003));
assert_eq!(take_trace(), vec![msg_complete(10003),]);
assert!(queue_is_empty());
});
@@ -694,20 +697,20 @@ mod tests {
new_test_ext().execute_with(|| {
let enqueued = vec![msg(1000), msg(1001)];
enqueue(&enqueued);
let weight_used = handle_messages(&vec![msg(1002)], 1500);
assert_eq!(weight_used, 1000);
let weight_used = handle_messages(&vec![msg(1002)], Weight::from_ref_time(1500));
assert_eq!(weight_used, Weight::from_ref_time(1000));
assert_eq!(take_trace(), vec![msg_complete(1000), msg_limit_reached(1001),]);
assert_eq!(pages_queued(), 2);
assert_eq!(PageIndex::<Test>::get().begin_used, 0);
let weight_used = handle_messages(&vec![msg(1003)], 1500);
assert_eq!(weight_used, 1001);
let weight_used = handle_messages(&vec![msg(1003)], Weight::from_ref_time(1500));
assert_eq!(weight_used, Weight::from_ref_time(1001));
assert_eq!(take_trace(), vec![msg_complete(1001), msg_limit_reached(1002),]);
assert_eq!(pages_queued(), 2);
assert_eq!(PageIndex::<Test>::get().begin_used, 1);
let weight_used = handle_messages(&vec![msg(1004)], 1500);
assert_eq!(weight_used, 1002);
let weight_used = handle_messages(&vec![msg(1004)], Weight::from_ref_time(1500));
assert_eq!(weight_used, Weight::from_ref_time(1002));
assert_eq!(take_trace(), vec![msg_complete(1002), msg_limit_reached(1003),]);
assert_eq!(pages_queued(), 2);
assert_eq!(PageIndex::<Test>::get().begin_used, 2);
@@ -718,11 +721,11 @@ mod tests {
fn overweight_should_not_block_queue() {
new_test_ext().execute_with(|| {
// Set the overweight threshold to 9999.
Configuration::<Test>::put(ConfigData { max_individual: 9999 });
Configuration::<Test>::put(ConfigData { max_individual: Weight::from_ref_time(9999) });
let incoming = vec![msg(1000), msg(10001), msg(1002)];
let weight_used = handle_messages(&incoming, 2500);
assert_eq!(weight_used, 2002);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::from_ref_time(2002));
assert!(queue_is_empty());
assert_eq!(
take_trace(),
@@ -737,37 +740,58 @@ mod tests {
fn overweights_should_be_manually_executable() {
new_test_ext().execute_with(|| {
// Set the overweight threshold to 9999.
Configuration::<Test>::put(ConfigData { max_individual: 9999 });
Configuration::<Test>::put(ConfigData { max_individual: Weight::from_ref_time(9999) });
let incoming = vec![msg(10000)];
let weight_used = handle_messages(&incoming, 2500);
assert_eq!(weight_used, 0);
let weight_used = handle_messages(&incoming, Weight::from_ref_time(2500));
assert_eq!(weight_used, Weight::zero());
assert_eq!(take_trace(), vec![msg_limit_reached(10000)]);
assert_eq!(overweights(), vec![0]);
assert_noop!(DmpQueue::service_overweight(Origin::signed(1), 0, 20000), BadOrigin);
assert_noop!(
DmpQueue::service_overweight(Origin::root(), 1, 20000),
DmpQueue::service_overweight(
RuntimeOrigin::signed(1),
0,
Weight::from_ref_time(20000)
),
BadOrigin
);
assert_noop!(
DmpQueue::service_overweight(
RuntimeOrigin::root(),
1,
Weight::from_ref_time(20000)
),
Error::<Test>::Unknown
);
assert_noop!(
DmpQueue::service_overweight(Origin::root(), 0, 9999),
DmpQueue::service_overweight(RuntimeOrigin::root(), 0, Weight::from_ref_time(9999)),
Error::<Test>::OverLimit
);
assert_eq!(take_trace(), vec![msg_limit_reached(10000)]);
let base_weight = super::Call::<Test>::service_overweight { index: 0, weight_limit: 0 }
.get_dispatch_info()
.weight;
use frame_support::weights::GetDispatchInfo;
let info = DmpQueue::service_overweight(Origin::root(), 0, 20000).unwrap();
let base_weight =
super::Call::<Test>::service_overweight { index: 0, weight_limit: Weight::zero() }
.get_dispatch_info()
.weight;
use frame_support::dispatch::GetDispatchInfo;
let info = DmpQueue::service_overweight(
RuntimeOrigin::root(),
0,
Weight::from_ref_time(20000),
)
.unwrap();
let actual_weight = info.actual_weight.unwrap();
assert_eq!(actual_weight, base_weight + 10000);
assert_eq!(actual_weight, base_weight + Weight::from_ref_time(10000));
assert_eq!(take_trace(), vec![msg_complete(10000)]);
assert!(overweights().is_empty());
assert_noop!(
DmpQueue::service_overweight(Origin::root(), 0, 20000),
DmpQueue::service_overweight(
RuntimeOrigin::root(),
0,
Weight::from_ref_time(20000)
),
Error::<Test>::Unknown
);
});
@@ -780,8 +804,8 @@ mod tests {
enqueue(&vec![msg(1002), msg(1003)]);
enqueue(&vec![msg(1004), msg(1005)]);
let weight_used = DmpQueue::on_idle(1, 6000);
assert_eq!(weight_used, 5010);
let weight_used = DmpQueue::on_idle(1, Weight::from_ref_time(6000));
assert_eq!(weight_used, Weight::from_ref_time(5010));
assert_eq!(
take_trace(),
vec![
+3 -1
View File
@@ -11,7 +11,7 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features =
environmental = { version = "1.1.2", default-features = false }
impl-trait-for-tuples = "0.2.1"
log = { version = "0.4.17", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.2.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.144", optional = true, features = ["derive"] }
# Substrate
@@ -78,3 +78,5 @@ std = [
runtime-benchmarks = [
"sp-runtime/runtime-benchmarks"
]
try-runtime = ["frame-support/try-runtime"]
+6 -6
View File
@@ -36,12 +36,12 @@ use cumulus_primitives_core::{
};
use cumulus_primitives_parachain_inherent::{MessageQueueChain, ParachainInherentData};
use frame_support::{
dispatch::{DispatchError, DispatchResult},
dispatch::{DispatchError, DispatchResult, Pays, PostDispatchInfo},
ensure,
inherent::{InherentData, InherentIdentifier, ProvideInherent},
storage,
traits::Get,
weights::{Pays, PostDispatchInfo, Weight},
weights::Weight,
};
use frame_system::{ensure_none, ensure_root};
use polkadot_parachain::primitives::RelayChainBlockNumber;
@@ -147,7 +147,7 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config<OnSetCode = ParachainSetCode<Self>> {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Something which can be notified when the validation data is set.
type OnSystemEvent: OnSystemEvent;
@@ -269,7 +269,7 @@ pub mod pallet {
}
fn on_initialize(_n: T::BlockNumber) -> Weight {
let mut weight = 0;
let mut weight = Weight::zero();
// To prevent removing `NewValidationCode` that was set by another `on_initialize`
// like for example from scheduler, we only kill the storage entry if it was not yet
@@ -416,7 +416,7 @@ pub mod pallet {
<T::OnSystemEvent as OnSystemEvent>::on_validation_data(&vfp);
// TODO: This is more than zero, but will need benchmarking to figure out what.
let mut total_weight = 0;
let mut total_weight = Weight::zero();
total_weight += Self::process_inbound_downward_messages(
relevant_messaging_state.dmq_mqc_head,
downward_messages,
@@ -808,7 +808,7 @@ impl<T: Config> Pallet<T> {
let dm_count = downward_messages.len() as u32;
let mut dmq_head = <LastDmqMqcHead<T>>::get();
let mut weight_used = 0;
let mut weight_used = Weight::zero();
if dm_count != 0 {
Self::deposit_event(Event::DownwardMessagesReceived { count: dm_count });
let max_weight =
+1 -1
View File
@@ -25,7 +25,7 @@ pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
/// Call this during the next runtime upgrade for this module.
pub fn on_runtime_upgrade<T: Config>() -> Weight {
let mut weight: Weight = 0;
let mut weight: Weight = Weight::zero();
if StorageVersion::get::<Pallet<T>>() == 0 {
weight = weight
+11 -11
View File
@@ -69,12 +69,12 @@ parameter_types! {
state_version: 1,
};
pub const ParachainId: ParaId = ParaId::new(200);
pub const ReservedXcmpWeight: Weight = 0;
pub const ReservedDmpWeight: Weight = 0;
pub const ReservedXcmpWeight: Weight = Weight::zero();
pub const ReservedDmpWeight: Weight = Weight::zero();
}
impl frame_system::Config for Test {
type Origin = Origin;
type Call = Call;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
@@ -82,7 +82,7 @@ impl frame_system::Config for Test {
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type BlockLength = ();
type BlockWeights = ();
@@ -99,7 +99,7 @@ impl frame_system::Config for Test {
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
impl Config for Test {
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type SelfParaId = ParachainId;
type OutboundXcmpMessageSource = FromThreadLocal;
@@ -155,7 +155,7 @@ impl DmpMessageHandler for SaveIntoThreadLocal {
for i in iter {
m.borrow_mut().push(i);
}
0
Weight::zero()
})
}
}
@@ -169,7 +169,7 @@ impl XcmpMessageHandler for SaveIntoThreadLocal {
for (sender, sent_at, message) in iter {
m.borrow_mut().push((sender, sent_at, message.to_vec()));
}
0
Weight::zero()
})
}
}
@@ -403,7 +403,7 @@ fn events() {
let events = System::events();
assert_eq!(
events[0].event,
Event::ParachainSystem(crate::Event::ValidationFunctionStored.into())
RuntimeEvent::ParachainSystem(crate::Event::ValidationFunctionStored.into())
);
},
)
@@ -414,7 +414,7 @@ fn events() {
let events = System::events();
assert_eq!(
events[0].event,
Event::ParachainSystem(
RuntimeEvent::ParachainSystem(
crate::Event::ValidationFunctionApplied { relay_chain_block_num: 1234 }
.into()
)
@@ -490,7 +490,7 @@ fn aborted_upgrade() {
let events = System::events();
assert_eq!(
events[0].event,
Event::ParachainSystem(crate::Event::ValidationFunctionDiscarded.into())
RuntimeEvent::ParachainSystem(crate::Event::ValidationFunctionDiscarded.into())
);
},
);
@@ -118,6 +118,11 @@ where
let inherent_data = block
.extrinsics()
.iter()
// Inherents are at the front of the block and are unsigned.
//
// If `is_signed` is returning `None`, we keep it safe and assume that it is "signed".
// We are searching for unsigned transactions anyway.
.take_while(|e| !e.is_signed().unwrap_or(true))
.filter_map(|e| e.call().is_sub_type())
.find_map(|c| match c {
crate::Call::set_validation_data { data: validation_data } =>
@@ -251,3 +251,40 @@ fn check_inherent_fails_on_validate_block_as_expected() {
);
}
}
#[test]
fn check_inherents_are_unsigned_and_before_all_other_extrinsics() {
sp_tracing::try_init_simple();
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::new(), parent_head.clone(), Default::default());
let (header, mut extrinsics, proof) = block.deconstruct();
extrinsics.insert(0, transfer(&client, Alice, Bob, 69));
call_validate_block(
parent_head,
ParachainBlockData::new(header, extrinsics, proof),
validation_data.relay_parent_storage_root,
)
.unwrap_err();
} else {
let output = Command::new(env::current_exe().unwrap())
.args(&[
"check_inherents_are_unsigned_and_before_all_other_extrinsics",
"--",
"--nocapture",
])
.env("RUN_TEST", "1")
.output()
.expect("Runs the test");
assert!(output.status.success());
assert!(String::from_utf8(output.stderr).unwrap()
.contains("Could not find `set_validation_data` inherent"));
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
parity-scale-codec = { version = "3.1.5", default-features = false }
parity-scale-codec = { version = "3.2.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" }
+1
View File
@@ -37,3 +37,4 @@ std = [
"sp-runtime/std",
"sp-std/std",
]
try-runtime = ["frame-support/try-runtime"]
+8 -5
View File
@@ -18,7 +18,10 @@
use codec::{Decode, Encode};
use cumulus_pallet_parachain_system as parachain_system;
use frame_support::{dispatch::DispatchResult, pallet_prelude::*, weights::DispatchInfo};
use frame_support::{
dispatch::{DispatchInfo, DispatchResult},
pallet_prelude::*,
};
use frame_system::pallet_prelude::*;
pub use pallet::*;
use polkadot_primitives::v2::PersistedValidationData;
@@ -40,7 +43,7 @@ pub mod pallet {
pub trait Config:
frame_system::Config + parachain_system::Config + pallet_sudo::Config
{
type Event: From<Event> + IsType<<Self as frame_system::Config>::Event>;
type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::pallet]
@@ -133,10 +136,10 @@ pub mod pallet {
impl<T: Config + Send + Sync> SignedExtension for CheckSudo<T>
where
<T as frame_system::Config>::Call: Dispatchable<Info = DispatchInfo>,
<T as frame_system::Config>::RuntimeCall: Dispatchable<Info = DispatchInfo>,
{
type AccountId = T::AccountId;
type Call = <T as frame_system::Config>::Call;
type Call = <T as frame_system::Config>::RuntimeCall;
type AdditionalSigned = ();
type Pre = ();
const IDENTIFIER: &'static str = "CheckSudo";
@@ -169,7 +172,7 @@ pub mod pallet {
if *who == root_account {
Ok(ValidTransaction {
priority: info.weight as TransactionPriority,
priority: info.weight.ref_time() as TransactionPriority,
longevity: TransactionLongevity::max_value(),
propagate: true,
..Default::default()
+2 -1
View File
@@ -6,7 +6,7 @@ version = "0.1.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.2.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.144", optional = true, features = ["derive"] }
sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
@@ -31,3 +31,4 @@ std = [
"frame-support/std",
"frame-system/std",
]
try-runtime = ["frame-support/try-runtime"]
+12 -12
View File
@@ -48,9 +48,9 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type XcmExecutor: ExecuteXcm<Self::Call>;
type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
}
#[pallet::error]
@@ -111,20 +111,20 @@ impl<T: Config> DmpMessageHandler for UnlimitedDmpExecution<T> {
iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
limit: Weight,
) -> Weight {
let mut used = 0;
let mut used = Weight::zero();
for (_sent_at, data) in iter {
let id = sp_io::hashing::blake2_256(&data[..]);
let msg = VersionedXcm::<T::Call>::decode_all_with_depth_limit(
let msg = VersionedXcm::<T::RuntimeCall>::decode_all_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut data.as_slice(),
)
.map(Xcm::<T::Call>::try_from);
.map(Xcm::<T::RuntimeCall>::try_from);
match msg {
Err(_) => Pallet::<T>::deposit_event(Event::InvalidFormat(id)),
Ok(Err(())) => Pallet::<T>::deposit_event(Event::UnsupportedVersion(id)),
Ok(Ok(x)) => {
let outcome = T::XcmExecutor::execute_xcm(Parent, x, id, limit);
used += outcome.weight_used();
let outcome = T::XcmExecutor::execute_xcm(Parent, x, id, limit.ref_time());
used += Weight::from_ref_time(outcome.weight_used());
Pallet::<T>::deposit_event(Event::ExecutedDownward(id, outcome));
},
}
@@ -144,21 +144,21 @@ impl<T: Config> DmpMessageHandler for LimitAndDropDmpExecution<T> {
iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
limit: Weight,
) -> Weight {
let mut used = 0;
let mut used = Weight::zero();
for (_sent_at, data) in iter {
let id = sp_io::hashing::blake2_256(&data[..]);
let msg = VersionedXcm::<T::Call>::decode_all_with_depth_limit(
let msg = VersionedXcm::<T::RuntimeCall>::decode_all_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut data.as_slice(),
)
.map(Xcm::<T::Call>::try_from);
.map(Xcm::<T::RuntimeCall>::try_from);
match msg {
Err(_) => Pallet::<T>::deposit_event(Event::InvalidFormat(id)),
Ok(Err(())) => Pallet::<T>::deposit_event(Event::UnsupportedVersion(id)),
Ok(Ok(x)) => {
let weight_limit = limit.saturating_sub(used);
let outcome = T::XcmExecutor::execute_xcm(Parent, x, id, weight_limit);
used += outcome.weight_used();
let outcome = T::XcmExecutor::execute_xcm(Parent, x, id, weight_limit.ref_time());
used += Weight::from_ref_time(outcome.weight_used());
Pallet::<T>::deposit_event(Event::ExecutedDownward(id, outcome));
},
}
+2 -1
View File
@@ -8,7 +8,7 @@ edition = "2021"
codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ], default-features = false }
log = { version = "0.4.17", default-features = false }
rand_chacha = { version = "0.3.0", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
scale-info = { version = "2.2.0", default-features = false, features = ["derive"] }
# Substrate
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
@@ -62,3 +62,4 @@ runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
]
try-runtime = ["frame-support/try-runtime"]
+1 -1
View File
@@ -22,7 +22,7 @@ use frame_system::RawOrigin;
benchmarks! {
set_config_with_u32 {}: update_resume_threshold(RawOrigin::Root, 100)
set_config_with_weight {}: update_weight_restrict_decay(RawOrigin::Root, 3_000_000 as Weight)
set_config_with_weight {}: update_weight_restrict_decay(RawOrigin::Root, Weight::from_ref_time(3_000_000))
}
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test);
+51 -34
View File
@@ -79,10 +79,10 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Something to execute an XCM message. We need this to service the XCMoXCMP queue.
type XcmExecutor: ExecuteXcm<Self::Call>;
type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
/// Information on the avaialble XCMP channels.
type ChannelInfo: GetChannelInfo;
@@ -91,14 +91,14 @@ pub mod pallet {
type VersionWrapper: WrapVersion;
/// The origin that is allowed to execute overweight messages.
type ExecuteOverweightOrigin: EnsureOrigin<Self::Origin>;
type ExecuteOverweightOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin that is allowed to resume or suspend the XCMP queue.
type ControllerOrigin: EnsureOrigin<Self::Origin>;
type ControllerOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The conversion function used to attempt to convert an XCM `MultiLocation` origin to a
/// superuser origin.
type ControllerOriginConverter: ConvertOrigin<Self::Origin>;
type ControllerOriginConverter: ConvertOrigin<Self::RuntimeOrigin>;
/// The price for delivering an XCM to a sibling parachain destination.
type PriceForSiblingDelivery: PriceForSiblingDelivery;
@@ -134,7 +134,7 @@ pub mod pallet {
///
/// Events:
/// - `OverweightServiced`: On success.
#[pallet::weight((weight_limit.saturating_add(1_000_000), DispatchClass::Operational,))]
#[pallet::weight((weight_limit.saturating_add(Weight::from_ref_time(1_000_000)), DispatchClass::Operational,))]
pub fn service_overweight(
origin: OriginFor<T>,
index: OverweightIndex,
@@ -144,7 +144,7 @@ pub mod pallet {
let (sender, sent_at, data) =
Overweight::<T>::get(index).ok_or(Error::<T>::BadOverweightIndex)?;
let xcm = VersionedXcm::<T::Call>::decode_all_with_depth_limit(
let xcm = VersionedXcm::<T::RuntimeCall>::decode_all_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut data.as_slice(),
)
@@ -153,7 +153,7 @@ pub mod pallet {
.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())
Ok(Some(used.saturating_add(Weight::from_ref_time(1_000_000))).into())
}
/// Suspends all XCM executions for the XCMP queue, regardless of the sender's origin.
@@ -453,9 +453,9 @@ impl Default for QueueConfigData {
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,
threshold_weight: Weight::from_ref_time(100_000),
weight_restrict_decay: Weight::from_ref_time(2),
xcmp_max_individual_weight: 20u64 * WEIGHT_PER_MILLIS,
}
}
}
@@ -600,24 +600,37 @@ impl<T: Config> Pallet<T> {
fn handle_xcm_message(
sender: ParaId,
_sent_at: RelayBlockNumber,
xcm: VersionedXcm<T::Call>,
xcm: VersionedXcm<T::RuntimeCall>,
max_weight: Weight,
) -> Result<Weight, XcmError> {
let hash = xcm.using_encoded(sp_io::hashing::blake2_256);
log::debug!("Processing XCMP-XCM: {:?}", &hash);
let (result, event) = match Xcm::<T::Call>::try_from(xcm) {
let (result, event) = match Xcm::<T::RuntimeCall>::try_from(xcm) {
Ok(xcm) => {
let location = (Parent, Parachain(sender.into()));
match T::XcmExecutor::execute_xcm(location, xcm, hash, max_weight) {
Outcome::Error(e) =>
(Err(e), Event::Fail { message_hash: Some(hash), error: e, weight: 0 }),
Outcome::Complete(w) =>
(Ok(w), Event::Success { message_hash: Some(hash), weight: w }),
match T::XcmExecutor::execute_xcm(location, xcm, hash, max_weight.ref_time()) {
Outcome::Error(e) => (
Err(e),
Event::Fail { message_hash: Some(hash), error: e, weight: Weight::zero() },
),
Outcome::Complete(w) => (
Ok(Weight::from_ref_time(w)),
Event::Success {
message_hash: Some(hash),
weight: Weight::from_ref_time(w),
},
),
// As far as the caller is concerned, this was dispatched without error, so
// we just report the weight used.
Outcome::Incomplete(w, e) =>
(Ok(w), Event::Fail { message_hash: Some(hash), error: e, weight: w }),
Outcome::Incomplete(w, e) => (
Ok(Weight::from_ref_time(w)),
Event::Fail {
message_hash: Some(hash),
error: e,
weight: Weight::from_ref_time(w),
},
),
}
},
Err(()) =>
@@ -636,12 +649,12 @@ impl<T: Config> Pallet<T> {
let data = <InboundXcmpMessages<T>>::get(sender, sent_at);
let mut last_remaining_fragments;
let mut remaining_fragments = &data[..];
let mut weight_used = 0;
let mut weight_used = Weight::zero();
match format {
XcmpMessageFormat::ConcatenatedVersionedXcm => {
while !remaining_fragments.is_empty() {
last_remaining_fragments = remaining_fragments;
if let Ok(xcm) = VersionedXcm::<T::Call>::decode_with_depth_limit(
if let Ok(xcm) = VersionedXcm::<T::RuntimeCall>::decode_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut remaining_fragments,
) {
@@ -649,7 +662,7 @@ impl<T: Config> Pallet<T> {
match Self::handle_xcm_message(sender, sent_at, xcm, weight) {
Ok(used) => weight_used = weight_used.saturating_add(used),
Err(XcmError::WeightLimitReached(required))
if required > max_individual_weight =>
if required > max_individual_weight.ref_time() =>
{
// overweight - add to overweight queue and continue with message
// execution consuming the message.
@@ -658,12 +671,16 @@ impl<T: Config> Pallet<T> {
.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 };
let e = Event::OverweightEnqueued {
sender,
sent_at,
index,
required: Weight::from_ref_time(required),
};
Self::deposit_event(e);
},
Err(XcmError::WeightLimitReached(required))
if required <= max_weight =>
if required <= max_weight.ref_time() =>
{
// That message didn't get processed this time because of being
// too heavy. We leave it around for next time and bail.
@@ -770,7 +787,7 @@ impl<T: Config> Pallet<T> {
let mut status = <InboundXcmpStatus<T>>::get(); // <- sorted.
if status.is_empty() {
return 0
return Weight::zero()
}
let QueueConfigData {
@@ -782,8 +799,8 @@ impl<T: Config> Pallet<T> {
} = <QueueConfig<T>>::get();
let mut shuffled = Self::create_shuffle(status.len());
let mut weight_used = 0;
let mut weight_available = 0;
let mut weight_used = Weight::zero();
let mut weight_available = Weight::zero();
// We don't want the possibility of a chain sending a series of really heavy messages and
// tying up the block's execution time from other chains. Therefore we execute any remaining
@@ -795,7 +812,7 @@ impl<T: Config> Pallet<T> {
let mut shuffle_index = 0;
while shuffle_index < shuffled.len() &&
max_weight.saturating_sub(weight_used) >= threshold_weight
max_weight.saturating_sub(weight_used).all_gte(threshold_weight)
{
let index = shuffled[shuffle_index];
let sender = status[index].sender;
@@ -817,8 +834,8 @@ impl<T: Config> Pallet<T> {
// on the first round to unlocking everything, then we do so.
if shuffle_index < status.len() {
weight_available +=
(max_weight - weight_available) / (weight_restrict_decay + 1);
if weight_available + threshold_weight > max_weight {
(max_weight - weight_available) / (weight_restrict_decay.ref_time() + 1);
if (weight_available + threshold_weight).any_gt(max_weight) {
weight_available = max_weight;
}
} else {
@@ -828,7 +845,7 @@ impl<T: Config> Pallet<T> {
let weight_processed = if status[index].message_metadata.is_empty() {
debug_assert!(false, "channel exists in status; there must be messages; qed");
0
Weight::zero()
} else {
// Process up to one block's worth for now.
let weight_remaining = weight_available.saturating_sub(weight_used);
@@ -858,7 +875,7 @@ impl<T: Config> Pallet<T> {
// 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].message_metadata.is_empty() &&
(weight_processed > 0 || weight_available != max_weight)
(weight_processed.any_gt(Weight::zero()) || weight_available != max_weight)
{
if shuffle_index + 1 == shuffled.len() {
// Only this queue left. Just run around this loop once more.
+6 -6
View File
@@ -25,7 +25,7 @@ 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;
let mut weight = Weight::zero();
if StorageVersion::get::<Pallet<T>>() == 0 {
weight += migrate_to_v1::<T>();
@@ -54,8 +54,8 @@ mod v0 {
suspend_threshold: 2,
drop_threshold: 5,
resume_threshold: 1,
threshold_weight: 100_000,
weight_restrict_decay: 2,
threshold_weight: Weight::from_ref_time(100_000),
weight_restrict_decay: Weight::from_ref_time(2),
}
}
}
@@ -102,8 +102,8 @@ mod tests {
suspend_threshold: 5,
drop_threshold: 12,
resume_threshold: 3,
threshold_weight: 333_333,
weight_restrict_decay: 1,
threshold_weight: Weight::from_ref_time(333_333),
weight_restrict_decay: Weight::from_ref_time(1),
};
new_test_ext().execute_with(|| {
@@ -122,7 +122,7 @@ mod tests {
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);
assert_eq!(v1.xcmp_max_individual_weight, Weight::from_ref_time(20_000_000_000));
});
}
}
+16 -14
View File
@@ -63,8 +63,8 @@ impl frame_system::Config for Test {
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Call = Call;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
@@ -72,7 +72,7 @@ impl frame_system::Config for Test {
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
@@ -92,7 +92,7 @@ parameter_types! {
impl pallet_balances::Config for Test {
type Balance = u64;
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
@@ -103,7 +103,7 @@ impl pallet_balances::Config for Test {
}
impl cumulus_pallet_parachain_system::Config for Test {
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type SelfParaId = ();
type OutboundXcmpMessageSource = XcmpQueue;
@@ -117,7 +117,7 @@ impl cumulus_pallet_parachain_system::Config for Test {
parameter_types! {
pub const RelayChain: MultiLocation = MultiLocation::parent();
pub UniversalLocation: InteriorMultiLocation = X1(Parachain(1u32.into())).into();
pub UnitWeightCost: Weight = 1_000_000;
pub UnitWeightCost: u64 = 1_000_000;
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
}
@@ -140,7 +140,7 @@ pub type LocationToAccountId = (ParentIsPreset<AccountId>,);
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type Call = Call;
type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter;
// How to withdraw and deposit an asset.
type AssetTransactor = LocalAssetTransactor;
@@ -149,7 +149,7 @@ impl xcm_executor::Config for XcmConfig {
type IsTeleporter = NativeAsset;
type UniversalLocation = UniversalLocation;
type Barrier = ();
type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type Trader = ();
type ResponseHandler = ();
type AssetTrap = ();
@@ -170,12 +170,14 @@ pub type XcmRouter = (
XcmpQueue,
);
pub struct SystemParachainAsSuperuser<Origin>(PhantomData<Origin>);
impl<Origin: OriginTrait> ConvertOrigin<Origin> for SystemParachainAsSuperuser<Origin> {
pub struct SystemParachainAsSuperuser<RuntimeOrigin>(PhantomData<RuntimeOrigin>);
impl<RuntimeOrigin: OriginTrait> ConvertOrigin<RuntimeOrigin>
for SystemParachainAsSuperuser<RuntimeOrigin>
{
fn convert_origin(
origin: impl Into<MultiLocation>,
kind: OriginKind,
) -> Result<Origin, MultiLocation> {
) -> Result<RuntimeOrigin, MultiLocation> {
let origin = origin.into();
if kind == OriginKind::Superuser &&
matches!(
@@ -185,7 +187,7 @@ impl<Origin: OriginTrait> ConvertOrigin<Origin> for SystemParachainAsSuperuser<O
interior: X1(Parachain(id)),
} if ParaId::from(id).is_system(),
) {
Ok(Origin::root())
Ok(RuntimeOrigin::root())
} else {
Err(origin)
}
@@ -193,13 +195,13 @@ impl<Origin: OriginTrait> ConvertOrigin<Origin> for SystemParachainAsSuperuser<O
}
impl Config for Test {
type Event = Event;
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
type ChannelInfo = ParachainSystem;
type VersionWrapper = ();
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = SystemParachainAsSuperuser<Origin>;
type ControllerOriginConverter = SystemParachainAsSuperuser<RuntimeOrigin>;
type WeightInfo = ();
type PriceForSiblingDelivery = ();
}
+70 -29
View File
@@ -16,7 +16,7 @@
use super::*;
use cumulus_primitives_core::XcmpMessageHandler;
use frame_support::{assert_noop, assert_ok};
use mock::{new_test_ext, Call, Origin, Test, XcmpQueue};
use mock::{new_test_ext, RuntimeCall, RuntimeOrigin, Test, XcmpQueue};
use sp_runtime::traits::BadOrigin;
#[test]
@@ -26,7 +26,7 @@ fn one_message_does_not_panic() {
let messages = vec![(Default::default(), 1u32.into(), message_format.as_slice())];
// This shouldn't cause a panic
XcmpQueue::handle_xcmp_messages(messages.into_iter(), Weight::max_value());
XcmpQueue::handle_xcmp_messages(messages.into_iter(), Weight::MAX);
})
}
@@ -43,7 +43,12 @@ 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, 10_000_000_000);
XcmpQueue::process_xcmp_message(
1000.into(),
(1, format),
Weight::from_ref_time(10_000_000_000),
Weight::from_ref_time(10_000_000_000),
);
});
}
@@ -61,7 +66,12 @@ fn handle_blob_message() {
];
InboundXcmpMessages::<Test>::insert(ParaId::from(1000), 1, bad_data);
let format = XcmpMessageFormat::ConcatenatedEncodedBlob;
XcmpQueue::process_xcmp_message(1000.into(), (1, format), 10_000_000_000, 10_000_000_000);
XcmpQueue::process_xcmp_message(
1000.into(),
(1, format),
Weight::from_ref_time(10_000_000_000),
Weight::from_ref_time(10_000_000_000),
);
});
}
@@ -73,7 +83,12 @@ fn handle_invalid_data() {
let data = Xcm::<Test>(vec![]).encode();
InboundXcmpMessages::<Test>::insert(ParaId::from(1000), 1, data);
let format = XcmpMessageFormat::ConcatenatedVersionedXcm;
XcmpQueue::process_xcmp_message(1000.into(), (1, format), 10_000_000_000, 10_000_000_000);
XcmpQueue::process_xcmp_message(
1000.into(),
(1, format),
Weight::from_ref_time(10_000_000_000),
Weight::from_ref_time(10_000_000_000),
);
});
}
@@ -81,7 +96,7 @@ fn handle_invalid_data() {
fn service_overweight_unknown() {
new_test_ext().execute_with(|| {
assert_noop!(
XcmpQueue::service_overweight(Origin::root(), 0, 1000),
XcmpQueue::service_overweight(RuntimeOrigin::root(), 0, Weight::from_ref_time(1000)),
Error::<Test>::BadOverweightIndex,
);
});
@@ -93,7 +108,10 @@ fn service_overweight_bad_xcm_format() {
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);
assert_noop!(
XcmpQueue::service_overweight(RuntimeOrigin::root(), 0, Weight::from_ref_time(1000)),
Error::<Test>::BadXcm
);
});
}
@@ -102,13 +120,15 @@ fn suspend_xcm_execution_works() {
new_test_ext().execute_with(|| {
QueueSuspended::<Test>::put(true);
let xcm = VersionedXcm::from(Xcm::<Call>(vec![Instruction::<Call>::ClearOrigin])).encode();
let xcm =
VersionedXcm::from(Xcm::<RuntimeCall>(vec![Instruction::<RuntimeCall>::ClearOrigin]))
.encode();
let mut message_format = XcmpMessageFormat::ConcatenatedVersionedXcm.encode();
message_format.extend(xcm.clone());
let messages = vec![(ParaId::from(999), 1u32.into(), message_format.as_slice())];
// This should have executed the incoming XCM, because it came from a system parachain
XcmpQueue::handle_xcmp_messages(messages.into_iter(), Weight::max_value());
XcmpQueue::handle_xcmp_messages(messages.into_iter(), Weight::MAX);
let queued_xcm = InboundXcmpMessages::<Test>::get(ParaId::from(999), 1u32);
assert!(queued_xcm.is_empty());
@@ -116,7 +136,7 @@ fn suspend_xcm_execution_works() {
let messages = vec![(ParaId::from(2000), 1u32.into(), message_format.as_slice())];
// This shouldn't have executed the incoming XCM
XcmpQueue::handle_xcmp_messages(messages.into_iter(), Weight::max_value());
XcmpQueue::handle_xcmp_messages(messages.into_iter(), Weight::MAX);
let queued_xcm = InboundXcmpMessages::<Test>::get(ParaId::from(2000), 1u32);
assert_eq!(queued_xcm, xcm);
@@ -128,8 +148,8 @@ fn update_suspend_threshold_works() {
new_test_ext().execute_with(|| {
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.suspend_threshold, 2);
assert_ok!(XcmpQueue::update_suspend_threshold(Origin::root(), 3));
assert_noop!(XcmpQueue::update_suspend_threshold(Origin::signed(2), 5), BadOrigin);
assert_ok!(XcmpQueue::update_suspend_threshold(RuntimeOrigin::root(), 3));
assert_noop!(XcmpQueue::update_suspend_threshold(RuntimeOrigin::signed(2), 5), BadOrigin);
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.suspend_threshold, 3);
@@ -141,8 +161,8 @@ fn update_drop_threshold_works() {
new_test_ext().execute_with(|| {
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.drop_threshold, 5);
assert_ok!(XcmpQueue::update_drop_threshold(Origin::root(), 6));
assert_noop!(XcmpQueue::update_drop_threshold(Origin::signed(2), 7), BadOrigin);
assert_ok!(XcmpQueue::update_drop_threshold(RuntimeOrigin::root(), 6));
assert_noop!(XcmpQueue::update_drop_threshold(RuntimeOrigin::signed(2), 7), BadOrigin);
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.drop_threshold, 6);
@@ -154,8 +174,8 @@ fn update_resume_threshold_works() {
new_test_ext().execute_with(|| {
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.resume_threshold, 1);
assert_ok!(XcmpQueue::update_resume_threshold(Origin::root(), 2));
assert_noop!(XcmpQueue::update_resume_threshold(Origin::signed(7), 3), BadOrigin);
assert_ok!(XcmpQueue::update_resume_threshold(RuntimeOrigin::root(), 2));
assert_noop!(XcmpQueue::update_resume_threshold(RuntimeOrigin::signed(7), 3), BadOrigin);
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.resume_threshold, 2);
@@ -166,12 +186,21 @@ fn update_resume_threshold_works() {
fn update_threshold_weight_works() {
new_test_ext().execute_with(|| {
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.threshold_weight, 100_000);
assert_ok!(XcmpQueue::update_threshold_weight(Origin::root(), 10_000));
assert_noop!(XcmpQueue::update_threshold_weight(Origin::signed(5), 10_000_000), BadOrigin);
assert_eq!(data.threshold_weight, Weight::from_ref_time(100_000));
assert_ok!(XcmpQueue::update_threshold_weight(
RuntimeOrigin::root(),
Weight::from_ref_time(10_000)
));
assert_noop!(
XcmpQueue::update_threshold_weight(
RuntimeOrigin::signed(5),
Weight::from_ref_time(10_000_000)
),
BadOrigin
);
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.threshold_weight, 10_000);
assert_eq!(data.threshold_weight, Weight::from_ref_time(10_000));
});
}
@@ -179,12 +208,21 @@ fn update_threshold_weight_works() {
fn update_weight_restrict_decay_works() {
new_test_ext().execute_with(|| {
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.weight_restrict_decay, 2);
assert_ok!(XcmpQueue::update_weight_restrict_decay(Origin::root(), 5));
assert_noop!(XcmpQueue::update_weight_restrict_decay(Origin::signed(6), 4), BadOrigin);
assert_eq!(data.weight_restrict_decay, Weight::from_ref_time(2));
assert_ok!(XcmpQueue::update_weight_restrict_decay(
RuntimeOrigin::root(),
Weight::from_ref_time(5)
));
assert_noop!(
XcmpQueue::update_weight_restrict_decay(
RuntimeOrigin::signed(6),
Weight::from_ref_time(4)
),
BadOrigin
);
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.weight_restrict_decay, 5);
assert_eq!(data.weight_restrict_decay, Weight::from_ref_time(5));
});
}
@@ -192,17 +230,20 @@ fn update_weight_restrict_decay_works() {
fn update_xcmp_max_individual_weight() {
new_test_ext().execute_with(|| {
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.xcmp_max_individual_weight, 20 * WEIGHT_PER_MILLIS);
assert_eq!(data.xcmp_max_individual_weight, 20u64 * WEIGHT_PER_MILLIS);
assert_ok!(XcmpQueue::update_xcmp_max_individual_weight(
Origin::root(),
30 * WEIGHT_PER_MILLIS
RuntimeOrigin::root(),
30u64 * WEIGHT_PER_MILLIS
));
assert_noop!(
XcmpQueue::update_xcmp_max_individual_weight(Origin::signed(3), 10 * WEIGHT_PER_MILLIS),
XcmpQueue::update_xcmp_max_individual_weight(
RuntimeOrigin::signed(3),
10u64 * WEIGHT_PER_MILLIS
),
BadOrigin
);
let data: QueueConfigData = <QueueConfig<Test>>::get();
assert_eq!(data.xcmp_max_individual_weight, 30 * WEIGHT_PER_MILLIS);
assert_eq!(data.xcmp_max_individual_weight, 30u64 * WEIGHT_PER_MILLIS);
});
}
+12 -12
View File
@@ -18,31 +18,31 @@ pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Storage: XcmpQueue QueueConfig (r:1 w:1)
fn set_config_with_u32() -> Weight {
(2_717_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
Weight::from_ref_time(2_717_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
// Storage: XcmpQueue QueueConfig (r:1 w:1)
fn set_config_with_weight() -> Weight {
(2_717_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
Weight::from_ref_time(2_717_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
}
impl WeightInfo for () {
// Storage: XcmpQueue QueueConfig (r:1 w:1)
fn set_config_with_u32() -> Weight {
(2_717_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
Weight::from_ref_time(2_717_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
// Storage: XcmpQueue QueueConfig (r:1 w:1)
fn set_config_with_weight() -> Weight {
(2_717_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
Weight::from_ref_time(2_717_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
}