Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit b6c1c1b

Browse files
gui1117apopiak
andauthored
Fix order of hook execution (#10043)
* fix order * Update frame/support/procedural/src/construct_runtime/mod.rs Co-authored-by: Alexander Popiak <alexander.popiak@parity.io> * format * more accurate description * format * better explicit types * fix tests * address feedback * add a type to ease non breaking implementation * add comment about constraint * fix test * add test for generated types Co-authored-by: Alexander Popiak <alexander.popiak@parity.io>
1 parent 4bef50f commit b6c1c1b

File tree

6 files changed

+231
-89
lines changed

6 files changed

+231
-89
lines changed

bin/node-template/runtime/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ pub type Executive = frame_executive::Executive<
323323
Block,
324324
frame_system::ChainContext<Runtime>,
325325
Runtime,
326-
AllPallets,
326+
AllPalletsWithSystem,
327327
>;
328328

329329
impl_runtime_apis! {

bin/node/runtime/src/lib.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1268,6 +1268,8 @@ construct_runtime!(
12681268
Utility: pallet_utility,
12691269
Babe: pallet_babe,
12701270
Timestamp: pallet_timestamp,
1271+
// Authorship must be before session in order to note author in the correct session and era
1272+
// for im-online and staking.
12711273
Authorship: pallet_authorship,
12721274
Indices: pallet_indices,
12731275
Balances: pallet_balances,
@@ -1345,7 +1347,7 @@ pub type Executive = frame_executive::Executive<
13451347
Block,
13461348
frame_system::ChainContext<Runtime>,
13471349
Runtime,
1348-
AllPallets,
1350+
AllPalletsWithSystem,
13491351
pallet_bags_list::migrations::CheckCounterPrefix<Runtime>,
13501352
>;
13511353

frame/executive/src/lib.rs

Lines changed: 44 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@
5959
//! # type Context = frame_system::ChainContext<Runtime>;
6060
//! # pub type Block = generic::Block<Header, UncheckedExtrinsic>;
6161
//! # pub type Balances = u64;
62-
//! # pub type AllPallets = u64;
62+
//! # pub type AllPalletsWithSystem = u64;
6363
//! # pub enum Runtime {};
6464
//! # use sp_runtime::transaction_validity::{
6565
//! # TransactionValidity, UnknownTransaction, TransactionSource,
@@ -73,7 +73,7 @@
7373
//! # }
7474
//! # }
7575
//! /// Executive: handles dispatch to the various modules.
76-
//! pub type Executive = executive::Executive<Runtime, Block, Context, Runtime, AllPallets>;
76+
//! pub type Executive = executive::Executive<Runtime, Block, Context, Runtime, AllPalletsWithSystem>;
7777
//! ```
7878
//!
7979
//! ### Custom `OnRuntimeUpgrade` logic
@@ -90,7 +90,7 @@
9090
//! # type Context = frame_system::ChainContext<Runtime>;
9191
//! # pub type Block = generic::Block<Header, UncheckedExtrinsic>;
9292
//! # pub type Balances = u64;
93-
//! # pub type AllPallets = u64;
93+
//! # pub type AllPalletsWithSystem = u64;
9494
//! # pub enum Runtime {};
9595
//! # use sp_runtime::transaction_validity::{
9696
//! # TransactionValidity, UnknownTransaction, TransactionSource,
@@ -111,7 +111,7 @@
111111
//! }
112112
//! }
113113
//!
114-
//! pub type Executive = executive::Executive<Runtime, Block, Context, Runtime, AllPallets, CustomOnRuntimeUpgrade>;
114+
//! pub type Executive = executive::Executive<Runtime, Block, Context, Runtime, AllPalletsWithSystem, CustomOnRuntimeUpgrade>;
115115
//! ```
116116
117117
#![cfg_attr(not(feature = "std"), no_std)]
@@ -147,26 +147,41 @@ pub type OriginOf<E, C> = <CallOf<E, C> as Dispatchable>::Origin;
147147
/// - `Block`: The block type of the runtime
148148
/// - `Context`: The context that is used when checking an extrinsic.
149149
/// - `UnsignedValidator`: The unsigned transaction validator of the runtime.
150-
/// - `AllPallets`: Tuple that contains all modules. Will be used to call e.g. `on_initialize`.
150+
/// - `AllPalletsWithSystem`: Tuple that contains all pallets including frame system pallet. Will be
151+
/// used to call hooks e.g. `on_initialize`.
151152
/// - `OnRuntimeUpgrade`: Custom logic that should be called after a runtime upgrade. Modules are
152-
/// already called by `AllPallets`. It will be called before all modules will be called.
153-
pub struct Executive<System, Block, Context, UnsignedValidator, AllPallets, OnRuntimeUpgrade = ()>(
154-
PhantomData<(System, Block, Context, UnsignedValidator, AllPallets, OnRuntimeUpgrade)>,
153+
/// already called by `AllPalletsWithSystem`. It will be called before all modules will be called.
154+
pub struct Executive<
155+
System,
156+
Block,
157+
Context,
158+
UnsignedValidator,
159+
AllPalletsWithSystem,
160+
OnRuntimeUpgrade = (),
161+
>(
162+
PhantomData<(
163+
System,
164+
Block,
165+
Context,
166+
UnsignedValidator,
167+
AllPalletsWithSystem,
168+
OnRuntimeUpgrade,
169+
)>,
155170
);
156171

157172
impl<
158173
System: frame_system::Config + EnsureInherentsAreFirst<Block>,
159174
Block: traits::Block<Header = System::Header, Hash = System::Hash>,
160175
Context: Default,
161176
UnsignedValidator,
162-
AllPallets: OnRuntimeUpgrade
177+
AllPalletsWithSystem: OnRuntimeUpgrade
163178
+ OnInitialize<System::BlockNumber>
164179
+ OnIdle<System::BlockNumber>
165180
+ OnFinalize<System::BlockNumber>
166181
+ OffchainWorker<System::BlockNumber>,
167182
COnRuntimeUpgrade: OnRuntimeUpgrade,
168183
> ExecuteBlock<Block>
169-
for Executive<System, Block, Context, UnsignedValidator, AllPallets, COnRuntimeUpgrade>
184+
for Executive<System, Block, Context, UnsignedValidator, AllPalletsWithSystem, COnRuntimeUpgrade>
170185
where
171186
Block::Extrinsic: Checkable<Context> + Codec,
172187
CheckedOf<Block::Extrinsic, Context>: Applyable + GetDispatchInfo,
@@ -181,7 +196,7 @@ where
181196
Block,
182197
Context,
183198
UnsignedValidator,
184-
AllPallets,
199+
AllPalletsWithSystem,
185200
COnRuntimeUpgrade,
186201
>::execute_block(block);
187202
}
@@ -192,13 +207,13 @@ impl<
192207
Block: traits::Block<Header = System::Header, Hash = System::Hash>,
193208
Context: Default,
194209
UnsignedValidator,
195-
AllPallets: OnRuntimeUpgrade
210+
AllPalletsWithSystem: OnRuntimeUpgrade
196211
+ OnInitialize<System::BlockNumber>
197212
+ OnIdle<System::BlockNumber>
198213
+ OnFinalize<System::BlockNumber>
199214
+ OffchainWorker<System::BlockNumber>,
200215
COnRuntimeUpgrade: OnRuntimeUpgrade,
201-
> Executive<System, Block, Context, UnsignedValidator, AllPallets, COnRuntimeUpgrade>
216+
> Executive<System, Block, Context, UnsignedValidator, AllPalletsWithSystem, COnRuntimeUpgrade>
202217
where
203218
Block::Extrinsic: Checkable<Context> + Codec,
204219
CheckedOf<Block::Extrinsic, Context>: Applyable + GetDispatchInfo,
@@ -209,14 +224,7 @@ where
209224
{
210225
/// Execute all `OnRuntimeUpgrade` of this runtime, and return the aggregate weight.
211226
pub fn execute_on_runtime_upgrade() -> frame_support::weights::Weight {
212-
let mut weight = 0;
213-
weight = weight.saturating_add(COnRuntimeUpgrade::on_runtime_upgrade());
214-
weight = weight.saturating_add(
215-
<frame_system::Pallet<System> as OnRuntimeUpgrade>::on_runtime_upgrade(),
216-
);
217-
weight = weight.saturating_add(<AllPallets as OnRuntimeUpgrade>::on_runtime_upgrade());
218-
219-
weight
227+
<(COnRuntimeUpgrade, AllPalletsWithSystem) as OnRuntimeUpgrade>::on_runtime_upgrade()
220228
}
221229

222230
/// Execute given block, but don't do any of the `final_checks`.
@@ -255,19 +263,10 @@ where
255263
/// This should only be used for testing.
256264
#[cfg(feature = "try-runtime")]
257265
pub fn try_runtime_upgrade() -> Result<frame_support::weights::Weight, &'static str> {
258-
<
259-
(frame_system::Pallet::<System>, COnRuntimeUpgrade, AllPallets)
260-
as
261-
OnRuntimeUpgrade
262-
>::pre_upgrade().unwrap();
263-
266+
<(COnRuntimeUpgrade, AllPalletsWithSystem) as OnRuntimeUpgrade>::pre_upgrade().unwrap();
264267
let weight = Self::execute_on_runtime_upgrade();
265268

266-
<
267-
(frame_system::Pallet::<System>, COnRuntimeUpgrade, AllPallets)
268-
as
269-
OnRuntimeUpgrade
270-
>::post_upgrade().unwrap();
269+
<(COnRuntimeUpgrade, AllPalletsWithSystem) as OnRuntimeUpgrade>::post_upgrade().unwrap();
271270

272271
Ok(weight)
273272
}
@@ -305,12 +304,9 @@ where
305304
digest,
306305
frame_system::InitKind::Full,
307306
);
308-
weight = weight.saturating_add(<frame_system::Pallet<System> as OnInitialize<
307+
weight = weight.saturating_add(<AllPalletsWithSystem as OnInitialize<
309308
System::BlockNumber,
310309
>>::on_initialize(*block_number));
311-
weight = weight.saturating_add(
312-
<AllPallets as OnInitialize<System::BlockNumber>>::on_initialize(*block_number),
313-
);
314310
weight = weight.saturating_add(
315311
<System::BlockWeights as frame_support::traits::Get<_>>::get().base_block,
316312
);
@@ -415,30 +411,20 @@ where
415411
fn idle_and_finalize_hook(block_number: NumberFor<Block>) {
416412
let weight = <frame_system::Pallet<System>>::block_weight();
417413
let max_weight = <System::BlockWeights as frame_support::traits::Get<_>>::get().max_block;
418-
let mut remaining_weight = max_weight.saturating_sub(weight.total());
414+
let remaining_weight = max_weight.saturating_sub(weight.total());
419415

420416
if remaining_weight > 0 {
421-
let mut used_weight =
422-
<frame_system::Pallet<System> as OnIdle<System::BlockNumber>>::on_idle(
423-
block_number,
424-
remaining_weight,
425-
);
426-
remaining_weight = remaining_weight.saturating_sub(used_weight);
427-
used_weight = <AllPallets as OnIdle<System::BlockNumber>>::on_idle(
417+
let used_weight = <AllPalletsWithSystem as OnIdle<System::BlockNumber>>::on_idle(
428418
block_number,
429419
remaining_weight,
430-
)
431-
.saturating_add(used_weight);
420+
);
432421
<frame_system::Pallet<System>>::register_extra_weight_unchecked(
433422
used_weight,
434423
DispatchClass::Mandatory,
435424
);
436425
}
437426

438-
<frame_system::Pallet<System> as OnFinalize<System::BlockNumber>>::on_finalize(
439-
block_number,
440-
);
441-
<AllPallets as OnFinalize<System::BlockNumber>>::on_finalize(block_number);
427+
<AllPalletsWithSystem as OnFinalize<System::BlockNumber>>::on_finalize(block_number);
442428
}
443429

444430
/// Apply extrinsic outside of the block execution function.
@@ -567,7 +553,9 @@ where
567553
// as well.
568554
frame_system::BlockHash::<System>::insert(header.number(), header.hash());
569555

570-
<AllPallets as OffchainWorker<System::BlockNumber>>::offchain_worker(*header.number())
556+
<AllPalletsWithSystem as OffchainWorker<System::BlockNumber>>::offchain_worker(
557+
*header.number(),
558+
)
571559
}
572560
}
573561

@@ -849,7 +837,7 @@ mod tests {
849837
Block<TestXt>,
850838
ChainContext<Runtime>,
851839
Runtime,
852-
AllPallets,
840+
AllPalletsWithSystem,
853841
CustomOnRuntimeUpgrade,
854842
>;
855843

@@ -1360,23 +1348,19 @@ mod tests {
13601348
));
13611349

13621350
// All weights that show up in the `initialize_block_impl`
1363-
let frame_system_upgrade_weight = frame_system::Pallet::<Runtime>::on_runtime_upgrade();
13641351
let custom_runtime_upgrade_weight = CustomOnRuntimeUpgrade::on_runtime_upgrade();
1365-
let runtime_upgrade_weight = <AllPallets as OnRuntimeUpgrade>::on_runtime_upgrade();
1366-
let frame_system_on_initialize_weight =
1367-
frame_system::Pallet::<Runtime>::on_initialize(block_number);
1352+
let runtime_upgrade_weight =
1353+
<AllPalletsWithSystem as OnRuntimeUpgrade>::on_runtime_upgrade();
13681354
let on_initialize_weight =
1369-
<AllPallets as OnInitialize<u64>>::on_initialize(block_number);
1355+
<AllPalletsWithSystem as OnInitialize<u64>>::on_initialize(block_number);
13701356
let base_block_weight =
13711357
<Runtime as frame_system::Config>::BlockWeights::get().base_block;
13721358

13731359
// Weights are recorded correctly
13741360
assert_eq!(
13751361
frame_system::Pallet::<Runtime>::block_weight().total(),
1376-
frame_system_upgrade_weight +
1377-
custom_runtime_upgrade_weight +
1362+
custom_runtime_upgrade_weight +
13781363
runtime_upgrade_weight +
1379-
frame_system_on_initialize_weight +
13801364
on_initialize_weight + base_block_weight,
13811365
);
13821366
});

