openethereum/parity/main.rs

328 lines
10 KiB
Rust
Raw Normal View History

2016-02-05 13:40:41 +01:00
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethcore client application.
#![warn(missing_docs)]
2016-01-23 23:53:20 +01:00
#![feature(plugin)]
#![plugin(docopt_macros)]
#![plugin(clippy)]
2016-01-23 23:53:20 +01:00
extern crate docopt;
extern crate rustc_serialize;
2015-12-22 22:19:50 +01:00
extern crate ethcore_util as util;
2016-01-07 16:08:12 +01:00
extern crate ethcore;
2016-01-29 15:56:06 +01:00
extern crate ethsync;
2016-01-31 11:08:04 +01:00
extern crate log as rlog;
2016-01-09 23:21:57 +01:00
extern crate env_logger;
extern crate ctrlc;
2016-02-05 13:49:36 +01:00
extern crate fdlimit;
extern crate target_info;
2015-12-22 22:19:50 +01:00
#[cfg(feature = "rpc")]
2016-01-26 13:14:22 +01:00
extern crate ethcore_rpc as rpc;
2016-02-08 15:04:12 +01:00
use std::net::{SocketAddr};
use std::env;
2016-02-15 18:36:34 +01:00
use std::path::PathBuf;
2016-01-31 11:08:04 +01:00
use rlog::{LogLevelFilter};
use env_logger::LogBuilder;
use ctrlc::CtrlC;
2016-01-16 13:30:27 +01:00
use util::*;
use util::panics::MayPanic;
use ethcore::spec::*;
2016-01-16 13:30:27 +01:00
use ethcore::client::*;
2016-01-21 23:33:52 +01:00
use ethcore::service::{ClientService, NetSyncMessage};
use ethcore::ethereum;
2016-01-18 23:23:32 +01:00
use ethcore::blockchain::CacheSize;
2016-01-29 15:56:06 +01:00
use ethsync::EthSync;
use target_info::Target;
2016-01-23 23:53:20 +01:00
docopt!(Args derive Debug, "
2016-01-23 23:53:20 +01:00
Parity. Ethereum Client.
By Wood/Paronyan/Kotewicz/Drwięga/Volf.
Copyright 2015, 2016 Ethcore (UK) Limited
2016-01-23 23:53:20 +01:00
Usage:
2016-02-11 10:46:55 +01:00
parity [options] [ --no-bootstrap | <enode>... ]
2016-01-23 23:53:20 +01:00
Options:
--chain CHAIN Specify the blockchain type. CHAIN may be either a JSON chain specification file
or frontier, mainnet, morden, or testnet [default: frontier].
2016-02-10 21:17:47 +01:00
-d --db-path PATH Specify the database & configuration directory path [default: $HOME/.parity]
2016-02-11 10:46:55 +01:00
--no-bootstrap Don't bother trying to connect to any nodes initially.
2016-02-16 02:05:36 +01:00
--listen-address URL Specify the IP/port on which to listen for peers.
--public-address URL Specify the IP/port on which peers may connect.
2016-02-08 15:04:12 +01:00
--address URL Equivalent to --listen-address URL --public-address URL.
2016-02-10 16:45:54 +01:00
--upnp Use UPnP to try to figure out the correct network settings.
2016-02-12 00:24:10 +01:00
--node-key KEY Specify node secret key as hex string.
2016-02-08 15:04:12 +01:00
2016-02-04 00:48:36 +01:00
--cache-pref-size BYTES Specify the prefered size of the blockchain cache in bytes [default: 16384].
--cache-max-size BYTES Specify the maximum size of the blockchain cache in bytes [default: 262144].
-j --jsonrpc Enable the JSON-RPC API sever.
--jsonrpc-url URL Specify URL for JSON-RPC API server [default: 127.0.0.1:8545].
-l --logging LOGGING Specify the logging level.
-v --version Show information about version.
-h --help Show this screen.
2016-02-16 02:05:36 +01:00
", flag_cache_pref_size: usize,
flag_cache_max_size: usize,
flag_address: Option<String>,
flag_listen_address: Option<String>,
flag_public_address: Option<String>,
flag_node_key: Option<String>);
2015-12-22 22:19:50 +01:00
fn setup_log(init: &str) {
let mut builder = LogBuilder::new();
2016-01-15 01:44:57 +01:00
builder.filter(None, LogLevelFilter::Info);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
}
builder.parse(init);
2016-01-23 23:53:20 +01:00
builder.init().unwrap();
}
#[cfg(feature = "rpc")]
fn setup_rpc_server(client: Arc<Client>, sync: Arc<EthSync>, url: &str) {
use rpc::v1::*;
let mut server = rpc::HttpServer::new(1);
2016-01-21 00:54:19 +01:00
server.add_delegate(Web3Client::new().to_delegate());
2016-02-10 16:28:59 +01:00
server.add_delegate(EthClient::new(client.clone(), sync.clone()).to_delegate());
2016-01-21 11:25:39 +01:00
server.add_delegate(EthFilterClient::new(client).to_delegate());
server.add_delegate(NetClient::new(sync).to_delegate());
server.start_async(url);
}
#[cfg(not(feature = "rpc"))]
fn setup_rpc_server(_client: Arc<Client>, _sync: Arc<EthSync>, _url: &str) {
}
2016-02-10 18:11:10 +01:00
fn print_version() {
println!("\
Parity version {} ({}-{}-{})
Copyright 2015, 2016 Ethcore (UK) Limited
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
2016-02-09 17:23:25 +01:00
By Wood/Paronyan/Kotewicz/Drwięga/Volf.\
", env!("CARGO_PKG_VERSION"), Target::arch(), Target::env(), Target::os());
2016-02-10 18:11:10 +01:00
}
struct Configuration {
args: Args
}
impl Configuration {
fn parse() -> Self {
Configuration {
args: Args::docopt().decode().unwrap_or_else(|e| e.exit())
}
}
2016-02-10 21:17:47 +01:00
fn path(&self) -> String {
self.args.flag_db_path.replace("$HOME", env::home_dir().unwrap().to_str().unwrap())
}
fn spec(&self) -> Spec {
2016-02-10 14:16:42 +01:00
match self.args.flag_chain.as_ref() {
"frontier" | "mainnet" => ethereum::new_frontier(),
"morden" | "testnet" => ethereum::new_morden(),
"olympic" => ethereum::new_olympic(),
f => Spec::from_json_utf8(contents(f).expect("Couldn't read chain specification file. Sure it exists?").as_ref()),
}
}
2016-02-10 21:17:47 +01:00
fn init_nodes(&self, spec: &Spec) -> Vec<String> {
2016-02-11 10:46:55 +01:00
if self.args.flag_no_bootstrap { Vec::new() } else {
match self.args.arg_enode.len() {
0 => spec.nodes().clone(),
_ => self.args.arg_enode.clone(),
}
}
}
2016-02-16 02:05:36 +01:00
fn net_addresses(&self) -> (Option<SocketAddr>, Option<SocketAddr>) {
let mut listen_address = None;
let mut public_address = None;
2016-02-16 02:05:36 +01:00
if let Some(ref a) = self.args.flag_address {
public_address = Some(SocketAddr::from_str(a.as_ref()).expect("Invalid listen/public address given with --address"));
listen_address = public_address;
}
if let Some(ref a) = self.args.flag_listen_address {
if listen_address.is_some() {
panic!("Conflicting flags: --address and --listen-address");
}
2016-02-16 02:05:36 +01:00
listen_address = Some(SocketAddr::from_str(a.as_ref()).expect("Invalid listen address given with --listen-address"));
}
if let Some(ref a) = self.args.flag_public_address {
if public_address.is_some() {
panic!("Conflicting flags: --address and --public-address");
}
2016-02-16 02:05:36 +01:00
public_address = Some(SocketAddr::from_str(a.as_ref()).expect("Invalid listen address given with --public-address"));
}
(listen_address, public_address)
}
}
2016-02-10 16:35:52 +01:00
fn wait_for_exit(client_service: &ClientService) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); });
let e = exit.clone();
2016-02-10 16:35:52 +01:00
client_service.on_panic(move |_reason| { e.notify_all(); });
// Wait for signal
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap()).unwrap();
}
2015-12-22 22:19:50 +01:00
fn main() {
let conf = Configuration::parse();
if conf.args.flag_version {
2016-02-10 18:11:10 +01:00
print_version();
return;
}
2016-02-10 21:17:47 +01:00
let spec = conf.spec();
2016-01-23 23:53:20 +01:00
// Setup logging
setup_log(&conf.args.flag_logging);
// Raise fdlimit
2016-02-05 13:49:36 +01:00
unsafe { ::fdlimit::raise_fd_limit(); }
2016-01-23 23:53:20 +01:00
// Configure network
2016-01-23 02:36:58 +01:00
let mut net_settings = NetworkConfiguration::new();
2016-02-10 18:11:10 +01:00
net_settings.nat_enabled = conf.args.flag_upnp;
2016-02-10 23:51:22 +01:00
net_settings.boot_nodes = conf.init_nodes(&spec);
let (listen, public) = conf.net_addresses();
net_settings.listen_address = listen;
net_settings.public_address = public;
2016-02-12 00:24:10 +01:00
net_settings.use_secret = conf.args.flag_node_key.as_ref().map(|s| Secret::from_str(&s).expect("Invalid key string"));
2016-02-15 18:36:34 +01:00
let mut net_path = PathBuf::from(&conf.path());
net_path.push("network");
net_settings.config_path = Some(net_path.to_str().unwrap().to_owned());
// Build client
2016-02-10 21:17:47 +01:00
let mut service = ClientService::start(spec, net_settings, &Path::new(&conf.path())).unwrap();
2016-01-29 15:56:06 +01:00
let client = service.client().clone();
client.configure_cache(conf.args.flag_cache_pref_size, conf.args.flag_cache_max_size);
// Sync
2016-01-29 15:56:06 +01:00
let sync = EthSync::register(service.network(), client);
// Setup rpc
if conf.args.flag_jsonrpc {
setup_rpc_server(service.client(), sync.clone(), &conf.args.flag_jsonrpc_url);
}
// Register IO handler
let io_handler = Arc::new(ClientIoHandler {
client: service.client(),
info: Default::default(),
sync: sync
});
2016-01-16 13:30:27 +01:00
service.io().register_handler(io_handler).expect("Error registering IO handler");
// Handle exit
2016-02-10 16:35:52 +01:00
wait_for_exit(&service);
2015-12-22 22:19:50 +01:00
}
2016-01-18 23:23:32 +01:00
struct Informant {
chain_info: RwLock<Option<BlockChainInfo>>,
cache_info: RwLock<Option<CacheSize>>,
report: RwLock<Option<ClientReport>>,
}
impl Default for Informant {
fn default() -> Self {
Informant {
chain_info: RwLock::new(None),
cache_info: RwLock::new(None),
report: RwLock::new(None),
}
}
2016-01-18 23:23:32 +01:00
}
impl Informant {
2016-01-22 04:54:38 +01:00
pub fn tick(&self, client: &Client, sync: &EthSync) {
2016-01-18 23:23:32 +01:00
// 5 seconds betwen calls. TODO: calculate this properly.
let dur = 5usize;
let chain_info = client.chain_info();
2016-01-22 04:54:38 +01:00
let queue_info = client.queue_info();
2016-01-18 23:23:32 +01:00
let cache_info = client.cache_info();
let report = client.report();
2016-01-22 04:54:38 +01:00
let sync_info = sync.status();
2016-01-18 23:23:32 +01:00
if let (_, &Some(ref last_cache_info), &Some(ref last_report)) = (self.chain_info.read().unwrap().deref(), self.cache_info.read().unwrap().deref(), self.report.read().unwrap().deref()) {
2016-02-11 22:14:06 +01:00
println!("[ #{} {} ]---[ {} blk/s | {} tx/s | {} gas/s //··· {}/{} peers, #{}, {}+{} queued ···// {} ({}) bl {} ({}) ex ]",
2016-01-18 23:23:32 +01:00
chain_info.best_block_number,
chain_info.best_block_hash,
(report.blocks_imported - last_report.blocks_imported) / dur,
(report.transactions_applied - last_report.transactions_applied) / dur,
(report.gas_processed - last_report.gas_processed) / From::from(dur),
2016-01-22 04:54:38 +01:00
sync_info.num_active_peers,
sync_info.num_peers,
2016-02-11 22:14:06 +01:00
sync_info.last_imported_block_number.unwrap_or(chain_info.best_block_number),
queue_info.unverified_queue_size,
queue_info.verified_queue_size,
2016-01-22 04:54:38 +01:00
2016-01-18 23:23:32 +01:00
cache_info.blocks,
cache_info.blocks as isize - last_cache_info.blocks as isize,
cache_info.block_details,
cache_info.block_details as isize - last_cache_info.block_details as isize
);
}
*self.chain_info.write().unwrap().deref_mut() = Some(chain_info);
*self.cache_info.write().unwrap().deref_mut() = Some(cache_info);
*self.report.write().unwrap().deref_mut() = Some(report);
2016-01-18 23:23:32 +01:00
}
}
2016-01-16 13:30:27 +01:00
const INFO_TIMER: TimerToken = 0;
2016-01-16 13:30:27 +01:00
struct ClientIoHandler {
2016-01-21 23:33:52 +01:00
client: Arc<Client>,
2016-01-22 04:54:38 +01:00
sync: Arc<EthSync>,
2016-01-18 23:23:32 +01:00
info: Informant,
2016-01-16 13:30:27 +01:00
}
impl IoHandler<NetSyncMessage> for ClientIoHandler {
fn initialize(&self, io: &IoContext<NetSyncMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
2016-01-16 13:30:27 +01:00
}
fn timeout(&self, _io: &IoContext<NetSyncMessage>, timer: TimerToken) {
if INFO_TIMER == timer {
2016-01-22 04:54:38 +01:00
self.info.tick(&self.client, &self.sync);
2016-01-16 13:30:27 +01:00
}
}
}
/// Parity needs at least 1 test to generate coverage reports correctly.
#[test]
fn if_works() {
}