Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Prev Previous commit
Next Next commit
WIP
  • Loading branch information
cecton committed Feb 3, 2020
commit 1ff8f99e79c00a0bb10165d461797a1f4efbd3fc
5 changes: 3 additions & 2 deletions collator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use sp_consensus::{
};
use sp_inherents::InherentDataProviders;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use sc_cli;

use polkadot_collator::{
BuildParachainContext, InvalidHead, Network as CollatorNetwork, ParachainContext,
Expand Down Expand Up @@ -350,15 +351,15 @@ pub fn run_collator<Block, SP>(
para_id: ParaId,
key: Arc<CollatorPair>,
configuration: polkadot_collator::Configuration,
) -> Result<(), sc_service::Error>
) -> Result<(), sc_cli::error::Error>
where
Block: BlockT,
SP: SetupParachain<Block> + Send + 'static,
<<SP as SetupParachain<Block>>::ProposerFactory as Environment<Block>>::Proposer: Send,
{
let builder = CollatorBuilder::new(setup_parachain);
let exit = future::ready(()); // TODO to delete
polkadot_collator::run_collator(builder, para_id, exit, key, configuration).map_err(|_| "boo (to delete)".into())
polkadot_collator::run_collator(builder, para_id, exit, key, configuration)
}

#[cfg(test)]
Expand Down
14 changes: 7 additions & 7 deletions test/parachain/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
use std::path::PathBuf;

use sc_cli;
use polkadot_cli::Cli as PolkadotCli;
pub use polkadot_cli::Cli as PolkadotCli;
use structopt::StructOpt;

