Skip to content

Commit

Permalink
consensus-slots: cleanup SlotDuration config (paritytech#10878)
Browse files Browse the repository at this point in the history
* consensus-slots: cleanup the SlotDuration config

* fix tests

* address review comments
  • Loading branch information
andresilva authored and grishasobol committed Mar 28, 2022
1 parent 0a1cc55 commit 1c37813
Show file tree
Hide file tree
Showing 19 changed files with 161 additions and 191 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 4 additions & 6 deletions bin/node-template/node/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use sc_finality_grandpa::SharedVoterState;
use sc_keystore::LocalKeystore;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sp_consensus::SlotData;
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use std::{sync::Arc, time::Duration};

Expand Down Expand Up @@ -111,7 +110,7 @@ pub fn new_partial(
telemetry.as_ref().map(|x| x.handle()),
)?;

let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration();
let slot_duration = sc_consensus_aura::slot_duration(&*client)?;

let import_queue =
sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>(ImportQueueParams {
Expand All @@ -122,7 +121,7 @@ pub fn new_partial(
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();

let slot =
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Expand Down Expand Up @@ -260,7 +259,6 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());

let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
let raw_slot_duration = slot_duration.slot_duration();

let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _, _, _>(
StartAuraParams {
Expand All @@ -273,9 +271,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();

let slot =
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(
sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
raw_slot_duration,
slot_duration,
);

Ok((timestamp, slot))
Expand Down
9 changes: 6 additions & 3 deletions bin/node/cli/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ pub fn new_partial(
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();

let slot =
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Expand Down Expand Up @@ -419,7 +419,7 @@ pub fn new_full_base(
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();

let slot =
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
slot_duration,
);
Expand Down Expand Up @@ -650,7 +650,10 @@ mod tests {
.epoch_changes()
.shared_data()
.epoch_data(&epoch_descriptor, |slot| {
sc_consensus_babe::Epoch::genesis(&babe_link.config(), slot)
sc_consensus_babe::Epoch::genesis(
babe_link.config().genesis_config(),
slot,
)
})
.unwrap();

Expand Down
21 changes: 8 additions & 13 deletions client/consensus/aura/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,11 @@ pub use sp_consensus::SyncOracle;
pub use sp_consensus_aura::{
digests::CompatibleDigestItem,
inherents::{InherentDataProvider, InherentType as AuraInherent, INHERENT_IDENTIFIER},
AuraApi, ConsensusLog, AURA_ENGINE_ID,
AuraApi, ConsensusLog, SlotDuration, AURA_ENGINE_ID,
};

type AuthorityId<P> = <P as Pair>::Public;

/// Slot duration type for Aura.
pub type SlotDuration = sc_consensus_slots::SlotDuration<sp_consensus_aura::SlotDuration>;

/// Get the slot duration for Aura.
pub fn slot_duration<A, B, C>(client: &C) -> CResult<SlotDuration>
where
Expand All @@ -94,9 +91,7 @@ where
C::Api: AuraApi<B, A>,
{
let best_block_id = BlockId::Hash(client.usage_info().chain.best_hash);
let slot_duration = client.runtime_api().slot_duration(&best_block_id)?;

Ok(SlotDuration::new(slot_duration))
client.runtime_api().slot_duration(&best_block_id).map_err(|err| err.into())
}

/// Get slot author for given block along with authorities.
Expand Down Expand Up @@ -574,7 +569,7 @@ mod tests {
use sc_network_test::{Block as TestBlock, *};
use sp_application_crypto::key_types::AURA;
use sp_consensus::{
AlwaysCanAuthor, DisableProofRecording, NoNetwork as DummyOracle, Proposal, SlotData,
AlwaysCanAuthor, DisableProofRecording, NoNetwork as DummyOracle, Proposal,
};
use sp_consensus_aura::sr25519::AuthorityPair;
use sp_inherents::InherentData;
Expand Down Expand Up @@ -672,14 +667,14 @@ mod tests {
let client = client.as_client();
let slot_duration = slot_duration(&*client).expect("slot duration available");

assert_eq!(slot_duration.slot_duration().as_millis() as u64, SLOT_DURATION);
assert_eq!(slot_duration.as_millis() as u64, SLOT_DURATION);
import_queue::AuraVerifier::new(
client,
Box::new(|_, _| async {
let timestamp = TimestampInherentDataProvider::from_system_time();
let slot = InherentDataProvider::from_timestamp_and_duration(
let slot = InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
Duration::from_secs(6),
SlotDuration::from_millis(6000),
);

Ok((timestamp, slot))
Expand Down Expand Up @@ -762,9 +757,9 @@ mod tests {
justification_sync_link: (),
create_inherent_data_providers: |_, _| async {
let timestamp = TimestampInherentDataProvider::from_system_time();
let slot = InherentDataProvider::from_timestamp_and_duration(
let slot = InherentDataProvider::from_timestamp_and_slot_duration(
*timestamp,
Duration::from_secs(6),
SlotDuration::from_millis(6000),
);

Ok((timestamp, slot))
Expand Down
2 changes: 1 addition & 1 deletion client/consensus/babe/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ where
&parent.hash(),
parent.number().clone(),
slot.into(),
|slot| Epoch::genesis(&babe_config, slot),
|slot| Epoch::genesis(babe_config.genesis_config(), slot),
)
.map_err(|e| Error::Consensus(ConsensusError::ChainLookup(e.to_string())))?
.ok_or(Error::Consensus(ConsensusError::InvalidAuthoritiesSet))
Expand Down
72 changes: 37 additions & 35 deletions client/consensus/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::{
borrow::Cow, collections::HashMap, convert::TryInto, pin::Pin, sync::Arc, time::Duration, u64,
};
use std::{borrow::Cow, collections::HashMap, convert::TryInto, pin::Pin, sync::Arc, u64};

use codec::{Decode, Encode};
use futures::{
Expand Down Expand Up @@ -106,10 +104,10 @@ use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_blockchain::{Error as ClientError, HeaderBackend, HeaderMetadata, Result as ClientResult};
use sp_consensus::{
BlockOrigin, CacheKeyId, CanAuthorWith, Environment, Error as ConsensusError, Proposer,
SelectChain, SlotData,
SelectChain,
};
use sp_consensus_babe::inherents::BabeInherentData;
use sp_consensus_slots::Slot;
use sp_consensus_slots::{Slot, SlotDuration};
use sp_core::{crypto::ByteArray, ExecutionContext};
use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider};
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
Expand Down Expand Up @@ -328,17 +326,15 @@ pub struct BabeIntermediate<B: BlockT> {
/// Intermediate key for Babe engine.
pub static INTERMEDIATE_KEY: &[u8] = b"babe1";

/// A slot duration.
///
/// Create with [`Self::get`].
// FIXME: Once Rust has higher-kinded types, the duplication between this
// and `super::babe::Config` can be eliminated.
// https://github.com/paritytech/substrate/issues/2434
/// Configuration for BABE used for defining block verification parameters as
/// well as authoring (e.g. the slot duration).
#[derive(Clone)]
pub struct Config(sc_consensus_slots::SlotDuration<BabeGenesisConfiguration>);
pub struct Config {
genesis_config: BabeGenesisConfiguration,
}

impl Config {
/// Fetch the config from the runtime.
/// Create a new config by reading the genesis configuration from the runtime.
pub fn get<B: BlockT, C>(client: &C) -> ClientResult<Self>
where
C: AuxStore + ProvideRuntimeApi<B> + UsageProvider<B>,
Expand All @@ -355,7 +351,7 @@ impl Config {

let version = runtime_api.api_version::<dyn BabeApi<B>>(&best_block_id)?;

let slot_duration = if version == Some(1) {
let genesis_config = if version == Some(1) {
#[allow(deprecated)]
{
runtime_api.configuration_before_version_2(&best_block_id)?.into()
Expand All @@ -368,20 +364,17 @@ impl Config {
))
};

Ok(Self(sc_consensus_slots::SlotDuration::new(slot_duration)))
Ok(Config { genesis_config })
}

/// Get the inner slot duration
pub fn slot_duration(&self) -> Duration {
self.0.slot_duration()
/// Get the genesis configuration.
pub fn genesis_config(&self) -> &BabeGenesisConfiguration {
&self.genesis_config
}
}

impl std::ops::Deref for Config {
type Target = BabeGenesisConfiguration;

fn deref(&self) -> &BabeGenesisConfiguration {
&*self.0
/// Get the slot duration defined in the genesis configuration.
pub fn slot_duration(&self) -> SlotDuration {
SlotDuration::from_millis(self.genesis_config.slot_duration)
}
}

Expand Down Expand Up @@ -488,7 +481,6 @@ where
{
const HANDLE_BUFFER_SIZE: usize = 1024;

let config = babe_link.config;
let slot_notification_sinks = Arc::new(Mutex::new(Vec::new()));

let worker = BabeSlotWorker {
Expand All @@ -502,15 +494,15 @@ where
keystore,
epoch_changes: babe_link.epoch_changes.clone(),
slot_notification_sinks: slot_notification_sinks.clone(),
config: config.clone(),
config: babe_link.config.clone(),
block_proposal_slot_portion,
max_block_proposal_slot_portion,
telemetry,
};

info!(target: "babe", "👶 Starting BABE Authorship worker");
let inner = sc_consensus_slots::start_slot_worker(
config.0.clone(),
babe_link.config.slot_duration(),
select_chain,
worker,
sync_oracle,
Expand All @@ -521,7 +513,8 @@ where
let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE);

let answer_requests =
answer_requests(worker_rx, config.0, client, babe_link.epoch_changes.clone());
answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes.clone());

Ok(BabeWorker {
inner: Box::pin(future::join(inner, answer_requests).map(|_| ())),
slot_notification_sinks,
Expand All @@ -531,7 +524,7 @@ where

async fn answer_requests<B: BlockT, C>(
mut request_rx: Receiver<BabeRequest<B>>,
genesis_config: sc_consensus_slots::SlotDuration<BabeGenesisConfiguration>,
config: Config,
client: Arc<C>,
epoch_changes: SharedEpochChanges<B, Epoch>,
) where
Expand Down Expand Up @@ -561,7 +554,7 @@ async fn answer_requests<B: BlockT, C>(

let viable_epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&genesis_config, slot)
Epoch::genesis(&config.genesis_config, slot)
})
.ok_or_else(|| Error::<B>::FetchEpoch(parent_hash))?;

Expand Down Expand Up @@ -720,7 +713,9 @@ where
fn authorities_len(&self, epoch_descriptor: &Self::EpochData) -> Option<usize> {
self.epoch_changes
.shared_data()
.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})
.map(|epoch| epoch.as_ref().authorities.len())
}

Expand All @@ -735,7 +730,9 @@ where
slot,
self.epoch_changes
.shared_data()
.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))?
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})?
.as_ref(),
&self.keystore,
);
Expand Down Expand Up @@ -1165,7 +1162,9 @@ where
.map_err(|e| Error::<Block>::ForkTree(Box::new(e)))?
.ok_or_else(|| Error::<Block>::FetchEpoch(parent_hash))?;
let viable_epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})
.ok_or_else(|| Error::<Block>::FetchEpoch(parent_hash))?;

// We add one to the current slot to allow for some small drift.
Expand Down Expand Up @@ -1498,7 +1497,9 @@ where
old_epoch_changes = Some((*epoch_changes).clone());

let viable_epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))
.viable_epoch(&epoch_descriptor, |slot| {
Epoch::genesis(&self.config.genesis_config, slot)
})
.ok_or_else(|| {
ConsensusError::ClientImport(Error::<Block>::FetchEpoch(parent_hash).into())
})?;
Expand Down Expand Up @@ -1684,7 +1685,8 @@ pub fn block_import<Client, Block: BlockT, I>(
where
Client: AuxStore + HeaderBackend<Block> + HeaderMetadata<Block, Error = sp_blockchain::Error>,
{
let epoch_changes = aux_schema::load_epoch_changes::<Block, _>(&*client, &config)?;
let epoch_changes =
aux_schema::load_epoch_changes::<Block, _>(&*client, &config.genesis_config)?;
let link = BabeLink { epoch_changes: epoch_changes.clone(), config: config.clone() };

// NOTE: this isn't entirely necessary, but since we didn't use to prune the
Expand Down
Loading

0 comments on commit 1c37813

Please sign in to comment.