// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Cumulus.
// Cumulus 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.
// Cumulus 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 Cumulus. If not, see .
//! Cumulus CLI library.
#![warn(missing_docs)]
use std::{
fs,
io::{self, Write},
net::SocketAddr,
path::PathBuf,
sync::Arc,
};
use codec::Encode;
use sc_chain_spec::ChainSpec;
use sc_client_api::HeaderBackend;
use sc_service::{
config::{PrometheusConfig, RpcBatchRequestConfig, TelemetryEndpoints},
BasePath, TransactionPoolOptions,
};
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::traits::{Block as BlockT, Zero};
use url::Url;
/// The `purge-chain` command used to remove the whole chain: the parachain and the relay chain.
#[derive(Debug, clap::Parser)]
#[group(skip)]
pub struct PurgeChainCmd {
/// The base struct of the purge-chain command.
#[command(flatten)]
pub base: sc_cli::PurgeChainCmd,
/// Only delete the para chain database
#[arg(long, aliases = &["para"])]
pub parachain: bool,
/// Only delete the relay chain database
#[arg(long, aliases = &["relay"])]
pub relaychain: bool,
}
impl PurgeChainCmd {
/// Run the purge command
pub fn run(
&self,
para_config: sc_service::Configuration,
relay_config: sc_service::Configuration,
) -> sc_cli::Result<()> {
let databases = match (self.parachain, self.relaychain) {
(true, true) | (false, false) => {
vec![("parachain", para_config.database), ("relaychain", relay_config.database)]
},
(true, false) => vec![("parachain", para_config.database)],
(false, true) => vec![("relaychain", relay_config.database)],
};
let db_paths = databases
.iter()
.map(|(chain_label, database)| {
database.path().ok_or_else(|| {
sc_cli::Error::Input(format!(
"Cannot purge custom database implementation of: {}",
chain_label,
))
})
})
.collect::>>()?;
if !self.base.yes {
for db_path in &db_paths {
println!("{}", db_path.display());
}
print!("Are you sure to remove? [y/N]: ");
io::stdout().flush().expect("failed to flush stdout");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let input = input.trim();
match input.chars().next() {
Some('y') | Some('Y') => {},
_ => {
println!("Aborted");
return Ok(())
},
}
}
for db_path in &db_paths {
match fs::remove_dir_all(db_path) {
Ok(_) => {
println!("{:?} removed.", &db_path);
},
Err(ref err) if err.kind() == io::ErrorKind::NotFound => {
eprintln!("{:?} did not exist.", &db_path);
},
Err(err) => return Err(err.into()),
}
}
Ok(())
}
}
impl sc_cli::CliConfiguration for PurgeChainCmd {
fn shared_params(&self) -> &sc_cli::SharedParams {
&self.base.shared_params
}
fn database_params(&self) -> Option<&sc_cli::DatabaseParams> {
Some(&self.base.database_params)
}
}
/// Get the SCALE encoded genesis header of the parachain.
pub fn get_raw_genesis_header(client: Arc) -> sc_cli::Result>
where
B: BlockT,
C: HeaderBackend + 'static,
{
let genesis_hash =
client
.hash(Zero::zero())?
.ok_or(sc_cli::Error::Client(sp_blockchain::Error::Backend(
"Failed to lookup genesis block hash when exporting genesis head data.".into(),
)))?;
let genesis_header = client.header(genesis_hash)?.ok_or(sc_cli::Error::Client(
sp_blockchain::Error::Backend(
"Failed to lookup genesis header by hash when exporting genesis head data.".into(),
),
))?;
Ok(genesis_header.encode())
}
/// Command for exporting the genesis head data of the parachain
#[derive(Debug, clap::Parser)]
pub struct ExportGenesisHeadCommand {
/// Output file name or stdout if unspecified.
#[arg()]
pub output: Option,
/// Write output in binary. Default is to write in hex.
#[arg(short, long)]
pub raw: bool,
#[allow(missing_docs)]
#[command(flatten)]
pub shared_params: sc_cli::SharedParams,
}
impl ExportGenesisHeadCommand {
/// Run the export-genesis-head command
pub fn run(&self, client: Arc) -> sc_cli::Result<()>
where
B: BlockT,
C: HeaderBackend + 'static,
{
let raw_header = get_raw_genesis_header(client)?;
let output_buf = if self.raw {
raw_header
} else {
format!("0x{:?}", HexDisplay::from(&raw_header)).into_bytes()
};
if let Some(output) = &self.output {
fs::write(output, output_buf)?;
} else {
io::stdout().write_all(&output_buf)?;
}
Ok(())
}
}
impl sc_cli::CliConfiguration for ExportGenesisHeadCommand {
fn shared_params(&self) -> &sc_cli::SharedParams {
&self.shared_params
}
fn base_path(&self) -> sc_cli::Result