Skip to content

Commit

Permalink
Merge branch 'dev' into 984-cli-fix-warning
Browse files Browse the repository at this point in the history
  • Loading branch information
frankli-dev authored Jan 4, 2024
2 parents 8ff6af3 + 938cc18 commit 2909f8e
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 188 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ sc-client-api = { workspace = true }
sc-consensus = { workspace = true }
sc-consensus-babe = { workspace = true }
sc-consensus-babe-rpc = { workspace = true }
sc-consensus-epochs = { workspace = true }
sc-consensus-grandpa = { workspace = true }
sc-consensus-grandpa-rpc = { workspace = true }
sc-consensus-manual-seal = { workspace = true }
Expand Down
3 changes: 1 addition & 2 deletions node/src/rpc/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,7 @@ pub struct EthDeps<B: BlockT, C, P, A: ChainApi, CT, CIDP> {
/// Something that can create the inherent data providers for pending state
pub pending_create_inherent_data_providers: CIDP,

pub pending_consensus_data_provider:
Option<consensus_data_provider::BabeConsensusDataProvider<B, C>>,
pub pending_consensus_data_provider: Option<consensus_data_provider::BabeConsensusDataProvider>,
}

/// Instantiate Ethereum-compatible RPC extensions.
Expand Down
187 changes: 16 additions & 171 deletions node/src/rpc/eth/consensus_data_provider.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,12 @@
use std::sync::Arc;

use fc_rpc::pending::ConsensusDataProvider;
use parity_scale_codec::Encode;
use sc_client_api::{AuxStore, UsageProvider};
use sc_consensus_babe::{
authorship::claim_slot, AuthorityId, BabeAuthorityWeight, BabeConfiguration,
CompatibleDigestItem, Epoch, NextEpochDescriptor, PreDigest, SecondaryPlainPreDigest,
};
use sc_consensus_epochs::{descendent_query, SharedEpochChanges, ViableEpochDescriptor};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::{HeaderBackend, HeaderMetadata};
use sp_consensus_babe::{inherents::BabeInherentData, BabeApi, ConsensusLog, Slot, BABE_ENGINE_ID};
use sp_keystore::KeystorePtr;
use sp_runtime::{
traits::{Block as BlockT, Header},
DigestItem,
};
use sc_consensus_babe::{CompatibleDigestItem, PreDigest, SecondaryPlainPreDigest};
use sp_consensus_babe::inherents::BabeInherentData;
use sp_runtime::{traits::Block as BlockT, DigestItem};

#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("BABE inherent data missing")]
MissingInherent,

#[error("Failed to get BABE config")]
MissingConfig(#[source] sp_blockchain::Error),

#[error("Failed to get epoch descriptor: {0}")]
EpochDataQuery(String),

#[error("Failed to get viable epoch")]
NoViableEpoch,

#[error("Consensus error: {0}")]
Consensus(#[from] sp_consensus::Error),

#[error("{0}")]
Other(String),
}

impl From<Error> for sp_inherents::Error {
Expand All @@ -44,96 +15,21 @@ impl From<Error> for sp_inherents::Error {
}
}

impl From<Error> for sc_service::Error {
fn from(err: Error) -> Self {
sc_service::Error::Application(Box::new(err))
}
}

fn application_error(err: impl std::error::Error + Send + Sync + 'static) -> sp_inherents::Error {
sp_inherents::Error::Application(Box::new(err))
}

pub struct BabeConsensusDataProvider<B: BlockT, C> {
/// shared reference to keystore
keystore: KeystorePtr,

/// Shared reference to the client.
client: Arc<C>,

/// Shared epoch changes
epoch_changes: SharedEpochChanges<B, Epoch>,

/// BABE config, gotten from the runtime.
/// 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)>,
}

impl<B, C> BabeConsensusDataProvider<B, C>
where
B: BlockT,
C: AuxStore
+ ProvideRuntimeApi<B>
+ UsageProvider<B>
+ HeaderBackend<B>
+ HeaderMetadata<B, Error = sp_blockchain::Error>,
C::Api: BabeApi<B>,
{
pub fn new(
client: Arc<C>,
keystore: KeystorePtr,
epoch_changes: SharedEpochChanges<B, Epoch>,
authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
) -> Result<Self, Error> {
let config = sc_consensus_babe::configuration(&*client).map_err(Error::MissingConfig)?;
pub struct BabeConsensusDataProvider {}

Ok(Self {
client,
epoch_changes,
authorities,
keystore,
config,
})
}

fn epoch(&self, parent: &<B as BlockT>::Header, slot: Slot) -> Result<Epoch, Error> {
let epoch_changes = self.epoch_changes.shared_data();
let epoch_descriptor = epoch_changes
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
*parent.number(),
slot,
)
.map_err(|e| Error::EpochDataQuery(e.to_string()))?
.ok_or(Error::Consensus(sp_consensus::Error::InvalidAuthoritiesSet))?;

let epoch = epoch_changes
.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&self.config, slot))
.ok_or(Error::NoViableEpoch)?;

