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

Move ExportGenesisStateCommand and ExportGenesisWasmCommand to cumulus-client-cli #1325

Merged
merged 6 commits into from
Jun 18, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
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
6 changes: 4 additions & 2 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions client/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ edition = "2021"

[dependencies]
clap = { version = "3.1", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0" }

# Substrate
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
url = "2.2.2"
186 changes: 164 additions & 22 deletions client/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,28 @@

#![warn(missing_docs)]

use clap::Parser;
use sc_service::{
config::{PrometheusConfig, TelemetryEndpoints},
BasePath, TransactionPoolOptions,
};
use std::{
fs,
io::{self, Write},
net::SocketAddr,
path::PathBuf,
};

use codec::Encode;
use sc_chain_spec::ChainSpec;
use sc_service::{
config::{PrometheusConfig, TelemetryEndpoints},
BasePath, TransactionPoolOptions,
};
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::{
traits::{Block as BlockT, Hash as HashT, Header as HeaderT, Zero},
StateVersion,
};
use url::Url;

/// The `purge-chain` command used to remove the whole chain: the parachain and the relay chain.
#[derive(Debug, Parser)]
#[derive(Debug, clap::Parser)]
pub struct PurgeChainCmd {
/// The base struct of the purge-chain command.
#[clap(flatten)]
Expand Down Expand Up @@ -119,6 +127,140 @@ impl sc_cli::CliConfiguration for PurgeChainCmd {
}
}

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

/// Write output in binary. Default is to write in hex.
#[clap(short, long)]
pub raw: bool,

#[allow(missing_docs)]
#[clap(flatten)]
pub shared_params: sc_cli::SharedParams,
}

impl ExportGenesisStateCommand {
/// Run the export-genesis-state command
pub fn run<Block: BlockT>(
&self,
chain_spec: &dyn ChainSpec,
genesis_state_version: StateVersion,
) -> sc_cli::Result<()> {
let block: Block = generate_genesis_block(chain_spec, genesis_state_version)?;
let raw_header = block.header().encode();
let output_buf = if self.raw {
raw_header
} else {
format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()
};

if let Some(output) = &self.output {
fs::write(output, output_buf)?;
} else {
io::stdout().write_all(&output_buf)?;
}

Ok(())
}
}

/// Generate the genesis block from a given ChainSpec.
pub fn generate_genesis_block<Block: BlockT>(
chain_spec: &dyn ChainSpec,
genesis_state_version: StateVersion,
) -> Result<Block, String> {
let storage = chain_spec.build_storage()?;

let child_roots = storage.children_default.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(),
genesis_state_version,
);
(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(),
genesis_state_version,
);

let extrinsics_root = <<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
Vec::new(),
sp_runtime::StateVersion::V0,
);

Ok(Block::new(
<<Block as BlockT>::Header as HeaderT>::new(
Zero::zero(),
extrinsics_root,
state_root,
Default::default(),
Default::default(),
),
Default::default(),
))
}

impl sc_cli::CliConfiguration for ExportGenesisStateCommand {
fn shared_params(&self) -> &sc_cli::SharedParams {
&self.shared_params
}
}

/// Command for exporting the genesis wasm file.
#[derive(Debug, clap::Parser)]
pub struct ExportGenesisWasmCommand {
/// Output file name or stdout if unspecified.
#[clap(parse(from_os_str))]
pub output: Option<PathBuf>,

/// Write output in binary. Default is to write in hex.
#[clap(short, long)]
pub raw: bool,

#[allow(missing_docs)]
#[clap(flatten)]
pub shared_params: sc_cli::SharedParams,
}

impl ExportGenesisWasmCommand {
/// Run the export-genesis-state command
pub fn run(&self, chain_spec: &dyn ChainSpec) -> sc_cli::Result<()> {
let raw_wasm_blob = extract_genesis_wasm(chain_spec)?;
let output_buf = if self.raw {
raw_wasm_blob
} else {
format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()
};

if let Some(output) = &self.output {
fs::write(output, output_buf)?;
} else {
io::stdout().write_all(&output_buf)?;
}

Ok(())
}
}

/// Extract the genesis code from a given ChainSpec.
pub fn extract_genesis_wasm(chain_spec: &dyn ChainSpec) -> sc_cli::Result<Vec<u8>> {
let mut storage = chain_spec.build_storage()?;
storage
.top
.remove(sp_core::storage::well_known_keys::CODE)
.ok_or_else(|| "Could not find wasm file in genesis state!".into())
}

impl sc_cli::CliConfiguration for ExportGenesisWasmCommand {
fn shared_params(&self) -> &sc_cli::SharedParams {
&self.shared_params
}
}

fn validate_relay_chain_url(arg: &str) -> Result<(), String> {
let url = Url::parse(arg).map_err(|e| e.to_string())?;

Expand All @@ -133,7 +275,7 @@ fn validate_relay_chain_url(arg: &str) -> Result<(), String> {
}

/// The `run` command used to run a node.
#[derive(Debug, Parser)]
#[derive(Debug, clap::Parser)]
pub struct RunCmd {
/// The cumulus RunCmd inherents from sc_cli's
#[clap(flatten)]
Expand All @@ -155,21 +297,6 @@ pub struct RunCmd {
pub relay_chain_rpc_url: Option<Url>,
}

/// Options only relevant for collator nodes
#[derive(Clone, Debug)]
pub struct CollatorOptions {
/// Location of relay chain full node
pub relay_chain_rpc_url: Option<Url>,
}

/// A non-redundant version of the `RunCmd` that sets the `validator` field when the
/// original `RunCmd` had the `collator` field.
/// This is how we make `--collator` imply `--validator`.
pub struct NormalizedRunCmd {
/// The cumulus RunCmd inherents from sc_cli's
pub base: sc_cli::RunCmd,
}

impl RunCmd {
/// Create a [`NormalizedRunCmd`] which merges the `collator` cli argument into `validator` to have only one.
pub fn normalize(&self) -> NormalizedRunCmd {
Expand All @@ -186,6 +313,21 @@ impl RunCmd {
}
}

/// Options only relevant for collator nodes
#[derive(Clone, Debug)]
pub struct CollatorOptions {
/// Location of relay chain full node
pub relay_chain_rpc_url: Option<Url>,
}

/// A non-redundant version of the `RunCmd` that sets the `validator` field when the
/// original `RunCmd` had the `collator` field.
/// This is how we make `--collator` imply `--validator`.
pub struct NormalizedRunCmd {
/// The cumulus RunCmd inherents from sc_cli's
pub base: sc_cli::RunCmd,
}

impl sc_cli::CliConfiguration for NormalizedRunCmd {
fn shared_params(&self) -> &sc_cli::SharedParams {
self.base.shared_params()
Expand Down
2 changes: 0 additions & 2 deletions client/service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@ authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0" }
parking_lot = "0.12.1"
tracing = "0.1.34"

# Substrate
sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-consensus-babe = { git = "https://github.com/paritytech/substrate", branch = "master" }
Expand Down
55 changes: 0 additions & 55 deletions client/service/src/genesis.rs

This file was deleted.

2 changes: 0 additions & 2 deletions client/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ use sp_runtime::{
};
use std::{sync::Arc, time::Duration};

pub mod genesis;

/// Parameters given to [`start_collator`].
pub struct StartCollatorParams<'a, Block: BlockT, BS, Client, RCInterface, Spawner, IQ> {
pub block_status: Arc<BS>,
Expand Down
Loading