Fetch Babe configuration from runtime state (#11760)

* Fetch babe config data from runtime state

* Some renaming

* More renaming

* Final nits

* Fix tests and benches

* Rename  to  in BabeConfiguration

* Remove duplicate babe parameter description

Already specified over the 'PRIMARY_PROBABILITY' constant value

* trigger pipeline

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