Ok(epoch.as_ref().clone())
impl BabeConsensusDataProvider {
pub fn new() -> Self {
Self {}
}
}

impl<B, C> ConsensusDataProvider<B> for BabeConsensusDataProvider<B, C>
impl<B> ConsensusDataProvider<B> for BabeConsensusDataProvider
where
B: BlockT,
C: AuxStore
+ ProvideRuntimeApi<B>
+ UsageProvider<B>
+ HeaderBackend<B>
+ HeaderMetadata<B, Error = sp_blockchain::Error>,
C::Api: BabeApi<B>,
{
fn create_digest(
&self,
parent: &<B as BlockT>::Header,
_parent: &<B as BlockT>::Header,
data: &sp_inherents::InherentData,
) -> Result<sp_runtime::Digest, sp_inherents::Error> {
let slot = data
Expand All @@ -142,65 +38,14 @@ where
Error::MissingInherent,
)))?;

let epoch = self
.epoch(parent, slot)
.map_err(|e| sp_inherents::Error::Application(Box::new(e)))?;

let logs =
if let Some((pre_digest, _authority_id)) = claim_slot(slot, &epoch, &self.keystore) {
vec![<DigestItem as CompatibleDigestItem>::babe_pre_digest(
pre_digest,
)]
} else {
// well we couldn't claim a slot because this is an existing chain and we're not in the
// authorities. we need to tell BabeBlockImport that the epoch has changed, and we put
// ourselves in the authorities.
let predigest = PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
slot,
authority_index: 0_u32,
});

let mut epoch_changes = self.epoch_changes.shared_data();
let epoch_descriptor = epoch_changes
.epoch_descriptor_for_child_of(
descendent_query(&*self.client),
&parent.hash(),
*parent.number(),
slot,
)
.map_err(|e| Error::Other(format!("failed to fetch epoch_descriptor: {}", e)))?
.ok_or(application_error(
sp_consensus::Error::InvalidAuthoritiesSet,
))?;

match epoch_descriptor {
ViableEpochDescriptor::Signaled(identifier, _epoch_header) => {
let epoch_mut = epoch_changes.epoch_mut(&identifier).ok_or(
sp_inherents::Error::Application(Box::new(
sp_consensus::Error::InvalidAuthoritiesSet,
)),
)?;

// mutate the current epoch
epoch_mut.authorities = self.authorities.clone();

let next_epoch = ConsensusLog::NextEpochData(NextEpochDescriptor {
authorities: self.authorities.clone(),
// copy the old randomness
randomness: epoch_mut.randomness,
});
let predigest = PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
slot,
authority_index: 0,
});

vec![
DigestItem::PreRuntime(BABE_ENGINE_ID, predigest.encode()),
DigestItem::Consensus(BABE_ENGINE_ID, next_epoch.encode()),
]
}
ViableEpochDescriptor::UnimportedGenesis(_) => {
// since this is the genesis, secondary predigest works for now.
vec![DigestItem::PreRuntime(BABE_ENGINE_ID, predigest.encode())]
}
}
};
let logs = vec![<DigestItem as CompatibleDigestItem>::babe_pre_digest(
predigest,
)];

