diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index b20a3ac59a..13003c1a7a 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -199,7 +199,7 @@ pub fn new_partial( let justification_import = grandpa_block_import.clone(); let (block_import, babe_link) = sc_consensus_babe::block_import( - sc_consensus_babe::Config::get(&*client)?, + sc_consensus_babe::configuration(&*client)?, grandpa_block_import, client.clone(), )?; @@ -682,10 +682,7 @@ mod tests { .epoch_changes() .shared_data() .epoch_data(&epoch_descriptor, |slot| { - sc_consensus_babe::Epoch::genesis( - babe_link.config().genesis_config(), - slot, - ) + sc_consensus_babe::Epoch::genesis(babe_link.config(), slot) }) .unwrap(); diff --git a/substrate/bin/node/rpc/src/lib.rs b/substrate/bin/node/rpc/src/lib.rs index e5b666195e..1c8b9cce1a 100644 --- a/substrate/bin/node/rpc/src/lib.rs +++ b/substrate/bin/node/rpc/src/lib.rs @@ -36,7 +36,7 @@ use std::sync::Arc; use jsonrpsee::RpcModule; use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index}; use sc_client_api::AuxStore; -use sc_consensus_babe::{Config, Epoch}; +use sc_consensus_babe::{BabeConfiguration, Epoch}; use sc_consensus_epochs::SharedEpochChanges; use sc_finality_grandpa::{ FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState, @@ -54,7 +54,7 @@ use sp_keystore::SyncCryptoStorePtr; /// Extra dependencies for BABE. pub struct BabeDeps { /// BABE protocol config. - pub babe_config: Config, + pub babe_config: BabeConfiguration, /// BABE pending epoch changes. pub shared_epoch_changes: SharedEpochChanges, /// The keystore that manages the keys of the node. diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index fa0f877c59..5aa488f328 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -1859,19 +1859,15 @@ impl_runtime_apis! { } impl sp_consensus_babe::BabeApi for Runtime { - fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { - // The choice of `c` parameter (where `1 - c` represents the - // probability of a slot being empty), is done in accordance to the - // slot duration and expected target block time, for safely - // resisting network delays of maximum two seconds. - // - sp_consensus_babe::BabeGenesisConfiguration { + fn configuration() -> sp_consensus_babe::BabeConfiguration { + let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG); + sp_consensus_babe::BabeConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), - c: BABE_GENESIS_EPOCH_CONFIG.c, - genesis_authorities: Babe::authorities().to_vec(), + c: epoch_config.c, + authorities: Babe::authorities().to_vec(), randomness: Babe::randomness(), - allowed_slots: BABE_GENESIS_EPOCH_CONFIG.allowed_slots, + allowed_slots: epoch_config.allowed_slots, } } diff --git a/substrate/client/consensus/babe/rpc/src/lib.rs b/substrate/client/consensus/babe/rpc/src/lib.rs index b000d38a44..288f852a5c 100644 --- a/substrate/client/consensus/babe/rpc/src/lib.rs +++ b/substrate/client/consensus/babe/rpc/src/lib.rs @@ -25,7 +25,7 @@ use jsonrpsee::{ types::{error::CallError, ErrorObject}, }; -use sc_consensus_babe::{authorship, Config, Epoch}; +use sc_consensus_babe::{authorship, Epoch}; use sc_consensus_epochs::{descendent_query, Epoch as EpochT, SharedEpochChanges}; use sc_rpc_api::DenyUnsafe; use serde::{Deserialize, Serialize}; @@ -33,7 +33,9 @@ use sp_api::{BlockId, ProvideRuntimeApi}; use sp_application_crypto::AppKey; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_consensus::{Error as ConsensusError, SelectChain}; -use sp_consensus_babe::{digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi}; +use sp_consensus_babe::{ + digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi, BabeConfiguration, +}; use sp_core::crypto::ByteArray; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_runtime::traits::{Block as BlockT, Header as _}; @@ -57,7 +59,7 @@ pub struct Babe { /// shared reference to the Keystore keystore: SyncCryptoStorePtr, /// config (actually holds the slot duration) - babe_config: Config, + babe_config: BabeConfiguration, /// The SelectChain strategy select_chain: SC, /// Whether to deny unsafe calls @@ -70,7 +72,7 @@ impl Babe { client: Arc, shared_epoch_changes: SharedEpochChanges, keystore: SyncCryptoStorePtr, - babe_config: Config, + babe_config: BabeConfiguration, select_chain: SC, deny_unsafe: DenyUnsafe, ) -> Self { @@ -185,7 +187,7 @@ impl From for JsonRpseeError { async fn epoch_data( epoch_changes: &SharedEpochChanges, client: &Arc, - babe_config: &Config, + babe_config: &BabeConfiguration, slot: u64, select_chain: &SC, ) -> Result @@ -202,7 +204,7 @@ where &parent.hash(), *parent.number(), slot.into(), - |slot| Epoch::genesis(babe_config.genesis_config(), slot), + |slot| Epoch::genesis(babe_config, slot), ) .map_err(|e| Error::Consensus(ConsensusError::ChainLookup(e.to_string())))? .ok_or(Error::Consensus(ConsensusError::InvalidAuthoritiesSet)) @@ -221,7 +223,7 @@ mod tests { TestClientBuilderExt, }; - use sc_consensus_babe::{block_import, AuthorityPair, Config}; + use sc_consensus_babe::{block_import, AuthorityPair}; use std::sync::Arc; /// creates keystore backed by a temp file @@ -243,7 +245,7 @@ mod tests { let builder = TestClientBuilder::new(); let (client, longest_chain) = builder.build_with_longest_chain(); let client = Arc::new(client); - let config = Config::get(&*client).expect("config available"); + let config = sc_consensus_babe::configuration(&*client).expect("config available"); let (_, link) = block_import(config.clone(), client.clone(), client.clone()) .expect("can initialize block-import"); diff --git a/substrate/client/consensus/babe/src/aux_schema.rs b/substrate/client/consensus/babe/src/aux_schema.rs index 2ab84b9b13..fef84bda86 100644 --- a/substrate/client/consensus/babe/src/aux_schema.rs +++ b/substrate/client/consensus/babe/src/aux_schema.rs @@ -28,7 +28,7 @@ use sc_consensus_epochs::{ EpochChangesFor, SharedEpochChanges, }; use sp_blockchain::{Error as ClientError, Result as ClientResult}; -use sp_consensus_babe::{BabeBlockWeight, BabeGenesisConfiguration}; +use sp_consensus_babe::{BabeBlockWeight, BabeConfiguration}; use sp_runtime::traits::Block as BlockT; const BABE_EPOCH_CHANGES_VERSION: &[u8] = b"babe_epoch_changes_version"; @@ -57,7 +57,7 @@ where /// Load or initialize persistent epoch change data from backend. pub fn load_epoch_changes( backend: &B, - config: &BabeGenesisConfiguration, + config: &BabeConfiguration, ) -> ClientResult> { let version = load_decode::<_, u32>(backend, BABE_EPOCH_CHANGES_VERSION)?; @@ -143,7 +143,7 @@ mod test { use sc_consensus_epochs::{EpochHeader, PersistedEpoch, PersistedEpochHeader}; use sc_network_test::Block as TestBlock; use sp_consensus::Error as ConsensusError; - use sp_consensus_babe::{AllowedSlots, BabeGenesisConfiguration}; + use sp_consensus_babe::AllowedSlots; use sp_core::H256; use sp_runtime::traits::NumberFor; use substrate_test_runtime_client; @@ -182,11 +182,11 @@ mod test { let epoch_changes = load_epoch_changes::( &client, - &BabeGenesisConfiguration { + &BabeConfiguration { slot_duration: 10, epoch_length: 4, c: (3, 10), - genesis_authorities: Vec::new(), + authorities: Vec::new(), randomness: Default::default(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, }, diff --git a/substrate/client/consensus/babe/src/lib.rs b/substrate/client/consensus/babe/src/lib.rs index f61ba23d92..1303915efe 100644 --- a/substrate/client/consensus/babe/src/lib.rs +++ b/substrate/client/consensus/babe/src/lib.rs @@ -119,7 +119,7 @@ use sp_consensus::{ SelectChain, }; use sp_consensus_babe::inherents::BabeInherentData; -use sp_consensus_slots::{Slot, SlotDuration}; +use sp_consensus_slots::Slot; use sp_core::{crypto::ByteArray, ExecutionContext}; use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider}; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; @@ -137,8 +137,7 @@ pub use sp_consensus_babe::{ PrimaryPreDigest, SecondaryPlainPreDigest, }, AuthorityId, AuthorityPair, AuthoritySignature, BabeApi, BabeAuthorityWeight, BabeBlockWeight, - BabeEpochConfiguration, BabeGenesisConfiguration, ConsensusLog, BABE_ENGINE_ID, - VRF_OUTPUT_LENGTH, + BabeConfiguration, BabeEpochConfiguration, ConsensusLog, BABE_ENGINE_ID, VRF_OUTPUT_LENGTH, }; pub use aux_schema::load_block_weight as block_weight; @@ -211,12 +210,12 @@ impl From for Epoch { impl Epoch { /// Create the genesis epoch (epoch #0). This is defined to start at the slot of /// the first block, so that has to be provided. - pub fn genesis(genesis_config: &BabeGenesisConfiguration, slot: Slot) -> Epoch { + pub fn genesis(genesis_config: &BabeConfiguration, slot: Slot) -> Epoch { Epoch { epoch_index: 0, start_slot: slot, duration: genesis_config.epoch_length, - authorities: genesis_config.genesis_authorities.clone(), + authorities: genesis_config.authorities.clone(), randomness: genesis_config.randomness, config: BabeEpochConfiguration { c: genesis_config.c, @@ -338,56 +337,36 @@ pub struct BabeIntermediate { /// Intermediate key for Babe engine. pub static INTERMEDIATE_KEY: &[u8] = b"babe1"; -/// Configuration for BABE used for defining block verification parameters as -/// well as authoring (e.g. the slot duration). -#[derive(Clone)] -pub struct Config { - genesis_config: BabeGenesisConfiguration, -} +/// Read configuration from the runtime state at current best block. +pub fn configuration(client: &C) -> ClientResult +where + C: AuxStore + ProvideRuntimeApi + UsageProvider, + C::Api: BabeApi, +{ + let block_id = if client.usage_info().chain.finalized_state.is_some() { + BlockId::Hash(client.usage_info().chain.best_hash) + } else { + debug!(target: "babe", "No finalized state is available. Reading config from genesis"); + BlockId::Hash(client.usage_info().chain.genesis_hash) + }; -impl Config { - /// Create a new config by reading the genesis configuration from the runtime. - pub fn get(client: &C) -> ClientResult - where - C: AuxStore + ProvideRuntimeApi + UsageProvider, - C::Api: BabeApi, - { - trace!(target: "babe", "Getting slot duration"); + let runtime_api = client.runtime_api(); + let version = runtime_api.api_version::>(&block_id)?; - let mut best_block_id = BlockId::Hash(client.usage_info().chain.best_hash); - if client.usage_info().chain.finalized_state.is_none() { - debug!(target: "babe", "No finalized state is available. Reading config from genesis"); - best_block_id = BlockId::Hash(client.usage_info().chain.genesis_hash); - } - let runtime_api = client.runtime_api(); - - let version = runtime_api.api_version::>(&best_block_id)?; - - let genesis_config = if version == Some(1) { + let config = match version { + Some(1) => { #[allow(deprecated)] { - runtime_api.configuration_before_version_2(&best_block_id)?.into() + runtime_api.configuration_before_version_2(&block_id)?.into() } - } else if version == Some(2) { - runtime_api.configuration(&best_block_id)? - } else { + }, + Some(2) => runtime_api.configuration(&block_id)?, + _ => return Err(sp_blockchain::Error::VersionInvalid( "Unsupported or invalid BabeApi version".to_string(), - )) - }; - - Ok(Config { genesis_config }) - } - - /// Get the genesis configuration. - pub fn genesis_config(&self) -> &BabeGenesisConfiguration { - &self.genesis_config - } - - /// Get the slot duration defined in the genesis configuration. - pub fn slot_duration(&self) -> SlotDuration { - SlotDuration::from_millis(self.genesis_config.slot_duration) - } + )), + }; + Ok(config) } /// Parameters for BABE. @@ -611,7 +590,7 @@ fn aux_storage_cleanup + HeaderBackend, Block: B async fn answer_requests( mut request_rx: Receiver>, - config: Config, + config: BabeConfiguration, client: Arc, epoch_changes: SharedEpochChanges, ) where @@ -640,9 +619,7 @@ async fn answer_requests( .ok_or(Error::::FetchEpoch(parent_hash))?; let viable_epoch = epoch_changes - .viable_epoch(&epoch_descriptor, |slot| { - Epoch::genesis(&config.genesis_config, slot) - }) + .viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&config, slot)) .ok_or(Error::::FetchEpoch(parent_hash))?; Ok(sp_consensus_babe::Epoch { @@ -739,7 +716,7 @@ struct BabeSlotWorker { keystore: SyncCryptoStorePtr, epoch_changes: SharedEpochChanges, slot_notification_sinks: SlotNotificationSinks, - config: Config, + config: BabeConfiguration, block_proposal_slot_portion: SlotProportion, max_block_proposal_slot_portion: Option, telemetry: Option, @@ -797,9 +774,7 @@ where fn authorities_len(&self, epoch_descriptor: &Self::EpochData) -> Option { self.epoch_changes .shared_data() - .viable_epoch(epoch_descriptor, |slot| { - Epoch::genesis(&self.config.genesis_config, slot) - }) + .viable_epoch(epoch_descriptor, |slot| Epoch::genesis(&self.config, slot)) .map(|epoch| epoch.as_ref().authorities.len()) } @@ -814,9 +789,7 @@ where slot, self.epoch_changes .shared_data() - .viable_epoch(epoch_descriptor, |slot| { - Epoch::genesis(&self.config.genesis_config, slot) - })? + .viable_epoch(epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))? .as_ref(), &self.keystore, ); @@ -1020,7 +993,7 @@ fn find_next_config_digest( #[derive(Clone)] pub struct BabeLink { epoch_changes: SharedEpochChanges, - config: Config, + config: BabeConfiguration, } impl BabeLink { @@ -1030,7 +1003,7 @@ impl BabeLink { } /// Get the config of this link. - pub fn config(&self) -> &Config { + pub fn config(&self) -> &BabeConfiguration { &self.config } } @@ -1040,7 +1013,7 @@ pub struct BabeVerifier { client: Arc, select_chain: SelectChain, create_inherent_data_providers: CIDP, - config: Config, + config: BabeConfiguration, epoch_changes: SharedEpochChanges, can_author_with: CAW, telemetry: Option, @@ -1245,9 +1218,7 @@ where .map_err(|e| Error::::ForkTree(Box::new(e)))? .ok_or(Error::::FetchEpoch(parent_hash))?; let viable_epoch = epoch_changes - .viable_epoch(&epoch_descriptor, |slot| { - Epoch::genesis(&self.config.genesis_config, slot) - }) + .viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot)) .ok_or(Error::::FetchEpoch(parent_hash))?; // We add one to the current slot to allow for some small drift. @@ -1353,7 +1324,7 @@ pub struct BabeBlockImport { inner: I, client: Arc, epoch_changes: SharedEpochChanges, - config: Config, + config: BabeConfiguration, } impl Clone for BabeBlockImport { @@ -1372,7 +1343,7 @@ impl BabeBlockImport { client: Arc, epoch_changes: SharedEpochChanges, block_import: I, - config: Config, + config: BabeConfiguration, ) -> Self { BabeBlockImport { client, inner: block_import, epoch_changes, config } } @@ -1580,9 +1551,7 @@ where old_epoch_changes = Some((*epoch_changes).clone()); let viable_epoch = epoch_changes - .viable_epoch(&epoch_descriptor, |slot| { - Epoch::genesis(&self.config.genesis_config, slot) - }) + .viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot)) .ok_or_else(|| { ConsensusError::ClientImport(Error::::FetchEpoch(parent_hash).into()) })?; @@ -1761,7 +1730,7 @@ where /// Also returns a link object used to correctly instantiate the import queue /// and background worker. pub fn block_import( - config: Config, + config: BabeConfiguration, wrapped_block_import: I, client: Arc, ) -> ClientResult<(BabeBlockImport, BabeLink)> @@ -1772,8 +1741,7 @@ where + PreCommitActions + 'static, { - let epoch_changes = - aux_schema::load_epoch_changes::(&*client, &config.genesis_config)?; + let epoch_changes = aux_schema::load_epoch_changes::(&*client, &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 @@ -1884,9 +1852,9 @@ where // Revert epoch changes tree. - let config = Config::get(&*client)?; - let epoch_changes = - aux_schema::load_epoch_changes::(&*client, config.genesis_config())?; + // This config is only used on-genesis. + let config = configuration(&*client)?; + let epoch_changes = aux_schema::load_epoch_changes::(&*client, &config)?; let mut epoch_changes = epoch_changes.shared_data(); if revert_up_to_number == Zero::zero() { diff --git a/substrate/client/consensus/babe/src/migration.rs b/substrate/client/consensus/babe/src/migration.rs index a8c3772bbe..23413aa6a7 100644 --- a/substrate/client/consensus/babe/src/migration.rs +++ b/substrate/client/consensus/babe/src/migration.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . use crate::{ - AuthorityId, BabeAuthorityWeight, BabeEpochConfiguration, BabeGenesisConfiguration, Epoch, + AuthorityId, BabeAuthorityWeight, BabeConfiguration, BabeEpochConfiguration, Epoch, NextEpochDescriptor, VRF_OUTPUT_LENGTH, }; use codec::{Decode, Encode}; @@ -64,7 +64,7 @@ impl EpochT for EpochV0 { impl EpochV0 { /// Migrate the sturct to current epoch version. - pub fn migrate(self, config: &BabeGenesisConfiguration) -> Epoch { + pub fn migrate(self, config: &BabeConfiguration) -> Epoch { Epoch { epoch_index: self.epoch_index, start_slot: self.start_slot, diff --git a/substrate/client/consensus/babe/src/tests.rs b/substrate/client/consensus/babe/src/tests.rs index 5ecdb42f7f..7207b7a36c 100644 --- a/substrate/client/consensus/babe/src/tests.rs +++ b/substrate/client/consensus/babe/src/tests.rs @@ -36,6 +36,7 @@ use sp_consensus_babe::{ inherents::InherentDataProvider, make_transcript, make_transcript_data, AllowedSlots, AuthorityPair, Slot, }; +use sp_consensus_slots::SlotDuration; use sp_core::crypto::Pair; use sp_keystore::{vrf::make_transcript as transcript_from_data, SyncCryptoStore}; use sp_runtime::{ @@ -71,7 +72,7 @@ type BabeBlockImport = struct DummyFactory { client: Arc, epoch_changes: SharedEpochChanges, - config: Config, + config: BabeConfiguration, mutator: Mutator, } @@ -139,7 +140,7 @@ impl DummyProposer { &self.parent_hash, self.parent_number, this_slot, - |slot| Epoch::genesis(self.factory.config.genesis_config(), slot), + |slot| Epoch::genesis(&self.factory.config, slot), ) .expect("client has data to find epoch") .expect("can compute epoch for baked block"); @@ -288,7 +289,7 @@ impl TestNetFactory for BabeTestNet { ) { let client = client.as_client(); - let config = Config::get(&*client).expect("config available"); + let config = crate::configuration(&*client).expect("config available"); let (block_import, link) = crate::block_import(config, client.clone(), client.clone()) .expect("can initialize block-import"); @@ -559,11 +560,11 @@ fn can_author_block() { }, }; - let mut config = crate::BabeGenesisConfiguration { + let mut config = crate::BabeConfiguration { slot_duration: 1000, epoch_length: 100, c: (3, 10), - genesis_authorities: Vec::new(), + authorities: Vec::new(), randomness: [0; 32], allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, }; @@ -708,12 +709,12 @@ fn importing_block_one_sets_genesis_epoch() { &mut block_import, ); - let genesis_epoch = Epoch::genesis(data.link.config.genesis_config(), 999.into()); + let genesis_epoch = Epoch::genesis(&data.link.config, 999.into()); let epoch_changes = data.link.epoch_changes.shared_data(); let epoch_for_second_block = epoch_changes .epoch_data_for_child_of(descendent_query(&*client), &block_hash, 1, 1000.into(), |slot| { - Epoch::genesis(data.link.config.genesis_config(), slot) + Epoch::genesis(&data.link.config, slot) }) .unwrap() .unwrap(); @@ -771,16 +772,14 @@ fn revert_prunes_epoch_changes_and_removes_weights() { // Load and check epoch changes. - let actual_nodes = aux_schema::load_epoch_changes::( - &*client, - data.link.config.genesis_config(), - ) - .expect("load epoch changes") - .shared_data() - .tree() - .iter() - .map(|(h, _, _)| *h) - .collect::>(); + let actual_nodes = + aux_schema::load_epoch_changes::(&*client, &data.link.config) + .expect("load epoch changes") + .shared_data() + .tree() + .iter() + .map(|(h, _, _)| *h) + .collect::>(); let expected_nodes = vec![ canon[0], // A diff --git a/substrate/client/consensus/manual-seal/src/consensus.rs b/substrate/client/consensus/manual-seal/src/consensus.rs index b5dfc3d809..a812bb028c 100644 --- a/substrate/client/consensus/manual-seal/src/consensus.rs +++ b/substrate/client/consensus/manual-seal/src/consensus.rs @@ -39,7 +39,7 @@ pub trait ConsensusDataProvider: Send + Sync { /// Attempt to create a consensus digest. fn create_digest(&self, parent: &B::Header, inherents: &InherentData) -> Result; - /// set up the neccessary import params. + /// Set up the necessary import params. fn append_block_import( &self, parent: &B::Header, diff --git a/substrate/client/consensus/manual-seal/src/consensus/babe.rs b/substrate/client/consensus/manual-seal/src/consensus/babe.rs index cc73a3fa96..300a96695c 100644 --- a/substrate/client/consensus/manual-seal/src/consensus/babe.rs +++ b/substrate/client/consensus/manual-seal/src/consensus/babe.rs @@ -24,8 +24,7 @@ use crate::Error; use codec::Encode; use sc_client_api::{AuxStore, UsageProvider}; use sc_consensus_babe::{ - authorship, find_pre_digest, BabeIntermediate, CompatibleDigestItem, Config, Epoch, - INTERMEDIATE_KEY, + authorship, find_pre_digest, BabeIntermediate, CompatibleDigestItem, Epoch, INTERMEDIATE_KEY, }; use sc_consensus_epochs::{ descendent_query, EpochHeader, SharedEpochChanges, ViableEpochDescriptor, @@ -40,7 +39,7 @@ use sp_consensus::CacheKeyId; use sp_consensus_babe::{ digests::{NextEpochDescriptor, PreDigest, SecondaryPlainPreDigest}, inherents::BabeInherentData, - AuthorityId, BabeApi, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID, + AuthorityId, BabeApi, BabeAuthorityWeight, BabeConfiguration, ConsensusLog, BABE_ENGINE_ID, }; use sp_consensus_slots::Slot; use sp_inherents::InherentData; @@ -64,7 +63,10 @@ pub struct BabeConsensusDataProvider { epoch_changes: SharedEpochChanges, /// BABE config, gotten from the runtime. - config: Config, + /// NOTE: This is used to fetch `slot_duration` and `epoch_length` in the + /// `ConsensusDataProvider` implementation. Correct as far as these values + /// are not changed during an epoch change. + config: BabeConfiguration, /// Authorities to be used for this babe chain. authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, @@ -152,7 +154,7 @@ where return Err(Error::StringError("Cannot supply empty authority set!".into())) } - let config = Config::get(&*client)?; + let config = sc_consensus_babe::configuration(&*client)?; Ok(Self { config, @@ -177,9 +179,7 @@ where .ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?; let epoch = epoch_changes - .viable_epoch(&epoch_descriptor, |slot| { - Epoch::genesis(self.config.genesis_config(), slot) - }) + .viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot)) .ok_or_else(|| { log::info!(target: "babe", "create_digest: no viable_epoch :("); sp_consensus::Error::InvalidAuthoritiesSet @@ -306,7 +306,7 @@ where identifier, EpochHeader { start_slot: slot, - end_slot: (*slot * self.config.genesis_config().epoch_length).into(), + end_slot: (*slot * self.config.epoch_length).into(), }, ), _ => unreachable!( diff --git a/substrate/client/consensus/manual-seal/src/consensus/timestamp.rs b/substrate/client/consensus/manual-seal/src/consensus/timestamp.rs index 70b5e5de4e..f899b80d6c 100644 --- a/substrate/client/consensus/manual-seal/src/consensus/timestamp.rs +++ b/substrate/client/consensus/manual-seal/src/consensus/timestamp.rs @@ -63,7 +63,7 @@ impl SlotTimestampProvider { C: AuxStore + HeaderBackend + ProvideRuntimeApi + UsageProvider, C::Api: BabeApi, { - let slot_duration = sc_consensus_babe::Config::get(&*client)?.slot_duration(); + let slot_duration = sc_consensus_babe::configuration(&*client)?.slot_duration(); let time = Self::with_header(&client, slot_duration, |header| { let slot_number = *sc_consensus_babe::find_pre_digest::(&header) diff --git a/substrate/frame/babe/src/lib.rs b/substrate/frame/babe/src/lib.rs index 48ca62a5b1..9a99d8ed99 100644 --- a/substrate/frame/babe/src/lib.rs +++ b/substrate/frame/babe/src/lib.rs @@ -306,6 +306,7 @@ pub mod pallet { /// The configuration for the current epoch. Should never be `None` as it is initialized in /// genesis. #[pallet::storage] + #[pallet::getter(fn epoch_config)] pub(super) type EpochConfig = StorageValue<_, BabeEpochConfiguration>; /// The configuration for the next epoch, `None` if the config will not change diff --git a/substrate/primitives/consensus/babe/src/lib.rs b/substrate/primitives/consensus/babe/src/lib.rs index 492d1a9a72..621ab859b9 100644 --- a/substrate/primitives/consensus/babe/src/lib.rs +++ b/substrate/primitives/consensus/babe/src/lib.rs @@ -137,7 +137,7 @@ pub enum ConsensusLog { /// Configuration data used by the BABE consensus engine. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] -pub struct BabeGenesisConfigurationV1 { +pub struct BabeConfigurationV1 { /// The slot duration in milliseconds for BABE. Currently, only /// the value provided by this type at genesis will be used. /// @@ -156,7 +156,7 @@ pub struct BabeGenesisConfigurationV1 { pub c: (u64, u64), /// The authorities for the genesis epoch. - pub genesis_authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, + pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, /// The randomness for the genesis epoch. pub randomness: Randomness, @@ -166,13 +166,13 @@ pub struct BabeGenesisConfigurationV1 { pub secondary_slots: bool, } -impl From for BabeGenesisConfiguration { - fn from(v1: BabeGenesisConfigurationV1) -> Self { +impl From for BabeConfiguration { + fn from(v1: BabeConfigurationV1) -> Self { Self { slot_duration: v1.slot_duration, epoch_length: v1.epoch_length, c: v1.c, - genesis_authorities: v1.genesis_authorities, + authorities: v1.authorities, randomness: v1.randomness, allowed_slots: if v1.secondary_slots { AllowedSlots::PrimaryAndSecondaryPlainSlots @@ -185,7 +185,7 @@ impl From for BabeGenesisConfiguration { /// Configuration data used by the BABE consensus engine. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] -pub struct BabeGenesisConfiguration { +pub struct BabeConfiguration { /// The slot duration in milliseconds for BABE. Currently, only /// the value provided by this type at genesis will be used. /// @@ -203,16 +203,23 @@ pub struct BabeGenesisConfiguration { /// of a slot being empty. pub c: (u64, u64), - /// The authorities for the genesis epoch. - pub genesis_authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, + /// The authorities + pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, - /// The randomness for the genesis epoch. + /// The randomness pub randomness: Randomness, /// Type of allowed slots. pub allowed_slots: AllowedSlots, } +impl BabeConfiguration { + /// Convenience method to get the slot duration as a `SlotDuration` value. + pub fn slot_duration(&self) -> SlotDuration { + SlotDuration::from_millis(self.slot_duration) + } +} + /// Types of allowed slots. #[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] @@ -237,7 +244,7 @@ impl AllowedSlots { } } -/// Configuration data used by the BABE consensus engine. +/// Configuration data used by the BABE consensus engine that may change with epochs. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct BabeEpochConfiguration { @@ -357,12 +364,12 @@ sp_api::decl_runtime_apis! { /// API necessary for block authorship with BABE. #[api_version(2)] pub trait BabeApi { - /// Return the genesis configuration for BABE. The configuration is only read on genesis. - fn configuration() -> BabeGenesisConfiguration; + /// Return the configuration for BABE. + fn configuration() -> BabeConfiguration; /// Return the configuration for BABE. Version 1. #[changed_in(2)] - fn configuration() -> BabeGenesisConfigurationV1; + fn configuration() -> BabeConfigurationV1; /// Returns the slot that started the current epoch. fn current_epoch_start() -> Slot; diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index 181e3fec62..bb526010dd 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -849,12 +849,12 @@ cfg_if! { } impl sp_consensus_babe::BabeApi for Runtime { - fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { - sp_consensus_babe::BabeGenesisConfiguration { + fn configuration() -> sp_consensus_babe::BabeConfiguration { + sp_consensus_babe::BabeConfiguration { slot_duration: 1000, epoch_length: EpochDuration::get(), c: (3, 10), - genesis_authorities: system::authorities() + authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), randomness: >::randomness(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, @@ -1123,12 +1123,12 @@ cfg_if! { } impl sp_consensus_babe::BabeApi for Runtime { - fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { - sp_consensus_babe::BabeGenesisConfiguration { + fn configuration() -> sp_consensus_babe::BabeConfiguration { + sp_consensus_babe::BabeConfiguration { slot_duration: 1000, epoch_length: EpochDuration::get(), c: (3, 10), - genesis_authorities: system::authorities() + authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), randomness: >::randomness(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,