Merge branch 'master' into lightsync

This commit is contained in:
Robert Habermeier
2016-12-28 15:53:11 +01:00
384 changed files with 9426 additions and 6137 deletions

View File

@@ -70,7 +70,7 @@ pub fn execute(cmd: AccountCmd) -> Result<String, String> {
}
fn keys_dir(path: String, spec: SpecType) -> Result<DiskDirectory, String> {
let spec = try!(spec.spec());
let spec = spec.spec()?;
let mut path = PathBuf::from(&path);
path.push(spec.data_dir);
DiskDirectory::create(path).map_err(|e| format!("Could not open keys directory: {}", e))
@@ -85,20 +85,20 @@ fn secret_store(dir: Box<DiskDirectory>, iterations: Option<u32>) -> Result<EthS
fn new(n: NewAccount) -> Result<String, String> {
let password: String = match n.password_file {
Some(file) => try!(password_from_file(file)),
None => try!(password_prompt()),
Some(file) => password_from_file(file)?,
None => password_prompt()?,
};
let dir = Box::new(try!(keys_dir(n.path, n.spec)));
let secret_store = Box::new(try!(secret_store(dir, Some(n.iterations))));
let dir = Box::new(keys_dir(n.path, n.spec)?);
let secret_store = Box::new(secret_store(dir, Some(n.iterations))?);
let acc_provider = AccountProvider::new(secret_store);
let new_account = try!(acc_provider.new_account(&password).map_err(|e| format!("Could not create new account: {}", e)));
let new_account = acc_provider.new_account(&password).map_err(|e| format!("Could not create new account: {}", e))?;
Ok(format!("{:?}", new_account))
}
fn list(list_cmd: ListAccounts) -> Result<String, String> {
let dir = Box::new(try!(keys_dir(list_cmd.path, list_cmd.spec)));
let secret_store = Box::new(try!(secret_store(dir, None)));
let dir = Box::new(keys_dir(list_cmd.path, list_cmd.spec)?);
let secret_store = Box::new(secret_store(dir, None)?);
let acc_provider = AccountProvider::new(secret_store);
let accounts = acc_provider.accounts();
let result = accounts.into_iter()
@@ -110,11 +110,11 @@ fn list(list_cmd: ListAccounts) -> Result<String, String> {
}
fn import(i: ImportAccounts) -> Result<String, String> {
let to = try!(keys_dir(i.to, i.spec));
let to = keys_dir(i.to, i.spec)?;
let mut imported = 0;
for path in &i.from {
let from = DiskDirectory::at(path);
imported += try!(import_accounts(&from, &to).map_err(|_| "Importing accounts failed.")).len();
imported += import_accounts(&from, &to).map_err(|_| "Importing accounts failed.")?.len();
}
Ok(format!("{} account(s) imported", imported))
}
@@ -123,8 +123,8 @@ fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> {
use std::io::ErrorKind;
use ethcore::ethstore::Error;
let dir = Box::new(try!(keys_dir(i.to, i.spec)));
let secret_store = Box::new(try!(secret_store(dir, None)));
let dir = Box::new(keys_dir(i.to, i.spec)?);
let secret_store = Box::new(secret_store(dir, None)?);
let geth_accounts = read_geth_accounts(i.testnet);
match secret_store.import_geth_accounts(geth_accounts, i.testnet) {
Ok(v) => Ok(format!("Successfully imported {} account(s) from geth.", v.len())),

View File

@@ -149,7 +149,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let panic_handler = PanicHandler::new_in_arc();
// load spec file
let spec = try!(cmd.spec.spec());
let spec = cmd.spec.spec()?;
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
@@ -161,7 +161,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = try!(UserDefaults::load(&user_defaults_path));
let mut user_defaults = UserDefaults::load(&user_defaults_path)?;
fdlimit::raise_fd_limit();
@@ -169,47 +169,47 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(cmd.tracing, &user_defaults));
let tracing = tracing_switch_to_bool(cmd.tracing, &user_defaults)?;
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm));
let fat_db = fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm)?;
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&cmd.dirs.base, &db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.db_root_path().as_path())));
execute_upgrades(&cmd.dirs.base, &db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.db_root_path().as_path()))?;
// create dirs used by parity
try!(cmd.dirs.create_dirs(false, false));
cmd.dirs.create_dirs(false, false)?;
// prepare client config
let mut client_config = to_client_config(
&cmd.cache_config,
Mode::Active,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
"".into(),
algorithm,
cmd.pruning_history,
&cmd.cache_config,
Mode::Active,
tracing,
fat_db,
cmd.compaction,
cmd.wal,
cmd.vm_type,
"".into(),
algorithm,
cmd.pruning_history,
cmd.check_seal
);
client_config.queue.verifier_settings = cmd.verifier_settings;
// build client
let service = try!(ClientService::start(
let service = ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e)));
).map_err(|e| format!("Client service error: {:?}", e))?;
// free up the spec in memory.
drop(spec);
@@ -218,7 +218,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let client = service.client();
let mut instream: Box<io::Read> = match cmd.file_path {
Some(f) => Box::new(try!(fs::File::open(&f).map_err(|_| format!("Cannot open given file: {}", f)))),
Some(f) => Box::new(fs::File::open(&f).map_err(|_| format!("Cannot open given file: {}", f))?),
None => Box::new(io::stdin()),
};
@@ -230,7 +230,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let format = match cmd.format {
Some(format) => format,
None => {
first_read = try!(instream.read(&mut first_bytes).map_err(|_| "Error reading from the file/stream."));
first_read = instream.read(&mut first_bytes).map_err(|_| "Error reading from the file/stream.")?;
match first_bytes[0] {
0xf9 => DataFormat::Binary,
_ => DataFormat::Hex,
@@ -262,23 +262,23 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let n = if first_read > 0 {
first_read
} else {
try!(instream.read(&mut bytes).map_err(|_| "Error reading from the file/stream."))
instream.read(&mut bytes).map_err(|_| "Error reading from the file/stream.")?
};
if n == 0 { break; }
first_read = 0;
let s = try!(PayloadInfo::from(&bytes).map_err(|e| format!("Invalid RLP in the file/stream: {:?}", e))).total();
let s = PayloadInfo::from(&bytes).map_err(|e| format!("Invalid RLP in the file/stream: {:?}", e))?.total();
bytes.resize(s, 0);
try!(instream.read_exact(&mut bytes[n..]).map_err(|_| "Error reading from the file/stream."));
try!(do_import(bytes));
instream.read_exact(&mut bytes[n..]).map_err(|_| "Error reading from the file/stream.")?;
do_import(bytes)?;
}
}
DataFormat::Hex => {
for line in BufReader::new(instream).lines() {
let s = try!(line.map_err(|_| "Error reading from the file/stream."));
let s = line.map_err(|_| "Error reading from the file/stream.")?;
let s = if first_read > 0 {from_utf8(&first_bytes).unwrap().to_owned() + &(s[..])} else {s};
first_read = 0;
let bytes = try!(s.from_hex().map_err(|_| "Invalid hex in file/stream."));
try!(do_import(bytes));
let bytes = s.from_hex().map_err(|_| "Invalid hex in file/stream.")?;
do_import(bytes)?;
}
}
}
@@ -288,7 +288,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
user_defaults.pruning = algorithm;
user_defaults.tracing = tracing;
user_defaults.fat_db = fat_db;
try!(user_defaults.save(&user_defaults_path));
user_defaults.save(&user_defaults_path)?;
let report = client.report();
@@ -318,7 +318,7 @@ fn start_client(
) -> Result<ClientService, String> {
// load spec file
let spec = try!(spec.spec());
let spec = spec.spec()?;
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
@@ -330,7 +330,7 @@ fn start_client(
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let user_defaults = try!(UserDefaults::load(&user_defaults_path));
let user_defaults = UserDefaults::load(&user_defaults_path)?;
fdlimit::raise_fd_limit();
@@ -338,32 +338,32 @@ fn start_client(
let algorithm = pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(tracing, &user_defaults));
let tracing = tracing_switch_to_bool(tracing, &user_defaults)?;
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(fat_db, &user_defaults, algorithm));
let fat_db = fatdb_switch_to_bool(fat_db, &user_defaults, algorithm)?;
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&dirs.base, &db_dirs, algorithm, compaction.compaction_profile(db_dirs.db_root_path().as_path())));
execute_upgrades(&dirs.base, &db_dirs, algorithm, compaction.compaction_profile(db_dirs.db_root_path().as_path()))?;
// create dirs used by parity
try!(dirs.create_dirs(false, false));
dirs.create_dirs(false, false)?;
// prepare client config
let client_config = to_client_config(&cache_config, Mode::Active, tracing, fat_db, compaction, wal, VMType::default(), "".into(), algorithm, pruning_history, true);
let service = try!(ClientService::start(
let service = ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e)));
).map_err(|e| format!("Client service error: {:?}", e))?;
drop(spec);
Ok(service)
@@ -371,7 +371,7 @@ fn start_client(
fn execute_export(cmd: ExportBlockchain) -> Result<(), String> {
// Setup panic handler
let service = try!(start_client(cmd.dirs, cmd.spec, cmd.pruning, cmd.pruning_history, cmd.tracing, cmd.fat_db, cmd.compaction, cmd.wal, cmd.cache_config));
let service = start_client(cmd.dirs, cmd.spec, cmd.pruning, cmd.pruning_history, cmd.tracing, cmd.fat_db, cmd.compaction, cmd.wal, cmd.cache_config)?;
let panic_handler = PanicHandler::new_in_arc();
let format = cmd.format.unwrap_or_default();
@@ -379,18 +379,18 @@ fn execute_export(cmd: ExportBlockchain) -> Result<(), String> {
let client = service.client();
let mut out: Box<io::Write> = match cmd.file_path {
Some(f) => Box::new(try!(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f)))),
Some(f) => Box::new(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f))?),
None => Box::new(io::stdout()),
};
let from = try!(client.block_number(cmd.from_block).ok_or("From block could not be found"));
let to = try!(client.block_number(cmd.to_block).ok_or("To block could not be found"));
let from = client.block_number(cmd.from_block).ok_or("From block could not be found")?;
let to = client.block_number(cmd.to_block).ok_or("To block could not be found")?;
for i in from..(to + 1) {
if i % 10000 == 0 {
info!("#{}", i);
}
let b = try!(client.block(BlockId::Number(i)).ok_or("Error exporting incomplete chain"));
let b = client.block(BlockId::Number(i)).ok_or("Error exporting incomplete chain")?.into_inner();
match format {
DataFormat::Binary => { out.write(&b).expect("Couldn't write to stream."); }
DataFormat::Hex => { out.write_fmt(format_args!("{}", b.pretty())).expect("Couldn't write to stream."); }
@@ -403,14 +403,14 @@ fn execute_export(cmd: ExportBlockchain) -> Result<(), String> {
fn execute_export_state(cmd: ExportState) -> Result<(), String> {
// Setup panic handler
let service = try!(start_client(cmd.dirs, cmd.spec, cmd.pruning, cmd.pruning_history, cmd.tracing, cmd.fat_db, cmd.compaction, cmd.wal, cmd.cache_config));
let service = start_client(cmd.dirs, cmd.spec, cmd.pruning, cmd.pruning_history, cmd.tracing, cmd.fat_db, cmd.compaction, cmd.wal, cmd.cache_config)?;
let panic_handler = PanicHandler::new_in_arc();
panic_handler.forward_from(&service);
let client = service.client();
let mut out: Box<io::Write> = match cmd.file_path {
Some(f) => Box::new(try!(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f)))),
Some(f) => Box::new(fs::File::create(&f).map_err(|_| format!("Cannot write to file given: {}", f))?),
None => Box::new(io::stdout()),
};
@@ -420,7 +420,7 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> {
out.write_fmt(format_args!("{{ \"state\": [", )).expect("Couldn't write to stream.");
loop {
let accounts = try!(client.list_accounts(at, last.as_ref(), 1000).ok_or("Specified block not found"));
let accounts = client.list_accounts(at, last.as_ref(), 1000).ok_or("Specified block not found")?;
if accounts.is_empty() {
break;
}
@@ -450,7 +450,7 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> {
out.write_fmt(format_args!(", \"storage\": {{")).expect("Write error");
let mut last_storage: Option<H256> = None;
loop {
let keys = try!(client.list_storage(at, &account, last_storage.as_ref(), 1000).ok_or("Specified block not found"));
let keys = client.list_storage(at, &account, last_storage.as_ref(), 1000).ok_or("Specified block not found")?;
if keys.is_empty() {
break;
}
@@ -482,14 +482,14 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> {
}
pub fn kill_db(cmd: KillBlockchain) -> Result<(), String> {
let spec = try!(cmd.spec.spec());
let spec = cmd.spec.spec()?;
let genesis_hash = spec.genesis_header().hash();
let db_dirs = cmd.dirs.database(genesis_hash, None, spec.data_dir);
let user_defaults_path = db_dirs.user_defaults_path();
let user_defaults = try!(UserDefaults::load(&user_defaults_path));
let user_defaults = UserDefaults::load(&user_defaults_path)?;
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
let dir = db_dirs.db_path(algorithm);
try!(fs::remove_dir_all(&dir).map_err(|e| format!("Error removing database: {:?}", e)));
fs::remove_dir_all(&dir).map_err(|e| format!("Error removing database: {:?}", e))?;
info!("Database deleted.");
Ok(())
}

View File

@@ -53,9 +53,7 @@ pub fn payload<B: ipc::BinaryConvertable>() -> Result<B, BootError> {
use std::io::Read;
let mut buffer = Vec::new();
try!(
io::stdin().read_to_end(&mut buffer).map_err(BootError::ReadArgs)
);
io::stdin().read_to_end(&mut buffer).map_err(BootError::ReadArgs)?;
ipc::binary::deserialize::<B>(&buffer).map_err(BootError::DecodeArgs)
}

View File

@@ -94,7 +94,7 @@ notify_work = ["http://localhost:3001"]
[footprint]
tracing = "auto"
pruning = "auto"
pruning_history = 64
pruning_history = 1200
cache_size_db = 64
cache_size_blocks = 8
cache_size_queue = 50

View File

@@ -238,7 +238,7 @@ usage! {
or |c: &Config| otry!(c.footprint).tracing.clone(),
flag_pruning: String = "auto",
or |c: &Config| otry!(c.footprint).pruning.clone(),
flag_pruning_history: u64 = 64u64,
flag_pruning_history: u64 = 1200u64,
or |c: &Config| otry!(c.footprint).pruning_history.clone(),
flag_cache_size_db: u32 = 64u32,
or |c: &Config| otry!(c.footprint).cache_size_db.clone(),
@@ -632,7 +632,7 @@ mod tests {
// -- Footprint Options
flag_tracing: "auto".into(),
flag_pruning: "auto".into(),
flag_pruning_history: 64u64,
flag_pruning_history: 1200u64,
flag_cache_size_db: 64u32,
flag_cache_size_blocks: 8u32,
flag_cache_size_queue: 50u32,

View File

@@ -137,7 +137,7 @@ macro_rules! usage {
impl Args {
pub fn parse<S: AsRef<str>>(command: &[S]) -> Result<Self, ArgsError> {
let raw_args = try!(RawArgs::parse(command));
let raw_args = RawArgs::parse(command)?;
// Skip loading config file if no_config flag is specified
if raw_args.flag_no_config {
@@ -151,8 +151,8 @@ macro_rules! usage {
(Ok(mut file), _) => {
println_stderr!("Loading config file from {}", &config_file);
let mut config = String::new();
try!(file.read_to_string(&mut config).map_err(|e| ArgsError::Config(config_file, e)));
try!(Self::parse_config(&config))
file.read_to_string(&mut config).map_err(|e| ArgsError::Config(config_file, e))?;
Self::parse_config(&config)?
},
// Don't display error in case default config cannot be loaded.
(Err(_), false) => Config::default(),
@@ -172,7 +172,7 @@ macro_rules! usage {
#[cfg(test)]
fn parse_with_config<S: AsRef<str>>(command: &[S], config: Config) -> Result<Self, ArgsError> {
Ok(try!(RawArgs::parse(command)).into_args(config))
RawArgs::parse(command).map(|raw| raw.into_args(config)).map_err(ArgsError::Docopt)
}
fn parse_config(config: &str) -> Result<Config, ArgsError> {

View File

@@ -85,7 +85,7 @@ pub struct Configuration {
impl Configuration {
pub fn parse<S: AsRef<str>>(command: &[S]) -> Result<Self, ArgsError> {
let args = try!(Args::parse(command));
let args = Args::parse(command)?;
let config = Configuration {
args: args,
@@ -96,29 +96,29 @@ impl Configuration {
pub fn into_command(self) -> Result<Execute, String> {
let dirs = self.directories();
let pruning = try!(self.args.flag_pruning.parse());
let pruning = self.args.flag_pruning.parse()?;
let pruning_history = self.args.flag_pruning_history;
let vm_type = try!(self.vm_type());
let mode = match self.args.flag_mode.as_ref() { "last" => None, mode => Some(try!(to_mode(&mode, self.args.flag_mode_timeout, self.args.flag_mode_alarm))), };
let update_policy = try!(self.update_policy());
let miner_options = try!(self.miner_options());
let vm_type = self.vm_type()?;
let mode = match self.args.flag_mode.as_ref() { "last" => None, mode => Some(to_mode(&mode, self.args.flag_mode_timeout, self.args.flag_mode_alarm)?), };
let update_policy = self.update_policy()?;
let miner_options = self.miner_options()?;
let logger_config = self.logger_config();
let http_conf = try!(self.http_config());
let ipc_conf = try!(self.ipc_config());
let net_conf = try!(self.net_config());
let http_conf = self.http_config()?;
let ipc_conf = self.ipc_config()?;
let net_conf = self.net_config()?;
let network_id = self.network_id();
let cache_config = self.cache_config();
let spec = try!(self.chain().parse());
let tracing = try!(self.args.flag_tracing.parse());
let fat_db = try!(self.args.flag_fat_db.parse());
let compaction = try!(self.args.flag_db_compaction.parse());
let spec = self.chain().parse()?;
let tracing = self.args.flag_tracing.parse()?;
let fat_db = self.args.flag_fat_db.parse()?;
let compaction = self.args.flag_db_compaction.parse()?;
let wal = !self.args.flag_fast_and_loose;
let warp_sync = self.args.flag_warp;
let geth_compatibility = self.args.flag_geth;
let ui_address = self.ui_port().map(|port| (self.ui_interface(), port));
let dapps_conf = self.dapps_config();
let signer_conf = self.signer_config();
let format = try!(self.format());
let format = self.format()?;
let cmd = if self.args.flag_version {
Cmd::Version
@@ -237,8 +237,8 @@ impl Configuration {
wal: wal,
tracing: tracing,
fat_db: fat_db,
from_block: try!(to_block_id(&self.args.flag_from)),
to_block: try!(to_block_id(&self.args.flag_to)),
from_block: to_block_id(&self.args.flag_from)?,
to_block: to_block_id(&self.args.flag_to)?,
check_seal: !self.args.flag_no_seal_check,
};
Cmd::Blockchain(BlockchainCmd::Export(export_cmd))
@@ -255,7 +255,7 @@ impl Configuration {
wal: wal,
tracing: tracing,
fat_db: fat_db,
at: try!(to_block_id(&self.args.flag_at)),
at: to_block_id(&self.args.flag_at)?,
storage: !self.args.flag_no_storage,
code: !self.args.flag_no_code,
min_balance: self.args.flag_min_balance.and_then(|s| to_u256(&s).ok()),
@@ -278,7 +278,7 @@ impl Configuration {
file_path: self.args.arg_file.clone(),
wal: wal,
kind: snapshot::Kind::Take,
block_at: try!(to_block_id(&self.args.flag_at)),
block_at: to_block_id(&self.args.flag_at)?,
};
Cmd::Snapshot(snapshot_cmd)
} else if self.args.cmd_restore {
@@ -294,7 +294,7 @@ impl Configuration {
file_path: self.args.arg_file.clone(),
wal: wal,
kind: snapshot::Kind::Restore,
block_at: try!(to_block_id("latest")), // unimportant.
block_at: to_block_id("latest")?, // unimportant.
};
Cmd::Snapshot(restore_cmd)
} else {
@@ -319,9 +319,9 @@ impl Configuration {
ipc_conf: ipc_conf,
net_conf: net_conf,
network_id: network_id,
acc_conf: try!(self.accounts_config()),
gas_pricer: try!(self.gas_pricer_config()),
miner_extras: try!(self.miner_extras()),
acc_conf: self.accounts_config()?,
gas_pricer: self.gas_pricer_config()?,
miner_extras: self.miner_extras()?,
update_policy: update_policy,
mode: mode,
tracing: tracing,
@@ -363,12 +363,12 @@ impl Configuration {
fn miner_extras(&self) -> Result<MinerExtras, String> {
let extras = MinerExtras {
author: try!(self.author()),
extra_data: try!(self.extra_data()),
gas_floor_target: try!(to_u256(&self.args.flag_gas_floor_target)),
gas_ceil_target: try!(to_u256(&self.args.flag_gas_cap)),
author: self.author()?,
extra_data: self.extra_data()?,
gas_floor_target: to_u256(&self.args.flag_gas_floor_target)?,
gas_ceil_target: to_u256(&self.args.flag_gas_cap)?,
transactions_limit: self.args.flag_tx_queue_size,
engine_signer: try!(self.engine_signer()),
engine_signer: self.engine_signer()?,
};
Ok(extras)
@@ -384,7 +384,7 @@ impl Configuration {
fn format(&self) -> Result<Option<DataFormat>, String> {
match self.args.flag_format {
Some(ref f) => Ok(Some(try!(f.parse()))),
Some(ref f) => Ok(Some(f.parse()?)),
None => Ok(None),
}
}
@@ -452,14 +452,14 @@ impl Configuration {
iterations: self.args.flag_keys_iterations,
testnet: self.args.flag_testnet,
password_files: self.args.flag_password.clone(),
unlocked_accounts: try!(to_addresses(&self.args.flag_unlock)),
unlocked_accounts: to_addresses(&self.args.flag_unlock)?,
};
Ok(cfg)
}
fn miner_options(&self) -> Result<MinerOptions, String> {
let reseal = try!(self.args.flag_reseal_on_txs.parse::<ResealPolicy>());
let reseal = self.args.flag_reseal_on_txs.parse::<ResealPolicy>()?;
let options = MinerOptions {
new_work_notify: self.work_notify(),
@@ -467,13 +467,13 @@ impl Configuration {
reseal_on_external_tx: reseal.external,
reseal_on_own_tx: reseal.own,
tx_gas_limit: match self.args.flag_tx_gas_limit {
Some(ref d) => try!(to_u256(d)),
Some(ref d) => to_u256(d)?,
None => U256::max_value(),
},
tx_queue_size: self.args.flag_tx_queue_size,
tx_queue_gas_limit: try!(to_gas_limit(&self.args.flag_tx_queue_gas)),
tx_queue_strategy: try!(to_queue_strategy(&self.args.flag_tx_queue_strategy)),
pending_set: try!(to_pending_set(&self.args.flag_relay_set)),
tx_queue_gas_limit: to_gas_limit(&self.args.flag_tx_queue_gas)?,
tx_queue_strategy: to_queue_strategy(&self.args.flag_tx_queue_strategy)?,
pending_set: to_pending_set(&self.args.flag_relay_set)?,
reseal_min_period: Duration::from_millis(self.args.flag_reseal_min_period),
work_queue_size: self.args.flag_work_queue_size,
enable_resubmission: !self.args.flag_remove_solved,
@@ -514,18 +514,18 @@ impl Configuration {
fn gas_pricer_config(&self) -> Result<GasPricerConfig, String> {
if let Some(d) = self.args.flag_gasprice.as_ref() {
return Ok(GasPricerConfig::Fixed(try!(to_u256(d))));
return Ok(GasPricerConfig::Fixed(to_u256(d)?));
}
let usd_per_tx = try!(to_price(&self.args.flag_usd_per_tx));
let usd_per_tx = to_price(&self.args.flag_usd_per_tx)?;
if "auto" == self.args.flag_usd_per_eth.as_str() {
return Ok(GasPricerConfig::Calibrated {
usd_per_tx: usd_per_tx,
recalibration_period: try!(to_duration(self.args.flag_price_update_period.as_str())),
recalibration_period: to_duration(self.args.flag_price_update_period.as_str())?,
});
}
let usd_per_eth = try!(to_price(&self.args.flag_usd_per_eth));
let usd_per_eth = to_price(&self.args.flag_usd_per_eth)?;
let wei_per_usd: f32 = 1.0e18 / usd_per_eth;
let gas_per_tx: f32 = 21000.0;
let wei_per_gas: f32 = wei_per_usd * usd_per_tx / gas_per_tx;
@@ -553,8 +553,8 @@ impl Configuration {
match self.args.flag_reserved_peers {
Some(ref path) => {
let mut buffer = String::new();
let mut node_file = try!(File::open(path).map_err(|e| format!("Error opening reserved nodes file: {}", e)));
try!(node_file.read_to_string(&mut buffer).map_err(|_| "Error reading reserved node file"));
let mut node_file = File::open(path).map_err(|e| format!("Error opening reserved nodes file: {}", e))?;
node_file.read_to_string(&mut buffer).map_err(|_| "Error reading reserved node file")?;
let lines = buffer.lines().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect::<Vec<_>>();
if let Some(invalid) = lines.iter().find(|s| !is_valid_node_url(s)) {
return Err(format!("Invalid node address format given for a boot node: {}", invalid));
@@ -570,7 +570,7 @@ impl Configuration {
let listen_address = Some(SocketAddr::new("0.0.0.0".parse().unwrap(), port));
let public_address = if self.args.flag_nat.starts_with("extip:") {
let host = &self.args.flag_nat[6..];
let host = try!(host.parse().map_err(|_| format!("Invalid host given with `--nat extip:{}`", host)));
let host = host.parse().map_err(|_| format!("Invalid host given with `--nat extip:{}`", host))?;
Some(SocketAddr::new(host, port))
} else {
None
@@ -581,8 +581,8 @@ impl Configuration {
fn net_config(&self) -> Result<NetworkConfiguration, String> {
let mut ret = NetworkConfiguration::new();
ret.nat_enabled = self.args.flag_nat == "any" || self.args.flag_nat == "upnp";
ret.boot_nodes = try!(to_bootnodes(&self.args.flag_bootnodes));
let (listen, public) = try!(self.net_addresses());
ret.boot_nodes = to_bootnodes(&self.args.flag_bootnodes)?;
let (listen, public) = self.net_addresses()?;
ret.listen_address = listen.map(|l| format!("{}", l));
ret.public_address = public.map(|p| format!("{}", p));
ret.use_secret = self.args.flag_node_key.as_ref().map(|s| s.parse::<Secret>().unwrap_or_else(|_| s.sha3()));
@@ -590,12 +590,12 @@ impl Configuration {
ret.max_peers = self.max_peers();
ret.min_peers = self.min_peers();
ret.snapshot_peers = self.snapshot_peers();
ret.allow_ips = try!(self.allow_ips());
ret.allow_ips = self.allow_ips()?;
ret.max_pending_peers = self.max_pending_peers();
let mut net_path = PathBuf::from(self.directories().base);
net_path.push("network");
ret.config_path = Some(net_path.to_str().unwrap().to_owned());
ret.reserved_nodes = try!(self.init_reserved_nodes());
ret.reserved_nodes = self.init_reserved_nodes()?;
ret.allow_non_reserved = !self.args.flag_reserved_only;
Ok(ret)
}
@@ -652,7 +652,7 @@ impl Configuration {
}
apis.push_str("personal");
}
try!(apis.parse())
apis.parse()?
},
};
@@ -664,7 +664,7 @@ impl Configuration {
enabled: !self.args.flag_jsonrpc_off && !self.args.flag_no_jsonrpc,
interface: self.rpc_interface(),
port: self.args.flag_rpcport.unwrap_or(self.args.flag_jsonrpc_port),
apis: try!(self.rpc_apis().parse()),
apis: self.rpc_apis().parse()?,
hosts: self.rpc_hosts(),
cors: self.rpc_cors(),
};
@@ -899,7 +899,7 @@ mod tests {
file_path: Some("blockchain.json".into()),
format: Default::default(),
pruning: Default::default(),
pruning_history: 64,
pruning_history: 1200,
compaction: Default::default(),
wal: true,
tracing: Default::default(),
@@ -921,7 +921,7 @@ mod tests {
dirs: Default::default(),
file_path: Some("blockchain.json".into()),
pruning: Default::default(),
pruning_history: 64,
pruning_history: 1200,
format: Default::default(),
compaction: Default::default(),
wal: true,
@@ -943,7 +943,7 @@ mod tests {
dirs: Default::default(),
file_path: Some("state.json".into()),
pruning: Default::default(),
pruning_history: 64,
pruning_history: 1200,
format: Default::default(),
compaction: Default::default(),
wal: true,
@@ -967,7 +967,7 @@ mod tests {
dirs: Default::default(),
file_path: Some("blockchain.json".into()),
pruning: Default::default(),
pruning_history: 64,
pruning_history: 1200,
format: Some(DataFormat::Hex),
compaction: Default::default(),
wal: true,
@@ -1002,7 +1002,7 @@ mod tests {
dirs: Default::default(),
spec: Default::default(),
pruning: Default::default(),
pruning_history: 64,
pruning_history: 1200,
daemon: None,
logger_config: Default::default(),
miner_options: Default::default(),

View File

@@ -21,6 +21,7 @@ use ethcore::client::Client;
use ethsync::SyncProvider;
use helpers::replace_home;
use dir::default_data_path;
use rpc_apis::SignerService;
use hash_fetch::fetch::Client as FetchClient;
use parity_reactor::Remote;
@@ -57,6 +58,7 @@ pub struct Dependencies {
pub sync: Arc<SyncProvider>,
pub remote: Remote,
pub fetch: FetchClient,
pub signer: Arc<SignerService>,
}
pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<WebappServer>, String> {
@@ -64,9 +66,8 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<We
return Ok(None);
}
let signer_address = deps.apis.signer_service.address();
let url = format!("{}:{}", configuration.interface, configuration.port);
let addr = try!(url.parse().map_err(|_| format!("Invalid Webapps listen host/port given: {}", url)));
let addr = url.parse().map_err(|_| format!("Invalid Webapps listen host/port given: {}", url))?;
let auth = configuration.user.as_ref().map(|username| {
let password = configuration.pass.as_ref().map_or_else(|| {
@@ -79,7 +80,7 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<We
(username.to_owned(), password)
});
Ok(Some(try!(setup_dapps_server(deps, configuration.dapps_path, &addr, configuration.hosts, auth, signer_address))))
Ok(Some(setup_dapps_server(deps, configuration.dapps_path, &addr, configuration.hosts, auth)?))
}
pub use self::server::WebappServer;
@@ -97,7 +98,6 @@ mod server {
_url: &SocketAddr,
_allowed_hosts: Option<Vec<String>>,
_auth: Option<(String, String)>,
_signer_address: Option<(String, u16)>,
) -> Result<WebappServer, String> {
Err("Your Parity version has been compiled without WebApps support.".into())
}
@@ -126,20 +126,22 @@ mod server {
url: &SocketAddr,
allowed_hosts: Option<Vec<String>>,
auth: Option<(String, String)>,
signer_address: Option<(String, u16)>,
) -> Result<WebappServer, String> {
use ethcore_dapps as dapps;
let mut server = dapps::ServerBuilder::new(
let server = dapps::ServerBuilder::new(
dapps_path,
Arc::new(Registrar { client: deps.client.clone() }),
deps.remote.clone(),
);
let sync = deps.sync.clone();
let client = deps.client.clone();
server.with_fetch(deps.fetch.clone());
server.with_sync_status(Arc::new(move || is_major_importing(Some(sync.status().state), client.queue_info())));
server.with_signer_address(signer_address);
let signer = deps.signer.clone();
let server = server
.fetch(deps.fetch.clone())
.sync_status(Arc::new(move || is_major_importing(Some(sync.status().state), client.queue_info())))
.web_proxy_tokens(Arc::new(move |token| signer.is_valid_web_proxy_access_token(&token)))
.signer_address(deps.signer.address());
let server = rpc_apis::setup_rpc(server, deps.apis.clone(), rpc_apis::ApiSet::UnsafeContext);
let start_result = match auth {

View File

@@ -59,14 +59,14 @@ impl Default for Directories {
impl Directories {
pub fn create_dirs(&self, dapps_enabled: bool, signer_enabled: bool) -> Result<(), String> {
try!(fs::create_dir_all(&self.base).map_err(|e| e.to_string()));
try!(fs::create_dir_all(&self.db).map_err(|e| e.to_string()));
try!(fs::create_dir_all(&self.keys).map_err(|e| e.to_string()));
fs::create_dir_all(&self.base).map_err(|e| e.to_string())?;
fs::create_dir_all(&self.db).map_err(|e| e.to_string())?;
fs::create_dir_all(&self.keys).map_err(|e| e.to_string())?;
if signer_enabled {
try!(fs::create_dir_all(&self.signer).map_err(|e| e.to_string()));
fs::create_dir_all(&self.signer).map_err(|e| e.to_string())?;
}
if dapps_enabled {
try!(fs::create_dir_all(&self.dapps).map_err(|e| e.to_string()));
fs::create_dir_all(&self.dapps).map_err(|e| e.to_string())?;
}
Ok(())
}

View File

@@ -97,7 +97,7 @@ pub fn to_gas_limit(s: &str) -> Result<GasLimit, String> {
match s {
"auto" => Ok(GasLimit::Auto),
"off" => Ok(GasLimit::None),
other => Ok(GasLimit::Fixed(try!(to_u256(other)))),
other => Ok(GasLimit::Fixed(to_u256(other)?)),
}
}
@@ -288,12 +288,12 @@ pub fn password_prompt() -> Result<String, String> {
print!("Type password: ");
flush_stdout();
let password = try!(read_password().map_err(|_| STDIN_ERROR.to_owned()));
let password = read_password().map_err(|_| STDIN_ERROR.to_owned())?;
print!("Repeat password: ");
flush_stdout();
let password_repeat = try!(read_password().map_err(|_| STDIN_ERROR.to_owned()));
let password_repeat = read_password().map_err(|_| STDIN_ERROR.to_owned())?;
if password != password_repeat {
return Err("Passwords do not match!".into());
@@ -304,7 +304,7 @@ pub fn password_prompt() -> Result<String, String> {
/// Read a password from password file.
pub fn password_from_file(path: String) -> Result<String, String> {
let passwords = try!(passwords_from_files(&[path]));
let passwords = passwords_from_files(&[path])?;
// use only first password from the file
passwords.get(0).map(String::to_owned)
.ok_or_else(|| "Password file seems to be empty.".to_owned())
@@ -313,7 +313,7 @@ pub fn password_from_file(path: String) -> Result<String, String> {
/// Reads passwords from files. Treats each line as a separate password.
pub fn passwords_from_files(files: &[String]) -> Result<Vec<String>, String> {
let passwords = files.iter().map(|filename| {
let file = try!(File::open(filename).map_err(|_| format!("{} Unable to read password file. Ensure it exists and permissions are correct.", filename)));
let file = File::open(filename).map_err(|_| format!("{} Unable to read password file. Ensure it exists and permissions are correct.", filename))?;
let reader = BufReader::new(&file);
let lines = reader.lines()
.filter_map(|l| l.ok())
@@ -321,7 +321,7 @@ pub fn passwords_from_files(files: &[String]) -> Result<Vec<String>, String> {
.collect::<Vec<String>>();
Ok(lines)
}).collect::<Result<Vec<Vec<String>>, String>>();
Ok(try!(passwords).into_iter().flat_map(|x| x).collect())
Ok(passwords?.into_iter().flat_map(|x| x).collect())
}
#[cfg(test)]

View File

@@ -27,15 +27,13 @@ use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::ClientIoMessage;
use ethcore::views::BlockView;
use ethcore::snapshot::service::Service as SnapshotService;
use ethcore::snapshot::{RestorationStatus, SnapshotService as SS};
use number_prefix::{binary_prefix, Standalone, Prefixed};
use ethcore_rpc::is_major_importing;
use rlp::View;
pub struct Informant {
chain_info: RwLock<Option<BlockChainInfo>>,
cache_info: RwLock<Option<BlockChainCacheSize>>,
report: RwLock<Option<ClientReport>>,
last_tick: RwLock<Instant>,
with_color: bool,
@@ -73,8 +71,6 @@ impl Informant {
/// Make a new instance potentially `with_color` output.
pub fn new(client: Arc<Client>, sync: Option<Arc<SyncProvider>>, net: Option<Arc<ManageNetwork>>, snapshot: Option<Arc<SnapshotService>>, with_color: bool) -> Self {
Informant {
chain_info: RwLock::new(None),
cache_info: RwLock::new(None),
report: RwLock::new(None),
last_tick: RwLock::new(Instant::now()),
with_color: with_color,
@@ -177,8 +173,6 @@ impl Informant {
)
);
*self.chain_info.write() = Some(chain_info);
*self.cache_info.write() = Some(cache_info);
*write_report = Some(report);
}
}
@@ -192,21 +186,19 @@ impl ChainNotify for Informant {
let txs_imported = imported.iter()
.take(imported.len().saturating_sub(if ripe { 1 } else { 0 }))
.filter_map(|h| self.client.block(BlockId::Hash(*h)))
.map(|b| BlockView::new(&b).transactions_count())
.map(|b| b.transactions_count())
.sum();
if ripe {
if let Some(block) = imported.last().and_then(|h| self.client.block(BlockId::Hash(*h))) {
let view = BlockView::new(&block);
let header = view.header();
let tx_count = view.transactions_count();
let size = block.len();
let header_view = block.header_view();
let size = block.rlp().as_raw().len();
let (skipped, skipped_txs) = (self.skipped.load(AtomicOrdering::Relaxed) + imported.len() - 1, self.skipped_txs.load(AtomicOrdering::Relaxed) + txs_imported);
info!(target: "import", "Imported {} {} ({} txs, {} Mgas, {} ms, {} KiB){}",
Colour::White.bold().paint(format!("#{}", header.number())),
Colour::White.bold().paint(format!("{}", header.hash())),
Colour::Yellow.bold().paint(format!("{}", tx_count)),
Colour::Yellow.bold().paint(format!("{:.2}", header.gas_used().low_u64() as f32 / 1000000f32)),
Colour::White.bold().paint(format!("#{}", header_view.number())),
Colour::White.bold().paint(format!("{}", header_view.hash())),
Colour::Yellow.bold().paint(format!("{}", block.transactions_count())),
Colour::Yellow.bold().paint(format!("{:.2}", header_view.gas_used().low_u64() as f32 / 1000000f32)),
Colour::Purple.bold().paint(format!("{:.2}", duration as f32 / 1000000f32)),
Colour::Blue.bold().paint(format!("{:.2}", size as f32 / 1024f32)),
if skipped > 0 {

View File

@@ -131,8 +131,8 @@ use dir::default_hypervisor_path;
fn print_hash_of(maybe_file: Option<String>) -> Result<String, String> {
if let Some(file) = maybe_file {
let mut f = BufReader::new(try!(File::open(&file).map_err(|_| "Unable to open file".to_owned())));
let hash = try!(sha3(&mut f).map_err(|_| "Unable to read from file".to_owned()));
let mut f = BufReader::new(File::open(&file).map_err(|_| "Unable to open file".to_owned())?);
let hash = sha3(&mut f).map_err(|_| "Unable to read from file".to_owned())?;
Ok(hash.hex())
} else {
Err("Streaming from standard input not yet supported. Specify a file.".to_owned())
@@ -175,7 +175,7 @@ fn start(can_restart: bool) -> Result<PostExecutionAction, String> {
println!("{}", d);
}
let cmd = try!(conf.into_command());
let cmd = conf.into_command()?;
execute(cmd, can_restart)
}

View File

@@ -104,7 +104,7 @@ fn current_version(path: &Path) -> Result<u32, Error> {
Err(_) => Err(Error::UnknownDatabaseVersion),
Ok(mut file) => {
let mut s = String::new();
try!(file.read_to_string(&mut s).map_err(|_| Error::UnknownDatabaseVersion));
file.read_to_string(&mut s).map_err(|_| Error::UnknownDatabaseVersion)?;
u32::from_str_radix(&s, 10).map_err(|_| Error::UnknownDatabaseVersion)
},
}
@@ -113,9 +113,9 @@ fn current_version(path: &Path) -> Result<u32, Error> {
/// Writes current database version to the file.
/// Creates a new file if the version file does not exist yet.
fn update_version(path: &Path) -> Result<(), Error> {
try!(fs::create_dir_all(path));
let mut file = try!(File::create(version_file_path(path)));
try!(file.write_all(format!("{}", CURRENT_VERSION).as_bytes()));
fs::create_dir_all(path)?;
let mut file = File::create(version_file_path(path))?;
file.write_all(format!("{}", CURRENT_VERSION).as_bytes())?;
Ok(())
}
@@ -145,7 +145,7 @@ pub fn default_migration_settings(compaction_profile: &CompactionProfile) -> Mig
/// Migrations on the consolidated database.
fn consolidated_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> {
let mut manager = MigrationManager::new(default_migration_settings(compaction_profile));
try!(manager.add_migration(migrations::ToV10::new()).map_err(|_| Error::MigrationImpossible));
manager.add_migration(migrations::ToV10::new()).map_err(|_| Error::MigrationImpossible)?;
Ok(manager)
}
@@ -171,16 +171,16 @@ fn consolidate_database(
wal: true,
};
let old_path_str = try!(old_db_path.to_str().ok_or(Error::MigrationImpossible));
let new_path_str = try!(new_db_path.to_str().ok_or(Error::MigrationImpossible));
let old_path_str = old_db_path.to_str().ok_or(Error::MigrationImpossible)?;
let new_path_str = new_db_path.to_str().ok_or(Error::MigrationImpossible)?;
let cur_db = Arc::new(try!(Database::open(&db_config, old_path_str).map_err(db_error)));
let cur_db = Arc::new(Database::open(&db_config, old_path_str).map_err(db_error)?);
// open new DB with proper number of columns
db_config.columns = migration.columns();
let mut new_db = try!(Database::open(&db_config, new_path_str).map_err(db_error));
let mut new_db = Database::open(&db_config, new_path_str).map_err(db_error)?;
// Migrate to new database (default column only)
try!(migration.migrate(cur_db, &config, &mut new_db, None));
migration.migrate(cur_db, &config, &mut new_db, None)?;
Ok(())
}
@@ -198,20 +198,20 @@ fn migrate_database(version: u32, db_path: PathBuf, mut migrations: MigrationMan
let _ = fs::remove_dir_all(&backup_path);
// migrate old database to the new one
let temp_path = try!(migrations.execute(&db_path, version));
let temp_path = migrations.execute(&db_path, version)?;
// create backup
try!(fs::rename(&db_path, &backup_path));
fs::rename(&db_path, &backup_path)?;
// replace the old database with the new one
if let Err(err) = fs::rename(&temp_path, &db_path) {
// if something went wrong, bring back backup
try!(fs::rename(&backup_path, &db_path));
fs::rename(&backup_path, &db_path)?;
return Err(err.into());
}
// remove backup
try!(fs::remove_dir_all(&backup_path));
fs::remove_dir_all(&backup_path)?;
Ok(())
}
@@ -223,7 +223,7 @@ fn exists(path: &Path) -> bool {
/// Migrates the database.
pub fn migrate(path: &Path, pruning: Algorithm, compaction_profile: CompactionProfile) -> Result<(), Error> {
// read version file.
let version = try!(current_version(path));
let version = current_version(path)?;
// migrate the databases.
// main db directory may already exists, so let's check if we have blocks dir
@@ -240,18 +240,18 @@ pub fn migrate(path: &Path, pruning: Algorithm, compaction_profile: CompactionPr
if version < CONSOLIDATION_VERSION && exists(&legacy::blocks_database_path(path)) {
println!("Migrating database from version {} to {}", version, CONSOLIDATION_VERSION);
try!(migrate_database(version, legacy::extras_database_path(path), try!(legacy::extras_database_migrations(&compaction_profile))));
try!(migrate_database(version, legacy::state_database_path(path), try!(legacy::state_database_migrations(pruning, &compaction_profile))));
try!(migrate_database(version, legacy::blocks_database_path(path), try!(legacy::blocks_database_migrations(&compaction_profile))));
migrate_database(version, legacy::extras_database_path(path), legacy::extras_database_migrations(&compaction_profile)?)?;
migrate_database(version, legacy::state_database_path(path), legacy::state_database_migrations(pruning, &compaction_profile)?)?;
migrate_database(version, legacy::blocks_database_path(path), legacy::blocks_database_migrations(&compaction_profile)?)?;
let db_path = consolidated_database_path(path);
// Remove the database dir (it shouldn't exist anyway, but it might when migration was interrupted)
let _ = fs::remove_dir_all(db_path.clone());
try!(consolidate_database(legacy::blocks_database_path(path), db_path.clone(), db::COL_HEADERS, Extract::Header, &compaction_profile));
try!(consolidate_database(legacy::blocks_database_path(path), db_path.clone(), db::COL_BODIES, Extract::Body, &compaction_profile));
try!(consolidate_database(legacy::extras_database_path(path), db_path.clone(), db::COL_EXTRA, Extract::All, &compaction_profile));
try!(consolidate_database(legacy::state_database_path(path), db_path.clone(), db::COL_STATE, Extract::All, &compaction_profile));
try!(consolidate_database(legacy::trace_database_path(path), db_path.clone(), db::COL_TRACE, Extract::All, &compaction_profile));
consolidate_database(legacy::blocks_database_path(path), db_path.clone(), db::COL_HEADERS, Extract::Header, &compaction_profile)?;
consolidate_database(legacy::blocks_database_path(path), db_path.clone(), db::COL_BODIES, Extract::Body, &compaction_profile)?;
consolidate_database(legacy::extras_database_path(path), db_path.clone(), db::COL_EXTRA, Extract::All, &compaction_profile)?;
consolidate_database(legacy::state_database_path(path), db_path.clone(), db::COL_STATE, Extract::All, &compaction_profile)?;
consolidate_database(legacy::trace_database_path(path), db_path.clone(), db::COL_TRACE, Extract::All, &compaction_profile)?;
let _ = fs::remove_dir_all(legacy::blocks_database_path(path));
let _ = fs::remove_dir_all(legacy::extras_database_path(path));
let _ = fs::remove_dir_all(legacy::state_database_path(path));
@@ -265,7 +265,7 @@ pub fn migrate(path: &Path, pruning: Algorithm, compaction_profile: CompactionPr
// Further migrations
if version >= CONSOLIDATION_VERSION && version < CURRENT_VERSION && exists(&consolidated_database_path(path)) {
println!("Migrating database from version {} to {}", ::std::cmp::max(CONSOLIDATION_VERSION, version), CURRENT_VERSION);
try!(migrate_database(version, consolidated_database_path(path), try!(consolidated_database_migrations(&compaction_profile))));
migrate_database(version, consolidated_database_path(path), consolidated_database_migrations(&compaction_profile)?)?;
println!("Migration finished");
}
@@ -313,14 +313,14 @@ mod legacy {
/// Migrations on the blocks database.
pub fn blocks_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> {
let mut manager = MigrationManager::new(default_migration_settings(compaction_profile));
try!(manager.add_migration(migrations::blocks::V8::default()).map_err(|_| Error::MigrationImpossible));
manager.add_migration(migrations::blocks::V8::default()).map_err(|_| Error::MigrationImpossible)?;
Ok(manager)
}
/// Migrations on the extras database.
pub fn extras_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> {
let mut manager = MigrationManager::new(default_migration_settings(compaction_profile));
try!(manager.add_migration(migrations::extras::ToV6).map_err(|_| Error::MigrationImpossible));
manager.add_migration(migrations::extras::ToV6).map_err(|_| Error::MigrationImpossible)?;
Ok(manager)
}
@@ -333,7 +333,7 @@ mod legacy {
_ => return Err(Error::UnsupportedPruningMethod),
};
try!(res.map_err(|_| Error::MigrationImpossible));
res.map_err(|_| Error::MigrationImpossible)?;
Ok(manager)
}
}

View File

@@ -171,13 +171,13 @@ pub fn sync
)
-> Result<SyncModules, NetworkError>
{
let eth_sync = try!(EthSync::new(Params {
let eth_sync = EthSync::new(Params {
config: sync_cfg,
chain: client,
provider: provider,
snapshot_service: snapshot_service,
network_config: net_cfg,
}));
})?;
Ok((eth_sync.clone() as Arc<SyncProvider>, eth_sync.clone() as Arc<ManageNetwork>, eth_sync.clone() as Arc<ChainNotify>))
}

View File

@@ -71,7 +71,7 @@ impl SpecType {
SpecType::Expanse => Ok(ethereum::new_expanse()),
SpecType::Dev => Ok(Spec::new_instant()),
SpecType::Custom(ref filename) => {
let file = try!(fs::File::open(filename).map_err(|_| "Could not load specification file."));
let file = fs::File::open(filename).map_err(|_| "Could not load specification file.")?;
Spec::load(file)
}
}

View File

@@ -31,15 +31,15 @@ pub struct ImportWallet {
pub fn execute(cmd: ImportWallet) -> Result<String, String> {
let password: String = match cmd.password_file {
Some(file) => try!(password_from_file(file)),
None => try!(password_prompt()),
Some(file) => password_from_file(file)?,
None => password_prompt()?,
};
let dir = Box::new(DiskDirectory::create(cmd.path).unwrap());
let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap());
let acc_provider = AccountProvider::new(secret_store);
let wallet = try!(PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet."));
let kp = try!(wallet.decrypt(&password).map_err(|_| "Invalid password."));
let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?;
let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?;
let address = acc_provider.insert_account(*kp.secret(), &password).unwrap();
Ok(format!("{:?}", address))
}

View File

@@ -89,8 +89,8 @@ pub fn new_http(conf: HttpConfiguration, deps: &Dependencies) -> Result<Option<H
}
let url = format!("{}:{}", conf.interface, conf.port);
let addr = try!(url.parse().map_err(|_| format!("Invalid JSONRPC listen host/port given: {}", url)));
Ok(Some(try!(setup_http_rpc_server(deps, &addr, conf.cors, conf.hosts, conf.apis))))
let addr = url.parse().map_err(|_| format!("Invalid JSONRPC listen host/port given: {}", url))?;
Ok(Some(setup_http_rpc_server(deps, &addr, conf.cors, conf.hosts, conf.apis)?))
}
fn setup_rpc_server(apis: ApiSet, deps: &Dependencies) -> Result<Server, String> {
@@ -105,7 +105,7 @@ pub fn setup_http_rpc_server(
allowed_hosts: Option<Vec<String>>,
apis: ApiSet
) -> Result<HttpServer, String> {
let server = try!(setup_rpc_server(apis, dependencies));
let server = setup_rpc_server(apis, dependencies)?;
let ph = dependencies.panic_handler.clone();
let start_result = server.start_http(url, cors_domains, allowed_hosts, ph);
match start_result {
@@ -120,11 +120,11 @@ pub fn setup_http_rpc_server(
pub fn new_ipc(conf: IpcConfiguration, deps: &Dependencies) -> Result<Option<IpcServer>, String> {
if !conf.enabled { return Ok(None); }
Ok(Some(try!(setup_ipc_rpc_server(deps, &conf.socket_addr, conf.apis))))
Ok(Some(setup_ipc_rpc_server(deps, &conf.socket_addr, conf.apis)?))
}
pub fn setup_ipc_rpc_server(dependencies: &Dependencies, addr: &str, apis: ApiSet) -> Result<IpcServer, String> {
let server = try!(setup_rpc_server(apis, dependencies));
let server = setup_rpc_server(apis, dependencies)?;
match server.start_ipc(addr) {
Err(IpcServerError::Io(io_error)) => Err(format!("RPC io error: {}", io_error)),
Err(any_error) => Err(format!("Rpc error: {:?}", any_error)),

View File

@@ -33,7 +33,7 @@ use ethsync::SyncConfig;
use informant::Informant;
use updater::{UpdatePolicy, Updater};
use parity_reactor::EventLoop;
use hash_fetch::fetch::Client as FetchClient;
use hash_fetch::fetch::{Fetch, Client as FetchClient};
use rpc::{HttpConfiguration, IpcConfiguration};
use params::{
@@ -108,7 +108,7 @@ pub fn open_ui(dapps_conf: &dapps::Configuration, signer_conf: &signer::Configur
return Err("Cannot use UI command with UI turned off.".into())
}
let token = try!(signer::generate_token_and_url(signer_conf));
let token = signer::generate_token_and_url(signer_conf)?;
// Open a browser
url::open(&token.url);
// Print a message
@@ -194,7 +194,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
raise_fd_limit();
// load spec
let spec = try!(cmd.spec.spec());
let spec = cmd.spec.spec()?;
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
@@ -206,19 +206,19 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let mut user_defaults = try!(UserDefaults::load(&user_defaults_path));
let mut user_defaults = UserDefaults::load(&user_defaults_path)?;
// select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(cmd.tracing, &user_defaults));
let tracing = tracing_switch_to_bool(cmd.tracing, &user_defaults)?;
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm));
let fat_db = fatdb_switch_to_bool(cmd.fat_db, &user_defaults, algorithm)?;
// get the mode
let mode = try!(mode_switch_to_bool(cmd.mode, &user_defaults));
let mode = mode_switch_to_bool(cmd.mode, &user_defaults)?;
trace!(target: "mode", "mode is {:?}", mode);
let network_enabled = match mode { Mode::Dark(_) | Mode::Off => false, _ => true, };
@@ -230,14 +230,14 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&cmd.dirs.base, &db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.db_root_path().as_path())));
execute_upgrades(&cmd.dirs.base, &db_dirs, algorithm, cmd.compaction.compaction_profile(db_dirs.db_root_path().as_path()))?;
// create dirs used by parity
try!(cmd.dirs.create_dirs(cmd.dapps_conf.enabled, cmd.signer_conf.enabled));
cmd.dirs.create_dirs(cmd.dapps_conf.enabled, cmd.signer_conf.enabled)?;
// run in daemon mode
if let Some(pid_file) = cmd.daemon {
try!(daemonize(pid_file));
daemonize(pid_file)?;
}
// display info about used pruning algorithm
@@ -275,10 +275,10 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
sync_config.warp_sync = cmd.warp_sync;
sync_config.download_old_blocks = cmd.download_old_blocks;
let passwords = try!(passwords_from_files(&cmd.acc_conf.password_files));
let passwords = passwords_from_files(&cmd.acc_conf.password_files)?;
// prepare account provider
let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, &spec.data_dir, cmd.acc_conf, &passwords)));
let account_provider = Arc::new(prepare_account_provider(&cmd.dirs, &spec.data_dir, cmd.acc_conf, &passwords)?);
// let the Engine access the accounts
spec.engine.register_account_provider(account_provider.clone());
@@ -327,14 +327,14 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path());
// create client service.
let service = try!(ClientService::start(
let service = ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&cmd.dirs.ipc_path(),
miner.clone(),
).map_err(|e| format!("Client service error: {:?}", e)));
).map_err(|e| format!("Client service error: {:?}", e))?;
// drop the spec to free up genesis state.
drop(spec);
@@ -350,7 +350,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let external_miner = Arc::new(ExternalMiner::default());
// create sync object
let (sync_provider, manage_network, chain_notify) = try!(modules::sync(
let (sync_provider, manage_network, chain_notify) = modules::sync(
&mut hypervisor,
sync_config,
net_conf.into(),
@@ -358,7 +358,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
snapshot_service.clone(),
client.clone(),
&cmd.logger_config,
).map_err(|e| format!("Sync error: {}", e)));
).map_err(|e| format!("Sync error: {}", e))?;
service.add_notify(chain_notify.clone());
@@ -371,7 +371,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let event_loop = EventLoop::spawn();
// fetch service
let fetch = try!(FetchClient::new().map_err(|e| format!("Error starting fetch client: {:?}", e)));
let fetch = FetchClient::new().map_err(|e| format!("Error starting fetch client: {:?}", e))?;
// the updater service
let updater = Updater::new(
@@ -420,8 +420,8 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
};
// start rpc servers
let http_server = try!(rpc::new_http(cmd.http_conf, &dependencies));
let ipc_server = try!(rpc::new_ipc(cmd.ipc_conf, &dependencies));
let http_server = rpc::new_http(cmd.http_conf, &dependencies)?;
let ipc_server = rpc::new_ipc(cmd.ipc_conf, &dependencies)?;
// the dapps server
let dapps_deps = dapps::Dependencies {
@@ -431,15 +431,16 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
sync: sync_provider.clone(),
remote: event_loop.remote(),
fetch: fetch.clone(),
signer: deps_for_rpc_apis.signer_service.clone(),
};
let dapps_server = try!(dapps::new(cmd.dapps_conf.clone(), dapps_deps));
let dapps_server = dapps::new(cmd.dapps_conf.clone(), dapps_deps)?;
// the signer server
let signer_deps = signer::Dependencies {
panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.clone(),
};
let signer_server = try!(signer::start(cmd.signer_conf.clone(), signer_deps));
let signer_server = signer::start(cmd.signer_conf.clone(), signer_deps)?;
// the informant
let informant = Arc::new(Informant::new(
@@ -457,7 +458,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
user_defaults.tracing = tracing;
user_defaults.fat_db = fat_db;
user_defaults.mode = mode;
try!(user_defaults.save(&user_defaults_path));
user_defaults.save(&user_defaults_path)?;
// tell client how to save the default mode if it gets changed.
client.on_mode_change(move |mode: &Mode| {
@@ -485,7 +486,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
// start ui
if cmd.ui {
try!(open_ui(&cmd.dapps_conf, &cmd.signer_conf));
open_ui(&cmd.dapps_conf, &cmd.signer_conf)?;
}
// Handle exit
@@ -531,9 +532,9 @@ fn prepare_account_provider(dirs: &Directories, data_dir: &str, cfg: AccountsCon
let path = dirs.keys_path(data_dir);
upgrade_key_location(&dirs.legacy_keys_path(cfg.testnet), &path);
let dir = Box::new(try!(DiskDirectory::create(&path).map_err(|e| format!("Could not open keys directory: {}", e))));
let dir = Box::new(DiskDirectory::create(&path).map_err(|e| format!("Could not open keys directory: {}", e))?);
let account_service = AccountProvider::new(Box::new(
try!(EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e)))
EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e))?
));
for a in cfg.unlocked_accounts {

View File

@@ -65,7 +65,7 @@ pub fn start(conf: Configuration, deps: Dependencies) -> Result<Option<SignerSer
if !conf.enabled {
Ok(None)
} else {
Ok(Some(try!(do_start(conf, deps))))
Ok(Some(do_start(conf, deps)?))
}
}
@@ -77,11 +77,11 @@ fn codes_path(path: String) -> PathBuf {
}
pub fn execute(cmd: Configuration) -> Result<String, String> {
Ok(try!(generate_token_and_url(&cmd)).message)
Ok(generate_token_and_url(&cmd)?.message)
}
pub fn generate_token_and_url(conf: &Configuration) -> Result<NewToken, String> {
let code = try!(generate_new_token(conf.signer_path.clone()).map_err(|err| format!("Error generating token: {:?}", err)));
let code = generate_new_token(conf.signer_path.clone()).map_err(|err| format!("Error generating token: {:?}", err))?;
let auth_url = format!("http://{}:{}/#/auth?token={}", conf.interface, conf.port, code);
// And print in to the console
Ok(NewToken {
@@ -101,18 +101,18 @@ Or use the generated token:
pub fn generate_new_token(path: String) -> io::Result<String> {
let path = codes_path(path);
let mut codes = try!(signer::AuthCodes::from_file(&path));
let mut codes = signer::AuthCodes::from_file(&path)?;
codes.clear_garbage();
let code = try!(codes.generate_new());
try!(codes.to_file(&path));
let code = codes.generate_new()?;
codes.to_file(&path)?;
trace!("New key code created: {}", Colour::White.bold().paint(&code[..]));
Ok(code)
}
fn do_start(conf: Configuration, deps: Dependencies) -> Result<SignerServer, String> {
let addr = try!(format!("{}:{}", conf.interface, conf.port)
let addr = format!("{}:{}", conf.interface, conf.port)
.parse()
.map_err(|_| format!("Invalid port specified: {}", conf.port)));
.map_err(|_| format!("Invalid port specified: {}", conf.port))?;
let start_result = {
let server = signer::ServerBuilder::new(

View File

@@ -72,9 +72,9 @@ fn restore_using<R: SnapshotReader>(snapshot: Arc<SnapshotService>, reader: &R,
info!("Restoring to block #{} (0x{:?})", manifest.block_number, manifest.block_hash);
try!(snapshot.init_restore(manifest.clone(), recover).map_err(|e| {
snapshot.init_restore(manifest.clone(), recover).map_err(|e| {
format!("Failed to begin restoration: {}", e)
}));
})?;
let (num_state, num_blocks) = (manifest.state_hashes.len(), manifest.block_hashes.len());
@@ -93,8 +93,8 @@ fn restore_using<R: SnapshotReader>(snapshot: Arc<SnapshotService>, reader: &R,
return Err("Restoration failed".into());
}
let chunk = try!(reader.chunk(state_hash)
.map_err(|e| format!("Encountered error while reading chunk {:?}: {}", state_hash, e)));
let chunk = reader.chunk(state_hash)
.map_err(|e| format!("Encountered error while reading chunk {:?}: {}", state_hash, e))?;
let hash = chunk.sha3();
if hash != state_hash {
@@ -110,8 +110,8 @@ fn restore_using<R: SnapshotReader>(snapshot: Arc<SnapshotService>, reader: &R,
return Err("Restoration failed".into());
}
let chunk = try!(reader.chunk(block_hash)
.map_err(|e| format!("Encountered error while reading chunk {:?}: {}", block_hash, e)));
let chunk = reader.chunk(block_hash)
.map_err(|e| format!("Encountered error while reading chunk {:?}: {}", block_hash, e))?;
let hash = chunk.sha3();
if hash != block_hash {
@@ -137,7 +137,7 @@ impl SnapshotCommand {
let panic_handler = PanicHandler::new_in_arc();
// load spec file
let spec = try!(self.spec.spec());
let spec = self.spec.spec()?;
// load genesis hash
let genesis_hash = spec.genesis_header().hash();
@@ -149,7 +149,7 @@ impl SnapshotCommand {
let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults
let user_defaults = try!(UserDefaults::load(&user_defaults_path));
let user_defaults = UserDefaults::load(&user_defaults_path)?;
fdlimit::raise_fd_limit();
@@ -157,36 +157,36 @@ impl SnapshotCommand {
let algorithm = self.pruning.to_algorithm(&user_defaults);
// check if tracing is on
let tracing = try!(tracing_switch_to_bool(self.tracing, &user_defaults));
let tracing = tracing_switch_to_bool(self.tracing, &user_defaults)?;
// check if fatdb is on
let fat_db = try!(fatdb_switch_to_bool(self.fat_db, &user_defaults, algorithm));
let fat_db = fatdb_switch_to_bool(self.fat_db, &user_defaults, algorithm)?;
// prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path();
// execute upgrades
try!(execute_upgrades(&self.dirs.base, &db_dirs, algorithm, self.compaction.compaction_profile(db_dirs.db_root_path().as_path())));
execute_upgrades(&self.dirs.base, &db_dirs, algorithm, self.compaction.compaction_profile(db_dirs.db_root_path().as_path()))?;
// prepare client config
let client_config = to_client_config(&self.cache_config, Mode::Active, tracing, fat_db, self.compaction, self.wal, VMType::default(), "".into(), algorithm, self.pruning_history, true);
let service = try!(ClientService::start(
let service = ClientService::start(
client_config,
&spec,
&client_path,
&snapshot_path,
&self.dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec))
).map_err(|e| format!("Client service error: {:?}", e)));
).map_err(|e| format!("Client service error: {:?}", e))?;
Ok((service, panic_handler))
}
/// restore from a snapshot
pub fn restore(self) -> Result<(), String> {
let file = self.file_path.clone();
let (service, _panic_handler) = try!(self.start_service());
let (service, _panic_handler) = self.start_service()?;
warn!("Snapshot restoration is experimental and the format may be subject to change.");
warn!("On encountering an unexpected error, please ensure that you have a recent snapshot.");
@@ -200,15 +200,15 @@ impl SnapshotCommand {
.map_err(|e| format!("Couldn't open snapshot file: {}", e))
.and_then(|x| x.ok_or("Snapshot file has invalid format.".into()));
let reader = try!(reader);
try!(restore_using(snapshot, &reader, true));
let reader = reader?;
restore_using(snapshot, &reader, true)?;
} else {
info!("Attempting to restore from local snapshot.");
// attempting restoration with recovery will lead to deadlock
// as we currently hold a read lock on the service's reader.
match *snapshot.reader() {
Some(ref reader) => try!(restore_using(snapshot.clone(), reader, false)),
Some(ref reader) => restore_using(snapshot.clone(), reader, false)?,
None => return Err("No local snapshot found.".into()),
}
}
@@ -218,15 +218,15 @@ impl SnapshotCommand {
/// Take a snapshot from the head of the chain.
pub fn take_snapshot(self) -> Result<(), String> {
let file_path = try!(self.file_path.clone().ok_or("No file path provided.".to_owned()));
let file_path = self.file_path.clone().ok_or("No file path provided.".to_owned())?;
let file_path: PathBuf = file_path.into();
let block_at = self.block_at;
let (service, _panic_handler) = try!(self.start_service());
let (service, _panic_handler) = self.start_service()?;
warn!("Snapshots are currently experimental. File formats may be subject to change.");
let writer = try!(PackedWriter::new(&file_path)
.map_err(|e| format!("Failed to open snapshot writer: {}", e)));
let writer = PackedWriter::new(&file_path)
.map_err(|e| format!("Failed to open snapshot writer: {}", e))?;
let progress = Arc::new(Progress::default());
let p = progress.clone();
@@ -254,7 +254,7 @@ impl SnapshotCommand {
info!("snapshot creation complete");
assert!(progress.done());
try!(informant_handle.join().map_err(|_| "failed to join logger thread"));
informant_handle.join().map_err(|_| "failed to join logger thread")?;
Ok(())
}
@@ -263,8 +263,8 @@ impl SnapshotCommand {
/// Execute this snapshot command.
pub fn execute(cmd: SnapshotCommand) -> Result<String, String> {
match cmd.kind {
Kind::Take => try!(cmd.take_snapshot()),
Kind::Restore => try!(cmd.restore()),
Kind::Take => cmd.take_snapshot()?,
Kind::Restore => cmd.restore()?,
}
Ok(String::new())

View File

@@ -89,7 +89,7 @@ fn upgrade_from_version(previous_version: &Version) -> Result<usize, Error> {
for upgrade_key in upgrades.keys() {
if upgrade_key.is_applicable(previous_version, &current_version) {
let upgrade_script = upgrades[upgrade_key];
try!(upgrade_script());
upgrade_script()?;
count += 1;
}
}
@@ -104,7 +104,7 @@ fn with_locked_version<F>(db_path: Option<&str>, script: F) -> Result<usize, Err
path.push(".parity");
path
}, PathBuf::from);
try!(create_dir_all(&path).map_err(|_| Error::CannotCreateConfigPath));
create_dir_all(&path).map_err(|_| Error::CannotCreateConfigPath)?;
path.push("ver.lock");
let version =
@@ -117,11 +117,11 @@ fn with_locked_version<F>(db_path: Option<&str>, script: F) -> Result<usize, Err
})
.unwrap_or_else(|| Version::parse("0.9.0").unwrap());
let mut lock = try!(File::create(&path).map_err(|_| Error::CannotWriteVersionFile));
let mut lock = File::create(&path).map_err(|_| Error::CannotWriteVersionFile)?;
let result = script(&version);
let written_version = Version::parse(CURRENT_VERSION).unwrap();
try!(lock.write_all(written_version.to_string().as_bytes()).map_err(|_| Error::CannotUpdateVersionFile));
lock.write_all(written_version.to_string().as_bytes()).map_err(|_| Error::CannotUpdateVersionFile)?;
result
}

View File

@@ -76,25 +76,25 @@ impl Visitor for UserDefaultsVisitor {
fn visit_map<V>(&mut self, visitor: V) -> Result<Self::Value, V::Error>
where V: MapVisitor {
let mut map: BTreeMap<String, Value> = try!(BTreeMapVisitor::new().visit_map(visitor));
let pruning: Value = try!(map.remove("pruning").ok_or_else(|| Error::custom("missing pruning")));
let pruning = try!(pruning.as_str().ok_or_else(|| Error::custom("invalid pruning value")));
let pruning = try!(pruning.parse().map_err(|_| Error::custom("invalid pruning method")));
let tracing: Value = try!(map.remove("tracing").ok_or_else(|| Error::custom("missing tracing")));
let tracing = try!(tracing.as_bool().ok_or_else(|| Error::custom("invalid tracing value")));
let mut map: BTreeMap<String, Value> = BTreeMapVisitor::new().visit_map(visitor)?;
let pruning: Value = map.remove("pruning").ok_or_else(|| Error::custom("missing pruning"))?;
let pruning = pruning.as_str().ok_or_else(|| Error::custom("invalid pruning value"))?;
let pruning = pruning.parse().map_err(|_| Error::custom("invalid pruning method"))?;
let tracing: Value = map.remove("tracing").ok_or_else(|| Error::custom("missing tracing"))?;
let tracing = tracing.as_bool().ok_or_else(|| Error::custom("invalid tracing value"))?;
let fat_db: Value = map.remove("fat_db").unwrap_or_else(|| Value::Bool(false));
let fat_db = try!(fat_db.as_bool().ok_or_else(|| Error::custom("invalid fat_db value")));
let fat_db = fat_db.as_bool().ok_or_else(|| Error::custom("invalid fat_db value"))?;
let mode: Value = map.remove("mode").unwrap_or_else(|| Value::String("active".to_owned()));
let mode = match try!(mode.as_str().ok_or_else(|| Error::custom("invalid mode value"))) {
let mode = match mode.as_str().ok_or_else(|| Error::custom("invalid mode value"))? {
"offline" => Mode::Off,
"dark" => {
let timeout = try!(map.remove("mode.timeout").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.timeout value")));
let timeout = map.remove("mode.timeout").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.timeout value"))?;
Mode::Dark(Duration::from_secs(timeout))
},
"passive" => {
let timeout = try!(map.remove("mode.timeout").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.timeout value")));
let alarm = try!(map.remove("mode.alarm").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.alarm value")));
let timeout = map.remove("mode.timeout").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.timeout value"))?;
let alarm = map.remove("mode.alarm").and_then(|v| v.as_u64()).ok_or_else(|| Error::custom("invalid/missing mode.alarm value"))?;
Mode::Passive(Duration::from_secs(timeout), Duration::from_secs(alarm))
},
"active" => Mode::Active,
@@ -140,7 +140,7 @@ impl UserDefaults {
}
pub fn save<P>(&self, path: P) -> Result<(), String> where P: AsRef<Path> {
let mut file: File = try!(File::create(path).map_err(|_| "Cannot create user defaults file".to_owned()));
let mut file: File = File::create(path).map_err(|_| "Cannot create user defaults file".to_owned())?;
file.write_all(to_string(&self).unwrap().as_bytes()).map_err(|_| "Failed to save user defaults".to_owned())
}
}