Ok(sp_runtime::Digest { logs })
}
Expand Down
8 changes: 1 addition & 7 deletions node/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,6 @@ where
};
let select_chain = select_chain.clone();
let keystore = keystore_container.keystore();
let epoch_changes = babe_link.epoch_changes().clone();

let shared_authority_set = grandpa_link.shared_authority_set().clone();
let finality_provider = sc_consensus_grandpa::FinalityProofProvider::new_for_service(
Expand Down Expand Up @@ -536,12 +535,7 @@ where
forced_parent_hashes: None,
pending_create_inherent_data_providers,
pending_consensus_data_provider: Some(
crate::rpc::BabeConsensusDataProvider::new(
client.clone(),
keystore.clone(),
epoch_changes.clone(),
vec![],
)?,
crate::rpc::BabeConsensusDataProvider::new(),
),
};
let deps = crate::rpc::FullDeps {
Expand Down
75 changes: 69 additions & 6 deletions pallets/bridge/src/weights.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,85 @@

//! Autogenerated weights for `crate`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2024-01-04, STEPS: `50`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `github-runner-7401546037-attempt-3`, CPU: `AMD EPYC 7452 32-Core Processor`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024
// Executed Command:
// ./target/release/creditcoin3-node
// benchmark
// pallet
// --chain
// dev
// --steps=50
// --repeat=30
// --pallet
// crate
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=10000
// --output
// ./pallets/bridge/src/weights.rs

#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]

use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;
use core::marker::PhantomData;

/// Weight functions for `crate`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> crate::WeightInfo for WeightInfo<T> {
/// Storage: `Bridge::Authorities` (r:1 w:1)
/// Proof: `Bridge::Authorities` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`)
fn add_authority() -> Weight {
Weight::from_parts(1, 1)
// Proof Size summary in bytes:
// Measured: `6`
// Estimated: `3513`
// Minimum execution time: 11_101_000 picoseconds.
Weight::from_parts(11_500_000, 0)
.saturating_add(Weight::from_parts(0, 3513))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}

/// Storage: `Bridge::Authorities` (r:1 w:0)
/// Proof: `Bridge::Authorities` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`)
/// Storage: `Bridge::Collections` (r:1 w:1)
/// Proof: `Bridge::Collections` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`)
/// Storage: `Balances::TotalIssuance` (r:1 w:1)
/// Proof: `Balances::TotalIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`)
/// Storage: `System::Number` (r:1 w:0)
/// Proof: `System::Number` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`)
/// Storage: `System::ExecutionPhase` (r:1 w:0)
/// Proof: `System::ExecutionPhase` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`)
/// Storage: `System::EventCount` (r:1 w:1)
/// Proof: `System::EventCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`)
/// Storage: `System::Events` (r:1 w:1)
/// Proof: `System::Events` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
fn approve_collection() -> Weight {
Weight::from_parts(1, 1)
// Proof Size summary in bytes:
// Measured: `320`
// Estimated: `3533`
// Minimum execution time: 76_002_000 picoseconds.
Weight::from_parts(77_702_000, 0)
.saturating_add(Weight::from_parts(0, 3533))
.saturating_add(T::DbWeight::get().reads(7))
.saturating_add(T::DbWeight::get().writes(4))
}

/// Storage: `Bridge::Authorities` (r:1 w:1)
/// Proof: `Bridge::Authorities` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`)
fn remove_authority() -> Weight {
Weight::from_parts(1, 1)
// Proof Size summary in bytes:
// Measured: `79`
// Estimated: `3513`
// Minimum execution time: 13_800_000 picoseconds.
Weight::from_parts(14_201_000, 0)
.saturating_add(Weight::from_parts(0, 3513))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}

0 comments on commit 2909f8e

Please sign in to comment.