frame/support/procedural/src/construct_runtime/mod.rs

Lines changed: 59 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -304,35 +304,82 @@ fn decl_all_pallets<'a>(
304304
types.extend(type_decl);
305305
names.push(&pallet_declaration.name);
306306
}
307-
// Make nested tuple structure like (((Babe, Consensus), Grandpa), ...)
307+
308+
// Make nested tuple structure like:
309+
// `((FirstPallet, (SecondPallet, ( ... , LastPallet) ... ))))`
308310
// But ignore the system pallet.
309-
let all_pallets = names
311+
let all_pallets_without_system = names
310312
.iter()
311313
.filter(|n| **n != SYSTEM_PALLET_NAME)
314+
.rev()
312315
.fold(TokenStream2::default(), |combined, name| quote!((#name, #combined)));
313316

317+
// Make nested tuple structure like:
318+
// `((FirstPallet, (SecondPallet, ( ... , LastPallet) ... ))))`
314319
let all_pallets_with_system = names
315320
.iter()
321+
.rev()
322+
.fold(TokenStream2::default(), |combined, name| quote!((#name, #combined)));
323+
324+
// Make nested tuple structure like:
325+
// `((LastPallet, (SecondLastPallet, ( ... , FirstPallet) ... ))))`
326+
// But ignore the system pallet.
327+
let all_pallets_without_system_reversed = names
328+
.iter()
329+
.filter(|n| **n != SYSTEM_PALLET_NAME)
316330
.fold(TokenStream2::default(), |combined, name| quote!((#name, #combined)));
317331

332+
// Make nested tuple structure like:
333+
// `((LastPallet, (SecondLastPallet, ( ... , FirstPallet) ... ))))`
334+
let all_pallets_with_system_reversed = names
335+
.iter()
336+
.fold(TokenStream2::default(), |combined, name| quote!((#name, #combined)));
337+
338+
let system_pallet = match names.iter().find(|n| **n == SYSTEM_PALLET_NAME) {
339+
Some(name) => name,
340+
None =>
341+
return syn::Error::new(
342+
proc_macro2::Span::call_site(),
343+
"`System` pallet declaration is missing. \
344+
Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event<T>},`",
345+
)
346+
.into_compile_error(),
347+
};
348+
318349
quote!(
319350
#types
320351

321352
/// All pallets included in the runtime as a nested tuple of types.
322-
/// Excludes the System pallet.
323-
pub type AllPallets = ( #all_pallets );
353+
#[deprecated(note = "The type definition has changed from representing all pallets \
354+
excluding system, in reversed order to become the representation of all pallets \
355+
including system pallet in regular order. For this reason it is encouraged to use \
356+
explicitly one of `AllPalletsWithSystem`, `AllPalletsWithoutSystem`, \
357+
`AllPalletsWithSystemReversed`, `AllPalletsWithoutSystemReversed`. \
358+
Note that the type `frame_executive::Executive` expects one of `AllPalletsWithSystem` \
359+
, `AllPalletsWithSystemReversed`, `AllPalletsReversedWithSystemFirst`. More details in \
360+
https://github.com/paritytech/substrate/pull/10043")]
361+
pub type AllPallets = AllPalletsWithSystem;
362+
324363
/// All pallets included in the runtime as a nested tuple of types.
325364
pub type AllPalletsWithSystem = ( #all_pallets_with_system );
326365

327-
/// All modules included in the runtime as a nested tuple of types.
366+
/// All pallets included in the runtime as a nested tuple of types.
367+
/// Excludes the System pallet.
368+
pub type AllPalletsWithoutSystem = ( #all_pallets_without_system );
369+
370+
/// All pallets included in the runtime as a nested tuple of types in reversed order.
328371
/// Excludes the System pallet.
329-
#[deprecated(note = "use `AllPallets` instead")]
330-
#[allow(dead_code)]
331-
pub type AllModules = ( #all_pallets );
332-
/// All modules included in the runtime as a nested tuple of types.
333-
#[deprecated(note = "use `AllPalletsWithSystem` instead")]
334-
#[allow(dead_code)]
335-
pub type AllModulesWithSystem = ( #all_pallets_with_system );
372+
pub type AllPalletsWithoutSystemReversed = ( #all_pallets_without_system_reversed );
373+
374+
/// All pallets included in the runtime as a nested tuple of types in reversed order.
375+
pub type AllPalletsWithSystemReversed = ( #all_pallets_with_system_reversed );
376+
377+
/// All pallets included in the runtime as a nested tuple of types in reversed order.
378+
/// With the system pallet first.
379+
pub type AllPalletsReversedWithSystemFirst = (
380+
#system_pallet,
381+
AllPalletsWithoutSystemReversed
382+
);
336383
)
337384
}
338385

0 commit comments

Comments
 (0)