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 (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();
+2 -2
View File
@@ -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<Block, Epoch>,
/// 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 {
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.
// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
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,
}
}
+10 -8
View File
@@ -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<B: BlockT, C, SC> {
/// 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<B: BlockT, C, SC> Babe<B, C, SC> {
client: Arc<C>,
shared_epoch_changes: SharedEpochChanges<B, Epoch>,
keystore: SyncCryptoStorePtr,
babe_config: Config,
babe_config: BabeConfiguration,
select_chain: SC,
deny_unsafe: DenyUnsafe,
) -> Self {
@@ -185,7 +187,7 @@ impl From<Error> for JsonRpseeError {
async fn epoch_data<B, C, SC>(
epoch_changes: &SharedEpochChanges<B, Epoch>,
client: &Arc<C>,
babe_config: &Config,
babe_config: &BabeConfiguration,
slot: u64,
select_chain: &SC,
) -> Result<Epoch, Error>
@@ -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");
@@ -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<Block: BlockT, B: AuxStore>(
backend: &B,
config: &BabeGenesisConfiguration,
config: &BabeConfiguration,
) -> ClientResult<SharedEpochChanges<Block, Epoch>> {
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::<TestBlock, _>(
&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,
},
+44 -76
View File
@@ -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<sp_consensus_babe::Epoch> 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<B: BlockT> {
/// 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<B: BlockT, C>(client: &C) -> ClientResult<BabeConfiguration>
where
C: AuxStore + ProvideRuntimeApi<B> + UsageProvider<B>,
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 {
/// 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>,
C::Api: BabeApi<B>,
{
trace!(target: "babe", "Getting slot duration");
let runtime_api = client.runtime_api();
let version = runtime_api.api_version::<dyn BabeApi<B>>(&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::<dyn BabeApi<B>>(&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<C: HeaderMetadata<Block> + HeaderBackend<Block>, Block: B
async fn answer_requests<B: BlockT, C>(
mut request_rx: Receiver<BabeRequest<B>>,
config: Config,
config: BabeConfiguration,
client: Arc<C>,
epoch_changes: SharedEpochChanges<B, Epoch>,
) where
@@ -640,9 +619,7 @@ async fn answer_requests<B: BlockT, C>(
.ok_or(Error::<B>::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::<B>::FetchEpoch(parent_hash))?;
Ok(sp_consensus_babe::Epoch {
@@ -739,7 +716,7 @@ struct BabeSlotWorker<B: BlockT, C, E, I, SO, L, BS> {
keystore: SyncCryptoStorePtr,
epoch_changes: SharedEpochChanges<B, Epoch>,
slot_notification_sinks: SlotNotificationSinks<B>,
config: Config,
config: BabeConfiguration,
block_proposal_slot_portion: SlotProportion,
max_block_proposal_slot_portion: Option<SlotProportion>,
telemetry: Option<TelemetryHandle>,
@@ -797,9 +774,7 @@ 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.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<B: BlockT>(
#[derive(Clone)]
pub struct BabeLink<Block: BlockT> {
epoch_changes: SharedEpochChanges<Block, Epoch>,
config: Config,
config: BabeConfiguration,
}
impl<Block: BlockT> BabeLink<Block> {
@@ -1030,7 +1003,7 @@ impl<Block: BlockT> BabeLink<Block> {
}
/// 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<Block: BlockT, Client, SelectChain, CAW, CIDP> {
client: Arc<Client>,
select_chain: SelectChain,
create_inherent_data_providers: CIDP,
config: Config,
config: BabeConfiguration,
epoch_changes: SharedEpochChanges<Block, Epoch>,
can_author_with: CAW,
telemetry: Option<TelemetryHandle>,
@@ -1245,9 +1218,7 @@ where
.map_err(|e| Error::<Block>::ForkTree(Box::new(e)))?
.ok_or(Error::<Block>::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::<Block>::FetchEpoch(parent_hash))?;
// 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,
client: Arc<Client>,
epoch_changes: SharedEpochChanges<Block, Epoch>,
config: Config,
config: BabeConfiguration,
}
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>,
epoch_changes: SharedEpochChanges<Block, Epoch>,
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::<Block>::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<Client, Block: BlockT, I>(
config: Config,
config: BabeConfiguration,
wrapped_block_import: I,
client: Arc<Client>,
) -> ClientResult<(BabeBlockImport<Block, Client, I>, BabeLink<Block>)>
@@ -1772,8 +1741,7 @@ where
+ PreCommitActions<Block>
+ 'static,
{
let epoch_changes =
aux_schema::load_epoch_changes::<Block, _>(&*client, &config.genesis_config)?;
let epoch_changes = aux_schema::load_epoch_changes::<Block, _>(&*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::<Block, Client>(&*client, config.genesis_config())?;
// This config is only used on-genesis.
let config = configuration(&*client)?;
let epoch_changes = aux_schema::load_epoch_changes::<Block, Client>(&*client, &config)?;
let mut epoch_changes = epoch_changes.shared_data();
if revert_up_to_number == Zero::zero() {
@@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
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,
+16 -17
View File
@@ -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<TestClient>,
epoch_changes: SharedEpochChanges<TestBlock, Epoch>,
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::<Block, TestClient>(
&*client,
data.link.config.genesis_config(),
)
.expect("load epoch changes")
.shared_data()
.tree()
.iter()
.map(|(h, _, _)| *h)
.collect::<Vec<_>>();
let actual_nodes =
aux_schema::load_epoch_changes::<Block, TestClient>(&*client, &data.link.config)
.expect("load epoch changes")
.shared_data()
.tree()
.iter()
.map(|(h, _, _)| *h)
.collect::<Vec<_>>();
let expected_nodes = vec![
canon[0], // A
@@ -39,7 +39,7 @@ pub trait ConsensusDataProvider<B: BlockT>: Send + Sync {
/// Attempt to create a consensus digest.
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(
&self,
parent: &B::Header,
@@ -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<B: BlockT, C, P> {
epoch_changes: SharedEpochChanges<B, Epoch>,
/// 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!(
@@ -63,7 +63,7 @@ impl SlotTimestampProvider {
C: AuxStore + HeaderBackend<B> + ProvideRuntimeApi<B> + UsageProvider<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 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
/// genesis.
#[pallet::storage]
#[pallet::getter(fn epoch_config)]
pub(super) type EpochConfig<T> = StorageValue<_, BabeEpochConfiguration>;
/// 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.
#[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<BabeGenesisConfigurationV1> for BabeGenesisConfiguration {
fn from(v1: BabeGenesisConfigurationV1) -> Self {
impl From<BabeConfigurationV1> 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<BabeGenesisConfigurationV1> 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;
+6 -6
View File
@@ -849,12 +849,12 @@ cfg_if! {
}
impl sp_consensus_babe::BabeApi<Block> 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: <pallet_babe::Pallet<Runtime>>::randomness(),
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
@@ -1123,12 +1123,12 @@ cfg_if! {
}
impl sp_consensus_babe::BabeApi<Block> 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: <pallet_babe::Pallet<Runtime>>::randomness(),
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,