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

Commit f09c905

Browse files
slumberNachoPal
andauthored
aura-ext: check slot in consensus hook and remove all CheckInherents logic (#2658)
* aura-ext: check slot in consensus hook * convert relay chain slot * Make relay chain slot duration generic * use fixed velocity hook for pallets with aura * purge timestamp inherent * fix warning * adjust runtime tests * fix slots in tests * Make `xcm-emulator` test pass for new consensus hook (#2722) * add pallets on_initialize * tests pass * add AuraExt on_init * ".git/.scripts/commands/fmt/fmt.sh" --------- Co-authored-by: command-bot <> --------- Co-authored-by: Ignacio Palacios <[email protected]>
1 parent 6141995 commit f09c905

File tree

58 files changed

+581
-876
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+581
-876
lines changed

Cargo.lock

Lines changed: 2 additions & 29 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ members = [
3232
"parachain-template/runtime",
3333
"primitives/core",
3434
"primitives/parachain-inherent",
35-
"primitives/timestamp",
3635
"primitives/utility",
3736
"polkadot-parachain",
3837
"parachains/common",

pallets/aura-ext/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ scale-info = { version = "2.7.0", default-features = false, features = ["derive"
1313
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
1414
frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
1515
pallet-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
16+
pallet-timestamp= { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
1617
sp-application-crypto = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
1718
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }
1819
sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" }

pallets/aura-ext/src/consensus_hook.rs

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,51 @@
1919
//!
2020
//! The velocity `V` refers to the rate of block processing by the relay chain.
2121
22-
use super::pallet;
22+
use super::{pallet, Aura};
2323
use cumulus_pallet_parachain_system::{
2424
consensus_hook::{ConsensusHook, UnincludedSegmentCapacity},
2525
relay_state_snapshot::RelayChainStateProof,
2626
};
2727
use frame_support::pallet_prelude::*;
28+
use sp_consensus_aura::{Slot, SlotDuration};
2829
use sp_std::{marker::PhantomData, num::NonZeroU32};
2930

31+
const MILLIS_PER_SECOND: u64 = 1000;
32+
3033
/// A consensus hook for a fixed block processing velocity and unincluded segment capacity.
31-
pub struct FixedVelocityConsensusHook<T, const V: u32, const C: u32>(PhantomData<T>);
34+
///
35+
/// Relay chain slot duration must be provided in seconds.
36+
pub struct FixedVelocityConsensusHook<
37+
T,
38+
const RELAY_CHAIN_SLOT_DURATION: u32,
39+
const V: u32,
40+
const C: u32,
41+
>(PhantomData<T>);
3242

33-
impl<T: pallet::Config, const V: u32, const C: u32> ConsensusHook
34-
for FixedVelocityConsensusHook<T, V, C>
43+
impl<T: pallet::Config, const RELAY_CHAIN_SLOT_DURATION: u32, const V: u32, const C: u32>
44+
ConsensusHook for FixedVelocityConsensusHook<T, RELAY_CHAIN_SLOT_DURATION, V, C>
45+
where
46+
<T as pallet_timestamp::Config>::Moment: Into<u64>,
3547
{
3648
// Validates the number of authored blocks within the slot with respect to the `V + 1` limit.
37-
fn on_state_proof(_state_proof: &RelayChainStateProof) -> (Weight, UnincludedSegmentCapacity) {
49+
fn on_state_proof(state_proof: &RelayChainStateProof) -> (Weight, UnincludedSegmentCapacity) {
3850
// Ensure velocity is non-zero.
3951
let velocity = V.max(1);
52+
let relay_chain_slot = state_proof.read_slot().expect("failed to read relay chain slot");
4053

41-
let authored = pallet::Pallet::<T>::slot_info()
42-
.map(|(_slot, authored)| authored)
54+
let (slot, authored) = pallet::Pallet::<T>::slot_info()
4355
.expect("slot info is inserted on block initialization");
56+
57+
// Convert relay chain timestamp.
58+
let relay_chain_timestamp = u64::from(RELAY_CHAIN_SLOT_DURATION)
59+
.saturating_mul(*relay_chain_slot)
60+
.saturating_mul(MILLIS_PER_SECOND);
61+
let para_slot_duration = SlotDuration::from_millis(Aura::<T>::slot_duration().into());
62+
let para_slot_from_relay =
63+
Slot::from_timestamp(relay_chain_timestamp.into(), para_slot_duration);
64+
65+
// Perform checks.
66+
assert_eq!(slot, para_slot_from_relay, "slot number mismatch");
4467
if authored > velocity + 1 {
4568
panic!("authored blocks limit is reached for the slot")
4669
}

pallets/aura-ext/src/lib.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,9 @@
2525
//! ```
2626
//!# struct Runtime;
2727
//!# struct Executive;
28-
//!# struct CheckInherents;
2928
//! cumulus_pallet_parachain_system::register_validate_block! {
3029
//! Runtime = Runtime,
3130
//! BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
32-
//! CheckInherents = CheckInherents,
3331
//! }
3432
//! ```
3533

pallets/parachain-system/proc-macro/src/lib.rs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,20 +25,17 @@ use syn::{
2525
mod keywords {
2626
syn::custom_keyword!(Runtime);
2727
syn::custom_keyword!(BlockExecutor);
28-
syn::custom_keyword!(CheckInherents);
2928
}
3029

3130
struct Input {
3231
runtime: Path,
3332
block_executor: Path,
34-
check_inherents: Path,
3533
}
3634

3735
impl Parse for Input {
3836
fn parse(input: ParseStream) -> Result<Self, Error> {
3937
let mut runtime = None;
4038
let mut block_executor = None;
41-
let mut check_inherents = None;
4239

4340
fn parse_inner<KW: Parse + Spanned>(
4441
input: ParseStream,
@@ -59,15 +56,13 @@ impl Parse for Input {
5956
}
6057
}
6158

62-
while runtime.is_none() || block_executor.is_none() || check_inherents.is_none() {
59+
while runtime.is_none() || block_executor.is_none() {
6360
let lookahead = input.lookahead1();
6461

6562
if lookahead.peek(keywords::Runtime) {
6663
parse_inner::<keywords::Runtime>(input, &mut runtime)?;
6764
} else if lookahead.peek(keywords::BlockExecutor) {
6865
parse_inner::<keywords::BlockExecutor>(input, &mut block_executor)?;
69-
} else if lookahead.peek(keywords::CheckInherents) {
70-
parse_inner::<keywords::CheckInherents>(input, &mut check_inherents)?;
7166
} else {
7267
return Err(lookahead.error())
7368
}
@@ -81,7 +76,6 @@ impl Parse for Input {
8176
Ok(Self {
8277
runtime: runtime.expect("Everything is parsed before; qed"),
8378
block_executor: block_executor.expect("Everything is parsed before; qed"),
84-
check_inherents: check_inherents.expect("Everything is parsed before; qed"),
8579
})
8680
}
8781
}
@@ -97,7 +91,7 @@ fn crate_() -> Result<Ident, Error> {
9791

9892
#[proc_macro]
9993
pub fn register_validate_block(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
100-
let Input { runtime, check_inherents, block_executor } = match syn::parse(input) {
94+
let Input { runtime, block_executor } = match syn::parse(input) {
10195
Ok(t) => t,
10296
Err(e) => return e.into_compile_error().into(),
10397
};
@@ -133,7 +127,6 @@ pub fn register_validate_block(input: proc_macro::TokenStream) -> proc_macro::To
133127
<#runtime as #crate_::validate_block::GetRuntimeBlockType>::RuntimeBlock,
134128
#block_executor,
135129
#runtime,
136-
#check_inherents,
137130
>(params);
138131

139132
#crate_::validate_block::polkadot_parachain::write_result(&res)

pallets/parachain-system/src/lib.rs

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ use frame_system::{ensure_none, ensure_root};
4848
use polkadot_parachain::primitives::RelayChainBlockNumber;
4949
use scale_info::TypeInfo;
5050
use sp_runtime::{
51-
traits::{Block as BlockT, BlockNumberProvider, Hash},
51+
traits::{BlockNumberProvider, Hash},
5252
transaction_validity::{
5353
InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
5454
ValidTransaction,
@@ -85,12 +85,10 @@ pub use consensus_hook::ConsensusHook;
8585
/// ```
8686
/// struct BlockExecutor;
8787
/// struct Runtime;
88-
/// struct CheckInherents;
8988
///
9089
/// cumulus_pallet_parachain_system::register_validate_block! {
9190
/// Runtime = Runtime,
9291
/// BlockExecutor = Executive,
93-
/// CheckInherents = CheckInherents,
9492
/// }
9593
///
9694
/// # fn main() {}
@@ -1387,18 +1385,6 @@ impl<T: Config> UpwardMessageSender for Pallet<T> {
13871385
}
13881386
}
13891387

1390-
/// Something that can check the inherents of a block.
1391-
pub trait CheckInherents<Block: BlockT> {
1392-
/// Check all inherents of the block.
1393-
///
1394-
/// This function gets passed all the extrinsics of the block, so it is up to the callee to
1395-
/// identify the inherents. The `validation_data` can be used to access the
1396-
fn check_inherents(
1397-
block: &Block,
1398-
validation_data: &RelayChainStateProof,
1399-
) -> frame_support::inherent::CheckInherentsResult;
1400-
}
1401-
14021388
/// Something that should be informed about system related events.
14031389
///
14041390
/// This includes events like [`on_validation_data`](Self::on_validation_data) that is being

pallets/parachain-system/src/validate_block/implementation.rs

Lines changed: 2 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -61,20 +61,12 @@ fn with_externalities<F: FnOnce(&mut dyn Externalities) -> R, R>(f: F) -> R {
6161
/// we have the in-memory database that contains all the values from the state of the parachain
6262
/// that we require to verify the block.
6363
///
64-
/// 5. We are going to run `check_inherents`. This is important to check stuff like the timestamp
65-
/// matching the real world time.
66-
///
67-
/// 6. The last step is to execute the entire block in the machinery we just have setup. Executing
64+
/// 5. The last step is to execute the entire block in the machinery we just have setup. Executing
6865
/// the blocks include running all transactions in the block against our in-memory database and
6966
/// ensuring that the final storage root matches the storage root in the header of the block. In the
7067
/// end we return back the [`ValidationResult`] with all the required information for the validator.
7168
#[doc(hidden)]
72-
pub fn validate_block<
73-
B: BlockT,
74-
E: ExecuteBlock<B>,
75-
PSC: crate::Config,
76-
CI: crate::CheckInherents<B>,
77-
>(
69+
pub fn validate_block<B: BlockT, E: ExecuteBlock<B>, PSC: crate::Config>(
7870
MemoryOptimizedValidationParams {
7971
block_data,
8072
parent_head,
@@ -158,27 +150,6 @@ where
158150
sp_io::offchain_index::host_clear.replace_implementation(host_offchain_index_clear),
159151
);
160152

161-
run_with_externalities::<B, _, _>(&backend, || {
162-
let relay_chain_proof = crate::RelayChainStateProof::new(
163-
PSC::SelfParaId::get(),
164-
inherent_data.validation_data.relay_parent_storage_root,
165-
inherent_data.relay_chain_state.clone(),
166-
)
167-
.expect("Invalid relay chain state proof");
168-
169-
let res = CI::check_inherents(&block, &relay_chain_proof);
170-
171-
if !res.ok() {
172-
if log::log_enabled!(log::Level::Error) {
173-
res.into_errors().for_each(|e| {
174-
log::error!("Checking inherent with identifier `{:?}` failed", e.0)
175-
});
176-
}
177-
178-
panic!("Checking inherents failed");
179-
}
180-
});
181-
182153
run_with_externalities::<B, _, _>(&backend, || {
183154
let head_data = HeadData(block.header().encode());
184155

0 commit comments

Comments
 (0)