/// Sub-commands supported by the collator.
#[derive(Debug, StructOpt, Clone)]
enum Subcommand {
pub enum Subcommand {
#[structopt(flatten)]
Base(sc_cli::Subcommand),
/// Export the genesis state of the parachain.
Expand All @@ -32,21 +32,21 @@ enum Subcommand {

/// Command for exporting the genesis state of the parachain
#[derive(Debug, StructOpt, Clone)]
struct ExportGenesisStateCommand {
pub struct ExportGenesisStateCommand {
/// Output file name or stdout if unspecified.
#[structopt(parse(from_os_str))]
pub output: Option<PathBuf>,
}

#[derive(Debug, StructOpt, Clone)]
struct Cli {
pub struct Cli {
#[structopt(subcommand)]
subcommand: Option<Subcommand>,
pub subcommand: Option<Subcommand>,

#[structopt(flatten)]
run: sc_cli::RunCmd,
pub run: sc_cli::RunCmd,

/// Relaychain arguments
#[structopt(raw = true)]
relaychain_args: Vec<String>,
pub relaychain_args: Vec<String>,
}
220 changes: 100 additions & 120 deletions test/parachain/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@
// along with Cumulus. If not, see <http://www.gnu.org/licenses/>.

use crate::chain_spec;
use crate::cli::{Cli, PolkadotCli, Subcommand};

use std::{path::PathBuf, sync::Arc};
use futures::{future::Map, FutureExt};

use parachain_runtime::Block;

pub use sc_cli::{error::{self, Result}, VersionInfo};
use sc_cli::{error::{self, Result}, VersionInfo};
use sc_client::genesis;
use sc_service::{Configuration, Roles as ServiceRoles};
use sp_core::hexdisplay::HexDisplay;
Expand All @@ -27,106 +31,110 @@ use sp_runtime::{
BuildStorage,
};
use polkadot_service::ChainSpec as ChainSpecPolkadot;
use polkadot_cli::Cli as PolkadotCli;

use futures::{future::Map, FutureExt};

use codec::Encode;

use log::info;

use std::{path::PathBuf, sync::Arc};

use structopt::StructOpt;

/// Parse command line arguments into service configuration.
pub fn run(version: VersionInfo) -> error::Result<()> {
/*
type Config<T> = Configuration<(), T>;

match parse_and_prepare::<SubCommands, NoCustom, _>(
&version,
"cumulus-test-parachain-collator",
args_parachain,
) {
ParseAndPrepare::Run(cmd) => cmd.run(
load_spec,
exit,
|exit, _cli_args, _custom_args, mut config: Config<_>| {
info!("{}", version.name);
info!(" version {}", config.full_version());
info!(" by {}, 2019", version.author);
info!("Chain specification: {}", config.chain_spec.name());
info!("Node name: {}", config.name);
info!("Roles: {:?}", config.roles);
info!("Parachain id: {:?}", crate::PARA_ID);

// TODO
let key = Arc::new(sp_core::Pair::from_seed(&[10; 32]));

// TODO
config.network.listen_addresses = Vec::new();

let mut polkadot_config = parse_and_prepare::<NoCustom, NoCustom, _>(
&version,
"cumulus-test-parachain-collator",
args_relaychain,
).into_configuration::<CustomConfigurationPolkadot, _, _, _>(
load_spec_polkadot,
config.in_chain_config_dir("polkadot"),
)
.map_err(|e| e.to_string())?
.expect(
"can only fail when this is a CustomCommand. Running parse_and_prepare with \
NoCustom can never return a CustomCommand; therefore this will never fail; qed"
);
polkadot_config.network.boot_nodes = config.network.boot_nodes.clone();

if let Some(ref config_dir) = polkadot_config.config_dir {
polkadot_config.database = sc_service::config::DatabaseConfig::Path {
cache_size: Default::default(),
path: config_dir.join("db"),
};

polkadot_config.keystore = sc_service::config::KeystoreConfig::Path {
path: config_dir.join("keystore"),
password: None,
};
}

match config.roles {
ServiceRoles::LIGHT => unimplemented!("Light client not supported!"),
_ => crate::service::run_collator(config, exit, key, polkadot_config),
}
.map_err(|e| format!("{:?}", e))
},
),
ParseAndPrepare::BuildSpec(cmd) => cmd.run::<NoCustom, _, _, _>(load_spec),
ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder(
|config: Config<_>| Ok(new_full_start!(config).0),
load_spec,
exit,
),
ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder(
|config: Config<_>| Ok(new_full_start!(config).0),
load_spec,
exit,
),
ParseAndPrepare::CheckBlock(cmd) => cmd.run_with_builder(
|config: Config<_>| Ok(new_full_start!(config).0),
let opt: Cli = sc_cli::from_args(&version);

let mut config = sc_service::Configuration::default();
config.impl_name = "cumulus-test-parachain-collator";

match opt.subcommand {
Some(Subcommand::Base(subcommand)) => sc_cli::run_subcommand(
config,
subcommand,
load_spec,
exit,
|config: Configuration<_, _>| Ok(new_full_start!(config).0),
&version,
),
ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec),
ParseAndPrepare::RevertChain(cmd) => {
cmd.run_with_builder(|config: Config<_>| Ok(new_full_start!(config).0), load_spec)
}
ParseAndPrepare::CustomCommand(SubCommands::ExportGenesisState(cmd)) => {
export_genesis_state(cmd.output)
}
}?;

Ok(())
Some(Subcommand::ExportGenesisState(params)) => {
sc_cli::init_logger("");

let storage = (&chain_spec::get_chain_spec()).build_storage()?;

let child_roots = storage.children.iter().map(|(sk, child_content)| {
let state_root = <<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
child_content.data.clone().into_iter().collect(),
);
(sk.clone(), state_root.encode())
});
let state_root = <<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
storage.top.clone().into_iter().chain(child_roots).collect(),
);
let block: Block = genesis::construct_genesis_block(state_root);

let header_hex = format!("0x{:?}", HexDisplay::from(&block.header().encode()));

if let Some(output) = params.output {
std::fs::write(output, header_hex)?;
} else {
println!("{}", header_hex);
}

Ok(())
},
None => {
sc_cli::init(&mut config, load_spec, &opt.run.shared_params, &version)?;

info!("{}", version.name);
info!(" version {}", config.full_version());
info!(" by {}, 2019", version.author);
info!("Chain specification: {}", config.expect_chain_spec().name());
info!("Node name: {}", config.name);
info!("Roles: {:?}", config.roles);
info!("Parachain id: {:?}", crate::PARA_ID);

// TODO
let key = Arc::new(sp_core::Pair::from_seed(&[10; 32]));

let mut polkadot_config = Configuration::default();
polkadot_config.impl_name = "cumulus-test-parachain-collator";
polkadot_config.config_dir = config.in_chain_config_dir("polkadot");

// TODO: parse_address is private
/*
let rpc_interface: &str = interface_str(opt.run.rpc_external, opt.run.unsafe_rpc_external, opt.run.validator)?;
config.rpc_http = Some(parse_address(&format!("{}:{}", rpc_interface, 9934), opt.run.rpc_port)?);
let ws_interface: &str = interface_str(opt.run.ws_external, opt.run.unsafe_ws_external, opt.run.validator)?;
config.rpc_ws = Some(parse_address(&format!("{}:{}", ws_interface, 9945), opt.run.ws_port)?);
let grafana_interface: &str = if opt.run.grafana_external { "0.0.0.0" } else { "127.0.0.1" };
config.grafana_port = Some(
parse_address(&format!("{}:{}", grafana_interface, 9956), opt.run.grafana_port)?
);
*/

let polkadot_opt: PolkadotCli = sc_cli::from_iter(opt.relaychain_args, &version);

// TODO
polkadot_config.chain_spec = Some(sc_cli::load_spec(&polkadot_opt.run.shared_params, load_spec_polkadot)?);
// TODO: base_path is private
//polkadot_config.config_dir = Some(sc_cli::base_path(&polkadot_opt.run.shared_params, &version));
polkadot_config.impl_commit = version.commit;
polkadot_config.impl_version = version.version;

// TODO
if let Some(ref config_dir) = polkadot_config.config_dir {
polkadot_config.database = sc_service::config::DatabaseConfig::Path {
cache_size: Default::default(),
path: config_dir.join("db"),
};
}
// TODO
polkadot_config.network.boot_nodes = polkadot_config.network.boot_nodes.clone();
polkadot_config.telemetry_endpoints = polkadot_config.expect_chain_spec().telemetry_endpoints().clone();

sc_cli::update_config_for_running_node(&mut polkadot_config, polkadot_opt.run);

match config.roles {
ServiceRoles::LIGHT => unimplemented!("Light client not supported!"),
_ => crate::service::run_collator(config, key, polkadot_config),
}
},
}
}

fn load_spec(_: &str) -> std::result::Result<Option<chain_spec::ChainSpec>, String> {
Expand All @@ -138,31 +146,3 @@ fn load_spec_polkadot(_: &str) -> std::result::Result<Option<ChainSpecPolkadot>,
&include_bytes!("../res/polkadot_chainspec.json")[..],
)).transpose()
}

/// Export the genesis state of the parachain.
fn export_genesis_state(output: Option<PathBuf>) -> error::Result<()> {
let storage = (&chain_spec::get_chain_spec()).build_storage()?;

let child_roots = storage.children.iter().map(|(sk, child_content)| {
let state_root = <<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
child_content.data.clone().into_iter().collect(),
);
(sk.clone(), state_root.encode())
});
let state_root = <<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
storage.top.clone().into_iter().chain(child_roots).collect(),
);
let block: Block = genesis::construct_genesis_block(state_root);

