From 1d19efbc1c393a3676916321d1f798294eeebb96 Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Tue, 5 Feb 2019 22:17:16 +0000 Subject: [PATCH] apply rustfmt --- src/config.rs | 55 +++++++++++++++-------- src/handlers/block.rs | 51 ++++++++++++--------- src/handlers/common.rs | 41 +++++++++++------ src/handlers/epoch.rs | 26 +++++------ src/handlers/mod.rs | 6 +-- src/handlers/pack.rs | 45 ++++++++++++------- src/handlers/tip.rs | 40 +++++++++-------- src/handlers/tx.rs | 55 ++++++++++++++--------- src/handlers/utxos.rs | 35 ++++++++------- src/handlers/utxos_delta.rs | 40 +++++++++-------- src/main.rs | 90 ++++++++++++++++++++----------------- src/service.rs | 27 +++++++---- 12 files changed, 302 insertions(+), 209 deletions(-) diff --git a/src/config.rs b/src/config.rs index 890d064..e4360a3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,11 +1,16 @@ use serde_yaml; -use cardano_storage::{self, Storage}; use cardano_storage::config::StorageConfig; -use exe_common::config::{net}; -use std::{io, result, path::{PathBuf, Path}, env::{VarError, self, home_dir}}; -use std::{num::{ParseIntError}, collections::{BTreeMap}, sync::{Arc}}; +use cardano_storage::{self, Storage}; +use exe_common::config::net; use std::collections::HashSet; +use std::{collections::BTreeMap, num::ParseIntError, sync::Arc}; +use std::{ + env::{self, home_dir, VarError}, + io, + path::{Path, PathBuf}, + result, +}; #[derive(Debug)] pub enum Error { @@ -14,22 +19,32 @@ pub enum Error { YamlError(serde_yaml::Error), ParseIntError(ParseIntError), StorageError(cardano_storage::Error), - BlockchainConfigError(&'static str) + BlockchainConfigError(&'static str), } impl From for Error { - fn from(e: VarError) -> Error { Error::VarError(e) } + fn from(e: VarError) -> Error { + Error::VarError(e) + } } impl From for Error { - fn from(e: ParseIntError) -> Error { Error::ParseIntError(e) } + fn from(e: ParseIntError) -> Error { + Error::ParseIntError(e) + } } impl From for Error { - fn from(e: io::Error) -> Error { Error::IoError(e) } + fn from(e: io::Error) -> Error { + Error::IoError(e) + } } impl From for Error { - fn from(e: cardano_storage::Error) -> Error { Error::StorageError(e) } + fn from(e: cardano_storage::Error) -> Error { + Error::StorageError(e) + } } impl From for Error { - fn from(e: serde_yaml::Error) -> Error { Error::YamlError(e) } + fn from(e: serde_yaml::Error) -> Error { + Error::YamlError(e) + } } type Result = result::Result; @@ -60,7 +75,9 @@ impl Config { } } - pub fn get_networks_dir(&self) -> PathBuf { self.root_dir.clone() } + pub fn get_networks_dir(&self) -> PathBuf { + self.root_dir.clone() + } pub fn get_networks(&self) -> Result { let mut networks = Networks::new(); @@ -71,7 +88,7 @@ impl Config { let network = Network { path: netcfg_dir, config: self.get_network_config(name)?, - storage: Arc::new(self.get_storage(name)?) + storage: Arc::new(self.get_storage(name)?), }; networks.insert(name.to_owned(), network); @@ -85,9 +102,11 @@ impl Config { match net::Config::from_file(&path) { None => { error!("error while parsing config file: {:?}", path); - Err(Error::BlockchainConfigError("error while parsing network config file")) - }, - Some(cfg) => Ok(cfg) + Err(Error::BlockchainConfigError( + "error while parsing network config file", + )) + } + Some(cfg) => Ok(cfg), } } @@ -96,7 +115,7 @@ impl Config { if netcfg_dir.exists() { self.network_names.insert(name.to_string()); - return Ok(()) + return Ok(()); } let storage_config = self.get_storage_config(name); @@ -132,7 +151,7 @@ pub type Networks = BTreeMap; /// /// this will include all the cardano network you will connect to (mainnet, testnet, ...), /// the different wallets you will create and all metadata. -pub static HERMES_PATH_ENV : &'static str = "HERMES_PATH"; +pub static HERMES_PATH_ENV: &'static str = "HERMES_PATH"; /// the home directory hidden directory where to find Hermes files. /// @@ -140,7 +159,7 @@ pub static HERMES_PATH_ENV : &'static str = "HERMES_PATH"; /// /// This is not standard on windows, set the appropriate setting here /// -pub static HERMES_HOME_PATH : &'static str = ".hermes"; +pub static HERMES_HOME_PATH: &'static str = ".hermes"; /// get the root directory of all the hermes path /// diff --git a/src/handlers/block.rs b/src/handlers/block.rs index 6ab5b78..87c868a 100644 --- a/src/handlers/block.rs +++ b/src/handlers/block.rs @@ -1,26 +1,24 @@ -use super::super::config::{Networks}; -use cardano_storage::{tag, block_location, block_read_location}; -use cardano::util::{hex, try_from_slice::TryFromSlice}; +use super::super::config::Networks; use cardano::block; -use std::sync::{Arc}; +use cardano::util::{hex, try_from_slice::TryFromSlice}; +use cardano_storage::{block_location, block_read_location, tag}; +use std::sync::Arc; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; use router; -use router::{Router}; +use router::Router; use super::common; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.get(":network/block/:blockid", self, "block") @@ -29,25 +27,38 @@ impl Handler { impl iron::Handler for Handler { fn handle(&self, req: &mut Request) -> IronResult { - let ref network_name = req.extensions.get::().unwrap().find("network").unwrap(); + let ref network_name = req + .extensions + .get::() + .unwrap() + .find("network") + .unwrap(); - if ! common::validate_network_name (network_name) { + if !common::validate_network_name(network_name) { return Ok(Response::with(status::BadRequest)); } let net = match self.networks.get(network_name.to_owned()) { None => return Ok(Response::with(status::BadRequest)), - Some(net) => net + Some(net) => net, }; - let ref blockid = req.extensions.get::().unwrap().find("blockid").unwrap(); - if ! blockid.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + let ref blockid = req + .extensions + .get::() + .unwrap() + .find("blockid") + .unwrap(); + if !blockid + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { error!("invalid blockid: {}", blockid); return Ok(Response::with(status::BadRequest)); } let hh_bytes = match tag::read(&net.storage, &blockid) { None => hex::decode(&blockid).unwrap(), - Some(t) => t + Some(t) => t, }; let hh = block::HeaderHash::try_from_slice(&hh_bytes).expect("blockid invalid"); info!("querying block header: {}", hh); @@ -56,17 +67,15 @@ impl iron::Handler for Handler { None => { warn!("block `{}' does not exist", hh); Ok(Response::with((status::NotFound, "Not Found"))) - }, + } Some(loc) => { debug!("blk location: {:?}", loc); match block_read_location(&net.storage, &loc, &hh.into()) { - None => { + None => { error!("error while reading block at location: {:?}", loc); Ok(Response::with(status::InternalServerError)) - }, - Some(rblk) => { - Ok(Response::with((status::Ok, rblk.as_ref()))) } + Some(rblk) => Ok(Response::with((status::Ok, rblk.as_ref()))), } } } diff --git a/src/handlers/common.rs b/src/handlers/common.rs index d4e8d43..23490c9 100644 --- a/src/handlers/common.rs +++ b/src/handlers/common.rs @@ -1,44 +1,57 @@ +use super::super::config::{Network, Networks}; use cardano::block::EpochId; -use router::{Router}; -use iron::{Request}; -use super::super::config::{Networks, Network}; +use iron::Request; +use router::Router; pub fn validate_network_name(v: &&str) -> bool { v.chars().all(|c| c.is_ascii_alphanumeric()) } pub fn validate_epochid(v: &&str) -> Option { - if ! v.chars().all(|c| c.is_digit(10)) { + if !v.chars().all(|c| c.is_digit(10)) { None } else { Some(v.parse::().unwrap()) } } -pub fn get_network<'a>(req: &Request, networks : &'a Networks) -> Option<(String, &'a Network)> { - let ref network_name = req.extensions.get::().unwrap().find("network").unwrap(); +pub fn get_network<'a>(req: &Request, networks: &'a Networks) -> Option<(String, &'a Network)> { + let ref network_name = req + .extensions + .get::() + .unwrap() + .find("network") + .unwrap(); - if ! validate_network_name (network_name) { + if !validate_network_name(network_name) { return None; } - + match networks.get(network_name.to_owned()) { None => None, - Some(net) => Some((network_name.to_string(), net)) + Some(net) => Some((network_name.to_string(), net)), } } -pub fn get_network_and_epoch<'a>(req: &Request, networks: &'a Networks) -> Option<(&'a Network, EpochId)> { +pub fn get_network_and_epoch<'a>( + req: &Request, + networks: &'a Networks, +) -> Option<(&'a Network, EpochId)> { let (_, net) = get_network(req, networks)?; - let ref epochid_str = req.extensions.get::().unwrap().find("epochid").unwrap(); + let ref epochid_str = req + .extensions + .get::() + .unwrap() + .find("epochid") + .unwrap(); - let epochid = match validate_epochid (epochid_str) { + let epochid = match validate_epochid(epochid_str) { None => { error!("invalid epochid: {}", epochid_str); return None; - }, + } Some(e) => e, }; Some((net, epochid)) -} \ No newline at end of file +} diff --git a/src/handlers/epoch.rs b/src/handlers/epoch.rs index 5968864..3decc2d 100644 --- a/src/handlers/epoch.rs +++ b/src/handlers/epoch.rs @@ -1,24 +1,22 @@ -use cardano_storage::{epoch}; +use cardano_storage::epoch; -use std::sync::{Arc}; +use std::sync::Arc; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; -use router::{Router}; +use router::Router; -use super::super::config::{Networks}; +use super::super::config::Networks; use super::common; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.get(":network/epoch/:epochid", self, "epoch") @@ -28,19 +26,21 @@ impl Handler { impl iron::Handler for Handler { fn handle(&self, req: &mut Request) -> IronResult { let (net, epochid) = match common::get_network_and_epoch(req, &self.networks) { - None => { return Ok(Response::with(status::BadRequest)); } - Some(x) => x + None => { + return Ok(Response::with(status::BadRequest)); + } + Some(x) => x, }; let opackref = epoch::epoch_read_pack(&net.storage.config, epochid); match opackref { Err(_) => { return Ok(Response::with(status::NotFound)); - }, + } Ok(packref) => { let path = net.storage.config.get_pack_filepath(&packref); Ok(Response::with((status::Ok, path))) - }, + } } } } diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index ec1fef6..18d2515 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -1,8 +1,8 @@ -pub mod common; pub mod block; -pub mod pack; +pub mod common; pub mod epoch; +pub mod pack; pub mod tip; pub mod tx; pub mod utxos; -pub mod utxos_delta; \ No newline at end of file +pub mod utxos_delta; diff --git a/src/handlers/pack.rs b/src/handlers/pack.rs index 53fb0b2..0d5a2d5 100644 --- a/src/handlers/pack.rs +++ b/src/handlers/pack.rs @@ -1,26 +1,24 @@ +use super::super::config::Networks; +use cardano::util::hex; +use cardano_storage::tag; use cardano_storage::types::HASH_SIZE; -use cardano_storage::{tag}; -use cardano::util::{hex}; -use std::sync::{Arc}; -use super::super::config::{Networks}; +use std::sync::Arc; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; use router; -use router::{Router}; +use router::Router; use super::common; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.get(":network/pack/:packid", self, "pack") @@ -29,28 +27,41 @@ impl Handler { impl iron::Handler for Handler { fn handle(&self, req: &mut Request) -> IronResult { - let ref network_name = req.extensions.get::().unwrap().find("network").unwrap(); + let ref network_name = req + .extensions + .get::() + .unwrap() + .find("network") + .unwrap(); - if ! common::validate_network_name (network_name) { + if !common::validate_network_name(network_name) { return Ok(Response::with(status::BadRequest)); } let net = match self.networks.get(network_name.to_owned()) { None => return Ok(Response::with(status::BadRequest)), - Some(net) => net + Some(net) => net, }; - let ref packid = req.extensions.get::().unwrap().find("packid").unwrap(); - if ! packid.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + let ref packid = req + .extensions + .get::() + .unwrap() + .find("packid") + .unwrap(); + if !packid + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { error!("invalid packid: {}", packid); return Ok(Response::with(status::BadRequest)); } info!("query pack: {}", packid); let packhash_vec = match tag::read(&net.storage, &packid) { None => hex::decode(&packid).unwrap(), - Some(t) => t + Some(t) => t, }; - let mut packhash = [0;HASH_SIZE]; + let mut packhash = [0; HASH_SIZE]; packhash[..].clone_from_slice(packhash_vec.as_slice()); let path = net.storage.config.get_pack_filepath(&packhash); diff --git a/src/handlers/tip.rs b/src/handlers/tip.rs index 7d75aab..29a345f 100644 --- a/src/handlers/tip.rs +++ b/src/handlers/tip.rs @@ -1,24 +1,22 @@ -use super::super::config::{Networks}; -use cardano_storage::{Error, tag}; -use std::sync::{Arc}; +use super::super::config::Networks; +use cardano_storage::{tag, Error}; +use std::sync::Arc; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; use router; -use router::{Router}; +use router::Router; use super::common; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.get(":network/tip", self, "tip") @@ -30,28 +28,32 @@ impl iron::Handler for Handler { // // The current implementation of the TIP handler is to look for the HEAD tag fn handle(&self, req: &mut Request) -> IronResult { - let ref network_name = req.extensions.get::().unwrap().find("network").unwrap(); - - if ! common::validate_network_name (network_name) { + let ref network_name = req + .extensions + .get::() + .unwrap() + .find("network") + .unwrap(); + + if !common::validate_network_name(network_name) { return Ok(Response::with(status::BadRequest)); } let net = match self.networks.get(network_name.to_owned()) { None => return Ok(Response::with(status::BadRequest)), - Some(net) => net + Some(net) => net, }; match net.storage.get_block_from_tag(&tag::HEAD) { - Err(Error::NoSuchTag) => - Ok(Response::with((status::NotFound, "No Tip To Serve"))), + Err(Error::NoSuchTag) => Ok(Response::with((status::NotFound, "No Tip To Serve"))), Err(err) => { error!("error while reading block: {:?}", err); Ok(Response::with(status::InternalServerError)) - }, - Ok(block) => { - Ok(Response::with((status::Ok, block.get_header().to_raw().as_ref()))) } + Ok(block) => Ok(Response::with(( + status::Ok, + block.get_header().to_raw().as_ref(), + ))), } } } - diff --git a/src/handlers/tx.rs b/src/handlers/tx.rs index b0e7fd4..227c8a7 100755 --- a/src/handlers/tx.rs +++ b/src/handlers/tx.rs @@ -3,25 +3,23 @@ use cardano::{block::Verify, tx::TxAux}; use std::{io::Read, sync::Arc}; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; -use router::{Router}; +use router::Router; use serde_json; -use super::super::config::{Networks}; +use super::super::config::Networks; use super::common; use exe_common::{config::net, network::Api, sync}; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.post(":network/txs/signed", self, "txs_signed_send") @@ -32,37 +30,54 @@ impl iron::Handler for Handler { fn handle(&self, req: &mut Request) -> IronResult { fn read_txaux_from_req_str(tx_str: &str) -> Option { let json = serde_json::from_str::(tx_str).ok()?; - let base_64 = json. - as_object()?. - get("signedTx")?. - as_str()?; + let base_64 = json.as_object()?.get("signedTx")?.as_str()?; let bytes = base64::decode(&base_64).ok()?; - cbor_event::de::RawCbor::from(&bytes).deserialize_complete().ok() + cbor_event::de::RawCbor::from(&bytes) + .deserialize_complete() + .ok() } let mut req_body_str = String::new(); req.body.read_to_string(&mut req_body_str).unwrap(); let txaux = match read_txaux_from_req_str(req_body_str.as_str()) { - None => { return Ok(Response::with((status::BadRequest, "Invalid input format for transaction"))); } - Some(x) => x + None => { + return Ok(Response::with(( + status::BadRequest, + "Invalid input format for transaction", + ))); + } + Some(x) => x, }; let (net_name, net) = match common::get_network(req, &self.networks) { - None => { return Ok(Response::with((status::BadRequest, "Invalid network name"))); } - Some(x) => x + None => { + return Ok(Response::with((status::BadRequest, "Invalid network name"))); + } + Some(x) => x, }; let netcfg_file = net.storage.config.get_config_file(); let net_cfg = net::Config::from_file(&netcfg_file).expect("no network config present"); if let Err(verify_error) = txaux.verify(net_cfg.protocol_magic) { - return Ok(Response::with((status::BadRequest, format!("Transaction failed verification: {}", verify_error)))); + return Ok(Response::with(( + status::BadRequest, + format!("Transaction failed verification: {}", verify_error), + ))); } let mut peer = sync::get_peer(&net_name, &net_cfg, true); match peer.send_transaction(txaux) { - Err(e) => return Ok(Response::with((status::InternalServerError, format!("Failed to send to peers: {}", e)))), - Ok(value) => assert!(value) + Err(e) => { + return Ok(Response::with(( + status::InternalServerError, + format!("Failed to send to peers: {}", e), + ))); + } + Ok(value) => assert!(value), }; - Ok(Response::with((status::Ok, "Transaction sent successfully!"))) + Ok(Response::with(( + status::Ok, + "Transaction sent successfully!", + ))) } } diff --git a/src/handlers/utxos.rs b/src/handlers/utxos.rs index 1daf822..21a4da8 100644 --- a/src/handlers/utxos.rs +++ b/src/handlers/utxos.rs @@ -1,24 +1,22 @@ use cardano_storage::utxo; -use std::sync::{Arc}; +use std::sync::Arc; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; -use router::{Router}; +use router::Router; -use super::super::config::{Networks}; +use super::super::config::Networks; use super::common; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.get(":network/utxos/:epochid", self, "utxos") @@ -27,21 +25,26 @@ impl Handler { impl iron::Handler for Handler { fn handle(&self, req: &mut Request) -> IronResult { - let (net, epochid) = match common::get_network_and_epoch(req, &self.networks) { - None => { return Ok(Response::with(status::BadRequest)); } - Some(x) => x + None => { + return Ok(Response::with(status::BadRequest)); + } + Some(x) => x, }; let mut res = vec![]; let utxo_state = utxo::get_utxos_for_epoch(&net.storage, epochid).unwrap(); - utxo::write_utxos_delta(&net.storage, - &utxo_state.last_block, - &utxo_state.last_date, - &utxo_state.utxos, - None, &mut res).unwrap(); + utxo::write_utxos_delta( + &net.storage, + &utxo_state.last_block, + &utxo_state.last_date, + &utxo_state.utxos, + None, + &mut res, + ) + .unwrap(); Ok(Response::with((status::Ok, res))) } diff --git a/src/handlers/utxos_delta.rs b/src/handlers/utxos_delta.rs index 36db07b..b0cfc53 100644 --- a/src/handlers/utxos_delta.rs +++ b/src/handlers/utxos_delta.rs @@ -1,24 +1,22 @@ use cardano_storage::utxo; -use std::sync::{Arc}; +use std::sync::Arc; use iron; -use iron::{Request, Response, IronResult}; use iron::status; +use iron::{IronResult, Request, Response}; -use router::{Router}; +use router::Router; -use super::super::config::{Networks}; +use super::super::config::Networks; use super::common; pub struct Handler { - networks: Arc + networks: Arc, } impl Handler { pub fn new(networks: Arc) -> Self { - Handler { - networks: networks - } + Handler { networks: networks } } pub fn route(self, router: &mut Router) -> &mut Router { router.get(":network/utxos-delta/:epochid/:to", self, "utxos-delta") @@ -27,24 +25,30 @@ impl Handler { impl iron::Handler for Handler { fn handle(&self, req: &mut Request) -> IronResult { - let (net, from) = match common::get_network_and_epoch(req, &self.networks) { - None => { return Ok(Response::with(status::BadRequest)); } - Some(x) => x + None => { + return Ok(Response::with(status::BadRequest)); + } + Some(x) => x, }; - let to = common::validate_epochid( - &req.extensions.get::().unwrap().find("to").unwrap()).unwrap(); + let to = + common::validate_epochid(&req.extensions.get::().unwrap().find("to").unwrap()) + .unwrap(); let mut res = vec![]; let to_state = utxo::get_utxos_for_epoch(&net.storage, to).unwrap(); - utxo::write_utxos_delta(&net.storage, - &to_state.last_block, - &to_state.last_date, - &to_state.utxos, - Some(from), &mut res).unwrap(); + utxo::write_utxos_delta( + &net.storage, + &to_state.last_block, + &to_state.last_date, + &to_state.utxos, + Some(from), + &mut res, + ) + .unwrap(); Ok(Response::with((status::Ok, res))) } diff --git a/src/main.rs b/src/main.rs index 938654d..5e2992f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,14 +14,13 @@ extern crate cardano; extern crate cardano_storage; extern crate exe_common; -use std::path::{PathBuf}; - +use std::path::PathBuf; mod config; mod handlers; mod service; -use self::config::{Config, hermes_path}; +use self::config::{hermes_path, Config}; use exe_common::config::net; fn main() { @@ -38,58 +37,67 @@ fn main() { .subcommand( SubCommand::with_name("start") .about("start explorer server") - .arg(Arg::with_name("PORT NUMBER") - .long("port") - .takes_value(true) - .value_name("PORT NUMBER") - .help("set the port number to listen to") - .required(false) - .default_value("80") - ) - .arg(Arg::with_name("NETWORKS DIRECTORY") - .long("networks-dir") - .takes_value(true) - .value_name("NETWORKS DIRECTORY") - .help("the relative or absolute directory of the networks to server") - .required(false) + .arg( + Arg::with_name("PORT NUMBER") + .long("port") + .takes_value(true) + .value_name("PORT NUMBER") + .help("set the port number to listen to") + .required(false) + .default_value("80"), ) - .arg(Arg::with_name("TEMPLATE") - .long("template") - .takes_value(true) - .value_name("TEMPLATE") - .help("either 'mainnet' or 'testnet'; may be given multiple times") - .required(false) - .multiple(true) - .default_value("mainnet") - .possible_values(&["mainnet", "staging", "testnet"]) + .arg( + Arg::with_name("NETWORKS DIRECTORY") + .long("networks-dir") + .takes_value(true) + .value_name("NETWORKS DIRECTORY") + .help("the relative or absolute directory of the networks to server") + .required(false), ) - .arg(Arg::with_name("no-sync") - .long("no-sync") - .help("disable synchronizing with the upstream network") + .arg( + Arg::with_name("TEMPLATE") + .long("template") + .takes_value(true) + .value_name("TEMPLATE") + .help("either 'mainnet' or 'testnet'; may be given multiple times") + .required(false) + .multiple(true) + .default_value("mainnet") + .possible_values(&["mainnet", "staging", "testnet"]), ) + .arg( + Arg::with_name("no-sync") + .long("no-sync") + .help("disable synchronizing with the upstream network"), + ), ) .get_matches(); match matches.subcommand() { ("start", Some(args)) => { - let mut cfg = Config::new( PathBuf::from( - value_t!(args.value_of("NETWORKS DIRECTORY"), String) - .unwrap_or( - hermes_path().unwrap().join("networks") - .to_str().unwrap().to_string())), - value_t!(args.value_of("PORT NUMBER"), u16).unwrap()); + value_t!(args.value_of("NETWORKS DIRECTORY"), String).unwrap_or( + hermes_path() + .unwrap() + .join("networks") + .to_str() + .unwrap() + .to_string(), + ), + ), + value_t!(args.value_of("PORT NUMBER"), u16).unwrap(), + ); ::std::fs::create_dir_all(cfg.root_dir.clone()).expect("create networks directory"); info!("Created networks directory {:?}", cfg.root_dir); for template in args.values_of("TEMPLATE").unwrap() { let net_cfg = match template { - "mainnet" => { net::Config::mainnet() }, - "staging" => { net::Config::staging() }, - "testnet" => { net::Config::testnet() }, - _ => { + "mainnet" => net::Config::mainnet(), + "staging" => net::Config::staging(), + "testnet" => net::Config::testnet(), + _ => { // we do not support custom template yet. // in the mean while the error is handled by clap // (possible_values) @@ -104,10 +112,10 @@ fn main() { info!("Starting {}-{}", crate_name!(), crate_version!()); service::start(cfg); - }, + } _ => { println!("{}", matches.usage()); ::std::process::exit(1); - }, + } } } diff --git a/src/service.rs b/src/service.rs index cdd5638..7db5f92 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1,15 +1,19 @@ -use super::config::{Config, Networks, Network}; -use exe_common::{sync, parse_genesis_data, genesis_data}; +use super::config::{Config, Network, Networks}; use super::handlers; +use exe_common::config::net; +use exe_common::{genesis_data, parse_genesis_data, sync}; use iron; use router::Router; use std::sync::Arc; use std::thread; use std::time::Duration; -use exe_common::config::net; pub fn start(cfg: Config) { - let _refreshers = if cfg.sync { Some(start_networks_refreshers(cfg.clone())) } else { None }; + let _refreshers = if cfg.sync { + Some(start_networks_refreshers(cfg.clone())) + } else { + None + }; let _server = start_http_server(&cfg, Arc::new(cfg.get_networks().unwrap())); // XXX: consider installing a signal handler to initiate a graceful shutdown here @@ -59,12 +63,17 @@ fn refresh_network(label: &str, net: &Network) { let net_cfg = net::Config::from_file(&netcfg_file).expect("no network config present"); let genesis_data = { - let genesis_data = genesis_data::get_genesis_data(&net_cfg.genesis_prev) - .expect("genesis data not found"); + let genesis_data = + genesis_data::get_genesis_data(&net_cfg.genesis_prev).expect("genesis data not found"); parse_genesis_data::parse_genesis_data(genesis_data) }; - sync::net_sync(&mut sync::get_peer(&label, &net_cfg, true), &net_cfg, - &genesis_data, &net.storage, false) - .unwrap_or_else(|err| { warn!("Sync failed: {:?}", err) }); + sync::net_sync( + &mut sync::get_peer(&label, &net_cfg, true), + &net_cfg, + &genesis_data, + &net.storage, + false, + ) + .unwrap_or_else(|err| warn!("Sync failed: {:?}", err)); }