From a4c726ef4731d9d111658cf97d8323439b4c643f Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 13:03:20 +0100 Subject: [PATCH 01/16] removed `pallet::getter` usage from `polkadot-runtime-common` Signed-off-by: Matteo Muraca --- .../runtime/common/src/assigned_slots/mod.rs | 64 +++++++++---------- polkadot/runtime/common/src/auctions.rs | 28 ++++---- polkadot/runtime/common/src/claims.rs | 44 ++++++------- polkadot/runtime/common/src/crowdloan/mod.rs | 60 ++++++++--------- .../runtime/common/src/integration_tests.rs | 64 ++++++++++--------- polkadot/runtime/common/src/slots/mod.rs | 1 - polkadot/runtime/rococo/src/lib.rs | 2 +- polkadot/runtime/westend/src/lib.rs | 2 +- 8 files changed, 127 insertions(+), 138 deletions(-) diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index 4f032f4dfa3b..0f2440d058f3 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -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 = StorageMap<_, Twox64Concat, ParaId, (LeasePeriodOf, LeasePeriodOf), OptionQuery>; /// Number of assigned (and active) permanent slots. #[pallet::storage] - #[pallet::getter(fn permanent_slot_count)] pub type PermanentSlotCount = StorageValue<_, u32, ValueQuery>; /// Assigned temporary slots. #[pallet::storage] - #[pallet::getter(fn temporary_slots)] pub type TemporarySlots = 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 = 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 = StorageValue<_, u32, ValueQuery>; /// The max number of temporary slots that can be assigned. @@ -364,7 +359,7 @@ pub mod pallet { }; if lease_period_start == SlotLeasePeriodStart::Current && - Self::active_temporary_slot_count() < T::MaxTemporarySlotPerLeasePeriod::get() + ActiveTemporarySlotCount::::get() < T::MaxTemporarySlotPerLeasePeriod::get() { // Try to allocate slot directly match Self::configure_slot_lease( @@ -965,7 +960,7 @@ mod tests { RuntimeOrigin::root(), ParaId::from(2_u32), )); - assert_eq!(AssignedSlots::permanent_slot_count(), 2); + assert_eq!(assigned_slots::PermanentSlotCount::::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::::get(), 0); + assert_eq!(assigned_slots::PermanentSlots::::get(ParaId::from(1_u32)), None); assert_ok!(AssignedSlots::assign_perm_parachain_slot( RuntimeOrigin::root(), @@ -1004,9 +999,12 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(1_u32)), true); - assert_eq!(AssignedSlots::permanent_slot_count(), 1); + assert_eq!(assigned_slots::PermanentSlotCount::::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::::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::::get(), 6); // Attempt to assign one more temp slot assert_ok!(TestRegistrar::::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::::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::::get(), 1); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::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::::get(ParaId::from(1_u32))); assert_eq!(TestRegistrar::::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::::get(), 1); assert_eq!( - AssignedSlots::temporary_slots(ParaId::from(1_u32)), + assigned_slots::TemporarySlots::::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::::get(ParaId::from(1_u32))); // Para lease ended, downgraded back to on-demand parachain assert_eq!(TestRegistrar::::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::::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::::get(ParaId::from(1_u32))); assert_eq!(TestRegistrar::::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::::get(), 1); }); } @@ -1270,7 +1268,7 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(3_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(4_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(5_u32)), false); - assert_eq!(AssignedSlots::active_temporary_slot_count(), 2); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::get(), 2); } // Block 6-11, Period 2-3 @@ -1282,7 +1280,7 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(3_u32)), true); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(4_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(5_u32)), false); - assert_eq!(AssignedSlots::active_temporary_slot_count(), 2); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::get(), 2); } // Block 12-17, Period 4-5 @@ -1294,7 +1292,7 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(3_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(4_u32)), true); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(5_u32)), true); - assert_eq!(AssignedSlots::active_temporary_slot_count(), 2); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::get(), 2); } // Block 18-23, Period 6-7 @@ -1306,7 +1304,7 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(3_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(4_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(5_u32)), false); - assert_eq!(AssignedSlots::active_temporary_slot_count(), 2); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::get(), 2); } // Block 24-29, Period 8-9 @@ -1318,7 +1316,7 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(3_u32)), true); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(4_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(5_u32)), false); - assert_eq!(AssignedSlots::active_temporary_slot_count(), 2); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::get(), 2); } // Block 30-35, Period 10-11 @@ -1330,7 +1328,7 @@ mod tests { assert_eq!(TestRegistrar::::is_parachain(ParaId::from(3_u32)), false); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(4_u32)), true); assert_eq!(TestRegistrar::::is_parachain(ParaId::from(5_u32)), true); - assert_eq!(AssignedSlots::active_temporary_slot_count(), 2); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::get(), 2); } }); } @@ -1386,9 +1384,9 @@ mod tests { ParaId::from(1_u32), )); - assert_eq!(AssignedSlots::permanent_slot_count(), 0); + assert_eq!(assigned_slots::PermanentSlotCount::::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::::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::::get(), 0); + assert_eq!(assigned_slots::ActiveTemporarySlotCount::::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::::get(ParaId::from(1_u32)), None); assert_eq!(Slots::already_leased(ParaId::from(1_u32), 0, 1), false); }); diff --git a/polkadot/runtime/common/src/auctions.rs b/polkadot/runtime/common/src/auctions.rs index 46ab673a7a0c..9e2b670c17fd 100644 --- a/polkadot/runtime/common/src/auctions.rs +++ b/polkadot/runtime/common/src/auctions.rs @@ -174,7 +174,6 @@ pub mod pallet { /// Number of auctions started so far. #[pallet::storage] - #[pallet::getter(fn auction_counter)] pub type AuctionCounter = 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 = StorageValue<_, (LeasePeriodOf, BlockNumberFor)>; /// Amounts currently reserved in the accounts of the bidders currently winning /// (sub-)ranges. #[pallet::storage] - #[pallet::getter(fn reserved_amounts)] pub type ReservedAmounts = StorageMap<_, Twox64Concat, (T::AccountId, ParaId), BalanceOf>; @@ -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 = StorageMap<_, Twox64Concat, BlockNumberFor, WinningData>; #[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::::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::::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::::get(0), Some(winning)); run_to_block(9); assert_eq!( @@ -1466,14 +1462,14 @@ mod tests { Auctions::auction_status(System::block_number()), AuctionStatus::::EndingPeriod(0, 0) ); - assert_eq!(Auctions::winning(0), Some(winning)); + assert_eq!(Winning::::get(0), Some(winning)); run_to_block(11); assert_eq!( Auctions::auction_status(System::block_number()), AuctionStatus::::EndingPeriod(1, 0) ); - assert_eq!(Auctions::winning(1), Some(winning)); + assert_eq!(Winning::::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::::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::::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::::get(0), Some(winning)); run_to_block(9); assert_eq!( @@ -1582,31 +1578,31 @@ mod tests { Auctions::auction_status(System::block_number()), AuctionStatus::::EndingPeriod(0, 0) ); - assert_eq!(Auctions::winning(0), Some(winning)); + assert_eq!(Winning::::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::::get(0), Some(winning)); run_to_block(20); assert_eq!( Auctions::auction_status(System::block_number()), AuctionStatus::::EndingPeriod(1, 0) ); - assert_eq!(Auctions::winning(1), Some(winning)); + assert_eq!(Winning::::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::::get(1), Some(winning)); run_to_block(30); assert_eq!( Auctions::auction_status(System::block_number()), AuctionStatus::::EndingPeriod(2, 0) ); - assert_eq!(Auctions::winning(2), Some(winning)); + assert_eq!(Winning::::get(2), Some(winning)); set_last_random(H256::from([254; 32]), 40); run_to_block(40); diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index 57a95b22af38..fa5775a2b87a 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -224,20 +224,17 @@ pub mod pallet { } #[pallet::storage] - #[pallet::getter(fn claims)] - pub(super) type Claims = StorageMap<_, Identity, EthereumAddress, BalanceOf>; + pub type Claims = StorageMap<_, Identity, EthereumAddress, BalanceOf>; #[pallet::storage] - #[pallet::getter(fn total)] - pub(super) type Total = StorageValue<_, BalanceOf, ValueQuery>; + pub type Total = StorageValue<_, BalanceOf, 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 = + pub type Vesting = StorageMap<_, Identity, EthereumAddress, (BalanceOf, BalanceOf, BlockNumberFor)>; /// The statement kind that must be signed, if any. @@ -572,9 +569,10 @@ impl Pallet { } fn process_claim(signer: EthereumAddress, dest: T::AccountId) -> sp_runtime::DispatchResult { - let balance_due = >::get(&signer).ok_or(Error::::SignerHasNoClaim)?; + let balance_due = Claims::::get(&signer).ok_or(Error::::SignerHasNoClaim)?; - let new_total = Self::total().checked_sub(&balance_due).ok_or(Error::::PotUnderflow)?; + let new_total = + Total::::get().checked_sub(&balance_due).ok_or(Error::::PotUnderflow)?; let vesting = Vesting::::get(&signer); if vesting.is_some() && T::VestingSchedule::vesting_balance(&dest).is_some() { @@ -875,13 +873,13 @@ pub(super) mod tests { #[test] fn basic_setup_works() { new_test_ext().execute_with(|| { - assert_eq!(Claims::total(), total_claims()); - assert_eq!(Claims::claims(ð(&alice())), Some(100)); - assert_eq!(Claims::claims(ð(&dave())), Some(200)); - assert_eq!(Claims::claims(ð(&eve())), Some(300)); - assert_eq!(Claims::claims(ð(&frank())), Some(400)); - assert_eq!(Claims::claims(&EthereumAddress::default()), None); - assert_eq!(Claims::vesting(ð(&alice())), Some((50, 10, 1))); + assert_eq!(claims::Total::::get(), total_claims()); + assert_eq!(claims::Claims::::get(ð(&alice())), Some(100)); + assert_eq!(claims::Claims::::get(ð(&dave())), Some(200)); + assert_eq!(claims::Claims::::get(ð(&eve())), Some(300)); + assert_eq!(claims::Claims::::get(ð(&frank())), Some(400)); + assert_eq!(claims::Claims::::get(&EthereumAddress::default()), None); + assert_eq!(claims::Vesting::::get(ð(&alice())), Some((50, 10, 1))); }); } @@ -905,7 +903,7 @@ pub(super) 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::::get(), total_claims() - 100); }); } @@ -938,7 +936,7 @@ pub(super) 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::::get(), total_claims() - 100); }); } @@ -1042,7 +1040,7 @@ pub(super) 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::::get(), total_claims() - 200); let s = sig::(&dave(), &42u64.encode(), StatementKind::Regular.to_text()); let r = Claims::claim_attest( @@ -1075,7 +1073,7 @@ pub(super) 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::::get(), total_claims() - 300); }); } @@ -1096,7 +1094,7 @@ pub(super) 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::::get(), total_claims() - 400); }); } @@ -1160,7 +1158,7 @@ pub(super) mod tests { Error::::SignerHasNoClaim, ); assert_ok!(Claims::mint_claim(RuntimeOrigin::root(), eth(&bob()), 200, None, None)); - assert_eq!(Claims::total(), total_claims() + 200); + assert_eq!(claims::Total::::get(), total_claims() + 200); assert_ok!(Claims::claim( RuntimeOrigin::none(), 69, @@ -1168,7 +1166,7 @@ pub(super) 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::::get(), total_claims()); }); } @@ -1322,7 +1320,7 @@ pub(super) mod tests { None )); // New total - assert_eq!(Claims::total(), total_claims() + 200); + assert_eq!(claims::Total::::get(), total_claims() + 200); // They should not be able to claim assert_noop!( diff --git a/polkadot/runtime/common/src/crowdloan/mod.rs b/polkadot/runtime/common/src/crowdloan/mod.rs index 35d075f2ff6c..c3413bda9bf9 100644 --- a/polkadot/runtime/common/src/crowdloan/mod.rs +++ b/polkadot/runtime/common/src/crowdloan/mod.rs @@ -229,8 +229,7 @@ pub mod pallet { /// Info on all of the funds. #[pallet::storage] - #[pallet::getter(fn funds)] - pub(crate) type Funds = StorageMap< + pub type Funds = StorageMap< _, Twox64Concat, ParaId, @@ -240,18 +239,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 = StorageValue<_, Vec, ValueQuery>; + pub type NewRaise = StorageValue<_, Vec, 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 = StorageValue<_, u32, ValueQuery>; + pub type EndingsCount = StorageValue<_, u32, ValueQuery>; /// Tracker for the next available fund index #[pallet::storage] - #[pallet::getter(fn next_fund_index)] - pub(super) type NextFundIndex = StorageValue<_, u32, ValueQuery>; + pub type NextFundIndex = StorageValue<_, u32, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -342,7 +338,7 @@ pub mod pallet { let new_raise = NewRaise::::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::::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 @@ -416,7 +412,7 @@ pub mod pallet { ensure!(depositor == manager, Error::::InvalidOrigin); ensure!(T::Registrar::is_registered(index), Error::::InvalidParaId); - let fund_index = Self::next_fund_index(); + let fund_index = NextFundIndex::::get(); let new_fund_index = fund_index.checked_add(1).ok_or(Error::::Overflow)?; let deposit = T::SubmissionDeposit::get(); @@ -486,7 +482,7 @@ pub mod pallet { ) -> DispatchResult { ensure_signed(origin)?; - let mut fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let mut fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; let now = frame_system::Pallet::::block_number(); let fund_account = Self::fund_account_id(fund.fund_index); Self::ensure_crowdloan_ended(now, &fund_account, &fund)?; @@ -519,7 +515,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { ensure_signed(origin)?; - let mut fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let mut fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; let now = frame_system::Pallet::::block_number(); let fund_account = Self::fund_account_id(fund.fund_index); Self::ensure_crowdloan_ended(now, &fund_account, &fund)?; @@ -562,7 +558,7 @@ pub mod pallet { pub fn dissolve(origin: OriginFor, #[pallet::compact] index: ParaId) -> DispatchResult { let who = ensure_signed(origin)?; - let fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; let now = frame_system::Pallet::::block_number(); // Only allow dissolution when the raised funds goes to zero, @@ -599,7 +595,7 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; - let fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; Funds::::insert( index, @@ -630,7 +626,7 @@ pub mod pallet { let who = ensure_signed(origin)?; ensure!(memo.len() <= T::MaxMemoLength::get().into(), Error::::MemoTooLarge); - let fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; let (balance, _) = Self::contribution_get(fund.fund_index, &who); ensure!(balance > Zero::zero(), Error::::NoContributions); @@ -647,7 +643,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::poke())] pub fn poke(origin: OriginFor, index: ParaId) -> DispatchResult { ensure_signed(origin)?; - let fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; ensure!(!fund.raised.is_zero(), Error::::NoContributions); ensure!(!NewRaise::::get().contains(&index), Error::::AlreadyInNewRaise); NewRaise::::append(index); @@ -757,7 +753,7 @@ impl Pallet { existence: ExistenceRequirement, ) -> DispatchResult { ensure!(value >= T::MinContribution::get(), Error::::ContributionTooSmall); - let mut fund = Self::funds(index).ok_or(Error::::InvalidParaId)?; + let mut fund = Funds::::get(index).ok_or(Error::::InvalidParaId)?; fund.raised = fund.raised.checked_add(&value).ok_or(Error::::Overflow)?; ensure!(fund.raised <= fund.cap, Error::::CapExceeded); @@ -811,7 +807,7 @@ impl Pallet { }, } } else { - let endings_count = Self::endings_count(); + let endings_count = EndingsCount::::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::::get(ParaId::from(0)), None); let empty: Vec = Vec::new(); - assert_eq!(Crowdloan::new_raise(), empty); + assert_eq!(crowdloan::NewRaise::::get(), empty); assert_eq!(Crowdloan::contribution_get(0u32, &1).0, 0); - assert_eq!(Crowdloan::endings_count(), 0); + assert_eq!(crowdloan::EndingsCount::::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::::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 = Vec::new(); - assert_eq!(Crowdloan::new_raise(), empty); + assert_eq!(crowdloan::NewRaise::::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::::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 = Vec::new(); - assert_eq!(Crowdloan::new_raise(), empty); + assert_eq!(crowdloan::NewRaise::::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::::get(), vec![para]); - let fund = Crowdloan::funds(para).unwrap(); + let fund = crowdloan::Funds::::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::::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::::get(), 1); }); } @@ -1873,10 +1869,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::::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::::get(para_1).unwrap(); // Some things stay the same assert_eq!(old_crowdloan.depositor, new_crowdloan.depositor); @@ -1937,7 +1933,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::::get(), vec![para_1]); assert_noop!( Crowdloan::poke(RuntimeOrigin::signed(1), para_1), Error::::AlreadyInNewRaise diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index 3aa291f0f1f3..83b7e64468a3 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -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::::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::::get(ParaId::from(2000)).unwrap(); let crowdloan_1 = Crowdloan::fund_account_id(fund_1.fund_index); assert_eq!( slots::Leases::::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::::get(ParaId::from(2000)).unwrap(); let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index); // Bunch of contributions @@ -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::::get(ParaId::from(2000)).is_some()); + assert!(crowdloan::Funds::::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::::get(ParaId::from(2000)).is_empty()); + assert!(slots::Leases::::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::::get(ParaId::from(2000)).is_none()); + assert!(crowdloan::Funds::::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::::get(ParaId::from(2000)).is_empty()); + assert!(!slots::Leases::::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::::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::::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::::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::::get(ParaId::from(2000)).is_empty()); + assert!(slots::Leases::::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::::get(ParaId::from(2000)).is_empty()); + assert!(!slots::Leases::::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::::get(ParaId::from(2000)).len(), 6); assert_eq!(slots::Leases::::get(ParaId::from(2001)).len(), 8); - let fund_2000 = Crowdloan::funds(ParaId::from(2000)).unwrap(); + let fund_2000 = crowdloan::Funds::::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::::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::::get(ParaId::from(2000)).len(), 6); + assert_eq!(slots::Leases::::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::::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::::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::::get(ParaId::from(2000)).len(), 8); + assert_eq!(slots::Leases::::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::::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::::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::::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::::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::::get(), vec![ParaId::from(2000)]); // Beginning of ending block. run_to_block(starting_block + 100); diff --git a/polkadot/runtime/common/src/slots/mod.rs b/polkadot/runtime/common/src/slots/mod.rs index 51bd0ba4debe..19c977fca9a6 100644 --- a/polkadot/runtime/common/src/slots/mod.rs +++ b/polkadot/runtime/common/src/slots/mod.rs @@ -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 = StorageMap<_, Twox64Concat, ParaId, Vec)>>, ValueQuery>; diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index ff54c7776701..ae847a1fbd49 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -1506,7 +1506,7 @@ pub mod migrations { impl coretime::migration::GetLegacyLease for GetLegacyLeaseImpl { fn get_parachain_lease_in_blocks(para: ParaId) -> Option { let now = frame_system::Pallet::::block_number(); - let lease = slots::Pallet::::lease(para); + let lease = slots::Leases::::get(para); if lease.is_empty() { return None } diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 45bbd0260e5e..4f0cf5999047 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -1587,7 +1587,7 @@ pub mod migrations { impl coretime::migration::GetLegacyLease for GetLegacyLeaseImpl { fn get_parachain_lease_in_blocks(para: ParaId) -> Option { let now = frame_system::Pallet::::block_number(); - let lease = slots::Pallet::::lease(para); + let lease = slots::Leases::::get(para); if lease.is_empty() { return None } From 802ca2d398fd2d859207eea28dd38056d92aa50d Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 13:29:11 +0100 Subject: [PATCH 02/16] removed `pallet::getter` usage from `polkadot-runtime-parachains::{configuration, disputes, paras_inherent}` Signed-off-by: Matteo Muraca --- .../runtime/common/src/integration_tests.rs | 2 +- .../runtime/common/src/paras_registrar/mod.rs | 10 ++-- .../runtime/common/src/paras_sudo_wrapper.rs | 2 +- polkadot/runtime/common/src/xcm_sender.rs | 2 +- .../parachains/src/assigner_coretime/mod.rs | 4 +- .../parachains/src/assigner_on_demand/mod.rs | 8 ++-- polkadot/runtime/parachains/src/builder.rs | 14 +++--- .../runtime/parachains/src/configuration.rs | 5 +- .../parachains/src/configuration/tests.rs | 47 ++++++++++--------- .../parachains/src/coretime/migration.rs | 10 ++-- polkadot/runtime/parachains/src/disputes.rs | 15 ++++-- .../parachains/src/disputes/slashing.rs | 2 +- .../runtime/parachains/src/disputes/tests.rs | 4 +- polkadot/runtime/parachains/src/dmp/tests.rs | 4 +- polkadot/runtime/parachains/src/hrmp.rs | 14 +++--- .../parachains/src/hrmp/benchmarking.rs | 30 ++++++------ polkadot/runtime/parachains/src/hrmp/tests.rs | 15 +++--- .../runtime/parachains/src/inclusion/mod.rs | 8 ++-- .../runtime/parachains/src/inclusion/tests.rs | 22 ++++----- .../parachains/src/initializer/tests.rs | 21 +++++++-- .../src/paras/benchmarking/pvf_check.rs | 4 +- polkadot/runtime/parachains/src/paras/mod.rs | 12 ++--- .../runtime/parachains/src/paras/tests.rs | 37 +++++++-------- .../src/paras_inherent/benchmarking.rs | 2 +- .../parachains/src/paras_inherent/mod.rs | 9 ++-- .../parachains/src/paras_inherent/tests.rs | 32 ++++++------- .../parachains/src/runtime_api_impl/v7.rs | 8 ++-- .../src/runtime_api_impl/vstaging.rs | 4 +- polkadot/runtime/parachains/src/scheduler.rs | 22 +++++---- .../runtime/parachains/src/scheduler/tests.rs | 2 +- .../runtime/parachains/src/session_info.rs | 2 +- .../parachains/src/session_info/tests.rs | 8 ++-- polkadot/runtime/parachains/src/ump_tests.rs | 32 ++++++++----- polkadot/runtime/parachains/src/util.rs | 2 +- 34 files changed, 222 insertions(+), 193 deletions(-) diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index 83b7e64468a3..761e742fc673 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -932,7 +932,7 @@ fn basic_swap_works() { // ----------------------------------------- para deposit --- crowdloan let crowdloan_deposit = 100; let para_id_deposit = ::ParaDeposit::get(); - let code_deposit = configuration::Pallet::::config().max_code_size * + let code_deposit = configuration::ActiveConfig::::get().max_code_size * ::DataDepositPerByte::get(); // Para 2000 has a genesis head size of 10. diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 4541b88ec6fe..04e4a255d43a 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -519,14 +519,14 @@ impl Registrar for Pallet { #[cfg(any(feature = "runtime-benchmarks", test))] fn worst_head_data() -> HeadData { - let max_head_size = configuration::Pallet::::config().max_head_data_size; + let max_head_size = configuration::ActiveConfig::::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::::config().max_code_size; + let max_code_size = configuration::ActiveConfig::::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() @@ -656,7 +656,7 @@ impl Pallet { validation_code: ValidationCode, para_kind: ParaKind, ) -> Result<(ParaGenesisArgs, BalanceOf), sp_runtime::DispatchError> { - let config = configuration::Pallet::::config(); + let config = configuration::ActiveConfig::::get(); ensure!(validation_code.0.len() >= MIN_CODE_SIZE as usize, Error::::InvalidCode); ensure!(validation_code.0.len() <= config.max_code_size as usize, Error::::CodeTooLarge); ensure!( @@ -936,11 +936,11 @@ mod tests { } fn max_code_size() -> u32 { - Configuration::config().max_code_size + configuration::ActiveConfig::::get().max_code_size } fn max_head_size() -> u32 { - Configuration::config().max_head_data_size + configuration::ActiveConfig::::get().max_head_data_size } #[test] diff --git a/polkadot/runtime/common/src/paras_sudo_wrapper.rs b/polkadot/runtime/common/src/paras_sudo_wrapper.rs index 4735c1763291..8bf400e3ab5a 100644 --- a/polkadot/runtime/common/src/paras_sudo_wrapper.rs +++ b/polkadot/runtime/common/src/paras_sudo_wrapper.rs @@ -147,7 +147,7 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; ensure!(>::is_valid_para(id), Error::::ParaDoesntExist); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); >::queue_downward_message(&config, id, xcm.encode()).map_err(|e| match e { dmp::QueueDownwardMessageError::ExceedsMaxMessageSize => diff --git a/polkadot/runtime/common/src/xcm_sender.rs b/polkadot/runtime/common/src/xcm_sender.rs index 46d09afcfb2c..9ecf576e1e09 100644 --- a/polkadot/runtime/common/src/xcm_sender.rs +++ b/polkadot/runtime/common/src/xcm_sender.rs @@ -116,7 +116,7 @@ where // Downward message passing. let xcm = msg.take().ok_or(MissingArgument)?; - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let para = id.into(); let price = P::price_for_delivery(para, &xcm); let blob = W::wrap_version(&d, xcm).map_err(|()| DestinationUnsupported)?.encode(); diff --git a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs index e2da89fadd48..a26faa5c83a2 100644 --- a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs @@ -324,7 +324,7 @@ impl AssignmentProvider> for Pallet { } fn session_core_count() -> u32 { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); config.scheduler_params.num_cores } } @@ -473,7 +473,7 @@ impl AssignCoretime for Pallet { let current_block = frame_system::Pallet::::block_number(); // Add a new core and assign the para to it. - let mut config = >::config(); + let mut config = configuration::ActiveConfig::::get(); let core = config.scheduler_params.num_cores; config.scheduler_params.num_cores.saturating_inc(); diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs b/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs index bc450dc78129..b3de04687ddb 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs @@ -196,7 +196,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn on_initialize(_now: BlockNumberFor) -> Weight { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); // Calculate spot price multiplier and store it. let old_traffic = SpotTraffic::::get(); match Self::calculate_spot_traffic( @@ -324,7 +324,7 @@ where para_id: ParaId, existence_requirement: ExistenceRequirement, ) -> DispatchResult { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); // Traffic always falls back to 1.0 let traffic = SpotTraffic::::get(); @@ -447,7 +447,7 @@ where // Only parathreads are valid paraids for on the go parachains. ensure!(>::is_parathread(order.para_id), Error::::InvalidParaId); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); OnDemandQueue::::try_mutate(|queue| { // Abort transaction if queue is too large @@ -468,7 +468,7 @@ where /// Returns: /// - The size of the on demand queue. fn queue_size() -> u32 { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); match OnDemandQueue::::get().len().try_into() { Ok(size) => return size, Err(_) => { diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index 5b218addb1a2..addc6b95e1c5 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -175,7 +175,7 @@ impl BenchBuilder { /// Maximum number of validators that may be part of a validator group. pub(crate) fn fallback_max_validators() -> u32 { - configuration::Pallet::::config().max_validators.unwrap_or(200) + configuration::ActiveConfig::::get().max_validators.unwrap_or(200) } /// Maximum number of validators participating in parachains consensus (a.k.a. active @@ -194,7 +194,7 @@ impl BenchBuilder { /// 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::::config() + configuration::ActiveConfig::::get() .scheduler_params .max_validators_per_core .unwrap_or(5) @@ -252,7 +252,7 @@ impl BenchBuilder { } fn mock_head_data() -> HeadData { - let max_head_size = configuration::Pallet::::config().max_head_data_size; + let max_head_size = configuration::ActiveConfig::::get().max_head_data_size; HeadData(vec![0xFF; max_head_size as usize]) } @@ -504,7 +504,7 @@ impl BenchBuilder { ) -> Vec> { let validators = self.validators.as_ref().expect("must have some validators prior to calling"); - let config = configuration::Pallet::::config(); + let config = configuration::ActiveConfig::::get(); cores_with_backed_candidates .iter() @@ -589,7 +589,7 @@ impl BenchBuilder { // 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::::config() + let core_idx = configuration::ActiveConfig::::get() .node_features .get(FeatureIndex::ElasticScalingMVP as usize) .map(|_the_bit| core_idx); @@ -722,7 +722,7 @@ impl BenchBuilder { let cores = (0..used_cores) .into_iter() .map(|i| { - let ttl = configuration::Pallet::::config().scheduler_params.ttl; + let ttl = configuration::ActiveConfig::::get().scheduler_params.ttl; // Load an assignment into provider so that one is present to pop let assignment = ::AssignmentProvider::get_mock_assignment( CoreIndex(i), @@ -737,7 +737,7 @@ impl BenchBuilder { let cores = (0..used_cores) .into_iter() .map(|i| { - let ttl = configuration::Pallet::::config().scheduler_params.ttl; + let ttl = configuration::ActiveConfig::::get().scheduler_params.ttl; // Load an assignment into provider so that one is present to pop let assignment = ::AssignmentProvider::get_mock_assignment( diff --git a/polkadot/runtime/parachains/src/configuration.rs b/polkadot/runtime/parachains/src/configuration.rs index 364a15215d38..a3fd7e1b8c3a 100644 --- a/polkadot/runtime/parachains/src/configuration.rs +++ b/polkadot/runtime/parachains/src/configuration.rs @@ -505,8 +505,7 @@ pub mod pallet { /// The active configuration for the current session. #[pallet::storage] #[pallet::whitelist_storage] - #[pallet::getter(fn config)] - pub(crate) type ActiveConfig = + pub type ActiveConfig = StorageValue<_, HostConfiguration>, ValueQuery>; /// Pending configuration changes. @@ -1368,7 +1367,7 @@ impl Pallet { let mut base_config = pending_configs .last() .map(|(_, config)| config.clone()) - .unwrap_or_else(Self::config); + .unwrap_or_else(ActiveConfig::::get); let base_config_consistent = base_config.check_consistency().is_ok(); // Now, we need to decide what the new configuration should be. diff --git a/polkadot/runtime/parachains/src/configuration/tests.rs b/polkadot/runtime/parachains/src/configuration/tests.rs index 254511231cac..239b466fde39 100644 --- a/polkadot/runtime/parachains/src/configuration/tests.rs +++ b/polkadot/runtime/parachains/src/configuration/tests.rs @@ -15,7 +15,10 @@ // along with Polkadot. If not, see . 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, HostC #[test] fn default_is_consistent() { new_test_ext(Default::default()).execute_with(|| { - Configuration::config().panic_if_not_consistent(); + configuration::ActiveConfig::::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::::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::::get(), old_config); assert_eq!(PendingConfigs::::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::::get(), old_config); assert_eq!(PendingConfigs::::get(), vec![(2, config.clone())]); on_new_session(2); - assert_eq!(Configuration::config(), config); + assert_eq!(configuration::ActiveConfig::::get(), config); assert_eq!(PendingConfigs::::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::::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::::get(), old_config); assert_eq!(PendingConfigs::::get(), vec![(2, config.clone())]); on_new_session(1); - assert_eq!(Configuration::config(), old_config); + assert_eq!(configuration::ActiveConfig::::get(), old_config); assert_eq!(PendingConfigs::::get(), vec![(2, config.clone())]); on_new_session(2); - assert_eq!(Configuration::config(), config); + assert_eq!(configuration::ActiveConfig::::get(), config); assert_eq!(PendingConfigs::::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::::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::::get(), initial_config); assert_eq!(PendingConfigs::::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::::get(), initial_config); assert_eq!( PendingConfigs::::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::::get(), intermediate_config); assert_eq!(PendingConfigs::::get(), vec![(3, final_config.clone())]); on_new_session(3); - assert_eq!(Configuration::config(), final_config); + assert_eq!(configuration::ActiveConfig::::get(), final_config); assert_eq!(PendingConfigs::::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::::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::::get(), initial_config); assert_eq!(PendingConfigs::::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::::get(), initial_config); assert_eq!( PendingConfigs::::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::::get(), intermediate_config); assert_eq!(PendingConfigs::::get(), vec![(3, final_config.clone())]); on_new_session(3); - assert_eq!(Configuration::config(), final_config); + assert_eq!(configuration::ActiveConfig::::get(), final_config); assert_eq!(PendingConfigs::::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::::get().max_code_size, HostConfiguration::::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::::get().max_code_size, MAX_CODE_SIZE + 1); }); } diff --git a/polkadot/runtime/parachains/src/coretime/migration.rs b/polkadot/runtime/parachains/src/coretime/migration.rs index 03fecc58570f..449d48782d3c 100644 --- a/polkadot/runtime/parachains/src/coretime/migration.rs +++ b/polkadot/runtime/parachains/src/coretime/migration.rs @@ -113,7 +113,7 @@ mod v_coretime { } let legacy_paras = paras::Parachains::::get(); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let total_core_count = config.scheduler_params.num_cores + legacy_paras.len() as u32; let dmp_queue_size = @@ -175,7 +175,7 @@ mod v_coretime { } } - let config = >::config(); + let config = configuration::ActiveConfig::::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 _)); @@ -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::::config().scheduler_params.num_cores.saturated_into(); + let core_count: u16 = configuration::ActiveConfig::::get() + .scheduler_params + .num_cores + .saturated_into(); let set_core_count = iter::once(mk_coretime_call( crate::coretime::CoretimeCalls::NotifyCoreCount(core_count), )); diff --git a/polkadot/runtime/parachains/src/disputes.rs b/polkadot/runtime/parachains/src/disputes.rs index da95b060c14a..62ac67db8559 100644 --- a/polkadot/runtime/parachains/src/disputes.rs +++ b/polkadot/runtime/parachains/src/disputes.rs @@ -432,7 +432,6 @@ 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 = StorageValue<_, Option>, ValueQuery>; #[pallet::event] @@ -853,6 +852,14 @@ impl StatementSetFilter { } impl Pallet { + /// Whether the chain is frozen. Starts as `None`. When this is `Some`, + /// the chain will not accept any new parachain blocks for backing or inclusion, + /// and its value indicates the last valid block number in the chain. + /// It can only be set back to `None` by governance intervention. + pub fn last_valid_block() -> Option> { + Frozen::::get() + } + /// Called by the initializer to initialize the disputes module. pub(crate) fn initializer_initialize(_now: BlockNumberFor) -> Weight { Weight::zero() @@ -865,7 +872,7 @@ impl Pallet { pub(crate) fn initializer_on_new_session( notification: &SessionChangeNotification>, ) { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); if notification.session_index <= config.dispute_period + 1 { return @@ -910,7 +917,7 @@ impl Pallet { pub(crate) fn process_checked_multi_dispute_data( statement_sets: &CheckedMultiDisputeStatementSet, ) -> Result, DispatchError> { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let mut fresh = Vec::with_capacity(statement_sets.len()); for statement_set in statement_sets { @@ -952,7 +959,7 @@ impl Pallet { None => return StatementSetFilter::RemoveAll, }; - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let n_validators = session_info.validators.len(); diff --git a/polkadot/runtime/parachains/src/disputes/slashing.rs b/polkadot/runtime/parachains/src/disputes/slashing.rs index 9b2b7a48dc8b..2f9274f305b1 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing.rs @@ -544,7 +544,7 @@ impl Pallet { // fine. const REMOVE_LIMIT: u32 = u32::MAX; - let config = >::config(); + let config = crate::configuration::ActiveConfig::::get(); if session_index <= config.dispute_period + 1 { return } diff --git a/polkadot/runtime/parachains/src/disputes/tests.rs b/polkadot/runtime/parachains/src/disputes/tests.rs index 1f3f00132d68..bea640f8a5da 100644 --- a/polkadot/runtime/parachains/src/disputes/tests.rs +++ b/polkadot/runtime/parachains/src/disputes/tests.rs @@ -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 = >::config(); + let config = configuration::ActiveConfig::::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>( sets: I, ) -> Vec { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let post_conclusion_acceptance_period = config.dispute_post_conclusion_acceptance_period; let mut acc = Vec::::new(); diff --git a/polkadot/runtime/parachains/src/dmp/tests.rs b/polkadot/runtime/parachains/src/dmp/tests.rs index f9197b156a1e..f39d7ae16733 100644 --- a/polkadot/runtime/parachains/src/dmp/tests.rs +++ b/polkadot/runtime/parachains/src/dmp/tests.rs @@ -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::::get(), para_id, msg) } #[test] diff --git a/polkadot/runtime/parachains/src/hrmp.rs b/polkadot/runtime/parachains/src/hrmp.rs index 42592d9d9f14..56ba4c17a0b0 100644 --- a/polkadot/runtime/parachains/src/hrmp.rs +++ b/polkadot/runtime/parachains/src/hrmp.rs @@ -597,7 +597,7 @@ pub mod pallet { Error::::WrongWitness ); - let host_config = configuration::Pallet::::config(); + let host_config = configuration::ActiveConfig::::get(); Self::process_hrmp_open_channel_requests(&host_config); Ok(()) } @@ -724,7 +724,7 @@ pub mod pallet { Error::::ChannelCreationNotAuthorized ); - let config = >::config(); + let config = configuration::ActiveConfig::::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 = >::config(); + let config = configuration::ActiveConfig::::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(preopen_hrmp_channels: &[(ParaId, ParaId, u32, u32)]) { - let host_config = configuration::Pallet::::config(); + let host_config = configuration::ActiveConfig::::get(); for &(sender, recipient, max_capacity, max_message_size) in preopen_hrmp_channels { if let Err(err) = preopen_hrmp_channel::(sender, recipient, max_capacity, max_message_size) @@ -1391,7 +1391,7 @@ impl Pallet { Error::::OpenHrmpChannelInvalidRecipient, ); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); ensure!(proposed_max_capacity > 0, Error::::OpenHrmpChannelZeroCapacity); ensure!( proposed_max_capacity <= config.hrmp_channel_max_capacity, @@ -1485,7 +1485,7 @@ impl Pallet { // check if by accepting this open channel request, this parachain would exceed the // number of inbound channels. - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let channel_num_limit = config.hrmp_max_parachain_inbound_channels; let ingress_cnt = HrmpIngressChannelsIndex::::decode_len(&origin).unwrap_or(0) as u32; let accepted_cnt = HrmpAcceptedChannelRequestCount::::get(&origin); @@ -1580,7 +1580,7 @@ impl Pallet { HrmpCloseChannelRequests::::insert(&channel_id, ()); HrmpCloseChannelRequestsList::::append(channel_id.clone()); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let notification_bytes = { use parity_scale_codec::Encode as _; use xcm::opaque::{latest::prelude::*, VersionedXcm}; diff --git a/polkadot/runtime/parachains/src/hrmp/benchmarking.rs b/polkadot/runtime/parachains/src/hrmp/benchmarking.rs index c6baf2f30cf5..507721b2b78d 100644 --- a/polkadot/runtime/parachains/src/hrmp/benchmarking.rs +++ b/polkadot/runtime/parachains/src/hrmp/benchmarking.rs @@ -71,7 +71,7 @@ fn establish_para_connection( where ::RuntimeOrigin: From, { - let config = Configuration::::config(); + let config = configuration::ActiveConfig::::get(); let ed = T::Currency::minimum_balance(); let deposit: BalanceOf = config.hrmp_sender_deposit.unique_saturated_into(); let capacity = config.hrmp_channel_max_capacity; @@ -109,7 +109,7 @@ where return output } - Hrmp::::process_hrmp_open_channel_requests(&Configuration::::config()); + Hrmp::::process_hrmp_open_channel_requests(&configuration::ActiveConfig::::get()); if matches!(until, ParachainSetupStep::Established) { return output } @@ -154,13 +154,14 @@ mod benchmarks { // make sure para is registered, and has enough balance. let ed = T::Currency::minimum_balance(); - let deposit: BalanceOf = - Configuration::::config().hrmp_sender_deposit.unique_saturated_into(); + let deposit: BalanceOf = configuration::ActiveConfig::::get() + .hrmp_sender_deposit + .unique_saturated_into(); register_parachain_with_balance::(sender_id, deposit + ed); register_parachain_with_balance::(recipient_id, deposit + ed); - let capacity = Configuration::::config().hrmp_channel_max_capacity; - let message_size = Configuration::::config().hrmp_channel_max_message_size; + let capacity = configuration::ActiveConfig::::get().hrmp_channel_max_capacity; + let message_size = configuration::ActiveConfig::::get().hrmp_channel_max_message_size; #[extrinsic_call] _(sender_origin, recipient_id, capacity, message_size); @@ -226,7 +227,7 @@ mod benchmarks { // .. and enact it. Configuration::::initializer_on_new_session(&Shared::::scheduled_session()); - let config = Configuration::::config(); + let config = configuration::ActiveConfig::::get(); let deposit: BalanceOf = config.hrmp_sender_deposit.unique_saturated_into(); let para: ParaId = 1u32.into(); @@ -358,7 +359,7 @@ mod benchmarks { assert_eq!(HrmpOpenChannelRequestsList::::decode_len().unwrap_or_default() as u32, c); let outgoing = (0..c).map(|id| (id + PREFIX_1).into()).collect::>(); - let config = Configuration::::config(); + let config = configuration::ActiveConfig::::get(); #[block] { @@ -381,13 +382,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 = - Configuration::::config().hrmp_sender_deposit.unique_saturated_into(); + let sender_deposit: BalanceOf = configuration::ActiveConfig::::get() + .hrmp_sender_deposit + .unique_saturated_into(); register_parachain_with_balance::(sender_id, sender_deposit + ed); register_parachain_with_balance::(recipient_id, Zero::zero()); - let capacity = Configuration::::config().hrmp_channel_max_capacity; - let message_size = Configuration::::config().hrmp_channel_max_message_size; + let capacity = configuration::ActiveConfig::::get().hrmp_channel_max_capacity; + let message_size = configuration::ActiveConfig::::get().hrmp_channel_max_message_size; let channel_id = HrmpChannelId { sender: sender_id, recipient: recipient_id }; if c == 1 { @@ -434,7 +436,7 @@ mod benchmarks { let recipient_id: ParaId = 2u32.into(); let caller: T::AccountId = whitelisted_caller(); - let config = Configuration::::config(); + let config = configuration::ActiveConfig::::get(); // make sure para is registered, and has zero balance. register_parachain_with_balance::(sender_id, Zero::zero()); @@ -464,7 +466,7 @@ mod benchmarks { let channel_id = HrmpChannelId { sender: sender_id, recipient: recipient_id }; let caller: T::AccountId = whitelisted_caller(); - let config = Configuration::::config(); + let config = configuration::ActiveConfig::::get(); // make sure para is registered, and has balance to reserve. let ed = T::Currency::minimum_balance(); diff --git a/polkadot/runtime/parachains/src/hrmp/tests.rs b/polkadot/runtime/parachains/src/hrmp/tests.rs index 7e7b67c8059d..8dae04114d62 100644 --- a/polkadot/runtime/parachains/src/hrmp/tests.rs +++ b/polkadot/runtime/parachains/src/hrmp/tests.rs @@ -20,16 +20,15 @@ use super::*; 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, + deregister_parachain, new_test_ext, register_parachain, register_parachain_with_balance, Hrmp, + MockGenesisConfig, Paras, ParasShared, RuntimeEvent as MockEvent, RuntimeOrigin, System, Test, }; 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>) { - let config = Configuration::config(); + let config = configuration::ActiveConfig::::get(); while System::block_number() < to { let b = System::block_number(); @@ -412,7 +411,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::::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 +511,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::::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 +620,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::::get(); assert!(Hrmp::check_outbound_hrmp(&config, para_a, &msgs).is_ok()); let _ = Hrmp::queue_outbound_hrmp(para_a, msgs.clone()); @@ -912,7 +911,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::::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(); diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index 16e2e93b5617..1caca2127fe1 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -611,7 +611,7 @@ impl Pallet { return Ok(ProcessedCandidates::default()) } - let minimum_backing_votes = configuration::Pallet::::config().minimum_backing_votes; + let minimum_backing_votes = configuration::ActiveConfig::::get().minimum_backing_votes; let validators = shared::Pallet::::active_validator_keys(); // Collect candidate receipts with backers. @@ -867,7 +867,7 @@ impl Pallet { ) -> Weight { let plain = receipt.to_plain(); let commitments = receipt.commitments; - let config = >::config(); + let config = configuration::ActiveConfig::::get(); T::RewardValidators::reward_backing( backers @@ -1168,7 +1168,7 @@ impl OnQueueChanged for Pallet { #[allow(deprecated)] well_known_keys::relay_dispatch_queue_size_typed(para).set((count, size)); - let config = >::config(); + let config = configuration::ActiveConfig::::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) @@ -1188,7 +1188,7 @@ pub(crate) struct FailedToCreatePVD; impl CandidateCheckContext { pub(crate) fn new(prev_context: Option>) -> Self { - Self { config: >::config(), prev_context } + Self { config: configuration::ActiveConfig::::get(), prev_context } } /// Execute verification of the candidate. diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index 3fe7d7f0c7d4..24202035b261 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -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::::config().minimum_backing_votes, + configuration::ActiveConfig::::get().minimum_backing_votes, ); let signing = match kind { @@ -182,8 +181,8 @@ pub(crate) fn back_candidate( pub(crate) fn run_to_block_default_notifications(to: BlockNumber, new_session: Vec) { run_to_block(to, |b| { new_session.contains(&b).then_some(SessionChangeNotification { - prev_config: Configuration::config(), - new_config: Configuration::config(), + prev_config: configuration::ActiveConfig::::get(), + new_config: configuration::ActiveConfig::::get(), session_index: ParasShared::session_index() + 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().len() + + configuration::ActiveConfig::::get().scheduler_params.num_cores as usize } fn default_bitfield() -> AvailabilityBitfield { @@ -1245,7 +1245,7 @@ fn candidate_checks() { ); { - let cfg = Configuration::config(); + let cfg = configuration::ActiveConfig::::get(); let expected_at = 10 + cfg.validation_upgrade_delay; assert_eq!(expected_at, 12); Paras::schedule_code_upgrade( @@ -1600,7 +1600,7 @@ fn backing_works() { let backers = { let num_backers = effective_minimum_backing_votes( group_validators(GroupIndex(0)).unwrap().len(), - configuration::Pallet::::config().minimum_backing_votes, + configuration::ActiveConfig::::get().minimum_backing_votes, ); backing_bitfield(&(0..num_backers).collect::>()) }; @@ -1625,7 +1625,7 @@ fn backing_works() { let backers = { let num_backers = effective_minimum_backing_votes( group_validators(GroupIndex(0)).unwrap().len(), - configuration::Pallet::::config().minimum_backing_votes, + configuration::ActiveConfig::::get().minimum_backing_votes, ); backing_bitfield(&(0..num_backers).map(|v| v + 2).collect::>()) }; @@ -1875,7 +1875,7 @@ fn backing_works_with_elastic_scaling_mvp() { let backers = { let num_backers = effective_minimum_backing_votes( group_validators(GroupIndex(0)).unwrap().len(), - configuration::Pallet::::config().minimum_backing_votes, + configuration::ActiveConfig::::get().minimum_backing_votes, ); backing_bitfield(&(0..num_backers).collect::>()) }; @@ -2009,7 +2009,7 @@ 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::::config().minimum_backing_votes, + configuration::ActiveConfig::::get().minimum_backing_votes, ); backing_bitfield(&(0..num_backers).collect::>()) }; diff --git a/polkadot/runtime/parachains/src/initializer/tests.rs b/polkadot/runtime/parachains/src/initializer/tests.rs index b0993d739fa9..ecea9be77ca0 100644 --- a/polkadot/runtime/parachains/src/initializer/tests.rs +++ b/polkadot/runtime/parachains/src/initializer/tests.rs @@ -16,8 +16,7 @@ use super::*; use crate::mock::{ - new_test_ext, Configuration, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, - Test, + new_test_ext, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, Test, }; use primitives::{HeadData, Id as ParaId}; use test_helpers::dummy_validation_code; @@ -116,9 +115,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::::get(), + a, + vec![1, 2, 3] + )); + assert_ok!(Dmp::queue_downward_message( + &configuration::ActiveConfig::::get(), + b, + vec![4, 5, 6] + )); + assert_ok!(Dmp::queue_downward_message( + &configuration::ActiveConfig::::get(), + c, + vec![7, 8, 9] + )); assert_ok!(Paras::schedule_para_cleanup(a)); assert_ok!(Paras::schedule_para_cleanup(b)); diff --git a/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs b/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs index 53ccc35c477c..fcce29678c45 100644 --- a/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs +++ b/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs @@ -133,7 +133,7 @@ where .collect::>(); // 1. Make sure PVF pre-checking is enabled in the config. - let config = configuration::Pallet::::config(); + let config = configuration::ActiveConfig::::get(); configuration::Pallet::::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::::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); } else { diff --git a/polkadot/runtime/parachains/src/paras/mod.rs b/polkadot/runtime/parachains/src/paras/mod.rs index 5acdb9683bbf..82b92b263ecd 100644 --- a/polkadot/runtime/parachains/src/paras/mod.rs +++ b/polkadot/runtime/parachains/src/paras/mod.rs @@ -922,7 +922,7 @@ pub mod pallet { relay_parent_number: BlockNumberFor, ) -> DispatchResult { ensure_root(origin)?; - let config = configuration::Pallet::::config(); + let config = configuration::ActiveConfig::::get(); Self::schedule_code_upgrade( para, new_code, @@ -998,7 +998,7 @@ pub mod pallet { } }); - let cfg = configuration::Pallet::::config(); + let cfg = configuration::ActiveConfig::::get(); Self::enact_pvf_accepted( >::block_number(), &code_hash, @@ -1108,7 +1108,7 @@ pub mod pallet { }); match outcome { PvfCheckOutcome::Accepted => { - let cfg = configuration::Pallet::::config(); + let cfg = configuration::ActiveConfig::::get(); Self::enact_pvf_accepted( >::block_number(), &stmt.subject, @@ -1231,7 +1231,7 @@ impl Pallet { ) -> DispatchResult { // Check that we can schedule an upgrade at all. ensure!(Self::can_upgrade_validation_code(id), Error::::CannotUpgradeCode); - let config = configuration::Pallet::::config(); + let config = configuration::ActiveConfig::::get(); // Validation code sanity checks: ensure!(new_code.0.len() >= MIN_CODE_SIZE as usize, Error::::InvalidCode); ensure!(new_code.0.len() <= config.max_code_size as usize, Error::::InvalidCode); @@ -1406,7 +1406,7 @@ impl Pallet { // 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) -> Weight { - let config = configuration::Pallet::::config(); + let config = configuration::ActiveConfig::::get(); let code_retention_period = config.code_retention_period; if now <= code_retention_period { let weight = T::DbWeight::get().reads_writes(1, 0); @@ -1765,7 +1765,7 @@ impl Pallet { let validation_code_hash = validation_code.hash(); CurrentCodeHash::::insert(&id, validation_code_hash); - let cfg = configuration::Pallet::::config(); + let cfg = configuration::ActiveConfig::::get(); Self::kick_off_pvf_check( PvfCheckCause::Onboarding(id), validation_code_hash, diff --git a/polkadot/runtime/parachains/src/paras/tests.rs b/polkadot/runtime/parachains/src/paras/tests.rs index 262ec9d3fdba..b718a0903dca 100644 --- a/polkadot/runtime/parachains/src/paras/tests.rs +++ b/polkadot/runtime/parachains/src/paras/tests.rs @@ -25,10 +25,7 @@ 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}, }; static VALIDATORS: &[Sr25519Keyring] = &[ @@ -450,7 +447,7 @@ fn code_upgrade_applied_after_delay() { para_id, new_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); // Include votes for super-majority. @@ -570,7 +567,7 @@ fn code_upgrade_applied_without_setting_go_ahead_signal() { para_id, new_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::No, ); // Include votes for super-majority. @@ -687,7 +684,7 @@ fn code_upgrade_applied_after_delay_even_when_late() { para_id, new_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); // Include votes for super-majority. @@ -771,7 +768,7 @@ fn submit_code_change_when_not_allowed_is_err() { para_id, new_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); // Include votes for super-majority. @@ -789,7 +786,7 @@ fn submit_code_change_when_not_allowed_is_err() { para_id, newer_code.clone(), 2, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); assert_eq!( @@ -853,7 +850,7 @@ fn upgrade_restriction_elapsed_doesnt_mean_can_upgrade() { para_id, new_code.clone(), 0, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); // Include votes for super-majority. @@ -878,7 +875,7 @@ fn upgrade_restriction_elapsed_doesnt_mean_can_upgrade() { para_id, newer_code.clone(), 30, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(0 + validation_upgrade_delay)); @@ -939,7 +936,7 @@ fn full_parachain_cleanup_storage() { para_id, new_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); // Include votes for super-majority. @@ -1035,7 +1032,7 @@ fn cannot_offboard_ongoing_pvf_check() { para_id, new_code.clone(), RELAY_PARENT, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); assert!(!Paras::pvfs_require_precheck().is_empty()); @@ -1193,7 +1190,7 @@ fn code_hash_at_returns_up_to_end_of_code_retention_period() { para_id, new_code.clone(), 0, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); // Include votes for super-majority. @@ -1302,7 +1299,7 @@ fn pvf_check_coalescing_onboarding_and_upgrade() { a, validation_code.clone(), RELAY_PARENT, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); assert!(!Paras::pvfs_require_precheck().is_empty()); @@ -1412,7 +1409,7 @@ fn pvf_check_upgrade_reject() { a, new_code.clone(), RELAY_PARENT, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); check_code_is_stored(&new_code); @@ -1598,7 +1595,7 @@ fn include_pvf_check_statement_refunds_weight() { a, new_code.clone(), RELAY_PARENT, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); @@ -1699,7 +1696,7 @@ fn poke_unused_validation_code_doesnt_remove_code_with_users() { para_id, validation_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); Paras::note_new_head(para_id, HeadData::default(), 1); @@ -1770,7 +1767,7 @@ fn add_trusted_validation_code_insta_approval() { para_id, validation_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); Paras::note_new_head(para_id, HeadData::default(), 1); @@ -1812,7 +1809,7 @@ fn add_trusted_validation_code_enacts_existing_pvf_vote() { para_id, validation_code.clone(), 1, - &Configuration::config(), + &configuration::ActiveConfig::::get(), SetGoAhead::Yes, ); Paras::note_new_head(para_id, HeadData::default(), 1); diff --git a/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs b/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs index ad3fa8e0dc71..1b35556bfbb0 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs @@ -157,7 +157,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::::config().max_code_size; + let v = crate::configuration::ActiveConfig::::get().max_code_size; let cores_with_backed: BTreeMap<_, _> = vec![(0, BenchBuilder::::fallback_min_validity_votes())] diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index 723a15bdba7a..b9ea866c0154 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -161,8 +161,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 = StorageValue<_, ScrapedOnChainVotes>; + pub type OnChainVotes = StorageValue<_, ScrapedOnChainVotes>; /// Update the disputes statements set part of the on-chain votes. pub(crate) fn set_scrapable_on_chain_disputes( @@ -362,7 +361,7 @@ impl Pallet { ); let now = >::block_number(); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); // Before anything else, update the allowed relay-parents. { @@ -591,7 +590,7 @@ impl Pallet { METRICS.on_candidates_processed_total(backed_candidates.len() as u64); - let core_index_enabled = configuration::Pallet::::config() + let core_index_enabled = configuration::ActiveConfig::::get() .node_features .get(FeatureIndex::ElasticScalingMVP as usize) .map(|b| *b) @@ -1170,7 +1169,7 @@ fn filter_backed_statements_from_disabled_validators::config().minimum_backing_votes; + let minimum_backing_votes = configuration::ActiveConfig::::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: diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index fb4d1bd2226e..6ccc5af68e4d 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -136,13 +136,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::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + OnChainVotes::::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::::on_chain_votes().unwrap().session, + OnChainVotes::::get().unwrap().session, 2 ); }); @@ -211,7 +211,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::(3, statements); - assert_matches!(pallet::Pallet::::on_chain_votes(), Some(ScrapedOnChainVotes { + assert_matches!(pallet::OnChainVotes::::get(), Some(ScrapedOnChainVotes { session, .. } ) => { @@ -230,7 +230,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::(7, statements); - assert_matches!(pallet::Pallet::::on_chain_votes(), Some(ScrapedOnChainVotes { + assert_matches!(pallet::OnChainVotes::::get(), Some(ScrapedOnChainVotes { session, .. } ) => { @@ -296,13 +296,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::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + OnChainVotes::::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::::on_chain_votes().unwrap().session, + OnChainVotes::::get().unwrap().session, 2 ); }); @@ -362,13 +362,13 @@ mod enter { assert_eq!( // Ensure that our inherent data did not included backed candidates as expected - Pallet::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + OnChainVotes::::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::::on_chain_votes().unwrap().session, + OnChainVotes::::get().unwrap().session, 2 ); }); @@ -443,13 +443,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::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + OnChainVotes::::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::::on_chain_votes().unwrap().session, + OnChainVotes::::get().unwrap().session, 2 ); }); @@ -529,13 +529,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::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + OnChainVotes::::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::::on_chain_votes().unwrap().session, + OnChainVotes::::get().unwrap().session, 2 ); }); @@ -691,13 +691,13 @@ 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::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + OnChainVotes::::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::::on_chain_votes().unwrap().session, + OnChainVotes::::get().unwrap().session, 2 ); @@ -708,7 +708,7 @@ mod enter { .into_iter() .map(|i| { let SchedulerParams { ttl, .. } = - >::config().scheduler_params; + configuration::ActiveConfig::::get().scheduler_params; // Load an assignment into provider so that one is present to pop let assignment = ::AssignmentProvider::get_mock_assignment( @@ -2058,7 +2058,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::::config(); + let mut hc = configuration::ActiveConfig::::get(); hc.minimum_backing_votes = 1; configuration::Pallet::::force_set_active_config(hc); diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs index 1bbd4dfb716f..afc195173ff0 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs @@ -337,7 +337,7 @@ pub fn validation_code_by_hash( /// Disputes imported via means of on-chain imports. pub fn on_chain_votes() -> Option> { - >::on_chain_votes() + paras_inherent::OnChainVotes::::get() } /// Submits an PVF pre-checking vote. @@ -401,14 +401,14 @@ pub fn submit_unsigned_slashing_report( /// Return the min backing votes threshold from the configuration. pub fn minimum_backing_votes() -> u32 { - >::config().minimum_backing_votes + configuration::ActiveConfig::::get().minimum_backing_votes } /// Implementation for `ParaBackingState` function from the runtime API pub fn backing_state( para_id: ParaId, ) -> Option>> { - let config = >::config(); + let config = configuration::ActiveConfig::::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. @@ -493,5 +493,5 @@ pub fn backing_state( /// Implementation for `AsyncBackingParams` function from the runtime API pub fn async_backing_params() -> AsyncBackingParams { - >::config().async_backing_params + configuration::ActiveConfig::::get().async_backing_params } diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs index 1fee1a4097d8..bc31747c8fb6 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs @@ -35,11 +35,11 @@ where /// Returns the current state of the node features. pub fn node_features() -> NodeFeatures { - >::config().node_features + configuration::ActiveConfig::::get().node_features } /// Approval voting subsystem configuration parameteres pub fn approval_voting_params() -> ApprovalVotingParams { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); config.approval_voting_params } diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index f231864a85e7..50088c9b2666 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -357,7 +357,7 @@ impl Pallet { fn drop_expired_claims_from_claimqueue() { let now = >::block_number(); let availability_cores = AvailabilityCores::::get(); - let ttl = >::config().scheduler_params.ttl; + let ttl = configuration::ActiveConfig::::get().scheduler_params.ttl; ClaimQueue::::mutate(|cq| { for (idx, _) in (0u32..).zip(availability_cores) { @@ -420,7 +420,7 @@ impl Pallet { core: CoreIndex, at: BlockNumberFor, ) -> Option { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let session_start_block = >::get(); if at < session_start_block { @@ -452,7 +452,7 @@ impl Pallet { /// This only ever times out cores that have been occupied across a group rotation boundary. pub(crate) fn availability_timeout_predicate( ) -> impl Fn(BlockNumberFor) -> AvailabilityTimeoutStatus> { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let now = >::block_number(); let rotation_info = Self::group_rotation_info(now); @@ -480,7 +480,7 @@ impl Pallet { /// 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 = >::config(); + let config = configuration::ActiveConfig::::get(); let now = >::block_number() + One::one(); let rotation_info = Self::group_rotation_info(now); @@ -494,8 +494,9 @@ impl Pallet { now: BlockNumberFor, ) -> GroupRotationInfo> { let session_start_block = Self::session_start_block(); - let group_rotation_frequency = - >::config().scheduler_params.group_rotation_frequency; + let group_rotation_frequency = configuration::ActiveConfig::::get() + .scheduler_params + .group_rotation_frequency; GroupRotationInfo { session_start_block, now, group_rotation_frequency } } @@ -515,8 +516,9 @@ impl Pallet { /// 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 { - let max_availability_timeouts = - >::config().scheduler_params.max_availability_timeouts; + let max_availability_timeouts = configuration::ActiveConfig::::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 @@ -571,7 +573,7 @@ impl Pallet { // ClaimQueue related functions // fn claimqueue_lookahead() -> u32 { - >::config().scheduler_params.lookahead + configuration::ActiveConfig::::get().scheduler_params.lookahead } /// Frees cores and fills the free claimqueue spots by popping from the `AssignmentProvider`. @@ -590,7 +592,7 @@ impl Pallet { let n_lookahead = Self::claimqueue_lookahead().max(1); let n_session_cores = T::AssignmentProvider::session_core_count(); let cq = ClaimQueue::::get(); - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let max_availability_timeouts = config.scheduler_params.max_availability_timeouts; let ttl = config.scheduler_params.ttl; diff --git a/polkadot/runtime/parachains/src/scheduler/tests.rs b/polkadot/runtime/parachains/src/scheduler/tests.rs index e6a1e66b3a53..5735607bc841 100644 --- a/polkadot/runtime/parachains/src/scheduler/tests.rs +++ b/polkadot/runtime/parachains/src/scheduler/tests.rs @@ -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 = >::config().scheduler_params.ttl; + let coretime_ttl = configuration::ActiveConfig::::get().scheduler_params.ttl; schedule_blank_para(para_a); schedule_blank_para(para_b); diff --git a/polkadot/runtime/parachains/src/session_info.rs b/polkadot/runtime/parachains/src/session_info.rs index 9e1b3d05842f..30f865299937 100644 --- a/polkadot/runtime/parachains/src/session_info.rs +++ b/polkadot/runtime/parachains/src/session_info.rs @@ -129,7 +129,7 @@ impl Pallet { pub(crate) fn initializer_on_new_session( notification: &crate::initializer::SessionChangeNotification>, ) { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); let dispute_period = config.dispute_period; diff --git a/polkadot/runtime/parachains/src/session_info/tests.rs b/polkadot/runtime/parachains/src/session_info/tests.rs index a5bfeae07455..ff51b8417242 100644 --- a/polkadot/runtime/parachains/src/session_info/tests.rs +++ b/polkadot/runtime/parachains/src/session_info/tests.rs @@ -92,7 +92,7 @@ fn new_session_every_block(n: BlockNumber) -> Option::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::::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::::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::::get(); assert_eq!(config.dispute_period, 16); // Earliest session stays the same assert_eq!(EarliestStoredSession::::get(), 21 - dispute_period); diff --git a/polkadot/runtime/parachains/src/ump_tests.rs b/polkadot/runtime/parachains/src/ump_tests.rs index 2ed1d64336b3..97d96cdba75a 100644 --- a/polkadot/runtime/parachains/src/ump_tests.rs +++ b/polkadot/runtime/parachains/src/ump_tests.rs @@ -15,13 +15,14 @@ // along with Polkadot. If not, see . 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::::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, err: Option) { assert_eq!( - ParaInclusion::check_upward_messages(&Configuration::config(), para, &msgs[..]).err(), + ParaInclusion::check_upward_messages( + &configuration::ActiveConfig::::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::::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::::get().max_upward_message_size; + let max_per_candidate = + configuration::ActiveConfig::::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::::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::::get().max_upward_queue_size as u64; assert_eq!(pallet_message_queue::ItemHeader::::max_encoded_len(), 5); assert!( - Configuration::config().max_upward_queue_size < + configuration::ActiveConfig::::get().max_upward_queue_size < crate::inclusion::MaxUmpMessageLenOf::::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::::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::::get(); for para in 0..10 { let para = para.into(); diff --git a/polkadot/runtime/parachains/src/util.rs b/polkadot/runtime/parachains/src/util.rs index aa07ef080055..a20748593709 100644 --- a/polkadot/runtime/parachains/src/util.rs +++ b/polkadot/runtime/parachains/src/util.rs @@ -32,7 +32,7 @@ pub fn make_persisted_validation_data( relay_parent_number: BlockNumberFor, relay_parent_storage_root: T::Hash, ) -> Option>> { - let config = >::config(); + let config = configuration::ActiveConfig::::get(); Some(PersistedValidationData { parent_head: >::para_head(¶_id)?, From 29f09b361af5cd47fd6824e3752123e98d785979 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 15:52:16 +0100 Subject: [PATCH 03/16] removed `pallet::getter` usage from `polkadot-runtime-parachains::paras` Signed-off-by: Matteo Muraca --- .../src/runtime/scheduler.md | 4 +- .../runtime/common/src/paras_registrar/mod.rs | 2 +- .../parachains/src/assigner_parachains.rs | 2 +- polkadot/runtime/parachains/src/builder.rs | 2 +- .../parachains/src/coretime/migration.rs | 4 +- .../runtime/parachains/src/inclusion/mod.rs | 6 +- .../runtime/parachains/src/inclusion/tests.rs | 4 +- polkadot/runtime/parachains/src/paras/mod.rs | 34 ++++------- .../runtime/parachains/src/paras/tests.rs | 61 ++++++++++--------- .../parachains/src/paras_inherent/mod.rs | 2 +- .../parachains/src/runtime_api_impl/v7.rs | 16 ++--- .../parachains/src/scheduler/migration.rs | 2 +- polkadot/runtime/parachains/src/util.rs | 2 +- polkadot/runtime/rococo/src/lib.rs | 4 +- polkadot/runtime/westend/src/lib.rs | 4 +- 15 files changed, 70 insertions(+), 79 deletions(-) diff --git a/polkadot/roadmap/implementers-guide/src/runtime/scheduler.md b/polkadot/roadmap/implementers-guide/src/runtime/scheduler.md index 32a7fe652dbc..960409befd89 100644 --- a/polkadot/roadmap/implementers-guide/src/runtime/scheduler.md +++ b/polkadot/roadmap/implementers-guide/src/runtime/scheduler.md @@ -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::::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::::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 diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 04e4a255d43a..2c2d3b3eb9ca 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -451,7 +451,7 @@ impl Registrar for Pallet { // All lease holding parachains. Ordered ascending by ParaId. On-demand parachains are not // included. fn parachains() -> Vec { - paras::Pallet::::parachains() + paras::Parachains::::get() } // Return if a para is a parathread (on-demand parachain) diff --git a/polkadot/runtime/parachains/src/assigner_parachains.rs b/polkadot/runtime/parachains/src/assigner_parachains.rs index b5f342563e97..e79facd1fef0 100644 --- a/polkadot/runtime/parachains/src/assigner_parachains.rs +++ b/polkadot/runtime/parachains/src/assigner_parachains.rs @@ -46,7 +46,7 @@ pub mod pallet { impl AssignmentProvider> for Pallet { fn pop_assignment_for_core(core_idx: CoreIndex) -> Option { - >::parachains() + paras::Parachains::::get() .get(core_idx.0 as usize) .copied() .map(Assignment::Bulk) diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index addc6b95e1c5..01555b3ff40d 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -442,7 +442,7 @@ impl BenchBuilder { self.validators = Some(validators_shuffled); self.block_number = block_number; self.session = target_session; - assert_eq!(paras::Pallet::::parachains().len(), total_cores as usize); + assert_eq!(paras::Parachains::::get().len(), total_cores as usize); self } diff --git a/polkadot/runtime/parachains/src/coretime/migration.rs b/polkadot/runtime/parachains/src/coretime/migration.rs index 449d48782d3c..8100b29d923d 100644 --- a/polkadot/runtime/parachains/src/coretime/migration.rs +++ b/polkadot/runtime/parachains/src/coretime/migration.rs @@ -156,7 +156,7 @@ mod v_coretime { SendXcm: xcm::v4::SendXcm, LegacyLease: GetLegacyLease>, >() -> Weight { - let legacy_paras = paras::Pallet::::parachains(); + let legacy_paras = paras::Parachains::::get(); let legacy_count = legacy_paras.len() as u32; let now = >::block_number(); for (core, para_id) in legacy_paras.into_iter().enumerate() { @@ -212,7 +212,7 @@ mod v_coretime { SendXcm: xcm::v4::SendXcm, LegacyLease: GetLegacyLease>, >() -> result::Result<(), SendError> { - let legacy_paras = paras::Pallet::::parachains(); + let legacy_paras = paras::Parachains::::get(); let legacy_paras_count = legacy_paras.len(); let (system_chains, lease_holding): (Vec<_>, Vec<_>) = legacy_paras.into_iter().partition(IsSystem::is_system); diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index 1caca2127fe1..4a1792d798bb 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -647,7 +647,7 @@ impl Pallet { let relay_parent_hash = backed_candidate.descriptor().relay_parent; let para_id = backed_candidate.descriptor().para_id; - let prev_context = >::para_most_recent_context(para_id); + let prev_context = paras::MostRecentContext::::get(para_id); let check_ctx = CandidateCheckContext::::new(prev_context); let signing_context = SigningContext { @@ -830,7 +830,7 @@ impl Pallet { relay_parent_number: BlockNumberFor, validation_outputs: primitives::CandidateCommitments, ) -> bool { - let prev_context = >::para_most_recent_context(para_id); + let prev_context = paras::MostRecentContext::::get(para_id); let check_ctx = CandidateCheckContext::::new(prev_context); if check_ctx @@ -1242,7 +1242,7 @@ impl CandidateCheckContext { Error::::NotCollatorSigned, ); - let validation_code_hash = >::current_code_hash(para_id) + let validation_code_hash = paras::CurrentCodeHash::::get(para_id) // A candidate for a parachain without current validation code is not scheduled. .ok_or_else(|| Error::::UnscheduledCandidate)?; ensure!( diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index 24202035b261..0a601c902d0c 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -223,7 +223,7 @@ pub(crate) fn run_to_block( } pub(crate) fn expected_bits() -> usize { - Paras::parachains().len() + + paras::Parachains::::get().len() + configuration::ActiveConfig::::get().scheduler_params.num_cores as usize } @@ -835,7 +835,7 @@ fn supermajority_bitfields_trigger_availability() { }); // and check that chain head was enacted. - assert_eq!(Paras::para_head(&chain_a), Some(vec![1, 2, 3, 4].into())); + assert_eq!(paras::Heads::::get(&chain_a), Some(vec![1, 2, 3, 4].into())); // Check that rewards are applied. { diff --git a/polkadot/runtime/parachains/src/paras/mod.rs b/polkadot/runtime/parachains/src/paras/mod.rs index 82b92b263ecd..c5d000203ab2 100644 --- a/polkadot/runtime/parachains/src/paras/mod.rs +++ b/polkadot/runtime/parachains/src/paras/mod.rs @@ -706,8 +706,7 @@ pub mod pallet { /// /// Consider using the [`ParachainsCache`] type of modifying. #[pallet::storage] - #[pallet::getter(fn parachains)] - pub(crate) type Parachains = StorageValue<_, Vec, ValueQuery>; + pub type Parachains = StorageValue<_, Vec, ValueQuery>; /// The current lifecycle of a all known Para IDs. #[pallet::storage] @@ -715,21 +714,18 @@ pub mod pallet { /// The head-data of every registered para. #[pallet::storage] - #[pallet::getter(fn para_head)] - pub(super) type Heads = StorageMap<_, Twox64Concat, ParaId, HeadData>; + pub type Heads = 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 = + pub type MostRecentContext = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor>; /// 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 = + pub type CurrentCodeHash = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; /// Actual past code hash, indicated by the para id as well as the block number at which it @@ -744,8 +740,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 = + pub type PastCodeMeta = StorageMap<_, Twox64Concat, ParaId, ParaPastCodeMeta>, ValueQuery>; /// Which paras have past code that needs pruning and the relay-chain block at which the code @@ -762,16 +757,14 @@ 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 = + pub type FutureCodeUpgrades = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor>; /// The actual future code hash of a para. /// /// Corresponding code can be retrieved with [`CodeByHash`]. #[pallet::storage] - #[pallet::getter(fn future_code_hash)] - pub(super) type FutureCodeHash = + pub type FutureCodeHash = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; /// This is used by the relay-chain to communicate to a parachain a go-ahead with in the upgrade @@ -798,8 +791,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 = + pub type UpgradeRestrictionSignal = StorageMap<_, Twox64Concat, ParaId, UpgradeRestriction>; /// The list of parachains that are awaiting for their upgrade restriction to cooldown. @@ -819,8 +811,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 = + pub type ActionsQueue = StorageMap<_, Twox64Concat, SessionIndex, Vec, ValueQuery>; /// Upcoming paras instantiation arguments. @@ -841,8 +832,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 = + pub type CodeByHash = StorageMap<_, Identity, ValidationCodeHash, ValidationCode>; #[pallet::genesis_config] @@ -1274,7 +1264,7 @@ impl Pallet { /// The validation code of live para. pub(crate) fn current_code(para_id: &ParaId) -> Option { - Self::current_code_hash(para_id).and_then(|code_hash| { + CurrentCodeHash::::get(para_id).and_then(|code_hash| { let code = CodeByHash::::get(&code_hash); if code.is_none() { log::error!( @@ -1442,7 +1432,7 @@ impl Pallet { } } - meta.is_empty() && Self::para_head(¶_id).is_none() + meta.is_empty() && Heads::::get(¶_id).is_none() }); // This parachain has been removed and now the vestigial code diff --git a/polkadot/runtime/parachains/src/paras/tests.rs b/polkadot/runtime/parachains/src/paras/tests.rs index b718a0903dca..6d5ae032734b 100644 --- a/polkadot/runtime/parachains/src/paras/tests.rs +++ b/polkadot/runtime/parachains/src/paras/tests.rs @@ -26,6 +26,7 @@ use test_helpers::{dummy_head_data, dummy_validation_code, validator_pubkeys}; use crate::{ configuration::HostConfiguration, mock::{new_test_ext, MockGenesisConfig, Paras, ParasShared, RuntimeOrigin, System, Test}, + paras, }; static VALIDATORS: &[Sr25519Keyring] = &[ @@ -298,7 +299,7 @@ fn para_past_code_pruning_in_initialize() { PastCodePruning::::put(&vec![(id, included_block)]); { - let mut code_meta = Paras::past_code_meta(&id); + let mut code_meta = paras::PastCodeMeta::::get(&id); code_meta.note_replacement(at_block, included_block); PastCodeMeta::::insert(&id, &code_meta); } @@ -309,12 +310,12 @@ fn para_past_code_pruning_in_initialize() { run_to_block(pruned_at - 1, None); assert_eq!(PastCodeHash::::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::::get(&id).most_recent_change(), Some(at_block)); check_code_is_stored(&validation_code); run_to_block(pruned_at, None); assert!(PastCodeHash::::get(&(id, at_block)).is_none()); - assert!(Paras::past_code_meta(&id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(&id).most_recent_change().is_none()); check_code_is_not_stored(&validation_code); }); } @@ -342,11 +343,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::::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::::get(&id_a), Some(vec![1, 2, 3].into())); }); } @@ -389,11 +390,11 @@ fn note_past_code_sets_up_pruning_correctly() { assert_eq!(PastCodePruning::::get(), vec![(id_a, 12), (id_b, 23)]); assert_eq!( - Paras::past_code_meta(&id_a), + paras::PastCodeMeta::::get(&id_a), ParaPastCodeMeta { upgrade_times: vec![upgrade_at(10, 12)], last_pruned: None } ); assert_eq!( - Paras::past_code_meta(&id_b), + paras::PastCodeMeta::::get(&id_b), ParaPastCodeMeta { upgrade_times: vec![upgrade_at(20, 23)], last_pruned: None } ); }); @@ -455,7 +456,7 @@ fn code_upgrade_applied_after_delay() { Paras::note_new_head(para_id, Default::default(), 1); - assert!(Paras::past_code_meta(¶_id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(¶_id).most_recent_change().is_none()); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(expected_at)); assert_eq!(FutureCodeHash::::get(¶_id), Some(new_code.hash())); assert_eq!(UpcomingUpgrades::::get(), vec![(para_id, expected_at)]); @@ -474,7 +475,7 @@ fn code_upgrade_applied_after_delay() { { Paras::note_new_head(para_id, Default::default(), expected_at - 1); - assert!(Paras::past_code_meta(¶_id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(¶_id).most_recent_change().is_none()); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(expected_at)); assert_eq!(FutureCodeHash::::get(¶_id), Some(new_code.hash())); assert_eq!(UpgradeGoAheadSignal::::get(¶_id), Some(UpgradeGoAhead::GoAhead)); @@ -490,7 +491,7 @@ fn code_upgrade_applied_after_delay() { { Paras::note_new_head(para_id, Default::default(), expected_at); - assert_eq!(Paras::past_code_meta(¶_id).most_recent_change(), Some(expected_at)); + assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(expected_at)); assert_eq!( PastCodeHash::::get(&(para_id, expected_at)), Some(original_code.hash()), @@ -575,7 +576,7 @@ fn code_upgrade_applied_without_setting_go_ahead_signal() { Paras::note_new_head(para_id, Default::default(), 1); - assert!(Paras::past_code_meta(¶_id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(¶_id).most_recent_change().is_none()); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(expected_at)); assert_eq!(FutureCodeHash::::get(¶_id), Some(new_code.hash())); assert_eq!(UpcomingUpgrades::::get(), vec![]); @@ -595,7 +596,7 @@ fn code_upgrade_applied_without_setting_go_ahead_signal() { { Paras::note_new_head(para_id, Default::default(), expected_at - 1); - assert!(Paras::past_code_meta(¶_id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(¶_id).most_recent_change().is_none()); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(expected_at)); assert_eq!(FutureCodeHash::::get(¶_id), Some(new_code.hash())); assert!(UpgradeGoAheadSignal::::get(¶_id).is_none()); @@ -611,7 +612,7 @@ fn code_upgrade_applied_without_setting_go_ahead_signal() { { Paras::note_new_head(para_id, Default::default(), expected_at); - assert_eq!(Paras::past_code_meta(¶_id).most_recent_change(), Some(expected_at)); + assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(expected_at)); assert_eq!( PastCodeHash::::get(&(para_id, expected_at)), Some(original_code.hash()), @@ -692,7 +693,7 @@ fn code_upgrade_applied_after_delay_even_when_late() { Paras::note_new_head(para_id, Default::default(), 1); - assert!(Paras::past_code_meta(¶_id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(¶_id).most_recent_change().is_none()); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(expected_at)); assert_eq!(FutureCodeHash::::get(¶_id), Some(new_code.hash())); assert_eq!(UpcomingUpgrades::::get(), vec![(para_id, expected_at)]); @@ -713,7 +714,7 @@ 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(¶_id).most_recent_change(), Some(expected_at)); + assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(expected_at)); assert_eq!( PastCodeHash::::get(&(para_id, expected_at)), @@ -944,7 +945,7 @@ fn full_parachain_cleanup_storage() { Paras::note_new_head(para_id, Default::default(), 1); - assert!(Paras::past_code_meta(¶_id).most_recent_change().is_none()); + assert!(paras::PastCodeMeta::::get(¶_id).most_recent_change().is_none()); assert_eq!(FutureCodeUpgrades::::get(¶_id), Some(expected_at)); assert_eq!(FutureCodeHash::::get(¶_id), Some(new_code.hash())); assert_eq!(Paras::current_code(¶_id), Some(original_code.clone())); @@ -973,7 +974,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(¶_id).most_recent_change(), Some(8)); + assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(8)); assert_eq!(PastCodeHash::::get(&(para_id, 8)), Some(new_code.hash())); assert_eq!(PastCodePruning::::get(), vec![(para_id, 7), (para_id, 8)]); check_code_is_stored(&original_code); @@ -990,7 +991,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(¶_id), Default::default()); + assert_eq!(paras::PastCodeMeta::::get(¶_id), Default::default()); assert!(PastCodeHash::::get(&(para_id, 7)).is_none()); assert!(PastCodeHash::::get(&(para_id, 8)).is_none()); assert!(PastCodePruning::::get().is_empty()); @@ -1127,7 +1128,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::::get(), Vec::new()); assert_eq!(ActionsQueue::::get(Paras::scheduled_session()), vec![c, b, a],); // Lifecycle is tracked correctly @@ -1138,7 +1139,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::::get(), vec![c, b]); assert_eq!(ActionsQueue::::get(Paras::scheduled_session()), Vec::new()); // Lifecycle is tracked correctly @@ -1204,25 +1205,25 @@ 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(¶_id).upgrade_times, vec![upgrade_at(4, 10)]); + assert_eq!(paras::PastCodeMeta::::get(¶_id).upgrade_times, vec![upgrade_at(4, 10)]); assert_eq!(Paras::current_code(¶_id), Some(new_code.clone())); // Make sure that the old code is available **before** the code retion 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::::get(&old_code.hash()), Some(old_code.clone())); + assert_eq!(paras::CodeByHash::::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(¶_id), + paras::PastCodeMeta::::get(¶_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::::get(&old_code.hash()), None); // pruned :( + assert_eq!(paras::CodeByHash::::get(&new_code.hash()), Some(new_code.clone())); }); } @@ -1888,7 +1889,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::::get(para_id), None); assert_ok!(Paras::schedule_para_initialize( para_id, @@ -1907,16 +1908,16 @@ fn most_recent_context() { // Double-check the para is onboarded, the context is set to the recent block. assert_eq!(ParaLifecycles::::get(¶_id), Some(ParaLifecycle::Parachain)); - assert_eq!(Paras::para_most_recent_context(para_id), Some(0)); + assert_eq!(paras::MostRecentContext::::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::::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::::get(para_id), None); }) } diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index b9ea866c0154..15f9d9bbb2dd 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -615,7 +615,7 @@ impl Pallet { backed_candidate: &BackedCandidate<::Hash>| -> bool { let para_id = backed_candidate.descriptor().para_id; - let prev_context = >::para_most_recent_context(para_id); + let prev_context = paras::MostRecentContext::::get(para_id); let check_ctx = CandidateCheckContext::::new(prev_context); // never include a concluded-invalid candidate diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs index afc195173ff0..a1e788d1889f 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs @@ -208,7 +208,7 @@ pub fn assumed_validation_data( }) }); // If we were successful, also query current validation code hash. - persisted_validation_data.zip(>::current_code_hash(¶_id)) + persisted_validation_data.zip(paras::CurrentCodeHash::::get(¶_id)) } /// Implementation for the `check_validation_outputs` function of the runtime API. @@ -332,7 +332,7 @@ pub fn inbound_hrmp_channels_contents( pub fn validation_code_by_hash( hash: ValidationCodeHash, ) -> Option { - >::code_by_hash(hash) + paras::CodeByHash::::get(hash) } /// Disputes imported via means of on-chain imports. @@ -363,7 +363,7 @@ where T: inclusion::Config, { with_assumption::(para_id, assumption, || { - >::current_code_hash(¶_id) + paras::CurrentCodeHash::::get(¶_id) }) } @@ -418,14 +418,14 @@ pub fn backing_state( let min_relay_parent_number = >::allowed_relay_parents() .hypothetical_earliest_block_number(now, config.async_backing_params.allowed_ancestry_len); - let required_parent = >::para_head(para_id)?; - let validation_code_hash = >::current_code_hash(para_id)?; + let required_parent = paras::Heads::::get(para_id)?; + let validation_code_hash = paras::CurrentCodeHash::::get(para_id)?; - let upgrade_restriction = >::upgrade_restriction_signal(para_id); + let upgrade_restriction = paras::UpgradeRestrictionSignal::::get(para_id); let future_validation_code = - >::future_code_upgrade_at(para_id).and_then(|block_num| { + paras::FutureCodeUpgrades::::get(para_id).and_then(|block_num| { // Only read the storage if there's a pending upgrade. - Some(block_num).zip(>::future_code_hash(para_id)) + Some(block_num).zip(paras::FutureCodeHash::::get(para_id)) }); let (ump_msg_count, ump_total_bytes) = diff --git a/polkadot/runtime/parachains/src/scheduler/migration.rs b/polkadot/runtime/parachains/src/scheduler/migration.rs index 4c0a07d73674..702f6942e8cf 100644 --- a/polkadot/runtime/parachains/src/scheduler/migration.rs +++ b/polkadot/runtime/parachains/src/scheduler/migration.rs @@ -181,7 +181,7 @@ mod v1 { v1::add_to_claimqueue::(core_idx, pe); } - let parachains = paras::Pallet::::parachains(); + let parachains = paras::Parachains::::get(); let availability_cores = v0::AvailabilityCores::::take(); let mut new_availability_cores = Vec::new(); diff --git a/polkadot/runtime/parachains/src/util.rs b/polkadot/runtime/parachains/src/util.rs index a20748593709..30421177398a 100644 --- a/polkadot/runtime/parachains/src/util.rs +++ b/polkadot/runtime/parachains/src/util.rs @@ -35,7 +35,7 @@ pub fn make_persisted_validation_data( let config = configuration::ActiveConfig::::get(); Some(PersistedValidationData { - parent_head: >::para_head(¶_id)?, + parent_head: paras::Heads::::get(¶_id)?, relay_parent_number, relay_parent_storage_root, max_pov_size: config.max_pov_size, diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index ae847a1fbd49..a38dd6440586 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -1265,9 +1265,9 @@ parameter_types! { pub struct ParaHeadsRootProvider; impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { - let mut para_heads: Vec<(u32, Vec)> = Paras::parachains() + let mut para_heads: Vec<(u32, Vec)> = paras::Parachains::::get() .into_iter() - .filter_map(|id| Paras::para_head(&id).map(|head| (id.into(), head.0))) + .filter_map(|id| paras::Heads::::get(&id).map(|head| (id.into(), head.0))) .collect(); para_heads.sort(); binary_merkle_tree::merkle_root::( diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 4f0cf5999047..ce649251e23c 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -353,9 +353,9 @@ parameter_types! { pub struct ParaHeadsRootProvider; impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { - let mut para_heads: Vec<(u32, Vec)> = Paras::parachains() + let mut para_heads: Vec<(u32, Vec)> = paras::Parachains::::get() .into_iter() - .filter_map(|id| Paras::para_head(&id).map(|head| (id.into(), head.0))) + .filter_map(|id| paras::Heads::::get(&id).map(|head| (id.into(), head.0))) .collect(); para_heads.sort_by_key(|k| k.0); binary_merkle_tree::merkle_root::( From 89ba91919ef488ebb083912765db1eec8696845c Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 16:05:47 +0100 Subject: [PATCH 04/16] removed `pallet::getter` usage from `polkadot-runtime-parachains::{scheduler, session_info}` Signed-off-by: Matteo Muraca --- .../src/runtime/session_info.md | 4 +-- polkadot/runtime/parachains/src/builder.rs | 6 ++-- polkadot/runtime/parachains/src/disputes.rs | 4 +-- .../parachains/src/disputes/slashing.rs | 4 +-- .../src/disputes/slashing/benchmarking.rs | 2 +- .../parachains/src/initializer/tests.rs | 9 ++--- polkadot/runtime/parachains/src/paras/mod.rs | 15 +++----- .../runtime/parachains/src/paras/tests.rs | 20 ++++++++--- .../parachains/src/paras_inherent/mod.rs | 2 +- .../runtime/parachains/src/reward_points.rs | 2 +- .../parachains/src/runtime_api_impl/v7.rs | 16 ++++----- polkadot/runtime/parachains/src/scheduler.rs | 15 +++----- .../runtime/parachains/src/scheduler/tests.rs | 36 +++++++++---------- .../runtime/parachains/src/session_info.rs | 17 ++++----- 14 files changed, 73 insertions(+), 79 deletions(-) diff --git a/polkadot/roadmap/implementers-guide/src/runtime/session_info.md b/polkadot/roadmap/implementers-guide/src/runtime/session_info.md index 0442ee57505d..fa7f55c4f0b4 100644 --- a/polkadot/roadmap/implementers-guide/src/runtime/session_info.md +++ b/polkadot/roadmap/implementers-guide/src/runtime/session_info.md @@ -76,6 +76,6 @@ Sessions: map SessionIndex => Option, ## Routines -* `earliest_stored_session() -> SessionIndex`: Yields the earliest session for which we have information stored. -* `session_info(session: SessionIndex) -> Option`: Yields the session info for the given session, if +* `EarliestStoredSession::::get() -> SessionIndex`: Yields the earliest session for which we have information stored. +* `Sessions::::get(session: SessionIndex) -> Option`: Yields the session info for the given session, if stored. diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index 01555b3ff40d..7f83962c0413 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -434,10 +434,8 @@ impl BenchBuilder { assert_eq!(>::session_index(), target_session); // We need to refetch validators since they have been shuffled. - let validators_shuffled = session_info::Pallet::::session_info(target_session) - .unwrap() - .validators - .clone(); + let validators_shuffled = + session_info::Sessions::::get(target_session).unwrap().validators.clone(); self.validators = Some(validators_shuffled); self.block_number = block_number; diff --git a/polkadot/runtime/parachains/src/disputes.rs b/polkadot/runtime/parachains/src/disputes.rs index 62ac67db8559..b933ef707950 100644 --- a/polkadot/runtime/parachains/src/disputes.rs +++ b/polkadot/runtime/parachains/src/disputes.rs @@ -954,7 +954,7 @@ impl Pallet { let oldest_accepted = now.saturating_sub(post_conclusion_acceptance_period); // Load session info to access validators - let session_info = match >::session_info(set.session) { + let session_info = match session_info::Sessions::::get(set.session) { Some(s) => s, None => return StatementSetFilter::RemoveAll, }; @@ -1074,7 +1074,7 @@ impl Pallet { let set = set.as_ref(); // Load session info to access validators - let session_info = match >::session_info(set.session) { + let session_info = match session_info::Sessions::::get(set.session) { Some(s) => s, None => return Err(Error::::AncientDisputeStatement.into()), }; diff --git a/polkadot/runtime/parachains/src/disputes/slashing.rs b/polkadot/runtime/parachains/src/disputes/slashing.rs index 2f9274f305b1..91b34739517c 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing.rs @@ -193,7 +193,7 @@ where // 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::::account_keys(session_index); + let account_keys = crate::session_info::AccountKeys::::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::::session_info(session_index); + let session_info = crate::session_info::Sessions::::get(session_index); let session_info = match session_info.defensive_proof(DEFENSIVE_PROOF) { Some(info) => info, None => return, diff --git a/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs b/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs index f075ce5ca737..17ac77ca503b 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs @@ -84,7 +84,7 @@ where initializer::Pallet::::on_finalize(BlockNumberFor::::one()); let session_index = crate::shared::Pallet::::session_index(); - let session_info = crate::session_info::Pallet::::session_info(session_index); + let session_info = crate::session_info::Sessions::::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()); diff --git a/polkadot/runtime/parachains/src/initializer/tests.rs b/polkadot/runtime/parachains/src/initializer/tests.rs index ecea9be77ca0..bfc399e2f658 100644 --- a/polkadot/runtime/parachains/src/initializer/tests.rs +++ b/polkadot/runtime/parachains/src/initializer/tests.rs @@ -15,8 +15,9 @@ // along with Polkadot. If not, see . use super::*; -use crate::mock::{ - new_test_ext, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, Test, +use crate::{ + mock::{new_test_ext, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, Test}, + session_info, }; use primitives::{HeadData, Id as ParaId}; use test_helpers::dummy_validation_code; @@ -35,8 +36,8 @@ fn session_0_is_instantly_applied() { let v = BufferedSessionChanges::::get(); assert!(v.is_empty()); - assert_eq!(SessionInfo::earliest_stored_session(), 0); - assert!(SessionInfo::session_info(0).is_some()); + assert_eq!(session_info::EarliestStoredSession::::get(), 0); + assert!(session_info::Sessions::::get(0).is_some()); }); } diff --git a/polkadot/runtime/parachains/src/paras/mod.rs b/polkadot/runtime/parachains/src/paras/mod.rs index c5d000203ab2..09a4cf89ffac 100644 --- a/polkadot/runtime/parachains/src/paras/mod.rs +++ b/polkadot/runtime/parachains/src/paras/mod.rs @@ -718,15 +718,13 @@ pub mod pallet { /// The context (relay-chain block number) of the most recent parachain head. #[pallet::storage] - pub type MostRecentContext = - StorageMap<_, Twox64Concat, ParaId, BlockNumberFor>; + pub type MostRecentContext = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor>; /// The validation code hash of every live para. /// /// Corresponding code can be retrieved with [`CodeByHash`]. #[pallet::storage] - pub type CurrentCodeHash = - StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; + pub type CurrentCodeHash = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; /// Actual past code hash, indicated by the para id as well as the block number at which it /// became outdated. @@ -757,15 +755,13 @@ 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] - pub type FutureCodeUpgrades = - StorageMap<_, Twox64Concat, ParaId, BlockNumberFor>; + pub type FutureCodeUpgrades = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor>; /// The actual future code hash of a para. /// /// Corresponding code can be retrieved with [`CodeByHash`]. #[pallet::storage] - pub type FutureCodeHash = - StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; + pub type FutureCodeHash = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; /// This is used by the relay-chain to communicate to a parachain a go-ahead with in the upgrade /// procedure. @@ -832,8 +828,7 @@ pub mod pallet { /// This storage is consistent with [`FutureCodeHash`], [`CurrentCodeHash`] and /// [`PastCodeHash`]. #[pallet::storage] - pub type CodeByHash = - StorageMap<_, Identity, ValidationCodeHash, ValidationCode>; + pub type CodeByHash = StorageMap<_, Identity, ValidationCodeHash, ValidationCode>; #[pallet::genesis_config] #[derive(DefaultNoBound)] diff --git a/polkadot/runtime/parachains/src/paras/tests.rs b/polkadot/runtime/parachains/src/paras/tests.rs index 6d5ae032734b..93f1e0dfa765 100644 --- a/polkadot/runtime/parachains/src/paras/tests.rs +++ b/polkadot/runtime/parachains/src/paras/tests.rs @@ -491,7 +491,10 @@ fn code_upgrade_applied_after_delay() { { Paras::note_new_head(para_id, Default::default(), expected_at); - assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(expected_at)); + assert_eq!( + paras::PastCodeMeta::::get(¶_id).most_recent_change(), + Some(expected_at) + ); assert_eq!( PastCodeHash::::get(&(para_id, expected_at)), Some(original_code.hash()), @@ -612,7 +615,10 @@ fn code_upgrade_applied_without_setting_go_ahead_signal() { { Paras::note_new_head(para_id, Default::default(), expected_at); - assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(expected_at)); + assert_eq!( + paras::PastCodeMeta::::get(¶_id).most_recent_change(), + Some(expected_at) + ); assert_eq!( PastCodeHash::::get(&(para_id, expected_at)), Some(original_code.hash()), @@ -714,7 +720,10 @@ fn code_upgrade_applied_after_delay_even_when_late() { Paras::note_new_head(para_id, Default::default(), expected_at + 4); - assert_eq!(paras::PastCodeMeta::::get(¶_id).most_recent_change(), Some(expected_at)); + assert_eq!( + paras::PastCodeMeta::::get(¶_id).most_recent_change(), + Some(expected_at) + ); assert_eq!( PastCodeHash::::get(&(para_id, expected_at)), @@ -1205,7 +1214,10 @@ 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::PastCodeMeta::::get(¶_id).upgrade_times, vec![upgrade_at(4, 10)]); + assert_eq!( + paras::PastCodeMeta::::get(¶_id).upgrade_times, + vec![upgrade_at(4, 10)] + ); assert_eq!(Paras::current_code(¶_id), Some(new_code.clone())); // Make sure that the old code is available **before** the code retion period passes. diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index 15f9d9bbb2dd..d3f73bfc5279 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -391,7 +391,7 @@ impl Pallet { 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 = >::session_index(); - let expected_bits = >::availability_cores().len(); + let expected_bits = scheduler::AvailabilityCores::::get().len(); let validator_public = shared::Pallet::::active_validator_keys(); // We are assuming (incorrectly) to have all the weight (for the mandatory class or even diff --git a/polkadot/runtime/parachains/src/reward_points.rs b/polkadot/runtime/parachains/src/reward_points.rs index e9a9c5547a7a..d623f24a78a3 100644 --- a/polkadot/runtime/parachains/src/reward_points.rs +++ b/polkadot/runtime/parachains/src/reward_points.rs @@ -45,7 +45,7 @@ where indices: impl IntoIterator, points: u32, ) { - let validators = session_info::Pallet::::account_keys(&session_index); + let validators = session_info::AccountKeys::::get(&session_index); let validators = match validators .defensive_proof("account_keys are present for dispute_period sessions") { diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs index a1e788d1889f..434535f3c7ec 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs @@ -49,7 +49,7 @@ pub fn validator_groups( // when populating group_responsible in `availability_cores` let now = >::block_number() + One::one(); - let groups = >::validator_groups(); + let groups = scheduler::ValidatorGroups::::get(); let rotation_info = >::group_rotation_info(now); (groups, rotation_info) @@ -57,7 +57,7 @@ pub fn validator_groups( /// Implementation for the `availability_cores` function of the runtime API. pub fn availability_cores() -> Vec>> { - let cores = >::availability_cores(); + let cores = scheduler::AvailabilityCores::::get(); let now = >::block_number() + One::one(); // This explicit update is only strictly required for session boundaries: @@ -242,7 +242,7 @@ pub fn session_index_for_child() -> SessionIndex { pub fn relevant_authority_ids( ) -> Vec { let current_session_index = session_index_for_child::(); - let earliest_stored_session = >::earliest_stored_session(); + let earliest_stored_session = session_info::EarliestStoredSession::::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 @@ -253,7 +253,7 @@ pub fn relevant_authority_ids>::session_info(session_index); + let info = session_info::Sessions::::get(session_index); if let Some(mut info) = info { authority_ids.append(&mut info.discovery_keys); } @@ -311,7 +311,7 @@ where /// Get the session info for the given session, if stored. pub fn session_info(index: SessionIndex) -> Option { - >::session_info(index) + session_info::Sessions::::get(index) } /// Implementation for the `dmq_contents` function of the runtime API. @@ -362,9 +362,7 @@ pub fn validation_code_hash( where T: inclusion::Config, { - with_assumption::(para_id, assumption, || { - paras::CurrentCodeHash::::get(¶_id) - }) + with_assumption::(para_id, assumption, || paras::CurrentCodeHash::::get(¶_id)) } /// Implementation for `get_session_disputes` function from the runtime API @@ -377,7 +375,7 @@ pub fn get_session_disputes( pub fn session_executor_params( session_index: SessionIndex, ) -> Option { - >::session_executor_params(session_index) + session_info::SessionExecutorParams::::get(session_index) } /// Implementation of `unapplied_slashes` runtime API diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index 50088c9b2666..5d0711e2bf49 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -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 = StorageValue<_, Vec>, ValueQuery>; + pub type ValidatorGroups = StorageValue<_, Vec>, 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 = - StorageValue<_, Vec>, ValueQuery>; + pub type AvailabilityCores = StorageValue<_, Vec>, 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 = StorageValue<_, BlockNumberFor, ValueQuery>; + pub type SessionStartBlock = StorageValue<_, BlockNumberFor, 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 = + pub type ClaimQueue = StorageValue<_, BTreeMap>>, ValueQuery>; /// Assignments as tracked in the claim queue. @@ -493,7 +488,7 @@ impl Pallet { pub(crate) fn group_rotation_info( now: BlockNumberFor, ) -> GroupRotationInfo> { - let session_start_block = Self::session_start_block(); + let session_start_block = SessionStartBlock::::get(); let group_rotation_frequency = configuration::ActiveConfig::::get() .scheduler_params .group_rotation_frequency; diff --git a/polkadot/runtime/parachains/src/scheduler/tests.rs b/polkadot/runtime/parachains/src/scheduler/tests.rs index 5735607bc841..030062fc79d3 100644 --- a/polkadot/runtime/parachains/src/scheduler/tests.rs +++ b/polkadot/runtime/parachains/src/scheduler/tests.rs @@ -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::::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::::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::::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::>().is_empty()); // All `core_queue`s should be empty - Scheduler::claimqueue() + scheduler::ClaimQueue::::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::::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::::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::::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::::get().len(), 1); // ParaId a is in the claimqueue. assert!(claimqueue_contains_para_ids::(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::::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::::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::::get().len(), 1); + assert_eq!(scheduler::AvailabilityCores::::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::::get(); match cores.get(0).unwrap() { CoreOccupied::Paras(entry) => { assert_eq!(entry.assignment, assignment_a.clone()); @@ -1085,7 +1085,7 @@ fn session_change_requires_reschedule_dropping_removed_paras() { _ => None, }); - assert_eq!(Scheduler::claimqueue().len(), 2); + assert_eq!(scheduler::ClaimQueue::::get().len(), 2); let groups = ValidatorGroups::::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::::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::::get().len(), 2); let groups = ValidatorGroups::::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::::get(), vec![ ( CoreIndex(0), diff --git a/polkadot/runtime/parachains/src/session_info.rs b/polkadot/runtime/parachains/src/session_info.rs index 30f865299937..18461d4800ea 100644 --- a/polkadot/runtime/parachains/src/session_info.rs +++ b/polkadot/runtime/parachains/src/session_info.rs @@ -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 = StorageValue<_, SessionIndex, ValueQuery>; + pub type EarliestStoredSession = 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 = StorageMap<_, Identity, SessionIndex, SessionInfo>; + pub type Sessions = 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 = - StorageMap<_, Identity, SessionIndex, Vec>>; + pub type AccountKeys = StorageMap<_, Identity, SessionIndex, Vec>>; /// Executor parameter set for a given session index #[pallet::storage] - #[pallet::getter(fn session_executor_params)] - pub(crate) type SessionExecutorParams = + pub type SessionExecutorParams = StorageMap<_, Identity, SessionIndex, ExecutorParams>; } @@ -138,8 +133,8 @@ impl Pallet { let assignment_keys = AssignmentKeysUnsafe::::get(); let active_set = >::active_validator_indices(); - let validator_groups = >::validator_groups().into(); - let n_cores = >::availability_cores().len() as u32; + let validator_groups = scheduler::ValidatorGroups::::get().into(); + let n_cores = scheduler::AvailabilityCores::::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; From 905a34eb6b364435c50df677f050b604af3de202 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 16:13:42 +0100 Subject: [PATCH 05/16] fixed rococo and westend clippy complaint Signed-off-by: Matteo Muraca --- polkadot/runtime/rococo/src/lib.rs | 4 ++-- polkadot/runtime/westend/src/lib.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index a38dd6440586..58fdf4ac582c 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -1265,9 +1265,9 @@ parameter_types! { pub struct ParaHeadsRootProvider; impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { - let mut para_heads: Vec<(u32, Vec)> = paras::Parachains::::get() + let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map(|id| paras::Heads::::get(&id).map(|head| (id.into(), head.0))) + .filter_map(|id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0))) .collect(); para_heads.sort(); binary_merkle_tree::merkle_root::( diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index ce649251e23c..b9f2ed7fbe0b 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -353,9 +353,9 @@ parameter_types! { pub struct ParaHeadsRootProvider; impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { - let mut para_heads: Vec<(u32, Vec)> = paras::Parachains::::get() + let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map(|id| paras::Heads::::get(&id).map(|head| (id.into(), head.0))) + .filter_map(|id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0))) .collect(); para_heads.sort_by_key(|k| k.0); binary_merkle_tree::merkle_root::( From 09cc5f865da0b897cdffee5a1c5e55c7410ac2e5 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 16:17:40 +0100 Subject: [PATCH 06/16] fixed rococo and westend fmt Signed-off-by: Matteo Muraca --- polkadot/runtime/rococo/src/lib.rs | 4 +++- polkadot/runtime/westend/src/lib.rs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 58fdf4ac582c..71c62004f3d6 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -1267,7 +1267,9 @@ impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map(|id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0))) + .filter_map(|id| { + parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) + }) .collect(); para_heads.sort(); binary_merkle_tree::merkle_root::( diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index b9f2ed7fbe0b..6450de78662c 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -355,7 +355,9 @@ impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() .into_iter() - .filter_map(|id| parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0))) + .filter_map(|id| { + parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) + }) .collect(); para_heads.sort_by_key(|k| k.0); binary_merkle_tree::merkle_root::( From 1669d0e6e3a2ff7c3efa52b73109ac8c77ce8d0d Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 17:06:40 +0100 Subject: [PATCH 07/16] removed `pallet::getter` usage from `polkadot-runtime-parachains::shared` Signed-off-by: Matteo Muraca --- .../runtime/common/src/integration_tests.rs | 2 +- .../runtime/common/src/paras_registrar/mod.rs | 2 +- polkadot/runtime/parachains/src/builder.rs | 2 +- .../parachains/src/disputes/slashing.rs | 2 +- .../src/disputes/slashing/benchmarking.rs | 4 ++-- polkadot/runtime/parachains/src/hrmp/tests.rs | 12 ++++++++---- .../runtime/parachains/src/inclusion/mod.rs | 4 ++-- .../runtime/parachains/src/inclusion/tests.rs | 16 ++++++++-------- .../parachains/src/initializer/tests.rs | 4 ++-- .../parachains/src/paras/benchmarking.rs | 4 ++-- .../src/paras/benchmarking/pvf_check.rs | 2 +- polkadot/runtime/parachains/src/paras/mod.rs | 16 ++++++++-------- polkadot/runtime/parachains/src/paras/tests.rs | 3 ++- .../parachains/src/paras_inherent/mod.rs | 6 +++--- .../parachains/src/paras_inherent/tests.rs | 18 +++++++++--------- .../runtime/parachains/src/reward_points.rs | 2 +- .../parachains/src/runtime_api_impl/v7.rs | 6 +++--- .../runtime/parachains/src/session_info.rs | 2 +- .../parachains/src/session_info/tests.rs | 2 +- polkadot/runtime/parachains/src/shared.rs | 14 +++++--------- .../runtime/parachains/src/shared/tests.rs | 11 ++++++----- 21 files changed, 68 insertions(+), 66 deletions(-) diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index 761e742fc673..45f4146bac6b 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -348,7 +348,7 @@ const VALIDATORS: &[Sr25519Keyring] = &[ fn maybe_new_session(n: u32) { if n % BLOCKS_PER_SESSION == 0 { - let session_index = shared::Pallet::::session_index() + 1; + let session_index = shared::CurrentSessionIndex::::get() + 1; let validators_pub_keys = validators_public_keys(VALIDATORS); shared::Pallet::::set_session_index(session_index); diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 2c2d3b3eb9ca..ce09b38e6878 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -904,7 +904,7 @@ mod tests { } // Session change every 3 blocks. if (b + 1) % BLOCKS_PER_SESSION == 0 { - let session_index = shared::Pallet::::session_index() + 1; + let session_index = shared::CurrentSessionIndex::::get() + 1; let validators_pub_keys = VALIDATORS.iter().map(|v| v.public().into()).collect(); shared::Pallet::::set_session_index(session_index); diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index 7f83962c0413..f068fcf64ebe 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -431,7 +431,7 @@ impl BenchBuilder { &Digest { logs: Vec::new() }, ); - assert_eq!(>::session_index(), target_session); + assert_eq!(shared::CurrentSessionIndex::::get(), target_session); // We need to refetch validators since they have been shuffled. let validators_shuffled = diff --git a/polkadot/runtime/parachains/src/disputes/slashing.rs b/polkadot/runtime/parachains/src/disputes/slashing.rs index 91b34739517c..188464218e95 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing.rs @@ -187,7 +187,7 @@ where validators: impl IntoIterator, ) -> Option>> { // We use `ValidatorSet::session_index` and not - // `shared::Pallet::session_index()` because at the first block of a new era, + // `shared::CurrentSessionIndex::::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. diff --git a/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs b/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs index 17ac77ca503b..42a64725160c 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs @@ -83,7 +83,7 @@ where } initializer::Pallet::::on_finalize(BlockNumberFor::::one()); - let session_index = crate::shared::Pallet::::session_index(); + let session_index = crate::shared::CurrentSessionIndex::::get(); let session_info = crate::session_info::Sessions::::get(session_index); let session_info = session_info.unwrap(); let validator_id = session_info.validators.get(ValidatorIndex::from(0)).unwrap().clone(); @@ -95,7 +95,7 @@ where pallet_session::Pallet::::rotate_session(); initializer::Pallet::::on_finalize(BlockNumberFor::::one()); - let idx = crate::shared::Pallet::::session_index(); + let idx = crate::shared::CurrentSessionIndex::::get(); assert!( idx > session_index, "session rotation should work for parachain pallets: {} <= {}", diff --git a/polkadot/runtime/parachains/src/hrmp/tests.rs b/polkadot/runtime/parachains/src/hrmp/tests.rs index 8dae04114d62..0f293781012a 100644 --- a/polkadot/runtime/parachains/src/hrmp/tests.rs +++ b/polkadot/runtime/parachains/src/hrmp/tests.rs @@ -19,9 +19,13 @@ // both paras are system chains, then they are also configured to the system's max configuration. use super::*; -use crate::mock::{ - deregister_parachain, new_test_ext, register_parachain, register_parachain_with_balance, Hrmp, - MockGenesisConfig, Paras, ParasShared, RuntimeEvent as MockEvent, RuntimeOrigin, System, Test, +use crate::{ + mock::{ + deregister_parachain, new_test_ext, register_parachain, register_parachain_with_balance, + Hrmp, MockGenesisConfig, Paras, ParasShared, RuntimeEvent as MockEvent, RuntimeOrigin, + System, Test, + }, + shared, }; use frame_support::{assert_noop, assert_ok}; use primitives::BlockNumber; @@ -41,7 +45,7 @@ pub(crate) fn run_to_block(to: BlockNumber, new_session: Option let notification = crate::initializer::SessionChangeNotification { prev_config: config.clone(), new_config: config.clone(), - session_index: ParasShared::session_index() + 1, + session_index: shared::CurrentSessionIndex::::get() + 1, ..Default::default() }; diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index 4a1792d798bb..1d665a417e49 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -612,7 +612,7 @@ impl Pallet { } let minimum_backing_votes = configuration::ActiveConfig::::get().minimum_backing_votes; - let validators = shared::Pallet::::active_validator_keys(); + let validators = shared::ActiveValidatorKeys::::get(); // Collect candidate receipts with backers. let mut candidate_receipt_with_backing_validator_indices = @@ -652,7 +652,7 @@ impl Pallet { let check_ctx = CandidateCheckContext::::new(prev_context); let signing_context = SigningContext { parent_hash: relay_parent_hash, - session_index: shared::Pallet::::session_index(), + session_index: shared::CurrentSessionIndex::::get(), }; let relay_parent_number = match check_ctx.verify_backed_candidate( diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index 0a601c902d0c..644cabbeaf44 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -183,7 +183,7 @@ pub(crate) fn run_to_block_default_notifications(to: BlockNumber, new_session: V new_session.contains(&b).then_some(SessionChangeNotification { prev_config: configuration::ActiveConfig::::get(), new_config: configuration::ActiveConfig::::get(), - session_index: ParasShared::session_index() + 1, + session_index: shared::CurrentSessionIndex::::get() + 1, ..Default::default() }) }); @@ -232,11 +232,11 @@ fn default_bitfield() -> AvailabilityBitfield { } fn default_availability_votes() -> BitVec { - bitvec::bitvec![u8, BitOrderLsb0; 0; ParasShared::active_validator_keys().len()] + bitvec::bitvec![u8, BitOrderLsb0; 0; shared::ActiveValidatorKeys::::get().len()] } fn default_backing_bitfield() -> BitVec { - bitvec::bitvec![u8, BitOrderLsb0; 0; ParasShared::active_validator_keys().len()] + bitvec::bitvec![u8, BitOrderLsb0; 0; shared::ActiveValidatorKeys::::get().len()] } fn backing_bitfield(v: &[usize]) -> BitVec { @@ -346,8 +346,8 @@ fn simple_sanitize_bitfields( expected_bits: usize, ) -> SignedAvailabilityBitfields { let parent_hash = frame_system::Pallet::::parent_hash(); - let session_index = shared::Pallet::::session_index(); - let validators = shared::Pallet::::active_validator_keys(); + let session_index = shared::CurrentSessionIndex::::get(); + let validators = shared::ActiveValidatorKeys::::get(); crate::paras_inherent::sanitize_bitfields::( unchecked_bitfields, @@ -364,7 +364,7 @@ pub(crate) fn process_bitfields( signed_bitfields: SignedAvailabilityBitfields, core_lookup: impl Fn(CoreIndex) -> Option, ) -> Vec<(CoreIndex, CandidateHash)> { - let validators = shared::Pallet::::active_validator_keys(); + let validators = shared::ActiveValidatorKeys::::get(); ParaInclusion::update_pending_availability_and_get_freed_cores::<_>( expected_bits, @@ -2312,7 +2312,7 @@ fn session_change_wipes() { run_to_block(11, |_| None); - assert_eq!(shared::Pallet::::session_index(), 5); + assert_eq!(shared::CurrentSessionIndex::::get(), 5); assert!(>::get(&ValidatorIndex(0)).is_some()); assert!(>::get(&ValidatorIndex(1)).is_some()); @@ -2335,7 +2335,7 @@ fn session_change_wipes() { _ => None, }); - assert_eq!(shared::Pallet::::session_index(), 6); + assert_eq!(shared::CurrentSessionIndex::::get(), 6); assert!(>::get(&ValidatorIndex(0)).is_none()); assert!(>::get(&ValidatorIndex(1)).is_none()); diff --git a/polkadot/runtime/parachains/src/initializer/tests.rs b/polkadot/runtime/parachains/src/initializer/tests.rs index bfc399e2f658..e757e6b9d117 100644 --- a/polkadot/runtime/parachains/src/initializer/tests.rs +++ b/polkadot/runtime/parachains/src/initializer/tests.rs @@ -16,13 +16,13 @@ use super::*; use crate::{ - mock::{new_test_ext, Dmp, Initializer, MockGenesisConfig, Paras, SessionInfo, System, Test}, + 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}, diff --git a/polkadot/runtime/parachains/src/paras/benchmarking.rs b/polkadot/runtime/parachains/src/paras/benchmarking.rs index 554f0c15af24..65f5368105fc 100644 --- a/polkadot/runtime/parachains/src/paras/benchmarking.rs +++ b/polkadot/runtime/parachains/src/paras/benchmarking.rs @@ -68,7 +68,7 @@ pub(crate) fn generate_disordered_upgrades() { fn generate_disordered_actions_queue() { let mut queue = Vec::new(); - let next_session = shared::Pallet::::session_index().saturating_add(One::one()); + let next_session = shared::CurrentSessionIndex::::get().saturating_add(One::one()); for _ in 0..SAMPLE_SIZE { let id = ParaId::from(1000); @@ -140,7 +140,7 @@ benchmarks! { generate_disordered_actions_queue::(); }: _(RawOrigin::Root, para_id) verify { - let next_session = crate::shared::Pallet::::session_index().saturating_add(One::one()); + let next_session = crate::shared::CurrentSessionIndex::::get().saturating_add(One::one()); assert_last_event::(Event::ActionQueued(para_id, next_session).into()); } diff --git a/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs b/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs index fcce29678c45..ddde136ee713 100644 --- a/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs +++ b/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs @@ -202,7 +202,7 @@ fn generate_statements( where T: Config + shared::Config, { - let validators = ParasShared::::active_validator_keys(); + let validators = shared::ActiveValidatorKeys::::get(); let accept_threshold = primitives::supermajority_threshold(validators.len()); let required_votes = match vote_outcome { diff --git a/polkadot/runtime/parachains/src/paras/mod.rs b/polkadot/runtime/parachains/src/paras/mod.rs index 09a4cf89ffac..bbf6f70ddb5c 100644 --- a/polkadot/runtime/parachains/src/paras/mod.rs +++ b/polkadot/runtime/parachains/src/paras/mod.rs @@ -941,7 +941,7 @@ pub mod pallet { #[pallet::weight(::WeightInfo::force_queue_action())] pub fn force_queue_action(origin: OriginFor, para: ParaId) -> DispatchResult { ensure_root(origin)?; - let next_session = shared::Pallet::::session_index().saturating_add(One::one()); + let next_session = shared::CurrentSessionIndex::::get().saturating_add(One::one()); ActionsQueue::::mutate(next_session, |v| { if let Err(i) = v.binary_search(¶) { v.insert(i, para); @@ -1044,8 +1044,8 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { ensure_none(origin)?; - let validators = shared::Pallet::::active_validator_keys(); - let current_session = shared::Pallet::::session_index(); + let validators = shared::ActiveValidatorKeys::::get(); + let current_session = shared::CurrentSessionIndex::::get(); if stmt.session_index < current_session { return Err(Error::::PvfCheckStatementStale.into()) } else if stmt.session_index > current_session { @@ -1143,7 +1143,7 @@ pub mod pallet { _ => return InvalidTransaction::Call.into(), }; - let current_session = shared::Pallet::::session_index(); + let current_session = shared::CurrentSessionIndex::::get(); if stmt.session_index < current_session { return InvalidTransaction::Stale.into() } else if stmt.session_index > current_session { @@ -1151,7 +1151,7 @@ pub mod pallet { } let validator_index = stmt.validator_index.0 as usize; - let validators = shared::Pallet::::active_validator_keys(); + let validators = shared::ActiveValidatorKeys::::get(); let validator_public = match validators.get(validator_index) { Some(pk) => pk, None => return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into(), @@ -1588,7 +1588,7 @@ impl Pallet { // // we cannot onboard at the current session, so it must be at least one // session ahead. - let onboard_at: SessionIndex = shared::Pallet::::session_index() + + let onboard_at: SessionIndex = shared::CurrentSessionIndex::::get() + cmp::max(shared::SESSION_DELAY.saturating_sub(sessions_observed), 1); ActionsQueue::::mutate(onboard_at, |v| { @@ -1986,7 +1986,7 @@ impl Pallet { // process. weight += T::DbWeight::get().reads_writes(3, 2); let now = >::block_number(); - let n_validators = shared::Pallet::::active_validator_keys().len(); + let n_validators = shared::ActiveValidatorKeys::::get().len(); PvfActiveVoteMap::::insert( &code_hash, PvfCheckActiveVoteState::new(now, n_validators, cause), @@ -2202,7 +2202,7 @@ impl Pallet { #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] pub fn test_on_new_session() { Self::initializer_on_new_session(&SessionChangeNotification { - session_index: shared::Pallet::::session_index(), + session_index: shared::CurrentSessionIndex::::get(), ..Default::default() }); } diff --git a/polkadot/runtime/parachains/src/paras/tests.rs b/polkadot/runtime/parachains/src/paras/tests.rs index 93f1e0dfa765..d4ce2f5db64a 100644 --- a/polkadot/runtime/parachains/src/paras/tests.rs +++ b/polkadot/runtime/parachains/src/paras/tests.rs @@ -93,7 +93,8 @@ fn run_to_block(to: BlockNumber, new_session: Option>) { 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::::get() + 1; session_change_notification.validators = validator_pubkeys.clone(); ParasShared::initializer_on_new_session( session_change_notification.session_index, diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index d3f73bfc5279..877950054111 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -377,7 +377,7 @@ impl Pallet { ); }); } - let allowed_relay_parents = >::allowed_relay_parents(); + let allowed_relay_parents = shared::AllowedRelayParents::::get(); let candidates_weight = backed_candidates_weight::(&backed_candidates); let bitfields_weight = signed_bitfields_weight::(&bitfields); @@ -390,9 +390,9 @@ impl Pallet { 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 = >::session_index(); + let current_session = shared::CurrentSessionIndex::::get(); let expected_bits = scheduler::AvailabilityCores::::get().len(); - let validator_public = shared::Pallet::::active_validator_keys(); + let validator_public = shared::ActiveValidatorKeys::::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 diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index 6ccc5af68e4d..9c211e46d061 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -1513,7 +1513,7 @@ mod sanitizers { vec![(CoreIndex(0), ParaId::from(1)), (CoreIndex(1), ParaId::from(2))] ); assert_eq!( - shared::Pallet::::active_validator_indices(), + shared::ActiveValidatorIndices::::get(), vec![ ValidatorIndex(0), ValidatorIndex(1), @@ -1861,7 +1861,7 @@ mod sanitizers { } assert_eq!( - shared::Pallet::::active_validator_indices(), + shared::ActiveValidatorIndices::::get(), vec![ ValidatorIndex(0), ValidatorIndex(1), @@ -1897,7 +1897,7 @@ mod sanitizers { assert_eq!( sanitize_backed_candidates::( backed_candidates.clone(), - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), has_concluded_invalid, scheduled, core_index_enabled @@ -1928,7 +1928,7 @@ mod sanitizers { assert_eq!( sanitize_backed_candidates::( backed_candidates.clone(), - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), has_concluded_invalid, scheduled, core_index_enabled @@ -1968,7 +1968,7 @@ mod sanitizers { dropped_unscheduled_candidates, } = sanitize_backed_candidates::( backed_candidates.clone(), - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), has_concluded_invalid, scheduled, core_index_enabled, @@ -2007,7 +2007,7 @@ mod sanitizers { dropped_unscheduled_candidates, } = sanitize_backed_candidates::( backed_candidates.clone(), - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), has_concluded_invalid, scheduled, core_index_enabled, @@ -2036,7 +2036,7 @@ mod sanitizers { // filtered assert!(!filter_backed_statements_from_disabled_validators::( &mut all_backed_candidates_with_core, - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), core_index_enabled )); assert_eq!(all_backed_candidates_with_core, before); @@ -2084,7 +2084,7 @@ mod sanitizers { assert!(filter_backed_statements_from_disabled_validators::( &mut all_backed_candidates_with_core, - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), core_index_enabled )); @@ -2134,7 +2134,7 @@ mod sanitizers { assert!(filter_backed_statements_from_disabled_validators::( &mut all_backed_candidates_with_core, - &>::allowed_relay_parents(), + &shared::AllowedRelayParents::::get(), core_index_enabled )); diff --git a/polkadot/runtime/parachains/src/reward_points.rs b/polkadot/runtime/parachains/src/reward_points.rs index d623f24a78a3..3be743a2c551 100644 --- a/polkadot/runtime/parachains/src/reward_points.rs +++ b/polkadot/runtime/parachains/src/reward_points.rs @@ -71,7 +71,7 @@ where C::ValidatorSet: ValidatorSet, { fn reward_backing(indices: impl IntoIterator) { - let session_index = shared::Pallet::::session_index(); + let session_index = shared::CurrentSessionIndex::::get(); Self::reward_only_active(session_index, indices, BACKING_POINTS); } diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs index 434535f3c7ec..d1fda56aee66 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/v7.rs @@ -39,7 +39,7 @@ use sp_std::{collections::btree_map::BTreeMap, prelude::*}; /// Implementation for the `validators` function of the runtime API. pub fn validators() -> Vec { - >::active_validator_keys() + shared::ActiveValidatorKeys::::get() } /// Implementation for the `validator_groups` function of the runtime API. @@ -233,7 +233,7 @@ pub fn session_index_for_child() -> 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". - >::session_index() + shared::CurrentSessionIndex::::get() } /// Implementation for the `AuthorityDiscoveryApi::authorities()` function of the runtime API. @@ -413,7 +413,7 @@ pub fn backing_state( // // Thus, minimum relay parent is ensured to have asynchronous backing enabled. let now = >::block_number(); - let min_relay_parent_number = >::allowed_relay_parents() + let min_relay_parent_number = shared::AllowedRelayParents::::get() .hypothetical_earliest_block_number(now, config.async_backing_params.allowed_ancestry_len); let required_parent = paras::Heads::::get(para_id)?; diff --git a/polkadot/runtime/parachains/src/session_info.rs b/polkadot/runtime/parachains/src/session_info.rs index 18461d4800ea..39eb2d3e2900 100644 --- a/polkadot/runtime/parachains/src/session_info.rs +++ b/polkadot/runtime/parachains/src/session_info.rs @@ -131,7 +131,7 @@ impl Pallet { let validators = notification.validators.clone().into(); let discovery_keys = ::authorities(); let assignment_keys = AssignmentKeysUnsafe::::get(); - let active_set = >::active_validator_indices(); + let active_set = shared::ActiveValidatorIndices::::get(); let validator_groups = scheduler::ValidatorGroups::::get().into(); let n_cores = scheduler::AvailabilityCores::::get().len() as u32; diff --git a/polkadot/runtime/parachains/src/session_info/tests.rs b/polkadot/runtime/parachains/src/session_info/tests.rs index ff51b8417242..18b9d8f59010 100644 --- a/polkadot/runtime/parachains/src/session_info/tests.rs +++ b/polkadot/runtime/parachains/src/session_info/tests.rs @@ -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::::get(), active_set); AssignmentKeysUnsafe::::set(unscrambled_assignment.clone()); crate::mock::set_discovery_authorities(unscrambled_discovery.clone()); diff --git a/polkadot/runtime/parachains/src/shared.rs b/polkadot/runtime/parachains/src/shared.rs index bdaffcd505f8..f2df923f3649 100644 --- a/polkadot/runtime/parachains/src/shared.rs +++ b/polkadot/runtime/parachains/src/shared.rs @@ -138,21 +138,17 @@ pub mod pallet { /// The current session index. #[pallet::storage] - #[pallet::getter(fn session_index)] - pub(super) type CurrentSessionIndex = StorageValue<_, SessionIndex, ValueQuery>; + pub type CurrentSessionIndex = 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 = - StorageValue<_, Vec, ValueQuery>; + pub type ActiveValidatorIndices = StorageValue<_, Vec, 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 = StorageValue<_, Vec, ValueQuery>; + pub type ActiveValidatorKeys = StorageValue<_, Vec, ValueQuery>; /// All allowed relay-parents. #[pallet::storage] @@ -218,13 +214,13 @@ impl Pallet { /// 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::::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 { - let shuffled_indices = Pallet::::active_validator_indices(); + let shuffled_indices = ActiveValidatorIndices::::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 diff --git a/polkadot/runtime/parachains/src/shared/tests.rs b/polkadot/runtime/parachains/src/shared/tests.rs index ae12b4b3fc16..4ae37463a6d9 100644 --- a/polkadot/runtime/parachains/src/shared/tests.rs +++ b/polkadot/runtime/parachains/src/shared/tests.rs @@ -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::::get(), validators); assert_eq!( - ParasShared::active_validator_indices(), + shared::ActiveValidatorIndices::::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::::get(), validators); assert_eq!( - ParasShared::active_validator_indices(), + shared::ActiveValidatorIndices::::get(), vec![ValidatorIndex(4), ValidatorIndex(1),] ); }); From 2802684bf5438c8c032696d65de7535cfe83f556 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 17:32:42 +0100 Subject: [PATCH 08/16] prdoc for #3660 Signed-off-by: Matteo Muraca --- prdoc/pr_3660.prdoc | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 prdoc/pr_3660.prdoc diff --git a/prdoc/pr_3660.prdoc b/prdoc/pr_3660.prdoc new file mode 100644 index 000000000000..0104713ad6b1 --- /dev/null +++ b/prdoc/pr_3660.prdoc @@ -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 depdendant runtimes accordingly. + The syntax `StorageItem::::get()` should be used instead. + +crates: + - name: polkadot-runtime-common + - name: polkadot-runtime-parachains + - name: rococo-runtime + - name: westend-runtime From 27e0e3ddc375e9fdbaba617a8a9bdb0f1e5f96d4 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 12 Mar 2024 17:34:29 +0100 Subject: [PATCH 09/16] fix hrmp benchmarking Signed-off-by: Matteo Muraca --- .../parachains/src/hrmp/benchmarking.rs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/polkadot/runtime/parachains/src/hrmp/benchmarking.rs b/polkadot/runtime/parachains/src/hrmp/benchmarking.rs index 507721b2b78d..a3bb1d7863e7 100644 --- a/polkadot/runtime/parachains/src/hrmp/benchmarking.rs +++ b/polkadot/runtime/parachains/src/hrmp/benchmarking.rs @@ -71,7 +71,7 @@ fn establish_para_connection( where ::RuntimeOrigin: From, { - let config = configuration::ActiveConfig::::get(); + let config = configuration::ActiveConfig::::get(); let ed = T::Currency::minimum_balance(); let deposit: BalanceOf = config.hrmp_sender_deposit.unique_saturated_into(); let capacity = config.hrmp_channel_max_capacity; @@ -109,7 +109,7 @@ where return output } - Hrmp::::process_hrmp_open_channel_requests(&configuration::ActiveConfig::::get()); + Hrmp::::process_hrmp_open_channel_requests(&configuration::ActiveConfig::::get()); if matches!(until, ParachainSetupStep::Established) { return output } @@ -154,14 +154,14 @@ mod benchmarks { // make sure para is registered, and has enough balance. let ed = T::Currency::minimum_balance(); - let deposit: BalanceOf = configuration::ActiveConfig::::get() + let deposit: BalanceOf = configuration::ActiveConfig::::get() .hrmp_sender_deposit .unique_saturated_into(); register_parachain_with_balance::(sender_id, deposit + ed); register_parachain_with_balance::(recipient_id, deposit + ed); - let capacity = configuration::ActiveConfig::::get().hrmp_channel_max_capacity; - let message_size = configuration::ActiveConfig::::get().hrmp_channel_max_message_size; + let capacity = configuration::ActiveConfig::::get().hrmp_channel_max_capacity; + let message_size = configuration::ActiveConfig::::get().hrmp_channel_max_message_size; #[extrinsic_call] _(sender_origin, recipient_id, capacity, message_size); @@ -227,7 +227,7 @@ mod benchmarks { // .. and enact it. Configuration::::initializer_on_new_session(&Shared::::scheduled_session()); - let config = configuration::ActiveConfig::::get(); + let config = configuration::ActiveConfig::::get(); let deposit: BalanceOf = config.hrmp_sender_deposit.unique_saturated_into(); let para: ParaId = 1u32.into(); @@ -359,7 +359,7 @@ mod benchmarks { assert_eq!(HrmpOpenChannelRequestsList::::decode_len().unwrap_or_default() as u32, c); let outgoing = (0..c).map(|id| (id + PREFIX_1).into()).collect::>(); - let config = configuration::ActiveConfig::::get(); + let config = configuration::ActiveConfig::::get(); #[block] { @@ -382,14 +382,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 = configuration::ActiveConfig::::get() + let sender_deposit: BalanceOf = configuration::ActiveConfig::::get() .hrmp_sender_deposit .unique_saturated_into(); register_parachain_with_balance::(sender_id, sender_deposit + ed); register_parachain_with_balance::(recipient_id, Zero::zero()); - let capacity = configuration::ActiveConfig::::get().hrmp_channel_max_capacity; - let message_size = configuration::ActiveConfig::::get().hrmp_channel_max_message_size; + let capacity = configuration::ActiveConfig::::get().hrmp_channel_max_capacity; + let message_size = configuration::ActiveConfig::::get().hrmp_channel_max_message_size; let channel_id = HrmpChannelId { sender: sender_id, recipient: recipient_id }; if c == 1 { @@ -436,7 +436,7 @@ mod benchmarks { let recipient_id: ParaId = 2u32.into(); let caller: T::AccountId = whitelisted_caller(); - let config = configuration::ActiveConfig::::get(); + let config = configuration::ActiveConfig::::get(); // make sure para is registered, and has zero balance. register_parachain_with_balance::(sender_id, Zero::zero()); @@ -466,7 +466,7 @@ mod benchmarks { let channel_id = HrmpChannelId { sender: sender_id, recipient: recipient_id }; let caller: T::AccountId = whitelisted_caller(); - let config = configuration::ActiveConfig::::get(); + let config = configuration::ActiveConfig::::get(); // make sure para is registered, and has balance to reserve. let ed = T::Currency::minimum_balance(); From 8b481a6850c60d84859925077b9b178c227f33f6 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Wed, 13 Mar 2024 09:14:14 +0100 Subject: [PATCH 10/16] silent removal of turbofish syntax Signed-off-by: Matteo Muraca --- .../runtime/common/src/assigned_slots/mod.rs | 10 +- polkadot/runtime/common/src/claims.rs | 30 ++-- .../runtime/parachains/src/disputes/tests.rs | 4 +- .../runtime/parachains/src/inclusion/tests.rs | 128 +++++++++--------- .../runtime/parachains/src/paras/tests.rs | 2 +- .../parachains/src/paras_inherent/tests.rs | 18 +-- polkadot/runtime/parachains/src/scheduler.rs | 4 +- 7 files changed, 98 insertions(+), 98 deletions(-) diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index 0f2440d058f3..318c0ba3da8f 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -301,7 +301,7 @@ pub mod pallet { LeasePeriodOf::::from(T::PermanentSlotLeasePeriodLength::get()), ), ); - >::mutate(|count| count.saturating_inc()); + PermanentSlotCount::::mutate(|count| count.saturating_inc()); Self::deposit_event(Event::::PermanentSlotAssigned(id)); Ok(()) @@ -389,7 +389,7 @@ pub mod pallet { } TemporarySlots::::insert(id, temp_slot); - >::mutate(|count| count.saturating_inc()); + TemporarySlotCount::::mutate(|count| count.saturating_inc()); Self::deposit_event(Event::::TemporarySlotAssigned(id)); @@ -415,12 +415,12 @@ pub mod pallet { if PermanentSlots::::contains_key(id) { PermanentSlots::::remove(id); - >::mutate(|count| *count = count.saturating_sub(One::one())); + PermanentSlotCount::::mutate(|count| *count = count.saturating_sub(One::one())); } else if TemporarySlots::::contains_key(id) { TemporarySlots::::remove(id); - >::mutate(|count| *count = count.saturating_sub(One::one())); + TemporarySlotCount::::mutate(|count| *count = count.saturating_sub(One::one())); if is_parachain { - >::mutate(|active_count| { + ActiveTemporarySlotCount::::mutate(|active_count| { *active_count = active_count.saturating_sub(One::one()) }); } diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index fa5775a2b87a..6e7255749cc4 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -359,10 +359,10 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; - >::mutate(|t| *t += value); - >::insert(who, value); + Total::::mutate(|t| *t += value); + Claims::::insert(who, value); if let Some(vs) = vesting_schedule { - >::insert(who, vs); + Vesting::::insert(who, vs); } if let Some(s) = statement { Signing::::insert(who, s); @@ -510,7 +510,7 @@ pub mod pallet { ))?; let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()); - ensure!(>::contains_key(&signer), e); + ensure!(Claims::::contains_key(&signer), e); let e = InvalidTransaction::Custom(ValidityError::InvalidStatement.into()); match Signing::::get(signer) { @@ -590,9 +590,9 @@ impl Pallet { .expect("No other vesting schedule exists, as checked above; qed"); } - >::put(new_total); - >::remove(&signer); - >::remove(&signer); + Total::::put(new_total); + Claims::::remove(&signer); + Vesting::::remove(&signer); Signing::::remove(&signer); // Let's deposit an event to let the outside world know this happened. @@ -1383,7 +1383,7 @@ pub(super) mod tests { new_test_ext().execute_with(|| { assert_eq!( - >::validate_unsigned( + Pallet::::validate_unsigned( source, &ClaimsCall::claim { dest: 1, @@ -1399,14 +1399,14 @@ pub(super) mod tests { }) ); assert_eq!( - >::validate_unsigned( + Pallet::::validate_unsigned( source, &ClaimsCall::claim { dest: 0, ethereum_signature: EcdsaSignature([0; 65]) } ), InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()).into(), ); assert_eq!( - >::validate_unsigned( + Pallet::::validate_unsigned( source, &ClaimsCall::claim { dest: 1, @@ -1422,7 +1422,7 @@ pub(super) mod tests { statement: StatementKind::Regular.to_text().to_vec(), }; assert_eq!( - >::validate_unsigned(source, &call), + Pallet::::validate_unsigned(source, &call), Ok(ValidTransaction { priority: 100, requires: vec![], @@ -1432,7 +1432,7 @@ pub(super) mod tests { }) ); assert_eq!( - >::validate_unsigned( + Pallet::::validate_unsigned( source, &ClaimsCall::claim_attest { dest: 1, @@ -1450,7 +1450,7 @@ pub(super) mod tests { statement: StatementKind::Regular.to_text().to_vec(), }; assert_eq!( - >::validate_unsigned(source, &call), + Pallet::::validate_unsigned(source, &call), InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), ); @@ -1461,7 +1461,7 @@ pub(super) mod tests { statement: StatementKind::Regular.to_text().to_vec(), }; assert_eq!( - >::validate_unsigned(source, &call), + Pallet::::validate_unsigned(source, &call), InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()).into(), ); @@ -1472,7 +1472,7 @@ pub(super) mod tests { statement: StatementKind::Saft.to_text().to_vec(), }; assert_eq!( - >::validate_unsigned(source, &call), + Pallet::::validate_unsigned(source, &call), InvalidTransaction::Custom(ValidityError::InvalidStatement.into()).into(), ); }); diff --git a/polkadot/runtime/parachains/src/disputes/tests.rs b/polkadot/runtime/parachains/src/disputes/tests.rs index bea640f8a5da..16b4fa3a9f1a 100644 --- a/polkadot/runtime/parachains/src/disputes/tests.rs +++ b/polkadot/runtime/parachains/src/disputes/tests.rs @@ -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)); - >::insert( + Disputes::::insert( &1, &candidate_hash_a, DisputeState { @@ -2214,7 +2214,7 @@ fn filter_removes_concluded_ancient() { }, ); - >::insert( + Disputes::::insert( &1, &candidate_hash_b, DisputeState { diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index 644cabbeaf44..0649a54de93f 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -323,7 +323,7 @@ impl TestCandidateBuilder { } pub(crate) fn make_vdata_hash(para_id: ParaId) -> Option { - let relay_parent_number = >::block_number() - 1; + let relay_parent_number = frame_system::Pallet::::block_number() - 1; make_vdata_hash_with_block_number(para_id, relay_parent_number) } @@ -389,7 +389,7 @@ fn collect_pending_cleans_up_pending() { config.configuration.config.scheduler_params.group_rotation_frequency = 3; new_test_ext(config).execute_with(|| { let default_candidate = TestCandidateBuilder::default().build(); - >::insert( + PendingAvailability::::insert( chain_a, CandidatePendingAvailability { core: CoreIndex::from(0), @@ -407,7 +407,7 @@ fn collect_pending_cleans_up_pending() { default_candidate.commitments.clone(), ); - >::insert( + PendingAvailability::::insert( &chain_b, CandidatePendingAvailability { core: CoreIndex::from(1), @@ -424,17 +424,17 @@ fn collect_pending_cleans_up_pending() { run_to_block(5, |_| None); - assert!(>::get(&chain_a).is_some()); - assert!(>::get(&chain_b).is_some()); - assert!(>::get(&chain_a).is_some()); - assert!(>::get(&chain_b).is_some()); + assert!(PendingAvailability::::get(&chain_a).is_some()); + assert!(PendingAvailability::::get(&chain_b).is_some()); + assert!(PendingAvailabilityCommitments::::get(&chain_a).is_some()); + assert!(PendingAvailabilityCommitments::::get(&chain_b).is_some()); ParaInclusion::collect_pending(Scheduler::availability_timeout_predicate()); - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_b).is_some()); - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_b).is_some()); + assert!(PendingAvailability::::get(&chain_a).is_none()); + assert!(PendingAvailability::::get(&chain_b).is_some()); + assert!(PendingAvailabilityCommitments::::get(&chain_a).is_none()); + assert!(PendingAvailabilityCommitments::::get(&chain_b).is_some()); }); } @@ -582,7 +582,7 @@ fn bitfield_checks() { assert_eq!(core_lookup(CoreIndex::from(0)), Some(chain_a)); let default_candidate = TestCandidateBuilder::default().build(); - >::insert( + PendingAvailability::::insert( chain_a, CandidatePendingAvailability { core: CoreIndex::from(0), @@ -616,7 +616,7 @@ fn bitfield_checks() { let x = process_bitfields(expected_bits(), checked_bitfields, core_lookup); assert!(x.is_empty(), "No core should be freed."); - >::remove(chain_a); + PendingAvailability::::remove(chain_a); PendingAvailabilityCommitments::::remove(chain_a); } @@ -627,7 +627,7 @@ fn bitfield_checks() { assert_eq!(core_lookup(CoreIndex::from(0)), Some(chain_a)); let default_candidate = TestCandidateBuilder::default().build(); - >::insert( + PendingAvailability::::insert( chain_a, CandidatePendingAvailability { core: CoreIndex::from(0), @@ -721,7 +721,7 @@ fn supermajority_bitfields_trigger_availability() { } .build(); - >::insert( + PendingAvailability::::insert( chain_a, CandidatePendingAvailability { core: CoreIndex::from(0), @@ -743,7 +743,7 @@ fn supermajority_bitfields_trigger_availability() { } .build(); - >::insert( + PendingAvailability::::insert( chain_b, CandidatePendingAvailability { core: CoreIndex::from(1), @@ -820,10 +820,10 @@ fn supermajority_bitfields_trigger_availability() { // chain A had 4 signing off, which is >= threshold. // chain B has 3 signing off, which is < threshold. - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_b).is_some()); - assert_eq!(>::get(&chain_b).unwrap().availability_votes, { + assert!(PendingAvailability::::get(&chain_a).is_none()); + assert!(PendingAvailabilityCommitments::::get(&chain_a).is_none()); + assert!(PendingAvailabilityCommitments::::get(&chain_b).is_some()); + assert_eq!(PendingAvailability::::get(&chain_b).unwrap().availability_votes, { // check that votes from first 3 were tracked. let mut votes = default_availability_votes(); @@ -1150,7 +1150,7 @@ fn candidate_checks() { ); let candidate = TestCandidateBuilder::default().build(); - >::insert( + PendingAvailability::::insert( &chain_a, CandidatePendingAvailability { core: CoreIndex::from(0), @@ -1163,7 +1163,7 @@ fn candidate_checks() { backing_group: GroupIndex::from(0), }, ); - >::insert(&chain_a, candidate.commitments); + PendingAvailabilityCommitments::::insert(&chain_a, candidate.commitments); assert_noop!( ParaInclusion::process_candidates( @@ -1175,8 +1175,8 @@ fn candidate_checks() { Error::::CandidateScheduledBeforeParaFree ); - >::remove(&chain_a); - >::remove(&chain_a); + PendingAvailability::::remove(&chain_a); + PendingAvailabilityCommitments::::remove(&chain_a); } // messed up commitments storage - do not panic - reject. @@ -1194,7 +1194,7 @@ fn candidate_checks() { collator_sign_candidate(Sr25519Keyring::One, &mut candidate); // this is not supposed to happen - >::insert(&chain_a, candidate.commitments.clone()); + PendingAvailabilityCommitments::::insert(&chain_a, candidate.commitments.clone()); let backed = back_candidate( candidate, @@ -1216,7 +1216,7 @@ fn candidate_checks() { Error::::CandidateScheduledBeforeParaFree ); - >::remove(&chain_a); + PendingAvailabilityCommitments::::remove(&chain_a); } // interfering code upgrade - reject @@ -1605,7 +1605,7 @@ fn backing_works() { backing_bitfield(&(0..num_backers).collect::>()) }; assert_eq!( - >::get(&chain_a), + PendingAvailability::::get(&chain_a), Some(CandidatePendingAvailability { core: CoreIndex::from(0), hash: candidate_a.hash(), @@ -1618,7 +1618,7 @@ fn backing_works() { }) ); assert_eq!( - >::get(&chain_a), + PendingAvailabilityCommitments::::get(&chain_a), Some(candidate_a.commitments), ); @@ -1630,7 +1630,7 @@ fn backing_works() { backing_bitfield(&(0..num_backers).map(|v| v + 2).collect::>()) }; assert_eq!( - >::get(&chain_b), + PendingAvailability::::get(&chain_b), Some(CandidatePendingAvailability { core: CoreIndex::from(1), hash: candidate_b.hash(), @@ -1643,12 +1643,12 @@ fn backing_works() { }) ); assert_eq!( - >::get(&chain_b), + PendingAvailabilityCommitments::::get(&chain_b), Some(candidate_b.commitments), ); assert_eq!( - >::get(&thread_a), + PendingAvailability::::get(&thread_a), Some(CandidatePendingAvailability { core: CoreIndex::from(2), hash: candidate_c.hash(), @@ -1661,7 +1661,7 @@ fn backing_works() { }) ); assert_eq!( - >::get(&thread_a), + PendingAvailabilityCommitments::::get(&thread_a), Some(candidate_c.commitments), ); }); @@ -1880,7 +1880,7 @@ fn backing_works_with_elastic_scaling_mvp() { backing_bitfield(&(0..num_backers).collect::>()) }; assert_eq!( - >::get(&chain_a), + PendingAvailability::::get(&chain_a), Some(CandidatePendingAvailability { core: CoreIndex::from(0), hash: candidate_a.hash(), @@ -1893,13 +1893,13 @@ fn backing_works_with_elastic_scaling_mvp() { }) ); assert_eq!( - >::get(&chain_a), + PendingAvailabilityCommitments::::get(&chain_a), Some(candidate_a.commitments), ); // Only one candidate for b will be recorded on chain. assert_eq!( - >::get(&chain_b), + PendingAvailability::::get(&chain_b), Some(CandidatePendingAvailability { core: CoreIndex::from(2), hash: candidate_b_2.hash(), @@ -1912,7 +1912,7 @@ fn backing_works_with_elastic_scaling_mvp() { }) ); assert_eq!( - >::get(&chain_b), + PendingAvailabilityCommitments::::get(&chain_b), Some(candidate_b_2.commitments), ); }); @@ -2014,7 +2014,7 @@ fn can_include_candidate_with_ok_code_upgrade() { backing_bitfield(&(0..num_backers).collect::>()) }; assert_eq!( - >::get(&chain_a), + PendingAvailability::::get(&chain_a), Some(CandidatePendingAvailability { core: CoreIndex::from(0), hash: candidate_a.hash(), @@ -2027,7 +2027,7 @@ fn can_include_candidate_with_ok_code_upgrade() { }) ); assert_eq!( - >::get(&chain_a), + PendingAvailabilityCommitments::::get(&chain_a), Some(candidate_a.commitments), ); }); @@ -2264,23 +2264,23 @@ fn session_change_wipes() { run_to_block(10, |_| None); - >::insert( + AvailabilityBitfields::::insert( &ValidatorIndex(0), AvailabilityBitfieldRecord { bitfield: default_bitfield(), submitted_at: 9 }, ); - >::insert( + AvailabilityBitfields::::insert( &ValidatorIndex(1), AvailabilityBitfieldRecord { bitfield: default_bitfield(), submitted_at: 9 }, ); - >::insert( + AvailabilityBitfields::::insert( &ValidatorIndex(4), AvailabilityBitfieldRecord { bitfield: default_bitfield(), submitted_at: 9 }, ); let candidate = TestCandidateBuilder::default().build(); - >::insert( + PendingAvailability::::insert( &chain_a, CandidatePendingAvailability { core: CoreIndex::from(0), @@ -2293,9 +2293,9 @@ fn session_change_wipes() { backing_group: GroupIndex::from(0), }, ); - >::insert(&chain_a, candidate.commitments.clone()); + PendingAvailabilityCommitments::::insert(&chain_a, candidate.commitments.clone()); - >::insert( + PendingAvailability::::insert( &chain_b, CandidatePendingAvailability { core: CoreIndex::from(1), @@ -2308,20 +2308,20 @@ fn session_change_wipes() { backing_group: GroupIndex::from(1), }, ); - >::insert(&chain_b, candidate.commitments); + PendingAvailabilityCommitments::::insert(&chain_b, candidate.commitments); run_to_block(11, |_| None); assert_eq!(shared::CurrentSessionIndex::::get(), 5); - assert!(>::get(&ValidatorIndex(0)).is_some()); - assert!(>::get(&ValidatorIndex(1)).is_some()); - assert!(>::get(&ValidatorIndex(4)).is_some()); + assert!(AvailabilityBitfields::::get(&ValidatorIndex(0)).is_some()); + assert!(AvailabilityBitfields::::get(&ValidatorIndex(1)).is_some()); + assert!(AvailabilityBitfields::::get(&ValidatorIndex(4)).is_some()); - assert!(>::get(&chain_a).is_some()); - assert!(>::get(&chain_b).is_some()); - assert!(>::get(&chain_a).is_some()); - assert!(>::get(&chain_b).is_some()); + assert!(PendingAvailability::::get(&chain_a).is_some()); + assert!(PendingAvailability::::get(&chain_b).is_some()); + assert!(PendingAvailabilityCommitments::::get(&chain_a).is_some()); + assert!(PendingAvailabilityCommitments::::get(&chain_b).is_some()); run_to_block(12, |n| match n { 12 => Some(SessionChangeNotification { @@ -2337,18 +2337,18 @@ fn session_change_wipes() { assert_eq!(shared::CurrentSessionIndex::::get(), 6); - assert!(>::get(&ValidatorIndex(0)).is_none()); - assert!(>::get(&ValidatorIndex(1)).is_none()); - assert!(>::get(&ValidatorIndex(4)).is_none()); + assert!(AvailabilityBitfields::::get(&ValidatorIndex(0)).is_none()); + assert!(AvailabilityBitfields::::get(&ValidatorIndex(1)).is_none()); + assert!(AvailabilityBitfields::::get(&ValidatorIndex(4)).is_none()); - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_b).is_none()); - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_b).is_none()); + assert!(PendingAvailability::::get(&chain_a).is_none()); + assert!(PendingAvailability::::get(&chain_b).is_none()); + assert!(PendingAvailabilityCommitments::::get(&chain_a).is_none()); + assert!(PendingAvailabilityCommitments::::get(&chain_b).is_none()); - assert!(>::iter().collect::>().is_empty()); - assert!(>::iter().collect::>().is_empty()); - assert!(>::iter().collect::>().is_empty()); + assert!(AvailabilityBitfields::::iter().collect::>().is_empty()); + assert!(PendingAvailability::::iter().collect::>().is_empty()); + assert!(PendingAvailabilityCommitments::::iter().collect::>().is_empty()); }); } @@ -2491,8 +2491,8 @@ fn para_upgrade_delay_scheduled_from_inclusion() { let v = process_bitfields(expected_bits(), checked_bitfields, core_lookup); assert_eq!(vec![(CoreIndex(0), candidate_a.hash())], v); - assert!(>::get(&chain_a).is_none()); - assert!(>::get(&chain_a).is_none()); + assert!(PendingAvailability::::get(&chain_a).is_none()); + assert!(PendingAvailabilityCommitments::::get(&chain_a).is_none()); let active_vote_state = paras::Pallet::::active_vote_state(&new_validation_code_hash) .expect("prechecking must be initiated"); diff --git a/polkadot/runtime/parachains/src/paras/tests.rs b/polkadot/runtime/parachains/src/paras/tests.rs index d4ce2f5db64a..adae9bfd9ecd 100644 --- a/polkadot/runtime/parachains/src/paras/tests.rs +++ b/polkadot/runtime/parachains/src/paras/tests.rs @@ -970,7 +970,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!(>::block_number(), 7); + assert_eq!(frame_system::Pallet::::block_number(), 7); Paras::note_new_head(para_id, Default::default(), expected_at); assert_ok!(Paras::schedule_para_cleanup(para_id)); diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index 9c211e46d061..e7da3fb7522e 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -125,7 +125,7 @@ mod enter { .unwrap(); // The current schedule is empty prior to calling `create_inherent_enter`. - assert!(>::claimqueue_is_empty()); + assert!(scheduler::Pallet::::claimqueue_is_empty()); // Nothing is filtered out (including the backed candidates.) assert_eq!( @@ -273,7 +273,7 @@ mod enter { .unwrap(); // The current schedule is empty prior to calling `create_inherent_enter`. - assert!(>::claimqueue_is_empty()); + assert!(scheduler::Pallet::::claimqueue_is_empty()); let multi_dispute_inherent_data = Pallet::::create_inherent_inner(&inherent_data.clone()).unwrap(); @@ -343,7 +343,7 @@ mod enter { .unwrap(); // The current schedule is empty prior to calling `create_inherent_enter`. - assert!(>::claimqueue_is_empty()); + assert!(scheduler::Pallet::::claimqueue_is_empty()); let limit_inherent_data = Pallet::::create_inherent_inner(&inherent_data.clone()).unwrap(); @@ -413,7 +413,7 @@ mod enter { .unwrap(); // The current schedule is empty prior to calling `create_inherent_enter`. - assert!(>::claimqueue_is_empty()); + assert!(scheduler::Pallet::::claimqueue_is_empty()); // Nothing is filtered out (including the backed candidates.) let limit_inherent_data = @@ -498,7 +498,7 @@ mod enter { .unwrap(); // The current schedule is empty prior to calling `create_inherent_enter`. - assert!(>::claimqueue_is_empty()); + assert!(scheduler::Pallet::::claimqueue_is_empty()); // Nothing is filtered out (including the backed candidates.) let limit_inherent_data = @@ -702,7 +702,7 @@ mod enter { ); // One core was scheduled. We should put the assignment back, before calling enter(). - let now = >::block_number() + 1; + let now = frame_system::Pallet::::block_number() + 1; let used_cores = 5; let cores = (0..used_cores) .into_iter() @@ -1509,7 +1509,7 @@ mod sanitizers { // State sanity checks assert_eq!( - >::scheduled_paras().collect::>(), + scheduler::Pallet::::scheduled_paras().collect::>(), vec![(CoreIndex(0), ParaId::from(1)), (CoreIndex(1), ParaId::from(2))] ); assert_eq!( @@ -1844,7 +1844,7 @@ mod sanitizers { // State sanity checks assert_eq!( - >::scheduled_paras().collect::>(), + scheduler::Pallet::::scheduled_paras().collect::>(), vec![ (CoreIndex(0), ParaId::from(1)), (CoreIndex(1), ParaId::from(1)), @@ -1856,7 +1856,7 @@ mod sanitizers { ] ); let mut scheduled: BTreeMap> = BTreeMap::new(); - for (core_idx, para_id) in >::scheduled_paras() { + for (core_idx, para_id) in scheduler::Pallet::::scheduled_paras() { scheduled.entry(para_id).or_default().insert(core_idx); } diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index 5d0711e2bf49..5506685cc515 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -269,7 +269,7 @@ impl Pallet { } let now = >::block_number() + One::one(); - >::set(now); + SessionStartBlock::::set(now); } /// Free unassigned cores. Provide a list of cores that should be considered newly-freed along @@ -416,7 +416,7 @@ impl Pallet { at: BlockNumberFor, ) -> Option { let config = configuration::ActiveConfig::::get(); - let session_start_block = >::get(); + let session_start_block = SessionStartBlock::::get(); if at < session_start_block { return None From 5feb9c2625e55ee91eb7b4183d63d4a689117afd Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 19 Mar 2024 08:19:05 +0100 Subject: [PATCH 11/16] review comments, clippy Signed-off-by: Matteo Muraca --- .../src/runtime/disputes.md | 3 -- polkadot/runtime/parachains/src/builder.rs | 6 +-- polkadot/runtime/parachains/src/disputes.rs | 46 ++++++++----------- 3 files changed, 22 insertions(+), 33 deletions(-) diff --git a/polkadot/roadmap/implementers-guide/src/runtime/disputes.md b/polkadot/roadmap/implementers-guide/src/runtime/disputes.md index 688ff7f1b330..f2b83aecb648 100644 --- a/polkadot/roadmap/implementers-guide/src/runtime/disputes.md +++ b/polkadot/roadmap/implementers-guide/src/runtime/disputes.md @@ -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. diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index 4ada45c68ded..a4c6c1dfb7f6 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -639,7 +639,7 @@ impl BenchBuilder { // 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::::config() + let core_idx = configuration::ActiveConfig::::get() .node_features .get(FeatureIndex::ElasticScalingMVP as usize) .map(|_the_bit| core_idx); @@ -806,7 +806,7 @@ impl BenchBuilder { .flat_map(|(para_id, _)| { (0..elastic_paras.get(¶_id).cloned().unwrap_or(1)) .map(|_para_local_core_idx| { - let ttl = configuration::Pallet::::config().scheduler_params.ttl; + let ttl = configuration::ActiveConfig::::get().scheduler_params.ttl; // Load an assignment into provider so that one is present to pop let assignment = ::AssignmentProvider::get_mock_assignment( @@ -829,7 +829,7 @@ impl BenchBuilder { .flat_map(|para_id| { (0..elastic_paras.get(¶_id).cloned().unwrap_or(1)) .map(|_para_local_core_idx| { - let ttl = configuration::Pallet::::config().scheduler_params.ttl; + let ttl = configuration::ActiveConfig::::get().scheduler_params.ttl; // Load an assignment into provider so that one is present to pop let assignment = ::AssignmentProvider::get_mock_assignment( diff --git a/polkadot/runtime/parachains/src/disputes.rs b/polkadot/runtime/parachains/src/disputes.rs index b933ef707950..78b91912c172 100644 --- a/polkadot/runtime/parachains/src/disputes.rs +++ b/polkadot/runtime/parachains/src/disputes.rs @@ -432,7 +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] - pub(super) type Frozen = StorageValue<_, Option>, ValueQuery>; + pub type Frozen = StorageValue<_, Option>, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub fn deposit_event)] @@ -852,14 +852,6 @@ impl StatementSetFilter { } impl Pallet { - /// Whether the chain is frozen. Starts as `None`. When this is `Some`, - /// the chain will not accept any new parachain blocks for backing or inclusion, - /// and its value indicates the last valid block number in the chain. - /// It can only be set back to `None` by governance intervention. - pub fn last_valid_block() -> Option> { - Frozen::::get() - } - /// Called by the initializer to initialize the disputes module. pub(crate) fn initializer_initialize(_now: BlockNumberFor) -> Weight { Weight::zero() @@ -890,14 +882,14 @@ impl Pallet { for to_prune in to_prune { // This should be small, as disputes are rare, so `None` is fine. #[allow(deprecated)] - >::remove_prefix(to_prune, None); + Disputes::::remove_prefix(to_prune, None); #[allow(deprecated)] - >::remove_prefix(to_prune, None); + BackersOnDisputes::::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)] - >::remove_prefix(to_prune, None); + Included::::remove_prefix(to_prune, None); } *last_pruned = Some(pruning_target); @@ -965,7 +957,7 @@ impl Pallet { // Check for ancient. let dispute_state = { - if let Some(dispute_state) = >::get(&set.session, &set.candidate_hash) { + if let Some(dispute_state) = Disputes::::get(&set.session, &set.candidate_hash) { if dispute_state.concluded_at.as_ref().map_or(false, |c| c < &oldest_accepted) { return StatementSetFilter::RemoveAll } @@ -983,7 +975,7 @@ impl Pallet { }; let backers = - >::get(&set.session, &set.candidate_hash).unwrap_or_default(); + BackersOnDisputes::::get(&set.session, &set.candidate_hash).unwrap_or_default(); // Check and import all votes. let summary = { @@ -1083,7 +1075,7 @@ impl Pallet { // Check for ancient. let (fresh, dispute_state) = { - if let Some(dispute_state) = >::get(&set.session, &set.candidate_hash) { + if let Some(dispute_state) = Disputes::::get(&set.session, &set.candidate_hash) { ensure!( dispute_state.concluded_at.as_ref().map_or(true, |c| c >= &oldest_accepted), Error::::AncientDisputeStatement, @@ -1104,7 +1096,7 @@ impl Pallet { }; let backers = - >::get(&set.session, &set.candidate_hash).unwrap_or_default(); + BackersOnDisputes::::get(&set.session, &set.candidate_hash).unwrap_or_default(); // Import all votes. They were pre-checked. let summary = { @@ -1134,7 +1126,7 @@ impl Pallet { let backers = summary.backers; // Reject statements with no accompanying backing votes. ensure!(!backers.is_empty(), Error::::MissingBackingVotes); - >::insert(&set.session, &set.candidate_hash, backers.clone()); + BackersOnDisputes::::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; @@ -1142,7 +1134,7 @@ impl Pallet { let candidate_hash = *candidate_hash; if fresh { - let is_local = >::contains_key(&session, &candidate_hash); + let is_local = Included::::contains_key(&session, &candidate_hash); Self::deposit_event(Event::DisputeInitiated( candidate_hash, @@ -1192,12 +1184,12 @@ impl Pallet { ); } - >::insert(&session, &candidate_hash, &summary.state); + Disputes::::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) = >::get(&session, &candidate_hash) { + if let Some(revert_to) = Included::::get(&session, &candidate_hash) { Self::revert_and_freeze(revert_to); } } @@ -1208,7 +1200,7 @@ impl Pallet { #[allow(unused)] pub(crate) fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState>)> { - >::iter().collect() + Disputes::::iter().collect() } pub(crate) fn note_included( @@ -1222,9 +1214,9 @@ impl Pallet { let revert_to = included_in - One::one(); - >::insert(&session, &candidate_hash, revert_to); + Included::::insert(&session, &candidate_hash, revert_to); - if let Some(state) = >::get(&session, candidate_hash) { + if let Some(state) = Disputes::::get(&session, candidate_hash) { if has_supermajority_against(&state) { Self::revert_and_freeze(revert_to); } @@ -1235,22 +1227,22 @@ impl Pallet { session: SessionIndex, candidate_hash: CandidateHash, ) -> Option> { - >::get(session, candidate_hash) + Included::::get(session, candidate_hash) } pub(crate) fn concluded_invalid(session: SessionIndex, candidate_hash: CandidateHash) -> bool { - >::get(&session, &candidate_hash).map_or(false, |dispute| { + Disputes::::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::::get().is_some() } pub(crate) fn revert_and_freeze(revert_to: BlockNumberFor) { - if Self::last_valid_block().map_or(true, |last| last > revert_to) { + if Frozen::::get().map_or(true, |last| last > revert_to) { Frozen::::set(Some(revert_to)); // The `Revert` log is about reverting a block, not reverting to a block. From b1e2b7a890b0987af5c6d7e389d7a8643be9e892 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Tue, 19 Mar 2024 08:28:24 +0100 Subject: [PATCH 12/16] more clippy fixes Signed-off-by: Matteo Muraca --- polkadot/runtime/common/src/crowdloan/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/runtime/common/src/crowdloan/mod.rs b/polkadot/runtime/common/src/crowdloan/mod.rs index 7576c7a4fc6c..01ad752518e5 100644 --- a/polkadot/runtime/common/src/crowdloan/mod.rs +++ b/polkadot/runtime/common/src/crowdloan/mod.rs @@ -1758,7 +1758,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::::get(para).unwrap(); let pot = Crowdloan::fund_account_id(fund.fund_index); System::dec_providers(&pot).unwrap(); assert_eq!(System::providers(&pot), 1); From 2de93b07b1c56a51aa02aabde8b62eceba60e709 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Sun, 24 Mar 2024 12:13:57 +0100 Subject: [PATCH 13/16] fmt --- polkadot/runtime/parachains/src/paras_inherent/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index 312aa2c7b139..0746e959b388 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -3142,7 +3142,7 @@ mod sanitizers { Vec<(BackedCandidate<_>, CoreIndex)>, > = sanitize_backed_candidates::( backed_candidates.clone(), - &shared::AllowedRelayParents::::get(),, + &shared::AllowedRelayParents::::get(), invalid_set, scheduled, true, @@ -3178,7 +3178,7 @@ mod sanitizers { Vec<(BackedCandidate<_>, CoreIndex)>, > = sanitize_backed_candidates::( backed_candidates.clone(), - &shared::AllowedRelayParents::::get(),, + &shared::AllowedRelayParents::::get(), invalid_set, scheduled, true, From 98c072ee095cbef5fb4754a303586e0b7526e6c4 Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Sun, 24 Mar 2024 21:46:24 +0100 Subject: [PATCH 14/16] fixed clippy issues Signed-off-by: Matteo Muraca --- .../runtime/parachains/src/inclusion/mod.rs | 6 ++-- .../runtime/parachains/src/inclusion/tests.rs | 12 ++++---- .../parachains/src/paras_inherent/mod.rs | 2 +- .../parachains/src/paras_inherent/tests.rs | 29 ++++++++++--------- 4 files changed, 26 insertions(+), 23 deletions(-) diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index 45a71d833d91..1998cf969095 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -700,7 +700,7 @@ impl Pallet { pending_candidates.back().map(|x| x.commitments.head_data.clone()) }) { Some(head_data) => Some(head_data), - None => paras::Pallet::::para_head(para_id), + None => paras::Heads::::get(para_id), } } @@ -710,12 +710,12 @@ impl Pallet { group_vals: Vec, core_index_enabled: bool, ) -> Result<(BitVec, Vec<(ValidatorIndex, ValidityAttestation)>), Error> { - let minimum_backing_votes = configuration::Pallet::::config().minimum_backing_votes; + let minimum_backing_votes = configuration::ActiveConfig::::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::::session_index(), + session_index: shared::CurrentSessionIndex::::get(), }; let (validator_indices, _) = diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index b9bb66be8474..a5097f98e013 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -1063,9 +1063,9 @@ fn supermajority_bitfields_trigger_availability() { 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::Head::::get(&chain_a), Some(vec![1, 2, 3, 4].into())); + assert_ne!(paras::Head::::get(&chain_b), Some(vec![5, 6, 7, 8].into())); + assert_eq!(paras::Head::::get(&chain_c), Some(vec![7, 8].into())); // Check that rewards are applied. { @@ -1129,9 +1129,9 @@ fn supermajority_bitfields_trigger_availability() { assert!(PendingAvailability::::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::Head::::get(&chain_a), Some(vec![1, 2, 3, 4].into())); + assert_ne!(paras::Head::::get(&chain_b), Some(vec![5, 6, 7, 8].into())); + assert_eq!(paras::Head::::get(&chain_c), Some(vec![11, 12].into())); // Check that rewards are applied. { diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index eb6ee5e47157..5d841f2db090 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -1276,7 +1276,7 @@ fn filter_unchained_candidates::para_most_recent_context(para_id); + let prev_context = paras::MostRecentContext::::get(para_id); let check_ctx = CandidateCheckContext::::new(prev_context); let res = match check_ctx.verify_backed_candidate( diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index 0746e959b388..a4e1e40c9087 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -259,7 +259,7 @@ mod enter { // The current schedule is empty prior to calling `create_inherent_enter`. assert!(scheduler::Pallet::::claimqueue_is_empty()); - assert!(Pallet::::on_chain_votes().is_none()); + assert!(pallet::OnChainVotes::::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::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + pallet::OnChainVotes::::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::::on_chain_votes().unwrap().session, + pallet::OnChainVotes::::get().unwrap().session, 2 ); @@ -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::::on_chain_votes().is_none()); + assert!(pallet::OnChainVotes::::get().is_none()); expected_para_inherent_data.backed_candidates = expected_para_inherent_data .backed_candidates @@ -379,13 +382,16 @@ mod enter { // 3 candidates have been backed (for cores 1,2 and 3) assert_eq!( - Pallet::::on_chain_votes().unwrap().backing_validators_per_candidate.len(), + pallet::OnChainVotes::::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::::on_chain_votes().unwrap().session, + pallet::OnChainVotes::::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::::session_info(2).unwrap().validators; + let validators = session_info::Sessions::::get(2).unwrap().validators; let signing_context = SigningContext { parent_hash: BenchBuilder::::header(4).hash(), session_index: 2, @@ -447,7 +453,7 @@ mod enter { ); // No more candidates have been backed - assert!(Pallet::::on_chain_votes() + assert!(pallet::OnChainVotes::::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::::para_head(ParaId::from(id as u32)).unwrap(), - head - ); + assert_eq!(paras::Head::::get(ParaId::from(id as u32)).unwrap(), head); }); }); } @@ -2956,7 +2959,7 @@ mod sanitizers { } assert_eq!( - shared::Pallet::::active_validator_indices(), + shared::ActiveValidatorIndices::::get(), vec![ ValidatorIndex(0), ValidatorIndex(1), From 713240c4ef136d7de3712ec38d1054271fbadae0 Mon Sep 17 00:00:00 2001 From: ordian Date: Thu, 4 Apr 2024 12:55:55 +0200 Subject: [PATCH 15/16] Update prdoc/pr_3660.prdoc --- prdoc/pr_3660.prdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prdoc/pr_3660.prdoc b/prdoc/pr_3660.prdoc index 0104713ad6b1..26245e5e795c 100644 --- a/prdoc/pr_3660.prdoc +++ b/prdoc/pr_3660.prdoc @@ -6,7 +6,7 @@ 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 depdendant runtimes accordingly. + This PR removes all the `pallet::getter` usages from the Polkadot Runtime pallets, and updates dependant runtimes accordingly. The syntax `StorageItem::::get()` should be used instead. crates: From 217a6da1c13cc98b2ff932a9bd5f4dae9444a3de Mon Sep 17 00:00:00 2001 From: Matteo Muraca Date: Sat, 6 Apr 2024 14:42:26 +0200 Subject: [PATCH 16/16] fixed copy-paste mistake Signed-off-by: Matteo Muraca --- polkadot/runtime/common/src/assigned_slots/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index a15e57fca3f6..9b24b99cfbe2 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -192,7 +192,7 @@ pub mod pallet { #[pallet::genesis_build] impl BuildGenesisConfig for GenesisConfig { fn build(&self) { - MaxTemporarySlots::::put(&self.max_permanent_slots); + MaxPermanentSlots::::put(&self.max_permanent_slots); MaxTemporarySlots::::put(&self.max_temporary_slots); } } @@ -451,7 +451,7 @@ pub mod pallet { pub fn set_max_permanent_slots(origin: OriginFor, slots: u32) -> DispatchResult { ensure_root(origin)?; - MaxTemporarySlots::::put(slots); + MaxPermanentSlots::::put(slots); Self::deposit_event(Event::::MaxPermanentSlotsChanged { slots }); Ok(())