let header_hex = format!("0x{:?}", HexDisplay::from(&block.header().encode()));

if let Some(output) = output {
std::fs::write(output, header_hex)?;
} else {
println!("{}", header_hex);
}

Ok(())
*/
todo!();
}
5 changes: 2 additions & 3 deletions test/parachain/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use sc_network::construct_simple_protocol;
use sc_service::{AbstractService, Configuration};
use sp_consensus::{BlockImport, Environment, Proposer};
use sp_inherents::InherentDataProviders;
use sc_cli;

use futures::{future, task::Spawn, FutureExt, TryFutureExt};

Expand Down Expand Up @@ -80,7 +81,7 @@ pub fn run_collator<E: sc_service::ChainSpecExtension>(
config: Configuration<GenesisConfig, E>,
key: Arc<polkadot_primitives::parachain::CollatorPair>,
polkadot_config: polkadot_collator::Configuration,
) -> Result<(), sc_service::Error> {
) -> Result<(), sc_cli::error::Error> {
let (builder, inherent_data_providers) = new_full_start!(config);
inherent_data_providers
.register_provider(sp_timestamp::InherentDataProvider)
Expand All @@ -94,7 +95,6 @@ pub fn run_collator<E: sc_service::ChainSpecExtension>(
transaction_pool: service.transaction_pool(),
};

let on_exit = service.on_exit();
let block_import = service.client();

let setup_parachain = SetupParachain {
Expand All @@ -107,7 +107,6 @@ pub fn run_collator<E: sc_service::ChainSpecExtension>(
cumulus_collator::run_collator(
setup_parachain,
crate::PARA_ID,
on_exit,
key,
polkadot_config,
)
Expand Down