lib.rs 5.06 KiB
Newer Older
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot 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.

// Polkadot 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 Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Polkadot CLI library.

#![warn(missing_docs)]

extern crate app_dirs;
extern crate env_logger;
extern crate ed25519;
extern crate triehash;
extern crate substrate_codec as codec;
extern crate substrate_state_machine as state_machine;
extern crate substrate_client as client;
extern crate substrate_primitives as primitives;
extern crate substrate_rpc_servers as rpc;
extern crate polkadot_primitives;
extern crate polkadot_executor;
extern crate polkadot_runtime;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
extern crate polkadot_service as service;

#[macro_use]
extern crate clap;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;

pub mod error;

use std::path::{Path, PathBuf};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
use std::net::SocketAddr;
use std::sync::mpsc;
/// Parse command line arguments and start the node.
///
/// IANA unassigned port ranges that we could use:
/// 6717-6766		Unassigned
/// 8504-8553		Unassigned
/// 9556-9591		Unassigned
/// 9803-9874		Unassigned
/// 9926-9949		Unassigned
pub fn run<I, T>(args: I, exit: mpsc::Receiver<()>) -> error::Result<()> where
	I: IntoIterator<Item = T>,
	T: Into<std::ffi::OsString> + Clone,
{
	let yaml = load_yaml!("./cli.yml");
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	let matches = match clap::App::from_yaml(yaml).version(crate_version!()).get_matches_from_safe(args) {
		Ok(m) => m,
		Err(ref e) if e.kind == clap::ErrorKind::VersionDisplayed => return Ok(()),
		Err(ref e) if e.kind == clap::ErrorKind::HelpDisplayed || e.kind == clap::ErrorKind::VersionDisplayed => {
			let _ = clap::App::from_yaml(yaml).print_long_help();
			return Ok(());
		}
		Err(e) => return Err(e.into()),
	};

	// TODO [ToDr] Split parameters parsing from actual execution.
	let log_pattern = matches.value_of("log").unwrap_or("");
	init_logger(log_pattern);

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	let mut config = service::Configuration::default();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	let base_path = matches.value_of("base-path")
		.map(|x| Path::new(x).to_owned())
		.unwrap_or_else(default_base_path);

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	config.keystore_path = matches.value_of("keystore")
		.map(|x| Path::new(x).to_owned())
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		.unwrap_or_else(|| keystore_path(&base_path))
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		.to_string_lossy()
		.into();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	let mut role = service::Role::FULL;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	if matches.is_present("collator") {
		info!("Starting collator.");
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		role = service::Role::COLLATOR;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	else if matches.is_present("validator") {
		info!("Starting validator.");
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
		role = service::Role::VALIDATOR;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	config.roles = role;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	config.network.boot_nodes = matches
		.values_of("bootnodes")
		.map_or(Default::default(), |v| v.map(|n| n.to_owned()).collect());
	config.network.config_path = Some(network_path(&base_path).to_string_lossy().into());
	config.network.net_config_path = config.network.config_path.clone();

	let port = match matches.value_of("port") {
		Some(port) => port.parse().expect("Invalid p2p port value specified."),
		None => 30333,
	};
	config.network.listen_address = Some(SocketAddr::new("0.0.0.0".parse().unwrap(), port));
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	config.network.public_address = None;
	config.network.client_version = format!("parity-polkadot/{}", crate_version!());
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed

	config.keys = matches.values_of("key").unwrap_or_default().map(str::to_owned).collect();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed

	let service = service::Service::new(config)?;

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	let mut address: SocketAddr = "127.0.0.1:9933".parse().unwrap();
	if let Some(port) = matches.value_of("rpc-port") {
		let rpc_port: u16 = port.parse().expect("Invalid RPC port value specified.");
		address.set_port(rpc_port);
	}
	let handler = rpc::rpc_handler(service.client(), service.transaction_pool());
	let _server = rpc::start_http(&address, handler)?;
	exit.recv().ok();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
fn keystore_path(base_path: &Path) -> PathBuf {
	let mut path = base_path.to_owned();
	path.push("keystore");
	path
}

fn network_path(base_path: &Path) -> PathBuf {
	let mut path = base_path.to_owned();
	path.push("network");
	path
}

fn default_base_path() -> PathBuf {
	use app_dirs::{AppInfo, AppDataType};

	let app_info = AppInfo {
		name: "Polkadot",
		author: "Parity Technologies",
	};

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
	app_dirs::get_app_root(
		AppDataType::UserData,
		&app_info,
	).expect("app directories exist on all supported platforms; qed")
}
fn init_logger(pattern: &str) {
	let mut builder = env_logger::LogBuilder::new();
	// Disable info logging by default for some modules:
	builder.filter(Some("hyper"), log::LogLevelFilter::Warn);
	// Enable info for others.
	builder.filter(None, log::LogLevelFilter::Info);

	if let Ok(lvl) = std::env::var("RUST_LOG") {
		builder.parse(&lvl);
	}

	builder.parse(pattern);


	builder.init().expect("Logger initialized only once.");
}