Removed pallet::getter usage from Polkadot Runtime pallets (#3660)

Part of #3326 

@kianenigma @ggwpez 

polkadot address: 12poSUQPtcF1HUPQGY3zZu2P8emuW9YnsPduA4XG3oCEfJVp

---------

Signed-off-by: Matteo Muraca <mmuraca247@gmail.com>
Co-authored-by: ordian <write@reusable.software>
This commit is contained in:
Matteo Muraca
2024-04-10 10:35:10 +02:00
committed by GitHub
parent d96a97526e
commit 92e142555d
58 changed files with 834 additions and 820 deletions
@@ -121,9 +121,6 @@ This is currently a `no op`.
* `is_frozen()`: Load the value of `Frozen` from storage. Return true if `Some` and false if `None`.
* `last_valid_block()`: Load the value of `Frozen` from storage and return. None indicates that all blocks in the chain
are potentially valid.
* `revert_and_freeze(BlockNumber)`:
1. If `is_frozen()` return.
1. Set `Frozen` to `Some(BlockNumber)` to indicate a rollback to the block number.
@@ -229,7 +229,7 @@ Actions:
[`HostConfiguration`](../types/runtime.md#host-configuration))
1. Fetch `Shared::ActiveValidators` as AV.
1. Determine the number of cores & validator groups as `n_cores`. This is the maximum of
1. `Paras::parachains().len() + configuration.parathread_cores`
1. `paras::Parachains::<T>::get().len() + configuration.parathread_cores`
1. `n_validators / max_validators_per_core` if `configuration.max_validators_per_core` is `Some` and non-zero.
1. Resize `AvailabilityCores` to have length `n_cores` with all `None` entries.
1. Compute new validator groups by shuffling using a secure randomness beacon
@@ -261,7 +261,7 @@ No finalization routine runs for this module.
- Fails if any on-demand claim on the same parachain is currently indexed.
- Fails if the queue length is >= `config.scheduling_lookahead * config.parathread_cores`.
- The core used for the on-demand claim is the `next_core` field of the `ParathreadQueue` (on-demand queue) and adding
`Paras::parachains().len()` to it.
`paras::Parachains::<T>::get().len()` to it.
- `next_core` is then updated by adding 1 and taking it modulo `config.parathread_cores`.
- The claim is then added to the claim index.
- `free_cores(Vec<(CoreIndex, FreedReason)>)`: indicate previously-occupied cores which are to be considered returned
@@ -76,6 +76,6 @@ Sessions: map SessionIndex => Option<SessionInfo>,
## Routines
* `earliest_stored_session() -> SessionIndex`: Yields the earliest session for which we have information stored.
* `session_info(session: SessionIndex) -> Option<SessionInfo>`: Yields the session info for the given session, if
* `EarliestStoredSession::<T>::get() -> SessionIndex`: Yields the earliest session for which we have information stored.
* `Sessions::<T>::get(session: SessionIndex) -> Option<SessionInfo>`: Yields the session info for the given session, if
stored.
@@ -39,8 +39,8 @@ pub mod v1 {
const MAX_PERMANENT_SLOTS: u32 = 100;
const MAX_TEMPORARY_SLOTS: u32 = 100;
<MaxPermanentSlots<T>>::put(MAX_PERMANENT_SLOTS);
<MaxTemporarySlots<T>>::put(MAX_TEMPORARY_SLOTS);
MaxPermanentSlots::<T>::put(MAX_PERMANENT_SLOTS);
MaxTemporarySlots::<T>::put(MAX_TEMPORARY_SLOTS);
// Return the weight consumed by the migration.
T::DbWeight::get().reads_writes(1, 3)
} else {
@@ -53,8 +53,8 @@ pub mod v1 {
fn post_upgrade(_state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
let on_chain_version = Pallet::<T>::on_chain_storage_version();
ensure!(on_chain_version == 1, "assigned_slots::MigrateToV1 needs to be run");
assert_eq!(<MaxPermanentSlots<T>>::get(), 100);
assert_eq!(<MaxTemporarySlots<T>>::get(), 100);
assert_eq!(MaxPermanentSlots::<T>::get(), 100);
assert_eq!(MaxTemporarySlots::<T>::get(), 100);
Ok(())
}
}
@@ -148,18 +148,15 @@ pub mod pallet {
/// Assigned permanent slots, with their start lease period, and duration.
#[pallet::storage]
#[pallet::getter(fn permanent_slots)]
pub type PermanentSlots<T: Config> =
StorageMap<_, Twox64Concat, ParaId, (LeasePeriodOf<T>, LeasePeriodOf<T>), OptionQuery>;
/// Number of assigned (and active) permanent slots.
#[pallet::storage]
#[pallet::getter(fn permanent_slot_count)]
pub type PermanentSlotCount<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Assigned temporary slots.
#[pallet::storage]
#[pallet::getter(fn temporary_slots)]
pub type TemporarySlots<T: Config> = StorageMap<
_,
Twox64Concat,
@@ -170,12 +167,10 @@ pub mod pallet {
/// Number of assigned temporary slots.
#[pallet::storage]
#[pallet::getter(fn temporary_slot_count)]
pub type TemporarySlotCount<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Number of active temporary slots in current slot lease period.
#[pallet::storage]
#[pallet::getter(fn active_temporary_slot_count)]
pub type ActiveTemporarySlotCount<T: Config> = StorageValue<_, u32, ValueQuery>;
/// The max number of temporary slots that can be assigned.
@@ -197,8 +192,8 @@ pub mod pallet {
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
<MaxPermanentSlots<T>>::put(&self.max_permanent_slots);
<MaxTemporarySlots<T>>::put(&self.max_temporary_slots);
MaxPermanentSlots::<T>::put(&self.max_permanent_slots);
MaxTemporarySlots::<T>::put(&self.max_temporary_slots);
}
}
@@ -306,7 +301,7 @@ pub mod pallet {
LeasePeriodOf::<T>::from(T::PermanentSlotLeasePeriodLength::get()),
),
);
<PermanentSlotCount<T>>::mutate(|count| count.saturating_inc());
PermanentSlotCount::<T>::mutate(|count| count.saturating_inc());
Self::deposit_event(Event::<T>::PermanentSlotAssigned(id));
Ok(())
@@ -364,7 +359,7 @@ pub mod pallet {
};
if lease_period_start == SlotLeasePeriodStart::Current &&
Self::active_temporary_slot_count() < T::MaxTemporarySlotPerLeasePeriod::get()
ActiveTemporarySlotCount::<T>::get() < T::MaxTemporarySlotPerLeasePeriod::get()
{
// Try to allocate slot directly
match Self::configure_slot_lease(
@@ -394,7 +389,7 @@ pub mod pallet {
}
TemporarySlots::<T>::insert(id, temp_slot);
<TemporarySlotCount<T>>::mutate(|count| count.saturating_inc());
TemporarySlotCount::<T>::mutate(|count| count.saturating_inc());
Self::deposit_event(Event::<T>::TemporarySlotAssigned(id));
@@ -420,12 +415,12 @@ pub mod pallet {
if PermanentSlots::<T>::contains_key(id) {
PermanentSlots::<T>::remove(id);
<PermanentSlotCount<T>>::mutate(|count| *count = count.saturating_sub(One::one()));
PermanentSlotCount::<T>::mutate(|count| *count = count.saturating_sub(One::one()));
} else if TemporarySlots::<T>::contains_key(id) {
TemporarySlots::<T>::remove(id);
<TemporarySlotCount<T>>::mutate(|count| *count = count.saturating_sub(One::one()));
TemporarySlotCount::<T>::mutate(|count| *count = count.saturating_sub(One::one()));
if is_parachain {
<ActiveTemporarySlotCount<T>>::mutate(|active_count| {
ActiveTemporarySlotCount::<T>::mutate(|active_count| {
*active_count = active_count.saturating_sub(One::one())
});
}
@@ -456,7 +451,7 @@ pub mod pallet {
pub fn set_max_permanent_slots(origin: OriginFor<T>, slots: u32) -> DispatchResult {
ensure_root(origin)?;
<MaxPermanentSlots<T>>::put(slots);
MaxPermanentSlots::<T>::put(slots);
Self::deposit_event(Event::<T>::MaxPermanentSlotsChanged { slots });
Ok(())
@@ -468,7 +463,7 @@ pub mod pallet {
pub fn set_max_temporary_slots(origin: OriginFor<T>, slots: u32) -> DispatchResult {
ensure_root(origin)?;
<MaxTemporarySlots<T>>::put(slots);
MaxTemporarySlots::<T>::put(slots);
Self::deposit_event(Event::<T>::MaxTemporarySlotsChanged { slots });
Ok(())
@@ -965,7 +960,7 @@ mod tests {
RuntimeOrigin::root(),
ParaId::from(2_u32),
));
assert_eq!(AssignedSlots::permanent_slot_count(), 2);
assert_eq!(assigned_slots::PermanentSlotCount::<Test>::get(), 2);
assert_noop!(
AssignedSlots::assign_perm_parachain_slot(
@@ -989,8 +984,8 @@ mod tests {
dummy_validation_code(),
));
assert_eq!(AssignedSlots::permanent_slot_count(), 0);
assert_eq!(AssignedSlots::permanent_slots(ParaId::from(1_u32)), None);
assert_eq!(assigned_slots::PermanentSlotCount::<Test>::get(), 0);
assert_eq!(assigned_slots::PermanentSlots::<Test>::get(ParaId::from(1_u32)), None);
assert_ok!(AssignedSlots::assign_perm_parachain_slot(
RuntimeOrigin::root(),
@@ -1004,9 +999,12 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(1_u32)), true);
assert_eq!(AssignedSlots::permanent_slot_count(), 1);
assert_eq!(assigned_slots::PermanentSlotCount::<Test>::get(), 1);
assert_eq!(AssignedSlots::has_permanent_slot(ParaId::from(1_u32)), true);
assert_eq!(AssignedSlots::permanent_slots(ParaId::from(1_u32)), Some((0, 3)));
assert_eq!(
assigned_slots::PermanentSlots::<Test>::get(ParaId::from(1_u32)),
Some((0, 3))
);
assert_eq!(Slots::already_leased(ParaId::from(1_u32), 0, 2), true);
@@ -1138,7 +1136,7 @@ mod tests {
));
}
assert_eq!(AssignedSlots::temporary_slot_count(), 6);
assert_eq!(assigned_slots::TemporarySlotCount::<Test>::get(), 6);
// Attempt to assign one more temp slot
assert_ok!(TestRegistrar::<Test>::register(
@@ -1170,15 +1168,15 @@ mod tests {
dummy_validation_code(),
));
assert_eq!(AssignedSlots::temporary_slots(ParaId::from(1_u32)), None);
assert_eq!(assigned_slots::TemporarySlots::<Test>::get(ParaId::from(1_u32)), None);
assert_ok!(AssignedSlots::assign_temp_parachain_slot(
RuntimeOrigin::root(),
ParaId::from(1_u32),
SlotLeasePeriodStart::Current
));
assert_eq!(AssignedSlots::temporary_slot_count(), 1);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 1);
assert_eq!(assigned_slots::TemporarySlotCount::<Test>::get(), 1);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 1);
// Block 1-5
// Para is a lease holding parachain for TemporarySlotLeasePeriodLength * LeasePeriod
@@ -1186,14 +1184,14 @@ mod tests {
while block < 6 {
println!("block #{}", block);
println!("lease period #{}", AssignedSlots::current_lease_period_index());
println!("lease {:?}", Slots::lease(ParaId::from(1_u32)));
println!("lease {:?}", slots::Leases::<Test>::get(ParaId::from(1_u32)));
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(1_u32)), true);
assert_eq!(AssignedSlots::has_temporary_slot(ParaId::from(1_u32)), true);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 1);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 1);
assert_eq!(
AssignedSlots::temporary_slots(ParaId::from(1_u32)),
assigned_slots::TemporarySlots::<Test>::get(ParaId::from(1_u32)),
Some(ParachainTemporarySlot {
manager: 1,
period_begin: 0,
@@ -1212,23 +1210,23 @@ mod tests {
// Block 6
println!("block #{}", block);
println!("lease period #{}", AssignedSlots::current_lease_period_index());
println!("lease {:?}", Slots::lease(ParaId::from(1_u32)));
println!("lease {:?}", slots::Leases::<Test>::get(ParaId::from(1_u32)));
// Para lease ended, downgraded back to on-demand parachain
assert_eq!(TestRegistrar::<Test>::is_parathread(ParaId::from(1_u32)), true);
assert_eq!(Slots::already_leased(ParaId::from(1_u32), 0, 3), false);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 0);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 0);
// Block 12
// Para should get a turn after TemporarySlotLeasePeriodLength * LeasePeriod blocks
run_to_block(12);
println!("block #{}", block);
println!("lease period #{}", AssignedSlots::current_lease_period_index());
println!("lease {:?}", Slots::lease(ParaId::from(1_u32)));
println!("lease {:?}", slots::Leases::<Test>::get(ParaId::from(1_u32)));
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(1_u32)), true);
assert_eq!(Slots::already_leased(ParaId::from(1_u32), 4, 5), true);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 1);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 1);
});
}
@@ -1270,7 +1268,7 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(3_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(4_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(5_u32)), false);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 2);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 2);
}
// Block 6-11, Period 2-3
@@ -1282,7 +1280,7 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(3_u32)), true);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(4_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(5_u32)), false);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 2);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 2);
}
// Block 12-17, Period 4-5
@@ -1294,7 +1292,7 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(3_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(4_u32)), true);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(5_u32)), true);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 2);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 2);
}
// Block 18-23, Period 6-7
@@ -1306,7 +1304,7 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(3_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(4_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(5_u32)), false);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 2);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 2);
}
// Block 24-29, Period 8-9
@@ -1318,7 +1316,7 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(3_u32)), true);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(4_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(5_u32)), false);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 2);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 2);
}
// Block 30-35, Period 10-11
@@ -1330,7 +1328,7 @@ mod tests {
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(3_u32)), false);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(4_u32)), true);
assert_eq!(TestRegistrar::<Test>::is_parachain(ParaId::from(5_u32)), true);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 2);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 2);
}
});
}
@@ -1386,9 +1384,9 @@ mod tests {
ParaId::from(1_u32),
));
assert_eq!(AssignedSlots::permanent_slot_count(), 0);
assert_eq!(assigned_slots::PermanentSlotCount::<Test>::get(), 0);
assert_eq!(AssignedSlots::has_permanent_slot(ParaId::from(1_u32)), false);
assert_eq!(AssignedSlots::permanent_slots(ParaId::from(1_u32)), None);
assert_eq!(assigned_slots::PermanentSlots::<Test>::get(ParaId::from(1_u32)), None);
assert_eq!(Slots::already_leased(ParaId::from(1_u32), 0, 2), false);
});
@@ -1419,10 +1417,10 @@ mod tests {
ParaId::from(1_u32),
));
assert_eq!(AssignedSlots::temporary_slot_count(), 0);
assert_eq!(AssignedSlots::active_temporary_slot_count(), 0);
assert_eq!(assigned_slots::TemporarySlotCount::<Test>::get(), 0);
assert_eq!(assigned_slots::ActiveTemporarySlotCount::<Test>::get(), 0);
assert_eq!(AssignedSlots::has_temporary_slot(ParaId::from(1_u32)), false);
assert_eq!(AssignedSlots::temporary_slots(ParaId::from(1_u32)), None);
assert_eq!(assigned_slots::TemporarySlots::<Test>::get(ParaId::from(1_u32)), None);
assert_eq!(Slots::already_leased(ParaId::from(1_u32), 0, 1), false);
});
+12 -16
View File
@@ -174,7 +174,6 @@ pub mod pallet {
/// Number of auctions started so far.
#[pallet::storage]
#[pallet::getter(fn auction_counter)]
pub type AuctionCounter<T> = StorageValue<_, AuctionIndex, ValueQuery>;
/// Information relating to the current auction, if there is one.
@@ -183,13 +182,11 @@ pub mod pallet {
/// contiguous lease periods on auction is for. The second is the block number when the
/// auction will "begin to end", i.e. the first block of the Ending Period of the auction.
#[pallet::storage]
#[pallet::getter(fn auction_info)]
pub type AuctionInfo<T: Config> = StorageValue<_, (LeasePeriodOf<T>, BlockNumberFor<T>)>;
/// Amounts currently reserved in the accounts of the bidders currently winning
/// (sub-)ranges.
#[pallet::storage]
#[pallet::getter(fn reserved_amounts)]
pub type ReservedAmounts<T: Config> =
StorageMap<_, Twox64Concat, (T::AccountId, ParaId), BalanceOf<T>>;
@@ -197,7 +194,6 @@ pub mod pallet {
/// the current auction. The map's key is the 0-based index into the Sample Size. The
/// first sample of the ending period is 0; the last is `Sample Size - 1`.
#[pallet::storage]
#[pallet::getter(fn winning)]
pub type Winning<T: Config> = StorageMap<_, Twox64Concat, BlockNumberFor<T>, WinningData<T>>;
#[pallet::extra_constants]
@@ -983,7 +979,7 @@ mod tests {
assert_eq!(Balances::reserved_balance(1), 5);
assert_eq!(Balances::free_balance(1), 5);
assert_eq!(
Auctions::winning(0).unwrap()[SlotRange::ZeroThree as u8 as usize],
Winning::<Test>::get(0).unwrap()[SlotRange::ZeroThree as u8 as usize],
Some((1, 0.into(), 5))
);
});
@@ -1016,7 +1012,7 @@ mod tests {
assert_eq!(Balances::reserved_balance(2), 6);
assert_eq!(Balances::free_balance(2), 14);
assert_eq!(
Auctions::winning(0).unwrap()[SlotRange::ZeroThree as u8 as usize],
Winning::<Test>::get(0).unwrap()[SlotRange::ZeroThree as u8 as usize],
Some((2, 0.into(), 6))
);
});
@@ -1453,7 +1449,7 @@ mod tests {
let mut winning = [None; SlotRange::SLOT_RANGE_COUNT];
winning[SlotRange::ZeroThree as u8 as usize] = Some((1, para_1, 9));
winning[SlotRange::TwoThree as u8 as usize] = Some((2, para_2, 19));
assert_eq!(Auctions::winning(0), Some(winning));
assert_eq!(Winning::<Test>::get(0), Some(winning));
run_to_block(9);
assert_eq!(
@@ -1466,14 +1462,14 @@ mod tests {
Auctions::auction_status(System::block_number()),
AuctionStatus::<u32>::EndingPeriod(0, 0)
);
assert_eq!(Auctions::winning(0), Some(winning));
assert_eq!(Winning::<Test>::get(0), Some(winning));
run_to_block(11);
assert_eq!(
Auctions::auction_status(System::block_number()),
AuctionStatus::<u32>::EndingPeriod(1, 0)
);
assert_eq!(Auctions::winning(1), Some(winning));
assert_eq!(Winning::<Test>::get(1), Some(winning));
assert_ok!(Auctions::bid(RuntimeOrigin::signed(3), para_3, 1, 3, 4, 29));
run_to_block(12);
@@ -1482,7 +1478,7 @@ mod tests {
AuctionStatus::<u32>::EndingPeriod(2, 0)
);
winning[SlotRange::TwoThree as u8 as usize] = Some((3, para_3, 29));
assert_eq!(Auctions::winning(2), Some(winning));
assert_eq!(Winning::<Test>::get(2), Some(winning));
});
}
@@ -1569,7 +1565,7 @@ mod tests {
let mut winning = [None; SlotRange::SLOT_RANGE_COUNT];
winning[SlotRange::ZeroThree as u8 as usize] = Some((1, para_1, 9));
winning[SlotRange::TwoThree as u8 as usize] = Some((2, para_2, 19));
assert_eq!(Auctions::winning(0), Some(winning));
assert_eq!(Winning::<Test>::get(0), Some(winning));
run_to_block(9);
assert_eq!(
@@ -1582,31 +1578,31 @@ mod tests {
Auctions::auction_status(System::block_number()),
AuctionStatus::<u32>::EndingPeriod(0, 0)
);
assert_eq!(Auctions::winning(0), Some(winning));
assert_eq!(Winning::<Test>::get(0), Some(winning));
// New bids update the current winning
assert_ok!(Auctions::bid(RuntimeOrigin::signed(3), para_3, 1, 14, 14, 29));
winning[SlotRange::ThreeThree as u8 as usize] = Some((3, para_3, 29));
assert_eq!(Auctions::winning(0), Some(winning));
assert_eq!(Winning::<Test>::get(0), Some(winning));
run_to_block(20);
assert_eq!(
Auctions::auction_status(System::block_number()),
AuctionStatus::<u32>::EndingPeriod(1, 0)
);
assert_eq!(Auctions::winning(1), Some(winning));
assert_eq!(Winning::<Test>::get(1), Some(winning));
run_to_block(25);
// Overbid mid sample
assert_ok!(Auctions::bid(RuntimeOrigin::signed(3), para_3, 1, 13, 14, 29));
winning[SlotRange::TwoThree as u8 as usize] = Some((3, para_3, 29));
assert_eq!(Auctions::winning(1), Some(winning));
assert_eq!(Winning::<Test>::get(1), Some(winning));
run_to_block(30);
assert_eq!(
Auctions::auction_status(System::block_number()),
AuctionStatus::<u32>::EndingPeriod(2, 0)
);
assert_eq!(Auctions::winning(2), Some(winning));
assert_eq!(Winning::<Test>::get(2), Some(winning));
set_last_random(H256::from([254; 32]), 40);
run_to_block(40);
+37 -39
View File
@@ -203,20 +203,17 @@ pub mod pallet {
}
#[pallet::storage]
#[pallet::getter(fn claims)]
pub(super) type Claims<T: Config> = StorageMap<_, Identity, EthereumAddress, BalanceOf<T>>;
pub type Claims<T: Config> = StorageMap<_, Identity, EthereumAddress, BalanceOf<T>>;
#[pallet::storage]
#[pallet::getter(fn total)]
pub(super) type Total<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
pub type Total<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
/// Vesting schedule for a claim.
/// First balance is the total amount that should be held for vesting.
/// Second balance is how much should be unlocked per block.
/// The block number is when the vesting should start.
#[pallet::storage]
#[pallet::getter(fn vesting)]
pub(super) type Vesting<T: Config> =
pub type Vesting<T: Config> =
StorageMap<_, Identity, EthereumAddress, (BalanceOf<T>, BalanceOf<T>, BlockNumberFor<T>)>;
/// The statement kind that must be signed, if any.
@@ -341,10 +338,10 @@ pub mod pallet {
) -> DispatchResult {
ensure_root(origin)?;
<Total<T>>::mutate(|t| *t += value);
<Claims<T>>::insert(who, value);
Total::<T>::mutate(|t| *t += value);
Claims::<T>::insert(who, value);
if let Some(vs) = vesting_schedule {
<Vesting<T>>::insert(who, vs);
Vesting::<T>::insert(who, vs);
}
if let Some(s) = statement {
Signing::<T>::insert(who, s);
@@ -492,7 +489,7 @@ pub mod pallet {
))?;
let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into());
ensure!(<Claims<T>>::contains_key(&signer), e);
ensure!(Claims::<T>::contains_key(&signer), e);
let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into());
match Signing::<T>::get(signer) {
@@ -551,9 +548,10 @@ impl<T: Config> Pallet<T> {
}
fn process_claim(signer: EthereumAddress, dest: T::AccountId) -> sp_runtime::DispatchResult {
let balance_due = <Claims<T>>::get(&signer).ok_or(Error::<T>::SignerHasNoClaim)?;
let balance_due = Claims::<T>::get(&signer).ok_or(Error::<T>::SignerHasNoClaim)?;
let new_total = Self::total().checked_sub(&balance_due).ok_or(Error::<T>::PotUnderflow)?;
let new_total =
Total::<T>::get().checked_sub(&balance_due).ok_or(Error::<T>::PotUnderflow)?;
let vesting = Vesting::<T>::get(&signer);
if vesting.is_some() && T::VestingSchedule::vesting_balance(&dest).is_some() {
@@ -571,9 +569,9 @@ impl<T: Config> Pallet<T> {
.expect("No other vesting schedule exists, as checked above; qed");
}
<Total<T>>::put(new_total);
<Claims<T>>::remove(&signer);
<Vesting<T>>::remove(&signer);
Total::<T>::put(new_total);
Claims::<T>::remove(&signer);
Vesting::<T>::remove(&signer);
Signing::<T>::remove(&signer);
// Let's deposit an event to let the outside world know this happened.
@@ -683,7 +681,7 @@ mod secp_utils {
what: &[u8],
extra: &[u8],
) -> EcdsaSignature {
let msg = keccak_256(&<super::Pallet<T>>::ethereum_signable_message(
let msg = keccak_256(&super::Pallet::<T>::ethereum_signable_message(
&to_ascii_hex(what)[..],
extra,
));
@@ -837,13 +835,13 @@ mod tests {
#[test]
fn basic_setup_works() {
new_test_ext().execute_with(|| {
assert_eq!(Claims::total(), total_claims());
assert_eq!(Claims::claims(&eth(&alice())), Some(100));
assert_eq!(Claims::claims(&eth(&dave())), Some(200));
assert_eq!(Claims::claims(&eth(&eve())), Some(300));
assert_eq!(Claims::claims(&eth(&frank())), Some(400));
assert_eq!(Claims::claims(&EthereumAddress::default()), None);
assert_eq!(Claims::vesting(&eth(&alice())), Some((50, 10, 1)));
assert_eq!(claims::Total::<Test>::get(), total_claims());
assert_eq!(claims::Claims::<Test>::get(&eth(&alice())), Some(100));
assert_eq!(claims::Claims::<Test>::get(&eth(&dave())), Some(200));
assert_eq!(claims::Claims::<Test>::get(&eth(&eve())), Some(300));
assert_eq!(claims::Claims::<Test>::get(&eth(&frank())), Some(400));
assert_eq!(claims::Claims::<Test>::get(&EthereumAddress::default()), None);
assert_eq!(claims::Vesting::<Test>::get(&eth(&alice())), Some((50, 10, 1)));
});
}
@@ -867,7 +865,7 @@ mod tests {
));
assert_eq!(Balances::free_balance(&42), 100);
assert_eq!(Vesting::vesting_balance(&42), Some(50));
assert_eq!(Claims::total(), total_claims() - 100);
assert_eq!(claims::Total::<Test>::get(), total_claims() - 100);
});
}
@@ -900,7 +898,7 @@ mod tests {
));
assert_eq!(Balances::free_balance(&42), 100);
assert_eq!(Vesting::vesting_balance(&42), Some(50));
assert_eq!(Claims::total(), total_claims() - 100);
assert_eq!(claims::Total::<Test>::get(), total_claims() - 100);
});
}
@@ -1004,7 +1002,7 @@ mod tests {
StatementKind::Regular.to_text().to_vec()
));
assert_eq!(Balances::free_balance(&42), 200);
assert_eq!(Claims::total(), total_claims() - 200);
assert_eq!(claims::Total::<Test>::get(), total_claims() - 200);
let s = sig::<Test>(&dave(), &42u64.encode(), StatementKind::Regular.to_text());
let r = Claims::claim_attest(
@@ -1037,7 +1035,7 @@ mod tests {
StatementKind::Saft.to_text().to_vec()
));
assert_eq!(Balances::free_balance(&42), 300);
assert_eq!(Claims::total(), total_claims() - 300);
assert_eq!(claims::Total::<Test>::get(), total_claims() - 300);
});
}
@@ -1058,7 +1056,7 @@ mod tests {
StatementKind::Saft.to_text().to_vec()
));
assert_eq!(Balances::free_balance(&42), 100 + 300);
assert_eq!(Claims::total(), total_claims() - 400);
assert_eq!(claims::Total::<Test>::get(), total_claims() - 400);
});
}
@@ -1122,7 +1120,7 @@ mod tests {
Error::<Test>::SignerHasNoClaim,
);
assert_ok!(Claims::mint_claim(RuntimeOrigin::root(), eth(&bob()), 200, None, None));
assert_eq!(Claims::total(), total_claims() + 200);
assert_eq!(claims::Total::<Test>::get(), total_claims() + 200);
assert_ok!(Claims::claim(
RuntimeOrigin::none(),
69,
@@ -1130,7 +1128,7 @@ mod tests {
));
assert_eq!(Balances::free_balance(&69), 200);
assert_eq!(Vesting::vesting_balance(&69), None);
assert_eq!(Claims::total(), total_claims());
assert_eq!(claims::Total::<Test>::get(), total_claims());
});
}
@@ -1284,7 +1282,7 @@ mod tests {
None
));
// New total
assert_eq!(Claims::total(), total_claims() + 200);
assert_eq!(claims::Total::<Test>::get(), total_claims() + 200);
// They should not be able to claim
assert_noop!(
@@ -1347,7 +1345,7 @@ mod tests {
new_test_ext().execute_with(|| {
assert_eq!(
<Pallet<Test>>::validate_unsigned(
Pallet::<Test>::validate_unsigned(
source,
&ClaimsCall::claim {
dest: 1,
@@ -1363,14 +1361,14 @@ mod tests {
})
);
assert_eq!(
<Pallet<Test>>::validate_unsigned(
Pallet::<Test>::validate_unsigned(
source,
&ClaimsCall::claim { dest: 0, ethereum_signature: EcdsaSignature([0; 65]) }
),
InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(),
);
assert_eq!(
<Pallet<Test>>::validate_unsigned(
Pallet::<Test>::validate_unsigned(
source,
&ClaimsCall::claim {
dest: 1,
@@ -1386,7 +1384,7 @@ mod tests {
statement: StatementKind::Regular.to_text().to_vec(),
};
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &call),
Pallet::<Test>::validate_unsigned(source, &call),
Ok(ValidTransaction {
priority: 100,
requires: vec![],
@@ -1396,7 +1394,7 @@ mod tests {
})
);
assert_eq!(
<Pallet<Test>>::validate_unsigned(
Pallet::<Test>::validate_unsigned(
source,
&ClaimsCall::claim_attest {
dest: 1,
@@ -1414,7 +1412,7 @@ mod tests {
statement: StatementKind::Regular.to_text().to_vec(),
};
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &call),
Pallet::<Test>::validate_unsigned(source, &call),
InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(),
);
@@ -1425,7 +1423,7 @@ mod tests {
statement: StatementKind::Regular.to_text().to_vec(),
};
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &call),
Pallet::<Test>::validate_unsigned(source, &call),
InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(),
);
@@ -1436,7 +1434,7 @@ mod tests {
statement: StatementKind::Saft.to_text().to_vec(),
};
assert_eq!(
<Pallet<Test>>::validate_unsigned(source, &call),
Pallet::<Test>::validate_unsigned(source, &call),
InvalidTransaction::Custom(ValidityError::InvalidStatement.into()).into(),
);
});
+30 -34
View File
@@ -225,8 +225,7 @@ pub mod pallet {
/// Info on all of the funds.
#[pallet::storage]
#[pallet::getter(fn funds)]
pub(crate) type Funds<T: Config> = StorageMap<
pub type Funds<T: Config> = StorageMap<
_,
Twox64Concat,
ParaId,
@@ -236,18 +235,15 @@ pub mod pallet {
/// The funds that have had additional contributions during the last block. This is used
/// in order to determine which funds should submit new or updated bids.
#[pallet::storage]
#[pallet::getter(fn new_raise)]
pub(super) type NewRaise<T> = StorageValue<_, Vec<ParaId>, ValueQuery>;
pub type NewRaise<T> = StorageValue<_, Vec<ParaId>, ValueQuery>;
/// The number of auctions that have entered into their ending period so far.
#[pallet::storage]
#[pallet::getter(fn endings_count)]
pub(super) type EndingsCount<T> = StorageValue<_, u32, ValueQuery>;
pub type EndingsCount<T> = StorageValue<_, u32, ValueQuery>;
/// Tracker for the next available fund index
#[pallet::storage]
#[pallet::getter(fn next_fund_index)]
pub(super) type NextFundIndex<T> = StorageValue<_, u32, ValueQuery>;
pub type NextFundIndex<T> = StorageValue<_, u32, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
@@ -338,7 +334,7 @@ pub mod pallet {
let new_raise = NewRaise::<T>::take();
let new_raise_len = new_raise.len() as u32;
for (fund, para_id) in
new_raise.into_iter().filter_map(|i| Self::funds(i).map(|f| (f, i)))
new_raise.into_iter().filter_map(|i| Funds::<T>::get(i).map(|f| (f, i)))
{
// Care needs to be taken by the crowdloan creator that this function will
// succeed given the crowdloaning configuration. We do some checks ahead of time
@@ -412,7 +408,7 @@ pub mod pallet {
ensure!(depositor == manager, Error::<T>::InvalidOrigin);
ensure!(T::Registrar::is_registered(index), Error::<T>::InvalidParaId);
let fund_index = Self::next_fund_index();
let fund_index = NextFundIndex::<T>::get();
let new_fund_index = fund_index.checked_add(1).ok_or(Error::<T>::Overflow)?;
let deposit = T::SubmissionDeposit::get();
@@ -482,7 +478,7 @@ pub mod pallet {
) -> DispatchResult {
ensure_signed(origin)?;
let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let mut fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
let now = frame_system::Pallet::<T>::block_number();
let fund_account = Self::fund_account_id(fund.fund_index);
Self::ensure_crowdloan_ended(now, &fund_account, &fund)?;
@@ -515,7 +511,7 @@ pub mod pallet {
) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;
let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let mut fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
let now = frame_system::Pallet::<T>::block_number();
let fund_account = Self::fund_account_id(fund.fund_index);
Self::ensure_crowdloan_ended(now, &fund_account, &fund)?;
@@ -558,7 +554,7 @@ pub mod pallet {
pub fn dissolve(origin: OriginFor<T>, #[pallet::compact] index: ParaId) -> DispatchResult {
let who = ensure_signed(origin)?;
let fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
let pot = Self::fund_account_id(fund.fund_index);
let now = frame_system::Pallet::<T>::block_number();
@@ -599,7 +595,7 @@ pub mod pallet {
) -> DispatchResult {
ensure_root(origin)?;
let fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
Funds::<T>::insert(
index,
@@ -630,7 +626,7 @@ pub mod pallet {
let who = ensure_signed(origin)?;
ensure!(memo.len() <= T::MaxMemoLength::get().into(), Error::<T>::MemoTooLarge);
let fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
let (balance, _) = Self::contribution_get(fund.fund_index, &who);
ensure!(balance > Zero::zero(), Error::<T>::NoContributions);
@@ -647,7 +643,7 @@ pub mod pallet {
#[pallet::weight(T::WeightInfo::poke())]
pub fn poke(origin: OriginFor<T>, index: ParaId) -> DispatchResult {
ensure_signed(origin)?;
let fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
ensure!(!fund.raised.is_zero(), Error::<T>::NoContributions);
ensure!(!NewRaise::<T>::get().contains(&index), Error::<T>::AlreadyInNewRaise);
NewRaise::<T>::append(index);
@@ -757,12 +753,12 @@ impl<T: Config> Pallet<T> {
existence: ExistenceRequirement,
) -> DispatchResult {
ensure!(value >= T::MinContribution::get(), Error::<T>::ContributionTooSmall);
let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidParaId)?;
let mut fund = Funds::<T>::get(index).ok_or(Error::<T>::InvalidParaId)?;
fund.raised = fund.raised.checked_add(&value).ok_or(Error::<T>::Overflow)?;
ensure!(fund.raised <= fund.cap, Error::<T>::CapExceeded);
// Make sure crowdloan has not ended
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
ensure!(now < fund.end, Error::<T>::ContributionPeriodOver);
// Make sure crowdloan is in a valid lease period
@@ -811,7 +807,7 @@ impl<T: Config> Pallet<T> {
},
}
} else {
let endings_count = Self::endings_count();
let endings_count = EndingsCount::<T>::get();
match fund.last_contribution {
LastContribution::PreEnding(a) if a == endings_count => {
// Not in ending period and no auctions have ended ending since our
@@ -1155,11 +1151,11 @@ mod tests {
fn basic_setup_works() {
new_test_ext().execute_with(|| {
assert_eq!(System::block_number(), 0);
assert_eq!(Crowdloan::funds(ParaId::from(0)), None);
assert_eq!(crowdloan::Funds::<Test>::get(ParaId::from(0)), None);
let empty: Vec<ParaId> = Vec::new();
assert_eq!(Crowdloan::new_raise(), empty);
assert_eq!(crowdloan::NewRaise::<Test>::get(), empty);
assert_eq!(Crowdloan::contribution_get(0u32, &1).0, 0);
assert_eq!(Crowdloan::endings_count(), 0);
assert_eq!(crowdloan::EndingsCount::<Test>::get(), 0);
assert_ok!(TestAuctioneer::new_auction(5, 0));
@@ -1201,14 +1197,14 @@ mod tests {
last_period: 4,
fund_index: 0,
};
assert_eq!(Crowdloan::funds(para), Some(fund_info));
assert_eq!(crowdloan::Funds::<Test>::get(para), Some(fund_info));
// User has deposit removed from their free balance
assert_eq!(Balances::free_balance(1), 999);
// Deposit is placed in reserved
assert_eq!(Balances::reserved_balance(1), 1);
// No new raise until first contribution
let empty: Vec<ParaId> = Vec::new();
assert_eq!(Crowdloan::new_raise(), empty);
assert_eq!(crowdloan::NewRaise::<Test>::get(), empty);
});
}
@@ -1241,14 +1237,14 @@ mod tests {
last_period: 4,
fund_index: 0,
};
assert_eq!(Crowdloan::funds(ParaId::from(0)), Some(fund_info));
assert_eq!(crowdloan::Funds::<Test>::get(ParaId::from(0)), Some(fund_info));
// User has deposit removed from their free balance
assert_eq!(Balances::free_balance(1), 999);
// Deposit is placed in reserved
assert_eq!(Balances::reserved_balance(1), 1);
// No new raise until first contribution
let empty: Vec<ParaId> = Vec::new();
assert_eq!(Crowdloan::new_raise(), empty);
assert_eq!(crowdloan::NewRaise::<Test>::get(), empty);
});
}
@@ -1321,9 +1317,9 @@ mod tests {
// Contributions appear in free balance of crowdloan
assert_eq!(Balances::free_balance(Crowdloan::fund_account_id(index)), 49);
// Crowdloan is added to NewRaise
assert_eq!(Crowdloan::new_raise(), vec![para]);
assert_eq!(crowdloan::NewRaise::<Test>::get(), vec![para]);
let fund = Crowdloan::funds(para).unwrap();
let fund = crowdloan::Funds::<Test>::get(para).unwrap();
// Last contribution time recorded
assert_eq!(fund.last_contribution, LastContribution::PreEnding(0));
@@ -1418,7 +1414,7 @@ mod tests {
assert_eq!(Balances::free_balance(Crowdloan::fund_account_id(index)), 59);
// Contribution amount is correct
let fund = Crowdloan::funds(para).unwrap();
let fund = crowdloan::Funds::<Test>::get(para).unwrap();
assert_eq!(fund.raised, 59);
});
}
@@ -1570,7 +1566,7 @@ mod tests {
);
// Endings count incremented
assert_eq!(Crowdloan::endings_count(), 1);
assert_eq!(crowdloan::EndingsCount::<Test>::get(), 1);
});
}
@@ -1758,7 +1754,7 @@ mod tests {
// We test the historic case where crowdloan accounts only have one provider:
{
let fund = Crowdloan::funds(para).unwrap();
let fund = crowdloan::Funds::<Test>::get(para).unwrap();
let pot = Crowdloan::fund_account_id(fund.fund_index);
System::dec_providers(&pot).unwrap();
assert_eq!(System::providers(&pot), 1);
@@ -1910,10 +1906,10 @@ mod tests {
assert_ok!(Crowdloan::create(RuntimeOrigin::signed(1), para_1, 1000, 1, 1, 9, None));
assert_ok!(Crowdloan::contribute(RuntimeOrigin::signed(2), para_1, 100, None));
let old_crowdloan = Crowdloan::funds(para_1).unwrap();
let old_crowdloan = crowdloan::Funds::<Test>::get(para_1).unwrap();
assert_ok!(Crowdloan::edit(RuntimeOrigin::root(), para_1, 1234, 2, 3, 4, None));
let new_crowdloan = Crowdloan::funds(para_1).unwrap();
let new_crowdloan = crowdloan::Funds::<Test>::get(para_1).unwrap();
// Some things stay the same
assert_eq!(old_crowdloan.depositor, new_crowdloan.depositor);
@@ -1974,7 +1970,7 @@ mod tests {
assert_ok!(Crowdloan::contribute(RuntimeOrigin::signed(2), para_1, 100, None));
run_to_block(6);
assert_ok!(Crowdloan::poke(RuntimeOrigin::signed(1), para_1));
assert_eq!(Crowdloan::new_raise(), vec![para_1]);
assert_eq!(crowdloan::NewRaise::<Test>::get(), vec![para_1]);
assert_noop!(
Crowdloan::poke(RuntimeOrigin::signed(1), para_1),
Error::<Test>::AlreadyInNewRaise
@@ -348,7 +348,7 @@ const VALIDATORS: &[Sr25519Keyring] = &[
fn maybe_new_session(n: u32) {
if n % BLOCKS_PER_SESSION == 0 {
let session_index = shared::Pallet::<Test>::session_index() + 1;
let session_index = shared::CurrentSessionIndex::<Test>::get() + 1;
let validators_pub_keys = validators_public_keys(VALIDATORS);
shared::Pallet::<Test>::set_session_index(session_index);
@@ -464,7 +464,7 @@ fn basic_end_to_end_works() {
200 + offset, // Block End
None,
));
let fund_2 = Crowdloan::funds(ParaId::from(para_2)).unwrap();
let fund_2 = crowdloan::Funds::<Test>::get(ParaId::from(para_2)).unwrap();
let crowdloan_account = Crowdloan::fund_account_id(fund_2.fund_index);
// Auction ending begins on block 100 + offset, so we make a bid before then.
@@ -826,7 +826,7 @@ fn competing_bids() {
run_to_block(starting_block + 110);
// Appropriate Paras should have won slots
let fund_1 = Crowdloan::funds(ParaId::from(2000)).unwrap();
let fund_1 = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
let crowdloan_1 = Crowdloan::fund_account_id(fund_1.fund_index);
assert_eq!(
slots::Leases::<Test>::get(ParaId::from(2000)),
@@ -912,7 +912,7 @@ fn basic_swap_works() {
200, // Block End
None,
));
let fund = Crowdloan::funds(ParaId::from(2000)).unwrap();
let fund = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index);
// Bunch of contributions
@@ -932,7 +932,7 @@ fn basic_swap_works() {
// ----------------------------------------- para deposit --- crowdloan
let crowdloan_deposit = 100;
let para_id_deposit = <Test as paras_registrar::Config>::ParaDeposit::get();
let code_deposit = configuration::Pallet::<Test>::config().max_code_size *
let code_deposit = configuration::ActiveConfig::<Test>::get().max_code_size *
<Test as paras_registrar::Config>::DataDepositPerByte::get();
// Para 2000 has a genesis head size of 10.
@@ -944,16 +944,16 @@ fn basic_swap_works() {
assert_eq!(Balances::reserved_balance(&account_id(2)), para_id_deposit + code_deposit + 20);
assert_eq!(Balances::reserved_balance(&crowdloan_account), total);
// Crowdloan is appropriately set
assert!(Crowdloan::funds(ParaId::from(2000)).is_some());
assert!(Crowdloan::funds(ParaId::from(2001)).is_none());
assert!(crowdloan::Funds::<Test>::get(ParaId::from(2000)).is_some());
assert!(crowdloan::Funds::<Test>::get(ParaId::from(2001)).is_none());
// New leases will start on block 400
let lease_start_block = 400;
run_to_block(lease_start_block);
// Slots are won by Para 1
assert!(!Slots::lease(ParaId::from(2000)).is_empty());
assert!(Slots::lease(ParaId::from(2001)).is_empty());
assert!(!slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
assert!(slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());
// 2 sessions later it is a parachain
run_to_block(lease_start_block + 20);
@@ -986,11 +986,11 @@ fn basic_swap_works() {
assert_eq!(Balances::reserved_balance(&account_id(1)), crowdloan_deposit);
assert_eq!(Balances::reserved_balance(&account_id(2)), para_id_deposit + code_deposit + 20);
// Crowdloan ownership is swapped
assert!(Crowdloan::funds(ParaId::from(2000)).is_none());
assert!(Crowdloan::funds(ParaId::from(2001)).is_some());
assert!(crowdloan::Funds::<Test>::get(ParaId::from(2000)).is_none());
assert!(crowdloan::Funds::<Test>::get(ParaId::from(2001)).is_some());
// Slot is swapped
assert!(Slots::lease(ParaId::from(2000)).is_empty());
assert!(!Slots::lease(ParaId::from(2001)).is_empty());
assert!(slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
assert!(!slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());
// Cant dissolve
assert_noop!(
@@ -1061,7 +1061,9 @@ fn parachain_swap_works() {
assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Onboarding));
assert_eq!(
Balances::total_balance(&Crowdloan::fund_account_id(Crowdloan::next_fund_index())),
Balances::total_balance(&Crowdloan::fund_account_id(
crowdloan::NextFundIndex::<Test>::get()
)),
0
);
@@ -1090,7 +1092,7 @@ fn parachain_swap_works() {
end, // Block End
None,
));
let winner_fund = Crowdloan::funds(ParaId::from(winner)).unwrap();
let winner_fund = crowdloan::Funds::<Test>::get(ParaId::from(winner)).unwrap();
let crowdloan_account = Crowdloan::fund_account_id(winner_fund.fund_index);
// Bunch of contributions
@@ -1107,7 +1109,7 @@ fn parachain_swap_works() {
run_to_block(end);
// Crowdloan is appropriately set
assert!(Crowdloan::funds(ParaId::from(winner)).is_some());
assert!(crowdloan::Funds::<Test>::get(ParaId::from(winner)).is_some());
// New leases will start on block lease period index * 100
let lease_start_block = lease_period_index_start * 100;
@@ -1116,8 +1118,8 @@ fn parachain_swap_works() {
start_auction(4u32, 2000, 200);
// Slots are won by Para 1
assert!(!Slots::lease(ParaId::from(2000)).is_empty());
assert!(Slots::lease(ParaId::from(2001)).is_empty());
assert!(!slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
assert!(slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());
// 2 sessions later it is a parachain
run_to_block(4 * 100 + 20);
@@ -1127,8 +1129,8 @@ fn parachain_swap_works() {
// Let's repeat the process now for another parachain.
start_auction(6u32, 2001, 500);
// Slots are won by Para 1
assert!(!Slots::lease(ParaId::from(2000)).is_empty());
assert!(!Slots::lease(ParaId::from(2001)).is_empty());
assert!(!slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
assert!(!slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());
// 2 sessions later it is a parachain
run_to_block(6 * 100 + 20);
@@ -1145,22 +1147,22 @@ fn parachain_swap_works() {
assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)).len(), 6);
assert_eq!(slots::Leases::<Test>::get(ParaId::from(2001)).len(), 8);
let fund_2000 = Crowdloan::funds(ParaId::from(2000)).unwrap();
let fund_2000 = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
assert_eq!(fund_2000.fund_index, 0);
assert_eq!(
Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2000.fund_index)),
fund_2000.raised
);
let fund_2001 = Crowdloan::funds(ParaId::from(2001)).unwrap();
let fund_2001 = crowdloan::Funds::<Test>::get(ParaId::from(2001)).unwrap();
assert_eq!(fund_2001.fund_index, 1);
assert_eq!(
Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2001.fund_index)),
fund_2001.raised
);
assert_eq!(Slots::lease(ParaId::from(2000)).len(), 6);
assert_eq!(Slots::lease(ParaId::from(2001)).len(), 8);
assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)).len(), 6);
assert_eq!(slots::Leases::<Test>::get(ParaId::from(2001)).len(), 8);
// Now we swap them.
assert_ok!(Registrar::swap(
@@ -1182,14 +1184,14 @@ fn parachain_swap_works() {
));
// Crowdloan Swapped
let fund_2000 = Crowdloan::funds(ParaId::from(2000)).unwrap();
let fund_2000 = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
assert_eq!(fund_2000.fund_index, 1);
assert_eq!(
Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2000.fund_index)),
fund_2000.raised
);
let fund_2001 = Crowdloan::funds(ParaId::from(2001)).unwrap();
let fund_2001 = crowdloan::Funds::<Test>::get(ParaId::from(2001)).unwrap();
assert_eq!(fund_2001.fund_index, 0);
assert_eq!(
Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2001.fund_index)),
@@ -1197,8 +1199,8 @@ fn parachain_swap_works() {
);
// Slots Swapped
assert_eq!(Slots::lease(ParaId::from(2000)).len(), 8);
assert_eq!(Slots::lease(ParaId::from(2001)).len(), 6);
assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)).len(), 8);
assert_eq!(slots::Leases::<Test>::get(ParaId::from(2001)).len(), 6);
})
}
@@ -1263,7 +1265,7 @@ fn crowdloan_ending_period_bid() {
200, // Block End
None,
));
let fund = Crowdloan::funds(ParaId::from(2000)).unwrap();
let fund = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index);
// Bunch of contributions
@@ -1297,7 +1299,7 @@ fn crowdloan_ending_period_bid() {
winning[SlotRange::ZeroThree as u8 as usize] =
Some((crowdloan_account.clone(), ParaId::from(2000), total));
assert_eq!(Auctions::winning(0), Some(winning));
assert_eq!(auctions::Winning::<Test>::get(0), Some(winning));
run_to_block(ends_at + 1);
@@ -1310,7 +1312,7 @@ fn crowdloan_ending_period_bid() {
winning[SlotRange::ZeroOne as u8 as usize] = Some((account_id(2), ParaId::from(2001), 900));
winning[SlotRange::ZeroThree as u8 as usize] =
Some((crowdloan_account.clone(), ParaId::from(2000), total + 900));
assert_eq!(Auctions::winning(2), Some(winning));
assert_eq!(auctions::Winning::<Test>::get(2), Some(winning));
})
}
@@ -1615,7 +1617,7 @@ fn cant_bid_on_existing_lease_periods() {
400, // Long block end
None,
));
let fund = Crowdloan::funds(ParaId::from(2000)).unwrap();
let fund = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index);
// Bunch of contributions
@@ -1656,7 +1658,7 @@ fn cant_bid_on_existing_lease_periods() {
// Poke the crowdloan into `NewRaise`
assert_ok!(Crowdloan::poke(signed(1), ParaId::from(2000)));
assert_eq!(Crowdloan::new_raise(), vec![ParaId::from(2000)]);
assert_eq!(crowdloan::NewRaise::<Test>::get(), vec![ParaId::from(2000)]);
// Beginning of ending block.
run_to_block(starting_block + 100);
@@ -462,7 +462,7 @@ impl<T: Config> Registrar for Pallet<T> {
// All lease holding parachains. Ordered ascending by ParaId. On-demand parachains are not
// included.
fn parachains() -> Vec<ParaId> {
paras::Pallet::<T>::parachains()
paras::Parachains::<T>::get()
}
// Return if a para is a parathread (on-demand parachain)
@@ -530,14 +530,14 @@ impl<T: Config> Registrar for Pallet<T> {
#[cfg(any(feature = "runtime-benchmarks", test))]
fn worst_head_data() -> HeadData {
let max_head_size = configuration::Pallet::<T>::config().max_head_data_size;
let max_head_size = configuration::ActiveConfig::<T>::get().max_head_data_size;
assert!(max_head_size > 0, "max_head_data can't be zero for generating worst head data.");
vec![0u8; max_head_size as usize].into()
}
#[cfg(any(feature = "runtime-benchmarks", test))]
fn worst_validation_code() -> ValidationCode {
let max_code_size = configuration::Pallet::<T>::config().max_code_size;
let max_code_size = configuration::ActiveConfig::<T>::get().max_code_size;
assert!(max_code_size > 0, "max_code_size can't be zero for generating worst code data.");
let validation_code = vec![0u8; max_code_size as usize];
validation_code.into()
@@ -667,7 +667,7 @@ impl<T: Config> Pallet<T> {
validation_code: ValidationCode,
para_kind: ParaKind,
) -> Result<(ParaGenesisArgs, BalanceOf<T>), sp_runtime::DispatchError> {
let config = configuration::Pallet::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
ensure!(validation_code.0.len() >= MIN_CODE_SIZE as usize, Error::<T>::InvalidCode);
ensure!(validation_code.0.len() <= config.max_code_size as usize, Error::<T>::CodeTooLarge);
ensure!(
@@ -915,7 +915,7 @@ mod tests {
}
// Session change every 3 blocks.
if (b + 1) % BLOCKS_PER_SESSION == 0 {
let session_index = shared::Pallet::<Test>::session_index() + 1;
let session_index = shared::CurrentSessionIndex::<Test>::get() + 1;
let validators_pub_keys = VALIDATORS.iter().map(|v| v.public().into()).collect();
shared::Pallet::<Test>::set_session_index(session_index);
@@ -947,11 +947,11 @@ mod tests {
}
fn max_code_size() -> u32 {
Configuration::config().max_code_size
configuration::ActiveConfig::<Test>::get().max_code_size
}
fn max_head_size() -> u32 {
Configuration::config().max_head_data_size
configuration::ActiveConfig::<Test>::get().max_head_data_size
}
#[test]
@@ -146,9 +146,9 @@ pub mod pallet {
xcm: Box<xcm::opaque::VersionedXcm>,
) -> DispatchResult {
ensure_root(origin)?;
ensure!(<paras::Pallet<T>>::is_valid_para(id), Error::<T>::ParaDoesntExist);
let config = <configuration::Pallet<T>>::config();
<dmp::Pallet<T>>::queue_downward_message(&config, id, xcm.encode()).map_err(|e| match e
ensure!(paras::Pallet::<T>::is_valid_para(id), Error::<T>::ParaDoesntExist);
let config = configuration::ActiveConfig::<T>::get();
dmp::Pallet::<T>::queue_downward_message(&config, id, xcm.encode()).map_err(|e| match e
{
dmp::QueueDownwardMessageError::ExceedsMaxMessageSize =>
Error::<T>::ExceedsMaxMessageSize.into(),
@@ -170,13 +170,13 @@ pub mod pallet {
) -> DispatchResult {
ensure_root(origin)?;
<hrmp::Pallet<T>>::init_open_channel(
hrmp::Pallet::<T>::init_open_channel(
sender,
recipient,
max_capacity,
max_message_size,
)?;
<hrmp::Pallet<T>>::accept_open_channel(recipient, sender)?;
hrmp::Pallet::<T>::accept_open_channel(recipient, sender)?;
Ok(())
}
}
-1
View File
@@ -114,7 +114,6 @@ pub mod pallet {
///
/// It is illegal for a `None` value to trail in the list.
#[pallet::storage]
#[pallet::getter(fn lease)]
pub type Leases<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<Option<(T::AccountId, BalanceOf<T>)>>, ValueQuery>;
+3 -3
View File
@@ -116,11 +116,11 @@ where
// Downward message passing.
let xcm = msg.take().ok_or(MissingArgument)?;
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let para = id.into();
let price = P::price_for_delivery(para, &xcm);
let blob = W::wrap_version(&d, xcm).map_err(|()| DestinationUnsupported)?.encode();
<dmp::Pallet<T>>::can_queue_downward_message(&config, &para, &blob)
dmp::Pallet::<T>::can_queue_downward_message(&config, &para, &blob)
.map_err(Into::<SendError>::into)?;
Ok(((config, para, blob), price))
@@ -130,7 +130,7 @@ where
(config, para, blob): (HostConfiguration<BlockNumberFor<T>>, ParaId, Vec<u8>),
) -> Result<XcmHash, SendError> {
let hash = sp_io::hashing::blake2_256(&blob[..]);
<dmp::Pallet<T>>::queue_downward_message(&config, para, blob)
dmp::Pallet::<T>::queue_downward_message(&config, para, blob)
.map(|()| hash)
.map_err(|_| SendError::Transport(&"Error placing into DMP queue"))
}
@@ -256,7 +256,7 @@ pub mod pallet {
impl<T: Config> AssignmentProvider<BlockNumberFor<T>> for Pallet<T> {
fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
CoreDescriptors::<T>::mutate(core_idx, |core_state| {
Self::ensure_workload(now, core_idx, core_state);
@@ -324,7 +324,7 @@ impl<T: Config> AssignmentProvider<BlockNumberFor<T>> for Pallet<T> {
}
fn session_core_count() -> u32 {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
config.scheduler_params.num_cores
}
}
@@ -473,7 +473,7 @@ impl<T: Config> AssignCoretime for Pallet<T> {
let current_block = frame_system::Pallet::<T>::block_number();
// Add a new core and assign the para to it.
let mut config = <configuration::Pallet<T>>::config();
let mut config = configuration::ActiveConfig::<T>::get();
let core = config.scheduler_params.num_cores;
config.scheduler_params.num_cores.saturating_inc();
@@ -56,7 +56,7 @@ mod v1 {
let mut weight: Weight = Weight::zero();
// Migrate the current traffic value
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
QueueStatus::<T>::mutate(|mut queue_status| {
Pallet::<T>::update_spot_traffic(&config, &mut queue_status);
@@ -386,7 +386,7 @@ pub mod pallet {
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
// We need to update the spot traffic on block initialize in order to account for idle
// blocks.
QueueStatus::<T>::mutate(|queue_status| {
@@ -551,7 +551,7 @@ where
para_id: ParaId,
existence_requirement: ExistenceRequirement,
) -> DispatchResult {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
QueueStatus::<T>::mutate(|queue_status| {
Self::update_spot_traffic(&config, queue_status);
@@ -46,7 +46,7 @@ pub mod pallet {
impl<T: Config> AssignmentProvider<BlockNumberFor<T>> for Pallet<T> {
fn pop_assignment_for_core(core_idx: CoreIndex) -> Option<Assignment> {
<paras::Pallet<T>>::parachains()
paras::Parachains::<T>::get()
.get(core_idx.0 as usize)
.copied()
.map(Assignment::Bulk)
+12 -15
View File
@@ -201,7 +201,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
/// Maximum number of validators that may be part of a validator group.
pub(crate) fn fallback_max_validators() -> u32 {
configuration::Pallet::<T>::config().max_validators.unwrap_or(200)
configuration::ActiveConfig::<T>::get().max_validators.unwrap_or(200)
}
/// Maximum number of validators participating in parachains consensus (a.k.a. active
@@ -220,7 +220,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
/// Maximum number of validators per core (a.k.a. max validators per group). This value is used
/// if none is explicitly set on the builder.
pub(crate) fn fallback_max_validators_per_core() -> u32 {
configuration::Pallet::<T>::config()
configuration::ActiveConfig::<T>::get()
.scheduler_params
.max_validators_per_core
.unwrap_or(5)
@@ -268,7 +268,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
}
fn mock_head_data() -> HeadData {
let max_head_size = configuration::Pallet::<T>::config().max_head_data_size;
let max_head_size = configuration::ActiveConfig::<T>::get().max_head_data_size;
HeadData(vec![0xFF; max_head_size as usize])
}
@@ -459,19 +459,16 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
&Digest { logs: Vec::new() },
);
assert_eq!(<shared::Pallet<T>>::session_index(), target_session);
assert_eq!(shared::CurrentSessionIndex::<T>::get(), target_session);
// We need to refetch validators since they have been shuffled.
let validators_shuffled = session_info::Pallet::<T>::session_info(target_session)
.unwrap()
.validators
.clone();
let validators_shuffled =
session_info::Sessions::<T>::get(target_session).unwrap().validators.clone();
self.validators = Some(validators_shuffled);
self.block_number = block_number;
self.session = target_session;
assert_eq!(paras::Pallet::<T>::parachains().len(), total_cores - extra_cores);
assert_eq!(paras::Parachains::<T>::get().len(), total_cores - extra_cores);
self
}
@@ -550,7 +547,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
) -> Vec<BackedCandidate<T::Hash>> {
let validators =
self.validators.as_ref().expect("must have some validators prior to calling");
let config = configuration::Pallet::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
let mut current_core_idx = 0u32;
paras_with_backed_candidates
@@ -664,7 +661,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
// Check if the elastic scaling bit is set, if so we need to supply the core
// index in the generated candidate.
let core_idx = configuration::Pallet::<T>::config()
let core_idx = configuration::ActiveConfig::<T>::get()
.node_features
.get(FeatureIndex::ElasticScalingMVP as usize)
.map(|_the_bit| core_idx);
@@ -821,7 +818,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
// Mark all the used cores as occupied. We expect that there are
// `backed_and_concluding_paras` that are pending availability and that there are
// `used_cores - backed_and_concluding_paras ` which are about to be disputed.
let now = <frame_system::Pallet<T>>::block_number() + One::one();
let now = frame_system::Pallet::<T>::block_number() + One::one();
let mut core_idx = 0u32;
let elastic_paras = &builder.elastic_paras;
@@ -831,7 +828,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
.flat_map(|(para_id, _)| {
(0..elastic_paras.get(&para_id).cloned().unwrap_or(1))
.map(|_para_local_core_idx| {
let ttl = configuration::Pallet::<T>::config().scheduler_params.ttl;
let ttl = configuration::ActiveConfig::<T>::get().scheduler_params.ttl;
// Load an assignment into provider so that one is present to pop
let assignment =
<T as scheduler::Config>::AssignmentProvider::get_mock_assignment(
@@ -854,7 +851,7 @@ impl<T: paras_inherent::Config> BenchBuilder<T> {
.flat_map(|para_id| {
(0..elastic_paras.get(&para_id).cloned().unwrap_or(1))
.filter_map(|_para_local_core_idx| {
let ttl = configuration::Pallet::<T>::config().scheduler_params.ttl;
let ttl = configuration::ActiveConfig::<T>::get().scheduler_params.ttl;
// Load an assignment into provider so that one is present to pop
let assignment =
<T as scheduler::Config>::AssignmentProvider::get_mock_assignment(
@@ -540,8 +540,7 @@ pub mod pallet {
/// The active configuration for the current session.
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::getter(fn config)]
pub(crate) type ActiveConfig<T: Config> =
pub type ActiveConfig<T: Config> =
StorageValue<_, HostConfiguration<BlockNumberFor<T>>, ValueQuery>;
/// Pending configuration changes.
@@ -1311,7 +1310,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn initializer_on_new_session(
session_index: &SessionIndex,
) -> SessionChangeOutcome<BlockNumberFor<T>> {
let pending_configs = <PendingConfigs<T>>::get();
let pending_configs = PendingConfigs::<T>::get();
let prev_config = ActiveConfig::<T>::get();
// No pending configuration changes, so we're done.
@@ -1338,7 +1337,7 @@ impl<T: Config> Pallet<T> {
ActiveConfig::<T>::put(new_config);
}
<PendingConfigs<T>>::put(future);
PendingConfigs::<T>::put(future);
SessionChangeOutcome { prev_config, new_config }
}
@@ -1373,7 +1372,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn schedule_config_update(
updater: impl FnOnce(&mut HostConfiguration<BlockNumberFor<T>>),
) -> DispatchResult {
let mut pending_configs = <PendingConfigs<T>>::get();
let mut pending_configs = PendingConfigs::<T>::get();
// 1. pending_configs = [] No pending configuration changes.
//
@@ -1404,7 +1403,7 @@ impl<T: Config> Pallet<T> {
let mut base_config = pending_configs
.last()
.map(|(_, config)| config.clone())
.unwrap_or_else(Self::config);
.unwrap_or_else(ActiveConfig::<T>::get);
let base_config_consistent = base_config.check_consistency().is_ok();
// Now, we need to decide what the new configuration should be.
@@ -1456,7 +1455,7 @@ impl<T: Config> Pallet<T> {
pending_configs.push((scheduled_session, new_config));
}
<PendingConfigs<T>>::put(pending_configs);
PendingConfigs::<T>::put(pending_configs);
Ok(())
}
@@ -15,7 +15,10 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use crate::mock::{new_test_ext, Configuration, ParasShared, RuntimeOrigin, Test};
use crate::{
configuration,
mock::{new_test_ext, Configuration, ParasShared, RuntimeOrigin, Test},
};
use bitvec::{bitvec, prelude::Lsb0};
use frame_support::{assert_err, assert_noop, assert_ok};
@@ -30,7 +33,7 @@ fn on_new_session(session_index: SessionIndex) -> (HostConfiguration<u32>, HostC
#[test]
fn default_is_consistent() {
new_test_ext(Default::default()).execute_with(|| {
Configuration::config().panic_if_not_consistent();
configuration::ActiveConfig::<Test>::get().panic_if_not_consistent();
});
}
@@ -63,7 +66,7 @@ fn initializer_on_new_session() {
#[test]
fn config_changes_after_2_session_boundary() {
new_test_ext(Default::default()).execute_with(|| {
let old_config = Configuration::config();
let old_config = configuration::ActiveConfig::<Test>::get();
let mut config = old_config.clone();
config.validation_upgrade_delay = 100;
assert!(old_config != config);
@@ -72,18 +75,18 @@ fn config_changes_after_2_session_boundary() {
// Verify that the current configuration has not changed and that there is a scheduled
// change for the SESSION_DELAY sessions in advance.
assert_eq!(Configuration::config(), old_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), old_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(2, config.clone())]);
on_new_session(1);
// One session has passed, we should be still waiting for the pending configuration.
assert_eq!(Configuration::config(), old_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), old_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(2, config.clone())]);
on_new_session(2);
assert_eq!(Configuration::config(), config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), config);
assert_eq!(PendingConfigs::<Test>::get(), vec![]);
})
}
@@ -91,7 +94,7 @@ fn config_changes_after_2_session_boundary() {
#[test]
fn consecutive_changes_within_one_session() {
new_test_ext(Default::default()).execute_with(|| {
let old_config = Configuration::config();
let old_config = configuration::ActiveConfig::<Test>::get();
let mut config = old_config.clone();
config.validation_upgrade_delay = 100;
config.validation_upgrade_cooldown = 100;
@@ -99,17 +102,17 @@ fn consecutive_changes_within_one_session() {
assert_ok!(Configuration::set_validation_upgrade_delay(RuntimeOrigin::root(), 100));
assert_ok!(Configuration::set_validation_upgrade_cooldown(RuntimeOrigin::root(), 100));
assert_eq!(Configuration::config(), old_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), old_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(2, config.clone())]);
on_new_session(1);
assert_eq!(Configuration::config(), old_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), old_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(2, config.clone())]);
on_new_session(2);
assert_eq!(Configuration::config(), config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), config);
assert_eq!(PendingConfigs::<Test>::get(), vec![]);
});
}
@@ -117,7 +120,7 @@ fn consecutive_changes_within_one_session() {
#[test]
fn pending_next_session_but_we_upgrade_once_more() {
new_test_ext(Default::default()).execute_with(|| {
let initial_config = Configuration::config();
let initial_config = configuration::ActiveConfig::<Test>::get();
let intermediate_config =
HostConfiguration { validation_upgrade_delay: 100, ..initial_config.clone() };
let final_config = HostConfiguration {
@@ -127,7 +130,7 @@ fn pending_next_session_but_we_upgrade_once_more() {
};
assert_ok!(Configuration::set_validation_upgrade_delay(RuntimeOrigin::root(), 100));
assert_eq!(Configuration::config(), initial_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), initial_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(2, intermediate_config.clone())]);
on_new_session(1);
@@ -137,7 +140,7 @@ fn pending_next_session_but_we_upgrade_once_more() {
assert_ok!(Configuration::set_validation_upgrade_cooldown(RuntimeOrigin::root(), 99));
// This should result in yet another configuration change scheduled.
assert_eq!(Configuration::config(), initial_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), initial_config);
assert_eq!(
PendingConfigs::<Test>::get(),
vec![(2, intermediate_config.clone()), (3, final_config.clone())]
@@ -145,12 +148,12 @@ fn pending_next_session_but_we_upgrade_once_more() {
on_new_session(2);
assert_eq!(Configuration::config(), intermediate_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), intermediate_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(3, final_config.clone())]);
on_new_session(3);
assert_eq!(Configuration::config(), final_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), final_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![]);
});
}
@@ -158,7 +161,7 @@ fn pending_next_session_but_we_upgrade_once_more() {
#[test]
fn scheduled_session_config_update_while_next_session_pending() {
new_test_ext(Default::default()).execute_with(|| {
let initial_config = Configuration::config();
let initial_config = configuration::ActiveConfig::<Test>::get();
let intermediate_config =
HostConfiguration { validation_upgrade_delay: 100, ..initial_config.clone() };
let final_config = HostConfiguration {
@@ -169,7 +172,7 @@ fn scheduled_session_config_update_while_next_session_pending() {
};
assert_ok!(Configuration::set_validation_upgrade_delay(RuntimeOrigin::root(), 100));
assert_eq!(Configuration::config(), initial_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), initial_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(2, intermediate_config.clone())]);
on_new_session(1);
@@ -180,7 +183,7 @@ fn scheduled_session_config_update_while_next_session_pending() {
assert_ok!(Configuration::set_code_retention_period(RuntimeOrigin::root(), 98));
// This should result in yet another configuration change scheduled.
assert_eq!(Configuration::config(), initial_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), initial_config);
assert_eq!(
PendingConfigs::<Test>::get(),
vec![(2, intermediate_config.clone()), (3, final_config.clone())]
@@ -188,12 +191,12 @@ fn scheduled_session_config_update_while_next_session_pending() {
on_new_session(2);
assert_eq!(Configuration::config(), intermediate_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), intermediate_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![(3, final_config.clone())]);
on_new_session(3);
assert_eq!(Configuration::config(), final_config);
assert_eq!(configuration::ActiveConfig::<Test>::get(), final_config);
assert_eq!(PendingConfigs::<Test>::get(), vec![]);
});
}
@@ -261,14 +264,14 @@ fn consistency_bypass_works() {
assert_ok!(Configuration::set_max_code_size(RuntimeOrigin::root(), MAX_CODE_SIZE + 1));
assert_eq!(
Configuration::config().max_code_size,
configuration::ActiveConfig::<Test>::get().max_code_size,
HostConfiguration::<u32>::default().max_code_size
);
on_new_session(1);
on_new_session(2);
assert_eq!(Configuration::config().max_code_size, MAX_CODE_SIZE + 1);
assert_eq!(configuration::ActiveConfig::<Test>::get().max_code_size, MAX_CODE_SIZE + 1);
});
}
@@ -113,7 +113,7 @@ mod v_coretime {
}
let legacy_paras = paras::Parachains::<T>::get();
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let total_core_count = config.scheduler_params.num_cores + legacy_paras.len() as u32;
let dmp_queue_size =
@@ -156,9 +156,9 @@ mod v_coretime {
SendXcm: xcm::v4::SendXcm,
LegacyLease: GetLegacyLease<BlockNumberFor<T>>,
>() -> Weight {
let legacy_paras = paras::Pallet::<T>::parachains();
let legacy_paras = paras::Parachains::<T>::get();
let legacy_count = legacy_paras.len() as u32;
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
for (core, para_id) in legacy_paras.into_iter().enumerate() {
let r = assigner_coretime::Pallet::<T>::assign_core(
CoreIndex(core as u32),
@@ -175,7 +175,7 @@ mod v_coretime {
}
}
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
// num_cores was on_demand_cores until now:
for on_demand in 0..config.scheduler_params.num_cores {
let core = CoreIndex(legacy_count.saturating_add(on_demand as _));
@@ -212,7 +212,7 @@ mod v_coretime {
SendXcm: xcm::v4::SendXcm,
LegacyLease: GetLegacyLease<BlockNumberFor<T>>,
>() -> result::Result<(), SendError> {
let legacy_paras = paras::Pallet::<T>::parachains();
let legacy_paras = paras::Parachains::<T>::get();
let legacy_paras_count = legacy_paras.len();
let (system_chains, lease_holding): (Vec<_>, Vec<_>) =
legacy_paras.into_iter().partition(IsSystem::is_system);
@@ -246,8 +246,10 @@ mod v_coretime {
Some(mk_coretime_call(crate::coretime::CoretimeCalls::SetLease(p.into(), time_slice)))
});
let core_count: u16 =
configuration::Pallet::<T>::config().scheduler_params.num_cores.saturated_into();
let core_count: u16 = configuration::ActiveConfig::<T>::get()
.scheduler_params
.num_cores
.saturated_into();
let set_core_count = iter::once(mk_coretime_call(
crate::coretime::CoretimeCalls::NotifyCoreCount(core_count),
));
+26 -27
View File
@@ -432,8 +432,7 @@ pub mod pallet {
/// and its value indicates the last valid block number in the chain.
/// It can only be set back to `None` by governance intervention.
#[pallet::storage]
#[pallet::getter(fn last_valid_block)]
pub(super) type Frozen<T: Config> = StorageValue<_, Option<BlockNumberFor<T>>, ValueQuery>;
pub type Frozen<T: Config> = StorageValue<_, Option<BlockNumberFor<T>>, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub fn deposit_event)]
@@ -865,7 +864,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn initializer_on_new_session(
notification: &SessionChangeNotification<BlockNumberFor<T>>,
) {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
if notification.session_index <= config.dispute_period + 1 {
return
@@ -883,14 +882,14 @@ impl<T: Config> Pallet<T> {
for to_prune in to_prune {
// This should be small, as disputes are rare, so `None` is fine.
#[allow(deprecated)]
<Disputes<T>>::remove_prefix(to_prune, None);
Disputes::<T>::remove_prefix(to_prune, None);
#[allow(deprecated)]
<BackersOnDisputes<T>>::remove_prefix(to_prune, None);
BackersOnDisputes::<T>::remove_prefix(to_prune, None);
// This is larger, and will be extracted to the `shared` pallet for more proper
// pruning. TODO: https://github.com/paritytech/polkadot/issues/3469
#[allow(deprecated)]
<Included<T>>::remove_prefix(to_prune, None);
Included::<T>::remove_prefix(to_prune, None);
}
*last_pruned = Some(pruning_target);
@@ -910,7 +909,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn process_checked_multi_dispute_data(
statement_sets: &CheckedMultiDisputeStatementSet,
) -> Result<Vec<(SessionIndex, CandidateHash)>, DispatchError> {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let mut fresh = Vec::with_capacity(statement_sets.len());
for statement_set in statement_sets {
@@ -943,22 +942,22 @@ impl<T: Config> Pallet<T> {
// Dispute statement sets on any dispute which concluded
// before this point are to be rejected.
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
let oldest_accepted = now.saturating_sub(post_conclusion_acceptance_period);
// Load session info to access validators
let session_info = match <session_info::Pallet<T>>::session_info(set.session) {
let session_info = match session_info::Sessions::<T>::get(set.session) {
Some(s) => s,
None => return StatementSetFilter::RemoveAll,
};
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let n_validators = session_info.validators.len();
// Check for ancient.
let dispute_state = {
if let Some(dispute_state) = <Disputes<T>>::get(&set.session, &set.candidate_hash) {
if let Some(dispute_state) = Disputes::<T>::get(&set.session, &set.candidate_hash) {
if dispute_state.concluded_at.as_ref().map_or(false, |c| c < &oldest_accepted) {
return StatementSetFilter::RemoveAll
}
@@ -976,7 +975,7 @@ impl<T: Config> Pallet<T> {
};
let backers =
<BackersOnDisputes<T>>::get(&set.session, &set.candidate_hash).unwrap_or_default();
BackersOnDisputes::<T>::get(&set.session, &set.candidate_hash).unwrap_or_default();
// Check and import all votes.
let summary = {
@@ -1061,13 +1060,13 @@ impl<T: Config> Pallet<T> {
) -> Result<bool, DispatchError> {
// Dispute statement sets on any dispute which concluded
// before this point are to be rejected.
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
let oldest_accepted = now.saturating_sub(dispute_post_conclusion_acceptance_period);
let set = set.as_ref();
// Load session info to access validators
let session_info = match <session_info::Pallet<T>>::session_info(set.session) {
let session_info = match session_info::Sessions::<T>::get(set.session) {
Some(s) => s,
None => return Err(Error::<T>::AncientDisputeStatement.into()),
};
@@ -1076,7 +1075,7 @@ impl<T: Config> Pallet<T> {
// Check for ancient.
let (fresh, dispute_state) = {
if let Some(dispute_state) = <Disputes<T>>::get(&set.session, &set.candidate_hash) {
if let Some(dispute_state) = Disputes::<T>::get(&set.session, &set.candidate_hash) {
ensure!(
dispute_state.concluded_at.as_ref().map_or(true, |c| c >= &oldest_accepted),
Error::<T>::AncientDisputeStatement,
@@ -1097,7 +1096,7 @@ impl<T: Config> Pallet<T> {
};
let backers =
<BackersOnDisputes<T>>::get(&set.session, &set.candidate_hash).unwrap_or_default();
BackersOnDisputes::<T>::get(&set.session, &set.candidate_hash).unwrap_or_default();
// Import all votes. They were pre-checked.
let summary = {
@@ -1127,7 +1126,7 @@ impl<T: Config> Pallet<T> {
let backers = summary.backers;
// Reject statements with no accompanying backing votes.
ensure!(!backers.is_empty(), Error::<T>::MissingBackingVotes);
<BackersOnDisputes<T>>::insert(&set.session, &set.candidate_hash, backers.clone());
BackersOnDisputes::<T>::insert(&set.session, &set.candidate_hash, backers.clone());
// AUDIT: from now on, no error should be returned.
let DisputeStatementSet { ref session, ref candidate_hash, .. } = set;
@@ -1135,7 +1134,7 @@ impl<T: Config> Pallet<T> {
let candidate_hash = *candidate_hash;
if fresh {
let is_local = <Included<T>>::contains_key(&session, &candidate_hash);
let is_local = Included::<T>::contains_key(&session, &candidate_hash);
Self::deposit_event(Event::DisputeInitiated(
candidate_hash,
@@ -1185,12 +1184,12 @@ impl<T: Config> Pallet<T> {
);
}
<Disputes<T>>::insert(&session, &candidate_hash, &summary.state);
Disputes::<T>::insert(&session, &candidate_hash, &summary.state);
// Freeze if the INVALID votes against some local candidate are above the byzantine
// threshold
if summary.new_flags.contains(DisputeStateFlags::AGAINST_BYZANTINE) {
if let Some(revert_to) = <Included<T>>::get(&session, &candidate_hash) {
if let Some(revert_to) = Included::<T>::get(&session, &candidate_hash) {
Self::revert_and_freeze(revert_to);
}
}
@@ -1201,7 +1200,7 @@ impl<T: Config> Pallet<T> {
#[allow(unused)]
pub(crate) fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumberFor<T>>)>
{
<Disputes<T>>::iter().collect()
Disputes::<T>::iter().collect()
}
pub(crate) fn note_included(
@@ -1215,9 +1214,9 @@ impl<T: Config> Pallet<T> {
let revert_to = included_in - One::one();
<Included<T>>::insert(&session, &candidate_hash, revert_to);
Included::<T>::insert(&session, &candidate_hash, revert_to);
if let Some(state) = <Disputes<T>>::get(&session, candidate_hash) {
if let Some(state) = Disputes::<T>::get(&session, candidate_hash) {
if has_supermajority_against(&state) {
Self::revert_and_freeze(revert_to);
}
@@ -1228,22 +1227,22 @@ impl<T: Config> Pallet<T> {
session: SessionIndex,
candidate_hash: CandidateHash,
) -> Option<BlockNumberFor<T>> {
<Included<T>>::get(session, candidate_hash)
Included::<T>::get(session, candidate_hash)
}
pub(crate) fn concluded_invalid(session: SessionIndex, candidate_hash: CandidateHash) -> bool {
<Disputes<T>>::get(&session, &candidate_hash).map_or(false, |dispute| {
Disputes::<T>::get(&session, &candidate_hash).map_or(false, |dispute| {
// A dispute that has concluded with supermajority-against.
has_supermajority_against(&dispute)
})
}
pub(crate) fn is_frozen() -> bool {
Self::last_valid_block().is_some()
Frozen::<T>::get().is_some()
}
pub(crate) fn revert_and_freeze(revert_to: BlockNumberFor<T>) {
if Self::last_valid_block().map_or(true, |last| last > revert_to) {
if Frozen::<T>::get().map_or(true, |last| last > revert_to) {
Frozen::<T>::set(Some(revert_to));
// The `Revert` log is about reverting a block, not reverting to a block.
@@ -187,13 +187,13 @@ where
validators: impl IntoIterator<Item = ValidatorIndex>,
) -> Option<Vec<IdentificationTuple<T>>> {
// We use `ValidatorSet::session_index` and not
// `shared::Pallet<T>::session_index()` because at the first block of a new era,
// `shared::CurrentSessionIndex::<T>::get()` because at the first block of a new era,
// the `IdentificationOf` of a validator in the previous session might be
// missing, while `shared` pallet would return the same session index as being
// updated at the end of the block.
let current_session = T::ValidatorSet::session_index();
if session_index == current_session {
let account_keys = crate::session_info::Pallet::<T>::account_keys(session_index);
let account_keys = crate::session_info::AccountKeys::<T>::get(session_index);
let account_ids = account_keys.defensive_unwrap_or_default();
let fully_identified = validators
@@ -232,7 +232,7 @@ where
return
}
let session_info = crate::session_info::Pallet::<T>::session_info(session_index);
let session_info = crate::session_info::Sessions::<T>::get(session_index);
let session_info = match session_info.defensive_proof(DEFENSIVE_PROOF) {
Some(info) => info,
None => return,
@@ -544,7 +544,7 @@ impl<T: Config> Pallet<T> {
// fine.
const REMOVE_LIMIT: u32 = u32::MAX;
let config = <crate::configuration::Pallet<T>>::config();
let config = crate::configuration::ActiveConfig::<T>::get();
if session_index <= config.dispute_period + 1 {
return
}
@@ -83,8 +83,8 @@ where
}
initializer::Pallet::<T>::on_finalize(BlockNumberFor::<T>::one());
let session_index = crate::shared::Pallet::<T>::session_index();
let session_info = crate::session_info::Pallet::<T>::session_info(session_index);
let session_index = crate::shared::CurrentSessionIndex::<T>::get();
let session_info = crate::session_info::Sessions::<T>::get(session_index);
let session_info = session_info.unwrap();
let validator_id = session_info.validators.get(ValidatorIndex::from(0)).unwrap().clone();
let key = (PARACHAIN_KEY_TYPE_ID, validator_id.clone());
@@ -95,7 +95,7 @@ where
pallet_session::Pallet::<T>::rotate_session();
initializer::Pallet::<T>::on_finalize(BlockNumberFor::<T>::one());
let idx = crate::shared::Pallet::<T>::session_index();
let idx = crate::shared::CurrentSessionIndex::<T>::get();
assert!(
idx > session_index,
"session rotation should work for parachain pallets: {} <= {}",
@@ -37,7 +37,7 @@ const VOTE_AGAINST: VoteKind = VoteKind::Invalid;
const VOTE_BACKING: VoteKind = VoteKind::Backing;
fn filter_dispute_set(stmts: MultiDisputeStatementSet) -> CheckedMultiDisputeStatementSet {
let config = <configuration::Pallet<Test>>::config();
let config = configuration::ActiveConfig::<Test>::get();
let post_conclusion_acceptance_period = config.dispute_post_conclusion_acceptance_period;
stmts
@@ -1985,7 +1985,7 @@ fn deduplication_and_sorting_works() {
fn apply_filter_all<T: Config, I: IntoIterator<Item = DisputeStatementSet>>(
sets: I,
) -> Vec<CheckedDisputeStatementSet> {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let post_conclusion_acceptance_period = config.dispute_post_conclusion_acceptance_period;
let mut acc = Vec::<CheckedDisputeStatementSet>::new();
@@ -2203,7 +2203,7 @@ fn filter_removes_concluded_ancient() {
let candidate_hash_a = CandidateHash(sp_core::H256::repeat_byte(1));
let candidate_hash_b = CandidateHash(sp_core::H256::repeat_byte(2));
<Disputes<Test>>::insert(
Disputes::<Test>::insert(
&1,
&candidate_hash_a,
DisputeState {
@@ -2214,7 +2214,7 @@ fn filter_removes_concluded_ancient() {
},
);
<Disputes<Test>>::insert(
Disputes::<Test>::insert(
&1,
&candidate_hash_b,
DisputeState {
+3 -3
View File
@@ -226,7 +226,7 @@ impl<T: Config> Pallet<T> {
}
let inbound =
InboundDownwardMessage { msg, sent_at: <frame_system::Pallet<T>>::block_number() };
InboundDownwardMessage { msg, sent_at: frame_system::Pallet::<T>::block_number() };
// obtain the new link in the MQC and update the head.
DownwardMessageQueueHeads::<T>::mutate(para, |head| {
@@ -346,14 +346,14 @@ impl<T: Config> FeeTracker for Pallet<T> {
}
fn increase_fee_factor(id: Self::Id, message_size_factor: FixedU128) -> FixedU128 {
<DeliveryFeeFactor<T>>::mutate(id, |f| {
DeliveryFeeFactor::<T>::mutate(id, |f| {
*f = f.saturating_mul(EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor));
*f
})
}
fn decrease_fee_factor(id: Self::Id) -> FixedU128 {
<DeliveryFeeFactor<T>>::mutate(id, |f| {
DeliveryFeeFactor::<T>::mutate(id, |f| {
*f = InitialFactor::get().max(*f / EXPONENTIAL_FEE_BASE);
*f
})
+2 -2
View File
@@ -17,7 +17,7 @@
use super::*;
use crate::{
configuration::ActiveConfig,
mock::{new_test_ext, Configuration, Dmp, MockGenesisConfig, Paras, System, Test},
mock::{new_test_ext, Dmp, MockGenesisConfig, Paras, System, Test},
};
use frame_support::assert_ok;
use hex_literal::hex;
@@ -58,7 +58,7 @@ fn queue_downward_message(
para_id: ParaId,
msg: DownwardMessage,
) -> Result<(), QueueDownwardMessageError> {
Dmp::queue_downward_message(&Configuration::config(), para_id, msg)
Dmp::queue_downward_message(&configuration::ActiveConfig::<Test>::get(), para_id, msg)
}
#[test]
+17 -17
View File
@@ -597,7 +597,7 @@ pub mod pallet {
Error::<T>::WrongWitness
);
let host_config = configuration::Pallet::<T>::config();
let host_config = configuration::ActiveConfig::<T>::get();
Self::process_hrmp_open_channel_requests(&host_config);
Ok(())
}
@@ -724,7 +724,7 @@ pub mod pallet {
Error::<T>::ChannelCreationNotAuthorized
);
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let max_message_size = config.hrmp_channel_max_message_size;
let max_capacity = config.hrmp_channel_max_capacity;
@@ -761,7 +761,7 @@ pub mod pallet {
let channel_id = HrmpChannelId { sender, recipient };
let is_system = sender.is_system() || recipient.is_system();
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
// Channels with and amongst the system do not require a deposit.
let (new_sender_deposit, new_recipient_deposit) = if is_system {
@@ -840,7 +840,7 @@ pub mod pallet {
}
fn initialize_storage<T: Config>(preopen_hrmp_channels: &[(ParaId, ParaId, u32, u32)]) {
let host_config = configuration::Pallet::<T>::config();
let host_config = configuration::ActiveConfig::<T>::get();
for &(sender, recipient, max_capacity, max_message_size) in preopen_hrmp_channels {
if let Err(err) =
preopen_hrmp_channel::<T>(sender, recipient, max_capacity, max_message_size)
@@ -848,7 +848,7 @@ fn initialize_storage<T: Config>(preopen_hrmp_channels: &[(ParaId, ParaId, u32,
panic!("failed to initialize the genesis storage: {:?}", err);
}
}
<Pallet<T>>::process_hrmp_open_channel_requests(&host_config);
Pallet::<T>::process_hrmp_open_channel_requests(&host_config);
}
fn preopen_hrmp_channel<T: Config>(
@@ -857,8 +857,8 @@ fn preopen_hrmp_channel<T: Config>(
max_capacity: u32,
max_message_size: u32,
) -> DispatchResult {
<Pallet<T>>::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
<Pallet<T>>::accept_open_channel(recipient, sender)?;
Pallet::<T>::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
Pallet::<T>::accept_open_channel(recipient, sender)?;
Ok(())
}
@@ -1018,8 +1018,8 @@ impl<T: Config> Pallet<T> {
let recipient_deposit = if system_channel { 0 } else { config.hrmp_recipient_deposit };
if request.confirmed {
if <paras::Pallet<T>>::is_valid_para(channel_id.sender) &&
<paras::Pallet<T>>::is_valid_para(channel_id.recipient)
if paras::Pallet::<T>::is_valid_para(channel_id.sender) &&
paras::Pallet::<T>::is_valid_para(channel_id.recipient)
{
HrmpChannels::<T>::insert(
&channel_id,
@@ -1310,7 +1310,7 @@ impl<T: Config> Pallet<T> {
/// Returns the amount of weight consumed.
pub(crate) fn queue_outbound_hrmp(sender: ParaId, out_hrmp_msgs: HorizontalMessages) -> Weight {
let mut weight = Weight::zero();
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
for out_msg in out_hrmp_msgs {
let channel_id = HrmpChannelId { sender, recipient: out_msg.recipient };
@@ -1387,11 +1387,11 @@ impl<T: Config> Pallet<T> {
) -> DispatchResult {
ensure!(origin != recipient, Error::<T>::OpenHrmpChannelToSelf);
ensure!(
<paras::Pallet<T>>::is_valid_para(recipient),
paras::Pallet::<T>::is_valid_para(recipient),
Error::<T>::OpenHrmpChannelInvalidRecipient,
);
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
ensure!(proposed_max_capacity > 0, Error::<T>::OpenHrmpChannelZeroCapacity);
ensure!(
proposed_max_capacity <= config.hrmp_channel_max_capacity,
@@ -1459,7 +1459,7 @@ impl<T: Config> Pallet<T> {
.encode()
};
if let Err(dmp::QueueDownwardMessageError::ExceedsMaxMessageSize) =
<dmp::Pallet<T>>::queue_downward_message(&config, recipient, notification_bytes)
dmp::Pallet::<T>::queue_downward_message(&config, recipient, notification_bytes)
{
// this should never happen unless the max downward message size is configured to a
// jokingly small number.
@@ -1485,7 +1485,7 @@ impl<T: Config> Pallet<T> {
// check if by accepting this open channel request, this parachain would exceed the
// number of inbound channels.
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let channel_num_limit = config.hrmp_max_parachain_inbound_channels;
let ingress_cnt = HrmpIngressChannelsIndex::<T>::decode_len(&origin).unwrap_or(0) as u32;
let accepted_cnt = HrmpAcceptedChannelRequestCount::<T>::get(&origin);
@@ -1517,7 +1517,7 @@ impl<T: Config> Pallet<T> {
VersionedXcm::from(xcm).encode()
};
if let Err(dmp::QueueDownwardMessageError::ExceedsMaxMessageSize) =
<dmp::Pallet<T>>::queue_downward_message(&config, sender, notification_bytes)
dmp::Pallet::<T>::queue_downward_message(&config, sender, notification_bytes)
{
// this should never happen unless the max downward message size is configured to an
// jokingly small number.
@@ -1580,7 +1580,7 @@ impl<T: Config> Pallet<T> {
HrmpCloseChannelRequests::<T>::insert(&channel_id, ());
HrmpCloseChannelRequestsList::<T>::append(channel_id.clone());
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let notification_bytes = {
use parity_scale_codec::Encode as _;
use xcm::opaque::{latest::prelude::*, VersionedXcm};
@@ -1595,7 +1595,7 @@ impl<T: Config> Pallet<T> {
let opposite_party =
if origin == channel_id.sender { channel_id.recipient } else { channel_id.sender };
if let Err(dmp::QueueDownwardMessageError::ExceedsMaxMessageSize) =
<dmp::Pallet<T>>::queue_downward_message(&config, opposite_party, notification_bytes)
dmp::Pallet::<T>::queue_downward_message(&config, opposite_party, notification_bytes)
{
// this should never happen unless the max downward message size is configured to an
// jokingly small number.
@@ -71,7 +71,7 @@ fn establish_para_connection<T: Config>(
where
<T as frame_system::Config>::RuntimeOrigin: From<crate::Origin>,
{
let config = Configuration::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
let ed = T::Currency::minimum_balance();
let deposit: BalanceOf<T> = config.hrmp_sender_deposit.unique_saturated_into();
let capacity = config.hrmp_channel_max_capacity;
@@ -111,7 +111,7 @@ where
return output
}
Hrmp::<T>::process_hrmp_open_channel_requests(&Configuration::<T>::config());
Hrmp::<T>::process_hrmp_open_channel_requests(&configuration::ActiveConfig::<T>::get());
if matches!(until, ParachainSetupStep::Established) {
return output
}
@@ -156,13 +156,14 @@ mod benchmarks {
// make sure para is registered, and has enough balance.
let ed = T::Currency::minimum_balance();
let deposit: BalanceOf<T> =
Configuration::<T>::config().hrmp_sender_deposit.unique_saturated_into();
let deposit: BalanceOf<T> = configuration::ActiveConfig::<T>::get()
.hrmp_sender_deposit
.unique_saturated_into();
register_parachain_with_balance::<T>(sender_id, deposit + ed);
register_parachain_with_balance::<T>(recipient_id, deposit + ed);
let capacity = Configuration::<T>::config().hrmp_channel_max_capacity;
let message_size = Configuration::<T>::config().hrmp_channel_max_message_size;
let capacity = configuration::ActiveConfig::<T>::get().hrmp_channel_max_capacity;
let message_size = configuration::ActiveConfig::<T>::get().hrmp_channel_max_message_size;
#[extrinsic_call]
_(sender_origin, recipient_id, capacity, message_size);
@@ -228,7 +229,7 @@ mod benchmarks {
// .. and enact it.
Configuration::<T>::initializer_on_new_session(&Shared::<T>::scheduled_session());
let config = Configuration::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
let deposit: BalanceOf<T> = config.hrmp_sender_deposit.unique_saturated_into();
let para: ParaId = 1u32.into();
@@ -360,7 +361,7 @@ mod benchmarks {
assert_eq!(HrmpOpenChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32, c);
let outgoing = (0..c).map(|id| (id + PREFIX_1).into()).collect::<Vec<ParaId>>();
let config = Configuration::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
#[block]
{
@@ -383,13 +384,14 @@ mod benchmarks {
// Make sure para is registered. The sender does actually need the normal deposit because it
// is first going the "init" route.
let ed = T::Currency::minimum_balance();
let sender_deposit: BalanceOf<T> =
Configuration::<T>::config().hrmp_sender_deposit.unique_saturated_into();
let sender_deposit: BalanceOf<T> = configuration::ActiveConfig::<T>::get()
.hrmp_sender_deposit
.unique_saturated_into();
register_parachain_with_balance::<T>(sender_id, sender_deposit + ed);
register_parachain_with_balance::<T>(recipient_id, Zero::zero());
let capacity = Configuration::<T>::config().hrmp_channel_max_capacity;
let message_size = Configuration::<T>::config().hrmp_channel_max_message_size;
let capacity = configuration::ActiveConfig::<T>::get().hrmp_channel_max_capacity;
let message_size = configuration::ActiveConfig::<T>::get().hrmp_channel_max_message_size;
let channel_id = HrmpChannelId { sender: sender_id, recipient: recipient_id };
if c == 1 {
@@ -436,7 +438,7 @@ mod benchmarks {
let recipient_id: ParaId = 2u32.into();
let caller: T::AccountId = whitelisted_caller();
let config = Configuration::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
// make sure para is registered, and has zero balance.
register_parachain_with_balance::<T>(sender_id, Zero::zero());
@@ -466,7 +468,7 @@ mod benchmarks {
let channel_id = HrmpChannelId { sender: sender_id, recipient: recipient_id };
let caller: T::AccountId = whitelisted_caller();
let config = Configuration::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
// make sure para is registered, and has balance to reserve.
let ed = T::Currency::minimum_balance();
+12 -9
View File
@@ -19,17 +19,20 @@
// both paras are system chains, then they are also configured to the system's max configuration.
use super::*;
use crate::mock::{
use crate::{
mock::{
deregister_parachain, new_test_ext, register_parachain, register_parachain_with_balance,
Configuration, Hrmp, MockGenesisConfig, Paras, ParasShared, RuntimeEvent as MockEvent,
RuntimeOrigin, System, Test,
Hrmp, MockGenesisConfig, Paras, ParasShared, RuntimeEvent as MockEvent, RuntimeOrigin,
System, Test,
},
shared,
};
use frame_support::{assert_noop, assert_ok};
use primitives::BlockNumber;
use std::collections::BTreeMap;
pub(crate) fn run_to_block(to: BlockNumber, new_session: Option<Vec<BlockNumber>>) {
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
while System::block_number() < to {
let b = System::block_number();
@@ -42,7 +45,7 @@ pub(crate) fn run_to_block(to: BlockNumber, new_session: Option<Vec<BlockNumber>
let notification = crate::initializer::SessionChangeNotification {
prev_config: config.clone(),
new_config: config.clone(),
session_index: ParasShared::session_index() + 1,
session_index: shared::CurrentSessionIndex::<Test>::get() + 1,
..Default::default()
};
@@ -412,7 +415,7 @@ fn poke_deposits_works() {
register_parachain_with_balance(para_a, 200);
register_parachain_with_balance(para_b, 200);
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
let channel_id = HrmpChannelId { sender: para_a, recipient: para_b };
// Our normal establishment won't actually reserve deposits, so just insert them directly.
@@ -512,7 +515,7 @@ fn send_recv_messages() {
vec![OutboundHrmpMessage { recipient: para_b, data: b"this is an emergency".to_vec() }]
.try_into()
.unwrap();
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert!(Hrmp::check_outbound_hrmp(&config, para_a, &msgs).is_ok());
let _ = Hrmp::queue_outbound_hrmp(para_a, msgs);
Hrmp::assert_storage_consistency_exhaustive();
@@ -621,7 +624,7 @@ fn check_sent_messages() {
vec![OutboundHrmpMessage { recipient: para_b, data: b"knock".to_vec() }]
.try_into()
.unwrap();
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert!(Hrmp::check_outbound_hrmp(&config, para_a, &msgs).is_ok());
let _ = Hrmp::queue_outbound_hrmp(para_a, msgs.clone());
@@ -912,7 +915,7 @@ fn watermark_maxed_out_at_relay_parent() {
vec![OutboundHrmpMessage { recipient: para_b, data: b"this is an emergency".to_vec() }]
.try_into()
.unwrap();
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert!(Hrmp::check_outbound_hrmp(&config, para_a, &msgs).is_ok());
let _ = Hrmp::queue_outbound_hrmp(para_a, msgs);
Hrmp::assert_storage_consistency_exhaustive();
@@ -458,7 +458,7 @@ impl<T: Config> Pallet<T> {
) {
// unlike most drain methods, drained elements are not cleared on `Drop` of the iterator
// and require consumption.
for _ in <PendingAvailability<T>>::drain() {}
for _ in PendingAvailability::<T>::drain() {}
Self::cleanup_outgoing_ump_dispatch_queues(outgoing_paras);
}
@@ -506,9 +506,9 @@ impl<T: Config> Pallet<T> {
let mut freed_cores = vec![];
let pending_paraids: Vec<_> = <PendingAvailability<T>>::iter_keys().collect();
let pending_paraids: Vec<_> = PendingAvailability::<T>::iter_keys().collect();
for paraid in pending_paraids {
<PendingAvailability<T>>::mutate(paraid, |candidates| {
PendingAvailability::<T>::mutate(paraid, |candidates| {
if let Some(candidates) = candidates {
let mut last_enacted_index: Option<usize> = None;
@@ -595,8 +595,8 @@ impl<T: Config> Pallet<T> {
return Ok(ProcessedCandidates::default())
}
let now = <frame_system::Pallet<T>>::block_number();
let validators = shared::Pallet::<T>::active_validator_keys();
let now = frame_system::Pallet::<T>::block_number();
let validators = shared::ActiveValidatorKeys::<T>::get();
// Collect candidate receipts with backers.
let mut candidate_receipt_with_backing_validator_indices =
@@ -626,7 +626,7 @@ impl<T: Config> Pallet<T> {
// group assigned to core at block `N + 1`. Thus,
// `relay_parent_number + 1` will always land in the current
// session.
let group_idx = <scheduler::Pallet<T>>::group_assigned_to_core(
let group_idx = scheduler::Pallet::<T>::group_assigned_to_core(
*core,
relay_parent_number + One::one(),
)
@@ -656,7 +656,7 @@ impl<T: Config> Pallet<T> {
core_indices.push((*core, *para_id));
// Update storage now
<PendingAvailability<T>>::mutate(&para_id, |pending_availability| {
PendingAvailability::<T>::mutate(&para_id, |pending_availability| {
let new_candidate = CandidatePendingAvailability {
core: *core,
hash: candidate_hash,
@@ -696,11 +696,11 @@ impl<T: Config> Pallet<T> {
// Get the latest backed output head data of this para.
pub(crate) fn para_latest_head_data(para_id: &ParaId) -> Option<HeadData> {
match <PendingAvailability<T>>::get(para_id).and_then(|pending_candidates| {
match PendingAvailability::<T>::get(para_id).and_then(|pending_candidates| {
pending_candidates.back().map(|x| x.commitments.head_data.clone())
}) {
Some(head_data) => Some(head_data),
None => <paras::Pallet<T>>::para_head(para_id),
None => paras::Heads::<T>::get(para_id),
}
}
@@ -710,12 +710,12 @@ impl<T: Config> Pallet<T> {
group_vals: Vec<ValidatorIndex>,
core_index_enabled: bool,
) -> Result<(BitVec<u8, BitOrderLsb0>, Vec<(ValidatorIndex, ValidityAttestation)>), Error<T>> {
let minimum_backing_votes = configuration::Pallet::<T>::config().minimum_backing_votes;
let minimum_backing_votes = configuration::ActiveConfig::<T>::get().minimum_backing_votes;
let mut backers = bitvec::bitvec![u8, BitOrderLsb0; 0; validators.len()];
let signing_context = SigningContext {
parent_hash: backed_candidate.descriptor().relay_parent,
session_index: shared::Pallet::<T>::session_index(),
session_index: shared::CurrentSessionIndex::<T>::get(),
};
let (validator_indices, _) =
@@ -773,7 +773,7 @@ impl<T: Config> Pallet<T> {
relay_parent_number: BlockNumberFor<T>,
validation_outputs: primitives::CandidateCommitments,
) -> bool {
let prev_context = <paras::Pallet<T>>::para_most_recent_context(para_id);
let prev_context = paras::MostRecentContext::<T>::get(para_id);
let check_ctx = CandidateCheckContext::<T>::new(prev_context);
if check_ctx
@@ -810,7 +810,7 @@ impl<T: Config> Pallet<T> {
) -> Weight {
let plain = receipt.to_plain();
let commitments = receipt.commitments;
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
T::RewardValidators::reward_backing(
backers
@@ -832,9 +832,9 @@ impl<T: Config> Pallet<T> {
let mut weight = T::DbWeight::get().reads_writes(1, 0);
if let Some(new_code) = commitments.new_validation_code {
// Block number of candidate's inclusion.
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
weight.saturating_add(<paras::Pallet<T>>::schedule_code_upgrade(
weight.saturating_add(paras::Pallet::<T>::schedule_code_upgrade(
receipt.descriptor.para_id,
new_code,
now,
@@ -844,7 +844,7 @@ impl<T: Config> Pallet<T> {
}
// enact the messaging facet of the candidate.
weight.saturating_accrue(<dmp::Pallet<T>>::prune_dmq(
weight.saturating_accrue(dmp::Pallet::<T>::prune_dmq(
receipt.descriptor.para_id,
commitments.processed_downward_messages,
));
@@ -852,11 +852,11 @@ impl<T: Config> Pallet<T> {
receipt.descriptor.para_id,
commitments.upward_messages.as_slice(),
));
weight.saturating_accrue(<hrmp::Pallet<T>>::prune_hrmp(
weight.saturating_accrue(hrmp::Pallet::<T>::prune_hrmp(
receipt.descriptor.para_id,
BlockNumberFor::<T>::from(commitments.hrmp_watermark),
));
weight.saturating_accrue(<hrmp::Pallet<T>>::queue_outbound_hrmp(
weight.saturating_accrue(hrmp::Pallet::<T>::queue_outbound_hrmp(
receipt.descriptor.para_id,
commitments.horizontal_messages,
));
@@ -868,7 +868,7 @@ impl<T: Config> Pallet<T> {
backing_group,
));
weight.saturating_add(<paras::Pallet<T>>::note_new_head(
weight.saturating_add(paras::Pallet::<T>::note_new_head(
receipt.descriptor.para_id,
commitments.head_data,
relay_parent_number,
@@ -887,7 +887,7 @@ impl<T: Config> Pallet<T> {
upward_messages: &[UpwardMessage],
) -> Result<(), UmpAcceptanceCheckErr> {
// Cannot send UMP messages while off-boarding.
if <paras::Pallet<T>>::is_offboarding(para) {
if paras::Pallet::<T>::is_offboarding(para) {
ensure!(upward_messages.is_empty(), UmpAcceptanceCheckErr::IsOffboarding);
}
@@ -975,7 +975,7 @@ impl<T: Config> Pallet<T> {
///
/// Returns a vector of cleaned-up core IDs.
pub(crate) fn free_timedout() -> Vec<CoreIndex> {
let timeout_pred = <scheduler::Pallet<T>>::availability_timeout_predicate();
let timeout_pred = scheduler::Pallet::<T>::availability_timeout_predicate();
let timed_out: Vec<_> = Self::free_failed_cores(
|candidate| timeout_pred(candidate.backed_in_number).timed_out,
@@ -1028,7 +1028,7 @@ impl<T: Config> Pallet<T> {
) -> impl Iterator<Item = CandidatePendingAvailability<T::Hash, BlockNumberFor<T>>> {
let mut earliest_dropped_indices: BTreeMap<ParaId, usize> = BTreeMap::new();
for (para_id, pending_candidates) in <PendingAvailability<T>>::iter() {
for (para_id, pending_candidates) in PendingAvailability::<T>::iter() {
// We assume that pending candidates are stored in dependency order. So we need to store
// the earliest dropped candidate. All others that follow will get freed as well.
let mut earliest_dropped_idx = None;
@@ -1051,7 +1051,7 @@ impl<T: Config> Pallet<T> {
for (para_id, earliest_dropped_idx) in earliest_dropped_indices {
// Do cleanups and record the cleaned up cores
<PendingAvailability<T>>::mutate(&para_id, |record| {
PendingAvailability::<T>::mutate(&para_id, |record| {
if let Some(record) = record {
let cleaned_up = record.drain(earliest_dropped_idx..);
cleaned_up_cores.extend(cleaned_up);
@@ -1070,7 +1070,7 @@ impl<T: Config> Pallet<T> {
/// them. This should generally not be used but it is useful during execution of Runtime APIs,
/// where the changes to the state are expected to be discarded directly after.
pub(crate) fn force_enact(para: ParaId) {
<PendingAvailability<T>>::mutate(&para, |candidates| {
PendingAvailability::<T>::mutate(&para, |candidates| {
if let Some(candidates) = candidates {
for candidate in candidates.drain(..) {
let receipt = CommittedCandidateReceipt {
@@ -1096,7 +1096,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn candidate_pending_availability(
para: ParaId,
) -> Option<CommittedCandidateReceipt<T::Hash>> {
<PendingAvailability<T>>::get(&para).and_then(|p| {
PendingAvailability::<T>::get(&para).and_then(|p| {
p.get(0).map(|p| CommittedCandidateReceipt {
descriptor: p.descriptor.clone(),
commitments: p.commitments.clone(),
@@ -1109,7 +1109,7 @@ impl<T: Config> Pallet<T> {
pub(crate) fn pending_availability(
para: ParaId,
) -> Option<CandidatePendingAvailability<T::Hash, BlockNumberFor<T>>> {
<PendingAvailability<T>>::get(&para).and_then(|p| p.get(0).cloned())
PendingAvailability::<T>::get(&para).and_then(|p| p.get(0).cloned())
}
/// Returns the metadata around the candidate pending availability occupying the supplied core,
@@ -1118,7 +1118,7 @@ impl<T: Config> Pallet<T> {
para: ParaId,
core: CoreIndex,
) -> Option<CandidatePendingAvailability<T::Hash, BlockNumberFor<T>>> {
<PendingAvailability<T>>::get(&para)
PendingAvailability::<T>::get(&para)
.and_then(|p| p.iter().find(|c| c.core == core).cloned())
}
}
@@ -1156,7 +1156,7 @@ impl<T: Config> OnQueueChanged<AggregateMessageOrigin> for Pallet<T> {
#[allow(deprecated)]
well_known_keys::relay_dispatch_queue_size_typed(para).set((count, size));
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let remaining_count = config.max_upward_queue_count.saturating_sub(count);
let remaining_size = config.max_upward_queue_size.saturating_sub(size);
well_known_keys::relay_dispatch_queue_remaining_capacity(para)
@@ -1172,7 +1172,7 @@ pub(crate) struct CandidateCheckContext<T: Config> {
impl<T: Config> CandidateCheckContext<T> {
pub(crate) fn new(prev_context: Option<BlockNumberFor<T>>) -> Self {
Self { config: <configuration::Pallet<T>>::config(), prev_context }
Self { config: configuration::ActiveConfig::<T>::get(), prev_context }
}
/// Execute verification of the candidate.
@@ -1221,7 +1221,7 @@ impl<T: Config> CandidateCheckContext<T> {
Error::<T>::NotCollatorSigned,
);
let validation_code_hash = <paras::Pallet<T>>::current_code_hash(para_id)
let validation_code_hash = paras::CurrentCodeHash::<T>::get(para_id)
// A candidate for a parachain without current validation code is not scheduled.
.ok_or_else(|| Error::<T>::UnscheduledCandidate)?;
ensure!(
@@ -1291,7 +1291,7 @@ impl<T: Config> CandidateCheckContext<T> {
// if any, the code upgrade attempt is allowed.
if let Some(new_validation_code) = new_validation_code {
ensure!(
<paras::Pallet<T>>::can_upgrade_validation_code(para_id),
paras::Pallet::<T>::can_upgrade_validation_code(para_id),
AcceptanceCheckErr::PrematureCodeUpgrade,
);
ensure!(
@@ -1301,14 +1301,14 @@ impl<T: Config> CandidateCheckContext<T> {
}
// check if the candidate passes the messaging acceptance criteria
<dmp::Pallet<T>>::check_processed_downward_messages(
dmp::Pallet::<T>::check_processed_downward_messages(
para_id,
relay_parent_number,
processed_downward_messages,
)?;
Pallet::<T>::check_upward_messages(&self.config, para_id, upward_messages)?;
<hrmp::Pallet<T>>::check_hrmp_watermark(para_id, relay_parent_number, hrmp_watermark)?;
<hrmp::Pallet<T>>::check_outbound_hrmp(&self.config, para_id, horizontal_messages)?;
hrmp::Pallet::<T>::check_hrmp_watermark(para_id, relay_parent_number, hrmp_watermark)?;
hrmp::Pallet::<T>::check_outbound_hrmp(&self.config, para_id, horizontal_messages)?;
Ok(())
}
@@ -19,8 +19,7 @@ use crate::{
configuration::HostConfiguration,
initializer::SessionChangeNotification,
mock::{
new_test_ext, Configuration, MockGenesisConfig, ParaInclusion, Paras, ParasShared,
Scheduler, System, Test,
new_test_ext, MockGenesisConfig, ParaInclusion, Paras, ParasShared, Scheduler, System, Test,
},
paras::{ParaGenesisArgs, ParaKind},
paras_inherent::DisputedBitfield,
@@ -125,7 +124,7 @@ pub(crate) fn back_candidate(
let mut validator_indices = bitvec::bitvec![u8, BitOrderLsb0; 0; group.len()];
let threshold = effective_minimum_backing_votes(
group.len(),
configuration::Pallet::<Test>::config().minimum_backing_votes,
configuration::ActiveConfig::<Test>::get().minimum_backing_votes,
);
let signing = match kind {
@@ -182,9 +181,9 @@ pub(crate) fn back_candidate(
pub(crate) fn run_to_block_default_notifications(to: BlockNumber, new_session: Vec<BlockNumber>) {
run_to_block(to, |b| {
new_session.contains(&b).then_some(SessionChangeNotification {
prev_config: Configuration::config(),
new_config: Configuration::config(),
session_index: ParasShared::session_index() + 1,
prev_config: configuration::ActiveConfig::<Test>::get(),
new_config: configuration::ActiveConfig::<Test>::get(),
session_index: shared::CurrentSessionIndex::<Test>::get() + 1,
..Default::default()
})
});
@@ -224,7 +223,8 @@ pub(crate) fn run_to_block(
}
pub(crate) fn expected_bits() -> usize {
Paras::parachains().len() + Configuration::config().scheduler_params.num_cores as usize
paras::Parachains::<Test>::get().len() +
configuration::ActiveConfig::<Test>::get().scheduler_params.num_cores as usize
}
fn default_bitfield() -> AvailabilityBitfield {
@@ -232,11 +232,11 @@ fn default_bitfield() -> AvailabilityBitfield {
}
fn default_availability_votes() -> BitVec<u8, BitOrderLsb0> {
bitvec::bitvec![u8, BitOrderLsb0; 0; ParasShared::active_validator_keys().len()]
bitvec::bitvec![u8, BitOrderLsb0; 0; shared::ActiveValidatorKeys::<Test>::get().len()]
}
fn default_backing_bitfield() -> BitVec<u8, BitOrderLsb0> {
bitvec::bitvec![u8, BitOrderLsb0; 0; ParasShared::active_validator_keys().len()]
bitvec::bitvec![u8, BitOrderLsb0; 0; shared::ActiveValidatorKeys::<Test>::get().len()]
}
fn backing_bitfield(v: &[usize]) -> BitVec<u8, BitOrderLsb0> {
@@ -323,7 +323,7 @@ impl TestCandidateBuilder {
}
pub(crate) fn make_vdata_hash(para_id: ParaId) -> Option<Hash> {
let relay_parent_number = <frame_system::Pallet<Test>>::block_number() - 1;
let relay_parent_number = frame_system::Pallet::<Test>::block_number() - 1;
make_vdata_hash_with_block_number(para_id, relay_parent_number)
}
@@ -346,8 +346,8 @@ fn simple_sanitize_bitfields(
expected_bits: usize,
) -> SignedAvailabilityBitfields {
let parent_hash = frame_system::Pallet::<Test>::parent_hash();
let session_index = shared::Pallet::<Test>::session_index();
let validators = shared::Pallet::<Test>::active_validator_keys();
let session_index = shared::CurrentSessionIndex::<Test>::get();
let validators = shared::ActiveValidatorKeys::<Test>::get();
crate::paras_inherent::sanitize_bitfields::<Test>(
unchecked_bitfields,
@@ -362,7 +362,7 @@ fn simple_sanitize_bitfields(
pub(crate) fn process_bitfields(
signed_bitfields: SignedAvailabilityBitfields,
) -> Vec<(CoreIndex, CandidateHash)> {
let validators = shared::Pallet::<Test>::active_validator_keys();
let validators = shared::ActiveValidatorKeys::<Test>::get();
ParaInclusion::update_pending_availability_and_get_freed_cores(
&validators[..],
@@ -412,12 +412,12 @@ fn free_timedout() {
}
};
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
chain_a,
[make_candidate(0, true)].into_iter().collect::<VecDeque<_>>(),
);
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
&chain_b,
[make_candidate(1, false)].into_iter().collect::<VecDeque<_>>(),
);
@@ -427,14 +427,14 @@ fn free_timedout() {
c_candidates.push_back(make_candidate(2, true));
c_candidates.push_back(make_candidate(3, false));
<PendingAvailability<Test>>::insert(&chain_c, c_candidates);
PendingAvailability::<Test>::insert(&chain_c, c_candidates);
// 2 chained candidates. All are timed out.
let mut d_candidates = VecDeque::new();
d_candidates.push_back(make_candidate(4, true));
d_candidates.push_back(make_candidate(5, true));
<PendingAvailability<Test>>::insert(&chain_d, d_candidates);
PendingAvailability::<Test>::insert(&chain_d, d_candidates);
// 3 chained candidates. The second one is timed out. The first one will remain in place.
// With the current time out predicate this scenario is impossible. But this is not a
@@ -444,7 +444,7 @@ fn free_timedout() {
e_candidates.push_back(make_candidate(7, true));
e_candidates.push_back(make_candidate(8, false));
<PendingAvailability<Test>>::insert(&chain_e, e_candidates);
PendingAvailability::<Test>::insert(&chain_e, e_candidates);
// 3 chained candidates, none are timed out.
let mut f_candidates = VecDeque::new();
@@ -452,16 +452,16 @@ fn free_timedout() {
f_candidates.push_back(make_candidate(10, false));
f_candidates.push_back(make_candidate(11, false));
<PendingAvailability<Test>>::insert(&chain_f, f_candidates);
PendingAvailability::<Test>::insert(&chain_f, f_candidates);
run_to_block(5, |_| None);
assert_eq!(<PendingAvailability<Test>>::get(&chain_a).unwrap().len(), 1);
assert_eq!(<PendingAvailability<Test>>::get(&chain_b).unwrap().len(), 1);
assert_eq!(<PendingAvailability<Test>>::get(&chain_c).unwrap().len(), 2);
assert_eq!(<PendingAvailability<Test>>::get(&chain_d).unwrap().len(), 2);
assert_eq!(<PendingAvailability<Test>>::get(&chain_e).unwrap().len(), 3);
assert_eq!(<PendingAvailability<Test>>::get(&chain_f).unwrap().len(), 3);
assert_eq!(PendingAvailability::<Test>::get(&chain_a).unwrap().len(), 1);
assert_eq!(PendingAvailability::<Test>::get(&chain_b).unwrap().len(), 1);
assert_eq!(PendingAvailability::<Test>::get(&chain_c).unwrap().len(), 2);
assert_eq!(PendingAvailability::<Test>::get(&chain_d).unwrap().len(), 2);
assert_eq!(PendingAvailability::<Test>::get(&chain_e).unwrap().len(), 3);
assert_eq!(PendingAvailability::<Test>::get(&chain_f).unwrap().len(), 3);
let timed_out_cores = ParaInclusion::free_timedout();
@@ -478,12 +478,12 @@ fn free_timedout() {
]
);
assert!(<PendingAvailability<Test>>::get(&chain_a).unwrap().is_empty());
assert_eq!(<PendingAvailability<Test>>::get(&chain_b).unwrap().len(), 1);
assert!(<PendingAvailability<Test>>::get(&chain_c).unwrap().is_empty());
assert!(<PendingAvailability<Test>>::get(&chain_d).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_a).unwrap().is_empty());
assert_eq!(PendingAvailability::<Test>::get(&chain_b).unwrap().len(), 1);
assert!(PendingAvailability::<Test>::get(&chain_c).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_d).unwrap().is_empty());
assert_eq!(
<PendingAvailability<Test>>::get(&chain_e)
PendingAvailability::<Test>::get(&chain_e)
.unwrap()
.into_iter()
.map(|c| c.core)
@@ -491,7 +491,7 @@ fn free_timedout() {
vec![CoreIndex(6)]
);
assert_eq!(
<PendingAvailability<Test>>::get(&chain_f)
PendingAvailability::<Test>::get(&chain_f)
.unwrap()
.into_iter()
.map(|c| c.core)
@@ -548,13 +548,13 @@ fn free_disputed() {
};
// Disputed
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
chain_a,
[make_candidate(0)].into_iter().collect::<VecDeque<_>>(),
);
// Not disputed.
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
&chain_b,
[make_candidate(1)].into_iter().collect::<VecDeque<_>>(),
);
@@ -564,14 +564,14 @@ fn free_disputed() {
c_candidates.push_back(make_candidate(2));
c_candidates.push_back(make_candidate(3));
<PendingAvailability<Test>>::insert(&chain_c, c_candidates);
PendingAvailability::<Test>::insert(&chain_c, c_candidates);
// 2 chained candidates. All are disputed.
let mut d_candidates = VecDeque::new();
d_candidates.push_back(make_candidate(4));
d_candidates.push_back(make_candidate(5));
<PendingAvailability<Test>>::insert(&chain_d, d_candidates);
PendingAvailability::<Test>::insert(&chain_d, d_candidates);
// 3 chained candidates. The second one is disputed. The first one will remain in place.
let mut e_candidates = VecDeque::new();
@@ -579,7 +579,7 @@ fn free_disputed() {
e_candidates.push_back(make_candidate(7));
e_candidates.push_back(make_candidate(8));
<PendingAvailability<Test>>::insert(&chain_e, e_candidates);
PendingAvailability::<Test>::insert(&chain_e, e_candidates);
// 3 chained candidates, none are disputed.
let mut f_candidates = VecDeque::new();
@@ -587,16 +587,16 @@ fn free_disputed() {
f_candidates.push_back(make_candidate(10));
f_candidates.push_back(make_candidate(11));
<PendingAvailability<Test>>::insert(&chain_f, f_candidates);
PendingAvailability::<Test>::insert(&chain_f, f_candidates);
run_to_block(5, |_| None);
assert_eq!(<PendingAvailability<Test>>::get(&chain_a).unwrap().len(), 1);
assert_eq!(<PendingAvailability<Test>>::get(&chain_b).unwrap().len(), 1);
assert_eq!(<PendingAvailability<Test>>::get(&chain_c).unwrap().len(), 2);
assert_eq!(<PendingAvailability<Test>>::get(&chain_d).unwrap().len(), 2);
assert_eq!(<PendingAvailability<Test>>::get(&chain_e).unwrap().len(), 3);
assert_eq!(<PendingAvailability<Test>>::get(&chain_f).unwrap().len(), 3);
assert_eq!(PendingAvailability::<Test>::get(&chain_a).unwrap().len(), 1);
assert_eq!(PendingAvailability::<Test>::get(&chain_b).unwrap().len(), 1);
assert_eq!(PendingAvailability::<Test>::get(&chain_c).unwrap().len(), 2);
assert_eq!(PendingAvailability::<Test>::get(&chain_d).unwrap().len(), 2);
assert_eq!(PendingAvailability::<Test>::get(&chain_e).unwrap().len(), 3);
assert_eq!(PendingAvailability::<Test>::get(&chain_f).unwrap().len(), 3);
let disputed_candidates = [
CandidateHash(Hash::from_low_u64_be(0)),
@@ -622,12 +622,12 @@ fn free_disputed() {
]
);
assert!(<PendingAvailability<Test>>::get(&chain_a).unwrap().is_empty());
assert_eq!(<PendingAvailability<Test>>::get(&chain_b).unwrap().len(), 1);
assert!(<PendingAvailability<Test>>::get(&chain_c).unwrap().is_empty());
assert!(<PendingAvailability<Test>>::get(&chain_d).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_a).unwrap().is_empty());
assert_eq!(PendingAvailability::<Test>::get(&chain_b).unwrap().len(), 1);
assert!(PendingAvailability::<Test>::get(&chain_c).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_d).unwrap().is_empty());
assert_eq!(
<PendingAvailability<Test>>::get(&chain_e)
PendingAvailability::<Test>::get(&chain_e)
.unwrap()
.into_iter()
.map(|c| c.core)
@@ -635,7 +635,7 @@ fn free_disputed() {
vec![CoreIndex(6)]
);
assert_eq!(
<PendingAvailability<Test>>::get(&chain_f)
PendingAvailability::<Test>::get(&chain_f)
.unwrap()
.into_iter()
.map(|c| c.core)
@@ -779,7 +779,7 @@ fn bitfield_checks() {
let mut bare_bitfield = default_bitfield();
let default_candidate = TestCandidateBuilder::default().build();
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
chain_a,
[CandidatePendingAvailability {
core: CoreIndex::from(0),
@@ -815,7 +815,7 @@ fn bitfield_checks() {
let x = process_bitfields(checked_bitfields);
assert!(x.is_empty(), "No core should be freed.");
<PendingAvailability<Test>>::remove(chain_a);
PendingAvailability::<Test>::remove(chain_a);
}
});
}
@@ -877,7 +877,7 @@ fn supermajority_bitfields_trigger_availability() {
}
.build();
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
chain_a,
[CandidatePendingAvailability {
core: CoreIndex::from(0),
@@ -902,7 +902,7 @@ fn supermajority_bitfields_trigger_availability() {
}
.build();
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
chain_b,
[CandidatePendingAvailability {
core: CoreIndex::from(1),
@@ -975,7 +975,7 @@ fn supermajority_bitfields_trigger_availability() {
commitments: candidate_c_3.commitments.clone(),
});
<PendingAvailability<Test>>::insert(chain_c, c_candidates);
PendingAvailability::<Test>::insert(chain_c, c_candidates);
// this bitfield signals that a and b are available.
let all_available = {
@@ -1048,24 +1048,24 @@ fn supermajority_bitfields_trigger_availability() {
votes
};
assert!(<PendingAvailability<Test>>::get(&chain_a).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_a).unwrap().is_empty());
assert_eq!(
<PendingAvailability<Test>>::get(&chain_b)
PendingAvailability::<Test>::get(&chain_b)
.unwrap()
.pop_front()
.unwrap()
.availability_votes,
votes(&[0, 1, 2, 3])
);
let mut pending_c = <PendingAvailability<Test>>::get(&chain_c).unwrap();
let mut pending_c = PendingAvailability::<Test>::get(&chain_c).unwrap();
assert_eq!(pending_c.pop_front().unwrap().availability_votes, votes(&[0, 1, 2, 3]));
assert_eq!(pending_c.pop_front().unwrap().availability_votes, votes(&[0, 1, 2, 3, 4]));
assert!(pending_c.is_empty());
// and check that chain heads.
assert_eq!(Paras::para_head(&chain_a), Some(vec![1, 2, 3, 4].into()));
assert_ne!(Paras::para_head(&chain_b), Some(vec![5, 6, 7, 8].into()));
assert_eq!(Paras::para_head(&chain_c), Some(vec![7, 8].into()));
assert_eq!(paras::Heads::<Test>::get(&chain_a), Some(vec![1, 2, 3, 4].into()));
assert_ne!(paras::Heads::<Test>::get(&chain_b), Some(vec![5, 6, 7, 8].into()));
assert_eq!(paras::Heads::<Test>::get(&chain_c), Some(vec![7, 8].into()));
// Check that rewards are applied.
{
@@ -1117,21 +1117,21 @@ fn supermajority_bitfields_trigger_availability() {
v
);
assert!(<PendingAvailability<Test>>::get(&chain_a).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_a).unwrap().is_empty());
assert_eq!(
<PendingAvailability<Test>>::get(&chain_b)
PendingAvailability::<Test>::get(&chain_b)
.unwrap()
.pop_front()
.unwrap()
.availability_votes,
votes(&[0, 1, 2, 3])
);
assert!(<PendingAvailability<Test>>::get(&chain_c).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_c).unwrap().is_empty());
// and check that chain heads.
assert_eq!(Paras::para_head(&chain_a), Some(vec![1, 2, 3, 4].into()));
assert_ne!(Paras::para_head(&chain_b), Some(vec![5, 6, 7, 8].into()));
assert_eq!(Paras::para_head(&chain_c), Some(vec![11, 12].into()));
assert_eq!(paras::Heads::<Test>::get(&chain_a), Some(vec![1, 2, 3, 4].into()));
assert_ne!(paras::Heads::<Test>::get(&chain_b), Some(vec![5, 6, 7, 8].into()));
assert_eq!(paras::Heads::<Test>::get(&chain_c), Some(vec![11, 12].into()));
// Check that rewards are applied.
{
@@ -1582,7 +1582,7 @@ fn candidate_checks() {
);
{
let cfg = Configuration::config();
let cfg = configuration::ActiveConfig::<Test>::get();
let expected_at = 10 + cfg.validation_upgrade_delay;
assert_eq!(expected_at, 12);
Paras::schedule_code_upgrade(
@@ -1951,12 +1951,12 @@ fn backing_works() {
let backers = {
let num_backers = effective_minimum_backing_votes(
group_validators(GroupIndex(0)).unwrap().len(),
configuration::Pallet::<Test>::config().minimum_backing_votes,
configuration::ActiveConfig::<Test>::get().minimum_backing_votes,
);
backing_bitfield(&(0..num_backers).collect::<Vec<_>>())
};
assert_eq!(
<PendingAvailability<Test>>::get(&chain_a),
PendingAvailability::<Test>::get(&chain_a),
Some(
[CandidatePendingAvailability {
core: CoreIndex::from(0),
@@ -1977,12 +1977,12 @@ fn backing_works() {
let backers = {
let num_backers = effective_minimum_backing_votes(
group_validators(GroupIndex(0)).unwrap().len(),
configuration::Pallet::<Test>::config().minimum_backing_votes,
configuration::ActiveConfig::<Test>::get().minimum_backing_votes,
);
backing_bitfield(&(0..num_backers).map(|v| v + 2).collect::<Vec<_>>())
};
assert_eq!(
<PendingAvailability<Test>>::get(&chain_b),
PendingAvailability::<Test>::get(&chain_b),
Some(
[CandidatePendingAvailability {
core: CoreIndex::from(1),
@@ -2001,7 +2001,7 @@ fn backing_works() {
);
assert_eq!(
<PendingAvailability<Test>>::get(&thread_a),
PendingAvailability::<Test>::get(&thread_a),
Some(
[CandidatePendingAvailability {
core: CoreIndex::from(2),
@@ -2244,12 +2244,12 @@ fn backing_works_with_elastic_scaling_mvp() {
let backers = {
let num_backers = effective_minimum_backing_votes(
group_validators(GroupIndex(0)).unwrap().len(),
configuration::Pallet::<Test>::config().minimum_backing_votes,
configuration::ActiveConfig::<Test>::get().minimum_backing_votes,
);
backing_bitfield(&(0..num_backers).collect::<Vec<_>>())
};
assert_eq!(
<PendingAvailability<Test>>::get(&chain_a),
PendingAvailability::<Test>::get(&chain_a),
Some(
[CandidatePendingAvailability {
core: CoreIndex::from(0),
@@ -2269,7 +2269,7 @@ fn backing_works_with_elastic_scaling_mvp() {
// Both candidates of b will be recorded on chain.
assert_eq!(
<PendingAvailability<Test>>::get(&chain_b),
PendingAvailability::<Test>::get(&chain_b),
Some(
[
CandidatePendingAvailability {
@@ -2395,12 +2395,12 @@ fn can_include_candidate_with_ok_code_upgrade() {
let backers = {
let num_backers = effective_minimum_backing_votes(
group_validators(GroupIndex(0)).unwrap().len(),
configuration::Pallet::<Test>::config().minimum_backing_votes,
configuration::ActiveConfig::<Test>::get().minimum_backing_votes,
);
backing_bitfield(&(0..num_backers).collect::<Vec<_>>())
};
assert_eq!(
<PendingAvailability<Test>>::get(&chain_a),
PendingAvailability::<Test>::get(&chain_a),
Some(
[CandidatePendingAvailability {
core: CoreIndex::from(0),
@@ -2654,7 +2654,7 @@ fn session_change_wipes() {
run_to_block(10, |_| None);
let candidate = TestCandidateBuilder::default().build();
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
&chain_a,
[CandidatePendingAvailability {
core: CoreIndex::from(0),
@@ -2671,7 +2671,7 @@ fn session_change_wipes() {
.collect::<VecDeque<_>>(),
);
<PendingAvailability<Test>>::insert(
PendingAvailability::<Test>::insert(
&chain_b,
[CandidatePendingAvailability {
core: CoreIndex::from(1),
@@ -2690,10 +2690,10 @@ fn session_change_wipes() {
run_to_block(11, |_| None);
assert_eq!(shared::Pallet::<Test>::session_index(), 5);
assert_eq!(shared::CurrentSessionIndex::<Test>::get(), 5);
assert!(<PendingAvailability<Test>>::get(&chain_a).is_some());
assert!(<PendingAvailability<Test>>::get(&chain_b).is_some());
assert!(PendingAvailability::<Test>::get(&chain_a).is_some());
assert!(PendingAvailability::<Test>::get(&chain_b).is_some());
run_to_block(12, |n| match n {
12 => Some(SessionChangeNotification {
@@ -2707,9 +2707,9 @@ fn session_change_wipes() {
_ => None,
});
assert_eq!(shared::Pallet::<Test>::session_index(), 6);
assert_eq!(shared::CurrentSessionIndex::<Test>::get(), 6);
assert!(<PendingAvailability<Test>>::iter().collect::<Vec<_>>().is_empty());
assert!(PendingAvailability::<Test>::iter().collect::<Vec<_>>().is_empty());
});
}
@@ -2849,7 +2849,7 @@ fn para_upgrade_delay_scheduled_from_inclusion() {
let v = process_bitfields(checked_bitfields);
assert_eq!(vec![(CoreIndex(0), candidate_a.hash())], v);
assert!(<PendingAvailability<Test>>::get(&chain_a).unwrap().is_empty());
assert!(PendingAvailability::<Test>::get(&chain_a).unwrap().is_empty());
let active_vote_state = paras::Pallet::<Test>::active_vote_state(&new_validation_code_hash)
.expect("prechecking must be initiated");
@@ -341,15 +341,15 @@ impl<T: pallet_session::Config + Config> OneSessionHandler<T::AccountId> for Pal
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
<Pallet<T>>::on_new_session(false, 0, validators, None);
Pallet::<T>::on_new_session(false, 0, validators, None);
}
fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued: I)
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
let session_index = <pallet_session::Pallet<T>>::current_index();
<Pallet<T>>::on_new_session(changed, session_index, validators, Some(queued));
let session_index = pallet_session::Pallet::<T>::current_index();
Pallet::<T>::on_new_session(changed, session_index, validators, Some(queued));
}
fn on_disabled(_i: u32) {}
@@ -27,12 +27,12 @@ benchmarks! {
force_approve {
let d in 0 .. DIGEST_MAX_LEN;
for _ in 0 .. d {
<frame_system::Pallet<T>>::deposit_log(ConsensusLog::ForceApprove(d).into());
frame_system::Pallet::<T>::deposit_log(ConsensusLog::ForceApprove(d).into());
}
}: _(RawOrigin::Root, d + 1)
verify {
assert_eq!(
<frame_system::Pallet<T>>::digest().logs.last().unwrap(),
frame_system::Pallet::<T>::digest().logs.last().unwrap(),
&DigestItem::from(ConsensusLog::ForceApprove(d + 1)),
);
}
@@ -15,14 +15,14 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use crate::mock::{
new_test_ext, Configuration, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System,
Test,
use crate::{
mock::{new_test_ext, Dmp, Initializer, MockGenesisConfig, Paras, System, Test},
paras::ParaKind,
session_info,
};
use primitives::{HeadData, Id as ParaId};
use test_helpers::dummy_validation_code;
use crate::paras::ParaKind;
use frame_support::{
assert_ok,
traits::{OnFinalize, OnInitialize},
@@ -36,8 +36,8 @@ fn session_0_is_instantly_applied() {
let v = BufferedSessionChanges::<Test>::get();
assert!(v.is_empty());
assert_eq!(SessionInfo::earliest_stored_session(), 0);
assert!(SessionInfo::session_info(0).is_some());
assert_eq!(session_info::EarliestStoredSession::<Test>::get(), 0);
assert!(session_info::Sessions::<Test>::get(0).is_some());
});
}
@@ -116,9 +116,21 @@ fn scheduled_cleanup_performed() {
})
.execute_with(|| {
// enqueue downward messages to A, B and C.
assert_ok!(Dmp::queue_downward_message(&Configuration::config(), a, vec![1, 2, 3]));
assert_ok!(Dmp::queue_downward_message(&Configuration::config(), b, vec![4, 5, 6]));
assert_ok!(Dmp::queue_downward_message(&Configuration::config(), c, vec![7, 8, 9]));
assert_ok!(Dmp::queue_downward_message(
&configuration::ActiveConfig::<Test>::get(),
a,
vec![1, 2, 3]
));
assert_ok!(Dmp::queue_downward_message(
&configuration::ActiveConfig::<Test>::get(),
b,
vec![4, 5, 6]
));
assert_ok!(Dmp::queue_downward_message(
&configuration::ActiveConfig::<Test>::get(),
c,
vec![7, 8, 9]
));
assert_ok!(Paras::schedule_para_cleanup(a));
assert_ok!(Paras::schedule_para_cleanup(b));
+2 -2
View File
@@ -82,12 +82,12 @@ pub fn schedule_para_initialize<T: paras::Config>(
id: ParaId,
genesis: paras::ParaGenesisArgs,
) -> Result<(), ()> {
<paras::Pallet<T>>::schedule_para_initialize(id, genesis).map_err(|_| ())
paras::Pallet::<T>::schedule_para_initialize(id, genesis).map_err(|_| ())
}
/// Schedule a para to be cleaned up at the start of the next session.
pub fn schedule_para_cleanup<T: paras::Config>(id: primitives::Id) -> Result<(), ()> {
<paras::Pallet<T>>::schedule_para_cleanup(id).map_err(|_| ())
paras::Pallet::<T>::schedule_para_cleanup(id).map_err(|_| ())
}
/// Schedule a parathread (on-demand parachain) to be upgraded to a lease holding parachain.
@@ -68,7 +68,7 @@ pub(crate) fn generate_disordered_upgrades<T: Config>() {
fn generate_disordered_actions_queue<T: Config>() {
let mut queue = Vec::new();
let next_session = shared::Pallet::<T>::session_index().saturating_add(One::one());
let next_session = shared::CurrentSessionIndex::<T>::get().saturating_add(One::one());
for _ in 0..SAMPLE_SIZE {
let id = ParaId::from(1000);
@@ -140,7 +140,7 @@ benchmarks! {
generate_disordered_actions_queue::<T>();
}: _(RawOrigin::Root, para_id)
verify {
let next_session = crate::shared::Pallet::<T>::session_index().saturating_add(One::one());
let next_session = crate::shared::CurrentSessionIndex::<T>::get().saturating_add(One::one());
assert_last_event::<T>(Event::ActionQueued(para_id, next_session).into());
}
@@ -133,7 +133,7 @@ where
.collect::<Vec<_>>();
// 1. Make sure PVF pre-checking is enabled in the config.
let config = configuration::Pallet::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
configuration::Pallet::<T>::force_set_active_config(config.clone());
// 2. initialize a new session with deterministic validator set.
@@ -176,7 +176,7 @@ where
id,
validation_code,
/* relay_parent_number */ 1u32.into(),
&configuration::Pallet::<T>::config(),
&configuration::ActiveConfig::<T>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
} else {
@@ -202,7 +202,7 @@ fn generate_statements<T>(
where
T: Config + shared::Config,
{
let validators = ParasShared::<T>::active_validator_keys();
let validators = shared::ActiveValidatorKeys::<T>::get();
let accept_threshold = primitives::supermajority_threshold(validators.len());
let required_votes = match vote_outcome {
+32 -47
View File
@@ -722,8 +722,7 @@ pub mod pallet {
///
/// Consider using the [`ParachainsCache`] type of modifying.
#[pallet::storage]
#[pallet::getter(fn parachains)]
pub(crate) type Parachains<T: Config> = StorageValue<_, Vec<ParaId>, ValueQuery>;
pub type Parachains<T: Config> = StorageValue<_, Vec<ParaId>, ValueQuery>;
/// The current lifecycle of a all known Para IDs.
#[pallet::storage]
@@ -731,22 +730,17 @@ pub mod pallet {
/// The head-data of every registered para.
#[pallet::storage]
#[pallet::getter(fn para_head)]
pub(super) type Heads<T: Config> = StorageMap<_, Twox64Concat, ParaId, HeadData>;
pub type Heads<T: Config> = StorageMap<_, Twox64Concat, ParaId, HeadData>;
/// The context (relay-chain block number) of the most recent parachain head.
#[pallet::storage]
#[pallet::getter(fn para_most_recent_context)]
pub(super) type MostRecentContext<T: Config> =
StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
pub type MostRecentContext<T: Config> = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
/// The validation code hash of every live para.
///
/// Corresponding code can be retrieved with [`CodeByHash`].
#[pallet::storage]
#[pallet::getter(fn current_code_hash)]
pub(super) type CurrentCodeHash<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
pub type CurrentCodeHash<T: Config> = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
/// Actual past code hash, indicated by the para id as well as the block number at which it
/// became outdated.
@@ -760,8 +754,7 @@ pub mod pallet {
/// but we also keep their code on-chain for the same amount of time as outdated code
/// to keep it available for approval checkers.
#[pallet::storage]
#[pallet::getter(fn past_code_meta)]
pub(super) type PastCodeMeta<T: Config> =
pub type PastCodeMeta<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ParaPastCodeMeta<BlockNumberFor<T>>, ValueQuery>;
/// Which paras have past code that needs pruning and the relay-chain block at which the code
@@ -779,9 +772,7 @@ pub mod pallet {
/// The change will be applied after the first parablock for this ID included which executes
/// in the context of a relay chain block with a number >= `expected_at`.
#[pallet::storage]
#[pallet::getter(fn future_code_upgrade_at)]
pub(super) type FutureCodeUpgrades<T: Config> =
StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
pub type FutureCodeUpgrades<T: Config> = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
/// The list of upcoming future code upgrades.
///
@@ -799,9 +790,7 @@ pub mod pallet {
///
/// Corresponding code can be retrieved with [`CodeByHash`].
#[pallet::storage]
#[pallet::getter(fn future_code_hash)]
pub(super) type FutureCodeHash<T: Config> =
StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
pub type FutureCodeHash<T: Config> = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
/// This is used by the relay-chain to communicate to a parachain a go-ahead with in the upgrade
/// procedure.
@@ -827,8 +816,7 @@ pub mod pallet {
/// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
/// the format will require migration of parachains.
#[pallet::storage]
#[pallet::getter(fn upgrade_restriction_signal)]
pub(super) type UpgradeRestrictionSignal<T: Config> =
pub type UpgradeRestrictionSignal<T: Config> =
StorageMap<_, Twox64Concat, ParaId, UpgradeRestriction>;
/// The list of parachains that are awaiting for their upgrade restriction to cooldown.
@@ -850,8 +838,7 @@ pub mod pallet {
/// The actions to perform during the start of a specific session index.
#[pallet::storage]
#[pallet::getter(fn actions_queue)]
pub(super) type ActionsQueue<T: Config> =
pub type ActionsQueue<T: Config> =
StorageMap<_, Twox64Concat, SessionIndex, Vec<ParaId>, ValueQuery>;
/// Upcoming paras instantiation arguments.
@@ -872,9 +859,7 @@ pub mod pallet {
/// This storage is consistent with [`FutureCodeHash`], [`CurrentCodeHash`] and
/// [`PastCodeHash`].
#[pallet::storage]
#[pallet::getter(fn code_by_hash)]
pub(super) type CodeByHash<T: Config> =
StorageMap<_, Identity, ValidationCodeHash, ValidationCode>;
pub type CodeByHash<T: Config> = StorageMap<_, Identity, ValidationCodeHash, ValidationCode>;
#[pallet::genesis_config]
#[derive(DefaultNoBound)]
@@ -941,7 +926,7 @@ pub mod pallet {
relay_parent_number: BlockNumberFor<T>,
) -> DispatchResult {
ensure_root(origin)?;
let config = configuration::Pallet::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
Self::schedule_code_upgrade(
para,
new_code,
@@ -975,7 +960,7 @@ pub mod pallet {
#[pallet::weight(<T as Config>::WeightInfo::force_queue_action())]
pub fn force_queue_action(origin: OriginFor<T>, para: ParaId) -> DispatchResult {
ensure_root(origin)?;
let next_session = shared::Pallet::<T>::session_index().saturating_add(One::one());
let next_session = shared::CurrentSessionIndex::<T>::get().saturating_add(One::one());
ActionsQueue::<T>::mutate(next_session, |v| {
if let Err(i) = v.binary_search(&para) {
v.insert(i, para);
@@ -1017,9 +1002,9 @@ pub mod pallet {
}
});
let cfg = configuration::Pallet::<T>::config();
let cfg = configuration::ActiveConfig::<T>::get();
Self::enact_pvf_accepted(
<frame_system::Pallet<T>>::block_number(),
frame_system::Pallet::<T>::block_number(),
&code_hash,
&vote.causes,
vote.age,
@@ -1078,8 +1063,8 @@ pub mod pallet {
) -> DispatchResultWithPostInfo {
ensure_none(origin)?;
let validators = shared::Pallet::<T>::active_validator_keys();
let current_session = shared::Pallet::<T>::session_index();
let validators = shared::ActiveValidatorKeys::<T>::get();
let current_session = shared::CurrentSessionIndex::<T>::get();
if stmt.session_index < current_session {
return Err(Error::<T>::PvfCheckStatementStale.into())
} else if stmt.session_index > current_session {
@@ -1127,9 +1112,9 @@ pub mod pallet {
});
match outcome {
PvfCheckOutcome::Accepted => {
let cfg = configuration::Pallet::<T>::config();
let cfg = configuration::ActiveConfig::<T>::get();
Self::enact_pvf_accepted(
<frame_system::Pallet<T>>::block_number(),
frame_system::Pallet::<T>::block_number(),
&stmt.subject,
&active_vote.causes,
active_vote.age,
@@ -1177,7 +1162,7 @@ pub mod pallet {
_ => return InvalidTransaction::Call.into(),
};
let current_session = shared::Pallet::<T>::session_index();
let current_session = shared::CurrentSessionIndex::<T>::get();
if stmt.session_index < current_session {
return InvalidTransaction::Stale.into()
} else if stmt.session_index > current_session {
@@ -1185,7 +1170,7 @@ pub mod pallet {
}
let validator_index = stmt.validator_index.0 as usize;
let validators = shared::Pallet::<T>::active_validator_keys();
let validators = shared::ActiveValidatorKeys::<T>::get();
let validator_public = match validators.get(validator_index) {
Some(pk) => pk,
None => return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into(),
@@ -1250,7 +1235,7 @@ impl<T: Config> Pallet<T> {
) -> DispatchResult {
// Check that we can schedule an upgrade at all.
ensure!(Self::can_upgrade_validation_code(id), Error::<T>::CannotUpgradeCode);
let config = configuration::Pallet::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
// Validation code sanity checks:
ensure!(new_code.0.len() >= MIN_CODE_SIZE as usize, Error::<T>::InvalidCode);
ensure!(new_code.0.len() <= config.max_code_size as usize, Error::<T>::InvalidCode);
@@ -1294,7 +1279,7 @@ impl<T: Config> Pallet<T> {
/// The validation code of live para.
pub(crate) fn current_code(para_id: &ParaId) -> Option<ValidationCode> {
Self::current_code_hash(para_id).and_then(|code_hash| {
CurrentCodeHash::<T>::get(para_id).and_then(|code_hash| {
let code = CodeByHash::<T>::get(&code_hash);
if code.is_none() {
log::error!(
@@ -1318,7 +1303,7 @@ impl<T: Config> Pallet<T> {
fn apply_actions_queue(session: SessionIndex) -> Vec<ParaId> {
let actions = ActionsQueue::<T>::take(session);
let mut parachains = ParachainsCache::new();
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
let mut outgoing = Vec::new();
for para in actions {
@@ -1423,7 +1408,7 @@ impl<T: Config> Pallet<T> {
// looks at old code metadata, compares them to the current acceptance window, and prunes those
// that are too old.
fn prune_old_code(now: BlockNumberFor<T>) -> Weight {
let config = configuration::Pallet::<T>::config();
let config = configuration::ActiveConfig::<T>::get();
let code_retention_period = config.code_retention_period;
if now <= code_retention_period {
let weight = T::DbWeight::get().reads_writes(1, 0);
@@ -1459,7 +1444,7 @@ impl<T: Config> Pallet<T> {
}
}
meta.is_empty() && Self::para_head(&para_id).is_none()
meta.is_empty() && Heads::<T>::get(&para_id).is_none()
});
// This parachain has been removed and now the vestigial code
@@ -1651,7 +1636,7 @@ impl<T: Config> Pallet<T> {
//
// we cannot onboard at the current session, so it must be at least one
// session ahead.
let onboard_at: SessionIndex = shared::Pallet::<T>::session_index() +
let onboard_at: SessionIndex = shared::CurrentSessionIndex::<T>::get() +
cmp::max(shared::SESSION_DELAY.saturating_sub(sessions_observed), 1);
ActionsQueue::<T>::mutate(onboard_at, |v| {
@@ -1717,7 +1702,7 @@ impl<T: Config> Pallet<T> {
let expected_at = expected_at.saturated_into();
let log = ConsensusLog::ParaScheduleUpgradeCode(id, *code_hash, expected_at);
<frame_system::Pallet<T>>::deposit_log(log.into());
frame_system::Pallet::<T>::deposit_log(log.into());
weight
}
@@ -1825,7 +1810,7 @@ impl<T: Config> Pallet<T> {
let validation_code_hash = validation_code.hash();
CurrentCodeHash::<T>::insert(&id, validation_code_hash);
let cfg = configuration::Pallet::<T>::config();
let cfg = configuration::ActiveConfig::<T>::get();
Self::kick_off_pvf_check(
PvfCheckCause::Onboarding(id),
validation_code_hash,
@@ -2054,14 +2039,14 @@ impl<T: Config> Pallet<T> {
// The code is known and there is no active PVF vote for it meaning it is
// already checked -- fast track the PVF checking into the accepted state.
weight += T::DbWeight::get().reads(1);
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
weight += Self::enact_pvf_accepted(now, &code_hash, &[cause], 0, cfg);
} else {
// PVF is not being pre-checked and it is not known. Start a new pre-checking
// process.
weight += T::DbWeight::get().reads_writes(3, 2);
let now = <frame_system::Pallet<T>>::block_number();
let n_validators = shared::Pallet::<T>::active_validator_keys().len();
let now = frame_system::Pallet::<T>::block_number();
let n_validators = shared::ActiveValidatorKeys::<T>::get().len();
PvfActiveVoteMap::<T>::insert(
&code_hash,
PvfCheckActiveVoteState::new(now, n_validators, cause),
@@ -2291,7 +2276,7 @@ impl<T: Config> Pallet<T> {
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn test_on_new_session() {
Self::initializer_on_new_session(&SessionChangeNotification {
session_index: shared::Pallet::<T>::session_index(),
session_index: shared::CurrentSessionIndex::<T>::get(),
..Default::default()
});
}
+61 -50
View File
@@ -25,10 +25,8 @@ use test_helpers::{dummy_head_data, dummy_validation_code, validator_pubkeys};
use crate::{
configuration::HostConfiguration,
mock::{
new_test_ext, Configuration, MockGenesisConfig, Paras, ParasShared, RuntimeOrigin, System,
Test,
},
mock::{new_test_ext, MockGenesisConfig, Paras, ParasShared, RuntimeOrigin, System, Test},
paras,
};
static VALIDATORS: &[Sr25519Keyring] = &[
@@ -95,7 +93,8 @@ fn run_to_block(to: BlockNumber, new_session: Option<Vec<BlockNumber>>) {
ParasShared::initializer_finalize();
if new_session.as_ref().map_or(false, |v| v.contains(&(b + 1))) {
let mut session_change_notification = SessionChangeNotification::default();
session_change_notification.session_index = ParasShared::session_index() + 1;
session_change_notification.session_index =
shared::CurrentSessionIndex::<Test>::get() + 1;
session_change_notification.validators = validator_pubkeys.clone();
ParasShared::initializer_on_new_session(
session_change_notification.session_index,
@@ -301,7 +300,7 @@ fn para_past_code_pruning_in_initialize() {
PastCodePruning::<Test>::put(&vec![(id, included_block)]);
{
let mut code_meta = Paras::past_code_meta(&id);
let mut code_meta = paras::PastCodeMeta::<Test>::get(&id);
code_meta.note_replacement(at_block, included_block);
PastCodeMeta::<Test>::insert(&id, &code_meta);
}
@@ -312,12 +311,12 @@ fn para_past_code_pruning_in_initialize() {
run_to_block(pruned_at - 1, None);
assert_eq!(PastCodeHash::<Test>::get(&(id, at_block)), Some(validation_code.hash()));
assert_eq!(Paras::past_code_meta(&id).most_recent_change(), Some(at_block));
assert_eq!(paras::PastCodeMeta::<Test>::get(&id).most_recent_change(), Some(at_block));
check_code_is_stored(&validation_code);
run_to_block(pruned_at, None);
assert!(PastCodeHash::<Test>::get(&(id, at_block)).is_none());
assert!(Paras::past_code_meta(&id).most_recent_change().is_none());
assert!(paras::PastCodeMeta::<Test>::get(&id).most_recent_change().is_none());
check_code_is_not_stored(&validation_code);
});
}
@@ -345,11 +344,11 @@ fn note_new_head_sets_head() {
new_test_ext(genesis_config).execute_with(|| {
let id_a = ParaId::from(0u32);
assert_eq!(Paras::para_head(&id_a), Some(dummy_head_data()));
assert_eq!(paras::Heads::<Test>::get(&id_a), Some(dummy_head_data()));
Paras::note_new_head(id_a, vec![1, 2, 3].into(), 0);
assert_eq!(Paras::para_head(&id_a), Some(vec![1, 2, 3].into()));
assert_eq!(paras::Heads::<Test>::get(&id_a), Some(vec![1, 2, 3].into()));
});
}
@@ -392,11 +391,11 @@ fn note_past_code_sets_up_pruning_correctly() {
assert_eq!(PastCodePruning::<Test>::get(), vec![(id_a, 12), (id_b, 23)]);
assert_eq!(
Paras::past_code_meta(&id_a),
paras::PastCodeMeta::<Test>::get(&id_a),
ParaPastCodeMeta { upgrade_times: vec![upgrade_at(10, 12)], last_pruned: None }
);
assert_eq!(
Paras::past_code_meta(&id_b),
paras::PastCodeMeta::<Test>::get(&id_b),
ParaPastCodeMeta { upgrade_times: vec![upgrade_at(20, 23)], last_pruned: None }
);
});
@@ -450,7 +449,7 @@ fn code_upgrade_applied_after_delay() {
para_id,
new_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
// Include votes for super-majority.
@@ -458,7 +457,7 @@ fn code_upgrade_applied_after_delay() {
Paras::note_new_head(para_id, Default::default(), 1);
assert!(Paras::past_code_meta(&para_id).most_recent_change().is_none());
assert!(paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change().is_none());
assert_eq!(FutureCodeUpgrades::<Test>::get(&para_id), Some(expected_at));
assert_eq!(FutureCodeHash::<Test>::get(&para_id), Some(new_code.hash()));
assert_eq!(UpcomingUpgrades::<Test>::get(), vec![(para_id, expected_at)]);
@@ -477,7 +476,7 @@ fn code_upgrade_applied_after_delay() {
{
Paras::note_new_head(para_id, Default::default(), expected_at - 1);
assert!(Paras::past_code_meta(&para_id).most_recent_change().is_none());
assert!(paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change().is_none());
assert_eq!(FutureCodeUpgrades::<Test>::get(&para_id), Some(expected_at));
assert_eq!(FutureCodeHash::<Test>::get(&para_id), Some(new_code.hash()));
assert_eq!(UpgradeGoAheadSignal::<Test>::get(&para_id), Some(UpgradeGoAhead::GoAhead));
@@ -493,7 +492,10 @@ fn code_upgrade_applied_after_delay() {
{
Paras::note_new_head(para_id, Default::default(), expected_at);
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(expected_at));
assert_eq!(
paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change(),
Some(expected_at)
);
assert_eq!(
PastCodeHash::<Test>::get(&(para_id, expected_at)),
Some(original_code.hash()),
@@ -569,7 +571,7 @@ fn upgrade_strategy_apply_at_expected_block_works() {
para_id,
new_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::ApplyAtExpectedBlock,
);
// Include votes for super-majority.
@@ -582,7 +584,10 @@ fn upgrade_strategy_apply_at_expected_block_works() {
// Reporting a head doesn't change anything.
Paras::note_new_head(para_id, Default::default(), expected_at - 1);
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(expected_at));
assert_eq!(
paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change(),
Some(expected_at)
);
assert_eq!(PastCodeHash::<Test>::get(&(para_id, expected_at)), Some(original_code.hash()));
assert!(FutureCodeUpgrades::<Test>::get(&para_id).is_none());
assert!(FutureCodeUpgradesAt::<Test>::get().iter().all(|(id, _)| *id != para_id));
@@ -652,7 +657,7 @@ fn code_upgrade_applied_after_delay_even_when_late() {
para_id,
new_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
// Include votes for super-majority.
@@ -660,7 +665,7 @@ fn code_upgrade_applied_after_delay_even_when_late() {
Paras::note_new_head(para_id, Default::default(), 1);
assert!(Paras::past_code_meta(&para_id).most_recent_change().is_none());
assert!(paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change().is_none());
assert_eq!(FutureCodeUpgrades::<Test>::get(&para_id), Some(expected_at));
assert_eq!(FutureCodeHash::<Test>::get(&para_id), Some(new_code.hash()));
assert_eq!(UpcomingUpgrades::<Test>::get(), vec![(para_id, expected_at)]);
@@ -681,7 +686,10 @@ fn code_upgrade_applied_after_delay_even_when_late() {
Paras::note_new_head(para_id, Default::default(), expected_at + 4);
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(expected_at));
assert_eq!(
paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change(),
Some(expected_at)
);
assert_eq!(
PastCodeHash::<Test>::get(&(para_id, expected_at)),
@@ -736,7 +744,7 @@ fn submit_code_change_when_not_allowed_is_err() {
para_id,
new_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
// Include votes for super-majority.
@@ -754,7 +762,7 @@ fn submit_code_change_when_not_allowed_is_err() {
para_id,
newer_code.clone(),
2,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
assert_eq!(
@@ -818,7 +826,7 @@ fn upgrade_restriction_elapsed_doesnt_mean_can_upgrade() {
para_id,
new_code.clone(),
0,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
// Include votes for super-majority.
@@ -843,7 +851,7 @@ fn upgrade_restriction_elapsed_doesnt_mean_can_upgrade() {
para_id,
newer_code.clone(),
30,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
assert_eq!(FutureCodeUpgrades::<Test>::get(&para_id), Some(0 + validation_upgrade_delay));
@@ -904,7 +912,7 @@ fn full_parachain_cleanup_storage() {
para_id,
new_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
// Include votes for super-majority.
@@ -912,7 +920,7 @@ fn full_parachain_cleanup_storage() {
Paras::note_new_head(para_id, Default::default(), 1);
assert!(Paras::past_code_meta(&para_id).most_recent_change().is_none());
assert!(paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change().is_none());
assert_eq!(FutureCodeUpgrades::<Test>::get(&para_id), Some(expected_at));
assert_eq!(FutureCodeHash::<Test>::get(&para_id), Some(new_code.hash()));
assert_eq!(Paras::current_code(&para_id), Some(original_code.clone()));
@@ -927,7 +935,7 @@ fn full_parachain_cleanup_storage() {
// For that run to block #7 and submit a new head.
assert_eq!(expected_at, 7);
run_to_block(7, None);
assert_eq!(<frame_system::Pallet<Test>>::block_number(), 7);
assert_eq!(frame_system::Pallet::<Test>::block_number(), 7);
Paras::note_new_head(para_id, Default::default(), expected_at);
assert_ok!(Paras::schedule_para_cleanup(para_id));
@@ -941,7 +949,7 @@ fn full_parachain_cleanup_storage() {
//
// Why 7 and 8? See above, the clean up scheduled above was processed at the block 8.
// The initial upgrade was enacted at the block 7.
assert_eq!(Paras::past_code_meta(&para_id).most_recent_change(), Some(8));
assert_eq!(paras::PastCodeMeta::<Test>::get(&para_id).most_recent_change(), Some(8));
assert_eq!(PastCodeHash::<Test>::get(&(para_id, 8)), Some(new_code.hash()));
assert_eq!(PastCodePruning::<Test>::get(), vec![(para_id, 7), (para_id, 8)]);
check_code_is_stored(&original_code);
@@ -958,7 +966,7 @@ fn full_parachain_cleanup_storage() {
run_to_block(cleaned_up_at, None);
// now the final cleanup: last past code cleaned up, and this triggers meta cleanup.
assert_eq!(Paras::past_code_meta(&para_id), Default::default());
assert_eq!(paras::PastCodeMeta::<Test>::get(&para_id), Default::default());
assert!(PastCodeHash::<Test>::get(&(para_id, 7)).is_none());
assert!(PastCodeHash::<Test>::get(&(para_id, 8)).is_none());
assert!(PastCodePruning::<Test>::get().is_empty());
@@ -1000,7 +1008,7 @@ fn cannot_offboard_ongoing_pvf_check() {
para_id,
new_code.clone(),
RELAY_PARENT,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
assert!(!Paras::pvfs_require_precheck().is_empty());
@@ -1095,7 +1103,7 @@ fn para_incoming_at_session() {
// run to block without session change.
run_to_block(2, None);
assert_eq!(Paras::parachains(), Vec::new());
assert_eq!(paras::Parachains::<Test>::get(), Vec::new());
assert_eq!(ActionsQueue::<Test>::get(Paras::scheduled_session()), vec![c, b, a],);
// Lifecycle is tracked correctly
@@ -1106,7 +1114,7 @@ fn para_incoming_at_session() {
// Two sessions pass, so action queue is triggered
run_to_block(4, Some(vec![3, 4]));
assert_eq!(Paras::parachains(), vec![c, b]);
assert_eq!(paras::Parachains::<Test>::get(), vec![c, b]);
assert_eq!(ActionsQueue::<Test>::get(Paras::scheduled_session()), Vec::new());
// Lifecycle is tracked correctly
@@ -1158,7 +1166,7 @@ fn code_hash_at_returns_up_to_end_of_code_retention_period() {
para_id,
new_code.clone(),
0,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
// Include votes for super-majority.
@@ -1172,25 +1180,28 @@ fn code_hash_at_returns_up_to_end_of_code_retention_period() {
run_to_block(10, None);
Paras::note_new_head(para_id, Default::default(), 7);
assert_eq!(Paras::past_code_meta(&para_id).upgrade_times, vec![upgrade_at(4, 10)]);
assert_eq!(
paras::PastCodeMeta::<Test>::get(&para_id).upgrade_times,
vec![upgrade_at(4, 10)]
);
assert_eq!(Paras::current_code(&para_id), Some(new_code.clone()));
// Make sure that the old code is available **before** the code retention period passes.
run_to_block(10 + code_retention_period, None);
assert_eq!(Paras::code_by_hash(&old_code.hash()), Some(old_code.clone()));
assert_eq!(Paras::code_by_hash(&new_code.hash()), Some(new_code.clone()));
assert_eq!(paras::CodeByHash::<Test>::get(&old_code.hash()), Some(old_code.clone()));
assert_eq!(paras::CodeByHash::<Test>::get(&new_code.hash()), Some(new_code.clone()));
run_to_block(10 + code_retention_period + 1, None);
// code entry should be pruned now.
assert_eq!(
Paras::past_code_meta(&para_id),
paras::PastCodeMeta::<Test>::get(&para_id),
ParaPastCodeMeta { upgrade_times: Vec::new(), last_pruned: Some(10) },
);
assert_eq!(Paras::code_by_hash(&old_code.hash()), None); // pruned :(
assert_eq!(Paras::code_by_hash(&new_code.hash()), Some(new_code.clone()));
assert_eq!(paras::CodeByHash::<Test>::get(&old_code.hash()), None); // pruned :(
assert_eq!(paras::CodeByHash::<Test>::get(&new_code.hash()), Some(new_code.clone()));
});
}
@@ -1267,7 +1278,7 @@ fn pvf_check_coalescing_onboarding_and_upgrade() {
a,
validation_code.clone(),
RELAY_PARENT,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
assert!(!Paras::pvfs_require_precheck().is_empty());
@@ -1377,7 +1388,7 @@ fn pvf_check_upgrade_reject() {
a,
new_code.clone(),
RELAY_PARENT,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
check_code_is_stored(&new_code);
@@ -1563,7 +1574,7 @@ fn include_pvf_check_statement_refunds_weight() {
a,
new_code.clone(),
RELAY_PARENT,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
@@ -1664,7 +1675,7 @@ fn poke_unused_validation_code_doesnt_remove_code_with_users() {
para_id,
validation_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
Paras::note_new_head(para_id, HeadData::default(), 1);
@@ -1735,7 +1746,7 @@ fn add_trusted_validation_code_insta_approval() {
para_id,
validation_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
Paras::note_new_head(para_id, HeadData::default(), 1);
@@ -1777,7 +1788,7 @@ fn add_trusted_validation_code_enacts_existing_pvf_vote() {
para_id,
validation_code.clone(),
1,
&Configuration::config(),
&configuration::ActiveConfig::<Test>::get(),
UpgradeStrategy::SetGoAheadSignal,
);
Paras::note_new_head(para_id, HeadData::default(), 1);
@@ -1856,7 +1867,7 @@ fn most_recent_context() {
let para_id = ParaId::from(111);
assert_eq!(Paras::para_most_recent_context(para_id), None);
assert_eq!(paras::MostRecentContext::<Test>::get(para_id), None);
assert_ok!(Paras::schedule_para_initialize(
para_id,
@@ -1875,16 +1886,16 @@ fn most_recent_context() {
// Double-check the para is onboarded, the context is set to the recent block.
assert_eq!(ParaLifecycles::<Test>::get(&para_id), Some(ParaLifecycle::Parachain));
assert_eq!(Paras::para_most_recent_context(para_id), Some(0));
assert_eq!(paras::MostRecentContext::<Test>::get(para_id), Some(0));
// Progress para to the new head and check that the recent context is updated.
Paras::note_new_head(para_id, vec![4, 5, 6].into(), 3);
assert_eq!(Paras::para_most_recent_context(para_id), Some(3));
assert_eq!(paras::MostRecentContext::<Test>::get(para_id), Some(3));
// Finally, offboard the para and expect the context to be cleared.
assert_ok!(Paras::schedule_para_cleanup(para_id));
run_to_block(6, Some(vec![5, 6]));
assert_eq!(Paras::para_most_recent_context(para_id), None);
assert_eq!(paras::MostRecentContext::<Test>::get(para_id), None);
})
}
@@ -153,7 +153,7 @@ benchmarks! {
enter_backed_candidate_code_upgrade {
// For now we always assume worst case code size. In the future we could vary over this.
let v = crate::configuration::Pallet::<T>::config().max_code_size;
let v = crate::configuration::ActiveConfig::<T>::get().max_code_size;
let cores_with_backed: BTreeMap<_, _>
= vec![(0, BenchBuilder::<T>::fallback_min_validity_votes())]
@@ -154,8 +154,7 @@ pub mod pallet {
/// Scraped on chain data for extracting resolved disputes as well as backing votes.
#[pallet::storage]
#[pallet::getter(fn on_chain_votes)]
pub(crate) type OnChainVotes<T: Config> = StorageValue<_, ScrapedOnChainVotes<T::Hash>>;
pub type OnChainVotes<T: Config> = StorageValue<_, ScrapedOnChainVotes<T::Hash>>;
/// Update the disputes statements set part of the on-chain votes.
pub(crate) fn set_scrapable_on_chain_disputes<T: Config>(
@@ -318,15 +317,15 @@ impl<T: Config> Pallet<T> {
disputes.len()
);
let parent_hash = <frame_system::Pallet<T>>::parent_hash();
let parent_hash = frame_system::Pallet::<T>::parent_hash();
ensure!(
parent_header.hash().as_ref() == parent_hash.as_ref(),
Error::<T>::InvalidParentHeader,
);
let now = <frame_system::Pallet<T>>::block_number();
let config = <configuration::Pallet<T>>::config();
let now = frame_system::Pallet::<T>::block_number();
let config = configuration::ActiveConfig::<T>::get();
// Before anything else, update the allowed relay-parents.
{
@@ -342,7 +341,7 @@ impl<T: Config> Pallet<T> {
);
});
}
let allowed_relay_parents = <shared::Pallet<T>>::allowed_relay_parents();
let allowed_relay_parents = shared::AllowedRelayParents::<T>::get();
let candidates_weight = backed_candidates_weight::<T>(&backed_candidates);
let bitfields_weight = signed_bitfields_weight::<T>(&bitfields);
@@ -355,9 +354,9 @@ impl<T: Config> Pallet<T> {
log::debug!(target: LOG_TARGET, "Size before filter: {}, candidates + bitfields: {}, disputes: {}", all_weight_before.proof_size(), candidates_weight.proof_size() + bitfields_weight.proof_size(), disputes_weight.proof_size());
log::debug!(target: LOG_TARGET, "Time weight before filter: {}, candidates + bitfields: {}, disputes: {}", all_weight_before.ref_time(), candidates_weight.ref_time() + bitfields_weight.ref_time(), disputes_weight.ref_time());
let current_session = <shared::Pallet<T>>::session_index();
let expected_bits = <scheduler::Pallet<T>>::availability_cores().len();
let validator_public = shared::Pallet::<T>::active_validator_keys();
let current_session = shared::CurrentSessionIndex::<T>::get();
let expected_bits = scheduler::AvailabilityCores::<T>::get().len();
let validator_public = shared::ActiveValidatorKeys::<T>::get();
// We are assuming (incorrectly) to have all the weight (for the mandatory class or even
// full block) available to us. This can lead to slightly overweight blocks, which still
@@ -508,7 +507,7 @@ impl<T: Config> Pallet<T> {
// Get the cores freed as a result of concluded invalid candidates.
let (freed_disputed, concluded_invalid_hashes): (Vec<CoreIndex>, BTreeSet<CandidateHash>) =
<inclusion::Pallet<T>>::free_disputed(&current_concluded_invalid_disputes)
inclusion::Pallet::<T>::free_disputed(&current_concluded_invalid_disputes)
.into_iter()
.unzip();
@@ -531,7 +530,7 @@ impl<T: Config> Pallet<T> {
// Process new availability bitfields, yielding any availability cores whose
// work has now concluded.
let freed_concluded =
<inclusion::Pallet<T>>::update_pending_availability_and_get_freed_cores(
inclusion::Pallet::<T>::update_pending_availability_and_get_freed_cores(
&validator_public[..],
bitfields.clone(),
);
@@ -544,8 +543,8 @@ impl<T: Config> Pallet<T> {
METRICS.on_candidates_included(freed_concluded.len() as u64);
// Get the timed out candidates
let freed_timeout = if <scheduler::Pallet<T>>::availability_timeout_check_required() {
<inclusion::Pallet<T>>::free_timedout()
let freed_timeout = if scheduler::Pallet::<T>::availability_timeout_check_required() {
inclusion::Pallet::<T>::free_timedout()
} else {
Vec::new()
};
@@ -561,11 +560,11 @@ impl<T: Config> Pallet<T> {
.chain(freed_disputed.into_iter().map(|core| (core, FreedReason::Concluded)))
.chain(freed_timeout.into_iter().map(|c| (c, FreedReason::TimedOut)))
.collect::<BTreeMap<CoreIndex, FreedReason>>();
<scheduler::Pallet<T>>::free_cores_and_fill_claimqueue(freed, now);
scheduler::Pallet::<T>::free_cores_and_fill_claimqueue(freed, now);
METRICS.on_candidates_processed_total(backed_candidates.len() as u64);
let core_index_enabled = configuration::Pallet::<T>::config()
let core_index_enabled = configuration::ActiveConfig::<T>::get()
.node_features
.get(FeatureIndex::ElasticScalingMVP as usize)
.map(|b| *b)
@@ -574,7 +573,7 @@ impl<T: Config> Pallet<T> {
let mut scheduled: BTreeMap<ParaId, BTreeSet<CoreIndex>> = BTreeMap::new();
let mut total_scheduled_cores = 0;
for (core_idx, para_id) in <scheduler::Pallet<T>>::scheduled_paras() {
for (core_idx, para_id) in scheduler::Pallet::<T>::scheduled_paras() {
total_scheduled_cores += 1;
scheduled.entry(para_id).or_default().insert(core_idx);
}
@@ -607,14 +606,14 @@ impl<T: Config> Pallet<T> {
let inclusion::ProcessedCandidates::<<HeaderFor<T> as HeaderT>::Hash> {
core_indices: occupied,
candidate_receipt_with_backing_validator_indices,
} = <inclusion::Pallet<T>>::process_candidates(
} = inclusion::Pallet::<T>::process_candidates(
&allowed_relay_parents,
&backed_candidates_with_core,
<scheduler::Pallet<T>>::group_validators,
scheduler::Pallet::<T>::group_validators,
core_index_enabled,
)?;
// Note which of the scheduled cores were actually occupied by a backed candidate.
<scheduler::Pallet<T>>::occupied(occupied.into_iter().map(|e| (e.0, e.1)).collect());
scheduler::Pallet::<T>::occupied(occupied.into_iter().map(|e| (e.0, e.1)).collect());
set_scrapable_on_chain_backings::<T>(
current_session,
@@ -1151,7 +1150,7 @@ fn filter_backed_statements_from_disabled_validators<
return
}
let minimum_backing_votes = configuration::Pallet::<T>::config().minimum_backing_votes;
let minimum_backing_votes = configuration::ActiveConfig::<T>::get().minimum_backing_votes;
// Process all backed candidates. `validator_indices` in `BackedCandidates` are indices within
// the validator group assigned to the parachain. To obtain this group we need:
@@ -1178,7 +1177,7 @@ fn filter_backed_statements_from_disabled_validators<
};
// Get the group index for the core
let group_idx = match <scheduler::Pallet<T>>::group_assigned_to_core(
let group_idx = match scheduler::Pallet::<T>::group_assigned_to_core(
*core_idx,
relay_parent_block_number + One::one(),
) {
@@ -1190,7 +1189,7 @@ fn filter_backed_statements_from_disabled_validators<
};
// And finally get the validator group for this group index
let validator_group = match <scheduler::Pallet<T>>::group_validators(group_idx) {
let validator_group = match scheduler::Pallet::<T>::group_validators(group_idx) {
Some(validator_group) => validator_group,
None => {
log::debug!(target: LOG_TARGET, "Can't get the validators from group {:?}. Dropping the candidate.", group_idx);
@@ -1245,7 +1244,7 @@ fn filter_unchained_candidates<T: inclusion::Config + paras::Config + inclusion:
) {
let mut para_latest_head_data: BTreeMap<ParaId, HeadData> = BTreeMap::new();
for para_id in candidates.keys() {
let latest_head_data = match <inclusion::Pallet<T>>::para_latest_head_data(&para_id) {
let latest_head_data = match inclusion::Pallet::<T>::para_latest_head_data(&para_id) {
None => {
defensive!("Latest included head data for paraid {:?} is None", para_id);
continue
@@ -1277,7 +1276,7 @@ fn filter_unchained_candidates<T: inclusion::Config + paras::Config + inclusion:
visited_candidates.insert(candidate_hash);
}
let prev_context = <paras::Pallet<T>>::para_most_recent_context(para_id);
let prev_context = paras::MostRecentContext::<T>::get(para_id);
let check_ctx = CandidateCheckContext::<T>::new(prev_context);
let res = match check_ctx.verify_backed_candidate(
@@ -1459,7 +1458,7 @@ fn get_injected_core_index<T: configuration::Config + scheduler::Config + inclus
};
// Get the backing group of the candidate backed at `core_idx`.
let group_idx = match <scheduler::Pallet<T>>::group_assigned_to_core(
let group_idx = match scheduler::Pallet::<T>::group_assigned_to_core(
core_idx,
relay_parent_block_number + One::one(),
) {
@@ -1474,7 +1473,7 @@ fn get_injected_core_index<T: configuration::Config + scheduler::Config + inclus
},
};
let group_validators = match <scheduler::Pallet<T>>::group_validators(group_idx) {
let group_validators = match scheduler::Pallet::<T>::group_validators(group_idx) {
Some(validators) => validators,
None => return None,
};
@@ -166,7 +166,7 @@ mod enter {
.unwrap();
// The current schedule is empty prior to calling `create_inherent_enter`.
assert!(<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(scheduler::Pallet::<Test>::claimqueue_is_empty());
// Nothing is filtered out (including the backed candidates.)
assert_eq!(
@@ -177,13 +177,13 @@ mod enter {
assert_eq!(
// The length of this vec is equal to the number of candidates, so we know our 2
// backed candidates did not get filtered out
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
OnChainVotes::<Test>::get().unwrap().backing_validators_per_candidate.len(),
2
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
OnChainVotes::<Test>::get().unwrap().session,
2
);
@@ -217,7 +217,7 @@ mod enter {
assert!(config.configuration.config.scheduler_params.lookahead > 0);
new_test_ext(config).execute_with(|| {
// Set the elastic scaling MVP feature.
<configuration::Pallet<Test>>::set_node_feature(
configuration::Pallet::<Test>::set_node_feature(
RuntimeOrigin::root(),
FeatureIndex::ElasticScalingMVP as u8,
true,
@@ -257,9 +257,9 @@ mod enter {
.unwrap();
// The current schedule is empty prior to calling `create_inherent_enter`.
assert!(<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(scheduler::Pallet::<Test>::claimqueue_is_empty());
assert!(Pallet::<Test>::on_chain_votes().is_none());
assert!(pallet::OnChainVotes::<Test>::get().is_none());
// Nothing is filtered out (including the backed candidates.)
assert_eq!(
@@ -270,13 +270,16 @@ mod enter {
assert_eq!(
// The length of this vec is equal to the number of candidates, so we know our 5
// backed candidates did not get filtered out
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
pallet::OnChainVotes::<Test>::get()
.unwrap()
.backing_validators_per_candidate
.len(),
5
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
pallet::OnChainVotes::<Test>::get().unwrap().session,
2
);
@@ -316,7 +319,7 @@ mod enter {
assert!(config.configuration.config.scheduler_params.lookahead > 0);
new_test_ext(config).execute_with(|| {
// Set the elastic scaling MVP feature.
<configuration::Pallet<Test>>::set_node_feature(
configuration::Pallet::<Test>::set_node_feature(
RuntimeOrigin::root(),
FeatureIndex::ElasticScalingMVP as u8,
true,
@@ -352,7 +355,7 @@ mod enter {
assert_eq!(expected_para_inherent_data.backed_candidates.len(), 6);
// * 0 disputes.
assert_eq!(expected_para_inherent_data.disputes.len(), 0);
assert!(Pallet::<Test>::on_chain_votes().is_none());
assert!(pallet::OnChainVotes::<Test>::get().is_none());
expected_para_inherent_data.backed_candidates = expected_para_inherent_data
.backed_candidates
@@ -369,7 +372,7 @@ mod enter {
let mut inherent_data = InherentData::new();
inherent_data.put_data(PARACHAINS_INHERENT_IDENTIFIER, &scenario.data).unwrap();
assert!(!<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(!scheduler::Pallet::<Test>::claimqueue_is_empty());
// The right candidates have been filtered out (the ones for cores 0,4,5)
assert_eq!(
@@ -379,13 +382,16 @@ mod enter {
// 3 candidates have been backed (for cores 1,2 and 3)
assert_eq!(
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
pallet::OnChainVotes::<Test>::get()
.unwrap()
.backing_validators_per_candidate
.len(),
3
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
pallet::OnChainVotes::<Test>::get().unwrap().session,
2
);
@@ -420,7 +426,7 @@ mod enter {
// Now just make all candidates available.
let mut data = scenario.data.clone();
let validators = session_info::Pallet::<Test>::session_info(2).unwrap().validators;
let validators = session_info::Sessions::<Test>::get(2).unwrap().validators;
let signing_context = SigningContext {
parent_hash: BenchBuilder::<Test>::header(4).hash(),
session_index: 2,
@@ -447,7 +453,7 @@ mod enter {
);
// No more candidates have been backed
assert!(Pallet::<Test>::on_chain_votes()
assert!(pallet::OnChainVotes::<Test>::get()
.unwrap()
.backing_validators_per_candidate
.is_empty());
@@ -480,10 +486,7 @@ mod enter {
// Paras have the right on-chain heads now
expected_heads.into_iter().enumerate().for_each(|(id, head)| {
assert_eq!(
paras::Pallet::<Test>::para_head(ParaId::from(id as u32)).unwrap(),
head
);
assert_eq!(paras::Heads::<Test>::get(ParaId::from(id as u32)).unwrap(), head);
});
});
}
@@ -551,7 +554,7 @@ mod enter {
let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(1));
let statements = generate_votes(3, candidate_hash);
set_scrapable_on_chain_disputes::<Test>(3, statements);
assert_matches!(pallet::Pallet::<Test>::on_chain_votes(), Some(ScrapedOnChainVotes {
assert_matches!(pallet::OnChainVotes::<Test>::get(), Some(ScrapedOnChainVotes {
session,
..
} ) => {
@@ -570,7 +573,7 @@ mod enter {
let candidate_hash = CandidateHash(sp_core::H256::repeat_byte(2));
let statements = generate_votes(7, candidate_hash);
set_scrapable_on_chain_disputes::<Test>(7, statements);
assert_matches!(pallet::Pallet::<Test>::on_chain_votes(), Some(ScrapedOnChainVotes {
assert_matches!(pallet::OnChainVotes::<Test>::get(), Some(ScrapedOnChainVotes {
session,
..
} ) => {
@@ -615,7 +618,7 @@ mod enter {
.unwrap();
// The current schedule is empty prior to calling `create_inherent_enter`.
assert!(<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(scheduler::Pallet::<Test>::claimqueue_is_empty());
let multi_dispute_inherent_data =
Pallet::<Test>::create_inherent_inner(&inherent_data.clone()).unwrap();
@@ -638,13 +641,13 @@ mod enter {
assert_eq!(
// The length of this vec is equal to the number of candidates, so we know there
// where no backed candidates included
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
OnChainVotes::<Test>::get().unwrap().backing_validators_per_candidate.len(),
0
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
OnChainVotes::<Test>::get().unwrap().session,
2
);
});
@@ -687,7 +690,7 @@ mod enter {
.unwrap();
// The current schedule is empty prior to calling `create_inherent_enter`.
assert!(<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(scheduler::Pallet::<Test>::claimqueue_is_empty());
let limit_inherent_data =
Pallet::<Test>::create_inherent_inner(&inherent_data.clone()).unwrap();
@@ -706,13 +709,13 @@ mod enter {
assert_eq!(
// Ensure that our inherent data did not included backed candidates as expected
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
OnChainVotes::<Test>::get().unwrap().backing_validators_per_candidate.len(),
0
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
OnChainVotes::<Test>::get().unwrap().session,
2
);
});
@@ -759,7 +762,7 @@ mod enter {
.unwrap();
// The current schedule is empty prior to calling `create_inherent_enter`.
assert!(<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(scheduler::Pallet::<Test>::claimqueue_is_empty());
// Nothing is filtered out (including the backed candidates.)
let limit_inherent_data =
@@ -789,13 +792,13 @@ mod enter {
assert_eq!(
// The length of this vec is equal to the number of candidates, so we know
// all of our candidates got filtered out
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
OnChainVotes::<Test>::get().unwrap().backing_validators_per_candidate.len(),
0,
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
OnChainVotes::<Test>::get().unwrap().session,
2
);
});
@@ -846,7 +849,7 @@ mod enter {
.unwrap();
// The current schedule is empty prior to calling `create_inherent_enter`.
assert!(<scheduler::Pallet<Test>>::claimqueue_is_empty());
assert!(scheduler::Pallet::<Test>::claimqueue_is_empty());
// Nothing is filtered out (including the backed candidates.)
let limit_inherent_data =
@@ -877,13 +880,13 @@ mod enter {
assert_eq!(
// The length of this vec is equal to the number of candidates, so we know
// all of our candidates got filtered out
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
OnChainVotes::<Test>::get().unwrap().backing_validators_per_candidate.len(),
0,
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
OnChainVotes::<Test>::get().unwrap().session,
2
);
});
@@ -1043,24 +1046,24 @@ mod enter {
assert_eq!(
// The length of this vec is equal to the number of candidates, so we know 1
// candidate got filtered out
Pallet::<Test>::on_chain_votes().unwrap().backing_validators_per_candidate.len(),
OnChainVotes::<Test>::get().unwrap().backing_validators_per_candidate.len(),
1
);
assert_eq!(
// The session of the on chain votes should equal the current session, which is 2
Pallet::<Test>::on_chain_votes().unwrap().session,
OnChainVotes::<Test>::get().unwrap().session,
2
);
// One core was scheduled. We should put the assignment back, before calling enter().
let now = <frame_system::Pallet<Test>>::block_number() + 1;
let now = frame_system::Pallet::<Test>::block_number() + 1;
let used_cores = 5;
let cores = (0..used_cores)
.into_iter()
.map(|i| {
let SchedulerParams { ttl, .. } =
<configuration::Pallet<Test>>::config().scheduler_params;
configuration::ActiveConfig::<Test>::get().scheduler_params;
// Load an assignment into provider so that one is present to pop
let assignment =
<Test as scheduler::Config>::AssignmentProvider::get_mock_assignment(
@@ -1899,11 +1902,11 @@ mod sanitizers {
// State sanity checks
assert_eq!(
<scheduler::Pallet<Test>>::scheduled_paras().collect::<Vec<_>>(),
scheduler::Pallet::<Test>::scheduled_paras().collect::<Vec<_>>(),
vec![(CoreIndex(0), ParaId::from(1)), (CoreIndex(1), ParaId::from(2))]
);
assert_eq!(
shared::Pallet::<Test>::active_validator_indices(),
shared::ActiveValidatorIndices::<Test>::get(),
vec![
ValidatorIndex(0),
ValidatorIndex(1),
@@ -2434,7 +2437,7 @@ mod sanitizers {
// State sanity checks
assert_eq!(
<scheduler::Pallet<Test>>::scheduled_paras().collect::<Vec<_>>(),
scheduler::Pallet::<Test>::scheduled_paras().collect::<Vec<_>>(),
vec![
(CoreIndex(0), ParaId::from(1)),
(CoreIndex(1), ParaId::from(1)),
@@ -2449,12 +2452,12 @@ mod sanitizers {
]
);
let mut scheduled: BTreeMap<ParaId, BTreeSet<CoreIndex>> = BTreeMap::new();
for (core_idx, para_id) in <scheduler::Pallet<Test>>::scheduled_paras() {
for (core_idx, para_id) in scheduler::Pallet::<Test>::scheduled_paras() {
scheduled.entry(para_id).or_default().insert(core_idx);
}
assert_eq!(
shared::Pallet::<Test>::active_validator_indices(),
shared::ActiveValidatorIndices::<Test>::get(),
vec![
ValidatorIndex(0),
ValidatorIndex(1),
@@ -2937,7 +2940,7 @@ mod sanitizers {
// State sanity checks
assert_eq!(
<scheduler::Pallet<Test>>::scheduled_paras().collect::<Vec<_>>(),
scheduler::Pallet::<Test>::scheduled_paras().collect::<Vec<_>>(),
vec![
(CoreIndex(0), ParaId::from(1)),
(CoreIndex(1), ParaId::from(1)),
@@ -2951,12 +2954,12 @@ mod sanitizers {
]
);
let mut scheduled: BTreeMap<ParaId, BTreeSet<CoreIndex>> = BTreeMap::new();
for (core_idx, para_id) in <scheduler::Pallet<Test>>::scheduled_paras() {
for (core_idx, para_id) in scheduler::Pallet::<Test>::scheduled_paras() {
scheduled.entry(para_id).or_default().insert(core_idx);
}
assert_eq!(
shared::Pallet::<Test>::active_validator_indices(),
shared::ActiveValidatorIndices::<Test>::get(),
vec![
ValidatorIndex(0),
ValidatorIndex(1),
@@ -2991,7 +2994,7 @@ mod sanitizers {
assert_eq!(
sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
BTreeSet::new(),
scheduled,
core_index_enabled
@@ -3015,7 +3018,7 @@ mod sanitizers {
assert_eq!(
sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
BTreeSet::new(),
scheduled,
core_index_enabled
@@ -3039,7 +3042,7 @@ mod sanitizers {
assert_eq!(
sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
BTreeSet::new(),
scheduled,
core_index_enabled,
@@ -3069,7 +3072,7 @@ mod sanitizers {
let sanitized_backed_candidates = sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
BTreeSet::new(),
scheduled,
core_index_enabled,
@@ -3105,7 +3108,7 @@ mod sanitizers {
Vec<(BackedCandidate<_>, CoreIndex)>,
> = sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
set,
scheduled,
core_index_enabled,
@@ -3142,7 +3145,7 @@ mod sanitizers {
Vec<(BackedCandidate<_>, CoreIndex)>,
> = sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
invalid_set,
scheduled,
true,
@@ -3178,7 +3181,7 @@ mod sanitizers {
Vec<(BackedCandidate<_>, CoreIndex)>,
> = sanitize_backed_candidates::<Test>(
backed_candidates.clone(),
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
invalid_set,
scheduled,
true,
@@ -3212,7 +3215,7 @@ mod sanitizers {
// filtered
filter_backed_statements_from_disabled_validators::<Test>(
&mut expected_backed_candidates_with_core,
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
core_index_enabled,
);
assert_eq!(expected_backed_candidates_with_core, before);
@@ -3235,7 +3238,7 @@ mod sanitizers {
// Update `minimum_backing_votes` in HostConfig. We want `minimum_backing_votes` set
// to one so that the candidate will have enough backing votes even after dropping
// Alice's one.
let mut hc = configuration::Pallet::<Test>::config();
let mut hc = configuration::ActiveConfig::<Test>::get();
hc.minimum_backing_votes = 1;
configuration::Pallet::<Test>::force_set_active_config(hc);
@@ -3280,7 +3283,7 @@ mod sanitizers {
let before = expected_backed_candidates_with_core.clone();
filter_backed_statements_from_disabled_validators::<Test>(
&mut expected_backed_candidates_with_core,
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
core_index_enabled,
);
assert_eq!(before.len(), expected_backed_candidates_with_core.len());
@@ -3368,7 +3371,7 @@ mod sanitizers {
filter_backed_statements_from_disabled_validators::<Test>(
&mut expected_backed_candidates_with_core,
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
core_index_enabled,
);
@@ -3400,7 +3403,7 @@ mod sanitizers {
filter_backed_statements_from_disabled_validators::<Test>(
&mut expected_backed_candidates_with_core,
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
true,
);
@@ -3422,7 +3425,7 @@ mod sanitizers {
filter_backed_statements_from_disabled_validators::<Test>(
&mut expected_backed_candidates_with_core,
&<shared::Pallet<Test>>::allowed_relay_parents(),
&shared::AllowedRelayParents::<Test>::get(),
true,
);
@@ -45,7 +45,7 @@ where
indices: impl IntoIterator<Item = ValidatorIndex>,
points: u32,
) {
let validators = session_info::Pallet::<C>::account_keys(&session_index);
let validators = session_info::AccountKeys::<C>::get(&session_index);
let validators = match validators
.defensive_proof("account_keys are present for dispute_period sessions")
{
@@ -71,7 +71,7 @@ where
C::ValidatorSet: ValidatorSet<C::AccountId, ValidatorId = C::AccountId>,
{
fn reward_backing(indices: impl IntoIterator<Item = ValidatorIndex>) {
let session_index = shared::Pallet::<C>::session_index();
let session_index = shared::CurrentSessionIndex::<C>::get();
Self::reward_only_active(session_index, indices, BACKING_POINTS);
}
@@ -41,7 +41,7 @@ use sp_std::{collections::btree_map::BTreeMap, prelude::*};
/// Implementation for the `validators` function of the runtime API.
pub fn validators<T: initializer::Config>() -> Vec<ValidatorId> {
<shared::Pallet<T>>::active_validator_keys()
shared::ActiveValidatorKeys::<T>::get()
}
/// Implementation for the `validator_groups` function of the runtime API.
@@ -49,29 +49,29 @@ pub fn validator_groups<T: initializer::Config>(
) -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumberFor<T>>) {
// This formula needs to be the same as the one we use
// when populating group_responsible in `availability_cores`
let now = <frame_system::Pallet<T>>::block_number() + One::one();
let now = frame_system::Pallet::<T>::block_number() + One::one();
let groups = <scheduler::Pallet<T>>::validator_groups();
let rotation_info = <scheduler::Pallet<T>>::group_rotation_info(now);
let groups = scheduler::ValidatorGroups::<T>::get();
let rotation_info = scheduler::Pallet::<T>::group_rotation_info(now);
(groups, rotation_info)
}
/// Implementation for the `availability_cores` function of the runtime API.
pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, BlockNumberFor<T>>> {
let cores = <scheduler::Pallet<T>>::availability_cores();
let now = <frame_system::Pallet<T>>::block_number() + One::one();
let cores = scheduler::AvailabilityCores::<T>::get();
let now = frame_system::Pallet::<T>::block_number() + One::one();
// This explicit update is only strictly required for session boundaries:
//
// At the end of a session we clear the claim queues: Without this update call, nothing would be
// scheduled to the client.
<scheduler::Pallet<T>>::free_cores_and_fill_claimqueue(Vec::new(), now);
scheduler::Pallet::<T>::free_cores_and_fill_claimqueue(Vec::new(), now);
let time_out_for = <scheduler::Pallet<T>>::availability_timeout_predicate();
let time_out_for = scheduler::Pallet::<T>::availability_timeout_predicate();
let group_responsible_for =
|backed_in_number, core_index| match <scheduler::Pallet<T>>::group_assigned_to_core(
|backed_in_number, core_index| match scheduler::Pallet::<T>::group_assigned_to_core(
core_index,
backed_in_number,
) {
@@ -87,7 +87,7 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, Bl
},
};
let scheduled: BTreeMap<_, _> = <scheduler::Pallet<T>>::scheduled_paras().collect();
let scheduled: BTreeMap<_, _> = scheduler::Pallet::<T>::scheduled_paras().collect();
cores
.into_iter()
@@ -98,13 +98,13 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, Bl
// this runtime API to panic. We explicitly handle the storage for version 0 to
// prevent that. When removing the inclusion v0 -> v1 migration, this bit of code
// can also be removed.
let pending_availability = if <inclusion::Pallet<T>>::on_chain_storage_version() ==
let pending_availability = if inclusion::Pallet::<T>::on_chain_storage_version() ==
StorageVersion::new(0)
{
inclusion::migration::v0::PendingAvailability::<T>::get(entry.para_id())
.expect("Occupied core always has pending availability; qed")
} else {
let candidate = <inclusion::Pallet<T>>::pending_availability_with_core(
let candidate = inclusion::Pallet::<T>::pending_availability_with_core(
entry.para_id(),
CoreIndex(i as u32),
)
@@ -130,12 +130,12 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, Bl
let backing_group_allocation_time =
pending_availability.relay_parent_number + One::one();
CoreState::Occupied(OccupiedCore {
next_up_on_available: <scheduler::Pallet<T>>::next_up_on_available(CoreIndex(
next_up_on_available: scheduler::Pallet::<T>::next_up_on_available(CoreIndex(
i as u32,
)),
occupied_since: backed_in_number,
time_out_at: time_out_for(backed_in_number).live_until,
next_up_on_time_out: <scheduler::Pallet<T>>::next_up_on_time_out(CoreIndex(
next_up_on_time_out: scheduler::Pallet::<T>::next_up_on_time_out(CoreIndex(
i as u32,
)),
availability: pending_availability.availability_votes.clone(),
@@ -162,8 +162,8 @@ pub fn availability_cores<T: initializer::Config>() -> Vec<CoreState<T::Hash, Bl
fn current_relay_parent<T: frame_system::Config>(
) -> (BlockNumberFor<T>, <T as frame_system::Config>::Hash) {
use parity_scale_codec::Decode as _;
let state_version = <frame_system::Pallet<T>>::runtime_version().state_version();
let relay_parent_number = <frame_system::Pallet<T>>::block_number();
let state_version = frame_system::Pallet::<T>::runtime_version().state_version();
let relay_parent_number = frame_system::Pallet::<T>::block_number();
let relay_parent_storage_root = T::Hash::decode(&mut &sp_io::storage::root(state_version)[..])
.expect("storage root must decode to the Hash type; qed");
(relay_parent_number, relay_parent_storage_root)
@@ -229,13 +229,13 @@ pub fn assumed_validation_data<T: initializer::Config>(
let persisted_validation_data = make_validation_data().or_else(|| {
// Try again with force enacting the pending candidates. This check only makes sense if
// there are any pending candidates.
<inclusion::Pallet<T>>::pending_availability(para_id).and_then(|_| {
<inclusion::Pallet<T>>::force_enact(para_id);
inclusion::Pallet::<T>::pending_availability(para_id).and_then(|_| {
inclusion::Pallet::<T>::force_enact(para_id);
make_validation_data()
})
});
// If we were successful, also query current validation code hash.
persisted_validation_data.zip(<paras::Pallet<T>>::current_code_hash(&para_id))
persisted_validation_data.zip(paras::CurrentCodeHash::<T>::get(&para_id))
}
/// Implementation for the `check_validation_outputs` function of the runtime API.
@@ -243,8 +243,8 @@ pub fn check_validation_outputs<T: initializer::Config>(
para_id: ParaId,
outputs: primitives::CandidateCommitments,
) -> bool {
let relay_parent_number = <frame_system::Pallet<T>>::block_number();
<inclusion::Pallet<T>>::check_validation_outputs_for_runtime_api(
let relay_parent_number = frame_system::Pallet::<T>::block_number();
inclusion::Pallet::<T>::check_validation_outputs_for_runtime_api(
para_id,
relay_parent_number,
outputs,
@@ -260,7 +260,7 @@ pub fn session_index_for_child<T: initializer::Config>() -> SessionIndex {
//
// Incidentally, this is also the rationale for why it is OK to query validators or
// occupied cores or etc. and expect the correct response "for child".
<shared::Pallet<T>>::session_index()
shared::CurrentSessionIndex::<T>::get()
}
/// Implementation for the `AuthorityDiscoveryApi::authorities()` function of the runtime API.
@@ -269,18 +269,18 @@ pub fn session_index_for_child<T: initializer::Config>() -> SessionIndex {
pub fn relevant_authority_ids<T: initializer::Config + pallet_authority_discovery::Config>(
) -> Vec<AuthorityDiscoveryId> {
let current_session_index = session_index_for_child::<T>();
let earliest_stored_session = <session_info::Pallet<T>>::earliest_stored_session();
let earliest_stored_session = session_info::EarliestStoredSession::<T>::get();
// Due to `max_validators`, the `SessionInfo` stores only the validators who are actively
// selected to participate in parachain consensus. We'd like all authorities for the current
// and next sessions to be used in authority-discovery. The two sets likely have large overlap.
let mut authority_ids = <pallet_authority_discovery::Pallet<T>>::current_authorities().to_vec();
authority_ids.extend(<pallet_authority_discovery::Pallet<T>>::next_authorities().to_vec());
let mut authority_ids = pallet_authority_discovery::Pallet::<T>::current_authorities().to_vec();
authority_ids.extend(pallet_authority_discovery::Pallet::<T>::next_authorities().to_vec());
// Due to disputes, we'd like to remain connected to authorities of the previous few sessions.
// For this, we don't need anyone other than the validators actively participating in consensus.
for session_index in earliest_stored_session..current_session_index {
let info = <session_info::Pallet<T>>::session_info(session_index);
let info = session_info::Sessions::<T>::get(session_index);
if let Some(mut info) = info {
authority_ids.append(&mut info.discovery_keys);
}
@@ -297,14 +297,14 @@ pub fn validation_code<T: initializer::Config>(
para_id: ParaId,
assumption: OccupiedCoreAssumption,
) -> Option<ValidationCode> {
with_assumption::<T, _, _>(para_id, assumption, || <paras::Pallet<T>>::current_code(&para_id))
with_assumption::<T, _, _>(para_id, assumption, || paras::Pallet::<T>::current_code(&para_id))
}
/// Implementation for the `candidate_pending_availability` function of the runtime API.
pub fn candidate_pending_availability<T: initializer::Config>(
para_id: ParaId,
) -> Option<CommittedCandidateReceipt<T::Hash>> {
<inclusion::Pallet<T>>::candidate_pending_availability(para_id)
inclusion::Pallet::<T>::candidate_pending_availability(para_id)
}
/// Implementation for the `candidate_events` function of the runtime API.
@@ -317,7 +317,7 @@ where
{
use inclusion::Event as RawEvent;
<frame_system::Pallet<T>>::read_events_no_consensus()
frame_system::Pallet::<T>::read_events_no_consensus()
.into_iter()
.filter_map(|record| extract_event(record.event))
.filter_map(|event| {
@@ -338,33 +338,33 @@ where
/// Get the session info for the given session, if stored.
pub fn session_info<T: session_info::Config>(index: SessionIndex) -> Option<SessionInfo> {
<session_info::Pallet<T>>::session_info(index)
session_info::Sessions::<T>::get(index)
}
/// Implementation for the `dmq_contents` function of the runtime API.
pub fn dmq_contents<T: dmp::Config>(
recipient: ParaId,
) -> Vec<InboundDownwardMessage<BlockNumberFor<T>>> {
<dmp::Pallet<T>>::dmq_contents(recipient)
dmp::Pallet::<T>::dmq_contents(recipient)
}
/// Implementation for the `inbound_hrmp_channels_contents` function of the runtime API.
pub fn inbound_hrmp_channels_contents<T: hrmp::Config>(
recipient: ParaId,
) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumberFor<T>>>> {
<hrmp::Pallet<T>>::inbound_hrmp_channels_contents(recipient)
hrmp::Pallet::<T>::inbound_hrmp_channels_contents(recipient)
}
/// Implementation for the `validation_code_by_hash` function of the runtime API.
pub fn validation_code_by_hash<T: paras::Config>(
hash: ValidationCodeHash,
) -> Option<ValidationCode> {
<paras::Pallet<T>>::code_by_hash(hash)
paras::CodeByHash::<T>::get(hash)
}
/// Disputes imported via means of on-chain imports.
pub fn on_chain_votes<T: paras_inherent::Config>() -> Option<ScrapedOnChainVotes<T::Hash>> {
<paras_inherent::Pallet<T>>::on_chain_votes()
paras_inherent::OnChainVotes::<T>::get()
}
/// Submits an PVF pre-checking vote.
@@ -372,12 +372,12 @@ pub fn submit_pvf_check_statement<T: paras::Config>(
stmt: PvfCheckStatement,
signature: ValidatorSignature,
) {
<paras::Pallet<T>>::submit_pvf_check_statement(stmt, signature)
paras::Pallet::<T>::submit_pvf_check_statement(stmt, signature)
}
/// Returns the list of all PVF code hashes that require pre-checking.
pub fn pvfs_require_precheck<T: paras::Config>() -> Vec<ValidationCodeHash> {
<paras::Pallet<T>>::pvfs_require_precheck()
paras::Pallet::<T>::pvfs_require_precheck()
}
/// Returns the validation code hash for the given parachain making the given
@@ -389,28 +389,26 @@ pub fn validation_code_hash<T>(
where
T: inclusion::Config,
{
with_assumption::<T, _, _>(para_id, assumption, || {
<paras::Pallet<T>>::current_code_hash(&para_id)
})
with_assumption::<T, _, _>(para_id, assumption, || paras::CurrentCodeHash::<T>::get(&para_id))
}
/// Implementation for `get_session_disputes` function from the runtime API
pub fn get_session_disputes<T: disputes::Config>(
) -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumberFor<T>>)> {
<disputes::Pallet<T>>::disputes()
disputes::Pallet::<T>::disputes()
}
/// Get session executor parameter set
pub fn session_executor_params<T: session_info::Config>(
session_index: SessionIndex,
) -> Option<ExecutorParams> {
<session_info::Pallet<T>>::session_executor_params(session_index)
session_info::SessionExecutorParams::<T>::get(session_index)
}
/// Implementation of `unapplied_slashes` runtime API
pub fn unapplied_slashes<T: disputes::slashing::Config>(
) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
<disputes::slashing::Pallet<T>>::unapplied_slashes()
disputes::slashing::Pallet::<T>::unapplied_slashes()
}
/// Implementation of `submit_report_dispute_lost` runtime API
@@ -420,7 +418,7 @@ pub fn submit_unsigned_slashing_report<T: disputes::slashing::Config>(
) -> Option<()> {
let key_ownership_proof = key_ownership_proof.decode()?;
<disputes::slashing::Pallet<T>>::submit_unsigned_slashing_report(
disputes::slashing::Pallet::<T>::submit_unsigned_slashing_report(
dispute_proof,
key_ownership_proof,
)
@@ -428,46 +426,46 @@ pub fn submit_unsigned_slashing_report<T: disputes::slashing::Config>(
/// Return the min backing votes threshold from the configuration.
pub fn minimum_backing_votes<T: initializer::Config>() -> u32 {
<configuration::Pallet<T>>::config().minimum_backing_votes
configuration::ActiveConfig::<T>::get().minimum_backing_votes
}
/// Implementation for `ParaBackingState` function from the runtime API
pub fn backing_state<T: initializer::Config>(
para_id: ParaId,
) -> Option<BackingState<T::Hash, BlockNumberFor<T>>> {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
// Async backing is only expected to be enabled with a tracker capacity of 1.
// Subsequent configuration update gets applied on new session, which always
// clears the buffer.
//
// Thus, minimum relay parent is ensured to have asynchronous backing enabled.
let now = <frame_system::Pallet<T>>::block_number();
let min_relay_parent_number = <shared::Pallet<T>>::allowed_relay_parents()
let now = frame_system::Pallet::<T>::block_number();
let min_relay_parent_number = shared::AllowedRelayParents::<T>::get()
.hypothetical_earliest_block_number(now, config.async_backing_params.allowed_ancestry_len);
let required_parent = <paras::Pallet<T>>::para_head(para_id)?;
let validation_code_hash = <paras::Pallet<T>>::current_code_hash(para_id)?;
let required_parent = paras::Heads::<T>::get(para_id)?;
let validation_code_hash = paras::CurrentCodeHash::<T>::get(para_id)?;
let upgrade_restriction = <paras::Pallet<T>>::upgrade_restriction_signal(para_id);
let upgrade_restriction = paras::UpgradeRestrictionSignal::<T>::get(para_id);
let future_validation_code =
<paras::Pallet<T>>::future_code_upgrade_at(para_id).and_then(|block_num| {
paras::FutureCodeUpgrades::<T>::get(para_id).and_then(|block_num| {
// Only read the storage if there's a pending upgrade.
Some(block_num).zip(<paras::Pallet<T>>::future_code_hash(para_id))
Some(block_num).zip(paras::FutureCodeHash::<T>::get(para_id))
});
let (ump_msg_count, ump_total_bytes) =
<inclusion::Pallet<T>>::relay_dispatch_queue_size(para_id);
inclusion::Pallet::<T>::relay_dispatch_queue_size(para_id);
let ump_remaining = config.max_upward_queue_count - ump_msg_count;
let ump_remaining_bytes = config.max_upward_queue_size - ump_total_bytes;
let dmp_remaining_messages = <dmp::Pallet<T>>::dmq_contents(para_id)
let dmp_remaining_messages = dmp::Pallet::<T>::dmq_contents(para_id)
.into_iter()
.map(|msg| msg.sent_at)
.collect();
let valid_watermarks = <hrmp::Pallet<T>>::valid_watermarks(para_id);
let valid_watermarks = hrmp::Pallet::<T>::valid_watermarks(para_id);
let hrmp_inbound = InboundHrmpLimitations { valid_watermarks };
let hrmp_channels_out = <hrmp::Pallet<T>>::outbound_remaining_capacity(para_id)
let hrmp_channels_out = hrmp::Pallet::<T>::outbound_remaining_capacity(para_id)
.into_iter()
.map(|(para, (messages_remaining, bytes_remaining))| {
(para, OutboundHrmpChannelLimitations { messages_remaining, bytes_remaining })
@@ -516,7 +514,7 @@ pub fn backing_state<T: initializer::Config>(
/// Implementation for `AsyncBackingParams` function from the runtime API
pub fn async_backing_params<T: configuration::Config>() -> AsyncBackingParams {
<configuration::Pallet<T>>::config().async_backing_params
configuration::ActiveConfig::<T>::get().async_backing_params
}
/// Implementation for `DisabledValidators`
@@ -531,11 +529,10 @@ where
/// Returns the current state of the node features.
pub fn node_features<T: initializer::Config>() -> NodeFeatures {
<configuration::Pallet<T>>::config().node_features
configuration::ActiveConfig::<T>::get().node_features
}
/// Approval voting subsystem configuration parameters
pub fn approval_voting_params<T: initializer::Config>() -> ApprovalVotingParams {
let config = <configuration::Pallet<T>>::config();
config.approval_voting_params
configuration::ActiveConfig::<T>::get().approval_voting_params
}
@@ -22,7 +22,7 @@ use sp_std::collections::{btree_map::BTreeMap, vec_deque::VecDeque};
/// Returns the claimqueue from the scheduler
pub fn claim_queue<T: scheduler::Config>() -> BTreeMap<CoreIndex, VecDeque<ParaId>> {
<scheduler::Pallet<T>>::claimqueue()
scheduler::ClaimQueue::<T>::get()
.into_iter()
.map(|(core_index, entries)| {
(core_index, entries.into_iter().map(|e| e.para_id()).collect())
+23 -26
View File
@@ -86,8 +86,7 @@ pub mod pallet {
/// multiplexers. Reasonably, 100-1000. The dominant factor is the number of validators: safe
/// upper bound at 10k.
#[pallet::storage]
#[pallet::getter(fn validator_groups)]
pub(crate) type ValidatorGroups<T> = StorageValue<_, Vec<Vec<ValidatorIndex>>, ValueQuery>;
pub type ValidatorGroups<T> = StorageValue<_, Vec<Vec<ValidatorIndex>>, ValueQuery>;
/// One entry for each availability core. The i'th parachain belongs to the i'th core, with the
/// remaining cores all being on demand parachain multiplexers.
@@ -96,9 +95,7 @@ pub mod pallet {
/// * The number of parachains and parathread multiplexers
/// * The number of validators divided by `configuration.max_validators_per_core`.
#[pallet::storage]
#[pallet::getter(fn availability_cores)]
pub(crate) type AvailabilityCores<T: Config> =
StorageValue<_, Vec<CoreOccupiedType<T>>, ValueQuery>;
pub type AvailabilityCores<T: Config> = StorageValue<_, Vec<CoreOccupiedType<T>>, ValueQuery>;
/// Representation of a core in `AvailabilityCores`.
///
@@ -140,15 +137,13 @@ pub mod pallet {
/// Thus for all intents and purposes the effect of the session change is observed at the
/// block following the session change, block number of which we save in this storage value.
#[pallet::storage]
#[pallet::getter(fn session_start_block)]
pub(crate) type SessionStartBlock<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
pub type SessionStartBlock<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
/// One entry for each availability core. The `VecDeque` represents the assignments to be
/// scheduled on that core. The value contained here will not be valid after the end of
/// a block. Runtime APIs should be used to determine scheduled cores for the upcoming block.
#[pallet::storage]
#[pallet::getter(fn claimqueue)]
pub(crate) type ClaimQueue<T: Config> =
pub type ClaimQueue<T: Config> =
StorageValue<_, BTreeMap<CoreIndex, VecDeque<ParasEntryType<T>>>, ValueQuery>;
/// Assignments as tracked in the claim queue.
@@ -273,8 +268,8 @@ impl<T: Config> Pallet<T> {
ValidatorGroups::<T>::set(groups);
}
let now = <frame_system::Pallet<T>>::block_number() + One::one();
<SessionStartBlock<T>>::set(now);
let now = frame_system::Pallet::<T>::block_number() + One::one();
SessionStartBlock::<T>::set(now);
}
/// Free unassigned cores. Provide a list of cores that should be considered newly-freed along
@@ -355,9 +350,9 @@ impl<T: Config> Pallet<T> {
/// `AssignmentProvider`. A claim is considered expired if it's `ttl` field is lower than the
/// current block height.
fn drop_expired_claims_from_claimqueue() {
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
let availability_cores = AvailabilityCores::<T>::get();
let ttl = <configuration::Pallet<T>>::config().scheduler_params.ttl;
let ttl = configuration::ActiveConfig::<T>::get().scheduler_params.ttl;
ClaimQueue::<T>::mutate(|cq| {
for (idx, _) in (0u32..).zip(availability_cores) {
@@ -410,8 +405,8 @@ impl<T: Config> Pallet<T> {
core: CoreIndex,
at: BlockNumberFor<T>,
) -> Option<GroupIndex> {
let config = <configuration::Pallet<T>>::config();
let session_start_block = <SessionStartBlock<T>>::get();
let config = configuration::ActiveConfig::<T>::get();
let session_start_block = SessionStartBlock::<T>::get();
if at < session_start_block {
return None
@@ -442,8 +437,8 @@ impl<T: Config> Pallet<T> {
/// This only ever times out cores that have been occupied across a group rotation boundary.
pub(crate) fn availability_timeout_predicate(
) -> impl Fn(BlockNumberFor<T>) -> AvailabilityTimeoutStatus<BlockNumberFor<T>> {
let config = <configuration::Pallet<T>>::config();
let now = <frame_system::Pallet<T>>::block_number();
let config = configuration::ActiveConfig::<T>::get();
let now = frame_system::Pallet::<T>::block_number();
let rotation_info = Self::group_rotation_info(now);
let next_rotation = rotation_info.next_rotation_at();
@@ -470,8 +465,8 @@ impl<T: Config> Pallet<T> {
/// This can be used to avoid calling `availability_timeout_predicate` for each core in case
/// this function returns false.
pub(crate) fn availability_timeout_check_required() -> bool {
let config = <configuration::Pallet<T>>::config();
let now = <frame_system::Pallet<T>>::block_number() + One::one();
let config = configuration::ActiveConfig::<T>::get();
let now = frame_system::Pallet::<T>::block_number() + One::one();
let rotation_info = Self::group_rotation_info(now);
let current_window =
@@ -483,9 +478,10 @@ impl<T: Config> Pallet<T> {
pub(crate) fn group_rotation_info(
now: BlockNumberFor<T>,
) -> GroupRotationInfo<BlockNumberFor<T>> {
let session_start_block = Self::session_start_block();
let group_rotation_frequency =
<configuration::Pallet<T>>::config().scheduler_params.group_rotation_frequency;
let session_start_block = SessionStartBlock::<T>::get();
let group_rotation_frequency = configuration::ActiveConfig::<T>::get()
.scheduler_params
.group_rotation_frequency;
GroupRotationInfo { session_start_block, now, group_rotation_frequency }
}
@@ -505,8 +501,9 @@ impl<T: Config> Pallet<T> {
/// Return the next thing that will be scheduled on this core assuming it is currently
/// occupied and the candidate occupying it times out.
pub(crate) fn next_up_on_time_out(core: CoreIndex) -> Option<ScheduledCore> {
let max_availability_timeouts =
<configuration::Pallet<T>>::config().scheduler_params.max_availability_timeouts;
let max_availability_timeouts = configuration::ActiveConfig::<T>::get()
.scheduler_params
.max_availability_timeouts;
Self::next_up_on_available(core).or_else(|| {
// Or, if none, the claim currently occupying the core,
// as it would be put back on the queue after timing out if number of retries is not at
@@ -561,7 +558,7 @@ impl<T: Config> Pallet<T> {
// ClaimQueue related functions
//
fn claimqueue_lookahead() -> u32 {
<configuration::Pallet<T>>::config().scheduler_params.lookahead
configuration::ActiveConfig::<T>::get().scheduler_params.lookahead
}
/// Frees cores and fills the free claimqueue spots by popping from the `AssignmentProvider`.
@@ -580,7 +577,7 @@ impl<T: Config> Pallet<T> {
let n_lookahead = Self::claimqueue_lookahead().max(1);
let n_session_cores = T::AssignmentProvider::session_core_count();
let cq = ClaimQueue::<T>::get();
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let max_availability_timeouts = config.scheduler_params.max_availability_timeouts;
let ttl = config.scheduler_params.ttl;
@@ -172,7 +172,7 @@ mod v1 {
v0::ParathreadQueue::<T>::kill();
v0::ParathreadClaimIndex::<T>::kill();
let now = <frame_system::Pallet<T>>::block_number();
let now = frame_system::Pallet::<T>::block_number();
let scheduled = v0::Scheduled::<T>::take();
let sched_len = scheduled.len() as u64;
for core_assignment in scheduled {
@@ -182,7 +182,7 @@ mod v1 {
v1::add_to_claimqueue::<T>(core_idx, pe);
}
let parachains = paras::Pallet::<T>::parachains();
let parachains = paras::Parachains::<T>::get();
let availability_cores = v0::AvailabilityCores::<T>::take();
let mut new_availability_cores = Vec::new();
@@ -31,7 +31,7 @@ use crate::{
Scheduler, System, Test,
},
paras::{ParaGenesisArgs, ParaKind},
scheduler::{common::Assignment, ClaimQueue},
scheduler::{self, common::Assignment, ClaimQueue},
};
fn schedule_blank_para(id: ParaId) {
@@ -222,7 +222,7 @@ fn claimqueue_ttl_drop_fn_works() {
Scheduler::add_to_claimqueue(core_idx, paras_entry_non_expired.clone());
Scheduler::add_to_claimqueue(core_idx, paras_entry_expired.clone());
Scheduler::add_to_claimqueue(core_idx, paras_entry_non_expired.clone());
let cq = Scheduler::claimqueue();
let cq = scheduler::ClaimQueue::<Test>::get();
assert_eq!(cq.get(&core_idx).unwrap().len(), 3);
// Add a claim to the test assignment provider.
@@ -233,7 +233,7 @@ fn claimqueue_ttl_drop_fn_works() {
// Drop expired claim.
Scheduler::drop_expired_claims_from_claimqueue();
let cq = Scheduler::claimqueue();
let cq = scheduler::ClaimQueue::<Test>::get();
let cqc = cq.get(&core_idx).unwrap();
// Same number of claims, because a new claim is popped from `MockAssigner` instead of the
// expired one
@@ -392,7 +392,7 @@ fn fill_claimqueue_fills() {
);
// Sits on the same core as `para_a`
assert_eq!(
Scheduler::claimqueue().get(&CoreIndex(0)).unwrap()[1],
scheduler::ClaimQueue::<Test>::get().get(&CoreIndex(0)).unwrap()[1],
ParasEntry {
assignment: assignment_b.clone(),
availability_timeouts: 0,
@@ -483,7 +483,7 @@ fn schedule_schedules_including_just_freed() {
assert!(Scheduler::scheduled_paras().collect::<Vec<_>>().is_empty());
// All `core_queue`s should be empty
Scheduler::claimqueue()
scheduler::ClaimQueue::<Test>::get()
.iter()
.for_each(|(_core_idx, core_queue)| assert_eq!(core_queue.len(), 0))
}
@@ -603,7 +603,7 @@ fn schedule_clears_availability_cores() {
run_to_block(2, |_| None);
assert_eq!(Scheduler::claimqueue().len(), 3);
assert_eq!(scheduler::ClaimQueue::<Test>::get().len(), 3);
// cores 0, 1, and 2 should be occupied. mark them as such.
Scheduler::occupied(
@@ -620,7 +620,7 @@ fn schedule_clears_availability_cores() {
assert_eq!(cores[2].is_free(), false);
// All `core_queue`s should be empty
Scheduler::claimqueue()
scheduler::ClaimQueue::<Test>::get()
.iter()
.for_each(|(_core_idx, core_queue)| assert!(core_queue.len() == 0))
}
@@ -699,7 +699,7 @@ fn schedule_rotates_groups() {
_ => None,
});
let session_start_block = Scheduler::session_start_block();
let session_start_block = scheduler::SessionStartBlock::<Test>::get();
assert_eq!(session_start_block, 1);
MockAssigner::add_test_assignment(assignment_a.clone());
@@ -783,7 +783,7 @@ fn on_demand_claims_are_pruned_after_timing_out() {
// #2
now += 1;
run_to_block(now, |_| None);
assert_eq!(Scheduler::claimqueue().len(), 1);
assert_eq!(scheduler::ClaimQueue::<Test>::get().len(), 1);
// ParaId a is in the claimqueue.
assert!(claimqueue_contains_para_ids::<Test>(vec![para_a]));
@@ -949,13 +949,13 @@ fn next_up_on_available_uses_next_scheduled_or_none() {
{
assert_eq!(Scheduler::claimqueue_len(), 1);
assert_eq!(Scheduler::availability_cores().len(), 1);
assert_eq!(scheduler::AvailabilityCores::<Test>::get().len(), 1);
let mut map = BTreeMap::new();
map.insert(CoreIndex(0), para_a);
Scheduler::occupied(map);
let cores = Scheduler::availability_cores();
let cores = scheduler::AvailabilityCores::<Test>::get();
match &cores[0] {
CoreOccupied::Paras(entry) => assert_eq!(entry, &entry_a),
_ => panic!("There should only be one test assigner core"),
@@ -1006,14 +1006,14 @@ fn next_up_on_time_out_reuses_claim_if_nothing_queued() {
run_to_block(2, |_| None);
{
assert_eq!(Scheduler::claimqueue().len(), 1);
assert_eq!(Scheduler::availability_cores().len(), 1);
assert_eq!(scheduler::ClaimQueue::<Test>::get().len(), 1);
assert_eq!(scheduler::AvailabilityCores::<Test>::get().len(), 1);
let mut map = BTreeMap::new();
map.insert(CoreIndex(0), para_a);
Scheduler::occupied(map);
let cores = Scheduler::availability_cores();
let cores = scheduler::AvailabilityCores::<Test>::get();
match cores.get(0).unwrap() {
CoreOccupied::Paras(entry) => {
assert_eq!(entry.assignment, assignment_a.clone());
@@ -1058,7 +1058,7 @@ fn session_change_requires_reschedule_dropping_removed_paras() {
new_test_ext(genesis_config).execute_with(|| {
// Setting explicit core count
MockAssigner::set_core_count(5);
let coretime_ttl = <configuration::Pallet<Test>>::config().scheduler_params.ttl;
let coretime_ttl = configuration::ActiveConfig::<Test>::get().scheduler_params.ttl;
schedule_blank_para(para_a);
schedule_blank_para(para_b);
@@ -1085,7 +1085,7 @@ fn session_change_requires_reschedule_dropping_removed_paras() {
_ => None,
});
assert_eq!(Scheduler::claimqueue().len(), 2);
assert_eq!(scheduler::ClaimQueue::<Test>::get().len(), 2);
let groups = ValidatorGroups::<Test>::get();
assert_eq!(groups.len(), 5);
@@ -1116,7 +1116,7 @@ fn session_change_requires_reschedule_dropping_removed_paras() {
Scheduler::free_cores_and_fill_claimqueue(BTreeMap::new(), 3);
assert_eq!(
Scheduler::claimqueue(),
scheduler::ClaimQueue::<Test>::get(),
vec![(
CoreIndex(0),
vec![ParasEntry::new(
@@ -1156,7 +1156,7 @@ fn session_change_requires_reschedule_dropping_removed_paras() {
_ => None,
});
assert_eq!(Scheduler::claimqueue().len(), 2);
assert_eq!(scheduler::ClaimQueue::<Test>::get().len(), 2);
let groups = ValidatorGroups::<Test>::get();
assert_eq!(groups.len(), 5);
@@ -1164,7 +1164,7 @@ fn session_change_requires_reschedule_dropping_removed_paras() {
Scheduler::free_cores_and_fill_claimqueue(BTreeMap::new(), 4);
assert_eq!(
Scheduler::claimqueue(),
scheduler::ClaimQueue::<Test>::get(),
vec![
(
CoreIndex(0),
@@ -86,28 +86,23 @@ pub mod pallet {
/// The earliest session for which previous session info is stored.
#[pallet::storage]
#[pallet::getter(fn earliest_stored_session)]
pub(crate) type EarliestStoredSession<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
pub type EarliestStoredSession<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
/// Session information in a rolling window.
/// Should have an entry in range `EarliestStoredSession..=CurrentSessionIndex`.
/// Does not have any entries before the session index in the first session change notification.
#[pallet::storage]
#[pallet::getter(fn session_info)]
pub(crate) type Sessions<T: Config> = StorageMap<_, Identity, SessionIndex, SessionInfo>;
pub type Sessions<T: Config> = StorageMap<_, Identity, SessionIndex, SessionInfo>;
/// The validator account keys of the validators actively participating in parachain consensus.
// We do not store this in `SessionInfo` to avoid leaking the `AccountId` type to the client,
// which would complicate the migration process if we are to change it in the future.
#[pallet::storage]
#[pallet::getter(fn account_keys)]
pub(crate) type AccountKeys<T: Config> =
StorageMap<_, Identity, SessionIndex, Vec<AccountId<T>>>;
pub type AccountKeys<T: Config> = StorageMap<_, Identity, SessionIndex, Vec<AccountId<T>>>;
/// Executor parameter set for a given session index
#[pallet::storage]
#[pallet::getter(fn session_executor_params)]
pub(crate) type SessionExecutorParams<T: Config> =
pub type SessionExecutorParams<T: Config> =
StorageMap<_, Identity, SessionIndex, ExecutorParams>;
}
@@ -120,7 +115,7 @@ pub trait AuthorityDiscoveryConfig {
impl<T: pallet_authority_discovery::Config> AuthorityDiscoveryConfig for T {
fn authorities() -> Vec<AuthorityDiscoveryId> {
<pallet_authority_discovery::Pallet<T>>::current_authorities().to_vec()
pallet_authority_discovery::Pallet::<T>::current_authorities().to_vec()
}
}
@@ -129,17 +124,17 @@ impl<T: Config> Pallet<T> {
pub(crate) fn initializer_on_new_session(
notification: &crate::initializer::SessionChangeNotification<BlockNumberFor<T>>,
) {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
let dispute_period = config.dispute_period;
let validators = notification.validators.clone().into();
let discovery_keys = <T as AuthorityDiscoveryConfig>::authorities();
let assignment_keys = AssignmentKeysUnsafe::<T>::get();
let active_set = <shared::Pallet<T>>::active_validator_indices();
let active_set = shared::ActiveValidatorIndices::<T>::get();
let validator_groups = <scheduler::Pallet<T>>::validator_groups().into();
let n_cores = <scheduler::Pallet<T>>::availability_cores().len() as u32;
let validator_groups = scheduler::ValidatorGroups::<T>::get().into();
let n_cores = scheduler::AvailabilityCores::<T>::get().len() as u32;
let zeroth_delay_tranche_width = config.zeroth_delay_tranche_width;
let relay_vrf_modulo_samples = config.relay_vrf_modulo_samples;
let n_delay_tranches = config.n_delay_tranches;
@@ -92,7 +92,7 @@ fn new_session_every_block(n: BlockNumber) -> Option<SessionChangeNotification<B
fn session_pruning_is_based_on_dispute_period() {
new_test_ext(genesis_config()).execute_with(|| {
// Dispute period starts at 2
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert_eq!(config.dispute_period, 2);
// Move to session 10
@@ -109,11 +109,11 @@ fn session_pruning_is_based_on_dispute_period() {
Configuration::set_dispute_period(RuntimeOrigin::root(), dispute_period).unwrap();
// Dispute period does not automatically change
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert_eq!(config.dispute_period, 2);
// Two sessions later it will though
run_to_block(120, session_changes);
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert_eq!(config.dispute_period, 5);
run_to_block(200, session_changes);
@@ -128,7 +128,7 @@ fn session_pruning_is_based_on_dispute_period() {
// Two sessions later it kicks in
run_to_block(220, session_changes);
let config = Configuration::config();
let config = configuration::ActiveConfig::<Test>::get();
assert_eq!(config.dispute_period, 16);
// Earliest session stays the same
assert_eq!(EarliestStoredSession::<Test>::get(), 21 - dispute_period);
@@ -183,7 +183,7 @@ fn session_info_active_subsets() {
new_test_ext(genesis_config()).execute_with(|| {
ParasShared::set_active_validators_with_indices(active_set.clone(), validators.clone());
assert_eq!(ParasShared::active_validator_indices(), active_set);
assert_eq!(shared::ActiveValidatorIndices::<Test>::get(), active_set);
AssignmentKeysUnsafe::<Test>::set(unscrambled_assignment.clone());
crate::mock::set_discovery_authorities(unscrambled_discovery.clone());
+5 -10
View File
@@ -138,25 +138,20 @@ pub mod pallet {
/// The current session index.
#[pallet::storage]
#[pallet::getter(fn session_index)]
pub(super) type CurrentSessionIndex<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
pub type CurrentSessionIndex<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
/// All the validators actively participating in parachain consensus.
/// Indices are into the broader validator set.
#[pallet::storage]
#[pallet::getter(fn active_validator_indices)]
pub(super) type ActiveValidatorIndices<T: Config> =
StorageValue<_, Vec<ValidatorIndex>, ValueQuery>;
pub type ActiveValidatorIndices<T: Config> = StorageValue<_, Vec<ValidatorIndex>, ValueQuery>;
/// The parachain attestation keys of the validators actively participating in parachain
/// consensus. This should be the same length as `ActiveValidatorIndices`.
#[pallet::storage]
#[pallet::getter(fn active_validator_keys)]
pub(super) type ActiveValidatorKeys<T: Config> = StorageValue<_, Vec<ValidatorId>, ValueQuery>;
pub type ActiveValidatorKeys<T: Config> = StorageValue<_, Vec<ValidatorId>, ValueQuery>;
/// All allowed relay-parents.
#[pallet::storage]
#[pallet::getter(fn allowed_relay_parents)]
pub(crate) type AllowedRelayParents<T: Config> =
StorageValue<_, AllowedRelayParentsTracker<T::Hash, BlockNumberFor<T>>, ValueQuery>;
@@ -218,13 +213,13 @@ impl<T: Config> Pallet<T> {
/// Return the session index that should be used for any future scheduled changes.
pub fn scheduled_session() -> SessionIndex {
Self::session_index().saturating_add(SESSION_DELAY)
CurrentSessionIndex::<T>::get().saturating_add(SESSION_DELAY)
}
/// Fetches disabled validators list from session pallet.
/// CAVEAT: this might produce incorrect results on session boundaries
pub fn disabled_validators() -> Vec<ValidatorIndex> {
let shuffled_indices = Pallet::<T>::active_validator_indices();
let shuffled_indices = ActiveValidatorIndices::<T>::get();
// mapping from raw validator index to `ValidatorIndex`
// this computation is the same within a session, but should be cheap
let reverse_index = shuffled_indices
@@ -17,7 +17,8 @@
use super::*;
use crate::{
configuration::HostConfiguration,
mock::{new_test_ext, MockGenesisConfig, ParasShared},
mock::{new_test_ext, MockGenesisConfig, ParasShared, Test},
shared,
};
use assert_matches::assert_matches;
use keyring::Sr25519Keyring;
@@ -120,10 +121,10 @@ fn sets_and_shuffles_validators() {
])
);
assert_eq!(ParasShared::active_validator_keys(), validators);
assert_eq!(shared::ActiveValidatorKeys::<Test>::get(), validators);
assert_eq!(
ParasShared::active_validator_indices(),
shared::ActiveValidatorIndices::<Test>::get(),
vec![
ValidatorIndex(4),
ValidatorIndex(1),
@@ -155,10 +156,10 @@ fn sets_truncates_and_shuffles_validators() {
assert_eq!(validators, validator_pubkeys(&[Sr25519Keyring::Ferdie, Sr25519Keyring::Bob,]));
assert_eq!(ParasShared::active_validator_keys(), validators);
assert_eq!(shared::ActiveValidatorKeys::<Test>::get(), validators);
assert_eq!(
ParasShared::active_validator_indices(),
shared::ActiveValidatorIndices::<Test>::get(),
vec![ValidatorIndex(4), ValidatorIndex(1),]
);
});
+20 -12
View File
@@ -15,13 +15,14 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::{
configuration,
inclusion::{
tests::run_to_block_default_notifications as run_to_block, AggregateMessageOrigin,
AggregateMessageOrigin::Ump, UmpAcceptanceCheckErr, UmpQueueId,
},
mock::{
assert_last_event, assert_last_events, new_test_ext, Configuration, MessageQueue,
MessageQueueSize, MockGenesisConfig, ParaInclusion, Processed, System, Test, *,
assert_last_event, assert_last_events, new_test_ext, MessageQueue, MessageQueueSize,
MockGenesisConfig, ParaInclusion, Processed, System, Test, *,
},
};
use frame_support::{
@@ -88,7 +89,7 @@ fn queue_upward_msg(para: ParaId, msg: UpwardMessage) {
fn try_queue_upward_msg(para: ParaId, msg: UpwardMessage) -> Result<(), UmpAcceptanceCheckErr> {
let msgs = vec![msg];
ParaInclusion::check_upward_messages(&Configuration::config(), para, &msgs)?;
ParaInclusion::check_upward_messages(&configuration::ActiveConfig::<Test>::get(), para, &msgs)?;
ParaInclusion::receive_upward_messages(para, msgs.as_slice());
Ok(())
}
@@ -107,7 +108,12 @@ mod check_upward_messages {
/// Check that these messages *could* be queued.
fn check(para: ParaId, msgs: Vec<UpwardMessage>, err: Option<UmpAcceptanceCheckErr>) {
assert_eq!(
ParaInclusion::check_upward_messages(&Configuration::config(), para, &msgs[..]).err(),
ParaInclusion::check_upward_messages(
&configuration::ActiveConfig::<Test>::get(),
para,
&msgs[..]
)
.err(),
err
);
}
@@ -132,7 +138,8 @@ mod check_upward_messages {
fn num_per_candidate_exceeded_error() {
new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| {
let _g = frame_support::StorageNoopGuard::default();
let permitted = Configuration::config().max_upward_message_num_per_candidate;
let permitted =
configuration::ActiveConfig::<Test>::get().max_upward_message_num_per_candidate;
for sent in 0..permitted + 1 {
check(P_0, vec![msg(""); sent as usize], None);
@@ -151,8 +158,9 @@ mod check_upward_messages {
fn size_per_message_exceeded_error() {
new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| {
let _g = frame_support::StorageNoopGuard::default();
let max_size = Configuration::config().max_upward_message_size;
let max_per_candidate = Configuration::config().max_upward_message_num_per_candidate;
let max_size = configuration::ActiveConfig::<Test>::get().max_upward_message_size;
let max_per_candidate =
configuration::ActiveConfig::<Test>::get().max_upward_message_num_per_candidate;
for msg_size in 0..=max_size {
check(P_0, vec![vec![0; msg_size as usize]], None);
@@ -175,7 +183,7 @@ mod check_upward_messages {
#[test]
fn queue_count_exceeded_error() {
new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| {
let limit = Configuration::config().max_upward_queue_count as u64;
let limit = configuration::ActiveConfig::<Test>::get().max_upward_queue_count as u64;
for _ in 0..limit {
check(P_0, vec![msg("")], None);
@@ -198,10 +206,10 @@ mod check_upward_messages {
#[test]
fn queue_size_exceeded_error() {
new_test_ext(GenesisConfigBuilder::large_queue_count().build()).execute_with(|| {
let limit = Configuration::config().max_upward_queue_size as u64;
let limit = configuration::ActiveConfig::<Test>::get().max_upward_queue_size as u64;
assert_eq!(pallet_message_queue::ItemHeader::<MessageQueueSize>::max_encoded_len(), 5);
assert!(
Configuration::config().max_upward_queue_size <
configuration::ActiveConfig::<Test>::get().max_upward_queue_size <
crate::inclusion::MaxUmpMessageLenOf::<Test>::get(),
"Test will not work"
);
@@ -351,7 +359,7 @@ fn queue_enact_too_long_ignored() {
#[test]
fn relay_dispatch_queue_size_is_updated() {
new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| {
let cfg = Configuration::config();
let cfg = configuration::ActiveConfig::<Test>::get();
for p in 0..100 {
let para = p.into();
@@ -430,7 +438,7 @@ fn verify_relay_dispatch_queue_size_is_externally_accessible() {
// Make sure that the relay dispatch queue size storage entry is accessible via well known
// keys and is decodable into a (u32, u32).
new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| {
let cfg = Configuration::config();
let cfg = configuration::ActiveConfig::<Test>::get();
for para in 0..10 {
let para = para.into();
+3 -3
View File
@@ -32,10 +32,10 @@ pub fn make_persisted_validation_data<T: paras::Config + hrmp::Config>(
relay_parent_number: BlockNumberFor<T>,
relay_parent_storage_root: T::Hash,
) -> Option<PersistedValidationData<T::Hash, BlockNumberFor<T>>> {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
Some(PersistedValidationData {
parent_head: <paras::Pallet<T>>::para_head(&para_id)?,
parent_head: paras::Heads::<T>::get(&para_id)?,
relay_parent_number,
relay_parent_storage_root,
max_pov_size: config.max_pov_size,
@@ -49,7 +49,7 @@ pub fn make_persisted_validation_data_with_parent<T: configuration::Config>(
relay_parent_storage_root: T::Hash,
parent_head: HeadData,
) -> PersistedValidationData<T::Hash, BlockNumberFor<T>> {
let config = <configuration::Pallet<T>>::config();
let config = configuration::ActiveConfig::<T>::get();
PersistedValidationData {
parent_head,
+5 -3
View File
@@ -1199,9 +1199,11 @@ parameter_types! {
pub struct ParaHeadsRootProvider;
impl BeefyDataProvider<H256> for ParaHeadsRootProvider {
fn extra_data() -> H256 {
let mut para_heads: Vec<(u32, Vec<u8>)> = Paras::parachains()
let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
.into_iter()
.filter_map(|id| Paras::para_head(&id).map(|head| (id.into(), head.0)))
.filter_map(|id| {
parachains_paras::Heads::<Runtime>::get(&id).map(|head| (id.into(), head.0))
})
.collect();
para_heads.sort();
binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
@@ -1446,7 +1448,7 @@ pub mod migrations {
impl coretime::migration::GetLegacyLease<BlockNumber> for GetLegacyLeaseImpl {
fn get_parachain_lease_in_blocks(para: ParaId) -> Option<BlockNumber> {
let now = frame_system::Pallet::<Runtime>::block_number();
let lease = slots::Pallet::<Runtime>::lease(para);
let lease = slots::Leases::<Runtime>::get(para);
if lease.is_empty() {
return None;
}
+5 -3
View File
@@ -354,9 +354,11 @@ parameter_types! {
pub struct ParaHeadsRootProvider;
impl BeefyDataProvider<H256> for ParaHeadsRootProvider {
fn extra_data() -> H256 {
let mut para_heads: Vec<(u32, Vec<u8>)> = Paras::parachains()
let mut para_heads: Vec<(u32, Vec<u8>)> = parachains_paras::Parachains::<Runtime>::get()
.into_iter()
.filter_map(|id| Paras::para_head(&id).map(|head| (id.into(), head.0)))
.filter_map(|id| {
parachains_paras::Heads::<Runtime>::get(&id).map(|head| (id.into(), head.0))
})
.collect();
para_heads.sort_by_key(|k| k.0);
binary_merkle_tree::merkle_root::<mmr::Hashing, _>(
@@ -1615,7 +1617,7 @@ pub mod migrations {
impl coretime::migration::GetLegacyLease<BlockNumber> for GetLegacyLeaseImpl {
fn get_parachain_lease_in_blocks(para: ParaId) -> Option<BlockNumber> {
let now = frame_system::Pallet::<Runtime>::block_number();
let lease = slots::Pallet::<Runtime>::lease(para);
let lease = slots::Leases::<Runtime>::get(para);
if lease.is_empty() {
return None;
}
+16
View File
@@ -0,0 +1,16 @@
# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0
# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json
title: Removed `pallet::getter` usage from Polkadot Runtime pallets
doc:
- audience: Runtime Dev
description: |
This PR removes all the `pallet::getter` usages from the Polkadot Runtime pallets, and updates dependant runtimes accordingly.
The syntax `StorageItem::<T, I>::get()` should be used instead.
crates:
- name: polkadot-runtime-common
- name: polkadot-runtime-parachains
- name: rococo-runtime
- name: westend-runtime