mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-15 04:31:08 +00:00
babe: replace usage of SharedEpochChanges with internal RPC (#13883)
* babe: replace usage of SharedEpochChanges with internal RPC * babe-rpc: fix tests * babe: use SinkExt::send instead of Sender::try_send SinkExt::send provides backpressure in case the channel is full * Update client/consensus/babe/src/lib.rs Co-authored-by: Bastian Köcher <git@kchr.de> * babe: fix spawn * babe: send handles backpressure * babe: use testing::TaskExecutor * babe-rpc: better error handling --------- Co-authored-by: Bastian Köcher <git@kchr.de>
This commit is contained in:
Generated
-1
@@ -5142,7 +5142,6 @@ dependencies = [
|
|||||||
"sc-client-api",
|
"sc-client-api",
|
||||||
"sc-consensus-babe",
|
"sc-consensus-babe",
|
||||||
"sc-consensus-babe-rpc",
|
"sc-consensus-babe-rpc",
|
||||||
"sc-consensus-epochs",
|
|
||||||
"sc-consensus-grandpa",
|
"sc-consensus-grandpa",
|
||||||
"sc-consensus-grandpa-rpc",
|
"sc-consensus-grandpa-rpc",
|
||||||
"sc-rpc",
|
"sc-rpc",
|
||||||
|
|||||||
@@ -203,7 +203,7 @@ pub fn new_partial(
|
|||||||
)?;
|
)?;
|
||||||
|
|
||||||
let slot_duration = babe_link.config().slot_duration();
|
let slot_duration = babe_link.config().slot_duration();
|
||||||
let import_queue = sc_consensus_babe::import_queue(
|
let (import_queue, babe_worker_handle) = sc_consensus_babe::import_queue(
|
||||||
babe_link.clone(),
|
babe_link.clone(),
|
||||||
block_import.clone(),
|
block_import.clone(),
|
||||||
Some(Box::new(justification_import)),
|
Some(Box::new(justification_import)),
|
||||||
@@ -228,7 +228,7 @@ pub fn new_partial(
|
|||||||
let import_setup = (block_import, grandpa_link, babe_link);
|
let import_setup = (block_import, grandpa_link, babe_link);
|
||||||
|
|
||||||
let (rpc_extensions_builder, rpc_setup) = {
|
let (rpc_extensions_builder, rpc_setup) = {
|
||||||
let (_, grandpa_link, babe_link) = &import_setup;
|
let (_, grandpa_link, _) = &import_setup;
|
||||||
|
|
||||||
let justification_stream = grandpa_link.justification_stream();
|
let justification_stream = grandpa_link.justification_stream();
|
||||||
let shared_authority_set = grandpa_link.shared_authority_set().clone();
|
let shared_authority_set = grandpa_link.shared_authority_set().clone();
|
||||||
@@ -240,9 +240,6 @@ pub fn new_partial(
|
|||||||
Some(shared_authority_set.clone()),
|
Some(shared_authority_set.clone()),
|
||||||
);
|
);
|
||||||
|
|
||||||
let babe_config = babe_link.config().clone();
|
|
||||||
let shared_epoch_changes = babe_link.epoch_changes().clone();
|
|
||||||
|
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
let pool = transaction_pool.clone();
|
let pool = transaction_pool.clone();
|
||||||
let select_chain = select_chain.clone();
|
let select_chain = select_chain.clone();
|
||||||
@@ -258,9 +255,8 @@ pub fn new_partial(
|
|||||||
chain_spec: chain_spec.cloned_box(),
|
chain_spec: chain_spec.cloned_box(),
|
||||||
deny_unsafe,
|
deny_unsafe,
|
||||||
babe: node_rpc::BabeDeps {
|
babe: node_rpc::BabeDeps {
|
||||||
babe_config: babe_config.clone(),
|
|
||||||
shared_epoch_changes: shared_epoch_changes.clone(),
|
|
||||||
keystore: keystore.clone(),
|
keystore: keystore.clone(),
|
||||||
|
babe_worker_handle: babe_worker_handle.clone(),
|
||||||
},
|
},
|
||||||
grandpa: node_rpc::GrandpaDeps {
|
grandpa: node_rpc::GrandpaDeps {
|
||||||
shared_voter_state: shared_voter_state.clone(),
|
shared_voter_state: shared_voter_state.clone(),
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" }
|
|||||||
sc-client-api = { version = "4.0.0-dev", path = "../../../client/api" }
|
sc-client-api = { version = "4.0.0-dev", path = "../../../client/api" }
|
||||||
sc-consensus-babe = { version = "0.10.0-dev", path = "../../../client/consensus/babe" }
|
sc-consensus-babe = { version = "0.10.0-dev", path = "../../../client/consensus/babe" }
|
||||||
sc-consensus-babe-rpc = { version = "0.10.0-dev", path = "../../../client/consensus/babe/rpc" }
|
sc-consensus-babe-rpc = { version = "0.10.0-dev", path = "../../../client/consensus/babe/rpc" }
|
||||||
sc-consensus-epochs = { version = "0.10.0-dev", path = "../../../client/consensus/epochs" }
|
|
||||||
sc-consensus-grandpa = { version = "0.10.0-dev", path = "../../../client/consensus/grandpa" }
|
sc-consensus-grandpa = { version = "0.10.0-dev", path = "../../../client/consensus/grandpa" }
|
||||||
sc-consensus-grandpa-rpc = { version = "0.10.0-dev", path = "../../../client/consensus/grandpa/rpc" }
|
sc-consensus-grandpa-rpc = { version = "0.10.0-dev", path = "../../../client/consensus/grandpa/rpc" }
|
||||||
sc-rpc = { version = "4.0.0-dev", path = "../../../client/rpc" }
|
sc-rpc = { version = "4.0.0-dev", path = "../../../client/rpc" }
|
||||||
|
|||||||
@@ -36,8 +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::{BabeConfiguration, Epoch};
|
use sc_consensus_babe::BabeWorkerHandle;
|
||||||
use sc_consensus_epochs::SharedEpochChanges;
|
|
||||||
use sc_consensus_grandpa::{
|
use sc_consensus_grandpa::{
|
||||||
FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,
|
FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,
|
||||||
};
|
};
|
||||||
@@ -53,10 +52,8 @@ use sp_keystore::KeystorePtr;
|
|||||||
|
|
||||||
/// Extra dependencies for BABE.
|
/// Extra dependencies for BABE.
|
||||||
pub struct BabeDeps {
|
pub struct BabeDeps {
|
||||||
/// BABE protocol config.
|
/// A handle to the BABE worker for issuing requests.
|
||||||
pub babe_config: BabeConfiguration,
|
pub babe_worker_handle: BabeWorkerHandle<Block>,
|
||||||
/// BABE pending epoch changes.
|
|
||||||
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.
|
||||||
pub keystore: KeystorePtr,
|
pub keystore: KeystorePtr,
|
||||||
}
|
}
|
||||||
@@ -130,7 +127,7 @@ where
|
|||||||
let mut io = RpcModule::new(());
|
let mut io = RpcModule::new(());
|
||||||
let FullDeps { client, pool, select_chain, chain_spec, deny_unsafe, babe, grandpa } = deps;
|
let FullDeps { client, pool, select_chain, chain_spec, deny_unsafe, babe, grandpa } = deps;
|
||||||
|
|
||||||
let BabeDeps { keystore, babe_config, shared_epoch_changes } = babe;
|
let BabeDeps { keystore, babe_worker_handle } = babe;
|
||||||
let GrandpaDeps {
|
let GrandpaDeps {
|
||||||
shared_voter_state,
|
shared_voter_state,
|
||||||
shared_authority_set,
|
shared_authority_set,
|
||||||
@@ -151,15 +148,8 @@ where
|
|||||||
io.merge(Mmr::new(client.clone()).into_rpc())?;
|
io.merge(Mmr::new(client.clone()).into_rpc())?;
|
||||||
io.merge(TransactionPayment::new(client.clone()).into_rpc())?;
|
io.merge(TransactionPayment::new(client.clone()).into_rpc())?;
|
||||||
io.merge(
|
io.merge(
|
||||||
Babe::new(
|
Babe::new(client.clone(), babe_worker_handle.clone(), keystore, select_chain, deny_unsafe)
|
||||||
client.clone(),
|
.into_rpc(),
|
||||||
shared_epoch_changes.clone(),
|
|
||||||
keystore,
|
|
||||||
babe_config,
|
|
||||||
select_chain,
|
|
||||||
deny_unsafe,
|
|
||||||
)
|
|
||||||
.into_rpc(),
|
|
||||||
)?;
|
)?;
|
||||||
io.merge(
|
io.merge(
|
||||||
Grandpa::new(
|
Grandpa::new(
|
||||||
@@ -173,7 +163,7 @@ where
|
|||||||
)?;
|
)?;
|
||||||
|
|
||||||
io.merge(
|
io.merge(
|
||||||
SyncState::new(chain_spec, client.clone(), shared_authority_set, shared_epoch_changes)?
|
SyncState::new(chain_spec, client.clone(), shared_authority_set, babe_worker_handle)?
|
||||||
.into_rpc(),
|
.into_rpc(),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
|||||||
@@ -18,28 +18,29 @@
|
|||||||
|
|
||||||
//! RPC api for babe.
|
//! RPC api for babe.
|
||||||
|
|
||||||
|
use std::{collections::HashMap, sync::Arc};
|
||||||
|
|
||||||
use futures::TryFutureExt;
|
use futures::TryFutureExt;
|
||||||
use jsonrpsee::{
|
use jsonrpsee::{
|
||||||
core::{async_trait, Error as JsonRpseeError, RpcResult},
|
core::{async_trait, Error as JsonRpseeError, RpcResult},
|
||||||
proc_macros::rpc,
|
proc_macros::rpc,
|
||||||
types::{error::CallError, ErrorObject},
|
types::{error::CallError, ErrorObject},
|
||||||
};
|
};
|
||||||
|
|
||||||
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};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use sc_consensus_babe::{authorship, BabeWorkerHandle};
|
||||||
|
use sc_consensus_epochs::Epoch as EpochT;
|
||||||
|
use sc_rpc_api::DenyUnsafe;
|
||||||
use sp_api::ProvideRuntimeApi;
|
use sp_api::ProvideRuntimeApi;
|
||||||
use sp_application_crypto::AppCrypto;
|
use sp_application_crypto::AppCrypto;
|
||||||
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::{
|
use sp_consensus_babe::{digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi};
|
||||||
digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi, BabeConfiguration,
|
|
||||||
};
|
|
||||||
use sp_core::crypto::ByteArray;
|
use sp_core::crypto::ByteArray;
|
||||||
use sp_keystore::KeystorePtr;
|
use sp_keystore::KeystorePtr;
|
||||||
use sp_runtime::traits::{Block as BlockT, Header as _};
|
use sp_runtime::traits::{Block as BlockT, Header as _};
|
||||||
use std::{collections::HashMap, sync::Arc};
|
|
||||||
|
const BABE_ERROR: i32 = 9000;
|
||||||
|
|
||||||
/// Provides rpc methods for interacting with Babe.
|
/// Provides rpc methods for interacting with Babe.
|
||||||
#[rpc(client, server)]
|
#[rpc(client, server)]
|
||||||
@@ -54,12 +55,10 @@ pub trait BabeApi {
|
|||||||
pub struct Babe<B: BlockT, C, SC> {
|
pub struct Babe<B: BlockT, C, SC> {
|
||||||
/// shared reference to the client.
|
/// shared reference to the client.
|
||||||
client: Arc<C>,
|
client: Arc<C>,
|
||||||
/// shared reference to EpochChanges
|
/// A handle to the BABE worker for issuing requests.
|
||||||
shared_epoch_changes: SharedEpochChanges<B, Epoch>,
|
babe_worker_handle: BabeWorkerHandle<B>,
|
||||||
/// shared reference to the Keystore
|
/// shared reference to the Keystore
|
||||||
keystore: KeystorePtr,
|
keystore: KeystorePtr,
|
||||||
/// config (actually holds the slot duration)
|
|
||||||
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,13 +69,12 @@ impl<B: BlockT, C, SC> Babe<B, C, SC> {
|
|||||||
/// Creates a new instance of the Babe Rpc handler.
|
/// Creates a new instance of the Babe Rpc handler.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
client: Arc<C>,
|
client: Arc<C>,
|
||||||
shared_epoch_changes: SharedEpochChanges<B, Epoch>,
|
babe_worker_handle: BabeWorkerHandle<B>,
|
||||||
keystore: KeystorePtr,
|
keystore: KeystorePtr,
|
||||||
babe_config: BabeConfiguration,
|
|
||||||
select_chain: SC,
|
select_chain: SC,
|
||||||
deny_unsafe: DenyUnsafe,
|
deny_unsafe: DenyUnsafe,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self { client, shared_epoch_changes, keystore, babe_config, select_chain, deny_unsafe }
|
Self { client, babe_worker_handle, keystore, select_chain, deny_unsafe }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,21 +91,21 @@ where
|
|||||||
{
|
{
|
||||||
async fn epoch_authorship(&self) -> RpcResult<HashMap<AuthorityId, EpochAuthorship>> {
|
async fn epoch_authorship(&self) -> RpcResult<HashMap<AuthorityId, EpochAuthorship>> {
|
||||||
self.deny_unsafe.check_if_safe()?;
|
self.deny_unsafe.check_if_safe()?;
|
||||||
let header = self.select_chain.best_chain().map_err(Error::Consensus).await?;
|
|
||||||
|
let best_header = self.select_chain.best_chain().map_err(Error::SelectChain).await?;
|
||||||
|
|
||||||
let epoch_start = self
|
let epoch_start = self
|
||||||
.client
|
.client
|
||||||
.runtime_api()
|
.runtime_api()
|
||||||
.current_epoch_start(header.hash())
|
.current_epoch_start(best_header.hash())
|
||||||
.map_err(|err| Error::StringError(format!("{:?}", err)))?;
|
.map_err(|_| Error::FetchEpoch)?;
|
||||||
|
|
||||||
|
let epoch = self
|
||||||
|
.babe_worker_handle
|
||||||
|
.epoch_data_for_child_of(best_header.hash(), *best_header.number(), epoch_start)
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::FetchEpoch)?;
|
||||||
|
|
||||||
let epoch = epoch_data(
|
|
||||||
&self.shared_epoch_changes,
|
|
||||||
&self.client,
|
|
||||||
&self.babe_config,
|
|
||||||
*epoch_start,
|
|
||||||
&self.select_chain,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let (epoch_start, epoch_end) = (epoch.start_slot(), epoch.end_slot());
|
let (epoch_start, epoch_end) = (epoch.start_slot(), epoch.end_slot());
|
||||||
let mut claims: HashMap<AuthorityId, EpochAuthorship> = HashMap::new();
|
let mut claims: HashMap<AuthorityId, EpochAuthorship> = HashMap::new();
|
||||||
|
|
||||||
@@ -159,59 +157,37 @@ pub struct EpochAuthorship {
|
|||||||
secondary_vrf: Vec<u64>,
|
secondary_vrf: Vec<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Errors encountered by the RPC
|
/// Top-level error type for the RPC handler.
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// Consensus error
|
/// Failed to fetch the current best header.
|
||||||
#[error(transparent)]
|
#[error("Failed to fetch the current best header: {0}")]
|
||||||
Consensus(#[from] ConsensusError),
|
SelectChain(ConsensusError),
|
||||||
/// Errors that can be formatted as a String
|
/// Failed to fetch epoch data.
|
||||||
#[error("{0}")]
|
#[error("Failed to fetch epoch data")]
|
||||||
StringError(String),
|
FetchEpoch,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Error> for JsonRpseeError {
|
impl From<Error> for JsonRpseeError {
|
||||||
fn from(error: Error) -> Self {
|
fn from(error: Error) -> Self {
|
||||||
|
let error_code = match error {
|
||||||
|
Error::SelectChain(_) => 1,
|
||||||
|
Error::FetchEpoch => 2,
|
||||||
|
};
|
||||||
|
|
||||||
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
|
JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
|
||||||
1234,
|
BABE_ERROR + error_code,
|
||||||
error.to_string(),
|
error.to_string(),
|
||||||
None::<()>,
|
Some(format!("{:?}", error)),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetches the epoch data for a given slot.
|
|
||||||
async fn epoch_data<B, C, SC>(
|
|
||||||
epoch_changes: &SharedEpochChanges<B, Epoch>,
|
|
||||||
client: &Arc<C>,
|
|
||||||
babe_config: &BabeConfiguration,
|
|
||||||
slot: u64,
|
|
||||||
select_chain: &SC,
|
|
||||||
) -> Result<Epoch, Error>
|
|
||||||
where
|
|
||||||
B: BlockT,
|
|
||||||
C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,
|
|
||||||
SC: SelectChain<B>,
|
|
||||||
{
|
|
||||||
let parent = select_chain.best_chain().await?;
|
|
||||||
epoch_changes
|
|
||||||
.shared_data()
|
|
||||||
.epoch_data_for_child_of(
|
|
||||||
descendent_query(&**client),
|
|
||||||
&parent.hash(),
|
|
||||||
*parent.number(),
|
|
||||||
slot.into(),
|
|
||||||
|slot| Epoch::genesis(babe_config, slot),
|
|
||||||
)
|
|
||||||
.map_err(|e| Error::Consensus(ConsensusError::ChainLookup(e.to_string())))?
|
|
||||||
.ok_or(Error::Consensus(ConsensusError::InvalidAuthoritiesSet))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use sc_consensus_babe::block_import;
|
use sp_consensus_babe::inherents::InherentDataProvider;
|
||||||
use sp_core::crypto::key_types::BABE;
|
use sp_core::{crypto::key_types::BABE, testing::TaskExecutor};
|
||||||
use sp_keyring::Sr25519Keyring;
|
use sp_keyring::Sr25519Keyring;
|
||||||
use sp_keystore::{testing::MemoryKeystore, Keystore};
|
use sp_keystore::{testing::MemoryKeystore, Keystore};
|
||||||
use substrate_test_runtime_client::{
|
use substrate_test_runtime_client::{
|
||||||
@@ -233,14 +209,35 @@ 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 = sc_consensus_babe::configuration(&*client).expect("config available");
|
let task_executor = TaskExecutor::new();
|
||||||
let (_, link) = block_import(config.clone(), client.clone(), client.clone())
|
|
||||||
.expect("can initialize block-import");
|
|
||||||
|
|
||||||
let epoch_changes = link.epoch_changes().clone();
|
|
||||||
let keystore = create_keystore(Sr25519Keyring::Alice);
|
let keystore = create_keystore(Sr25519Keyring::Alice);
|
||||||
|
|
||||||
Babe::new(client.clone(), epoch_changes, keystore, config, longest_chain, deny_unsafe)
|
let config = sc_consensus_babe::configuration(&*client).expect("config available");
|
||||||
|
let slot_duration = config.slot_duration();
|
||||||
|
|
||||||
|
let (block_import, link) =
|
||||||
|
sc_consensus_babe::block_import(config.clone(), client.clone(), client.clone())
|
||||||
|
.expect("can initialize block-import");
|
||||||
|
|
||||||
|
let (_, babe_worker_handle) = sc_consensus_babe::import_queue(
|
||||||
|
link.clone(),
|
||||||
|
block_import.clone(),
|
||||||
|
None,
|
||||||
|
client.clone(),
|
||||||
|
longest_chain.clone(),
|
||||||
|
move |_, _| async move {
|
||||||
|
Ok((InherentDataProvider::from_timestamp_and_slot_duration(
|
||||||
|
0.into(),
|
||||||
|
slot_duration,
|
||||||
|
),))
|
||||||
|
},
|
||||||
|
&task_executor,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Babe::new(client.clone(), babe_worker_handle, keystore, longest_chain, deny_unsafe)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -89,8 +89,8 @@ use prometheus_endpoint::Registry;
|
|||||||
use schnorrkel::SignatureError;
|
use schnorrkel::SignatureError;
|
||||||
|
|
||||||
use sc_client_api::{
|
use sc_client_api::{
|
||||||
backend::AuxStore, AuxDataOperations, Backend as BackendT, BlockchainEvents,
|
backend::AuxStore, AuxDataOperations, Backend as BackendT, FinalityNotification,
|
||||||
FinalityNotification, PreCommitActions, ProvideUncles, UsageProvider,
|
PreCommitActions, UsageProvider,
|
||||||
};
|
};
|
||||||
use sc_consensus::{
|
use sc_consensus::{
|
||||||
block_import::{
|
block_import::{
|
||||||
@@ -338,6 +338,9 @@ pub enum Error<B: BlockT> {
|
|||||||
/// Create inherents error.
|
/// Create inherents error.
|
||||||
#[error("Creating inherents failed: {0}")]
|
#[error("Creating inherents failed: {0}")]
|
||||||
CreateInherents(sp_inherents::Error),
|
CreateInherents(sp_inherents::Error),
|
||||||
|
/// Background worker is not running and therefore requests cannot be answered.
|
||||||
|
#[error("Background worker is not running")]
|
||||||
|
BackgroundWorkerTerminated,
|
||||||
/// Client error
|
/// Client error
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Client(sp_blockchain::Error),
|
Client(sp_blockchain::Error),
|
||||||
@@ -475,9 +478,6 @@ pub fn start_babe<B, C, SC, E, I, SO, CIDP, BS, L, Error>(
|
|||||||
where
|
where
|
||||||
B: BlockT,
|
B: BlockT,
|
||||||
C: ProvideRuntimeApi<B>
|
C: ProvideRuntimeApi<B>
|
||||||
+ ProvideUncles<B>
|
|
||||||
+ BlockchainEvents<B>
|
|
||||||
+ PreCommitActions<B>
|
|
||||||
+ HeaderBackend<B>
|
+ HeaderBackend<B>
|
||||||
+ HeaderMetadata<B, Error = ClientError>
|
+ HeaderMetadata<B, Error = ClientError>
|
||||||
+ Send
|
+ Send
|
||||||
@@ -498,8 +498,6 @@ where
|
|||||||
BS: BackoffAuthoringBlocksStrategy<NumberFor<B>> + Send + Sync + 'static,
|
BS: BackoffAuthoringBlocksStrategy<NumberFor<B>> + Send + Sync + 'static,
|
||||||
Error: std::error::Error + Send + From<ConsensusError> + From<I::Error> + 'static,
|
Error: std::error::Error + Send + From<ConsensusError> + From<I::Error> + 'static,
|
||||||
{
|
{
|
||||||
const HANDLE_BUFFER_SIZE: usize = 1024;
|
|
||||||
|
|
||||||
let slot_notification_sinks = Arc::new(Mutex::new(Vec::new()));
|
let slot_notification_sinks = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
|
||||||
let worker = BabeSlotWorker {
|
let worker = BabeSlotWorker {
|
||||||
@@ -529,17 +527,7 @@ where
|
|||||||
create_inherent_data_providers,
|
create_inherent_data_providers,
|
||||||
);
|
);
|
||||||
|
|
||||||
let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE);
|
Ok(BabeWorker { inner: Box::pin(slot_worker), slot_notification_sinks })
|
||||||
|
|
||||||
let answer_requests =
|
|
||||||
answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes);
|
|
||||||
|
|
||||||
let inner = future::select(Box::pin(slot_worker), Box::pin(answer_requests));
|
|
||||||
Ok(BabeWorker {
|
|
||||||
inner: Box::pin(inner.map(|_| ())),
|
|
||||||
slot_notification_sinks,
|
|
||||||
handle: BabeWorkerHandle(worker_tx),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove obsolete block's weight data by leveraging finality notifications.
|
// Remove obsolete block's weight data by leveraging finality notifications.
|
||||||
@@ -593,42 +581,26 @@ async fn answer_requests<B: BlockT, C>(
|
|||||||
client: Arc<C>,
|
client: Arc<C>,
|
||||||
epoch_changes: SharedEpochChanges<B, Epoch>,
|
epoch_changes: SharedEpochChanges<B, Epoch>,
|
||||||
) where
|
) where
|
||||||
C: ProvideRuntimeApi<B>
|
C: HeaderBackend<B> + HeaderMetadata<B, Error = ClientError>,
|
||||||
+ ProvideUncles<B>
|
|
||||||
+ BlockchainEvents<B>
|
|
||||||
+ HeaderBackend<B>
|
|
||||||
+ HeaderMetadata<B, Error = ClientError>
|
|
||||||
+ Send
|
|
||||||
+ Sync
|
|
||||||
+ 'static,
|
|
||||||
{
|
{
|
||||||
while let Some(request) = request_rx.next().await {
|
while let Some(request) = request_rx.next().await {
|
||||||
match request {
|
match request {
|
||||||
BabeRequest::EpochForChild(parent_hash, parent_number, slot_number, response) => {
|
BabeRequest::EpochData(response) => {
|
||||||
|
let _ = response.send(epoch_changes.shared_data().clone());
|
||||||
|
},
|
||||||
|
BabeRequest::EpochDataForChildOf(parent_hash, parent_number, slot, response) => {
|
||||||
let lookup = || {
|
let lookup = || {
|
||||||
let epoch_changes = epoch_changes.shared_data();
|
let epoch_changes = epoch_changes.shared_data();
|
||||||
let epoch_descriptor = epoch_changes
|
epoch_changes
|
||||||
.epoch_descriptor_for_child_of(
|
.epoch_data_for_child_of(
|
||||||
descendent_query(&*client),
|
descendent_query(&*client),
|
||||||
&parent_hash,
|
&parent_hash,
|
||||||
parent_number,
|
parent_number,
|
||||||
slot_number,
|
slot,
|
||||||
|
|slot| Epoch::genesis(&config, slot),
|
||||||
)
|
)
|
||||||
.map_err(|e| Error::<B>::ForkTree(Box::new(e)))?
|
.map_err(|e| Error::<B>::ForkTree(Box::new(e)))?
|
||||||
.ok_or(Error::<B>::FetchEpoch(parent_hash))?;
|
.ok_or(Error::<B>::FetchEpoch(parent_hash))
|
||||||
|
|
||||||
let viable_epoch = epoch_changes
|
|
||||||
.viable_epoch(&epoch_descriptor, |slot| Epoch::genesis(&config, slot))
|
|
||||||
.ok_or(Error::<B>::FetchEpoch(parent_hash))?;
|
|
||||||
|
|
||||||
Ok(sp_consensus_babe::Epoch {
|
|
||||||
epoch_index: viable_epoch.as_ref().epoch_index,
|
|
||||||
start_slot: viable_epoch.as_ref().start_slot,
|
|
||||||
duration: viable_epoch.as_ref().duration,
|
|
||||||
authorities: viable_epoch.as_ref().authorities.clone(),
|
|
||||||
randomness: viable_epoch.as_ref().randomness,
|
|
||||||
config: viable_epoch.as_ref().config.clone(),
|
|
||||||
})
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let _ = response.send(lookup());
|
let _ = response.send(lookup());
|
||||||
@@ -638,17 +610,13 @@ async fn answer_requests<B: BlockT, C>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Requests to the BABE service.
|
/// Requests to the BABE service.
|
||||||
#[non_exhaustive]
|
enum BabeRequest<B: BlockT> {
|
||||||
pub enum BabeRequest<B: BlockT> {
|
/// Request all available epoch data.
|
||||||
|
EpochData(oneshot::Sender<EpochChangesFor<B, Epoch>>),
|
||||||
/// Request the epoch that a child of the given block, with the given slot number would have.
|
/// Request the epoch that a child of the given block, with the given slot number would have.
|
||||||
///
|
///
|
||||||
/// The parent block is identified by its hash and number.
|
/// The parent block is identified by its hash and number.
|
||||||
EpochForChild(
|
EpochDataForChildOf(B::Hash, NumberFor<B>, Slot, oneshot::Sender<Result<Epoch, Error<B>>>),
|
||||||
B::Hash,
|
|
||||||
NumberFor<B>,
|
|
||||||
Slot,
|
|
||||||
oneshot::Sender<Result<sp_consensus_babe::Epoch, Error<B>>>,
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A handle to the BABE worker for issuing requests.
|
/// A handle to the BABE worker for issuing requests.
|
||||||
@@ -656,11 +624,41 @@ pub enum BabeRequest<B: BlockT> {
|
|||||||
pub struct BabeWorkerHandle<B: BlockT>(Sender<BabeRequest<B>>);
|
pub struct BabeWorkerHandle<B: BlockT>(Sender<BabeRequest<B>>);
|
||||||
|
|
||||||
impl<B: BlockT> BabeWorkerHandle<B> {
|
impl<B: BlockT> BabeWorkerHandle<B> {
|
||||||
/// Send a request to the BABE service.
|
async fn send_request(&self, request: BabeRequest<B>) -> Result<(), Error<B>> {
|
||||||
pub async fn send(&mut self, request: BabeRequest<B>) {
|
match self.0.clone().send(request).await {
|
||||||
// Failure to send means that the service is down.
|
Err(err) if err.is_disconnected() => return Err(Error::BackgroundWorkerTerminated),
|
||||||
// This will manifest as the receiver of the request being dropped.
|
Err(err) => warn!(
|
||||||
let _ = self.0.send(request).await;
|
target: LOG_TARGET,
|
||||||
|
"Unhandled error when sending request to worker: {:?}", err
|
||||||
|
),
|
||||||
|
_ => {},
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch all available epoch data.
|
||||||
|
pub async fn epoch_data(&self) -> Result<EpochChangesFor<B, Epoch>, Error<B>> {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.send_request(BabeRequest::EpochData(tx)).await?;
|
||||||
|
|
||||||
|
rx.await.or(Err(Error::BackgroundWorkerTerminated))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch the epoch that a child of the given block, with the given slot number would have.
|
||||||
|
///
|
||||||
|
/// The parent block is identified by its hash and number.
|
||||||
|
pub async fn epoch_data_for_child_of(
|
||||||
|
&self,
|
||||||
|
parent_hash: B::Hash,
|
||||||
|
parent_number: NumberFor<B>,
|
||||||
|
slot: Slot,
|
||||||
|
) -> Result<Epoch, Error<B>> {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.send_request(BabeRequest::EpochDataForChildOf(parent_hash, parent_number, slot, tx))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
rx.await.or(Err(Error::BackgroundWorkerTerminated))?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -669,7 +667,6 @@ impl<B: BlockT> BabeWorkerHandle<B> {
|
|||||||
pub struct BabeWorker<B: BlockT> {
|
pub struct BabeWorker<B: BlockT> {
|
||||||
inner: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
|
inner: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
|
||||||
slot_notification_sinks: SlotNotificationSinks<B>,
|
slot_notification_sinks: SlotNotificationSinks<B>,
|
||||||
handle: BabeWorkerHandle<B>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<B: BlockT> BabeWorker<B> {
|
impl<B: BlockT> BabeWorker<B> {
|
||||||
@@ -684,11 +681,6 @@ impl<B: BlockT> BabeWorker<B> {
|
|||||||
self.slot_notification_sinks.lock().push(sink);
|
self.slot_notification_sinks.lock().push(sink);
|
||||||
stream
|
stream
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a handle to the worker.
|
|
||||||
pub fn handle(&self) -> BabeWorkerHandle<B> {
|
|
||||||
self.handle.clone()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<B: BlockT> Future for BabeWorker<B> {
|
impl<B: BlockT> Future for BabeWorker<B> {
|
||||||
@@ -1790,7 +1782,7 @@ pub fn import_queue<Block: BlockT, Client, SelectChain, Inner, CIDP>(
|
|||||||
spawner: &impl sp_core::traits::SpawnEssentialNamed,
|
spawner: &impl sp_core::traits::SpawnEssentialNamed,
|
||||||
registry: Option<&Registry>,
|
registry: Option<&Registry>,
|
||||||
telemetry: Option<TelemetryHandle>,
|
telemetry: Option<TelemetryHandle>,
|
||||||
) -> ClientResult<DefaultImportQueue<Block, Client>>
|
) -> ClientResult<(DefaultImportQueue<Block, Client>, BabeWorkerHandle<Block>)>
|
||||||
where
|
where
|
||||||
Inner: BlockImport<
|
Inner: BlockImport<
|
||||||
Block,
|
Block,
|
||||||
@@ -1811,16 +1803,28 @@ where
|
|||||||
CIDP: CreateInherentDataProviders<Block, ()> + Send + Sync + 'static,
|
CIDP: CreateInherentDataProviders<Block, ()> + Send + Sync + 'static,
|
||||||
CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync,
|
CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync,
|
||||||
{
|
{
|
||||||
|
const HANDLE_BUFFER_SIZE: usize = 1024;
|
||||||
|
|
||||||
let verifier = BabeVerifier {
|
let verifier = BabeVerifier {
|
||||||
select_chain,
|
select_chain,
|
||||||
create_inherent_data_providers,
|
create_inherent_data_providers,
|
||||||
config: babe_link.config,
|
config: babe_link.config.clone(),
|
||||||
epoch_changes: babe_link.epoch_changes,
|
epoch_changes: babe_link.epoch_changes.clone(),
|
||||||
telemetry,
|
telemetry,
|
||||||
client,
|
client: client.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(BasicQueue::new(verifier, Box::new(block_import), justification_import, spawner, registry))
|
let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE);
|
||||||
|
|
||||||
|
let answer_requests =
|
||||||
|
answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes);
|
||||||
|
|
||||||
|
spawner.spawn_essential("babe-worker", Some("babe"), answer_requests.boxed());
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
BasicQueue::new(verifier, Box::new(block_import), justification_import, spawner, registry),
|
||||||
|
BabeWorkerHandle(worker_tx),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reverts protocol aux data to at most the last finalized block.
|
/// Reverts protocol aux data to at most the last finalized block.
|
||||||
|
|||||||
@@ -41,20 +41,21 @@
|
|||||||
|
|
||||||
#![deny(unused_crate_dependencies)]
|
#![deny(unused_crate_dependencies)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use jsonrpsee::{
|
use jsonrpsee::{
|
||||||
core::{Error as JsonRpseeError, RpcResult},
|
core::{async_trait, Error as JsonRpseeError, RpcResult},
|
||||||
proc_macros::rpc,
|
proc_macros::rpc,
|
||||||
types::{error::CallError, ErrorObject},
|
types::{error::CallError, ErrorObject},
|
||||||
};
|
};
|
||||||
|
|
||||||
use sc_client_api::StorageData;
|
use sc_client_api::StorageData;
|
||||||
|
use sc_consensus_babe::{BabeWorkerHandle, Error as BabeError};
|
||||||
use sp_blockchain::HeaderBackend;
|
use sp_blockchain::HeaderBackend;
|
||||||
use sp_runtime::traits::{Block as BlockT, NumberFor};
|
use sp_runtime::traits::{Block as BlockT, NumberFor};
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
type SharedAuthoritySet<TBl> =
|
type SharedAuthoritySet<TBl> =
|
||||||
sc_consensus_grandpa::SharedAuthoritySet<<TBl as BlockT>::Hash, NumberFor<TBl>>;
|
sc_consensus_grandpa::SharedAuthoritySet<<TBl as BlockT>::Hash, NumberFor<TBl>>;
|
||||||
type SharedEpochChanges<TBl> =
|
|
||||||
sc_consensus_epochs::SharedEpochChanges<TBl, sc_consensus_babe::Epoch>;
|
|
||||||
|
|
||||||
/// Error type used by this crate.
|
/// Error type used by this crate.
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
@@ -66,6 +67,9 @@ pub enum Error<Block: BlockT> {
|
|||||||
#[error("Failed to load the block weight for block {0:?}")]
|
#[error("Failed to load the block weight for block {0:?}")]
|
||||||
LoadingBlockWeightFailed(Block::Hash),
|
LoadingBlockWeightFailed(Block::Hash),
|
||||||
|
|
||||||
|
#[error("Failed to load the BABE epoch data: {0}")]
|
||||||
|
LoadingEpochDataFailed(BabeError<Block>),
|
||||||
|
|
||||||
#[error("JsonRpc error: {0}")]
|
#[error("JsonRpc error: {0}")]
|
||||||
JsonRpc(String),
|
JsonRpc(String),
|
||||||
|
|
||||||
@@ -125,7 +129,7 @@ pub struct LightSyncState<Block: BlockT> {
|
|||||||
pub trait SyncStateApi {
|
pub trait SyncStateApi {
|
||||||
/// Returns the JSON serialized chainspec running the node, with a sync state.
|
/// Returns the JSON serialized chainspec running the node, with a sync state.
|
||||||
#[method(name = "sync_state_genSyncSpec")]
|
#[method(name = "sync_state_genSyncSpec")]
|
||||||
fn system_gen_sync_spec(&self, raw: bool) -> RpcResult<serde_json::Value>;
|
async fn system_gen_sync_spec(&self, raw: bool) -> RpcResult<serde_json::Value>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An api for sync state RPC calls.
|
/// An api for sync state RPC calls.
|
||||||
@@ -133,7 +137,7 @@ pub struct SyncState<Block: BlockT, Client> {
|
|||||||
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
|
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
|
||||||
client: Arc<Client>,
|
client: Arc<Client>,
|
||||||
shared_authority_set: SharedAuthoritySet<Block>,
|
shared_authority_set: SharedAuthoritySet<Block>,
|
||||||
shared_epoch_changes: SharedEpochChanges<Block>,
|
babe_worker_handle: BabeWorkerHandle<Block>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Block, Client> SyncState<Block, Client>
|
impl<Block, Client> SyncState<Block, Client>
|
||||||
@@ -146,18 +150,24 @@ where
|
|||||||
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
|
chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
|
||||||
client: Arc<Client>,
|
client: Arc<Client>,
|
||||||
shared_authority_set: SharedAuthoritySet<Block>,
|
shared_authority_set: SharedAuthoritySet<Block>,
|
||||||
shared_epoch_changes: SharedEpochChanges<Block>,
|
babe_worker_handle: BabeWorkerHandle<Block>,
|
||||||
) -> Result<Self, Error<Block>> {
|
) -> Result<Self, Error<Block>> {
|
||||||
if sc_chain_spec::get_extension::<LightSyncStateExtension>(chain_spec.extensions())
|
if sc_chain_spec::get_extension::<LightSyncStateExtension>(chain_spec.extensions())
|
||||||
.is_some()
|
.is_some()
|
||||||
{
|
{
|
||||||
Ok(Self { chain_spec, client, shared_authority_set, shared_epoch_changes })
|
Ok(Self { chain_spec, client, shared_authority_set, babe_worker_handle })
|
||||||
} else {
|
} else {
|
||||||
Err(Error::<Block>::LightSyncStateExtensionNotFound)
|
Err(Error::<Block>::LightSyncStateExtensionNotFound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_sync_state(&self) -> Result<LightSyncState<Block>, Error<Block>> {
|
async fn build_sync_state(&self) -> Result<LightSyncState<Block>, Error<Block>> {
|
||||||
|
let epoch_changes = self
|
||||||
|
.babe_worker_handle
|
||||||
|
.epoch_data()
|
||||||
|
.await
|
||||||
|
.map_err(Error::LoadingEpochDataFailed)?;
|
||||||
|
|
||||||
let finalized_hash = self.client.info().finalized_hash;
|
let finalized_hash = self.client.info().finalized_hash;
|
||||||
let finalized_header = self
|
let finalized_header = self
|
||||||
.client
|
.client
|
||||||
@@ -170,20 +180,21 @@ where
|
|||||||
|
|
||||||
Ok(LightSyncState {
|
Ok(LightSyncState {
|
||||||
finalized_block_header: finalized_header,
|
finalized_block_header: finalized_header,
|
||||||
babe_epoch_changes: self.shared_epoch_changes.shared_data().clone(),
|
babe_epoch_changes: epoch_changes,
|
||||||
babe_finalized_block_weight: finalized_block_weight,
|
babe_finalized_block_weight: finalized_block_weight,
|
||||||
grandpa_authority_set: self.shared_authority_set.clone_inner(),
|
grandpa_authority_set: self.shared_authority_set.clone_inner(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
impl<Block, Backend> SyncStateApiServer for SyncState<Block, Backend>
|
impl<Block, Backend> SyncStateApiServer for SyncState<Block, Backend>
|
||||||
where
|
where
|
||||||
Block: BlockT,
|
Block: BlockT,
|
||||||
Backend: HeaderBackend<Block> + sc_client_api::AuxStore + 'static,
|
Backend: HeaderBackend<Block> + sc_client_api::AuxStore + 'static,
|
||||||
{
|
{
|
||||||
fn system_gen_sync_spec(&self, raw: bool) -> RpcResult<serde_json::Value> {
|
async fn system_gen_sync_spec(&self, raw: bool) -> RpcResult<serde_json::Value> {
|
||||||
let current_sync_state = self.build_sync_state()?;
|
let current_sync_state = self.build_sync_state().await?;
|
||||||
let mut chain_spec = self.chain_spec.cloned_box();
|
let mut chain_spec = self.chain_spec.cloned_box();
|
||||||
|
|
||||||
let extension = sc_chain_spec::get_extension_mut::<LightSyncStateExtension>(
|
let extension = sc_chain_spec::get_extension_mut::<LightSyncStateExtension>(
|
||||||
|
|||||||
Reference in New Issue
Block a user