Skip to content

Commit

Permalink
Update parachain client
Browse files Browse the repository at this point in the history
  • Loading branch information
sea212 committed Apr 30, 2024
1 parent e58f4cf commit 6f94464
Show file tree
Hide file tree
Showing 10 changed files with 126 additions and 203 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ sc-consensus-grandpa = { git = "https://github.com/paritytech/polkadot-sdk", bra
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-keystore = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-network = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-network-common = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-network-statement = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-offchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-rpc = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
sc-rpc-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
Expand Down
2 changes: 2 additions & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pallet-author-inherent = { workspace = true, features = ["default"], optional =
pallet-parachain-staking = { workspace = true, features = ["default"], optional = true }
parity-scale-codec = { workspace = true, features = ["default"], optional = true }
sc-chain-spec = { workspace = true, optional = true }
sc-network-sync = { workspace = true, optional = true }
sc-tracing = { workspace = true, optional = true }
serde = { workspace = true, features = ["default"], optional = true }
session-keys-primitives = { workspace = true, features = ["default"], optional = true }
Expand Down Expand Up @@ -149,6 +150,7 @@ parachain = [
"parity-scale-codec",
"session-keys-primitives",
"sc-chain-spec",
"sc-network-sync",
"sc-tracing",
"serde",
"sp-keystore",
Expand Down
7 changes: 5 additions & 2 deletions node/src/chain_spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,10 @@ macro_rules! generate_generic_genesis_function {
per_block_distribution: LIQUIDITY_MINING_PTD.mul_ceil(LIQUIDITY_MINING),
},
#[cfg(feature = "parachain")]
parachain_info: $runtime::ParachainInfoConfig { parachain_id: acs.parachain_id },
parachain_info: $runtime::ParachainInfoConfig {
parachain_id: acs.parachain_id,
..Default::default()
},
#[cfg(feature = "parachain")]
parachain_staking: $runtime::ParachainStakingConfig {
blocks_per_round: acs.blocks_per_round,
Expand Down Expand Up @@ -232,7 +235,7 @@ pub struct Extensions {
/// The relay chain of the Parachain.
pub relay_chain: String,
/// Known bad block hashes.
pub bad_blocks: sc_client_api::BadBlocks<polkadot_primitives::v2::Block>,
pub bad_blocks: sc_client_api::BadBlocks<polkadot_primitives::Block>,
}

#[cfg(feature = "parachain")]
Expand Down
4 changes: 2 additions & 2 deletions node/src/chain_spec/zeitgeist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ use {
zeitgeist_primitives::constants::ztg::{STAKING_PTD, TOTAL_INITIAL_ZTG},
zeitgeist_runtime::{
CollatorDeposit, DefaultBlocksPerRound, DefaultCollatorCommission,
DefaultParachainBondReservePercent, EligibilityValue, MinCollatorStk, PolkadotXcmConfig,
DefaultParachainBondReservePercent, EligibilityValue, MinCandidateStk, PolkadotXcmConfig,
},
};

cfg_if::cfg_if! {
if #[cfg(feature = "parachain")] {
const DEFAULT_STAKING_AMOUNT_ZEITGEIST: u128 = MinCollatorStk::get();
const DEFAULT_STAKING_AMOUNT_ZEITGEIST: u128 = MinCandidateStk::get();
const DEFAULT_COLLATOR_BALANCE_ZEITGEIST: Option<u128> =
DEFAULT_STAKING_AMOUNT_ZEITGEIST.checked_add(CollatorDeposit::get());
const NUM_SELECTED_CANDIDATES: u32 = 8;
Expand Down
117 changes: 18 additions & 99 deletions node/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,15 @@
#[cfg(feature = "parachain")]
mod cli_parachain;

use super::service::{
AdditionalRuntimeApiCollection, FullBackend, FullClient, IdentifyVariant, RuntimeApiCollection,
};
use super::service::{FullBackend, FullClient, IdentifyVariant};
use clap::Parser;
#[cfg(feature = "parachain")]
pub use cli_parachain::RelayChainCli;
use sc_cli::{ChainSpec, SubstrateCli};
use sc_client_api::{Backend as BackendT, BlockchainEvents, KeysIter, PairsIter};
use sp_api::{CallApiAt, NumberFor, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use sc_client_api::{KeysIter, PairsIter};
use sp_api::NumberFor;
use sp_consensus::BlockStatus;
use sp_runtime::{
generic::SignedBlock,
traits::{BlakeTwo256, Block as BlockT},
Justifications,
};
use sp_runtime::{generic::SignedBlock, traits::Block as BlockT, Justifications};
use sp_storage::{ChildInfo, StorageData, StorageKey};
use std::sync::Arc;
use zeitgeist_primitives::types::{Block, Header};
Expand Down Expand Up @@ -212,6 +205,20 @@ pub struct Cli {
pub storage_monitor: sc_storage_monitor::StorageMonitorParams,
}

#[cfg(feature = "parachain")]
impl Cli {
pub(crate) fn runtime_version(spec: &Box<dyn sc_service::ChainSpec>) -> sc_cli::RuntimeVersion {
match spec {
#[cfg(feature = "with-zeitgeist-runtime")]
spec if spec.is_zeitgeist() => zeitgeist_runtime::VERSION,
#[cfg(feature = "with-battery-station-runtime")]
_ => zeitgeist_runtime::VERSION,
#[cfg(not(feature = "with-battery-station-runtime"))]
_ => panic!("{}", crate::BATTERY_STATION_RUNTIME_NOT_AVAILABLE),
}
}
}

impl SubstrateCli for Cli {
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
Expand Down Expand Up @@ -242,79 +249,6 @@ impl SubstrateCli for Cli {
}
}

/// Config that abstracts over all available client implementations.
///
/// For a concrete type there exists [`Client`].
pub trait AbstractClient<Block, Backend>:
BlockchainEvents<Block>
+ Sized
+ Send
+ Sync
+ ProvideRuntimeApi<Block>
+ HeaderBackend<Block>
+ CallApiAt<Block, StateBackend = Backend::State>
where
Block: BlockT,
Backend: BackendT<Block>,
Backend::State: sp_api::StateBackend<BlakeTwo256>,
Self::Api: RuntimeApiCollection + AdditionalRuntimeApiCollection,
{
}

impl<Block, Backend, Client> AbstractClient<Block, Backend> for Client
where
Block: BlockT,
Backend: BackendT<Block>,
Backend::State: sp_api::StateBackend<BlakeTwo256>,
Client: BlockchainEvents<Block>
+ ProvideRuntimeApi<Block>
+ HeaderBackend<Block>
+ Sized
+ Send
+ Sync
+ CallApiAt<Block, StateBackend = Backend::State>,
Client::Api: RuntimeApiCollection + AdditionalRuntimeApiCollection,
{
}

/// Execute something with the client instance.
///
/// As there exist multiple chains inside Zeitgeist, like Zeitgeist itself,
/// Battery Station etc., there can exist different kinds of client types. As these
/// client types differ in the generics that are being used, we can not easily
/// return them from a function. For returning them from a function there exists
/// [`Client`]. However, the problem on how to use this client instance still
/// exists. This trait "solves" it in a dirty way. It requires a type to
/// implement this trait and than the [`execute_with_client`](ExecuteWithClient::execute_with_client)
/// function can be called with any possible client
/// instance.
///
/// In a perfect world, we could make a closure work in this way.
pub trait ExecuteWithClient {
/// The return type when calling this instance.
type Output;

/// Execute whatever should be executed with the given client instance.
fn execute_with_client<Client, Api, Backend>(self, client: Arc<Client>) -> Self::Output
where
Backend: sc_client_api::Backend<Block>,
Backend::State: sc_client_api::backend::StateBackend<BlakeTwo256>,
Api: RuntimeApiCollection + AdditionalRuntimeApiCollection,
Client: AbstractClient<Block, Backend, Api = Api> + 'static;
}

/// A handle to a Zeitgeist client instance.
///
/// The Zeitgeist service supports multiple different runtimes (Zeitgeist, Battery
/// Station, etc.). As each runtime has a specialized client, we need to hide them
/// behind a trait. This is this trait.
///
/// When wanting to work with the inner client, you need to use `execute_with`.
pub trait ClientHandle {
/// Execute the given something with the client.
fn execute_with<T: ExecuteWithClient>(&self, t: T) -> T::Output;
}

/// A client instance of Zeitgeist.
#[derive(Clone)]
pub enum Client {
Expand All @@ -338,21 +272,6 @@ impl From<Arc<FullClient<ZeitgeistRuntimeApi, ZeitgeistExecutor>>> for Client {
}
}

impl ClientHandle for Client {
fn execute_with<T: ExecuteWithClient>(&self, t: T) -> T::Output {
match self {
#[cfg(feature = "with-battery-station-runtime")]
Self::BatteryStation(client) => {
T::execute_with_client::<_, _, FullBackend>(t, client.clone())
}
#[cfg(feature = "with-zeitgeist-runtime")]
Self::Zeitgeist(client) => {
T::execute_with_client::<_, _, FullBackend>(t, client.clone())
}
}
}
}

macro_rules! match_client {
($self:ident, $method:ident($($param:ident),*)) => {
match $self {
Expand Down
42 changes: 11 additions & 31 deletions node/src/cli/cli_parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@

use clap::Parser;
use sc_cli::{
self, ChainSpec, ImportParams, KeystoreParams, NetworkParams, RuntimeVersion, SharedParams,
SubstrateCli,
self, ChainSpec, ImportParams, KeystoreParams, NetworkParams, SharedParams, SubstrateCli,
};
use sc_service::config::{BasePath, PrometheusConfig};
use std::{net::SocketAddr, path::PathBuf};
use std::path::PathBuf;

const BATTERY_STATION_RELAY_ID: &str = "battery_station_relay_v3";

Expand All @@ -46,12 +45,13 @@ impl RelayChainCli {
) -> Self {
let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec);
let chain_id = extension.map(|e| e.relay_chain.clone());
let base_path = para_config
.base_path
.as_ref()
.map(|x| x.path().join(chain_id.clone().unwrap_or_else(|| "polkadot".into())));
let base_path = para_config.base_path.path().join("polkadot");

Self { base_path, chain_id, base: clap::Parser::parse_from(relay_chain_args) }
Self {
base_path: Some(base_path),
chain_id,
base: polkadot_cli::RunCmd::parse_from(relay_chain_args),
}
}
}

Expand Down Expand Up @@ -127,24 +127,12 @@ impl sc_cli::CliConfiguration<Self> for RelayChainCli {
self.base.base.rpc_cors(is_dev)
}

fn rpc_http(&self, default_listen_port: u16) -> sc_cli::Result<Option<SocketAddr>> {
self.base.base.rpc_http(default_listen_port)
}

fn rpc_ipc(&self) -> sc_cli::Result<Option<String>> {
self.base.base.rpc_ipc()
}

fn rpc_methods(&self) -> sc_cli::Result<sc_service::config::RpcMethods> {
self.base.base.rpc_methods()
}

fn rpc_ws(&self, default_listen_port: u16) -> sc_cli::Result<Option<SocketAddr>> {
self.base.base.rpc_ws(default_listen_port)
}

fn rpc_ws_max_connections(&self) -> sc_cli::Result<Option<usize>> {
self.base.base.rpc_ws_max_connections()
fn rpc_max_connections(&self) -> sc_cli::Result<u32> {
self.base.base.rpc_max_connections()
}

fn shared_params(&self) -> &SharedParams {
Expand All @@ -168,11 +156,7 @@ impl sc_cli::DefaultConfigurationValues for RelayChainCli {
9616
}

fn rpc_http_listen_port() -> u16 {
9934
}

fn rpc_ws_listen_port() -> u16 {
fn rpc_listen_port() -> u16 {
9945
}
}
Expand Down Expand Up @@ -211,10 +195,6 @@ impl sc_cli::SubstrateCli for RelayChainCli {
}
}

fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
polkadot_cli::Cli::native_runtime_version(chain_spec)
}

fn support_url() -> String {
crate::cli::SUPPORT_URL.into()
}
Expand Down
18 changes: 9 additions & 9 deletions node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ pub fn run() -> sc_cli::Result<()> {
let _ = builder.init();
let chain_spec =
&crate::cli::load_spec(&params.shared_params.chain.clone().unwrap_or_default())?;
let state_version = Cli::native_runtime_version(chain_spec).state_version();
let state_version = Cli::runtime_version(chain_spec).state_version();

let buf = match chain_spec {
#[cfg(feature = "with-zeitgeist-runtime")]
Expand Down Expand Up @@ -430,11 +430,11 @@ pub fn run() -> sc_cli::Result<()> {
Ok((cmd.run(client, backend, None), task_manager))
})
}
Some(Subcommand::TryRuntime(_)) => Err("The `try-runtime` subcommand has been migrated to a \
standalone CLI (https://github.com/paritytech/try-runtime-cli). It is no longer \
being maintained here and will be removed entirely some time after January 2024. \
Please remove this subcommand from your runtime and use the standalone CLI."
.into()),
Some(Subcommand::TryRuntime(_)) => Err("The `try-runtime` subcommand has been migrated to a \
standalone CLI (https://github.com/paritytech/try-runtime-cli). It is no longer \
being maintained here and will be removed entirely some time after January 2024. \
Please remove this subcommand from your runtime and use the standalone CLI."
.into()),
None => none_command(cli),
}
}
Expand Down Expand Up @@ -466,10 +466,10 @@ fn none_command(cli: Cli) -> sc_cli::Result<()> {
cli.parachain_id.or(parachain_id_extension).unwrap_or(super::POLKADOT_PARACHAIN_ID),
);
let parachain_account =
AccountIdConversion::<polkadot_primitives::v2::AccountId>::into_account_truncating(
AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(
&parachain_id,
);
let state_version = Cli::native_runtime_version(chain_spec).state_version();
let state_version = Cli::runtime_version(chain_spec).state_version();
let block: zeitgeist_runtime::Block =
cumulus_client_cli::generate_genesis_block(&**chain_spec, state_version)
.map_err(|e| format!("{:?}", e))?;
Expand All @@ -496,7 +496,7 @@ fn none_command(cli: Cli) -> sc_cli::Result<()> {
if parachain_config.role.is_authority() { "yes" } else { "no" }
);

if !collator_options.relay_chain_rpc_urls.is_empty() && !cli.relaychain_args.is_empty() {
if !cli.run.relay_chain_rpc_urls.is_empty() && !cli.relaychain_args.is_empty() {
log::warn!(
"Detected relay chain node arguments together with --relay-chain-rpc-url. This \
command starts a minimal Polkadot node that only uses a network-related subset \
Expand Down
7 changes: 0 additions & 7 deletions node/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,11 @@ impl sc_executor::NativeExecutionDispatch for ZeitgeistExecutor {
/// Can be called for a `Configuration` to check if it is a configuration for
/// the `Zeitgeist` network.
pub trait IdentifyVariant {
/// Returns `true` if this is a configuration for the `Battery Station` network.
fn is_battery_station(&self) -> bool;

/// Returns `true` if this is a configuration for the `Zeitgeist` network.
fn is_zeitgeist(&self) -> bool;
}

impl IdentifyVariant for Box<dyn ChainSpec> {
fn is_battery_station(&self) -> bool {
self.id().starts_with("battery_station")
}

fn is_zeitgeist(&self) -> bool {
self.id().starts_with("zeitgeist")
}
Expand Down
Loading

0 comments on commit 6f94464

Please sign in to comment.