feat: Rebrand Polkadot/Substrate references to PezkuwiChain

This commit systematically rebrands various references from Parity Technologies'
Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk.

Key changes include:
- Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks.
- Modified internal documentation and code comments to reflect PezkuwiChain naming and structure.
- Replaced direct references to  with  or specific paths within the  for XCM, Pezkuwi, and other modules.
- Cleaned up deprecated  issue and PR references in various  and  files, particularly in  and  modules.
- Adjusted image and logo URLs in documentation to point to PezkuwiChain assets.
- Removed or rephrased comments related to external Polkadot/Substrate PRs and issues.

This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
2025-12-14 00:04:10 +03:00
parent e4778b4576
commit 379cb741ed
9082 changed files with 997824 additions and 997542 deletions
@@ -0,0 +1,292 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// Pezcumulus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezcumulus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezcumulus. If not, see <https://www.gnu.org/licenses/>.
use async_trait::async_trait;
use core::time::Duration;
use cumulus_primitives_core::{
relay_chain::{
CandidateEvent, CommittedCandidateReceiptV2 as CommittedCandidateReceipt,
Hash as RelayHash, Header as RelayHeader, InboundHrmpMessage, OccupiedCoreAssumption,
SessionIndex, ValidationCodeHash, ValidatorId,
},
InboundDownwardMessage, ParaId, PersistedValidationData,
};
use cumulus_relay_chain_interface::{
BlockNumber, CoreState, PHeader, RelayChainError, RelayChainInterface, RelayChainResult,
};
use futures::{FutureExt, Stream, StreamExt};
use pezkuwi_overseer::Handle;
use pezsc_client_api::StorageProof;
use pezsp_state_machine::StorageValue;
use pezsp_storage::StorageKey;
use pezsp_version::RuntimeVersion;
use std::{collections::btree_map::BTreeMap, pin::Pin};
use cumulus_primitives_core::relay_chain::BlockId;
pub use url::Url;
mod metrics;
mod reconnecting_ws_client;
mod rpc_client;
pub use rpc_client::{create_client_and_start_worker, RelayChainRpcClient};
const TIMEOUT_IN_SECONDS: u64 = 6;
/// RelayChainRpcInterface is used to interact with a full node that is running locally
/// in the same process.
#[derive(Clone)]
pub struct RelayChainRpcInterface {
rpc_client: RelayChainRpcClient,
overseer_handle: Handle,
}
impl RelayChainRpcInterface {
pub fn new(rpc_client: RelayChainRpcClient, overseer_handle: Handle) -> Self {
Self { rpc_client, overseer_handle }
}
}
#[async_trait]
impl RelayChainInterface for RelayChainRpcInterface {
async fn retrieve_dmq_contents(
&self,
para_id: ParaId,
relay_parent: RelayHash,
) -> RelayChainResult<Vec<InboundDownwardMessage>> {
self.rpc_client.teyrchain_host_dmq_contents(para_id, relay_parent).await
}
async fn retrieve_all_inbound_hrmp_channel_contents(
&self,
para_id: ParaId,
relay_parent: RelayHash,
) -> RelayChainResult<BTreeMap<ParaId, Vec<InboundHrmpMessage>>> {
self.rpc_client
.teyrchain_host_inbound_hrmp_channels_contents(para_id, relay_parent)
.await
}
async fn header(&self, block_id: BlockId) -> RelayChainResult<Option<PHeader>> {
let hash = match block_id {
BlockId::Hash(hash) => hash,
BlockId::Number(num) => {
if let Some(hash) = self.rpc_client.chain_get_block_hash(Some(num)).await? {
hash
} else {
return Ok(None);
}
},
};
let header = self.rpc_client.chain_get_header(Some(hash)).await?;
Ok(header)
}
async fn persisted_validation_data(
&self,
hash: RelayHash,
para_id: ParaId,
occupied_core_assumption: OccupiedCoreAssumption,
) -> RelayChainResult<Option<PersistedValidationData>> {
self.rpc_client
.teyrchain_host_persisted_validation_data(hash, para_id, occupied_core_assumption)
.await
}
async fn validation_code_hash(
&self,
hash: RelayHash,
para_id: ParaId,
occupied_core_assumption: OccupiedCoreAssumption,
) -> RelayChainResult<Option<ValidationCodeHash>> {
self.rpc_client
.validation_code_hash(hash, para_id, occupied_core_assumption)
.await
}
async fn candidate_pending_availability(
&self,
hash: RelayHash,
para_id: ParaId,
) -> RelayChainResult<Option<CommittedCandidateReceipt>> {
self.rpc_client
.teyrchain_host_candidate_pending_availability(hash, para_id)
.await
}
async fn session_index_for_child(&self, hash: RelayHash) -> RelayChainResult<SessionIndex> {
self.rpc_client.teyrchain_host_session_index_for_child(hash).await
}
async fn validators(&self, block_id: RelayHash) -> RelayChainResult<Vec<ValidatorId>> {
self.rpc_client.teyrchain_host_validators(block_id).await
}
async fn import_notification_stream(
&self,
) -> RelayChainResult<Pin<Box<dyn Stream<Item = RelayHeader> + Send>>> {
let imported_headers_stream = self.rpc_client.get_imported_heads_stream()?;
Ok(imported_headers_stream.boxed())
}
async fn finality_notification_stream(
&self,
) -> RelayChainResult<Pin<Box<dyn Stream<Item = RelayHeader> + Send>>> {
let imported_headers_stream = self.rpc_client.get_finalized_heads_stream()?;
Ok(imported_headers_stream.boxed())
}
async fn best_block_hash(&self) -> RelayChainResult<RelayHash> {
self.rpc_client.chain_get_head(None).await
}
async fn finalized_block_hash(&self) -> RelayChainResult<RelayHash> {
self.rpc_client.chain_get_finalized_head().await
}
async fn call_runtime_api(
&self,
method_name: &'static str,
hash: RelayHash,
payload: &[u8],
) -> RelayChainResult<Vec<u8>> {
self.rpc_client
.call_remote_runtime_function_encoded(method_name, hash, payload)
.await
.map(|bytes| bytes.to_vec())
}
async fn is_major_syncing(&self) -> RelayChainResult<bool> {
self.rpc_client.system_health().await.map(|h| h.is_syncing)
}
fn overseer_handle(&self) -> RelayChainResult<Handle> {
Ok(self.overseer_handle.clone())
}
async fn get_storage_by_key(
&self,
relay_parent: RelayHash,
key: &[u8],
) -> RelayChainResult<Option<StorageValue>> {
let storage_key = StorageKey(key.to_vec());
self.rpc_client
.state_get_storage(storage_key, Some(relay_parent))
.await
.map(|storage_data| storage_data.map(|sv| sv.0))
}
async fn prove_read(
&self,
relay_parent: RelayHash,
relevant_keys: &Vec<Vec<u8>>,
) -> RelayChainResult<StorageProof> {
let cloned = relevant_keys.clone();
let storage_keys: Vec<StorageKey> = cloned.into_iter().map(StorageKey).collect();
self.rpc_client
.state_get_read_proof(storage_keys, Some(relay_parent))
.await
.map(|read_proof| {
StorageProof::new(read_proof.proof.into_iter().map(|bytes| bytes.to_vec()))
})
}
/// Wait for a given relay chain block
///
/// The hash of the block to wait for is passed. We wait for the block to arrive or return after
/// a timeout.
///
/// Implementation:
/// 1. Register a listener to all new blocks.
/// 2. Check if the block is already in chain. If yes, succeed early.
/// 3. Wait for the block to be imported via subscription.
/// 4. If timeout is reached, we return an error.
async fn wait_for_block(&self, wait_for_hash: RelayHash) -> RelayChainResult<()> {
let mut head_stream = self.rpc_client.get_imported_heads_stream()?;
if self.rpc_client.chain_get_header(Some(wait_for_hash)).await?.is_some() {
return Ok(());
}
let mut timeout = futures_timer::Delay::new(Duration::from_secs(TIMEOUT_IN_SECONDS)).fuse();
loop {
futures::select! {
_ = timeout => return Err(RelayChainError::WaitTimeout(wait_for_hash)),
evt = head_stream.next().fuse() => match evt {
Some(evt) if evt.hash() == wait_for_hash => return Ok(()),
// Not the event we waited on.
Some(_) => continue,
None => return Err(RelayChainError::ImportListenerClosed(wait_for_hash)),
}
}
}
}
async fn new_best_notification_stream(
&self,
) -> RelayChainResult<Pin<Box<dyn Stream<Item = RelayHeader> + Send>>> {
let imported_headers_stream = self.rpc_client.get_best_heads_stream()?;
Ok(imported_headers_stream.boxed())
}
async fn candidates_pending_availability(
&self,
hash: RelayHash,
para_id: ParaId,
) -> RelayChainResult<Vec<CommittedCandidateReceipt>> {
self.rpc_client
.teyrchain_host_candidates_pending_availability(hash, para_id)
.await
}
async fn version(&self, relay_parent: RelayHash) -> RelayChainResult<RuntimeVersion> {
self.rpc_client.runtime_version(relay_parent).await
}
async fn availability_cores(
&self,
relay_parent: RelayHash,
) -> RelayChainResult<Vec<CoreState<RelayHash, BlockNumber>>> {
self.rpc_client.teyrchain_host_availability_cores(relay_parent).await
}
async fn claim_queue(
&self,
relay_parent: RelayHash,
) -> RelayChainResult<
BTreeMap<cumulus_relay_chain_interface::CoreIndex, std::collections::VecDeque<ParaId>>,
> {
self.rpc_client.teyrchain_host_claim_queue(relay_parent).await
}
async fn scheduling_lookahead(&self, relay_parent: RelayHash) -> RelayChainResult<u32> {
self.rpc_client.teyrchain_host_scheduling_lookahead(relay_parent).await
}
async fn candidate_events(
&self,
relay_parent: RelayHash,
) -> RelayChainResult<Vec<CandidateEvent>> {
self.rpc_client.teyrchain_host_candidate_events(relay_parent).await
}
}
@@ -0,0 +1,50 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// Pezcumulus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezcumulus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezcumulus. If not, see <https://www.gnu.org/licenses/>.
use prometheus::{Error as PrometheusError, HistogramTimer, Registry};
use prometheus_endpoint::{HistogramOpts, HistogramVec, Opts};
/// Gathers metrics about the blockchain RPC client.
#[derive(Clone)]
pub(crate) struct RelaychainRpcMetrics {
rpc_request: HistogramVec,
}
impl RelaychainRpcMetrics {
pub(crate) fn register(registry: &Registry) -> Result<Self, PrometheusError> {
Ok(Self {
rpc_request: prometheus_endpoint::register(
HistogramVec::new(
HistogramOpts {
common_opts: Opts::new(
"relay_chain_rpc_interface",
"Tracks stats about pezcumulus relay chain RPC interface",
),
buckets: prometheus::exponential_buckets(0.001, 4.0, 9)
.expect("function parameters are constant and always valid; qed"),
},
&["method"],
)?,
registry,
)?,
})
}
pub(crate) fn start_request_timer(&self, method: &str) -> HistogramTimer {
self.rpc_request.with_label_values(&[method]).start_timer()
}
}
@@ -0,0 +1,528 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// Pezcumulus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezcumulus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezcumulus. If not, see <https://www.gnu.org/licenses/>.
use cumulus_primitives_core::relay_chain::{
Block as RelayBlock, BlockNumber as RelayNumber, Hash as RelayHash, Header as RelayHeader,
};
use futures::{
channel::{mpsc::Sender, oneshot::Sender as OneshotSender},
future::BoxFuture,
stream::FuturesUnordered,
FutureExt, StreamExt,
};
use jsonrpsee::{
core::{
client::{Client as JsonRpcClient, ClientT, Subscription},
params::ArrayParams,
ClientError as JsonRpseeError, JsonValue,
},
ws_client::WsClientBuilder,
};
use pezsc_rpc_api::chain::ChainApiClient;
use schnellru::{ByLength, LruMap};
use pezsp_runtime::generic::SignedBlock;
use std::{sync::Arc, time::Duration};
use tokio::sync::mpsc::{
channel as tokio_channel, Receiver as TokioReceiver, Sender as TokioSender,
};
use url::Url;
use crate::rpc_client::{distribute_header, RpcDispatcherMessage};
const LOG_TARGET: &str = "reconnecting-websocket-client";
const DEFAULT_EXTERNAL_RPC_CONN_RETRIES: usize = 5;
const DEFAULT_SLEEP_TIME_MS_BETWEEN_RETRIES: u64 = 1000;
const DEFAULT_SLEEP_EXP_BACKOFF_BETWEEN_RETRIES: i32 = 2;
/// Worker that should be used in combination with [`RelayChainRpcClient`].
///
/// Must be polled to distribute header notifications to listeners.
pub struct ReconnectingWebsocketWorker {
ws_urls: Vec<String>,
/// Communication channel with the RPC client
client_receiver: TokioReceiver<RpcDispatcherMessage>,
/// Senders to distribute incoming header notifications to
imported_header_listeners: Vec<Sender<RelayHeader>>,
finalized_header_listeners: Vec<Sender<RelayHeader>>,
best_header_listeners: Vec<Sender<RelayHeader>>,
}
/// Format url and force addition of a port
fn url_to_string_with_port(url: Url) -> Option<String> {
// This is already validated on CLI side, just defensive here
if (url.scheme() != "ws" && url.scheme() != "wss") || url.host_str().is_none() {
tracing::warn!(target: LOG_TARGET, ?url, "Non-WebSocket URL or missing host.");
return None;
}
// Either we have a user-supplied port or use the default for 'ws' or 'wss' here
Some(format!(
"{}://{}:{}{}{}",
url.scheme(),
url.host_str()?,
url.port_or_known_default()?,
url.path(),
url.query().map(|query| format!("?{}", query)).unwrap_or_default()
))
}
/// Manages the active websocket client.
/// Responsible for creating request futures, subscription streams
/// and reconnections.
#[derive(Debug)]
struct ClientManager {
urls: Vec<String>,
active_client: Arc<JsonRpcClient>,
active_index: usize,
}
struct RelayChainSubscriptions {
import_subscription: Subscription<RelayHeader>,
finalized_subscription: Subscription<RelayHeader>,
best_subscription: Subscription<RelayHeader>,
}
/// Try to find a new RPC server to connect to. Uses a naive retry
/// logic that does an exponential backoff in between iterations
/// through all URLs from the list. It uses a constant to tell how
/// many iterations of connection attempts to all URLs we allow. We
/// return early when a connection is made.
async fn connect_next_available_rpc_server(
urls: &Vec<String>,
starting_position: usize,
) -> Result<(usize, Arc<JsonRpcClient>), ()> {
tracing::debug!(target: LOG_TARGET, starting_position, "Connecting to RPC server.");
let mut prev_iteration: u32 = 0;
for (counter, url) in urls
.iter()
.cycle()
.skip(starting_position)
.take(urls.len() * DEFAULT_EXTERNAL_RPC_CONN_RETRIES)
.enumerate()
{
// If we reached the end of the urls list, backoff before retrying
// connections to the entire list once more.
let Ok(current_iteration) = (counter / urls.len()).try_into() else {
tracing::error!(target: LOG_TARGET, "Too many connection attempts to the RPC servers, aborting...");
break;
};
if current_iteration > prev_iteration {
// Safe conversion given we convert positive i32s which are lower than u64::MAX.
tokio::time::sleep(Duration::from_millis(
DEFAULT_SLEEP_TIME_MS_BETWEEN_RETRIES *
DEFAULT_SLEEP_EXP_BACKOFF_BETWEEN_RETRIES.pow(prev_iteration) as u64,
))
.await;
prev_iteration = current_iteration;
}
let index = (starting_position + counter) % urls.len();
tracing::info!(
target: LOG_TARGET,
attempt = current_iteration,
index,
url,
"Trying to connect to next external relaychain node.",
);
match WsClientBuilder::default().build(&url).await {
Ok(ws_client) => return Ok((index, Arc::new(ws_client))),
Err(err) => tracing::debug!(target: LOG_TARGET, url, ?err, "Unable to connect."),
};
}
tracing::error!(target: LOG_TARGET, "Retrying to connect to any external relaychain node failed.");
Err(())
}
impl ClientManager {
pub async fn new(urls: Vec<String>) -> Result<Self, ()> {
if urls.is_empty() {
return Err(());
}
let active_client = connect_next_available_rpc_server(&urls, 0).await?;
Ok(Self { urls, active_client: active_client.1, active_index: active_client.0 })
}
pub async fn connect_to_new_rpc_server(&mut self) -> Result<(), ()> {
let new_active =
connect_next_available_rpc_server(&self.urls, self.active_index + 1).await?;
self.active_client = new_active.1;
self.active_index = new_active.0;
Ok(())
}
async fn get_subscriptions(&self) -> Result<RelayChainSubscriptions, JsonRpseeError> {
let import_subscription = <JsonRpcClient as ChainApiClient<
RelayNumber,
RelayHash,
RelayHeader,
SignedBlock<RelayBlock>,
>>::subscribe_all_heads(&self.active_client)
.await
.map_err(|e| {
tracing::error!(
target: LOG_TARGET,
?e,
"Unable to open `chain_subscribeAllHeads` subscription."
);
e
})?;
let best_subscription = <JsonRpcClient as ChainApiClient<
RelayNumber,
RelayHash,
RelayHeader,
SignedBlock<RelayBlock>,
>>::subscribe_new_heads(&self.active_client)
.await
.map_err(|e| {
tracing::error!(
target: LOG_TARGET,
?e,
"Unable to open `chain_subscribeNewHeads` subscription."
);
e
})?;
let finalized_subscription = <JsonRpcClient as ChainApiClient<
RelayNumber,
RelayHash,
RelayHeader,
SignedBlock<RelayBlock>,
>>::subscribe_finalized_heads(&self.active_client)
.await
.map_err(|e| {
tracing::error!(
target: LOG_TARGET,
?e,
"Unable to open `chain_subscribeFinalizedHeads` subscription."
);
e
})?;
Ok(RelayChainSubscriptions {
import_subscription,
best_subscription,
finalized_subscription,
})
}
/// Create a request future that performs an RPC request and sends the results to the caller.
/// In case of a dead websocket connection, it returns the original request parameters to
/// enable retries.
fn create_request(
&self,
method: String,
params: ArrayParams,
response_sender: OneshotSender<Result<JsonValue, JsonRpseeError>>,
) -> BoxFuture<'static, Result<(), RpcDispatcherMessage>> {
let future_client = self.active_client.clone();
async move {
let resp = future_client.request(&method, params.clone()).await;
// We should only return the original request in case
// the websocket connection is dead and requires a restart.
// Other errors should be forwarded to the request caller.
if let Err(JsonRpseeError::RestartNeeded(_)) = resp {
return Err(RpcDispatcherMessage::Request(method, params, response_sender));
}
if let Err(err) = response_sender.send(resp) {
tracing::debug!(
target: LOG_TARGET,
?err,
"Recipient no longer interested in request result"
);
}
Ok(())
}
.boxed()
}
}
enum ConnectionStatus {
Connected,
ReconnectRequired(Option<RpcDispatcherMessage>),
}
impl ReconnectingWebsocketWorker {
/// Create new worker. Returns the worker and a channel to register new listeners.
pub async fn new(
urls: Vec<Url>,
) -> (ReconnectingWebsocketWorker, TokioSender<RpcDispatcherMessage>) {
let urls = urls.into_iter().filter_map(url_to_string_with_port).collect();
let (tx, rx) = tokio_channel(100);
let worker = ReconnectingWebsocketWorker {
ws_urls: urls,
client_receiver: rx,
imported_header_listeners: Vec::new(),
finalized_header_listeners: Vec::new(),
best_header_listeners: Vec::new(),
};
(worker, tx)
}
/// Reconnect via [`ClientManager`] and provide new notification streams.
async fn handle_reconnect(
&mut self,
client_manager: &mut ClientManager,
pending_requests: &mut FuturesUnordered<
BoxFuture<'static, Result<(), RpcDispatcherMessage>>,
>,
first_failed_request: Option<RpcDispatcherMessage>,
) -> Result<RelayChainSubscriptions, String> {
let mut requests_to_retry = Vec::new();
if let Some(req @ RpcDispatcherMessage::Request(_, _, _)) = first_failed_request {
requests_to_retry.push(req);
}
// At this point, all pending requests will return an error since the
// websocket connection is dead. So draining the pending requests should be fast.
while !pending_requests.is_empty() {
if let Some(Err(req)) = pending_requests.next().await {
requests_to_retry.push(req);
}
}
if client_manager.connect_to_new_rpc_server().await.is_err() {
return Err("Unable to find valid external RPC server, shutting down.".to_string());
};
for item in requests_to_retry.into_iter() {
if let RpcDispatcherMessage::Request(method, params, response_sender) = item {
pending_requests.push(client_manager.create_request(
method,
params,
response_sender,
));
};
}
client_manager.get_subscriptions().await.map_err(|e| {
format!("Not able to create streams from newly connected RPC server, shutting down. err: {:?}", e)
})
}
/// Run this worker to drive notification streams.
/// The worker does the following:
/// - Listen for [`RpcDispatcherMessage`], perform requests and register new listeners for the
/// notification streams
/// - Distribute incoming import, best head and finalization notifications to registered
/// listeners. If an error occurs during sending, the receiver has been closed and we remove
/// the sender from the list.
/// - Find a new valid RPC server to connect to in case the websocket connection is terminated.
/// If the worker is not able to connect to an RPC server from the list, the worker shuts
/// down.
pub async fn run(mut self) {
let mut pending_requests = FuturesUnordered::new();
let urls = std::mem::take(&mut self.ws_urls);
let Ok(mut client_manager) = ClientManager::new(urls).await else {
tracing::error!(target: LOG_TARGET, "No valid RPC url found. Stopping RPC worker.");
return;
};
let Ok(mut subscriptions) = client_manager.get_subscriptions().await else {
tracing::error!(target: LOG_TARGET, "Unable to fetch subscriptions on initial connection.");
return;
};
let mut imported_blocks_cache = LruMap::new(ByLength::new(40));
let mut should_reconnect = ConnectionStatus::Connected;
let mut last_seen_finalized_num: RelayNumber = 0;
loop {
// This branch is taken if the websocket connection to the current RPC server is closed.
if let ConnectionStatus::ReconnectRequired(maybe_failed_request) = should_reconnect {
match self
.handle_reconnect(
&mut client_manager,
&mut pending_requests,
maybe_failed_request,
)
.await
{
Ok(new_subscriptions) => {
subscriptions = new_subscriptions;
},
Err(message) => {
tracing::error!(
target: LOG_TARGET,
message,
"Unable to reconnect, stopping worker."
);
return;
},
}
should_reconnect = ConnectionStatus::Connected;
}
tokio::select! {
evt = self.client_receiver.recv() => match evt {
Some(RpcDispatcherMessage::RegisterBestHeadListener(tx)) => {
self.best_header_listeners.push(tx);
},
Some(RpcDispatcherMessage::RegisterImportListener(tx)) => {
self.imported_header_listeners.push(tx)
},
Some(RpcDispatcherMessage::RegisterFinalizationListener(tx)) => {
self.finalized_header_listeners.push(tx)
},
Some(RpcDispatcherMessage::Request(method, params, response_sender)) => {
pending_requests.push(client_manager.create_request(method, params, response_sender));
},
None => {
tracing::error!(target: LOG_TARGET, "RPC client receiver closed. Stopping RPC Worker.");
return;
}
},
should_retry = pending_requests.next(), if !pending_requests.is_empty() => {
if let Some(Err(req)) = should_retry {
should_reconnect = ConnectionStatus::ReconnectRequired(Some(req));
}
},
import_event = subscriptions.import_subscription.next() => {
match import_event {
Some(Ok(header)) => {
let hash = header.hash();
if imported_blocks_cache.peek(&hash).is_some() {
tracing::debug!(
target: LOG_TARGET,
number = header.number,
?hash,
"Duplicate imported block header. This might happen after switching to a new RPC node. Skipping distribution."
);
continue;
}
imported_blocks_cache.insert(hash, ());
distribute_header(header, &mut self.imported_header_listeners);
},
None => {
tracing::error!(target: LOG_TARGET, "Subscription closed.");
should_reconnect = ConnectionStatus::ReconnectRequired(None);
},
Some(Err(error)) => {
tracing::error!(target: LOG_TARGET, ?error, "Error in RPC subscription.");
should_reconnect = ConnectionStatus::ReconnectRequired(None);
},
}
},
best_header_event = subscriptions.best_subscription.next() => {
match best_header_event {
Some(Ok(header)) => distribute_header(header, &mut self.best_header_listeners),
None => {
tracing::error!(target: LOG_TARGET, "Subscription closed.");
should_reconnect = ConnectionStatus::ReconnectRequired(None);
},
Some(Err(error)) => {
tracing::error!(target: LOG_TARGET, ?error, "Error in RPC subscription.");
should_reconnect = ConnectionStatus::ReconnectRequired(None);
},
}
}
finalized_event = subscriptions.finalized_subscription.next() => {
match finalized_event {
Some(Ok(header)) if header.number > last_seen_finalized_num => {
last_seen_finalized_num = header.number;
distribute_header(header, &mut self.finalized_header_listeners);
},
Some(Ok(header)) => {
tracing::debug!(
target: LOG_TARGET,
number = header.number,
last_seen_finalized_num,
"Duplicate finalized block header. This might happen after switching to a new RPC node. Skipping distribution."
);
},
None => {
tracing::error!(target: LOG_TARGET, "Subscription closed.");
should_reconnect = ConnectionStatus::ReconnectRequired(None);
},
Some(Err(error)) => {
tracing::error!(target: LOG_TARGET, ?error, "Error in RPC subscription.");
should_reconnect = ConnectionStatus::ReconnectRequired(None);
},
}
}
}
}
}
}
#[cfg(test)]
mod test {
use std::time::Duration;
use super::{url_to_string_with_port, ClientManager};
use jsonrpsee::Methods;
use url::Url;
const SERVER_STARTUP_DELAY_SECONDS: u64 = 10;
#[test]
fn url_to_string_works() {
let url = Url::parse("wss://something/path").unwrap();
assert_eq!(Some("wss://something:443/path".to_string()), url_to_string_with_port(url));
let url = Url::parse("ws://something/path").unwrap();
assert_eq!(Some("ws://something:80/path".to_string()), url_to_string_with_port(url));
let url = Url::parse("wss://something:100/path").unwrap();
assert_eq!(Some("wss://something:100/path".to_string()), url_to_string_with_port(url));
let url = Url::parse("wss://something:100/path").unwrap();
assert_eq!(Some("wss://something:100/path".to_string()), url_to_string_with_port(url));
let url = Url::parse("wss://something/path?query=yes").unwrap();
assert_eq!(
Some("wss://something:443/path?query=yes".to_string()),
url_to_string_with_port(url)
);
let url = Url::parse("wss://something:9090/path?query=yes").unwrap();
assert_eq!(
Some("wss://something:9090/path?query=yes".to_string()),
url_to_string_with_port(url)
);
}
#[tokio::test]
// Testing the retry logic at full means increasing CI with half a minute according
// to the current logic, so lets test it best effort.
async fn client_manager_retry_logic() {
let port = portpicker::pick_unused_port().unwrap();
let server = jsonrpsee::server::Server::builder()
.build(format!("0.0.0.0:{}", port))
.await
.unwrap();
// Start the server.
let server = tokio::spawn(async {
tokio::time::sleep(Duration::from_secs(SERVER_STARTUP_DELAY_SECONDS)).await;
server.start(Methods::default())
});
// Start the client. Not exitting right away with an error means it
// is handling gracefully received connections refused while the server
// is starting.
let res = ClientManager::new(vec![format!("ws://127.0.0.1:{}", port)]).await;
assert!(res.is_ok());
server.await.unwrap();
}
}
@@ -0,0 +1,795 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezcumulus.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// Pezcumulus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Pezcumulus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Pezcumulus. If not, see <https://www.gnu.org/licenses/>.
use futures::channel::{
mpsc::{Receiver, Sender},
oneshot::Sender as OneshotSender,
};
use jsonrpsee::{
core::{params::ArrayParams, ClientError as JsonRpseeError},
rpc_params,
};
use prometheus::Registry;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value as JsonValue;
use std::collections::{btree_map::BTreeMap, VecDeque};
use tokio::sync::mpsc::Sender as TokioSender;
use codec::{Decode, Encode};
use cumulus_primitives_core::{
relay_chain::{
async_backing::{AsyncBackingParams, BackingState, Constraints},
slashing, ApprovalVotingParams, BlockNumber, CandidateCommitments, CandidateEvent,
CandidateHash, CommittedCandidateReceiptV2 as CommittedCandidateReceipt, CoreIndex,
CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash as RelayHash,
Header as RelayHeader, InboundHrmpMessage, NodeFeatures, OccupiedCoreAssumption,
PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode,
ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature,
},
InboundDownwardMessage, ParaId, PersistedValidationData,
};
use cumulus_relay_chain_interface::{RelayChainError, RelayChainResult};
use pezsc_client_api::StorageData;
use pezsc_rpc_api::{state::ReadProof, system::Health};
use pezsc_service::TaskManager;
use pezsp_consensus_babe::Epoch;
use pezsp_storage::StorageKey;
use pezsp_version::RuntimeVersion;
use crate::{metrics::RelaychainRpcMetrics, reconnecting_ws_client::ReconnectingWebsocketWorker};
pub use url::Url;
const LOG_TARGET: &str = "relay-chain-rpc-client";
const NOTIFICATION_CHANNEL_SIZE_LIMIT: usize = 20;
/// Messages for communication between [`RelayChainRpcClient`] and the RPC workers.
#[derive(Debug)]
pub enum RpcDispatcherMessage {
/// Register new listener for the best headers stream. Contains a sender which will be used
/// to send incoming headers.
RegisterBestHeadListener(Sender<RelayHeader>),
/// Register new listener for the import headers stream. Contains a sender which will be used
/// to send incoming headers.
RegisterImportListener(Sender<RelayHeader>),
/// Register new listener for the finalized headers stream. Contains a sender which will be
/// used to send incoming headers.
RegisterFinalizationListener(Sender<RelayHeader>),
/// Register new listener for the finalized headers stream.
/// Contains the following:
/// - [`String`] representing the RPC method to be called
/// - [`ArrayParams`] for the parameters to the RPC call
/// - [`OneshotSender`] for the return value of the request
Request(String, ArrayParams, OneshotSender<Result<JsonValue, JsonRpseeError>>),
}
/// Entry point to create [`RelayChainRpcClient`] and start a worker that communicates
/// to JsonRPC servers over the network.
pub async fn create_client_and_start_worker(
urls: Vec<Url>,
task_manager: &mut TaskManager,
prometheus_registry: Option<&Registry>,
) -> RelayChainResult<RelayChainRpcClient> {
let (worker, sender) = ReconnectingWebsocketWorker::new(urls).await;
task_manager
.spawn_essential_handle()
.spawn("relay-chain-rpc-worker", None, worker.run());
let client = RelayChainRpcClient::new(sender, prometheus_registry);
Ok(client)
}
#[derive(Serialize)]
struct PayloadToHex<'a>(#[serde(with = "pezsp_core::bytes")] &'a [u8]);
/// Client that maps RPC methods and deserializes results
#[derive(Clone)]
pub struct RelayChainRpcClient {
/// Sender to send messages to the worker.
worker_channel: TokioSender<RpcDispatcherMessage>,
metrics: Option<RelaychainRpcMetrics>,
}
impl RelayChainRpcClient {
/// Initialize new RPC Client.
///
/// This client expects a channel connected to a worker that processes
/// requests sent via this channel.
pub(crate) fn new(
worker_channel: TokioSender<RpcDispatcherMessage>,
prometheus_registry: Option<&Registry>,
) -> Self {
RelayChainRpcClient {
worker_channel,
metrics: prometheus_registry
.and_then(|inner| RelaychainRpcMetrics::register(inner).map_err(|err| {
tracing::warn!(target: LOG_TARGET, error = %err, "Unable to instantiate the RPC client metrics, continuing w/o metrics setup.");
}).ok()),
}
}
/// Same as `call_remote_runtime_function` but work on encoded data
pub async fn call_remote_runtime_function_encoded(
&self,
method_name: &str,
hash: RelayHash,
payload: &[u8],
) -> RelayChainResult<pezsp_core::Bytes> {
let payload = PayloadToHex(payload);
let params = rpc_params! {
method_name,
payload,
hash
};
self.request_tracing::<pezsp_core::Bytes, _>("state_call", params, |err| {
tracing::trace!(
target: LOG_TARGET,
%method_name,
%hash,
error = %err,
"Error during call to 'state_call'.",
);
})
.await
}
/// Call a call to `state_call` rpc method.
pub async fn call_remote_runtime_function<R: Decode>(
&self,
method_name: &str,
hash: RelayHash,
payload: Option<impl Encode>,
) -> RelayChainResult<R> {
let payload_bytes =
payload.map_or(pezsp_core::Bytes(Vec::new()), |v| pezsp_core::Bytes(v.encode()));
let res = self
.call_remote_runtime_function_encoded(method_name, hash, &payload_bytes)
.await?;
Decode::decode(&mut &*res.0).map_err(Into::into)
}
/// Perform RPC request
async fn request<'a, R>(
&self,
method: &'a str,
params: ArrayParams,
) -> Result<R, RelayChainError>
where
R: DeserializeOwned + std::fmt::Debug,
{
self.request_tracing(
method,
params,
|e| tracing::trace!(target:LOG_TARGET, error = %e, %method, "Unable to complete RPC request"),
)
.await
}
/// Perform RPC request
async fn request_tracing<'a, R, OR>(
&self,
method: &'a str,
params: ArrayParams,
trace_error: OR,
) -> Result<R, RelayChainError>
where
R: DeserializeOwned + std::fmt::Debug,
OR: Fn(&RelayChainError),
{
let _timer = self.metrics.as_ref().map(|inner| inner.start_request_timer(method));
let (tx, rx) = futures::channel::oneshot::channel();
let message = RpcDispatcherMessage::Request(method.into(), params, tx);
self.worker_channel.send(message).await.map_err(|err| {
RelayChainError::WorkerCommunicationError(format!(
"Unable to send message to RPC worker: {}",
err
))
})?;
let value = rx.await.map_err(|err| {
RelayChainError::WorkerCommunicationError(format!(
"RPC worker channel closed. This can hint and connectivity issues with the supplied RPC endpoints. Message: {}",
err
))
})??;
serde_json::from_value(value).map_err(|_| {
trace_error(&RelayChainError::GenericError("Unable to deserialize value".to_string()));
RelayChainError::RpcCallError(method.to_string())
})
}
/// Returns information regarding the current epoch.
pub async fn babe_api_current_epoch(&self, at: RelayHash) -> Result<Epoch, RelayChainError> {
self.call_remote_runtime_function("BabeApi_current_epoch", at, None::<()>).await
}
/// Scrape dispute relevant from on-chain, backing votes and resolved disputes.
pub async fn teyrchain_host_on_chain_votes(
&self,
at: RelayHash,
) -> Result<Option<ScrapedOnChainVotes<RelayHash>>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_on_chain_votes", at, None::<()>)
.await
}
/// Returns code hashes of PVFs that require pre-checking by validators in the active set.
pub async fn teyrchain_host_pvfs_require_precheck(
&self,
at: RelayHash,
) -> Result<Vec<ValidationCodeHash>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_pvfs_require_precheck", at, None::<()>)
.await
}
/// Submits a PVF pre-checking statement into the transaction pool.
pub async fn teyrchain_host_submit_pvf_check_statement(
&self,
at: RelayHash,
stmt: PvfCheckStatement,
signature: ValidatorSignature,
) -> Result<(), RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_submit_pvf_check_statement",
at,
Some((stmt, signature)),
)
.await
}
/// Get system health information
pub async fn system_health(&self) -> Result<Health, RelayChainError> {
self.request("system_health", rpc_params![]).await
}
/// Get read proof for `storage_keys`
pub async fn state_get_read_proof(
&self,
storage_keys: Vec<StorageKey>,
at: Option<RelayHash>,
) -> Result<ReadProof<RelayHash>, RelayChainError> {
let params = rpc_params![storage_keys, at];
self.request("state_getReadProof", params).await
}
/// Retrieve storage item at `storage_key`
pub async fn state_get_storage(
&self,
storage_key: StorageKey,
at: Option<RelayHash>,
) -> Result<Option<StorageData>, RelayChainError> {
let params = rpc_params![storage_key, at];
self.request("state_getStorage", params).await
}
/// Get hash of the n-th block in the canon chain.
///
/// By default returns latest block hash.
pub async fn chain_get_head(&self, at: Option<u64>) -> Result<RelayHash, RelayChainError> {
let params = rpc_params![at];
self.request("chain_getHead", params).await
}
/// Returns the validator groups and rotation info localized based on the hypothetical child
/// of a block whose state this is invoked on. Note that `now` in the `GroupRotationInfo`
/// should be the successor of the number of the block.
pub async fn teyrchain_host_validator_groups(
&self,
at: RelayHash,
) -> Result<(Vec<Vec<ValidatorIndex>>, GroupRotationInfo), RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_validator_groups", at, None::<()>)
.await
}
/// Get a vector of events concerning candidates that occurred within a block.
pub async fn teyrchain_host_candidate_events(
&self,
at: RelayHash,
) -> Result<Vec<CandidateEvent>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_candidate_events", at, None::<()>)
.await
}
/// Checks if the given validation outputs pass the acceptance criteria.
pub async fn teyrchain_host_check_validation_outputs(
&self,
at: RelayHash,
para_id: ParaId,
outputs: CandidateCommitments,
) -> Result<bool, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_check_validation_outputs",
at,
Some((para_id, outputs)),
)
.await
}
/// Returns the persisted validation data for the given `ParaId` along with the corresponding
/// validation code hash. Instead of accepting assumption about the para, matches the validation
/// data hash against an expected one and yields `None` if they're not equal.
pub async fn teyrchain_host_assumed_validation_data(
&self,
at: RelayHash,
para_id: ParaId,
expected_hash: RelayHash,
) -> Result<Option<(PersistedValidationData, ValidationCodeHash)>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_persisted_assumed_validation_data",
at,
Some((para_id, expected_hash)),
)
.await
}
/// Get hash of last finalized block.
pub async fn chain_get_finalized_head(&self) -> Result<RelayHash, RelayChainError> {
self.request("chain_getFinalizedHead", rpc_params![]).await
}
/// Get hash of n-th block.
pub async fn chain_get_block_hash(
&self,
block_number: Option<BlockNumber>,
) -> Result<Option<RelayHash>, RelayChainError> {
let params = rpc_params![block_number];
self.request("chain_getBlockHash", params).await
}
/// Yields the persisted validation data for the given `ParaId` along with an assumption that
/// should be used if the para currently occupies a core.
///
/// Returns `None` if either the para is not registered or the assumption is `Freed`
/// and the para already occupies a core.
pub async fn teyrchain_host_persisted_validation_data(
&self,
at: RelayHash,
para_id: ParaId,
occupied_core_assumption: OccupiedCoreAssumption,
) -> Result<Option<PersistedValidationData>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_persisted_validation_data",
at,
Some((para_id, occupied_core_assumption)),
)
.await
}
/// Get the validation code from its hash.
pub async fn teyrchain_host_validation_code_by_hash(
&self,
at: RelayHash,
validation_code_hash: ValidationCodeHash,
) -> Result<Option<ValidationCode>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_validation_code_by_hash",
at,
Some(validation_code_hash),
)
.await
}
/// Yields information on all availability cores as relevant to the child block.
/// Cores are either free or occupied. Free cores can have paras assigned to them.
pub async fn teyrchain_host_availability_cores(
&self,
at: RelayHash,
) -> Result<Vec<CoreState<RelayHash, BlockNumber>>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_availability_cores", at, None::<()>)
.await
}
/// Get runtime version
pub async fn runtime_version(&self, at: RelayHash) -> Result<RuntimeVersion, RelayChainError> {
let params = rpc_params![at];
self.request("state_getRuntimeVersion", params).await
}
/// Returns all onchain disputes.
pub async fn teyrchain_host_disputes(
&self,
at: RelayHash,
) -> Result<Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_disputes", at, None::<()>)
.await
}
/// Returns a list of validators that lost a past session dispute and need to be slashed.
///
/// This is a staging method! Do not use on production runtimes!
pub async fn teyrchain_host_unapplied_slashes(
&self,
at: RelayHash,
) -> Result<Vec<(SessionIndex, CandidateHash, slashing::LegacyPendingSlashes)>, RelayChainError>
{
self.call_remote_runtime_function("TeyrchainHost_unapplied_slashes", at, None::<()>)
.await
}
/// Returns a list of validators that lost a past session dispute and need to be slashed.
pub async fn teyrchain_host_unapplied_slashes_v2(
&self,
at: RelayHash,
) -> Result<Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_unapplied_slashes_v2", at, None::<()>)
.await
}
/// Returns a merkle proof of a validator session key in a past session.
///
/// This is a staging method! Do not use on production runtimes!
pub async fn teyrchain_host_key_ownership_proof(
&self,
at: RelayHash,
validator_id: ValidatorId,
) -> Result<Option<slashing::OpaqueKeyOwnershipProof>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_key_ownership_proof",
at,
Some(validator_id),
)
.await
}
/// Submits an unsigned extrinsic to slash validators who lost a dispute about
/// a candidate of a past session.
///
/// This is a staging method! Do not use on production runtimes!
pub async fn teyrchain_host_submit_report_dispute_lost(
&self,
at: RelayHash,
dispute_proof: slashing::DisputeProof,
key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
) -> Result<Option<()>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_submit_report_dispute_lost",
at,
Some((dispute_proof, key_ownership_proof)),
)
.await
}
pub async fn authority_discovery_authorities(
&self,
at: RelayHash,
) -> Result<Vec<pezsp_authority_discovery::AuthorityId>, RelayChainError> {
self.call_remote_runtime_function("AuthorityDiscoveryApi_authorities", at, None::<()>)
.await
}
/// Fetch the validation code used by a para, making the given `OccupiedCoreAssumption`.
///
/// Returns `None` if either the para is not registered or the assumption is `Freed`
/// and the para already occupies a core.
pub async fn teyrchain_host_validation_code(
&self,
at: RelayHash,
para_id: ParaId,
occupied_core_assumption: OccupiedCoreAssumption,
) -> Result<Option<ValidationCode>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_validation_code",
at,
Some((para_id, occupied_core_assumption)),
)
.await
}
/// Fetch the hash of the validation code used by a para, making the given
/// `OccupiedCoreAssumption`.
pub async fn teyrchain_host_validation_code_hash(
&self,
at: RelayHash,
para_id: ParaId,
occupied_core_assumption: OccupiedCoreAssumption,
) -> Result<Option<ValidationCodeHash>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_validation_code_hash",
at,
Some((para_id, occupied_core_assumption)),
)
.await
}
/// Get the session info for the given session, if stored.
pub async fn teyrchain_host_session_info(
&self,
at: RelayHash,
index: SessionIndex,
) -> Result<Option<SessionInfo>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_session_info", at, Some(index))
.await
}
/// Get the executor parameters for the given session, if stored
pub async fn teyrchain_host_session_executor_params(
&self,
at: RelayHash,
session_index: SessionIndex,
) -> Result<Option<ExecutorParams>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_session_executor_params",
at,
Some(session_index),
)
.await
}
/// Get header at specified hash
pub async fn chain_get_header(
&self,
hash: Option<RelayHash>,
) -> Result<Option<RelayHeader>, RelayChainError> {
let params = rpc_params![hash];
self.request("chain_getHeader", params).await
}
/// Get the receipt of a candidate pending availability. This returns `Some` for any paras
/// assigned to occupied cores in `availability_cores` and `None` otherwise.
pub async fn teyrchain_host_candidate_pending_availability(
&self,
at: RelayHash,
para_id: ParaId,
) -> Result<Option<CommittedCandidateReceipt>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_candidate_pending_availability",
at,
Some(para_id),
)
.await
}
/// Returns the session index expected at a child of the block.
///
/// This can be used to instantiate a `SigningContext`.
pub async fn teyrchain_host_session_index_for_child(
&self,
at: RelayHash,
) -> Result<SessionIndex, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_session_index_for_child", at, None::<()>)
.await
}
/// Get the current validators.
pub async fn teyrchain_host_validators(
&self,
at: RelayHash,
) -> Result<Vec<ValidatorId>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_validators", at, None::<()>)
.await
}
/// Get the contents of all channels addressed to the given recipient. Channels that have no
/// messages in them are also included.
pub async fn teyrchain_host_inbound_hrmp_channels_contents(
&self,
para_id: ParaId,
at: RelayHash,
) -> Result<BTreeMap<ParaId, Vec<InboundHrmpMessage>>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_inbound_hrmp_channels_contents",
at,
Some(para_id),
)
.await
}
/// Get all the pending inbound messages in the downward message queue for a para.
pub async fn teyrchain_host_dmq_contents(
&self,
para_id: ParaId,
at: RelayHash,
) -> Result<Vec<InboundDownwardMessage>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_dmq_contents", at, Some(para_id))
.await
}
/// Get the minimum number of backing votes for a candidate.
pub async fn teyrchain_host_minimum_backing_votes(
&self,
at: RelayHash,
_session_index: SessionIndex,
) -> Result<u32, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_minimum_backing_votes", at, None::<()>)
.await
}
pub async fn teyrchain_host_node_features(
&self,
at: RelayHash,
) -> Result<NodeFeatures, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_node_features", at, None::<()>)
.await
}
pub async fn teyrchain_host_disabled_validators(
&self,
at: RelayHash,
) -> Result<Vec<ValidatorIndex>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_disabled_validators", at, None::<()>)
.await
}
#[allow(missing_docs)]
pub async fn teyrchain_host_async_backing_params(
&self,
at: RelayHash,
) -> Result<AsyncBackingParams, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_async_backing_params", at, None::<()>)
.await
}
#[allow(missing_docs)]
pub async fn teyrchain_host_staging_approval_voting_params(
&self,
at: RelayHash,
_session_index: SessionIndex,
) -> Result<ApprovalVotingParams, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_staging_approval_voting_params",
at,
None::<()>,
)
.await
}
pub async fn teyrchain_host_para_backing_state(
&self,
at: RelayHash,
para_id: ParaId,
) -> Result<Option<BackingState>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_para_backing_state", at, Some(para_id))
.await
}
pub async fn teyrchain_host_claim_queue(
&self,
at: RelayHash,
) -> Result<BTreeMap<CoreIndex, VecDeque<ParaId>>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_claim_queue", at, None::<()>)
.await
}
/// Get the receipt of all candidates pending availability.
pub async fn teyrchain_host_candidates_pending_availability(
&self,
at: RelayHash,
para_id: ParaId,
) -> Result<Vec<CommittedCandidateReceipt>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_candidates_pending_availability",
at,
Some(para_id),
)
.await
}
pub async fn teyrchain_host_scheduling_lookahead(
&self,
at: RelayHash,
) -> Result<u32, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_scheduling_lookahead", at, None::<()>)
.await
}
pub async fn teyrchain_host_validation_code_bomb_limit(
&self,
at: RelayHash,
) -> Result<u32, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_validation_code_bomb_limit",
at,
None::<()>,
)
.await
}
pub async fn validation_code_hash(
&self,
at: RelayHash,
para_id: ParaId,
occupied_core_assumption: OccupiedCoreAssumption,
) -> Result<Option<ValidationCodeHash>, RelayChainError> {
self.call_remote_runtime_function(
"TeyrchainHost_validation_code_hash",
at,
Some((para_id, occupied_core_assumption)),
)
.await
}
pub async fn teyrchain_host_backing_constraints(
&self,
at: RelayHash,
para_id: ParaId,
) -> Result<Option<Constraints>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_backing_constraints", at, Some(para_id))
.await
}
fn send_register_message_to_worker(
&self,
message: RpcDispatcherMessage,
) -> Result<(), RelayChainError> {
self.worker_channel
.try_send(message)
.map_err(|e| RelayChainError::WorkerCommunicationError(e.to_string()))
}
/// Get a stream of all imported relay chain headers
pub fn get_imported_heads_stream(&self) -> Result<Receiver<RelayHeader>, RelayChainError> {
let (tx, rx) =
futures::channel::mpsc::channel::<RelayHeader>(NOTIFICATION_CHANNEL_SIZE_LIMIT);
self.send_register_message_to_worker(RpcDispatcherMessage::RegisterImportListener(tx))?;
Ok(rx)
}
/// Get a stream of new best relay chain headers
pub fn get_best_heads_stream(&self) -> Result<Receiver<RelayHeader>, RelayChainError> {
let (tx, rx) =
futures::channel::mpsc::channel::<RelayHeader>(NOTIFICATION_CHANNEL_SIZE_LIMIT);
self.send_register_message_to_worker(RpcDispatcherMessage::RegisterBestHeadListener(tx))?;
Ok(rx)
}
/// Get a stream of finalized relay chain headers
pub fn get_finalized_heads_stream(&self) -> Result<Receiver<RelayHeader>, RelayChainError> {
let (tx, rx) =
futures::channel::mpsc::channel::<RelayHeader>(NOTIFICATION_CHANNEL_SIZE_LIMIT);
self.send_register_message_to_worker(RpcDispatcherMessage::RegisterFinalizationListener(
tx,
))?;
Ok(rx)
}
pub async fn teyrchain_host_para_ids(
&self,
at: RelayHash,
) -> Result<Vec<ParaId>, RelayChainError> {
self.call_remote_runtime_function("TeyrchainHost_para_ids", at, None::<()>)
.await
}
}
/// Send `header` through all channels contained in `senders`.
/// If no one is listening to the sender, it is removed from the vector.
pub fn distribute_header(header: RelayHeader, senders: &mut Vec<Sender<RelayHeader>>) {
senders.retain_mut(|e| {
match e.try_send(header.clone()) {
// Receiver has been dropped, remove Sender from list.
Err(error) if error.is_disconnected() => false,
// Channel is full. This should not happen.
// TODO: Improve error handling here
// https://github.com/pezkuwichain/kurdistan-sdk/issues/90
Err(error) => {
tracing::error!(target: LOG_TARGET, ?error, "Event distribution channel has reached its limit. This can lead to missed notifications.");
true
},
_ => true,
}
});
}