Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Remove HeaderBackend from RelayChainRPCClient #2385

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 10 additions & 68 deletions client/relay-chain-minimal-node/src/blockchain_rpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@ use std::pin::Pin;

use cumulus_relay_chain_interface::{RelayChainError, RelayChainResult};
use cumulus_relay_chain_rpc_interface::RelayChainRpcClient;
use futures::{Future, Stream, StreamExt};
use futures::{Stream, StreamExt};
use polkadot_core_primitives::{Block, BlockNumber, Hash, Header};
use polkadot_overseer::RuntimeApiSubsystemClient;
use sc_authority_discovery::AuthorityDiscovery;
use sc_authority_discovery::{AuthorityDiscovery, Error as AuthorityDiscoveryError};
use sp_api::{ApiError, RuntimeApiInfo};
use sp_blockchain::{HeaderBackend, Info};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};

#[derive(Clone)]
pub struct BlockChainRpcClient {
Expand Down Expand Up @@ -312,6 +310,14 @@ impl AuthorityDiscovery<Block> for BlockChainRpcClient {
let result = self.rpc_client.authority_discovery_authorities(at).await?;
Ok(result)
}

async fn best_hash(&self) -> std::result::Result<Hash, AuthorityDiscoveryError> {
self.block_get_hash(None)
.await
.ok()
.flatten()
.ok_or_else(|| AuthorityDiscoveryError::BestBlockFetchingError)
}
}

impl BlockChainRpcClient {
Expand All @@ -327,67 +333,3 @@ impl BlockChainRpcClient {
Ok(self.rpc_client.get_finalized_heads_stream()?.boxed())
}
}

fn block_local<T>(fut: impl Future<Output = T>) -> T {
let tokio_handle = tokio::runtime::Handle::current();
tokio::task::block_in_place(|| tokio_handle.block_on(fut))
}

impl HeaderBackend<Block> for BlockChainRpcClient {
fn header(
&self,
hash: <Block as BlockT>::Hash,
) -> sp_blockchain::Result<Option<<Block as BlockT>::Header>> {
Ok(block_local(self.rpc_client.chain_get_header(Some(hash)))?)
}

fn info(&self) -> Info<Block> {
let best_header = block_local(self.rpc_client.chain_get_header(None))
.expect("Unable to get header from relay chain.")
.unwrap();
let genesis_hash = block_local(self.rpc_client.chain_get_head(Some(0)))
.expect("Unable to get header from relay chain.");
let finalized_head = block_local(self.rpc_client.chain_get_finalized_head())
.expect("Unable to get finalized head from relay chain.");
let finalized_header = block_local(self.rpc_client.chain_get_header(Some(finalized_head)))
.expect("Unable to get finalized header from relay chain.")
.unwrap();
Info {
best_hash: best_header.hash(),
best_number: best_header.number,
genesis_hash,
finalized_hash: finalized_head,
finalized_number: finalized_header.number,
finalized_state: None,
number_leaves: 1,
block_gap: None,
}
}

fn status(
&self,
hash: <Block as BlockT>::Hash,
) -> sp_blockchain::Result<sp_blockchain::BlockStatus> {
if self.header(hash)?.is_some() {
Ok(sc_client_api::blockchain::BlockStatus::InChain)
} else {
Ok(sc_client_api::blockchain::BlockStatus::Unknown)
}
}

fn number(
&self,
hash: <Block as BlockT>::Hash,
) -> sp_blockchain::Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>> {
let result = block_local(self.rpc_client.chain_get_header(Some(hash)))?
.map(|maybe_header| maybe_header.number);
Ok(result)
}

fn hash(
&self,
number: NumberFor<Block>,
) -> sp_blockchain::Result<Option<<Block as BlockT>::Hash>> {
Ok(block_local(self.rpc_client.chain_get_block_hash(number.into()))?)
}
}
22 changes: 9 additions & 13 deletions client/relay-chain-minimal-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use collator_overseer::{CollatorOverseerGenArgs, NewMinimalNode};

use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};
use cumulus_relay_chain_rpc_interface::{RelayChainRpcInterface, Url};
use network::build_collator_network;
use polkadot_network_bridge::{peer_sets_info, IsAuthority};
use polkadot_node_network_protocol::{
peer_set::PeerSetProtocolNames,
Expand Down Expand Up @@ -149,14 +150,12 @@ async fn new_minimal_relay_chain(
let (collation_req_receiver, available_data_req_receiver) =
build_request_response_protocol_receivers(&request_protocol_names, &mut config);

let best_header = relay_chain_rpc_client.chain_get_header(None).await?.ok_or_else(|| {
RelayChainError::RpcCallError("Unable to fetch best header".to_string().into())
})?;
let (network, network_starter, sync_oracle) =
network::build_collator_network(network::BuildCollatorNetworkParams {
config: &config,
client: relay_chain_rpc_client.clone(),
spawn_handle: task_manager.spawn_handle(),
genesis_hash,
})
.map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?;
build_collator_network(&config, task_manager.spawn_handle(), genesis_hash, best_header)
.map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?;

let authority_discovery_service = build_authority_discovery_service(
&task_manager,
Expand All @@ -180,12 +179,9 @@ async fn new_minimal_relay_chain(
peer_set_protocol_names,
};

let overseer_handle = collator_overseer::spawn_overseer(
overseer_args,
&task_manager,
relay_chain_rpc_client.clone(),
)
.map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?;
let overseer_handle =
collator_overseer::spawn_overseer(overseer_args, &task_manager, relay_chain_rpc_client)
.map_err(|e| RelayChainError::Application(Box::new(e) as Box<_>))?;

network_starter.start_network();

Expand Down
31 changes: 9 additions & 22 deletions client/relay-chain-minimal-node/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Cumulus. If not, see <http://www.gnu.org/licenses/>.

use polkadot_core_primitives::{Block, Hash};
use polkadot_core_primitives::{Block, Hash, Header};
use sp_runtime::traits::{Block as BlockT, NumberFor};

use sc_network::{
Expand All @@ -24,45 +24,32 @@ use sc_network::{
NetworkService,
};

use sc_client_api::HeaderBackend;
use sc_network_common::{role::Roles, sync::message::BlockAnnouncesHandshake};
use sc_service::{error::Error, Configuration, NetworkStarter, SpawnTaskHandle};

use std::{iter, sync::Arc};

use crate::BlockChainRpcClient;

pub(crate) struct BuildCollatorNetworkParams<'a> {
/// The service configuration.
pub config: &'a Configuration,
/// A shared client returned by `new_full_parts`.
pub client: Arc<BlockChainRpcClient>,
/// A handle for spawning tasks.
pub spawn_handle: SpawnTaskHandle,
/// Genesis hash
pub genesis_hash: Hash,
}

/// Build the network service, the network status sinks and an RPC sender.
pub(crate) fn build_collator_network(
params: BuildCollatorNetworkParams,
config: &Configuration,
spawn_handle: SpawnTaskHandle,
genesis_hash: Hash,
best_header: Header,
) -> Result<
(Arc<NetworkService<Block, Hash>>, NetworkStarter, Box<dyn sp_consensus::SyncOracle + Send>),
Error,
> {
let BuildCollatorNetworkParams { config, client, spawn_handle, genesis_hash } = params;

let protocol_id = config.protocol_id();
let block_announce_config = get_block_announce_proto_config::<Block>(
protocol_id.clone(),
&None,
Roles::from(&config.role),
client.info().best_number,
client.info().best_hash,
best_header.number,
best_header.hash(),
genesis_hash,
);

let network_params = sc_network::config::Params {
let network_params = sc_network::config::Params::<Block> {
role: config.role.clone(),
executor: {
let spawn_handle = Clone::clone(&spawn_handle);
Expand All @@ -72,7 +59,7 @@ pub(crate) fn build_collator_network(
},
fork_id: None,
network_config: config.network.clone(),
chain: client.clone(),
genesis_hash,
protocol_id,
metrics_registry: config.prometheus_config.as_ref().map(|config| config.registry.clone()),
block_announce_config,
Expand Down