Port `try` macro to new `?` operator. (#3962)

* initial untry sweep

* restore try in ipc codegen, fix inference

* change a few missed try instances
This commit is contained in:
Robert Habermeier 2016-12-27 12:53:56 +01:00 committed by Arkadiy Paronyan
parent b1ef52a6d7
commit 8125b5690c
165 changed files with 1696 additions and 1696 deletions

View File

@ -35,30 +35,30 @@ fn write_response_and_check_hash(
response: fetch::Response response: fetch::Response
) -> Result<(fs::File, PathBuf), ValidationError> { ) -> Result<(fs::File, PathBuf), ValidationError> {
// try to parse id // try to parse id
let id = try!(id.parse().map_err(|_| ValidationError::InvalidContentId)); let id = id.parse().map_err(|_| ValidationError::InvalidContentId)?;
// check if content exists // check if content exists
if content_path.exists() { if content_path.exists() {
warn!(target: "dapps", "Overwriting existing content at 0x{:?}", id); warn!(target: "dapps", "Overwriting existing content at 0x{:?}", id);
try!(fs::remove_dir_all(&content_path)) fs::remove_dir_all(&content_path)?
} }
// create directory // create directory
try!(fs::create_dir_all(&content_path)); fs::create_dir_all(&content_path)?;
// append filename // append filename
content_path.push(filename); content_path.push(filename);
// Now write the response // Now write the response
let mut file = io::BufWriter::new(try!(fs::File::create(&content_path))); let mut file = io::BufWriter::new(fs::File::create(&content_path)?);
let mut reader = io::BufReader::new(response); let mut reader = io::BufReader::new(response);
try!(io::copy(&mut reader, &mut file)); io::copy(&mut reader, &mut file)?;
try!(file.flush()); file.flush()?;
// Validate hash // Validate hash
// TODO [ToDr] calculate sha3 in-flight while reading the response // TODO [ToDr] calculate sha3 in-flight while reading the response
let mut file = io::BufReader::new(try!(fs::File::open(&content_path))); let mut file = io::BufReader::new(fs::File::open(&content_path)?);
let hash = try!(sha3(&mut file)); let hash = sha3(&mut file)?;
if id == hash { if id == hash {
Ok((file.into_inner(), content_path)) Ok((file.into_inner(), content_path))
} else { } else {
@ -93,7 +93,7 @@ impl ContentValidator for Content {
fn validate_and_install(&self, response: fetch::Response) -> Result<ValidatorResponse, ValidationError> { fn validate_and_install(&self, response: fetch::Response) -> Result<ValidatorResponse, ValidationError> {
let validate = |content_path: PathBuf| { let validate = |content_path: PathBuf| {
// Create dir // Create dir
let (_, content_path) = try!(write_response_and_check_hash(self.id.as_str(), content_path.clone(), self.id.as_str(), response)); let (_, content_path) = write_response_and_check_hash(self.id.as_str(), content_path.clone(), self.id.as_str(), response)?;
Ok(LocalPageEndpoint::single_file(content_path, self.mime.clone(), PageCache::Enabled)) Ok(LocalPageEndpoint::single_file(content_path, self.mime.clone(), PageCache::Enabled))
}; };
@ -131,7 +131,7 @@ impl Dapp {
fn find_manifest(zip: &mut zip::ZipArchive<fs::File>) -> Result<(Manifest, PathBuf), ValidationError> { fn find_manifest(zip: &mut zip::ZipArchive<fs::File>) -> Result<(Manifest, PathBuf), ValidationError> {
for i in 0..zip.len() { for i in 0..zip.len() {
let mut file = try!(zip.by_index(i)); let mut file = zip.by_index(i)?;
if !file.name().ends_with(MANIFEST_FILENAME) { if !file.name().ends_with(MANIFEST_FILENAME) {
continue; continue;
@ -159,18 +159,18 @@ impl ContentValidator for Dapp {
fn validate_and_install(&self, response: fetch::Response) -> Result<ValidatorResponse, ValidationError> { fn validate_and_install(&self, response: fetch::Response) -> Result<ValidatorResponse, ValidationError> {
let validate = |dapp_path: PathBuf| { let validate = |dapp_path: PathBuf| {
let (file, zip_path) = try!(write_response_and_check_hash(self.id.as_str(), dapp_path.clone(), &format!("{}.zip", self.id), response)); let (file, zip_path) = write_response_and_check_hash(self.id.as_str(), dapp_path.clone(), &format!("{}.zip", self.id), response)?;
trace!(target: "dapps", "Opening dapp bundle at {:?}", zip_path); trace!(target: "dapps", "Opening dapp bundle at {:?}", zip_path);
// Unpack archive // Unpack archive
let mut zip = try!(zip::ZipArchive::new(file)); let mut zip = zip::ZipArchive::new(file)?;
// First find manifest file // First find manifest file
let (mut manifest, manifest_dir) = try!(Self::find_manifest(&mut zip)); let (mut manifest, manifest_dir) = Self::find_manifest(&mut zip)?;
// Overwrite id to match hash // Overwrite id to match hash
manifest.id = self.id.clone(); manifest.id = self.id.clone();
// Unpack zip // Unpack zip
for i in 0..zip.len() { for i in 0..zip.len() {
let mut file = try!(zip.by_index(i)); let mut file = zip.by_index(i)?;
let is_dir = file.name().chars().rev().next() == Some('/'); let is_dir = file.name().chars().rev().next() == Some('/');
let file_path = PathBuf::from(file.name()); let file_path = PathBuf::from(file.name());
@ -180,22 +180,22 @@ impl ContentValidator for Dapp {
let p = dapp_path.join(location_in_manifest_base); let p = dapp_path.join(location_in_manifest_base);
// Check if it's a directory // Check if it's a directory
if is_dir { if is_dir {
try!(fs::create_dir_all(p)); fs::create_dir_all(p)?;
} else { } else {
let mut target = try!(fs::File::create(p)); let mut target = fs::File::create(p)?;
try!(io::copy(&mut file, &mut target)); io::copy(&mut file, &mut target)?;
} }
} }
} }
// Remove zip // Remove zip
try!(fs::remove_file(&zip_path)); fs::remove_file(&zip_path)?;
// Write manifest // Write manifest
let manifest_str = try!(serialize_manifest(&manifest).map_err(ValidationError::ManifestSerialization)); let manifest_str = serialize_manifest(&manifest).map_err(ValidationError::ManifestSerialization)?;
let manifest_path = dapp_path.join(MANIFEST_FILENAME); let manifest_path = dapp_path.join(MANIFEST_FILENAME);
let mut manifest_file = try!(fs::File::create(manifest_path)); let mut manifest_file = fs::File::create(manifest_path)?;
try!(manifest_file.write_all(manifest_str.as_bytes())); manifest_file.write_all(manifest_str.as_bytes())?;
// Create endpoint // Create endpoint
let endpoint = LocalPageEndpoint::new(dapp_path, manifest.clone().into(), PageCache::Enabled, self.embeddable_on.clone()); let endpoint = LocalPageEndpoint::new(dapp_path, manifest.clone().into(), PageCache::Enabled, self.embeddable_on.clone());
Ok(endpoint) Ok(endpoint)

View File

@ -37,8 +37,8 @@ fn local_dapps(dapps_path: String) -> Vec<LocalDapp> {
let files = files.expect("Check is done earlier"); let files = files.expect("Check is done earlier");
files.map(|dir| { files.map(|dir| {
let entry = try!(dir); let entry = dir?;
let file_type = try!(entry.file_type()); let file_type = entry.file_type()?;
// skip files // skip files
if file_type.is_file() { if file_type.is_file() {
@ -79,7 +79,7 @@ fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo {
.and_then(|mut f| { .and_then(|mut f| {
// Reat file // Reat file
let mut s = String::new(); let mut s = String::new();
try!(f.read_to_string(&mut s).map_err(|e| format!("{:?}", e))); f.read_to_string(&mut s).map_err(|e| format!("{:?}", e))?;
// Try to deserialize manifest // Try to deserialize manifest
deserialize_manifest(s) deserialize_manifest(s)
}) })

View File

@ -188,7 +188,7 @@ impl ServerBuilder {
self.sync_status.clone(), self.sync_status.clone(),
self.web_proxy_tokens.clone(), self.web_proxy_tokens.clone(),
self.remote.clone(), self.remote.clone(),
try!(self.fetch()), self.fetch()?,
) )
} }
@ -206,7 +206,7 @@ impl ServerBuilder {
self.sync_status.clone(), self.sync_status.clone(),
self.web_proxy_tokens.clone(), self.web_proxy_tokens.clone(),
self.remote.clone(), self.remote.clone(),
try!(self.fetch()), self.fetch()?,
) )
} }
@ -288,7 +288,7 @@ impl Server {
}); });
let hosts = Self::allowed_hosts(hosts, format!("{}", addr)); let hosts = Self::allowed_hosts(hosts, format!("{}", addr));
try!(hyper::Server::http(addr)) hyper::Server::http(addr)?
.handle(move |ctrl| router::Router::new( .handle(move |ctrl| router::Router::new(
ctrl, ctrl,
signer_address.clone(), signer_address.clone(),

View File

@ -85,9 +85,9 @@ impl Url {
_ => None, _ => None,
}; };
let port = try!(raw_url.port_or_known_default().ok_or_else(|| format!("Unknown port for scheme: `{}`", raw_url.scheme()))); let port = raw_url.port_or_known_default().ok_or_else(|| format!("Unknown port for scheme: `{}`", raw_url.scheme()))?;
let host = try!(raw_url.host().ok_or_else(|| "Valid host, because only data:, mailto: protocols does not have host.".to_owned())).to_owned(); let host = raw_url.host().ok_or_else(|| "Valid host, because only data:, mailto: protocols does not have host.".to_owned())?.to_owned();
let path = try!(raw_url.path_segments().ok_or_else(|| "Valid path segments. In HTTP we won't get cannot-be-a-base URLs".to_owned())) let path = raw_url.path_segments().ok_or_else(|| "Valid path segments. In HTTP we won't get cannot-be-a-base URLs".to_owned())?
.map(|part| part.to_owned()).collect(); .map(|part| part.to_owned()).collect();
let query = raw_url.query().map(|x| x.to_owned()); let query = raw_url.query().map(|x| x.to_owned());

View File

@ -73,10 +73,10 @@ impl WriteCache {
match *cache_entry { match *cache_entry {
WriteCacheEntry::Write(ref val) => { WriteCacheEntry::Write(ref val) => {
try!(batch.put(&key, val)); batch.put(&key, val)?;
}, },
WriteCacheEntry::Remove => { WriteCacheEntry::Remove => {
try!(batch.delete(&key)); batch.delete(&key)?;
}, },
} }
key.clone() key.clone()
@ -87,14 +87,14 @@ impl WriteCache {
removed_so_far = removed_so_far + 1; removed_so_far = removed_so_far + 1;
} }
if removed_so_far > 0 { if removed_so_far > 0 {
try!(db.write(batch)); db.write(batch)?;
} }
Ok(()) Ok(())
} }
/// flushes until cache is empty /// flushes until cache is empty
fn flush_all(&mut self, db: &DB) -> Result<(), Error> { fn flush_all(&mut self, db: &DB) -> Result<(), Error> {
while !self.is_empty() { try!(self.flush(db, FLUSH_BATCH_SIZE)); } while !self.is_empty() { self.flush(db, FLUSH_BATCH_SIZE)?; }
Ok(()) Ok(())
} }
@ -104,7 +104,7 @@ impl WriteCache {
fn try_shrink(&mut self, db: &DB) -> Result<(), Error> { fn try_shrink(&mut self, db: &DB) -> Result<(), Error> {
if self.entries.len() > self.preferred_len { if self.entries.len() > self.preferred_len {
try!(self.flush(db, FLUSH_BATCH_SIZE)); self.flush(db, FLUSH_BATCH_SIZE)?;
} }
Ok(()) Ok(())
} }
@ -135,7 +135,7 @@ impl Database {
if db_lock.is_none() { return Ok(()); } if db_lock.is_none() { return Ok(()); }
let db = db_lock.as_ref().unwrap(); let db = db_lock.as_ref().unwrap();
try!(cache_lock.try_shrink(&db)); cache_lock.try_shrink(&db)?;
Ok(()) Ok(())
} }
@ -145,7 +145,7 @@ impl Database {
if db_lock.is_none() { return Ok(()); } if db_lock.is_none() { return Ok(()); }
let db = db_lock.as_ref().expect("we should have exited with Ok(()) on the previous step"); let db = db_lock.as_ref().expect("we should have exited with Ok(()) on the previous step");
try!(cache_lock.flush_all(&db)); cache_lock.flush_all(&db)?;
Ok(()) Ok(())
} }
@ -174,7 +174,7 @@ impl DatabaseService for Database {
opts.set_block_based_table_factory(&block_opts); opts.set_block_based_table_factory(&block_opts);
opts.set_prefix_extractor_fixed_size(size); opts.set_prefix_extractor_fixed_size(size);
} }
*db = Some(try!(DB::open(&opts, &path))); *db = Some(DB::open(&opts, &path)?);
Ok(()) Ok(())
} }
@ -185,7 +185,7 @@ impl DatabaseService for Database {
} }
fn close(&self) -> Result<(), Error> { fn close(&self) -> Result<(), Error> {
try!(self.flush_all()); self.flush_all()?;
let mut db = self.db.write(); let mut db = self.db.write();
if db.is_none() { return Err(Error::IsClosed); } if db.is_none() { return Err(Error::IsClosed); }
@ -231,9 +231,9 @@ impl DatabaseService for Database {
} }
} }
let db_lock = self.db.read(); let db_lock = self.db.read();
let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let db = db_lock.as_ref().ok_or(Error::IsClosed)?;
match try!(db.get(key)) { match db.get(key)? {
Some(db_vec) => { Some(db_vec) => {
Ok(Some(db_vec.to_vec())) Ok(Some(db_vec.to_vec()))
}, },
@ -243,7 +243,7 @@ impl DatabaseService for Database {
fn get_by_prefix(&self, prefix: &[u8]) -> Result<Option<Vec<u8>>, Error> { fn get_by_prefix(&self, prefix: &[u8]) -> Result<Option<Vec<u8>>, Error> {
let db_lock = self.db.read(); let db_lock = self.db.read();
let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let db = db_lock.as_ref().ok_or(Error::IsClosed)?;
let mut iter = db.iterator(IteratorMode::From(prefix, Direction::Forward)); let mut iter = db.iterator(IteratorMode::From(prefix, Direction::Forward));
match iter.next() { match iter.next() {
@ -255,14 +255,14 @@ impl DatabaseService for Database {
fn is_empty(&self) -> Result<bool, Error> { fn is_empty(&self) -> Result<bool, Error> {
let db_lock = self.db.read(); let db_lock = self.db.read();
let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let db = db_lock.as_ref().ok_or(Error::IsClosed)?;
Ok(db.iterator(IteratorMode::Start).next().is_none()) Ok(db.iterator(IteratorMode::Start).next().is_none())
} }
fn iter(&self) -> Result<IteratorHandle, Error> { fn iter(&self) -> Result<IteratorHandle, Error> {
let db_lock = self.db.read(); let db_lock = self.db.read();
let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let db = db_lock.as_ref().ok_or(Error::IsClosed)?;
let mut iterators = self.iterators.write(); let mut iterators = self.iterators.write();
let next_iterator = iterators.keys().last().unwrap_or(&0) + 1; let next_iterator = iterators.keys().last().unwrap_or(&0) + 1;

View File

@ -52,27 +52,27 @@ impl std::convert::From<nanoipc::SocketError> for ServiceError {
pub fn blocks_service_url(db_path: &str) -> Result<String, std::io::Error> { pub fn blocks_service_url(db_path: &str) -> Result<String, std::io::Error> {
let mut path = PathBuf::from(db_path); let mut path = PathBuf::from(db_path);
try!(::std::fs::create_dir_all(db_path)); ::std::fs::create_dir_all(db_path)?;
path.push("blocks.ipc"); path.push("blocks.ipc");
Ok(format!("ipc://{}", path.to_str().unwrap())) Ok(format!("ipc://{}", path.to_str().unwrap()))
} }
pub fn extras_service_url(db_path: &str) -> Result<String, ::std::io::Error> { pub fn extras_service_url(db_path: &str) -> Result<String, ::std::io::Error> {
let mut path = PathBuf::from(db_path); let mut path = PathBuf::from(db_path);
try!(::std::fs::create_dir_all(db_path)); ::std::fs::create_dir_all(db_path)?;
path.push("extras.ipc"); path.push("extras.ipc");
Ok(format!("ipc://{}", path.to_str().unwrap())) Ok(format!("ipc://{}", path.to_str().unwrap()))
} }
pub fn blocks_client(db_path: &str) -> Result<DatabaseConnection, ServiceError> { pub fn blocks_client(db_path: &str) -> Result<DatabaseConnection, ServiceError> {
let url = try!(blocks_service_url(db_path)); let url = blocks_service_url(db_path)?;
let client = try!(nanoipc::generic_client::<DatabaseClient<_>>(&url)); let client = nanoipc::generic_client::<DatabaseClient<_>>(&url)?;
Ok(client) Ok(client)
} }
pub fn extras_client(db_path: &str) -> Result<DatabaseConnection, ServiceError> { pub fn extras_client(db_path: &str) -> Result<DatabaseConnection, ServiceError> {
let url = try!(extras_service_url(db_path)); let url = extras_service_url(db_path)?;
let client = try!(nanoipc::generic_client::<DatabaseClient<_>>(&url)); let client = nanoipc::generic_client::<DatabaseClient<_>>(&url)?;
Ok(client) Ok(client)
} }

View File

@ -116,17 +116,17 @@ impl Light {
pub fn from_file(block_number: u64) -> io::Result<Light> { pub fn from_file(block_number: u64) -> io::Result<Light> {
let seed_compute = SeedHashCompute::new(); let seed_compute = SeedHashCompute::new();
let path = Light::file_path(seed_compute.get_seedhash(block_number)); let path = Light::file_path(seed_compute.get_seedhash(block_number));
let mut file = try!(File::open(path)); let mut file = File::open(path)?;
let cache_size = get_cache_size(block_number); let cache_size = get_cache_size(block_number);
if try!(file.metadata()).len() != cache_size as u64 { if file.metadata()?.len() != cache_size as u64 {
return Err(io::Error::new(io::ErrorKind::Other, "Cache file size mismatch")); return Err(io::Error::new(io::ErrorKind::Other, "Cache file size mismatch"));
} }
let num_nodes = cache_size / NODE_BYTES; let num_nodes = cache_size / NODE_BYTES;
let mut nodes: Vec<Node> = Vec::new(); let mut nodes: Vec<Node> = Vec::new();
nodes.resize(num_nodes, unsafe { mem::uninitialized() }); nodes.resize(num_nodes, unsafe { mem::uninitialized() });
let buf = unsafe { slice::from_raw_parts_mut(nodes.as_mut_ptr() as *mut u8, cache_size) }; let buf = unsafe { slice::from_raw_parts_mut(nodes.as_mut_ptr() as *mut u8, cache_size) };
try!(file.read_exact(buf)); file.read_exact(buf)?;
Ok(Light { Ok(Light {
cache: nodes, cache: nodes,
block_number: block_number, block_number: block_number,
@ -144,16 +144,16 @@ impl Light {
if deprecated.exists() { if deprecated.exists() {
debug!(target: "ethash", "removing: {:?}", &deprecated); debug!(target: "ethash", "removing: {:?}", &deprecated);
try!(fs::remove_file(deprecated)); fs::remove_file(deprecated)?;
} }
} }
try!(fs::create_dir_all(path.parent().unwrap())); fs::create_dir_all(path.parent().unwrap())?;
let mut file = try!(File::create(&path)); let mut file = File::create(&path)?;
let cache_size = self.cache.len() * NODE_BYTES; let cache_size = self.cache.len() * NODE_BYTES;
let buf = unsafe { slice::from_raw_parts(self.cache.as_ptr() as *const u8, cache_size) }; let buf = unsafe { slice::from_raw_parts(self.cache.as_ptr() as *const u8, cache_size) };
try!(file.write(buf)); file.write(buf)?;
Ok(path) Ok(path)
} }
} }

View File

@ -135,10 +135,10 @@ impl RlpDecodable for CostTable {
let mut header_proofs = None; let mut header_proofs = None;
for row in rlp.iter() { for row in rlp.iter() {
let msg_id: u8 = try!(row.val_at(0)); let msg_id: u8 = row.val_at(0)?;
let cost = { let cost = {
let base = try!(row.val_at(1)); let base = row.val_at(1)?;
let per = try!(row.val_at(2)); let per = row.val_at(2)?;
Cost(base, per) Cost(base, per)
}; };
@ -155,12 +155,12 @@ impl RlpDecodable for CostTable {
} }
Ok(CostTable { Ok(CostTable {
headers: try!(headers.ok_or(DecoderError::Custom("No headers cost specified"))), headers: headers.ok_or(DecoderError::Custom("No headers cost specified"))?,
bodies: try!(bodies.ok_or(DecoderError::Custom("No bodies cost specified"))), bodies: bodies.ok_or(DecoderError::Custom("No bodies cost specified"))?,
receipts: try!(receipts.ok_or(DecoderError::Custom("No receipts cost specified"))), receipts: receipts.ok_or(DecoderError::Custom("No receipts cost specified"))?,
state_proofs: try!(state_proofs.ok_or(DecoderError::Custom("No proofs cost specified"))), state_proofs: state_proofs.ok_or(DecoderError::Custom("No proofs cost specified"))?,
contract_codes: try!(contract_codes.ok_or(DecoderError::Custom("No contract codes specified"))), contract_codes: contract_codes.ok_or(DecoderError::Custom("No contract codes specified"))?,
header_proofs: try!(header_proofs.ok_or(DecoderError::Custom("No header proofs cost specified"))), header_proofs: header_proofs.ok_or(DecoderError::Custom("No header proofs cost specified"))?,
}) })
} }
} }

View File

@ -143,7 +143,7 @@ impl Peer {
flow_params.recharge(&mut self.local_buffer); flow_params.recharge(&mut self.local_buffer);
let max_cost = flow_params.compute_cost(kind, max); let max_cost = flow_params.compute_cost(kind, max);
try!(self.local_buffer.deduct_cost(max_cost)); self.local_buffer.deduct_cost(max_cost)?;
Ok(max_cost) Ok(max_cost)
} }
@ -275,14 +275,14 @@ impl LightProtocol {
/// with an event. /// with an event.
pub fn request_from(&self, io: &IoContext, peer_id: &PeerId, request: Request) -> Result<ReqId, Error> { pub fn request_from(&self, io: &IoContext, peer_id: &PeerId, request: Request) -> Result<ReqId, Error> {
let peers = self.peers.read(); let peers = self.peers.read();
let peer = try!(peers.get(peer_id).ok_or_else(|| Error::UnknownPeer)); let peer = peers.get(peer_id).ok_or_else(|| Error::UnknownPeer)?;
let mut peer = peer.lock(); let mut peer = peer.lock();
match peer.remote_flow.as_mut() { match peer.remote_flow.as_mut() {
Some(&mut (ref mut buf, ref flow)) => { Some(&mut (ref mut buf, ref flow)) => {
flow.recharge(buf); flow.recharge(buf);
let max = flow.compute_cost(request.kind(), request.amount()); let max = flow.compute_cost(request.kind(), request.amount());
try!(buf.deduct_cost(max)); buf.deduct_cost(max)?;
} }
None => return Err(Error::NotServer), None => return Err(Error::NotServer),
} }
@ -386,8 +386,8 @@ impl LightProtocol {
// - check whether request was made // - check whether request was made
// - check whether request kinds match // - check whether request kinds match
fn pre_verify_response(&self, peer: &PeerId, kind: request::Kind, raw: &UntrustedRlp) -> Result<ReqId, Error> { fn pre_verify_response(&self, peer: &PeerId, kind: request::Kind, raw: &UntrustedRlp) -> Result<ReqId, Error> {
let req_id: usize = try!(raw.val_at(0)); let req_id: usize = raw.val_at(0)?;
let cur_buffer: U256 = try!(raw.val_at(1)); let cur_buffer: U256 = raw.val_at(1)?;
trace!(target: "les", "pre-verifying response from peer {}, kind={:?}", peer, kind); trace!(target: "les", "pre-verifying response from peer {}, kind={:?}", peer, kind);
@ -582,7 +582,7 @@ impl LightProtocol {
} }
}; };
let (status, capabilities, flow_params) = try!(status::parse_handshake(data)); let (status, capabilities, flow_params) = status::parse_handshake(data)?;
trace!(target: "les", "Connected peer with chain head {:?}", (status.head_hash, status.head_num)); trace!(target: "les", "Connected peer with chain head {:?}", (status.head_hash, status.head_num));
@ -623,7 +623,7 @@ impl LightProtocol {
return Ok(()) return Ok(())
} }
let announcement = try!(status::parse_announcement(data)); let announcement = status::parse_announcement(data)?;
// scope to ensure locks are dropped before moving into handler-space. // scope to ensure locks are dropped before moving into handler-space.
{ {
@ -676,25 +676,25 @@ impl LightProtocol {
let mut peer = peer.lock(); let mut peer = peer.lock();
let req_id: u64 = try!(data.val_at(0)); let req_id: u64 = data.val_at(0)?;
let data = try!(data.at(1)); let data = data.at(1)?;
let start_block = { let start_block = {
if try!(data.at(0)).size() == 32 { if data.at(0)?.size() == 32 {
HashOrNumber::Hash(try!(data.val_at(0))) HashOrNumber::Hash(data.val_at(0)?)
} else { } else {
HashOrNumber::Number(try!(data.val_at(0))) HashOrNumber::Number(data.val_at(0)?)
} }
}; };
let req = request::Headers { let req = request::Headers {
start: start_block, start: start_block,
max: ::std::cmp::min(MAX_HEADERS, try!(data.val_at(1))), max: ::std::cmp::min(MAX_HEADERS, data.val_at(1)?),
skip: try!(data.val_at(2)), skip: data.val_at(2)?,
reverse: try!(data.val_at(3)), reverse: data.val_at(3)?,
}; };
let max_cost = try!(peer.deduct_max(&self.flow_params, request::Kind::Headers, req.max)); let max_cost = peer.deduct_max(&self.flow_params, request::Kind::Headers, req.max)?;
let response = self.provider.block_headers(req); let response = self.provider.block_headers(req);
let actual_cost = self.flow_params.compute_cost(request::Kind::Headers, response.len()); let actual_cost = self.flow_params.compute_cost(request::Kind::Headers, response.len());
@ -717,8 +717,8 @@ impl LightProtocol {
// Receive a response for block headers. // Receive a response for block headers.
fn block_headers(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> { fn block_headers(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> {
let req_id = try!(self.pre_verify_response(peer, request::Kind::Headers, &raw)); let req_id = self.pre_verify_response(peer, request::Kind::Headers, &raw)?;
let raw_headers: Vec<_> = try!(raw.at(2)).iter().map(|x| x.as_raw().to_owned()).collect(); let raw_headers: Vec<_> = raw.at(2)?.iter().map(|x| x.as_raw().to_owned()).collect();
for handler in &self.handlers { for handler in &self.handlers {
handler.on_block_headers(&Ctx { handler.on_block_headers(&Ctx {
@ -745,13 +745,16 @@ impl LightProtocol {
}; };
let mut peer = peer.lock(); let mut peer = peer.lock();
let req_id: u64 = try!(data.val_at(0)); let req_id: u64 = data.val_at(0)?;
let req = request::Bodies { let req = request::Bodies {
block_hashes: try!(try!(data.at(1)).iter().take(MAX_BODIES).map(|x| x.as_val()).collect()) block_hashes: data.at(1)?.iter()
.take(MAX_BODIES)
.map(|x| x.as_val())
.collect::<Result<_, _>>()?
}; };
let max_cost = try!(peer.deduct_max(&self.flow_params, request::Kind::Bodies, req.block_hashes.len())); let max_cost = peer.deduct_max(&self.flow_params, request::Kind::Bodies, req.block_hashes.len())?;
let response = self.provider.block_bodies(req); let response = self.provider.block_bodies(req);
let response_len = response.iter().filter(|x| &x[..] != &::rlp::EMPTY_LIST_RLP).count(); let response_len = response.iter().filter(|x| &x[..] != &::rlp::EMPTY_LIST_RLP).count();
@ -776,8 +779,8 @@ impl LightProtocol {
// Receive a response for block bodies. // Receive a response for block bodies.
fn block_bodies(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> { fn block_bodies(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> {
let req_id = try!(self.pre_verify_response(peer, request::Kind::Bodies, &raw)); let req_id = self.pre_verify_response(peer, request::Kind::Bodies, &raw)?;
let raw_bodies: Vec<Bytes> = try!(raw.at(2)).iter().map(|x| x.as_raw().to_owned()).collect(); let raw_bodies: Vec<Bytes> = raw.at(2)?.iter().map(|x| x.as_raw().to_owned()).collect();
for handler in &self.handlers { for handler in &self.handlers {
handler.on_block_bodies(&Ctx { handler.on_block_bodies(&Ctx {
@ -804,13 +807,16 @@ impl LightProtocol {
}; };
let mut peer = peer.lock(); let mut peer = peer.lock();
let req_id: u64 = try!(data.val_at(0)); let req_id: u64 = data.val_at(0)?;
let req = request::Receipts { let req = request::Receipts {
block_hashes: try!(try!(data.at(1)).iter().take(MAX_RECEIPTS).map(|x| x.as_val()).collect()) block_hashes: data.at(1)?.iter()
.take(MAX_RECEIPTS)
.map(|x| x.as_val())
.collect::<Result<_,_>>()?
}; };
let max_cost = try!(peer.deduct_max(&self.flow_params, request::Kind::Receipts, req.block_hashes.len())); let max_cost = peer.deduct_max(&self.flow_params, request::Kind::Receipts, req.block_hashes.len())?;
let response = self.provider.receipts(req); let response = self.provider.receipts(req);
let response_len = response.iter().filter(|x| &x[..] != &::rlp::EMPTY_LIST_RLP).count(); let response_len = response.iter().filter(|x| &x[..] != &::rlp::EMPTY_LIST_RLP).count();
@ -835,11 +841,11 @@ impl LightProtocol {
// Receive a response for receipts. // Receive a response for receipts.
fn receipts(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> { fn receipts(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> {
let req_id = try!(self.pre_verify_response(peer, request::Kind::Receipts, &raw)); let req_id = self.pre_verify_response(peer, request::Kind::Receipts, &raw)?;
let raw_receipts: Vec<Vec<Receipt>> = try!(try!(raw.at(2)) let raw_receipts: Vec<Vec<Receipt>> = raw.at(2)?
.iter() .iter()
.map(|x| x.as_val()) .map(|x| x.as_val())
.collect()); .collect::<Result<_,_>>()?;
for handler in &self.handlers { for handler in &self.handlers {
handler.on_receipts(&Ctx { handler.on_receipts(&Ctx {
@ -866,24 +872,24 @@ impl LightProtocol {
}; };
let mut peer = peer.lock(); let mut peer = peer.lock();
let req_id: u64 = try!(data.val_at(0)); let req_id: u64 = data.val_at(0)?;
let req = { let req = {
let requests: Result<Vec<_>, Error> = try!(data.at(1)).iter().take(MAX_PROOFS).map(|x| { let requests: Result<Vec<_>, Error> = data.at(1)?.iter().take(MAX_PROOFS).map(|x| {
Ok(request::StateProof { Ok(request::StateProof {
block: try!(x.val_at(0)), block: x.val_at(0)?,
key1: try!(x.val_at(1)), key1: x.val_at(1)?,
key2: if try!(x.at(2)).is_empty() { None } else { Some(try!(x.val_at(2))) }, key2: if x.at(2)?.is_empty() { None } else { Some(x.val_at(2)?) },
from_level: try!(x.val_at(3)), from_level: x.val_at(3)?,
}) })
}).collect(); }).collect();
request::StateProofs { request::StateProofs {
requests: try!(requests), requests: requests?,
} }
}; };
let max_cost = try!(peer.deduct_max(&self.flow_params, request::Kind::StateProofs, req.requests.len())); let max_cost = peer.deduct_max(&self.flow_params, request::Kind::StateProofs, req.requests.len())?;
let response = self.provider.proofs(req); let response = self.provider.proofs(req);
let response_len = response.iter().filter(|x| &x[..] != &::rlp::EMPTY_LIST_RLP).count(); let response_len = response.iter().filter(|x| &x[..] != &::rlp::EMPTY_LIST_RLP).count();
@ -908,9 +914,9 @@ impl LightProtocol {
// Receive a response for proofs. // Receive a response for proofs.
fn proofs(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> { fn proofs(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> {
let req_id = try!(self.pre_verify_response(peer, request::Kind::StateProofs, &raw)); let req_id = self.pre_verify_response(peer, request::Kind::StateProofs, &raw)?;
let raw_proofs: Vec<Vec<Bytes>> = try!(raw.at(2)).iter() let raw_proofs: Vec<Vec<Bytes>> = raw.at(2)?.iter()
.map(|x| x.iter().map(|node| node.as_raw().to_owned()).collect()) .map(|x| x.iter().map(|node| node.as_raw().to_owned()).collect())
.collect(); .collect();
@ -939,22 +945,22 @@ impl LightProtocol {
}; };
let mut peer = peer.lock(); let mut peer = peer.lock();
let req_id: u64 = try!(data.val_at(0)); let req_id: u64 = data.val_at(0)?;
let req = { let req = {
let requests: Result<Vec<_>, Error> = try!(data.at(1)).iter().take(MAX_CODES).map(|x| { let requests: Result<Vec<_>, Error> = data.at(1)?.iter().take(MAX_CODES).map(|x| {
Ok(request::ContractCode { Ok(request::ContractCode {
block_hash: try!(x.val_at(0)), block_hash: x.val_at(0)?,
account_key: try!(x.val_at(1)), account_key: x.val_at(1)?,
}) })
}).collect(); }).collect();
request::ContractCodes { request::ContractCodes {
code_requests: try!(requests), code_requests: requests?,
} }
}; };
let max_cost = try!(peer.deduct_max(&self.flow_params, request::Kind::Codes, req.code_requests.len())); let max_cost = peer.deduct_max(&self.flow_params, request::Kind::Codes, req.code_requests.len())?;
let response = self.provider.contract_codes(req); let response = self.provider.contract_codes(req);
let response_len = response.iter().filter(|x| !x.is_empty()).count(); let response_len = response.iter().filter(|x| !x.is_empty()).count();
@ -979,9 +985,11 @@ impl LightProtocol {
// Receive a response for contract code. // Receive a response for contract code.
fn contract_code(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> { fn contract_code(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> {
let req_id = try!(self.pre_verify_response(peer, request::Kind::Codes, &raw)); let req_id = self.pre_verify_response(peer, request::Kind::Codes, &raw)?;
let raw_code: Vec<Bytes> = try!(try!(raw.at(2)).iter().map(|x| x.as_val()).collect()); let raw_code: Vec<Bytes> = raw.at(2)?.iter()
.map(|x| x.as_val())
.collect::<Result<_,_>>()?;
for handler in &self.handlers { for handler in &self.handlers {
handler.on_code(&Ctx { handler.on_code(&Ctx {
@ -1008,23 +1016,23 @@ impl LightProtocol {
}; };
let mut peer = peer.lock(); let mut peer = peer.lock();
let req_id: u64 = try!(data.val_at(0)); let req_id: u64 = data.val_at(0)?;
let req = { let req = {
let requests: Result<Vec<_>, Error> = try!(data.at(1)).iter().take(MAX_PROOFS).map(|x| { let requests: Result<Vec<_>, Error> = data.at(1)?.iter().take(MAX_PROOFS).map(|x| {
Ok(request::HeaderProof { Ok(request::HeaderProof {
cht_number: try!(x.val_at(0)), cht_number: x.val_at(0)?,
block_number: try!(x.val_at(1)), block_number: x.val_at(1)?,
from_level: try!(x.val_at(2)), from_level: x.val_at(2)?,
}) })
}).collect(); }).collect();
request::HeaderProofs { request::HeaderProofs {
requests: try!(requests), requests: requests?,
} }
}; };
let max_cost = try!(peer.deduct_max(&self.flow_params, request::Kind::HeaderProofs, req.requests.len())); let max_cost = peer.deduct_max(&self.flow_params, request::Kind::HeaderProofs, req.requests.len())?;
let response = self.provider.header_proofs(req); let response = self.provider.header_proofs(req);
let response_len = response.iter().filter(|x| &x[..] != ::rlp::EMPTY_LIST_RLP).count(); let response_len = response.iter().filter(|x| &x[..] != ::rlp::EMPTY_LIST_RLP).count();
@ -1051,13 +1059,15 @@ impl LightProtocol {
fn header_proofs(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> { fn header_proofs(&self, peer: &PeerId, io: &IoContext, raw: UntrustedRlp) -> Result<(), Error> {
fn decode_res(raw: UntrustedRlp) -> Result<(Bytes, Vec<Bytes>), ::rlp::DecoderError> { fn decode_res(raw: UntrustedRlp) -> Result<(Bytes, Vec<Bytes>), ::rlp::DecoderError> {
Ok(( Ok((
try!(raw.val_at(0)), raw.val_at(0)?,
try!(raw.at(1)).iter().map(|x| x.as_raw().to_owned()).collect(), raw.at(1)?.iter().map(|x| x.as_raw().to_owned()).collect(),
)) ))
} }
let req_id = try!(self.pre_verify_response(peer, request::Kind::HeaderProofs, &raw)); let req_id = self.pre_verify_response(peer, request::Kind::HeaderProofs, &raw)?;
let raw_proofs: Vec<_> = try!(try!(raw.at(2)).iter().map(decode_res).collect()); let raw_proofs: Vec<_> = raw.at(2)?.iter()
.map(decode_res)
.collect::<Result<_,_>>()?;
for handler in &self.handlers { for handler in &self.handlers {
handler.on_header_proofs(&Ctx { handler.on_header_proofs(&Ctx {
@ -1074,7 +1084,10 @@ impl LightProtocol {
fn relay_transactions(&self, peer: &PeerId, io: &IoContext, data: UntrustedRlp) -> Result<(), Error> { fn relay_transactions(&self, peer: &PeerId, io: &IoContext, data: UntrustedRlp) -> Result<(), Error> {
const MAX_TRANSACTIONS: usize = 256; const MAX_TRANSACTIONS: usize = 256;
let txs: Vec<_> = try!(data.iter().take(MAX_TRANSACTIONS).map(|x| x.as_val::<SignedTransaction>()).collect()); let txs: Vec<_> = data.iter()
.take(MAX_TRANSACTIONS)
.map(|x| x.as_val::<SignedTransaction>())
.collect::<Result<_,_>>()?;
debug!(target: "les", "Received {} transactions to relay from peer {}", txs.len(), peer); debug!(target: "les", "Received {} transactions to relay from peer {}", txs.len(), peer);

View File

@ -100,7 +100,7 @@ impl<'a> Parser<'a> {
fn expect_raw(&mut self, key: Key) -> Result<UntrustedRlp<'a>, DecoderError> { fn expect_raw(&mut self, key: Key) -> Result<UntrustedRlp<'a>, DecoderError> {
trace!(target: "les", "Expecting key {}", key.as_str()); trace!(target: "les", "Expecting key {}", key.as_str());
let pre_pos = self.pos; let pre_pos = self.pos;
if let Some((k, val)) = try!(self.get_next()) { if let Some((k, val)) = self.get_next()? {
if k == key { return Ok(val) } if k == key { return Ok(val) }
} }
@ -111,12 +111,12 @@ impl<'a> Parser<'a> {
// get the next key and value RLP. // get the next key and value RLP.
fn get_next(&mut self) -> Result<Option<(Key, UntrustedRlp<'a>)>, DecoderError> { fn get_next(&mut self) -> Result<Option<(Key, UntrustedRlp<'a>)>, DecoderError> {
while self.pos < self.rlp.item_count() { while self.pos < self.rlp.item_count() {
let pair = try!(self.rlp.at(self.pos)); let pair = self.rlp.at(self.pos)?;
let k: String = try!(pair.val_at(0)); let k: String = pair.val_at(0)?;
self.pos += 1; self.pos += 1;
match Key::from_str(&k) { match Key::from_str(&k) {
Some(key) => return Ok(Some((key , try!(pair.at(1))))), Some(key) => return Ok(Some((key , pair.at(1)?))),
None => continue, None => continue,
} }
} }
@ -205,12 +205,12 @@ pub fn parse_handshake(rlp: UntrustedRlp) -> Result<(Status, Capabilities, Optio
}; };
let status = Status { let status = Status {
protocol_version: try!(parser.expect(Key::ProtocolVersion)), protocol_version: parser.expect(Key::ProtocolVersion)?,
network_id: try!(parser.expect(Key::NetworkId)), network_id: parser.expect(Key::NetworkId)?,
head_td: try!(parser.expect(Key::HeadTD)), head_td: parser.expect(Key::HeadTD)?,
head_hash: try!(parser.expect(Key::HeadHash)), head_hash: parser.expect(Key::HeadHash)?,
head_num: try!(parser.expect(Key::HeadNum)), head_num: parser.expect(Key::HeadNum)?,
genesis_hash: try!(parser.expect(Key::GenesisHash)), genesis_hash: parser.expect(Key::GenesisHash)?,
last_head: None, last_head: None,
}; };
@ -298,10 +298,10 @@ pub fn parse_announcement(rlp: UntrustedRlp) -> Result<Announcement, DecoderErro
let mut last_key = None; let mut last_key = None;
let mut announcement = Announcement { let mut announcement = Announcement {
head_hash: try!(rlp.val_at(0)), head_hash: rlp.val_at(0)?,
head_num: try!(rlp.val_at(1)), head_num: rlp.val_at(1)?,
head_td: try!(rlp.val_at(2)), head_td: rlp.val_at(2)?,
reorg_depth: try!(rlp.val_at(3)), reorg_depth: rlp.val_at(3)?,
serve_headers: false, serve_headers: false,
serve_state_since: None, serve_state_since: None,
serve_chain_since: None, serve_chain_since: None,
@ -313,14 +313,14 @@ pub fn parse_announcement(rlp: UntrustedRlp) -> Result<Announcement, DecoderErro
rlp: rlp, rlp: rlp,
}; };
while let Some((key, item)) = try!(parser.get_next()) { while let Some((key, item)) = parser.get_next()? {
if Some(key) <= last_key { return Err(DecoderError::Custom("Invalid announcement key ordering")) } if Some(key) <= last_key { return Err(DecoderError::Custom("Invalid announcement key ordering")) }
last_key = Some(key); last_key = Some(key);
match key { match key {
Key::ServeHeaders => announcement.serve_headers = true, Key::ServeHeaders => announcement.serve_headers = true,
Key::ServeStateSince => announcement.serve_state_since = Some(try!(item.as_val())), Key::ServeStateSince => announcement.serve_state_since = Some(item.as_val()?),
Key::ServeChainSince => announcement.serve_chain_since = Some(try!(item.as_val())), Key::ServeChainSince => announcement.serve_chain_since = Some(item.as_val()?),
Key::TxRelay => announcement.tx_relay = true, Key::TxRelay => announcement.tx_relay = true,
_ => return Err(DecoderError::Custom("Nonsensical key in announcement")), _ => return Err(DecoderError::Custom("Nonsensical key in announcement")),
} }

View File

@ -127,32 +127,32 @@ impl AccountProvider {
let acc = Random.generate().expect("secp context has generation capabilities; qed"); let acc = Random.generate().expect("secp context has generation capabilities; qed");
let public = acc.public().clone(); let public = acc.public().clone();
let secret = acc.secret().clone(); let secret = acc.secret().clone();
let address = try!(self.sstore.insert_account(secret, password)); let address = self.sstore.insert_account(secret, password)?;
Ok((address, public)) Ok((address, public))
} }
/// Inserts new account into underlying store. /// Inserts new account into underlying store.
/// Does not unlock account! /// Does not unlock account!
pub fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { pub fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> {
let address = try!(self.sstore.insert_account(secret, password)); let address = self.sstore.insert_account(secret, password)?;
Ok(address) Ok(address)
} }
/// Import a new presale wallet. /// Import a new presale wallet.
pub fn import_presale(&self, presale_json: &[u8], password: &str) -> Result<Address, Error> { pub fn import_presale(&self, presale_json: &[u8], password: &str) -> Result<Address, Error> {
let address = try!(self.sstore.import_presale(presale_json, password)); let address = self.sstore.import_presale(presale_json, password)?;
Ok(Address::from(address).into()) Ok(Address::from(address).into())
} }
/// Import a new presale wallet. /// Import a new presale wallet.
pub fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> { pub fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> {
let address = try!(self.sstore.import_wallet(json, password)); let address = self.sstore.import_wallet(json, password)?;
Ok(Address::from(address).into()) Ok(Address::from(address).into())
} }
/// Returns addresses of all accounts. /// Returns addresses of all accounts.
pub fn accounts(&self) -> Result<Vec<Address>, Error> { pub fn accounts(&self) -> Result<Vec<Address>, Error> {
let accounts = try!(self.sstore.accounts()); let accounts = self.sstore.accounts()?;
Ok(accounts) Ok(accounts)
} }
@ -229,7 +229,7 @@ impl AccountProvider {
/// Returns each account along with name and meta. /// Returns each account along with name and meta.
pub fn accounts_info(&self) -> Result<HashMap<Address, AccountMeta>, Error> { pub fn accounts_info(&self) -> Result<HashMap<Address, AccountMeta>, Error> {
let r: HashMap<Address, AccountMeta> = try!(self.sstore.accounts()) let r: HashMap<Address, AccountMeta> = self.sstore.accounts()?
.into_iter() .into_iter()
.map(|a| (a.clone(), self.account_meta(a).ok().unwrap_or_default())) .map(|a| (a.clone(), self.account_meta(a).ok().unwrap_or_default()))
.collect(); .collect();
@ -239,21 +239,21 @@ impl AccountProvider {
/// Returns each account along with name and meta. /// Returns each account along with name and meta.
pub fn account_meta(&self, account: Address) -> Result<AccountMeta, Error> { pub fn account_meta(&self, account: Address) -> Result<AccountMeta, Error> {
Ok(AccountMeta { Ok(AccountMeta {
name: try!(self.sstore.name(&account)), name: self.sstore.name(&account)?,
meta: try!(self.sstore.meta(&account)), meta: self.sstore.meta(&account)?,
uuid: self.sstore.uuid(&account).ok().map(Into::into), // allowed to not have a Uuid uuid: self.sstore.uuid(&account).ok().map(Into::into), // allowed to not have a Uuid
}) })
} }
/// Returns each account along with name and meta. /// Returns each account along with name and meta.
pub fn set_account_name(&self, account: Address, name: String) -> Result<(), Error> { pub fn set_account_name(&self, account: Address, name: String) -> Result<(), Error> {
try!(self.sstore.set_name(&account, name)); self.sstore.set_name(&account, name)?;
Ok(()) Ok(())
} }
/// Returns each account along with name and meta. /// Returns each account along with name and meta.
pub fn set_account_meta(&self, account: Address, meta: String) -> Result<(), Error> { pub fn set_account_meta(&self, account: Address, meta: String) -> Result<(), Error> {
try!(self.sstore.set_meta(&account, meta)); self.sstore.set_meta(&account, meta)?;
Ok(()) Ok(())
} }
@ -265,7 +265,7 @@ impl AccountProvider {
/// Permanently removes an account. /// Permanently removes an account.
pub fn kill_account(&self, account: &Address, password: &str) -> Result<(), Error> { pub fn kill_account(&self, account: &Address, password: &str) -> Result<(), Error> {
try!(self.sstore.remove_account(account, &password)); self.sstore.remove_account(account, &password)?;
Ok(()) Ok(())
} }
@ -278,7 +278,7 @@ impl AccountProvider {
fn unlock_account(&self, account: Address, password: String, unlock: Unlock) -> Result<(), Error> { fn unlock_account(&self, account: Address, password: String, unlock: Unlock) -> Result<(), Error> {
// verify password by signing dump message // verify password by signing dump message
// result may be discarded // result may be discarded
let _ = try!(self.sstore.sign(&account, &password, &Default::default())); let _ = self.sstore.sign(&account, &password, &Default::default())?;
// check if account is already unlocked pernamently, if it is, do nothing // check if account is already unlocked pernamently, if it is, do nothing
let mut unlocked = self.unlocked.write(); let mut unlocked = self.unlocked.write();
@ -299,7 +299,7 @@ impl AccountProvider {
fn password(&self, account: &Address) -> Result<String, Error> { fn password(&self, account: &Address) -> Result<String, Error> {
let mut unlocked = self.unlocked.write(); let mut unlocked = self.unlocked.write();
let data = try!(unlocked.get(account).ok_or(Error::NotUnlocked)).clone(); let data = unlocked.get(account).ok_or(Error::NotUnlocked)?.clone();
if let Unlock::Temp = data.unlock { if let Unlock::Temp = data.unlock {
unlocked.remove(account).expect("data exists: so key must exist: qed"); unlocked.remove(account).expect("data exists: so key must exist: qed");
} }
@ -335,25 +335,25 @@ impl AccountProvider {
/// Signs the message. If password is not provided the account must be unlocked. /// Signs the message. If password is not provided the account must be unlocked.
pub fn sign(&self, account: Address, password: Option<String>, message: Message) -> Result<Signature, Error> { pub fn sign(&self, account: Address, password: Option<String>, message: Message) -> Result<Signature, Error> {
let password = try!(password.map(Ok).unwrap_or_else(|| self.password(&account))); let password = password.map(Ok).unwrap_or_else(|| self.password(&account))?;
Ok(try!(self.sstore.sign(&account, &password, &message))) Ok(self.sstore.sign(&account, &password, &message)?)
} }
/// Signs given message with supplied token. Returns a token to use in next signing within this session. /// Signs given message with supplied token. Returns a token to use in next signing within this session.
pub fn sign_with_token(&self, account: Address, token: AccountToken, message: Message) -> Result<(Signature, AccountToken), Error> { pub fn sign_with_token(&self, account: Address, token: AccountToken, message: Message) -> Result<(Signature, AccountToken), Error> {
let is_std_password = try!(self.sstore.test_password(&account, &token)); let is_std_password = self.sstore.test_password(&account, &token)?;
let new_token = random_string(16); let new_token = random_string(16);
let signature = if is_std_password { let signature = if is_std_password {
// Insert to transient store // Insert to transient store
try!(self.sstore.copy_account(&self.transient_sstore, &account, &token, &new_token)); self.sstore.copy_account(&self.transient_sstore, &account, &token, &new_token)?;
// sign // sign
try!(self.sstore.sign(&account, &token, &message)) self.sstore.sign(&account, &token, &message)?
} else { } else {
// check transient store // check transient store
try!(self.transient_sstore.change_password(&account, &token, &new_token)); self.transient_sstore.change_password(&account, &token, &new_token)?;
// and sign // and sign
try!(self.transient_sstore.sign(&account, &new_token, &message)) self.transient_sstore.sign(&account, &new_token, &message)?
}; };
Ok((signature, new_token)) Ok((signature, new_token))
@ -363,19 +363,19 @@ impl AccountProvider {
pub fn decrypt_with_token(&self, account: Address, token: AccountToken, shared_mac: &[u8], message: &[u8]) pub fn decrypt_with_token(&self, account: Address, token: AccountToken, shared_mac: &[u8], message: &[u8])
-> Result<(Vec<u8>, AccountToken), Error> -> Result<(Vec<u8>, AccountToken), Error>
{ {
let is_std_password = try!(self.sstore.test_password(&account, &token)); let is_std_password = self.sstore.test_password(&account, &token)?;
let new_token = random_string(16); let new_token = random_string(16);
let message = if is_std_password { let message = if is_std_password {
// Insert to transient store // Insert to transient store
try!(self.sstore.copy_account(&self.transient_sstore, &account, &token, &new_token)); self.sstore.copy_account(&self.transient_sstore, &account, &token, &new_token)?;
// decrypt // decrypt
try!(self.sstore.decrypt(&account, &token, shared_mac, message)) self.sstore.decrypt(&account, &token, shared_mac, message)?
} else { } else {
// check transient store // check transient store
try!(self.transient_sstore.change_password(&account, &token, &new_token)); self.transient_sstore.change_password(&account, &token, &new_token)?;
// and decrypt // and decrypt
try!(self.transient_sstore.decrypt(&account, &token, shared_mac, message)) self.transient_sstore.decrypt(&account, &token, shared_mac, message)?
}; };
Ok((message, new_token)) Ok((message, new_token))
@ -383,8 +383,8 @@ impl AccountProvider {
/// Decrypts a message. If password is not provided the account must be unlocked. /// Decrypts a message. If password is not provided the account must be unlocked.
pub fn decrypt(&self, account: Address, password: Option<String>, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { pub fn decrypt(&self, account: Address, password: Option<String>, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
let password = try!(password.map(Ok).unwrap_or_else(|| self.password(&account))); let password = password.map(Ok).unwrap_or_else(|| self.password(&account))?;
Ok(try!(self.sstore.decrypt(&account, &password, shared_mac, message))) Ok(self.sstore.decrypt(&account, &password, shared_mac, message)?)
} }
/// Returns the underlying `SecretStore` reference if one exists. /// Returns the underlying `SecretStore` reference if one exists.

View File

@ -67,7 +67,7 @@ impl Block {
impl Decodable for Block { impl Decodable for Block {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
if decoder.as_raw().len() != try!(decoder.as_rlp().payload_info()).total() { if decoder.as_raw().len() != decoder.as_rlp().payload_info()?.total() {
return Err(DecoderError::RlpIsTooBig); return Err(DecoderError::RlpIsTooBig);
} }
let d = decoder.as_rlp(); let d = decoder.as_rlp();
@ -75,9 +75,9 @@ impl Decodable for Block {
return Err(DecoderError::RlpIncorrectListLen); return Err(DecoderError::RlpIncorrectListLen);
} }
Ok(Block { Ok(Block {
header: try!(d.val_at(0)), header: d.val_at(0)?,
transactions: try!(d.val_at(1)), transactions: d.val_at(1)?,
uncles: try!(d.val_at(2)), uncles: d.val_at(2)?,
}) })
} }
} }
@ -252,7 +252,7 @@ impl<'x> OpenBlock<'x> {
gas_range_target: (U256, U256), gas_range_target: (U256, U256),
extra_data: Bytes, extra_data: Bytes,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let state = try!(State::from_existing(db, parent.state_root().clone(), engine.account_start_nonce(), factories)); let state = State::from_existing(db, parent.state_root().clone(), engine.account_start_nonce(), factories)?;
let mut r = OpenBlock { let mut r = OpenBlock {
block: ExecutedBlock::new(state, tracing), block: ExecutedBlock::new(state, tracing),
engine: engine, engine: engine,
@ -521,12 +521,12 @@ pub fn enact(
) -> Result<LockedBlock, Error> { ) -> Result<LockedBlock, Error> {
{ {
if ::log::max_log_level() >= ::log::LogLevel::Trace { if ::log::max_log_level() >= ::log::LogLevel::Trace {
let s = try!(State::from_existing(db.boxed_clone(), parent.state_root().clone(), engine.account_start_nonce(), factories.clone())); let s = State::from_existing(db.boxed_clone(), parent.state_root().clone(), engine.account_start_nonce(), factories.clone())?;
trace!(target: "enact", "num={}, root={}, author={}, author_balance={}\n", header.number(), s.root(), header.author(), s.balance(&header.author())); trace!(target: "enact", "num={}, root={}, author={}, author_balance={}\n", header.number(), s.root(), header.author(), s.balance(&header.author()));
} }
} }
let mut b = try!(OpenBlock::new(engine, factories, tracing, db, parent, last_hashes, Address::new(), (3141562.into(), 31415620.into()), vec![])); let mut b = OpenBlock::new(engine, factories, tracing, db, parent, last_hashes, Address::new(), (3141562.into(), 31415620.into()), vec![])?;
b.set_difficulty(*header.difficulty()); b.set_difficulty(*header.difficulty());
b.set_gas_limit(*header.gas_limit()); b.set_gas_limit(*header.gas_limit());
b.set_timestamp(header.timestamp()); b.set_timestamp(header.timestamp());
@ -536,9 +536,9 @@ pub fn enact(
b.set_transactions_root(header.transactions_root().clone()); b.set_transactions_root(header.transactions_root().clone());
b.set_receipts_root(header.receipts_root().clone()); b.set_receipts_root(header.receipts_root().clone());
try!(push_transactions(&mut b, transactions)); push_transactions(&mut b, transactions)?;
for u in uncles { for u in uncles {
try!(b.push_uncle(u.clone())); b.push_uncle(u.clone())?;
} }
Ok(b.close_and_lock()) Ok(b.close_and_lock())
} }
@ -547,7 +547,7 @@ pub fn enact(
#[cfg(not(feature = "slow-blocks"))] #[cfg(not(feature = "slow-blocks"))]
fn push_transactions(block: &mut OpenBlock, transactions: &[SignedTransaction]) -> Result<(), Error> { fn push_transactions(block: &mut OpenBlock, transactions: &[SignedTransaction]) -> Result<(), Error> {
for t in transactions { for t in transactions {
try!(block.push_transaction(t.clone(), None)); block.push_transaction(t.clone(), None)?;
} }
Ok(()) Ok(())
} }
@ -560,7 +560,7 @@ fn push_transactions(block: &mut OpenBlock, transactions: &[SignedTransaction])
for t in transactions { for t in transactions {
let hash = t.hash(); let hash = t.hash();
let start = time::Instant::now(); let start = time::Instant::now();
try!(block.push_transaction(t.clone(), None)); block.push_transaction(t.clone(), None)?;
let took = start.elapsed(); let took = start.elapsed();
if took > time::Duration::from_millis(slow_tx) { if took > time::Duration::from_millis(slow_tx) {
warn!("Heavy transaction in block {:?}: {:?}", block.header().number(), hash); warn!("Heavy transaction in block {:?}: {:?}", block.header().number(), hash);
@ -627,7 +627,7 @@ mod tests {
factories: Factories, factories: Factories,
) -> Result<SealedBlock, Error> { ) -> Result<SealedBlock, Error> {
let header = BlockView::new(block_bytes).header_view(); let header = BlockView::new(block_bytes).header_view();
Ok(try!(try!(enact_bytes(block_bytes, engine, tracing, db, parent, last_hashes, factories)).seal(engine, header.seal()))) Ok(enact_bytes(block_bytes, engine, tracing, db, parent, last_hashes, factories)?.seal(engine, header.seal())?)
} }
#[test] #[test]

View File

@ -157,10 +157,10 @@ impl Decodable for BlockDetails {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let details = BlockDetails { let details = BlockDetails {
number: try!(d.val_at(0)), number: d.val_at(0)?,
total_difficulty: try!(d.val_at(1)), total_difficulty: d.val_at(1)?,
parent: try!(d.val_at(2)), parent: d.val_at(2)?,
children: try!(d.val_at(3)), children: d.val_at(3)?,
}; };
Ok(details) Ok(details)
} }
@ -193,8 +193,8 @@ impl Decodable for TransactionAddress {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let tx_address = TransactionAddress { let tx_address = TransactionAddress {
block_hash: try!(d.val_at(0)), block_hash: d.val_at(0)?,
index: try!(d.val_at(1)), index: d.val_at(1)?,
}; };
Ok(tx_address) Ok(tx_address)
@ -226,7 +226,7 @@ impl BlockReceipts {
impl Decodable for BlockReceipts { impl Decodable for BlockReceipts {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
Ok(BlockReceipts { Ok(BlockReceipts {
receipts: try!(Decodable::decode(decoder)) receipts: Decodable::decode(decoder)?
}) })
} }
} }

View File

@ -53,7 +53,7 @@ impl Into<bc::BloomGroup> for BloomGroup {
impl Decodable for BloomGroup { impl Decodable for BloomGroup {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let blooms = try!(Decodable::decode(decoder)); let blooms = Decodable::decode(decoder)?;
let group = BloomGroup { let group = BloomGroup {
blooms: blooms blooms: blooms
}; };

View File

@ -167,7 +167,7 @@ impl Client {
) -> Result<Arc<Client>, ClientError> { ) -> Result<Arc<Client>, ClientError> {
let path = path.to_path_buf(); let path = path.to_path_buf();
let db = Arc::new(try!(Database::open(&db_config, &path.to_str().expect("DB path could not be converted to string.")).map_err(ClientError::Database))); let db = Arc::new(Database::open(&db_config, &path.to_str().expect("DB path could not be converted to string.")).map_err(ClientError::Database)?);
let trie_spec = match config.fat_db { let trie_spec = match config.fat_db {
true => TrieSpec::Fat, true => TrieSpec::Fat,
false => TrieSpec::Secure, false => TrieSpec::Secure,
@ -186,8 +186,8 @@ impl Client {
// Sets the correct state root. // Sets the correct state root.
state_db = spec.ensure_db_good(state_db, &factories)?; state_db = spec.ensure_db_good(state_db, &factories)?;
let mut batch = DBTransaction::new(&db); let mut batch = DBTransaction::new(&db);
try!(state_db.journal_under(&mut batch, 0, &spec.genesis_header().hash())); state_db.journal_under(&mut batch, 0, &spec.genesis_header().hash())?;
try!(db.write(batch).map_err(ClientError::Database)); db.write(batch).map_err(ClientError::Database)?;
} }
let gb = spec.genesis_block(); let gb = spec.genesis_block();
@ -210,8 +210,8 @@ impl Client {
for era in earliest..(latest - history + 1) { for era in earliest..(latest - history + 1) {
trace!("Removing era {}", era); trace!("Removing era {}", era);
let mut batch = DBTransaction::new(&db); let mut batch = DBTransaction::new(&db);
try!(state_db.mark_canonical(&mut batch, era, &chain.block_hash(era).expect("Old block not found in the database"))); state_db.mark_canonical(&mut batch, era, &chain.block_hash(era).expect("Old block not found in the database"))?;
try!(db.write(batch).map_err(ClientError::Database)); db.write(batch).map_err(ClientError::Database)?;
} }
} }
} }
@ -252,7 +252,7 @@ impl Client {
last_hashes: RwLock::new(VecDeque::new()), last_hashes: RwLock::new(VecDeque::new()),
factories: factories, factories: factories,
history: history, history: history,
rng: Mutex::new(try!(OsRng::new().map_err(::util::UtilError::StdIo))), rng: Mutex::new(OsRng::new().map_err(::util::UtilError::StdIo)?),
on_mode_change: Mutex::new(None), on_mode_change: Mutex::new(None),
registrar: Mutex::new(None), registrar: Mutex::new(None),
}); });
@ -370,9 +370,9 @@ impl Client {
let db = self.state_db.lock().boxed_clone_canon(header.parent_hash()); let db = self.state_db.lock().boxed_clone_canon(header.parent_hash());
let enact_result = enact_verified(block, engine, self.tracedb.read().tracing_enabled(), db, &parent, last_hashes, self.factories.clone()); let enact_result = enact_verified(block, engine, self.tracedb.read().tracing_enabled(), db, &parent, last_hashes, self.factories.clone());
let locked_block = try!(enact_result.map_err(|e| { let locked_block = enact_result.map_err(|e| {
warn!(target: "client", "Block import failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e); warn!(target: "client", "Block import failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e);
})); })?;
// Final Verification // Final Verification
if let Err(e) = self.verifier.verify_block_final(header, locked_block.block().header()) { if let Err(e) = self.verifier.verify_block_final(header, locked_block.block().header()) {
@ -511,14 +511,14 @@ impl Client {
let chain = self.chain.read(); let chain = self.chain.read();
// verify block. // verify block.
try!(::snapshot::verify_old_block( ::snapshot::verify_old_block(
&mut *rng, &mut *rng,
&header, &header,
&*self.engine, &*self.engine,
&*chain, &*chain,
Some(&block_bytes), Some(&block_bytes),
false, false,
)); )?;
// Commit results // Commit results
let receipts = ::rlp::decode(&receipts_bytes); let receipts = ::rlp::decode(&receipts_bytes);
@ -739,7 +739,7 @@ impl Client {
pub fn take_snapshot<W: snapshot_io::SnapshotWriter + Send>(&self, writer: W, at: BlockId, p: &snapshot::Progress) -> Result<(), EthcoreError> { pub fn take_snapshot<W: snapshot_io::SnapshotWriter + Send>(&self, writer: W, at: BlockId, p: &snapshot::Progress) -> Result<(), EthcoreError> {
let db = self.state_db.lock().journal_db().boxed_clone(); let db = self.state_db.lock().journal_db().boxed_clone();
let best_block_number = self.chain_info().best_block_number; let best_block_number = self.chain_info().best_block_number;
let block_number = try!(self.block_number(at).ok_or(snapshot::Error::InvalidStartingBlock(at))); let block_number = self.block_number(at).ok_or(snapshot::Error::InvalidStartingBlock(at))?;
if best_block_number > self.history + block_number && db.is_pruned() { if best_block_number > self.history + block_number && db.is_pruned() {
return Err(snapshot::Error::OldBlockPrunedDB.into()); return Err(snapshot::Error::OldBlockPrunedDB.into());
@ -765,7 +765,7 @@ impl Client {
}, },
}; };
try!(snapshot::take_snapshot(&self.chain.read(), start_hash, db.as_hashdb(), writer, p)); snapshot::take_snapshot(&self.chain.read(), start_hash, db.as_hashdb(), writer, p)?;
Ok(()) Ok(())
} }
@ -829,7 +829,7 @@ impl snapshot::DatabaseRestore for Client {
let mut tracedb = self.tracedb.write(); let mut tracedb = self.tracedb.write();
self.miner.clear(); self.miner.clear();
let db = self.db.write(); let db = self.db.write();
try!(db.restore(new_db)); db.restore(new_db)?;
let cache_size = state_db.cache_size(); let cache_size = state_db.cache_size();
*state_db = StateDB::new(journaldb::new(db.clone(), self.pruning, ::db::COL_STATE), cache_size); *state_db = StateDB::new(journaldb::new(db.clone(), self.pruning, ::db::COL_STATE), cache_size);
@ -842,7 +842,7 @@ impl snapshot::DatabaseRestore for Client {
impl BlockChainClient for Client { impl BlockChainClient for Client {
fn call(&self, t: &SignedTransaction, block: BlockId, analytics: CallAnalytics) -> Result<Executed, CallError> { fn call(&self, t: &SignedTransaction, block: BlockId, analytics: CallAnalytics) -> Result<Executed, CallError> {
let header = try!(self.block_header(block).ok_or(CallError::StatePruned)); let header = self.block_header(block).ok_or(CallError::StatePruned)?;
let view = HeaderView::new(&header); let view = HeaderView::new(&header);
let last_hashes = self.build_last_hashes(view.parent_hash()); let last_hashes = self.build_last_hashes(view.parent_hash());
let env_info = EnvInfo { let env_info = EnvInfo {
@ -855,13 +855,13 @@ impl BlockChainClient for Client {
gas_limit: U256::max_value(), gas_limit: U256::max_value(),
}; };
// that's just a copy of the state. // that's just a copy of the state.
let mut state = try!(self.state_at(block).ok_or(CallError::StatePruned)); let mut state = self.state_at(block).ok_or(CallError::StatePruned)?;
let original_state = if analytics.state_diffing { Some(state.clone()) } else { None }; let original_state = if analytics.state_diffing { Some(state.clone()) } else { None };
let sender = try!(t.sender().map_err(|e| { let sender = t.sender().map_err(|e| {
let message = format!("Transaction malformed: {:?}", e); let message = format!("Transaction malformed: {:?}", e);
ExecutionError::TransactionMalformed(message) ExecutionError::TransactionMalformed(message)
})); })?;
let balance = state.balance(&sender); let balance = state.balance(&sender);
let needed_balance = t.value + t.gas * t.gas_price; let needed_balance = t.value + t.gas * t.gas_price;
if balance < needed_balance { if balance < needed_balance {
@ -869,7 +869,7 @@ impl BlockChainClient for Client {
state.add_balance(&sender, &(needed_balance - balance), CleanupMode::NoEmpty); state.add_balance(&sender, &(needed_balance - balance), CleanupMode::NoEmpty);
} }
let options = TransactOptions { tracing: analytics.transaction_tracing, vm_tracing: analytics.vm_tracing, check_nonce: false }; let options = TransactOptions { tracing: analytics.transaction_tracing, vm_tracing: analytics.vm_tracing, check_nonce: false };
let mut ret = try!(Executive::new(&mut state, &env_info, &*self.engine, &self.factories.vm).transact(t, options)); let mut ret = Executive::new(&mut state, &env_info, &*self.engine, &self.factories.vm).transact(t, options)?;
// TODO gav move this into Executive. // TODO gav move this into Executive.
ret.state_diff = original_state.map(|original| state.diff_from(original)); ret.state_diff = original_state.map(|original| state.diff_from(original));
@ -878,10 +878,10 @@ impl BlockChainClient for Client {
} }
fn replay(&self, id: TransactionId, analytics: CallAnalytics) -> Result<Executed, CallError> { fn replay(&self, id: TransactionId, analytics: CallAnalytics) -> Result<Executed, CallError> {
let address = try!(self.transaction_address(id).ok_or(CallError::TransactionNotFound)); let address = self.transaction_address(id).ok_or(CallError::TransactionNotFound)?;
let header_data = try!(self.block_header(BlockId::Hash(address.block_hash)).ok_or(CallError::StatePruned)); let header_data = self.block_header(BlockId::Hash(address.block_hash)).ok_or(CallError::StatePruned)?;
let body_data = try!(self.block_body(BlockId::Hash(address.block_hash)).ok_or(CallError::StatePruned)); let body_data = self.block_body(BlockId::Hash(address.block_hash)).ok_or(CallError::StatePruned)?;
let mut state = try!(self.state_at_beginning(BlockId::Hash(address.block_hash)).ok_or(CallError::StatePruned)); let mut state = self.state_at_beginning(BlockId::Hash(address.block_hash)).ok_or(CallError::StatePruned)?;
let txs = BodyView::new(&body_data).transactions(); let txs = BodyView::new(&body_data).transactions();
if address.index >= txs.len() { if address.index >= txs.len() {
@ -909,7 +909,7 @@ impl BlockChainClient for Client {
let t = &txs[address.index]; let t = &txs[address.index];
let original_state = if analytics.state_diffing { Some(state.clone()) } else { None }; let original_state = if analytics.state_diffing { Some(state.clone()) } else { None };
let mut ret = try!(Executive::new(&mut state, &env_info, &*self.engine, &self.factories.vm).transact(t, options)); let mut ret = Executive::new(&mut state, &env_info, &*self.engine, &self.factories.vm).transact(t, options)?;
ret.state_diff = original_state.map(|original| state.diff_from(original)); ret.state_diff = original_state.map(|original| state.diff_from(original));
Ok(ret) Ok(ret)
@ -1221,7 +1221,7 @@ impl BlockChainClient for Client {
return Err(BlockImportError::Block(BlockError::UnknownParent(unverified.parent_hash()))); return Err(BlockImportError::Block(BlockError::UnknownParent(unverified.parent_hash())));
} }
} }
Ok(try!(self.block_queue.import(unverified))) Ok(self.block_queue.import(unverified)?)
} }
fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result<H256, BlockImportError> { fn import_block_with_receipts(&self, block_bytes: Bytes, receipts_bytes: Bytes) -> Result<H256, BlockImportError> {

View File

@ -43,7 +43,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserve","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserve","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}`
@ -55,7 +55,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"bytes32"}],"name":"set","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"bytes32"}],"name":"set","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}`
@ -67,7 +67,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"drop","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"drop","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}`
@ -79,7 +79,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"getAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"getAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"}`
@ -91,7 +91,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_address().ok_or("Invalid type returned")); util::Address::from(r) })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_address().ok_or("Invalid type returned")?; util::Address::from(r) }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"setFee","outputs":[],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"setFee","outputs":[],"payable":false,"type":"function"}`
@ -115,7 +115,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"}`
@ -127,7 +127,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_address().ok_or("Invalid type returned")); util::Address::from(r) })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_address().ok_or("Invalid type returned")?; util::Address::from(r) }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserved","outputs":[{"name":"reserved","type":"bool"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserved","outputs":[{"name":"reserved","type":"bool"}],"payable":false,"type":"function"}`
@ -139,7 +139,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[],"name":"drain","outputs":[],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[],"name":"drain","outputs":[],"payable":false,"type":"function"}`
@ -163,7 +163,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"getUint","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"getUint","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}`
@ -175,7 +175,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_uint().ok_or("Invalid type returned")); util::U256::from(r.as_ref()) })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_uint().ok_or("Invalid type returned")?; util::U256::from(r.as_ref()) }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"get","outputs":[{"name":"","type":"bytes32"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"}],"name":"get","outputs":[{"name":"","type":"bytes32"}],"payable":false,"type":"function"}`
@ -187,7 +187,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_fixed_bytes().ok_or("Invalid type returned")); util::H256::from_slice(r.as_ref()) })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_fixed_bytes().ok_or("Invalid type returned")?; util::H256::from_slice(r.as_ref()) }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}`
@ -199,7 +199,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_uint().ok_or("Invalid type returned")); util::U256::from(r.as_ref()) })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_uint().ok_or("Invalid type returned")?; util::U256::from(r.as_ref()) }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"}`
@ -211,7 +211,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_address().ok_or("Invalid type returned")); util::Address::from(r) })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_address().ok_or("Invalid type returned")?; util::Address::from(r) }))
} }
/// Auto-generated from: `{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"reverse","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"reverse","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}`
@ -223,7 +223,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_string().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_string().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"uint256"}],"name":"setUint","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_key","type":"string"},{"name":"_value","type":"uint256"}],"name":"setUint","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"}`
@ -235,7 +235,7 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
/// Auto-generated from: `{"constant":false,"inputs":[],"name":"removeReverse","outputs":[],"payable":false,"type":"function"}` /// Auto-generated from: `{"constant":false,"inputs":[],"name":"removeReverse","outputs":[],"payable":false,"type":"function"}`
@ -259,6 +259,6 @@ impl Registry {
).map_err(Self::as_string)?; ).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?; let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>(); let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = try!(r.to_bool().ok_or("Invalid type returned")); r })) Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_bool().ok_or("Invalid type returned")?; r }))
} }
} }

View File

@ -107,7 +107,7 @@ impl AuthorityRound {
params: params, params: params,
our_params: our_params, our_params: our_params,
builtins: builtins, builtins: builtins,
transition_service: try!(IoService::<()>::start()), transition_service: IoService::<()>::start()?,
message_channel: Mutex::new(None), message_channel: Mutex::new(None),
step: AtomicUsize::new(initial_step), step: AtomicUsize::new(initial_step),
proposed: AtomicBool::new(false), proposed: AtomicBool::new(false),
@ -117,7 +117,7 @@ impl AuthorityRound {
// Do not initialize timeouts for tests. // Do not initialize timeouts for tests.
if should_timeout { if should_timeout {
let handler = TransitionHandler { engine: Arc::downgrade(&engine) }; let handler = TransitionHandler { engine: Arc::downgrade(&engine) };
try!(engine.transition_service.register_handler(Arc::new(handler))); engine.transition_service.register_handler(Arc::new(handler))?;
} }
Ok(engine) Ok(engine)
} }
@ -263,20 +263,20 @@ impl Engine for AuthorityRound {
/// Check if the signature belongs to the correct proposer. /// Check if the signature belongs to the correct proposer.
fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> { fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
let header_step = try!(header_step(header)); let header_step = header_step(header)?;
// Give one step slack if step is lagging, double vote is still not possible. // Give one step slack if step is lagging, double vote is still not possible.
if header_step <= self.step.load(AtomicOrdering::SeqCst) + 1 { if header_step <= self.step.load(AtomicOrdering::SeqCst) + 1 {
let proposer_signature = try!(header_signature(header)); let proposer_signature = header_signature(header)?;
let ok_sig = try!(verify_address(self.step_proposer(header_step), &proposer_signature, &header.bare_hash())); let ok_sig = verify_address(self.step_proposer(header_step), &proposer_signature, &header.bare_hash())?;
if ok_sig { if ok_sig {
Ok(()) Ok(())
} else { } else {
trace!(target: "poa", "verify_block_unordered: invalid seal signature"); trace!(target: "poa", "verify_block_unordered: invalid seal signature");
try!(Err(BlockError::InvalidSeal)) Err(BlockError::InvalidSeal)?
} }
} else { } else {
trace!(target: "poa", "verify_block_unordered: block from the future"); trace!(target: "poa", "verify_block_unordered: block from the future");
try!(Err(BlockError::InvalidSeal)) Err(BlockError::InvalidSeal)?
} }
} }
@ -285,11 +285,11 @@ impl Engine for AuthorityRound {
return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() }))); return Err(From::from(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() })));
} }
let step = try!(header_step(header)); let step = header_step(header)?;
// Check if parent is from a previous step. // Check if parent is from a previous step.
if step == try!(header_step(parent)) { if step == header_step(parent)? {
trace!(target: "poa", "Multiple blocks proposed for step {}.", step); trace!(target: "poa", "Multiple blocks proposed for step {}.", step);
try!(Err(EngineError::DoubleVote(header.author().clone()))); Err(EngineError::DoubleVote(header.author().clone()))?;
} }
let gas_limit_divisor = self.our_params.gas_limit_bound_divisor; let gas_limit_divisor = self.our_params.gas_limit_bound_divisor;
@ -302,7 +302,7 @@ impl Engine for AuthorityRound {
} }
fn verify_transaction_basic(&self, t: &SignedTransaction, _header: &Header) -> Result<(), Error> { fn verify_transaction_basic(&self, t: &SignedTransaction, _header: &Header) -> Result<(), Error> {
try!(t.check_low_s()); t.check_low_s()?;
Ok(()) Ok(())
} }

View File

@ -143,10 +143,10 @@ impl Engine for BasicAuthority {
use rlp::{UntrustedRlp, View}; use rlp::{UntrustedRlp, View};
// check the signature is legit. // check the signature is legit.
let sig = try!(UntrustedRlp::new(&header.seal()[0]).as_val::<H520>()); let sig = UntrustedRlp::new(&header.seal()[0]).as_val::<H520>()?;
let signer = public_to_address(&try!(recover(&sig.into(), &header.bare_hash()))); let signer = public_to_address(&recover(&sig.into(), &header.bare_hash())?);
if !self.our_params.authorities.contains(&signer) { if !self.our_params.authorities.contains(&signer) {
return try!(Err(BlockError::InvalidSeal)); return Err(BlockError::InvalidSeal)?;
} }
Ok(()) Ok(())
} }
@ -171,7 +171,7 @@ impl Engine for BasicAuthority {
} }
fn verify_transaction_basic(&self, t: &SignedTransaction, _header: &Header) -> result::Result<(), Error> { fn verify_transaction_basic(&self, t: &SignedTransaction, _header: &Header) -> result::Result<(), Error> {
try!(t.check_low_s()); t.check_low_s()?;
Ok(()) Ok(())
} }

View File

@ -51,9 +51,9 @@ impl ConsensusMessage {
pub fn new_proposal(header: &Header) -> Result<Self, ::rlp::DecoderError> { pub fn new_proposal(header: &Header) -> Result<Self, ::rlp::DecoderError> {
Ok(ConsensusMessage { Ok(ConsensusMessage {
signature: try!(UntrustedRlp::new(header.seal().get(1).expect("seal passed basic verification; seal has 3 fields; qed").as_slice()).as_val()), signature: UntrustedRlp::new(header.seal().get(1).expect("seal passed basic verification; seal has 3 fields; qed").as_slice()).as_val()?,
height: header.number() as Height, height: header.number() as Height,
round: try!(consensus_round(header)), round: consensus_round(header)?,
step: Step::Propose, step: Step::Propose,
block_hash: Some(header.bare_hash()), block_hash: Some(header.bare_hash()),
}) })
@ -92,7 +92,7 @@ impl ConsensusMessage {
pub fn verify(&self) -> Result<Address, Error> { pub fn verify(&self) -> Result<Address, Error> {
let full_rlp = ::rlp::encode(self); let full_rlp = ::rlp::encode(self);
let block_info = Rlp::new(&full_rlp).at(1); let block_info = Rlp::new(&full_rlp).at(1);
let public_key = try!(recover(&self.signature.into(), &block_info.as_raw().sha3())); let public_key = recover(&self.signature.into(), &block_info.as_raw().sha3())?;
Ok(public_to_address(&public_key)) Ok(public_to_address(&public_key))
} }
@ -134,7 +134,7 @@ impl Ord for ConsensusMessage {
impl Decodable for Step { impl Decodable for Step {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
match try!(decoder.as_rlp().as_val()) { match decoder.as_rlp().as_val()? {
0u8 => Ok(Step::Propose), 0u8 => Ok(Step::Propose),
1 => Ok(Step::Prevote), 1 => Ok(Step::Prevote),
2 => Ok(Step::Precommit), 2 => Ok(Step::Precommit),
@ -153,13 +153,13 @@ impl Encodable for Step {
impl Decodable for ConsensusMessage { impl Decodable for ConsensusMessage {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let rlp = decoder.as_rlp(); let rlp = decoder.as_rlp();
let m = try!(rlp.at(1)); let m = rlp.at(1)?;
let block_message: H256 = try!(m.val_at(3)); let block_message: H256 = m.val_at(3)?;
Ok(ConsensusMessage { Ok(ConsensusMessage {
signature: try!(rlp.val_at(0)), signature: rlp.val_at(0)?,
height: try!(m.val_at(0)), height: m.val_at(0)?,
round: try!(m.val_at(1)), round: m.val_at(1)?,
step: try!(m.val_at(2)), step: m.val_at(2)?,
block_hash: match block_message.is_zero() { block_hash: match block_message.is_zero() {
true => None, true => None,
false => Some(block_message), false => Some(block_message),

View File

@ -109,7 +109,7 @@ impl Tendermint {
params: params, params: params,
our_params: our_params, our_params: our_params,
builtins: builtins, builtins: builtins,
step_service: try!(IoService::<Step>::start()), step_service: IoService::<Step>::start()?,
authority: RwLock::new(Address::default()), authority: RwLock::new(Address::default()),
password: RwLock::new(None), password: RwLock::new(None),
height: AtomicUsize::new(1), height: AtomicUsize::new(1),
@ -123,7 +123,7 @@ impl Tendermint {
proposal: RwLock::new(None), proposal: RwLock::new(None),
}); });
let handler = TransitionHandler { engine: Arc::downgrade(&engine) }; let handler = TransitionHandler { engine: Arc::downgrade(&engine) };
try!(engine.step_service.register_handler(Arc::new(handler))); engine.step_service.register_handler(Arc::new(handler))?;
Ok(engine) Ok(engine)
} }
@ -455,11 +455,11 @@ impl Engine for Tendermint {
fn handle_message(&self, rlp: &[u8]) -> Result<(), Error> { fn handle_message(&self, rlp: &[u8]) -> Result<(), Error> {
let rlp = UntrustedRlp::new(rlp); let rlp = UntrustedRlp::new(rlp);
let message: ConsensusMessage = try!(rlp.as_val()); let message: ConsensusMessage = rlp.as_val()?;
if !self.votes.is_old_or_known(&message) { if !self.votes.is_old_or_known(&message) {
let sender = public_to_address(&try!(recover(&message.signature.into(), &try!(rlp.at(1)).as_raw().sha3()))); let sender = public_to_address(&recover(&message.signature.into(), &rlp.at(1)?.as_raw().sha3())?);
if !self.is_authority(&sender) { if !self.is_authority(&sender) {
try!(Err(EngineError::NotAuthorized(sender))); Err(EngineError::NotAuthorized(sender))?;
} }
self.broadcast_message(rlp.as_raw().to_vec()); self.broadcast_message(rlp.as_raw().to_vec());
trace!(target: "poa", "Handling a valid {:?} from {}.", message, sender); trace!(target: "poa", "Handling a valid {:?} from {}.", message, sender);
@ -491,10 +491,10 @@ impl Engine for Tendermint {
} }
fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> { fn verify_block_unordered(&self, header: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
let proposal = try!(ConsensusMessage::new_proposal(header)); let proposal = ConsensusMessage::new_proposal(header)?;
let proposer = try!(proposal.verify()); let proposer = proposal.verify()?;
if !self.is_authority(&proposer) { if !self.is_authority(&proposer) {
try!(Err(EngineError::NotAuthorized(proposer))) Err(EngineError::NotAuthorized(proposer))?
} }
let precommit_hash = proposal.precommit_hash(); let precommit_hash = proposal.precommit_hash();
@ -502,20 +502,20 @@ impl Engine for Tendermint {
let mut signature_count = 0; let mut signature_count = 0;
let mut origins = HashSet::new(); let mut origins = HashSet::new();
for rlp in UntrustedRlp::new(signatures_field).iter() { for rlp in UntrustedRlp::new(signatures_field).iter() {
let precommit: ConsensusMessage = ConsensusMessage::new_commit(&proposal, try!(rlp.as_val())); let precommit: ConsensusMessage = ConsensusMessage::new_commit(&proposal, rlp.as_val()?);
let address = match self.votes.get(&precommit) { let address = match self.votes.get(&precommit) {
Some(a) => a, Some(a) => a,
None => public_to_address(&try!(recover(&precommit.signature.into(), &precommit_hash))), None => public_to_address(&recover(&precommit.signature.into(), &precommit_hash)?),
}; };
if !self.our_params.authorities.contains(&address) { if !self.our_params.authorities.contains(&address) {
try!(Err(EngineError::NotAuthorized(address.to_owned()))) Err(EngineError::NotAuthorized(address.to_owned()))?
} }
if origins.insert(address) { if origins.insert(address) {
signature_count += 1; signature_count += 1;
} else { } else {
warn!(target: "poa", "verify_block_unordered: Duplicate signature from {} on the seal.", address); warn!(target: "poa", "verify_block_unordered: Duplicate signature from {} on the seal.", address);
try!(Err(BlockError::InvalidSeal)); Err(BlockError::InvalidSeal)?;
} }
} }
@ -524,34 +524,34 @@ impl Engine for Tendermint {
let signatures_len = signatures_field.len(); let signatures_len = signatures_field.len();
// Proposal has to have an empty signature list. // Proposal has to have an empty signature list.
if signatures_len != 1 { if signatures_len != 1 {
try!(Err(EngineError::BadSealFieldSize(OutOfBounds { Err(EngineError::BadSealFieldSize(OutOfBounds {
min: Some(1), min: Some(1),
max: Some(1), max: Some(1),
found: signatures_len found: signatures_len
}))); }))?;
} }
try!(self.is_round_proposer(proposal.height, proposal.round, &proposer)); self.is_round_proposer(proposal.height, proposal.round, &proposer)?;
} }
Ok(()) Ok(())
} }
fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> Result<(), Error> { fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> Result<(), Error> {
if header.number() == 0 { if header.number() == 0 {
try!(Err(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() }))); Err(BlockError::RidiculousNumber(OutOfBounds { min: Some(1), max: None, found: header.number() }))?;
} }
let gas_limit_divisor = self.our_params.gas_limit_bound_divisor; let gas_limit_divisor = self.our_params.gas_limit_bound_divisor;
let min_gas = parent.gas_limit().clone() - parent.gas_limit().clone() / gas_limit_divisor; let min_gas = parent.gas_limit().clone() - parent.gas_limit().clone() / gas_limit_divisor;
let max_gas = parent.gas_limit().clone() + parent.gas_limit().clone() / gas_limit_divisor; let max_gas = parent.gas_limit().clone() + parent.gas_limit().clone() / gas_limit_divisor;
if header.gas_limit() <= &min_gas || header.gas_limit() >= &max_gas { if header.gas_limit() <= &min_gas || header.gas_limit() >= &max_gas {
try!(Err(BlockError::InvalidGasLimit(OutOfBounds { min: Some(min_gas), max: Some(max_gas), found: header.gas_limit().clone() }))); Err(BlockError::InvalidGasLimit(OutOfBounds { min: Some(min_gas), max: Some(max_gas), found: header.gas_limit().clone() }))?;
} }
Ok(()) Ok(())
} }
fn verify_transaction_basic(&self, t: &SignedTransaction, _header: &Header) -> Result<(), Error> { fn verify_transaction_basic(&self, t: &SignedTransaction, _header: &Header) -> Result<(), Error> {
try!(t.check_low_s()); t.check_low_s()?;
Ok(()) Ok(())
} }

View File

@ -240,8 +240,8 @@ impl Engine for Ethash {
Mismatch { expected: self.seal_fields(), found: header.seal().len() } Mismatch { expected: self.seal_fields(), found: header.seal().len() }
))); )));
} }
try!(UntrustedRlp::new(&header.seal()[0]).as_val::<H256>()); UntrustedRlp::new(&header.seal()[0]).as_val::<H256>()?;
try!(UntrustedRlp::new(&header.seal()[1]).as_val::<H64>()); UntrustedRlp::new(&header.seal()[1]).as_val::<H64>()?;
// TODO: consider removing these lines. // TODO: consider removing these lines.
let min_difficulty = self.ethash_params.minimum_difficulty; let min_difficulty = self.ethash_params.minimum_difficulty;
@ -312,7 +312,7 @@ impl Engine for Ethash {
fn verify_transaction_basic(&self, t: &SignedTransaction, header: &Header) -> result::Result<(), Error> { fn verify_transaction_basic(&self, t: &SignedTransaction, header: &Header) -> result::Result<(), Error> {
if header.number() >= self.ethash_params.homestead_transition { if header.number() >= self.ethash_params.homestead_transition {
try!(t.check_low_s()); t.check_low_s()?;
} }
if let Some(n) = t.network_id() { if let Some(n) = t.network_id() {

View File

@ -159,39 +159,39 @@ impl<Gas: CostType> Gasometer<Gas> {
Request::Gas(gas) Request::Gas(gas)
}, },
instructions::MSTORE | instructions::MLOAD => { instructions::MSTORE | instructions::MLOAD => {
Request::GasMem(default_gas, try!(mem_needed_const(stack.peek(0), 32))) Request::GasMem(default_gas, mem_needed_const(stack.peek(0), 32)?)
}, },
instructions::MSTORE8 => { instructions::MSTORE8 => {
Request::GasMem(default_gas, try!(mem_needed_const(stack.peek(0), 1))) Request::GasMem(default_gas, mem_needed_const(stack.peek(0), 1)?)
}, },
instructions::RETURN => { instructions::RETURN => {
Request::GasMem(default_gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) Request::GasMem(default_gas, mem_needed(stack.peek(0), stack.peek(1))?)
}, },
instructions::SHA3 => { instructions::SHA3 => {
let w = overflowing!(add_gas_usize(try!(Gas::from_u256(*stack.peek(1))), 31)); let w = overflowing!(add_gas_usize(Gas::from_u256(*stack.peek(1))?, 31));
let words = w >> 5; let words = w >> 5;
let gas = Gas::from(schedule.sha3_gas) + (Gas::from(schedule.sha3_word_gas) * words); let gas = Gas::from(schedule.sha3_gas) + (Gas::from(schedule.sha3_word_gas) * words);
Request::GasMem(gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) Request::GasMem(gas, mem_needed(stack.peek(0), stack.peek(1))?)
}, },
instructions::CALLDATACOPY | instructions::CODECOPY => { instructions::CALLDATACOPY | instructions::CODECOPY => {
Request::GasMemCopy(default_gas, try!(mem_needed(stack.peek(0), stack.peek(2))), try!(Gas::from_u256(*stack.peek(2)))) Request::GasMemCopy(default_gas, mem_needed(stack.peek(0), stack.peek(2))?, Gas::from_u256(*stack.peek(2))?)
}, },
instructions::EXTCODECOPY => { instructions::EXTCODECOPY => {
Request::GasMemCopy(schedule.extcodecopy_base_gas.into(), try!(mem_needed(stack.peek(1), stack.peek(3))), try!(Gas::from_u256(*stack.peek(3)))) Request::GasMemCopy(schedule.extcodecopy_base_gas.into(), mem_needed(stack.peek(1), stack.peek(3))?, Gas::from_u256(*stack.peek(3))?)
}, },
instructions::LOG0...instructions::LOG4 => { instructions::LOG0...instructions::LOG4 => {
let no_of_topics = instructions::get_log_topics(instruction); let no_of_topics = instructions::get_log_topics(instruction);
let log_gas = schedule.log_gas + schedule.log_topic_gas * no_of_topics; let log_gas = schedule.log_gas + schedule.log_topic_gas * no_of_topics;
let data_gas = overflowing!(try!(Gas::from_u256(*stack.peek(1))).overflow_mul(Gas::from(schedule.log_data_gas))); let data_gas = overflowing!(Gas::from_u256(*stack.peek(1))?.overflow_mul(Gas::from(schedule.log_data_gas)));
let gas = overflowing!(data_gas.overflow_add(Gas::from(log_gas))); let gas = overflowing!(data_gas.overflow_add(Gas::from(log_gas)));
Request::GasMem(gas, try!(mem_needed(stack.peek(0), stack.peek(1)))) Request::GasMem(gas, mem_needed(stack.peek(0), stack.peek(1))?)
}, },
instructions::CALL | instructions::CALLCODE => { instructions::CALL | instructions::CALLCODE => {
let mut gas = Gas::from(schedule.call_gas); let mut gas = Gas::from(schedule.call_gas);
let mem = cmp::max( let mem = cmp::max(
try!(mem_needed(stack.peek(5), stack.peek(6))), mem_needed(stack.peek(5), stack.peek(6))?,
try!(mem_needed(stack.peek(3), stack.peek(4))) mem_needed(stack.peek(3), stack.peek(4))?
); );
let address = u256_to_address(stack.peek(1)); let address = u256_to_address(stack.peek(1));
@ -216,8 +216,8 @@ impl<Gas: CostType> Gasometer<Gas> {
instructions::DELEGATECALL => { instructions::DELEGATECALL => {
let gas = Gas::from(schedule.call_gas); let gas = Gas::from(schedule.call_gas);
let mem = cmp::max( let mem = cmp::max(
try!(mem_needed(stack.peek(4), stack.peek(5))), mem_needed(stack.peek(4), stack.peek(5))?,
try!(mem_needed(stack.peek(2), stack.peek(3))) mem_needed(stack.peek(2), stack.peek(3))?
); );
let requested = *stack.peek(0); let requested = *stack.peek(0);
@ -225,7 +225,7 @@ impl<Gas: CostType> Gasometer<Gas> {
}, },
instructions::CREATE => { instructions::CREATE => {
let gas = Gas::from(schedule.create_gas); let gas = Gas::from(schedule.create_gas);
let mem = try!(mem_needed(stack.peek(1), stack.peek(2))); let mem = mem_needed(stack.peek(1), stack.peek(2))?;
Request::GasMemProvide(gas, mem, None) Request::GasMemProvide(gas, mem, None)
}, },
@ -248,7 +248,7 @@ impl<Gas: CostType> Gasometer<Gas> {
} }
}, },
Request::GasMem(gas, mem_size) => { Request::GasMem(gas, mem_size) => {
let (mem_gas_cost, new_mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, current_mem_size, &mem_size)); let (mem_gas_cost, new_mem_gas, new_mem_size) = self.mem_gas_cost(schedule, current_mem_size, &mem_size)?;
let gas = overflowing!(gas.overflow_add(mem_gas_cost)); let gas = overflowing!(gas.overflow_add(mem_gas_cost));
InstructionRequirements { InstructionRequirements {
gas_cost: gas, gas_cost: gas,
@ -258,9 +258,9 @@ impl<Gas: CostType> Gasometer<Gas> {
} }
}, },
Request::GasMemProvide(gas, mem_size, requested) => { Request::GasMemProvide(gas, mem_size, requested) => {
let (mem_gas_cost, new_mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, current_mem_size, &mem_size)); let (mem_gas_cost, new_mem_gas, new_mem_size) = self.mem_gas_cost(schedule, current_mem_size, &mem_size)?;
let gas = overflowing!(gas.overflow_add(mem_gas_cost)); let gas = overflowing!(gas.overflow_add(mem_gas_cost));
let provided = try!(self.gas_provided(schedule, gas, requested)); let provided = self.gas_provided(schedule, gas, requested)?;
let total_gas = overflowing!(gas.overflow_add(provided)); let total_gas = overflowing!(gas.overflow_add(provided));
InstructionRequirements { InstructionRequirements {
@ -271,7 +271,7 @@ impl<Gas: CostType> Gasometer<Gas> {
} }
}, },
Request::GasMemCopy(gas, mem_size, copy) => { Request::GasMemCopy(gas, mem_size, copy) => {
let (mem_gas_cost, new_mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, current_mem_size, &mem_size)); let (mem_gas_cost, new_mem_gas, new_mem_size) = self.mem_gas_cost(schedule, current_mem_size, &mem_size)?;
let copy = overflowing!(add_gas_usize(copy, 31)) >> 5; let copy = overflowing!(add_gas_usize(copy, 31)) >> 5;
let copy_gas = Gas::from(schedule.copy_gas) * copy; let copy_gas = Gas::from(schedule.copy_gas) * copy;
let gas = overflowing!(gas.overflow_add(copy_gas)); let gas = overflowing!(gas.overflow_add(copy_gas));
@ -303,7 +303,7 @@ impl<Gas: CostType> Gasometer<Gas> {
let req_mem_size_rounded = (overflowing!(mem_size.overflow_add(Gas::from(31 as usize))) >> 5) << 5; let req_mem_size_rounded = (overflowing!(mem_size.overflow_add(Gas::from(31 as usize))) >> 5) << 5;
let (mem_gas_cost, new_mem_gas) = if req_mem_size_rounded > current_mem_size { let (mem_gas_cost, new_mem_gas) = if req_mem_size_rounded > current_mem_size {
let new_mem_gas = try!(gas_for_mem(req_mem_size_rounded)); let new_mem_gas = gas_for_mem(req_mem_size_rounded)?;
(new_mem_gas - self.current_mem_gas, new_mem_gas) (new_mem_gas - self.current_mem_gas, new_mem_gas)
} else { } else {
(Gas::from(0), self.current_mem_gas) (Gas::from(0), self.current_mem_gas)

View File

@ -107,7 +107,7 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
let code = &params.code.as_ref().expect("exec always called with code; qed"); let code = &params.code.as_ref().expect("exec always called with code; qed");
let valid_jump_destinations = self.cache.jump_destinations(&params.code_hash, code); let valid_jump_destinations = self.cache.jump_destinations(&params.code_hash, code);
let mut gasometer = Gasometer::<Cost>::new(try!(Cost::from_u256(params.gas))); let mut gasometer = Gasometer::<Cost>::new(Cost::from_u256(params.gas)?);
let mut stack = VecStack::with_capacity(ext.schedule().stack_limit, U256::zero()); let mut stack = VecStack::with_capacity(ext.schedule().stack_limit, U256::zero());
let mut reader = CodeReader::new(code); let mut reader = CodeReader::new(code);
let infos = &*instructions::INSTRUCTIONS; let infos = &*instructions::INSTRUCTIONS;
@ -117,14 +117,14 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
reader.position += 1; reader.position += 1;
let info = &infos[instruction as usize]; let info = &infos[instruction as usize];
try!(self.verify_instruction(ext, instruction, info, &stack)); self.verify_instruction(ext, instruction, info, &stack)?;
// Calculate gas cost // Calculate gas cost
let requirements = try!(gasometer.requirements(ext, instruction, info, &stack, self.mem.size())); let requirements = gasometer.requirements(ext, instruction, info, &stack, self.mem.size())?;
// TODO: make compile-time removable if too much of a performance hit. // TODO: make compile-time removable if too much of a performance hit.
let trace_executed = ext.trace_prepare_execute(reader.position - 1, instruction, &requirements.gas_cost.as_u256()); let trace_executed = ext.trace_prepare_execute(reader.position - 1, instruction, &requirements.gas_cost.as_u256());
try!(gasometer.verify_gas(&requirements.gas_cost)); gasometer.verify_gas(&requirements.gas_cost)?;
self.mem.expand(requirements.memory_required_size); self.mem.expand(requirements.memory_required_size);
gasometer.current_mem_gas = requirements.memory_total_gas; gasometer.current_mem_gas = requirements.memory_total_gas;
gasometer.current_gas = gasometer.current_gas - requirements.gas_cost; gasometer.current_gas = gasometer.current_gas - requirements.gas_cost;
@ -137,9 +137,9 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
}; };
// Execute instruction // Execute instruction
let result = try!(self.exec_instruction( let result = self.exec_instruction(
gasometer.current_gas, &params, ext, instruction, &mut reader, &mut stack, requirements.provide_gas gasometer.current_gas, &params, ext, instruction, &mut reader, &mut stack, requirements.provide_gas
)); )?;
evm_debug!({ informant.after_instruction(instruction) }); evm_debug!({ informant.after_instruction(instruction) });
@ -154,7 +154,7 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
// Advance // Advance
match result { match result {
InstructionResult::JumpToPosition(position) => { InstructionResult::JumpToPosition(position) => {
let pos = try!(self.verify_jump(position, &valid_jump_destinations)); let pos = self.verify_jump(position, &valid_jump_destinations)?;
reader.position = pos; reader.position = pos;
}, },
InstructionResult::StopExecutionNeedsReturn(gas, off, size) => { InstructionResult::StopExecutionNeedsReturn(gas, off, size) => {
@ -513,7 +513,7 @@ impl<Cost: CostType> Interpreter<Cost> {
stack.push(ext.env_info().gas_limit.clone()); stack.push(ext.env_info().gas_limit.clone());
}, },
_ => { _ => {
try!(self.exec_stack_instruction(instruction, stack)); self.exec_stack_instruction(instruction, stack)?;
} }
}; };
Ok(InstructionResult::Ok) Ok(InstructionResult::Ok)

View File

@ -122,10 +122,10 @@ impl<'a> Executive<'a> {
mut tracer: T, mut tracer: T,
mut vm_tracer: V mut vm_tracer: V
) -> Result<Executed, ExecutionError> where T: Tracer, V: VMTracer { ) -> Result<Executed, ExecutionError> where T: Tracer, V: VMTracer {
let sender = try!(t.sender().map_err(|e| { let sender = t.sender().map_err(|e| {
let message = format!("Transaction malformed: {:?}", e); let message = format!("Transaction malformed: {:?}", e);
ExecutionError::TransactionMalformed(message) ExecutionError::TransactionMalformed(message)
})); })?;
let nonce = self.state.nonce(&sender); let nonce = self.state.nonce(&sender);
let schedule = self.engine.schedule(self.info); let schedule = self.engine.schedule(self.info);
@ -206,7 +206,7 @@ impl<'a> Executive<'a> {
}; };
// finalize here! // finalize here!
Ok(try!(self.finalize(t, substate, gas_left, output, tracer.traces(), vm_tracer.drain()))) Ok(self.finalize(t, substate, gas_left, output, tracer.traces(), vm_tracer.drain())?)
} }
fn exec_vm<T, V>( fn exec_vm<T, V>(

View File

@ -265,26 +265,26 @@ impl Decodable for Header {
let r = decoder.as_rlp(); let r = decoder.as_rlp();
let mut blockheader = Header { let mut blockheader = Header {
parent_hash: try!(r.val_at(0)), parent_hash: r.val_at(0)?,
uncles_hash: try!(r.val_at(1)), uncles_hash: r.val_at(1)?,
author: try!(r.val_at(2)), author: r.val_at(2)?,
state_root: try!(r.val_at(3)), state_root: r.val_at(3)?,
transactions_root: try!(r.val_at(4)), transactions_root: r.val_at(4)?,
receipts_root: try!(r.val_at(5)), receipts_root: r.val_at(5)?,
log_bloom: try!(r.val_at(6)), log_bloom: r.val_at(6)?,
difficulty: try!(r.val_at(7)), difficulty: r.val_at(7)?,
number: try!(r.val_at(8)), number: r.val_at(8)?,
gas_limit: try!(r.val_at(9)), gas_limit: r.val_at(9)?,
gas_used: try!(r.val_at(10)), gas_used: r.val_at(10)?,
timestamp: try!(r.val_at(11)), timestamp: r.val_at(11)?,
extra_data: try!(r.val_at(12)), extra_data: r.val_at(12)?,
seal: vec![], seal: vec![],
hash: RefCell::new(Some(r.as_raw().sha3())), hash: RefCell::new(Some(r.as_raw().sha3())),
bare_hash: RefCell::new(None), bare_hash: RefCell::new(None),
}; };
for i in 13..r.item_count() { for i in 13..r.item_count() {
blockheader.seal.push(try!(r.at(i)).as_raw().to_vec()) blockheader.seal.push(r.at(i)?.as_raw().to_vec())
} }
Ok(blockheader) Ok(blockheader)

View File

@ -109,7 +109,7 @@ impl OverlayRecentV7 {
// walk all journal entries in the database backwards. // walk all journal entries in the database backwards.
// find migrations for any possible inserted keys. // find migrations for any possible inserted keys.
fn walk_journal(&mut self, source: Arc<Database>) -> Result<(), Error> { fn walk_journal(&mut self, source: Arc<Database>) -> Result<(), Error> {
if let Some(val) = try!(source.get(None, V7_LATEST_ERA_KEY).map_err(Error::Custom)) { if let Some(val) = source.get(None, V7_LATEST_ERA_KEY).map_err(Error::Custom)? {
let mut era = decode::<u64>(&val); let mut era = decode::<u64>(&val);
loop { loop {
let mut index: usize = 0; let mut index: usize = 0;
@ -120,7 +120,7 @@ impl OverlayRecentV7 {
r.out() r.out()
}; };
if let Some(journal_raw) = try!(source.get(None, &entry_key).map_err(Error::Custom)) { if let Some(journal_raw) = source.get(None, &entry_key).map_err(Error::Custom)? {
let rlp = Rlp::new(&journal_raw); let rlp = Rlp::new(&journal_raw);
// migrate all inserted keys. // migrate all inserted keys.
@ -153,8 +153,8 @@ impl OverlayRecentV7 {
// replace all possible inserted/deleted keys with their migrated counterparts // replace all possible inserted/deleted keys with their migrated counterparts
// and commit the altered entries. // and commit the altered entries.
fn migrate_journal(&self, source: Arc<Database>, mut batch: Batch, dest: &mut Database) -> Result<(), Error> { fn migrate_journal(&self, source: Arc<Database>, mut batch: Batch, dest: &mut Database) -> Result<(), Error> {
if let Some(val) = try!(source.get(None, V7_LATEST_ERA_KEY).map_err(Error::Custom)) { if let Some(val) = source.get(None, V7_LATEST_ERA_KEY).map_err(Error::Custom)? {
try!(batch.insert(V7_LATEST_ERA_KEY.into(), val.clone().to_vec(), dest)); batch.insert(V7_LATEST_ERA_KEY.into(), val.clone().to_vec(), dest)?;
let mut era = decode::<u64>(&val); let mut era = decode::<u64>(&val);
loop { loop {
@ -166,7 +166,7 @@ impl OverlayRecentV7 {
r.out() r.out()
}; };
if let Some(journal_raw) = try!(source.get(None, &entry_key).map_err(Error::Custom)) { if let Some(journal_raw) = source.get(None, &entry_key).map_err(Error::Custom)? {
let rlp = Rlp::new(&journal_raw); let rlp = Rlp::new(&journal_raw);
let id: H256 = rlp.val_at(0); let id: H256 = rlp.val_at(0);
let mut inserted_keys: Vec<(H256, Bytes)> = Vec::new(); let mut inserted_keys: Vec<(H256, Bytes)> = Vec::new();
@ -202,7 +202,7 @@ impl OverlayRecentV7 {
stream.append(&deleted_keys); stream.append(&deleted_keys);
// and insert it into the new database. // and insert it into the new database.
try!(batch.insert(entry_key, stream.out(), dest)); batch.insert(entry_key, stream.out(), dest)?;
index += 1; index += 1;
} else { } else {
@ -233,7 +233,7 @@ impl Migration for OverlayRecentV7 {
let mut batch = Batch::new(config, col); let mut batch = Batch::new(config, col);
// check version metadata. // check version metadata.
match try!(source.get(None, V7_VERSION_KEY).map_err(Error::Custom)) { match source.get(None, V7_VERSION_KEY).map_err(Error::Custom)? {
Some(ref version) if decode::<u32>(&*version) == DB_VERSION => {} Some(ref version) if decode::<u32>(&*version) == DB_VERSION => {}
_ => return Err(Error::MigrationImpossible), // missing or wrong version _ => return Err(Error::MigrationImpossible), // missing or wrong version
} }
@ -255,10 +255,10 @@ impl Migration for OverlayRecentV7 {
} }
} }
try!(batch.insert(key, value.into_vec(), dest)); batch.insert(key, value.into_vec(), dest)?;
} }
try!(self.walk_journal(source.clone())); self.walk_journal(source.clone())?;
self.migrate_journal(source, batch, dest) self.migrate_journal(source, batch, dest)
} }
} }

View File

@ -32,7 +32,7 @@ use util::{Database, DBTransaction};
/// Can be called on upgraded database with no issues (will do nothing). /// Can be called on upgraded database with no issues (will do nothing).
pub fn generate_bloom(source: Arc<Database>, dest: &mut Database) -> Result<(), Error> { pub fn generate_bloom(source: Arc<Database>, dest: &mut Database) -> Result<(), Error> {
trace!(target: "migration", "Account bloom upgrade started"); trace!(target: "migration", "Account bloom upgrade started");
let best_block_hash = match try!(source.get(COL_EXTRA, b"best")) { let best_block_hash = match source.get(COL_EXTRA, b"best")? {
// no migration needed // no migration needed
None => { None => {
trace!(target: "migration", "No best block hash, skipping"); trace!(target: "migration", "No best block hash, skipping");
@ -40,7 +40,7 @@ pub fn generate_bloom(source: Arc<Database>, dest: &mut Database) -> Result<(),
}, },
Some(hash) => hash, Some(hash) => hash,
}; };
let best_block_header = match try!(source.get(COL_HEADERS, &best_block_hash)) { let best_block_header = match source.get(COL_HEADERS, &best_block_hash)? {
// no best block, nothing to do // no best block, nothing to do
None => { None => {
trace!(target: "migration", "No best block header, skipping"); trace!(target: "migration", "No best block header, skipping");
@ -58,9 +58,9 @@ pub fn generate_bloom(source: Arc<Database>, dest: &mut Database) -> Result<(),
source.clone(), source.clone(),
journaldb::Algorithm::OverlayRecent, journaldb::Algorithm::OverlayRecent,
COL_STATE); COL_STATE);
let account_trie = try!(TrieDB::new(state_db.as_hashdb(), &state_root).map_err(|e| Error::Custom(format!("Cannot open trie: {:?}", e)))); let account_trie = TrieDB::new(state_db.as_hashdb(), &state_root).map_err(|e| Error::Custom(format!("Cannot open trie: {:?}", e)))?;
for item in try!(account_trie.iter().map_err(|_| Error::MigrationImpossible)) { for item in account_trie.iter().map_err(|_| Error::MigrationImpossible)? {
let (ref account_key, _) = try!(item.map_err(|_| Error::MigrationImpossible)); let (ref account_key, _) = item.map_err(|_| Error::MigrationImpossible)?;
let account_key_hash = H256::from_slice(account_key); let account_key_hash = H256::from_slice(account_key);
bloom.set(&*account_key_hash); bloom.set(&*account_key_hash);
} }
@ -71,8 +71,8 @@ pub fn generate_bloom(source: Arc<Database>, dest: &mut Database) -> Result<(),
trace!(target: "migration", "Generated {} bloom updates", bloom_journal.entries.len()); trace!(target: "migration", "Generated {} bloom updates", bloom_journal.entries.len());
let mut batch = DBTransaction::new(dest); let mut batch = DBTransaction::new(dest);
try!(StateDB::commit_bloom(&mut batch, bloom_journal).map_err(|_| Error::Custom("Failed to commit bloom".to_owned()))); StateDB::commit_bloom(&mut batch, bloom_journal).map_err(|_| Error::Custom("Failed to commit bloom".to_owned()))?;
try!(dest.write(batch)); dest.write(batch)?;
trace!(target: "migration", "Finished bloom update"); trace!(target: "migration", "Finished bloom update");
@ -104,12 +104,12 @@ impl Migration for ToV10 {
let mut batch = Batch::new(config, col); let mut batch = Batch::new(config, col);
for (key, value) in source.iter(col) { for (key, value) in source.iter(col) {
self.progress.tick(); self.progress.tick();
try!(batch.insert(key.to_vec(), value.to_vec(), dest)); batch.insert(key.to_vec(), value.to_vec(), dest)?;
} }
try!(batch.commit(dest)); batch.commit(dest)?;
if col == COL_STATE { if col == COL_STATE {
try!(generate_bloom(source, dest)); generate_bloom(source, dest)?;
} }
Ok(()) Ok(())

View File

@ -63,17 +63,17 @@ impl Migration for ToV9 {
self.progress.tick(); self.progress.tick();
match self.extract { match self.extract {
Extract::Header => { Extract::Header => {
try!(batch.insert(key.to_vec(), Rlp::new(&value).at(0).as_raw().to_vec(), dest)) batch.insert(key.to_vec(), Rlp::new(&value).at(0).as_raw().to_vec(), dest)?
}, },
Extract::Body => { Extract::Body => {
let mut body = RlpStream::new_list(2); let mut body = RlpStream::new_list(2);
let block_rlp = Rlp::new(&value); let block_rlp = Rlp::new(&value);
body.append_raw(block_rlp.at(1).as_raw(), 1); body.append_raw(block_rlp.at(1).as_raw(), 1);
body.append_raw(block_rlp.at(2).as_raw(), 1); body.append_raw(block_rlp.at(2).as_raw(), 1);
try!(batch.insert(key.to_vec(), body.out(), dest)) batch.insert(key.to_vec(), body.out(), dest)?
}, },
Extract::All => { Extract::All => {
try!(batch.insert(key.to_vec(), value.to_vec(), dest)) batch.insert(key.to_vec(), value.to_vec(), dest)?
} }
} }
} }

View File

@ -698,10 +698,10 @@ impl MinerService for Miner {
let mut state = block.state().clone(); let mut state = block.state().clone();
let original_state = if analytics.state_diffing { Some(state.clone()) } else { None }; let original_state = if analytics.state_diffing { Some(state.clone()) } else { None };
let sender = try!(t.sender().map_err(|e| { let sender = t.sender().map_err(|e| {
let message = format!("Transaction malformed: {:?}", e); let message = format!("Transaction malformed: {:?}", e);
ExecutionError::TransactionMalformed(message) ExecutionError::TransactionMalformed(message)
})); })?;
let balance = state.balance(&sender); let balance = state.balance(&sender);
let needed_balance = t.value + t.gas * t.gas_price; let needed_balance = t.value + t.gas * t.gas_price;
if balance < needed_balance { if balance < needed_balance {
@ -709,7 +709,7 @@ impl MinerService for Miner {
state.add_balance(&sender, &(needed_balance - balance), CleanupMode::NoEmpty); state.add_balance(&sender, &(needed_balance - balance), CleanupMode::NoEmpty);
} }
let options = TransactOptions { tracing: analytics.transaction_tracing, vm_tracing: analytics.vm_tracing, check_nonce: false }; let options = TransactOptions { tracing: analytics.transaction_tracing, vm_tracing: analytics.vm_tracing, check_nonce: false };
let mut ret = try!(Executive::new(&mut state, &env_info, &*self.engine, chain.vm_factory()).transact(t, options)); let mut ret = Executive::new(&mut state, &env_info, &*self.engine, chain.vm_factory()).transact(t, options)?;
// TODO gav move this into Executive. // TODO gav move this into Executive.
ret.state_diff = original_state.map(|original| state.diff_from(original)); ret.state_diff = original_state.map(|original| state.diff_from(original));
@ -765,7 +765,7 @@ impl MinerService for Miner {
fn set_engine_signer(&self, address: Address, password: String) -> Result<(), AccountError> { fn set_engine_signer(&self, address: Address, password: String) -> Result<(), AccountError> {
if self.seals_internally { if self.seals_internally {
if let Some(ref ap) = self.accounts { if let Some(ref ap) = self.accounts {
try!(ap.sign(address.clone(), Some(password.clone()), Default::default())); ap.sign(address.clone(), Some(password.clone()), Default::default())?;
} }
let mut sealing_work = self.sealing_work.lock(); let mut sealing_work = self.sealing_work.lock();
sealing_work.enabled = self.engine.is_sealer(&address).unwrap_or(false); sealing_work.enabled = self.engine.is_sealer(&address).unwrap_or(false);
@ -1104,7 +1104,7 @@ impl MinerService for Miner {
result.and_then(|sealed| { result.and_then(|sealed| {
let n = sealed.header().number(); let n = sealed.header().number();
let h = sealed.header().hash(); let h = sealed.header().hash();
try!(chain.import_sealed_block(sealed)); chain.import_sealed_block(sealed)?;
info!(target: "miner", "Submitted block imported OK. #{}: {}", Colour::White.bold().paint(format!("{}", n)), Colour::White.bold().paint(h.hex())); info!(target: "miner", "Submitted block imported OK. #{}: {}", Colour::White.bold().paint(format!("{}", n)), Colour::White.bold().paint(h.hex()));
Ok(()) Ok(())
}) })

View File

@ -65,7 +65,7 @@ impl<F: Fn(PriceInfo) + Sync + Send + 'static> Handler<HttpStream> for SetPriceH
impl PriceInfo { impl PriceInfo {
pub fn get<F: Fn(PriceInfo) + Sync + Send + 'static>(set_price: F) -> Result<(), ()> { pub fn get<F: Fn(PriceInfo) + Sync + Send + 'static>(set_price: F) -> Result<(), ()> {
// TODO: Handle each error type properly // TODO: Handle each error type properly
let client = try!(Client::new().map_err(|_| ())); let client = Client::new().map_err(|_| ())?;
thread::spawn(move || { thread::spawn(move || {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
let url = FromStr::from_str("http://api.etherscan.io/api?module=stats&action=ethprice") let url = FromStr::from_str("http://api.etherscan.io/api?module=stats&action=ethprice")

View File

@ -264,7 +264,7 @@ struct VerifiedTransaction {
impl VerifiedTransaction { impl VerifiedTransaction {
fn new(transaction: SignedTransaction, origin: TransactionOrigin, min_block: Option<BlockNumber>) -> Result<Self, Error> { fn new(transaction: SignedTransaction, origin: TransactionOrigin, min_block: Option<BlockNumber>) -> Result<Self, Error> {
try!(transaction.sender()); transaction.sender()?;
Ok(VerifiedTransaction { Ok(VerifiedTransaction {
transaction: transaction, transaction: transaction,
origin: origin, origin: origin,
@ -732,9 +732,9 @@ impl TransactionQueue {
} }
// Verify signature // Verify signature
try!(tx.check_low_s()); tx.check_low_s()?;
let vtx = try!(VerifiedTransaction::new(tx, origin, min_block)); let vtx = VerifiedTransaction::new(tx, origin, min_block)?;
let client_account = fetch_account(&vtx.sender()); let client_account = fetch_account(&vtx.sender());
let cost = vtx.transaction.value + vtx.transaction.gas_price * vtx.transaction.gas; let cost = vtx.transaction.value + vtx.transaction.gas_price * vtx.transaction.gas;
@ -1138,13 +1138,13 @@ impl TransactionQueue {
if nonce > next_nonce { if nonce > next_nonce {
// We have a gap - put to future. // We have a gap - put to future.
// Insert transaction (or replace old one with lower gas price) // Insert transaction (or replace old one with lower gas price)
try!(check_too_cheap( check_too_cheap(
Self::replace_transaction(tx, state_nonce, min_gas_price, &mut self.future, &mut self.by_hash, &mut self.local_transactions) Self::replace_transaction(tx, state_nonce, min_gas_price, &mut self.future, &mut self.by_hash, &mut self.local_transactions)
)); )?;
// Enforce limit in Future // Enforce limit in Future
let removed = self.future.enforce_limit(&mut self.by_hash, &mut self.local_transactions); let removed = self.future.enforce_limit(&mut self.by_hash, &mut self.local_transactions);
// Return an error if this transaction was not imported because of limit. // Return an error if this transaction was not imported because of limit.
try!(check_if_removed(&address, &nonce, removed)); check_if_removed(&address, &nonce, removed)?;
debug!(target: "txqueue", "Importing transaction to future: {:?}", hash); debug!(target: "txqueue", "Importing transaction to future: {:?}", hash);
debug!(target: "txqueue", "status: {:?}", self.status()); debug!(target: "txqueue", "status: {:?}", self.status());
@ -1156,9 +1156,9 @@ impl TransactionQueue {
self.move_matching_future_to_current(address, nonce + U256::one(), state_nonce); self.move_matching_future_to_current(address, nonce + U256::one(), state_nonce);
// Replace transaction if any // Replace transaction if any
try!(check_too_cheap( check_too_cheap(
Self::replace_transaction(tx, state_nonce, min_gas_price, &mut self.current, &mut self.by_hash, &mut self.local_transactions) Self::replace_transaction(tx, state_nonce, min_gas_price, &mut self.current, &mut self.by_hash, &mut self.local_transactions)
)); )?;
// Keep track of highest nonce stored in current // Keep track of highest nonce stored in current
let new_max = self.last_nonces.get(&address).map_or(nonce, |n| cmp::max(nonce, *n)); let new_max = self.last_nonces.get(&address).map_or(nonce, |n| cmp::max(nonce, *n));
self.last_nonces.insert(address, new_max); self.last_nonces.insert(address, new_max);
@ -1168,7 +1168,7 @@ impl TransactionQueue {
// If some transaction were removed because of limit we need to update last_nonces also. // If some transaction were removed because of limit we need to update last_nonces also.
self.update_last_nonces(&removed); self.update_last_nonces(&removed);
// Trigger error if the transaction we are importing was removed. // Trigger error if the transaction we are importing was removed.
try!(check_if_removed(&address, &nonce, removed)); check_if_removed(&address, &nonce, removed)?;
debug!(target: "txqueue", "Imported transaction to current: {:?}", hash); debug!(target: "txqueue", "Imported transaction to current: {:?}", hash);
debug!(target: "txqueue", "status: {:?}", self.status()); debug!(target: "txqueue", "status: {:?}", self.status());

View File

@ -64,7 +64,7 @@ impl From<ethjson::spec::State> for PodState {
impl fmt::Display for PodState { impl fmt::Display for PodState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (add, acc) in &self.0 { for (add, acc) in &self.0 {
try!(writeln!(f, "{} => {}", add, acc)); writeln!(f, "{} => {}", add, acc)?;
} }
Ok(()) Ok(())
} }

View File

@ -77,7 +77,7 @@ impl ClientService {
) -> Result<ClientService, Error> ) -> Result<ClientService, Error>
{ {
let panic_handler = PanicHandler::new_in_arc(); let panic_handler = PanicHandler::new_in_arc();
let io_service = try!(IoService::<ClientIoMessage>::start()); let io_service = IoService::<ClientIoMessage>::start()?;
panic_handler.forward_from(&io_service); panic_handler.forward_from(&io_service);
info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name())); info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name()));
@ -94,7 +94,7 @@ impl ClientService {
db_config.wal = config.db_wal; db_config.wal = config.db_wal;
let pruning = config.pruning; let pruning = config.pruning;
let client = try!(Client::new(config, &spec, client_path, miner, io_service.channel(), &db_config)); let client = Client::new(config, &spec, client_path, miner, io_service.channel(), &db_config)?;
let snapshot_params = SnapServiceParams { let snapshot_params = SnapServiceParams {
engine: spec.engine.clone(), engine: spec.engine.clone(),
@ -105,14 +105,14 @@ impl ClientService {
snapshot_root: snapshot_path.into(), snapshot_root: snapshot_path.into(),
db_restore: client.clone(), db_restore: client.clone(),
}; };
let snapshot = Arc::new(try!(SnapshotService::new(snapshot_params))); let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
panic_handler.forward_from(&*client); panic_handler.forward_from(&*client);
let client_io = Arc::new(ClientIoHandler { let client_io = Arc::new(ClientIoHandler {
client: client.clone(), client: client.clone(),
snapshot: snapshot.clone(), snapshot: snapshot.clone(),
}); });
try!(io_service.register_handler(client_io)); io_service.register_handler(client_io)?;
spec.engine.register_message_channel(io_service.channel()); spec.engine.register_message_channel(io_service.channel());

View File

@ -100,12 +100,12 @@ impl Account {
return Ok(::rlp::NULL_RLP.to_vec()); return Ok(::rlp::NULL_RLP.to_vec());
} }
let db = try!(TrieDB::new(acct_db, &self.storage_root)); let db = TrieDB::new(acct_db, &self.storage_root)?;
let mut pairs = Vec::new(); let mut pairs = Vec::new();
for item in try!(db.iter()) { for item in db.iter()? {
let (k, v) = try!(item); let (k, v) = item?;
pairs.push((k, v)); pairs.push((k, v));
} }
@ -158,24 +158,24 @@ impl Account {
return Ok((ACC_EMPTY, None)); return Ok((ACC_EMPTY, None));
} }
let nonce = try!(rlp.val_at(0)); let nonce = rlp.val_at(0)?;
let balance = try!(rlp.val_at(1)); let balance = rlp.val_at(1)?;
let code_state: CodeState = { let code_state: CodeState = {
let raw: u8 = try!(rlp.val_at(2)); let raw: u8 = rlp.val_at(2)?;
try!(CodeState::from(raw)) CodeState::from(raw)?
}; };
// load the code if it exists. // load the code if it exists.
let (code_hash, new_code) = match code_state { let (code_hash, new_code) = match code_state {
CodeState::Empty => (SHA3_EMPTY, None), CodeState::Empty => (SHA3_EMPTY, None),
CodeState::Inline => { CodeState::Inline => {
let code: Bytes = try!(rlp.val_at(3)); let code: Bytes = rlp.val_at(3)?;
let code_hash = acct_db.insert(&code); let code_hash = acct_db.insert(&code);
(code_hash, Some(code)) (code_hash, Some(code))
} }
CodeState::Hash => { CodeState::Hash => {
let code_hash = try!(rlp.val_at(3)); let code_hash = rlp.val_at(3)?;
(code_hash, None) (code_hash, None)
} }
@ -185,12 +185,12 @@ impl Account {
{ {
let mut storage_trie = TrieDBMut::new(acct_db, &mut storage_root); let mut storage_trie = TrieDBMut::new(acct_db, &mut storage_root);
let pairs = try!(rlp.at(4)); let pairs = rlp.at(4)?;
for pair_rlp in pairs.iter() { for pair_rlp in pairs.iter() {
let k: Bytes = try!(pair_rlp.val_at(0)); let k: Bytes = pair_rlp.val_at(0)?;
let v: Bytes = try!(pair_rlp.val_at(1)); let v: Bytes = pair_rlp.val_at(1)?;
try!(storage_trie.insert(&k, &v)); storage_trie.insert(&k, &v)?;
} }
} }

View File

@ -89,21 +89,21 @@ impl AbridgedBlock {
let mut header: Header = Default::default(); let mut header: Header = Default::default();
header.set_parent_hash(parent_hash); header.set_parent_hash(parent_hash);
header.set_author(try!(rlp.val_at(0))); header.set_author(rlp.val_at(0)?);
header.set_state_root(try!(rlp.val_at(1))); header.set_state_root(rlp.val_at(1)?);
header.set_log_bloom(try!(rlp.val_at(2))); header.set_log_bloom(rlp.val_at(2)?);
header.set_difficulty(try!(rlp.val_at(3))); header.set_difficulty(rlp.val_at(3)?);
header.set_number(number); header.set_number(number);
header.set_gas_limit(try!(rlp.val_at(4))); header.set_gas_limit(rlp.val_at(4)?);
header.set_gas_used(try!(rlp.val_at(5))); header.set_gas_used(rlp.val_at(5)?);
header.set_timestamp(try!(rlp.val_at(6))); header.set_timestamp(rlp.val_at(6)?);
header.set_extra_data(try!(rlp.val_at(7))); header.set_extra_data(rlp.val_at(7)?);
let transactions = try!(rlp.val_at(8)); let transactions = rlp.val_at(8)?;
let uncles: Vec<Header> = try!(rlp.val_at(9)); let uncles: Vec<Header> = rlp.val_at(9)?;
header.set_transactions_root(ordered_trie_root( header.set_transactions_root(ordered_trie_root(
try!(rlp.at(8)).iter().map(|r| r.as_raw().to_owned()) rlp.at(8)?.iter().map(|r| r.as_raw().to_owned())
)); ));
header.set_receipts_root(receipts_root); header.set_receipts_root(receipts_root);
@ -113,7 +113,7 @@ impl AbridgedBlock {
let mut seal_fields = Vec::new(); let mut seal_fields = Vec::new();
for i in (HEADER_FIELDS + BLOCK_FIELDS)..rlp.item_count() { for i in (HEADER_FIELDS + BLOCK_FIELDS)..rlp.item_count() {
let seal_rlp = try!(rlp.at(i)); let seal_rlp = rlp.at(i)?;
seal_fields.push(seal_rlp.as_raw().to_owned()); seal_fields.push(seal_rlp.as_raw().to_owned());
} }

View File

@ -60,9 +60,9 @@ impl rlp::Decodable for ChunkInfo {
fn decode<D: rlp::Decoder>(decoder: &D) -> Result<Self, rlp::DecoderError> { fn decode<D: rlp::Decoder>(decoder: &D) -> Result<Self, rlp::DecoderError> {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let hash = try!(d.val_at(0)); let hash = d.val_at(0)?;
let len = try!(d.val_at(1)); let len = d.val_at(1)?;
let off = try!(d.val_at(2)); let off = d.val_at(2)?;
Ok(ChunkInfo(hash, len, off)) Ok(ChunkInfo(hash, len, off))
} }
} }
@ -88,7 +88,7 @@ impl PackedWriter {
/// Create a new "PackedWriter", to write into the file at the given path. /// Create a new "PackedWriter", to write into the file at the given path.
pub fn new(path: &Path) -> io::Result<Self> { pub fn new(path: &Path) -> io::Result<Self> {
Ok(PackedWriter { Ok(PackedWriter {
file: try!(File::create(path)), file: File::create(path)?,
state_hashes: Vec::new(), state_hashes: Vec::new(),
block_hashes: Vec::new(), block_hashes: Vec::new(),
cur_len: 0, cur_len: 0,
@ -98,7 +98,7 @@ impl PackedWriter {
impl SnapshotWriter for PackedWriter { impl SnapshotWriter for PackedWriter {
fn write_state_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()> { fn write_state_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()> {
try!(self.file.write_all(chunk)); self.file.write_all(chunk)?;
let len = chunk.len() as u64; let len = chunk.len() as u64;
self.state_hashes.push(ChunkInfo(hash, len, self.cur_len)); self.state_hashes.push(ChunkInfo(hash, len, self.cur_len));
@ -108,7 +108,7 @@ impl SnapshotWriter for PackedWriter {
} }
fn write_block_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()> { fn write_block_chunk(&mut self, hash: H256, chunk: &[u8]) -> io::Result<()> {
try!(self.file.write_all(chunk)); self.file.write_all(chunk)?;
let len = chunk.len() as u64; let len = chunk.len() as u64;
self.block_hashes.push(ChunkInfo(hash, len, self.cur_len)); self.block_hashes.push(ChunkInfo(hash, len, self.cur_len));
@ -130,7 +130,7 @@ impl SnapshotWriter for PackedWriter {
let manifest_rlp = stream.out(); let manifest_rlp = stream.out();
try!(self.file.write_all(&manifest_rlp)); self.file.write_all(&manifest_rlp)?;
let off = self.cur_len; let off = self.cur_len;
trace!(target: "snapshot_io", "writing manifest of len {} to offset {}", manifest_rlp.len(), off); trace!(target: "snapshot_io", "writing manifest of len {} to offset {}", manifest_rlp.len(), off);
@ -146,7 +146,7 @@ impl SnapshotWriter for PackedWriter {
(off >> 56) as u8, (off >> 56) as u8,
]; ];
try!(self.file.write_all(&off_bytes[..])); self.file.write_all(&off_bytes[..])?;
Ok(()) Ok(())
} }
@ -161,7 +161,7 @@ impl LooseWriter {
/// Create a new LooseWriter which will write into the given directory, /// Create a new LooseWriter which will write into the given directory,
/// creating it if it doesn't exist. /// creating it if it doesn't exist.
pub fn new(path: PathBuf) -> io::Result<Self> { pub fn new(path: PathBuf) -> io::Result<Self> {
try!(fs::create_dir_all(&path)); fs::create_dir_all(&path)?;
Ok(LooseWriter { Ok(LooseWriter {
dir: path, dir: path,
@ -173,8 +173,8 @@ impl LooseWriter {
let mut file_path = self.dir.clone(); let mut file_path = self.dir.clone();
file_path.push(hash.hex()); file_path.push(hash.hex());
let mut file = try!(File::create(file_path)); let mut file = File::create(file_path)?;
try!(file.write_all(chunk)); file.write_all(chunk)?;
Ok(()) Ok(())
} }
@ -194,8 +194,8 @@ impl SnapshotWriter for LooseWriter {
let mut path = self.dir.clone(); let mut path = self.dir.clone();
path.push("MANIFEST"); path.push("MANIFEST");
let mut file = try!(File::create(path)); let mut file = File::create(path)?;
try!(file.write_all(&rlp[..])); file.write_all(&rlp[..])?;
Ok(()) Ok(())
} }
@ -224,18 +224,18 @@ impl PackedReader {
/// This will fail if any io errors are encountered or the file /// This will fail if any io errors are encountered or the file
/// is not a valid packed snapshot. /// is not a valid packed snapshot.
pub fn new(path: &Path) -> Result<Option<Self>, ::error::Error> { pub fn new(path: &Path) -> Result<Option<Self>, ::error::Error> {
let mut file = try!(File::open(path)); let mut file = File::open(path)?;
let file_len = try!(file.metadata()).len(); let file_len = file.metadata()?.len();
if file_len < 8 { if file_len < 8 {
// ensure we don't seek before beginning. // ensure we don't seek before beginning.
return Ok(None); return Ok(None);
} }
try!(file.seek(SeekFrom::End(-8))); file.seek(SeekFrom::End(-8))?;
let mut off_bytes = [0u8; 8]; let mut off_bytes = [0u8; 8];
try!(file.read_exact(&mut off_bytes[..])); file.read_exact(&mut off_bytes[..])?;
let manifest_off: u64 = let manifest_off: u64 =
((off_bytes[7] as u64) << 56) + ((off_bytes[7] as u64) << 56) +
@ -252,20 +252,20 @@ impl PackedReader {
let mut manifest_buf = vec![0; manifest_len as usize]; let mut manifest_buf = vec![0; manifest_len as usize];
try!(file.seek(SeekFrom::Start(manifest_off))); file.seek(SeekFrom::Start(manifest_off))?;
try!(file.read_exact(&mut manifest_buf)); file.read_exact(&mut manifest_buf)?;
let rlp = UntrustedRlp::new(&manifest_buf); let rlp = UntrustedRlp::new(&manifest_buf);
let state: Vec<ChunkInfo> = try!(rlp.val_at(0)); let state: Vec<ChunkInfo> = rlp.val_at(0)?;
let blocks: Vec<ChunkInfo> = try!(rlp.val_at(1)); let blocks: Vec<ChunkInfo> = rlp.val_at(1)?;
let manifest = ManifestData { let manifest = ManifestData {
state_hashes: state.iter().map(|c| c.0).collect(), state_hashes: state.iter().map(|c| c.0).collect(),
block_hashes: blocks.iter().map(|c| c.0).collect(), block_hashes: blocks.iter().map(|c| c.0).collect(),
state_root: try!(rlp.val_at(2)), state_root: rlp.val_at(2)?,
block_number: try!(rlp.val_at(3)), block_number: rlp.val_at(3)?,
block_hash: try!(rlp.val_at(4)), block_hash: rlp.val_at(4)?,
}; };
Ok(Some(PackedReader { Ok(Some(PackedReader {
@ -288,10 +288,10 @@ impl SnapshotReader for PackedReader {
let mut file = &self.file; let mut file = &self.file;
try!(file.seek(SeekFrom::Start(off))); file.seek(SeekFrom::Start(off))?;
let mut buf = vec![0; len as usize]; let mut buf = vec![0; len as usize];
try!(file.read_exact(&mut buf[..])); file.read_exact(&mut buf[..])?;
Ok(buf) Ok(buf)
} }
@ -310,10 +310,10 @@ impl LooseReader {
let mut manifest_buf = Vec::new(); let mut manifest_buf = Vec::new();
dir.push("MANIFEST"); dir.push("MANIFEST");
let mut manifest_file = try!(File::open(&dir)); let mut manifest_file = File::open(&dir)?;
try!(manifest_file.read_to_end(&mut manifest_buf)); manifest_file.read_to_end(&mut manifest_buf)?;
let manifest = try!(ManifestData::from_rlp(&manifest_buf[..])); let manifest = ManifestData::from_rlp(&manifest_buf[..])?;
dir.pop(); dir.pop();
@ -334,9 +334,9 @@ impl SnapshotReader for LooseReader {
path.push(hash.hex()); path.push(hash.hex());
let mut buf = Vec::new(); let mut buf = Vec::new();
let mut file = try!(File::open(&path)); let mut file = File::open(&path)?;
try!(file.read_to_end(&mut buf)); file.read_to_end(&mut buf)?;
Ok(buf) Ok(buf)
} }

View File

@ -128,22 +128,22 @@ pub fn take_snapshot<W: SnapshotWriter + Send>(
writer: W, writer: W,
p: &Progress p: &Progress
) -> Result<(), Error> { ) -> Result<(), Error> {
let start_header = try!(chain.block_header(&block_at) let start_header = chain.block_header(&block_at)
.ok_or(Error::InvalidStartingBlock(BlockId::Hash(block_at)))); .ok_or(Error::InvalidStartingBlock(BlockId::Hash(block_at)))?;
let state_root = start_header.state_root(); let state_root = start_header.state_root();
let number = start_header.number(); let number = start_header.number();
info!("Taking snapshot starting at block {}", number); info!("Taking snapshot starting at block {}", number);
let writer = Mutex::new(writer); let writer = Mutex::new(writer);
let (state_hashes, block_hashes) = try!(scope(|scope| { let (state_hashes, block_hashes) = scope(|scope| {
let block_guard = scope.spawn(|| chunk_blocks(chain, block_at, &writer, p)); let block_guard = scope.spawn(|| chunk_blocks(chain, block_at, &writer, p));
let state_res = chunk_state(state_db, state_root, &writer, p); let state_res = chunk_state(state_db, state_root, &writer, p);
state_res.and_then(|state_hashes| { state_res.and_then(|state_hashes| {
block_guard.join().map(|block_hashes| (state_hashes, block_hashes)) block_guard.join().map(|block_hashes| (state_hashes, block_hashes))
}) })
})); })?;
info!("produced {} state chunks and {} block chunks.", state_hashes.len(), block_hashes.len()); info!("produced {} state chunks and {} block chunks.", state_hashes.len(), block_hashes.len());
@ -155,7 +155,7 @@ pub fn take_snapshot<W: SnapshotWriter + Send>(
block_hash: block_at, block_hash: block_at,
}; };
try!(writer.into_inner().finish(manifest_data)); writer.into_inner().finish(manifest_data)?;
p.done.store(true, Ordering::SeqCst); p.done.store(true, Ordering::SeqCst);
@ -186,9 +186,9 @@ impl<'a> BlockChunker<'a> {
for _ in 0..SNAPSHOT_BLOCKS { for _ in 0..SNAPSHOT_BLOCKS {
if self.current_hash == genesis_hash { break } if self.current_hash == genesis_hash { break }
let (block, receipts) = try!(self.chain.block(&self.current_hash) let (block, receipts) = self.chain.block(&self.current_hash)
.and_then(|b| self.chain.block_receipts(&self.current_hash).map(|r| (b, r))) .and_then(|b| self.chain.block_receipts(&self.current_hash).map(|r| (b, r)))
.ok_or(Error::BlockNotFound(self.current_hash))); .ok_or(Error::BlockNotFound(self.current_hash))?;
let view = BlockView::new(&block); let view = BlockView::new(&block);
let abridged_rlp = AbridgedBlock::from_block_view(&view).into_inner(); let abridged_rlp = AbridgedBlock::from_block_view(&view).into_inner();
@ -204,7 +204,7 @@ impl<'a> BlockChunker<'a> {
// cut off the chunk if too large. // cut off the chunk if too large.
if new_loaded_size > PREFERRED_CHUNK_SIZE && !self.rlps.is_empty() { if new_loaded_size > PREFERRED_CHUNK_SIZE && !self.rlps.is_empty() {
try!(self.write_chunk(last)); self.write_chunk(last)?;
loaded_size = pair.len(); loaded_size = pair.len();
} else { } else {
loaded_size = new_loaded_size; loaded_size = new_loaded_size;
@ -217,7 +217,7 @@ impl<'a> BlockChunker<'a> {
} }
if loaded_size != 0 { if loaded_size != 0 {
try!(self.write_chunk(last)); self.write_chunk(last)?;
} }
Ok(()) Ok(())
@ -230,9 +230,9 @@ impl<'a> BlockChunker<'a> {
fn write_chunk(&mut self, last: H256) -> Result<(), Error> { fn write_chunk(&mut self, last: H256) -> Result<(), Error> {
trace!(target: "snapshot", "prepared block chunk with {} blocks", self.rlps.len()); trace!(target: "snapshot", "prepared block chunk with {} blocks", self.rlps.len());
let (last_header, last_details) = try!(self.chain.block_header(&last) let (last_header, last_details) = self.chain.block_header(&last)
.and_then(|n| self.chain.block_details(&last).map(|d| (n, d))) .and_then(|n| self.chain.block_details(&last).map(|d| (n, d)))
.ok_or(Error::BlockNotFound(last))); .ok_or(Error::BlockNotFound(last))?;
let parent_number = last_header.number() - 1; let parent_number = last_header.number() - 1;
let parent_hash = last_header.parent_hash(); let parent_hash = last_header.parent_hash();
@ -254,7 +254,7 @@ impl<'a> BlockChunker<'a> {
let compressed = &self.snappy_buffer[..size]; let compressed = &self.snappy_buffer[..size];
let hash = compressed.sha3(); let hash = compressed.sha3();
try!(self.writer.lock().write_block_chunk(hash, compressed)); self.writer.lock().write_block_chunk(hash, compressed)?;
trace!(target: "snapshot", "wrote block chunk. hash: {}, size: {}, uncompressed size: {}", hash.hex(), size, raw_data.len()); trace!(target: "snapshot", "wrote block chunk. hash: {}, size: {}, uncompressed size: {}", hash.hex(), size, raw_data.len());
self.progress.size.fetch_add(size, Ordering::SeqCst); self.progress.size.fetch_add(size, Ordering::SeqCst);
@ -282,7 +282,7 @@ pub fn chunk_blocks<'a>(chain: &'a BlockChain, start_hash: H256, writer: &Mutex<
progress: progress, progress: progress,
}; };
try!(chunker.chunk_all()); chunker.chunk_all()?;
Ok(chunker.hashes) Ok(chunker.hashes)
} }
@ -310,7 +310,7 @@ impl<'a> StateChunker<'a> {
}; };
if self.cur_size + pair.len() >= PREFERRED_CHUNK_SIZE { if self.cur_size + pair.len() >= PREFERRED_CHUNK_SIZE {
try!(self.write_chunk()); self.write_chunk()?;
} }
self.cur_size += pair.len(); self.cur_size += pair.len();
@ -334,7 +334,7 @@ impl<'a> StateChunker<'a> {
let compressed = &self.snappy_buffer[..compressed_size]; let compressed = &self.snappy_buffer[..compressed_size];
let hash = compressed.sha3(); let hash = compressed.sha3();
try!(self.writer.lock().write_state_chunk(hash, compressed)); self.writer.lock().write_state_chunk(hash, compressed)?;
trace!(target: "snapshot", "wrote state chunk. size: {}, uncompressed size: {}", compressed_size, raw_data.len()); trace!(target: "snapshot", "wrote state chunk. size: {}, uncompressed size: {}", compressed_size, raw_data.len());
self.progress.accounts.fetch_add(num_entries, Ordering::SeqCst); self.progress.accounts.fetch_add(num_entries, Ordering::SeqCst);
@ -353,7 +353,7 @@ impl<'a> StateChunker<'a> {
/// Returns a list of hashes of chunks created, or any error it may /// Returns a list of hashes of chunks created, or any error it may
/// have encountered. /// have encountered.
pub fn chunk_state<'a>(db: &HashDB, root: &H256, writer: &Mutex<SnapshotWriter + 'a>, progress: &'a Progress) -> Result<Vec<H256>, Error> { pub fn chunk_state<'a>(db: &HashDB, root: &H256, writer: &Mutex<SnapshotWriter + 'a>, progress: &'a Progress) -> Result<Vec<H256>, Error> {
let account_trie = try!(TrieDB::new(db, &root)); let account_trie = TrieDB::new(db, &root)?;
let mut chunker = StateChunker { let mut chunker = StateChunker {
hashes: Vec::new(), hashes: Vec::new(),
@ -367,19 +367,19 @@ pub fn chunk_state<'a>(db: &HashDB, root: &H256, writer: &Mutex<SnapshotWriter +
let mut used_code = HashSet::new(); let mut used_code = HashSet::new();
// account_key here is the address' hash. // account_key here is the address' hash.
for item in try!(account_trie.iter()) { for item in account_trie.iter()? {
let (account_key, account_data) = try!(item); let (account_key, account_data) = item?;
let account = Account::from_thin_rlp(&*account_data); let account = Account::from_thin_rlp(&*account_data);
let account_key_hash = H256::from_slice(&account_key); let account_key_hash = H256::from_slice(&account_key);
let account_db = AccountDB::from_hash(db, account_key_hash); let account_db = AccountDB::from_hash(db, account_key_hash);
let fat_rlp = try!(account.to_fat_rlp(&account_db, &mut used_code)); let fat_rlp = account.to_fat_rlp(&account_db, &mut used_code)?;
try!(chunker.push(account_key, fat_rlp)); chunker.push(account_key, fat_rlp)?;
} }
if chunker.cur_size != 0 { if chunker.cur_size != 0 {
try!(chunker.write_chunk()); chunker.write_chunk()?;
} }
Ok(chunker.hashes) Ok(chunker.hashes)
@ -415,13 +415,13 @@ impl StateRebuilder {
// initialize the pairs vector with empty values so we have slots to write into. // initialize the pairs vector with empty values so we have slots to write into.
pairs.resize(rlp.item_count(), (H256::new(), Vec::new())); pairs.resize(rlp.item_count(), (H256::new(), Vec::new()));
let status = try!(rebuild_accounts( let status = rebuild_accounts(
self.db.as_hashdb_mut(), self.db.as_hashdb_mut(),
rlp, rlp,
&mut pairs, &mut pairs,
&self.known_code, &self.known_code,
flag flag
)); )?;
for (addr_hash, code_hash) in status.missing_code { for (addr_hash, code_hash) in status.missing_code {
self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash); self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash);
@ -442,7 +442,7 @@ impl StateRebuilder {
// batch trie writes // batch trie writes
{ {
let mut account_trie = if self.state_root != SHA3_NULL_RLP { let mut account_trie = if self.state_root != SHA3_NULL_RLP {
try!(TrieDBMut::from_existing(self.db.as_hashdb_mut(), &mut self.state_root)) TrieDBMut::from_existing(self.db.as_hashdb_mut(), &mut self.state_root)?
} else { } else {
TrieDBMut::new(self.db.as_hashdb_mut(), &mut self.state_root) TrieDBMut::new(self.db.as_hashdb_mut(), &mut self.state_root)
}; };
@ -453,14 +453,14 @@ impl StateRebuilder {
if &thin_rlp[..] != &empty_rlp[..] { if &thin_rlp[..] != &empty_rlp[..] {
self.bloom.set(&*hash); self.bloom.set(&*hash);
} }
try!(account_trie.insert(&hash, &thin_rlp)); account_trie.insert(&hash, &thin_rlp)?;
} }
} }
let bloom_journal = self.bloom.drain_journal(); let bloom_journal = self.bloom.drain_journal();
let mut batch = backing.transaction(); let mut batch = backing.transaction();
try!(StateDB::commit_bloom(&mut batch, bloom_journal)); StateDB::commit_bloom(&mut batch, bloom_journal)?;
try!(self.db.inject(&mut batch)); self.db.inject(&mut batch)?;
backing.write_buffered(batch); backing.write_buffered(batch);
trace!(target: "snapshot", "current state root: {:?}", self.state_root); trace!(target: "snapshot", "current state root: {:?}", self.state_root);
Ok(()) Ok(())
@ -500,15 +500,15 @@ fn rebuild_accounts(
for (account_rlp, out) in account_fat_rlps.into_iter().zip(out_chunk) { for (account_rlp, out) in account_fat_rlps.into_iter().zip(out_chunk) {
if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) } if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
let hash: H256 = try!(account_rlp.val_at(0)); let hash: H256 = account_rlp.val_at(0)?;
let fat_rlp = try!(account_rlp.at(1)); let fat_rlp = account_rlp.at(1)?;
let thin_rlp = { let thin_rlp = {
// fill out the storage trie and code while decoding. // fill out the storage trie and code while decoding.
let (acc, maybe_code) = { let (acc, maybe_code) = {
let mut acct_db = AccountDBMut::from_hash(db, hash); let mut acct_db = AccountDBMut::from_hash(db, hash);
try!(Account::from_fat_rlp(&mut acct_db, fat_rlp)) Account::from_fat_rlp(&mut acct_db, fat_rlp)?
}; };
let code_hash = acc.code_hash().clone(); let code_hash = acc.code_hash().clone();
@ -521,9 +521,9 @@ fn rebuild_accounts(
match known_code.get(&code_hash) { match known_code.get(&code_hash) {
Some(&first_with) => { Some(&first_with) => {
// if so, load it from the database. // if so, load it from the database.
let code = try!(AccountDB::from_hash(db, first_with) let code = AccountDB::from_hash(db, first_with)
.get(&code_hash) .get(&code_hash)
.ok_or_else(|| Error::MissingCode(vec![first_with]))); .ok_or_else(|| Error::MissingCode(vec![first_with]))?;
// and write it again under a different mangled key // and write it again under a different mangled key
AccountDBMut::from_hash(db, hash).emplace(code_hash, code); AccountDBMut::from_hash(db, hash).emplace(code_hash, code);
@ -586,7 +586,7 @@ impl BlockRebuilder {
Ok(BlockRebuilder { Ok(BlockRebuilder {
chain: chain, chain: chain,
db: db, db: db,
rng: try!(OsRng::new()), rng: OsRng::new()?,
disconnected: Vec::new(), disconnected: Vec::new(),
best_number: manifest.block_number, best_number: manifest.block_number,
best_hash: manifest.block_hash, best_hash: manifest.block_hash,
@ -613,22 +613,22 @@ impl BlockRebuilder {
} }
// todo: assert here that these values are consistent with chunks being in order. // todo: assert here that these values are consistent with chunks being in order.
let mut cur_number = try!(rlp.val_at::<u64>(0)) + 1; let mut cur_number = rlp.val_at::<u64>(0)? + 1;
let mut parent_hash = try!(rlp.val_at::<H256>(1)); let mut parent_hash = rlp.val_at::<H256>(1)?;
let parent_total_difficulty = try!(rlp.val_at::<U256>(2)); let parent_total_difficulty = rlp.val_at::<U256>(2)?;
for idx in 3..item_count { for idx in 3..item_count {
if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) } if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
let pair = try!(rlp.at(idx)); let pair = rlp.at(idx)?;
let abridged_rlp = try!(pair.at(0)).as_raw().to_owned(); let abridged_rlp = pair.at(0)?.as_raw().to_owned();
let abridged_block = AbridgedBlock::from_raw(abridged_rlp); let abridged_block = AbridgedBlock::from_raw(abridged_rlp);
let receipts: Vec<::receipt::Receipt> = try!(pair.val_at(1)); let receipts: Vec<::receipt::Receipt> = pair.val_at(1)?;
let receipts_root = ordered_trie_root( let receipts_root = ordered_trie_root(
try!(pair.at(1)).iter().map(|r| r.as_raw().to_owned()) pair.at(1)?.iter().map(|r| r.as_raw().to_owned())
); );
let block = try!(abridged_block.to_block(parent_hash, cur_number, receipts_root)); let block = abridged_block.to_block(parent_hash, cur_number, receipts_root)?;
let block_bytes = block.rlp_bytes(With); let block_bytes = block.rlp_bytes(With);
let is_best = cur_number == self.best_number; let is_best = cur_number == self.best_number;
@ -642,14 +642,14 @@ impl BlockRebuilder {
} }
} }
try!(verify_old_block( verify_old_block(
&mut self.rng, &mut self.rng,
&block.header, &block.header,
engine, engine,
&self.chain, &self.chain,
Some(&block_bytes), Some(&block_bytes),
is_best is_best
)); )?;
let mut batch = self.db.transaction(); let mut batch = self.db.transaction();
@ -693,7 +693,7 @@ impl BlockRebuilder {
let best_number = self.best_number; let best_number = self.best_number;
for num in (0..self.fed_blocks).map(|x| best_number - x) { for num in (0..self.fed_blocks).map(|x| best_number - x) {
let hash = try!(self.chain.block_hash(num).ok_or(Error::IncompleteChain)); let hash = self.chain.block_hash(num).ok_or(Error::IncompleteChain)?;
if let Some(canon_hash) = canonical.get(&num).cloned() { if let Some(canon_hash) = canonical.get(&num).cloned() {
if canon_hash != hash { if canon_hash != hash {

View File

@ -97,11 +97,11 @@ impl Restoration {
let state_chunks = manifest.state_hashes.iter().cloned().collect(); let state_chunks = manifest.state_hashes.iter().cloned().collect();
let block_chunks = manifest.block_hashes.iter().cloned().collect(); let block_chunks = manifest.block_hashes.iter().cloned().collect();
let raw_db = Arc::new(try!(Database::open(params.db_config, &*params.db_path.to_string_lossy()) let raw_db = Arc::new(Database::open(params.db_config, &*params.db_path.to_string_lossy())
.map_err(UtilError::SimpleString))); .map_err(UtilError::SimpleString)?);
let chain = BlockChain::new(Default::default(), params.genesis, raw_db.clone(), params.engine); let chain = BlockChain::new(Default::default(), params.genesis, raw_db.clone(), params.engine);
let blocks = try!(BlockRebuilder::new(chain, raw_db.clone(), &manifest)); let blocks = BlockRebuilder::new(chain, raw_db.clone(), &manifest)?;
let root = manifest.state_root.clone(); let root = manifest.state_root.clone();
Ok(Restoration { Ok(Restoration {
@ -122,12 +122,12 @@ impl Restoration {
// feeds a state chunk, aborts early if `flag` becomes false. // feeds a state chunk, aborts early if `flag` becomes false.
fn feed_state(&mut self, hash: H256, chunk: &[u8], flag: &AtomicBool) -> Result<(), Error> { fn feed_state(&mut self, hash: H256, chunk: &[u8], flag: &AtomicBool) -> Result<(), Error> {
if self.state_chunks_left.remove(&hash) { if self.state_chunks_left.remove(&hash) {
let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer)); let len = snappy::decompress_into(chunk, &mut self.snappy_buffer)?;
try!(self.state.feed(&self.snappy_buffer[..len], flag)); self.state.feed(&self.snappy_buffer[..len], flag)?;
if let Some(ref mut writer) = self.writer.as_mut() { if let Some(ref mut writer) = self.writer.as_mut() {
try!(writer.write_state_chunk(hash, chunk)); writer.write_state_chunk(hash, chunk)?;
} }
} }
@ -137,11 +137,11 @@ impl Restoration {
// feeds a block chunk // feeds a block chunk
fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &Engine, flag: &AtomicBool) -> Result<(), Error> { fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &Engine, flag: &AtomicBool) -> Result<(), Error> {
if self.block_chunks_left.remove(&hash) { if self.block_chunks_left.remove(&hash) {
let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer)); let len = snappy::decompress_into(chunk, &mut self.snappy_buffer)?;
try!(self.blocks.feed(&self.snappy_buffer[..len], engine, flag)); self.blocks.feed(&self.snappy_buffer[..len], engine, flag)?;
if let Some(ref mut writer) = self.writer.as_mut() { if let Some(ref mut writer) = self.writer.as_mut() {
try!(writer.write_block_chunk(hash, chunk)); writer.write_block_chunk(hash, chunk)?;
} }
} }
@ -167,13 +167,13 @@ impl Restoration {
} }
// check for missing code. // check for missing code.
try!(self.state.check_missing()); self.state.check_missing()?;
// connect out-of-order chunks and verify chain integrity. // connect out-of-order chunks and verify chain integrity.
try!(self.blocks.finalize(self.canonical_hashes)); self.blocks.finalize(self.canonical_hashes)?;
if let Some(writer) = self.writer { if let Some(writer) = self.writer {
try!(writer.finish(self.manifest)); writer.finish(self.manifest)?;
} }
self.guard.disarm(); self.guard.disarm();
@ -315,7 +315,7 @@ impl Service {
fn replace_client_db(&self) -> Result<(), Error> { fn replace_client_db(&self) -> Result<(), Error> {
let our_db = self.restoration_db(); let our_db = self.restoration_db();
try!(self.db_restore.restore_db(&*our_db.to_string_lossy())); self.db_restore.restore_db(&*our_db.to_string_lossy())?;
Ok(()) Ok(())
} }
@ -351,7 +351,7 @@ impl Service {
let _ = fs::remove_dir_all(&temp_dir); let _ = fs::remove_dir_all(&temp_dir);
let writer = try!(LooseWriter::new(temp_dir.clone())); let writer = LooseWriter::new(temp_dir.clone())?;
let guard = Guard::new(temp_dir.clone()); let guard = Guard::new(temp_dir.clone());
let res = client.take_snapshot(writer, BlockId::Number(num), &self.progress); let res = client.take_snapshot(writer, BlockId::Number(num), &self.progress);
@ -378,12 +378,12 @@ impl Service {
*reader = None; *reader = None;
if snapshot_dir.exists() { if snapshot_dir.exists() {
try!(fs::remove_dir_all(&snapshot_dir)); fs::remove_dir_all(&snapshot_dir)?;
} }
try!(fs::rename(temp_dir, &snapshot_dir)); fs::rename(temp_dir, &snapshot_dir)?;
*reader = Some(try!(LooseReader::new(snapshot_dir))); *reader = Some(LooseReader::new(snapshot_dir)?);
guard.disarm(); guard.disarm();
Ok(()) Ok(())
@ -410,11 +410,11 @@ impl Service {
} }
} }
try!(fs::create_dir_all(&rest_dir)); fs::create_dir_all(&rest_dir)?;
// make new restoration. // make new restoration.
let writer = match recover { let writer = match recover {
true => Some(try!(LooseWriter::new(self.temp_recovery_dir()))), true => Some(LooseWriter::new(self.temp_recovery_dir())?),
false => None false => None
}; };
@ -432,7 +432,7 @@ impl Service {
let state_chunks = params.manifest.state_hashes.len(); let state_chunks = params.manifest.state_hashes.len();
let block_chunks = params.manifest.block_hashes.len(); let block_chunks = params.manifest.block_hashes.len();
*res = Some(try!(Restoration::new(params))); *res = Some(Restoration::new(params)?);
*self.status.lock() = RestorationStatus::Ongoing { *self.status.lock() = RestorationStatus::Ongoing {
state_chunks: state_chunks as u32, state_chunks: state_chunks as u32,
@ -454,8 +454,8 @@ impl Service {
let recover = rest.as_ref().map_or(false, |rest| rest.writer.is_some()); let recover = rest.as_ref().map_or(false, |rest| rest.writer.is_some());
// destroy the restoration before replacing databases and snapshot. // destroy the restoration before replacing databases and snapshot.
try!(rest.take().map(Restoration::finalize).unwrap_or(Ok(()))); rest.take().map(Restoration::finalize).unwrap_or(Ok(()))?;
try!(self.replace_client_db()); self.replace_client_db()?;
if recover { if recover {
let mut reader = self.reader.write(); let mut reader = self.reader.write();
@ -465,13 +465,13 @@ impl Service {
if snapshot_dir.exists() { if snapshot_dir.exists() {
trace!(target: "snapshot", "removing old snapshot dir at {}", snapshot_dir.to_string_lossy()); trace!(target: "snapshot", "removing old snapshot dir at {}", snapshot_dir.to_string_lossy());
try!(fs::remove_dir_all(&snapshot_dir)); fs::remove_dir_all(&snapshot_dir)?;
} }
trace!(target: "snapshot", "copying restored snapshot files over"); trace!(target: "snapshot", "copying restored snapshot files over");
try!(fs::rename(self.temp_recovery_dir(), &snapshot_dir)); fs::rename(self.temp_recovery_dir(), &snapshot_dir)?;
*reader = Some(try!(LooseReader::new(snapshot_dir))); *reader = Some(LooseReader::new(snapshot_dir)?);
} }
let _ = fs::remove_dir_all(self.restoration_dir()); let _ = fs::remove_dir_all(self.restoration_dir());
@ -510,7 +510,7 @@ impl Service {
match is_done { match is_done {
true => { true => {
try!(db.flush().map_err(::util::UtilError::SimpleString)); db.flush().map_err(::util::UtilError::SimpleString)?;
drop(db); drop(db);
return self.finalize_restoration(&mut *restoration); return self.finalize_restoration(&mut *restoration);
}, },

View File

@ -259,7 +259,7 @@ impl Spec {
{ {
let mut t = factories.trie.create(db.as_hashdb_mut(), &mut root); let mut t = factories.trie.create(db.as_hashdb_mut(), &mut root);
for (address, account) in self.genesis_state.get().iter() { for (address, account) in self.genesis_state.get().iter() {
try!(t.insert(&**address, &account.rlp())); t.insert(&**address, &account.rlp())?;
} }
} }

View File

@ -450,8 +450,8 @@ impl Account {
let mut recorder = TrieRecorder::with_depth(from_level); let mut recorder = TrieRecorder::with_depth(from_level);
let trie = try!(TrieDB::new(db, &self.storage_root)); let trie = TrieDB::new(db, &self.storage_root)?;
let _ = try!(trie.get_recorded(&storage_key, &mut recorder)); let _ = trie.get_recorded(&storage_key, &mut recorder)?;
Ok(recorder.drain().into_iter().map(|r| r.data).collect()) Ok(recorder.drain().into_iter().map(|r| r.data).collect())
} }

View File

@ -515,11 +515,11 @@ impl State {
let options = TransactOptions { tracing: tracing, vm_tracing: false, check_nonce: true }; let options = TransactOptions { tracing: tracing, vm_tracing: false, check_nonce: true };
let vm_factory = self.factories.vm.clone(); let vm_factory = self.factories.vm.clone();
let e = try!(Executive::new(self, env_info, engine, &vm_factory).transact(t, options)); let e = Executive::new(self, env_info, engine, &vm_factory).transact(t, options)?;
// TODO uncomment once to_pod() works correctly. // TODO uncomment once to_pod() works correctly.
// trace!("Applied transaction. Diff:\n{}\n", state_diff::diff_pod(&old, &self.to_pod())); // trace!("Applied transaction. Diff:\n{}\n", state_diff::diff_pod(&old, &self.to_pod()));
try!(self.commit()); self.commit()?;
let receipt = Receipt::new(self.root().clone(), e.cumulative_gas_used, e.logs); let receipt = Receipt::new(self.root().clone(), e.cumulative_gas_used, e.logs);
trace!(target: "state", "Transaction receipt: {:?}", receipt); trace!(target: "state", "Transaction receipt: {:?}", receipt);
Ok(ApplyOutcome{receipt: receipt, trace: e.trace}) Ok(ApplyOutcome{receipt: receipt, trace: e.trace})
@ -551,15 +551,15 @@ impl State {
} }
{ {
let mut trie = try!(factories.trie.from_existing(db.as_hashdb_mut(), root)); let mut trie = factories.trie.from_existing(db.as_hashdb_mut(), root)?;
for (address, ref mut a) in accounts.iter_mut().filter(|&(_, ref a)| a.is_dirty()) { for (address, ref mut a) in accounts.iter_mut().filter(|&(_, ref a)| a.is_dirty()) {
a.state = AccountState::Committed; a.state = AccountState::Committed;
match a.account { match a.account {
Some(ref mut account) => { Some(ref mut account) => {
try!(trie.insert(address, &account.rlp())); trie.insert(address, &account.rlp())?;
}, },
None => { None => {
try!(trie.remove(address)); trie.remove(address)?;
}, },
} }
} }
@ -771,8 +771,8 @@ impl State {
/// `account_key` == sha3(address) /// `account_key` == sha3(address)
pub fn prove_account(&self, account_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> { pub fn prove_account(&self, account_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> {
let mut recorder = TrieRecorder::with_depth(from_level); let mut recorder = TrieRecorder::with_depth(from_level);
let trie = try!(TrieDB::new(self.db.as_hashdb(), &self.root)); let trie = TrieDB::new(self.db.as_hashdb(), &self.root)?;
let _ = try!(trie.get_recorded(&account_key, &mut recorder)); let _ = trie.get_recorded(&account_key, &mut recorder)?;
Ok(recorder.drain().into_iter().map(|r| r.data).collect()) Ok(recorder.drain().into_iter().map(|r| r.data).collect())
} }
@ -785,8 +785,8 @@ impl State {
pub fn prove_storage(&self, account_key: H256, storage_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> { pub fn prove_storage(&self, account_key: H256, storage_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> {
// TODO: probably could look into cache somehow but it's keyed by // TODO: probably could look into cache somehow but it's keyed by
// address, not sha3(address). // address, not sha3(address).
let trie = try!(TrieDB::new(self.db.as_hashdb(), &self.root)); let trie = TrieDB::new(self.db.as_hashdb(), &self.root)?;
let acc = match try!(trie.get(&account_key)) { let acc = match trie.get(&account_key)? {
Some(rlp) => Account::from_rlp(&rlp), Some(rlp) => Account::from_rlp(&rlp),
None => return Ok(Vec::new()), None => return Ok(Vec::new()),
}; };
@ -798,8 +798,8 @@ impl State {
/// Get code by address hash. /// Get code by address hash.
/// Only works when backed by a secure trie. /// Only works when backed by a secure trie.
pub fn code_by_address_hash(&self, account_key: H256) -> Result<Option<Bytes>, Box<TrieError>> { pub fn code_by_address_hash(&self, account_key: H256) -> Result<Option<Bytes>, Box<TrieError>> {
let trie = try!(TrieDB::new(self.db.as_hashdb(), &self.root)); let trie = TrieDB::new(self.db.as_hashdb(), &self.root)?;
let mut acc = match try!(trie.get(&account_key)) { let mut acc = match trie.get(&account_key)? {
Some(rlp) => Account::from_rlp(&rlp), Some(rlp) => Account::from_rlp(&rlp),
None => return Ok(None), None => return Ok(None),
}; };

View File

@ -195,9 +195,9 @@ impl StateDB {
pub fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError> { pub fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError> {
{ {
let mut bloom_lock = self.account_bloom.lock(); let mut bloom_lock = self.account_bloom.lock();
try!(Self::commit_bloom(batch, bloom_lock.drain_journal())); Self::commit_bloom(batch, bloom_lock.drain_journal())?;
} }
let records = try!(self.db.journal_under(batch, now, id)); let records = self.db.journal_under(batch, now, id)?;
self.commit_hash = Some(id.clone()); self.commit_hash = Some(id.clone());
self.commit_number = Some(now); self.commit_number = Some(now);
Ok(records) Ok(records)

View File

@ -73,7 +73,7 @@ impl Encodable for BlockTracesBloom {
impl Decodable for BlockTracesBloomGroup { impl Decodable for BlockTracesBloomGroup {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let blooms = try!(Decodable::decode(decoder)); let blooms = Decodable::decode(decoder)?;
let group = BlockTracesBloomGroup { let group = BlockTracesBloomGroup {
blooms: blooms blooms: blooms
}; };

View File

@ -80,9 +80,9 @@ pub enum Existance {
impl fmt::Display for Existance { impl fmt::Display for Existance {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Existance::Born => try!(write!(f, "+++")), Existance::Born => write!(f, "+++")?,
Existance::Alive => try!(write!(f, "***")), Existance::Alive => write!(f, "***")?,
Existance::Died => try!(write!(f, "XXX")), Existance::Died => write!(f, "XXX")?,
} }
Ok(()) Ok(())
} }
@ -117,24 +117,24 @@ impl fmt::Display for AccountDiff {
use util::bytes::ToPretty; use util::bytes::ToPretty;
match self.nonce { match self.nonce {
Diff::Born(ref x) => try!(write!(f, " non {}", x)), Diff::Born(ref x) => write!(f, " non {}", x)?,
Diff::Changed(ref pre, ref post) => try!(write!(f, "#{} ({} {} {})", post, pre, if pre > post {"-"} else {"+"}, *max(pre, post) - * min(pre, post))), Diff::Changed(ref pre, ref post) => write!(f, "#{} ({} {} {})", post, pre, if pre > post {"-"} else {"+"}, *max(pre, post) - * min(pre, post))?,
_ => {}, _ => {},
} }
match self.balance { match self.balance {
Diff::Born(ref x) => try!(write!(f, " bal {}", x)), Diff::Born(ref x) => write!(f, " bal {}", x)?,
Diff::Changed(ref pre, ref post) => try!(write!(f, "${} ({} {} {})", post, pre, if pre > post {"-"} else {"+"}, *max(pre, post) - *min(pre, post))), Diff::Changed(ref pre, ref post) => write!(f, "${} ({} {} {})", post, pre, if pre > post {"-"} else {"+"}, *max(pre, post) - *min(pre, post))?,
_ => {}, _ => {},
} }
if let Diff::Born(ref x) = self.code { if let Diff::Born(ref x) = self.code {
try!(write!(f, " code {}", x.pretty())); write!(f, " code {}", x.pretty())?;
} }
try!(write!(f, "\n")); write!(f, "\n")?;
for (k, dv) in &self.storage { for (k, dv) in &self.storage {
match *dv { match *dv {
Diff::Born(ref v) => try!(write!(f, " + {} => {}\n", interpreted_hash(k), interpreted_hash(v))), Diff::Born(ref v) => write!(f, " + {} => {}\n", interpreted_hash(k), interpreted_hash(v))?,
Diff::Changed(ref pre, ref post) => try!(write!(f, " * {} => {} (was {})\n", interpreted_hash(k), interpreted_hash(post), interpreted_hash(pre))), Diff::Changed(ref pre, ref post) => write!(f, " * {} => {} (was {})\n", interpreted_hash(k), interpreted_hash(post), interpreted_hash(pre))?,
Diff::Died(_) => try!(write!(f, " X {}\n", interpreted_hash(k))), Diff::Died(_) => write!(f, " X {}\n", interpreted_hash(k))?,
_ => {}, _ => {},
} }
} }

View File

@ -50,9 +50,9 @@ impl Decodable for LogEntry {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let entry = LogEntry { let entry = LogEntry {
address: try!(d.val_at(0)), address: d.val_at(0)?,
topics: try!(d.val_at(1)), topics: d.val_at(1)?,
data: try!(d.val_at(2)), data: d.val_at(2)?,
}; };
Ok(entry) Ok(entry)
} }

View File

@ -64,10 +64,10 @@ impl Decodable for Receipt {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let receipt = Receipt { let receipt = Receipt {
state_root: try!(d.val_at(0)), state_root: d.val_at(0)?,
gas_used: try!(d.val_at(1)), gas_used: d.val_at(1)?,
log_bloom: try!(d.val_at(2)), log_bloom: d.val_at(2)?,
logs: try!(d.val_at(3)), logs: d.val_at(3)?,
}; };
Ok(receipt) Ok(receipt)
} }

View File

@ -53,11 +53,11 @@ impl ManifestData {
pub fn from_rlp(raw: &[u8]) -> Result<Self, DecoderError> { pub fn from_rlp(raw: &[u8]) -> Result<Self, DecoderError> {
let decoder = UntrustedRlp::new(raw); let decoder = UntrustedRlp::new(raw);
let state_hashes: Vec<H256> = try!(decoder.val_at(0)); let state_hashes: Vec<H256> = decoder.val_at(0)?;
let block_hashes: Vec<H256> = try!(decoder.val_at(1)); let block_hashes: Vec<H256> = decoder.val_at(1)?;
let state_root: H256 = try!(decoder.val_at(2)); let state_root: H256 = decoder.val_at(2)?;
let block_number: u64 = try!(decoder.val_at(3)); let block_number: u64 = decoder.val_at(3)?;
let block_hash: H256 = try!(decoder.val_at(4)); let block_hash: H256 = decoder.val_at(4)?;
Ok(ManifestData { Ok(ManifestData {
state_hashes: state_hashes, state_hashes: state_hashes,

View File

@ -41,7 +41,7 @@ impl StateDiff {
impl fmt::Display for StateDiff { impl fmt::Display for StateDiff {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (add, acc) in &self.raw { for (add, acc) in &self.raw {
try!(write!(f, "{} {}: {}", acc.existance(), add, acc)); write!(f, "{} {}: {}", acc.existance(), add, acc)?;
} }
Ok(()) Ok(())
} }

View File

@ -86,7 +86,7 @@ impl Encodable for Error {
impl Decodable for Error { impl Decodable for Error {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
use self::Error::*; use self::Error::*;
let value: u8 = try!(decoder.as_rlp().as_val()); let value: u8 = decoder.as_rlp().as_val()?;
match value { match value {
0 => Ok(OutOfGas), 0 => Ok(OutOfGas),
1 => Ok(BadJumpDestination), 1 => Ok(BadJumpDestination),

View File

@ -66,11 +66,11 @@ impl Encodable for FlatTrace {
impl Decodable for FlatTrace { impl Decodable for FlatTrace {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let v: Vec<usize> = try!(d.val_at(3)); let v: Vec<usize> = d.val_at(3)?;
let res = FlatTrace { let res = FlatTrace {
action: try!(d.val_at(0)), action: d.val_at(0)?,
result: try!(d.val_at(1)), result: d.val_at(1)?,
subtraces: try!(d.val_at(2)), subtraces: d.val_at(2)?,
trace_address: v.into_iter().collect(), trace_address: v.into_iter().collect(),
}; };
@ -109,7 +109,7 @@ impl Encodable for FlatTransactionTraces {
impl Decodable for FlatTransactionTraces { impl Decodable for FlatTransactionTraces {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
Ok(FlatTransactionTraces(try!(Decodable::decode(decoder)))) Ok(FlatTransactionTraces(Decodable::decode(decoder)?))
} }
} }
@ -150,7 +150,7 @@ impl Encodable for FlatBlockTraces {
impl Decodable for FlatBlockTraces { impl Decodable for FlatBlockTraces {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
Ok(FlatBlockTraces(try!(Decodable::decode(decoder)))) Ok(FlatBlockTraces(Decodable::decode(decoder)?))
} }
} }

View File

@ -48,8 +48,8 @@ impl Decodable for CallResult {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = CallResult { let res = CallResult {
gas_used: try!(d.val_at(0)), gas_used: d.val_at(0)?,
output: try!(d.val_at(1)), output: d.val_at(1)?,
}; };
Ok(res) Ok(res)
@ -81,9 +81,9 @@ impl Decodable for CreateResult {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = CreateResult { let res = CreateResult {
gas_used: try!(d.val_at(0)), gas_used: d.val_at(0)?,
code: try!(d.val_at(1)), code: d.val_at(1)?,
address: try!(d.val_at(2)), address: d.val_at(2)?,
}; };
Ok(res) Ok(res)
@ -144,12 +144,12 @@ impl Decodable for Call {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = Call { let res = Call {
from: try!(d.val_at(0)), from: d.val_at(0)?,
to: try!(d.val_at(1)), to: d.val_at(1)?,
value: try!(d.val_at(2)), value: d.val_at(2)?,
gas: try!(d.val_at(3)), gas: d.val_at(3)?,
input: try!(d.val_at(4)), input: d.val_at(4)?,
call_type: try!(d.val_at(5)), call_type: d.val_at(5)?,
}; };
Ok(res) Ok(res)
@ -204,10 +204,10 @@ impl Decodable for Create {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = Create { let res = Create {
from: try!(d.val_at(0)), from: d.val_at(0)?,
value: try!(d.val_at(1)), value: d.val_at(1)?,
gas: try!(d.val_at(2)), gas: d.val_at(2)?,
init: try!(d.val_at(3)), init: d.val_at(3)?,
}; };
Ok(res) Ok(res)
@ -255,9 +255,9 @@ impl Decodable for Suicide {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = Suicide { let res = Suicide {
address: try!(d.val_at(0)), address: d.val_at(0)?,
refund_address: try!(d.val_at(1)), refund_address: d.val_at(1)?,
balance: try!(d.val_at(2)), balance: d.val_at(2)?,
}; };
Ok(res) Ok(res)
@ -300,7 +300,7 @@ impl Encodable for Action {
impl Decodable for Action { impl Decodable for Action {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let action_type: u8 = try!(d.val_at(0)); let action_type: u8 = d.val_at(0)?;
match action_type { match action_type {
0 => d.val_at(1).map(Action::Call), 0 => d.val_at(1).map(Action::Call),
1 => d.val_at(1).map(Action::Create), 1 => d.val_at(1).map(Action::Create),
@ -371,7 +371,7 @@ impl Encodable for Res {
impl Decodable for Res { impl Decodable for Res {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let action_type: u8 = try!(d.val_at(0)); let action_type: u8 = d.val_at(0)?;
match action_type { match action_type {
0 => d.val_at(1).map(Res::Call), 0 => d.val_at(1).map(Res::Call),
1 => d.val_at(1).map(Res::Create), 1 => d.val_at(1).map(Res::Create),
@ -415,8 +415,8 @@ impl Decodable for MemoryDiff {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
Ok(MemoryDiff { Ok(MemoryDiff {
offset: try!(d.val_at(0)), offset: d.val_at(0)?,
data: try!(d.val_at(1)), data: d.val_at(1)?,
}) })
} }
} }
@ -443,8 +443,8 @@ impl Decodable for StorageDiff {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
Ok(StorageDiff { Ok(StorageDiff {
location: try!(d.val_at(0)), location: d.val_at(0)?,
value: try!(d.val_at(1)), value: d.val_at(1)?,
}) })
} }
} }
@ -477,10 +477,10 @@ impl Decodable for VMExecutedOperation {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
Ok(VMExecutedOperation { Ok(VMExecutedOperation {
gas_used: try!(d.val_at(0)), gas_used: d.val_at(0)?,
stack_push: try!(d.val_at(1)), stack_push: d.val_at(1)?,
mem_diff: try!(d.val_at(2)), mem_diff: d.val_at(2)?,
store_diff: try!(d.val_at(3)), store_diff: d.val_at(3)?,
}) })
} }
} }
@ -513,10 +513,10 @@ impl Decodable for VMOperation {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = VMOperation { let res = VMOperation {
pc: try!(d.val_at(0)), pc: d.val_at(0)?,
instruction: try!(d.val_at(1)), instruction: d.val_at(1)?,
gas_cost: try!(d.val_at(2)), gas_cost: d.val_at(2)?,
executed: try!(d.val_at(3)), executed: d.val_at(3)?,
}; };
Ok(res) Ok(res)
@ -552,10 +552,10 @@ impl Decodable for VMTrace {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp(); let d = decoder.as_rlp();
let res = VMTrace { let res = VMTrace {
parent_step: try!(d.val_at(0)), parent_step: d.val_at(0)?,
code: try!(d.val_at(1)), code: d.val_at(1)?,
operations: try!(d.val_at(2)), operations: d.val_at(2)?,
subs: try!(d.val_at(3)), subs: d.val_at(3)?,
}; };
Ok(res) Ok(res)

View File

@ -48,7 +48,7 @@ impl Decodable for Action {
if rlp.is_empty() { if rlp.is_empty() {
Ok(Action::Create) Ok(Action::Create)
} else { } else {
Ok(Action::Call(try!(rlp.as_val()))) Ok(Action::Call(rlp.as_val()?))
} }
} }
} }
@ -247,16 +247,16 @@ impl Decodable for SignedTransaction {
} }
Ok(SignedTransaction { Ok(SignedTransaction {
unsigned: Transaction { unsigned: Transaction {
nonce: try!(d.val_at(0)), nonce: d.val_at(0)?,
gas_price: try!(d.val_at(1)), gas_price: d.val_at(1)?,
gas: try!(d.val_at(2)), gas: d.val_at(2)?,
action: try!(d.val_at(3)), action: d.val_at(3)?,
value: try!(d.val_at(4)), value: d.val_at(4)?,
data: try!(d.val_at(5)), data: d.val_at(5)?,
}, },
v: try!(d.val_at(6)), v: d.val_at(6)?,
r: try!(d.val_at(7)), r: d.val_at(7)?,
s: try!(d.val_at(8)), s: d.val_at(8)?,
hash: Cell::new(None), hash: Cell::new(None),
sender: Cell::new(None), sender: Cell::new(None),
}) })
@ -338,7 +338,7 @@ impl SignedTransaction {
match sender { match sender {
Some(s) => Ok(s), Some(s) => Ok(s),
None => { None => {
let s = public_to_address(&try!(self.public_key())); let s = public_to_address(&self.public_key()?);
self.sender.set(Some(s)); self.sender.set(Some(s));
Ok(s) Ok(s)
} }
@ -347,7 +347,7 @@ impl SignedTransaction {
/// Returns the public key of the sender. /// Returns the public key of the sender.
pub fn public_key(&self) -> Result<Public, Error> { pub fn public_key(&self) -> Result<Public, Error> {
Ok(try!(recover(&self.signature(), &self.unsigned.hash(self.network_id())))) Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?)
} }
/// Do basic validation, checking for valid signature and minimum gas, /// Do basic validation, checking for valid signature and minimum gas,
@ -363,7 +363,7 @@ impl SignedTransaction {
Some(1) if allow_network_id_of_one => {}, Some(1) if allow_network_id_of_one => {},
_ => return Err(TransactionError::InvalidNetworkId.into()), _ => return Err(TransactionError::InvalidNetworkId.into()),
} }
try!(self.sender()); self.sender()?;
if self.gas < U256::from(self.gas_required(&schedule)) { if self.gas < U256::from(self.gas_required(&schedule)) {
Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into())
} else { } else {

View File

@ -51,19 +51,19 @@ impl HeapSizeOf for PreverifiedBlock {
/// Phase 1 quick block verification. Only does checks that are cheap. Operates on a single block /// Phase 1 quick block verification. Only does checks that are cheap. Operates on a single block
pub fn verify_block_basic(header: &Header, bytes: &[u8], engine: &Engine) -> Result<(), Error> { pub fn verify_block_basic(header: &Header, bytes: &[u8], engine: &Engine) -> Result<(), Error> {
try!(verify_header_params(&header, engine)); verify_header_params(&header, engine)?;
try!(verify_block_integrity(bytes, &header.transactions_root(), &header.uncles_hash())); verify_block_integrity(bytes, &header.transactions_root(), &header.uncles_hash())?;
try!(engine.verify_block_basic(&header, Some(bytes))); engine.verify_block_basic(&header, Some(bytes))?;
for u in try!(UntrustedRlp::new(bytes).at(2)).iter().map(|rlp| rlp.as_val::<Header>()) { for u in UntrustedRlp::new(bytes).at(2)?.iter().map(|rlp| rlp.as_val::<Header>()) {
let u = try!(u); let u = u?;
try!(verify_header_params(&u, engine)); verify_header_params(&u, engine)?;
try!(engine.verify_block_basic(&u, None)); engine.verify_block_basic(&u, None)?;
} }
// Verify transactions. // Verify transactions.
// TODO: either use transaction views or cache the decoded transactions. // TODO: either use transaction views or cache the decoded transactions.
let v = BlockView::new(bytes); let v = BlockView::new(bytes);
for t in v.transactions() { for t in v.transactions() {
try!(engine.verify_transaction_basic(&t, &header)); engine.verify_transaction_basic(&t, &header)?;
} }
Ok(()) Ok(())
} }
@ -73,9 +73,9 @@ pub fn verify_block_basic(header: &Header, bytes: &[u8], engine: &Engine) -> Res
/// Returns a `PreverifiedBlock` structure populated with transactions /// Returns a `PreverifiedBlock` structure populated with transactions
pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine, check_seal: bool) -> Result<PreverifiedBlock, Error> { pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine, check_seal: bool) -> Result<PreverifiedBlock, Error> {
if check_seal { if check_seal {
try!(engine.verify_block_unordered(&header, Some(&bytes))); engine.verify_block_unordered(&header, Some(&bytes))?;
for u in try!(UntrustedRlp::new(&bytes).at(2)).iter().map(|rlp| rlp.as_val::<Header>()) { for u in UntrustedRlp::new(&bytes).at(2)?.iter().map(|rlp| rlp.as_val::<Header>()) {
try!(engine.verify_block_unordered(&try!(u), None)); engine.verify_block_unordered(&u?, None)?;
} }
} }
// Verify transactions. // Verify transactions.
@ -83,7 +83,7 @@ pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine, che
{ {
let v = BlockView::new(&bytes); let v = BlockView::new(&bytes);
for t in v.transactions() { for t in v.transactions() {
try!(engine.verify_transaction(&t, &header)); engine.verify_transaction(&t, &header)?;
transactions.push(t); transactions.push(t);
} }
} }
@ -97,11 +97,11 @@ pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine, che
/// Phase 3 verification. Check block information against parent and uncles. /// Phase 3 verification. Check block information against parent and uncles.
pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: &BlockProvider) -> Result<(), Error> { pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: &BlockProvider) -> Result<(), Error> {
// TODO: verify timestamp // TODO: verify timestamp
let parent = try!(bc.block_header(&header.parent_hash()).ok_or_else(|| Error::from(BlockError::UnknownParent(header.parent_hash().clone())))); let parent = bc.block_header(&header.parent_hash()).ok_or_else(|| Error::from(BlockError::UnknownParent(header.parent_hash().clone())))?;
try!(verify_parent(&header, &parent)); verify_parent(&header, &parent)?;
try!(engine.verify_block_family(&header, &parent, Some(bytes))); engine.verify_block_family(&header, &parent, Some(bytes))?;
let num_uncles = try!(UntrustedRlp::new(bytes).at(2)).item_count(); let num_uncles = UntrustedRlp::new(bytes).at(2)?.item_count();
if num_uncles != 0 { if num_uncles != 0 {
if num_uncles > engine.maximum_uncle_count() { if num_uncles > engine.maximum_uncle_count() {
return Err(From::from(BlockError::TooManyUncles(OutOfBounds { min: None, max: Some(engine.maximum_uncle_count()), found: num_uncles }))); return Err(From::from(BlockError::TooManyUncles(OutOfBounds { min: None, max: Some(engine.maximum_uncle_count()), found: num_uncles })));
@ -124,8 +124,8 @@ pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: &
} }
} }
for uncle in try!(UntrustedRlp::new(bytes).at(2)).iter().map(|rlp| rlp.as_val::<Header>()) { for uncle in UntrustedRlp::new(bytes).at(2)?.iter().map(|rlp| rlp.as_val::<Header>()) {
let uncle = try!(uncle); let uncle = uncle?;
if excluded.contains(&uncle.hash()) { if excluded.contains(&uncle.hash()) {
return Err(From::from(BlockError::UncleInChain(uncle.hash()))) return Err(From::from(BlockError::UncleInChain(uncle.hash())))
} }
@ -157,7 +157,7 @@ pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: &
// cB.p^7 -------------/ // cB.p^7 -------------/
// cB.p^8 // cB.p^8
let mut expected_uncle_parent = header.parent_hash().clone(); let mut expected_uncle_parent = header.parent_hash().clone();
let uncle_parent = try!(bc.block_header(&uncle.parent_hash()).ok_or_else(|| Error::from(BlockError::UnknownUncleParent(uncle.parent_hash().clone())))); let uncle_parent = bc.block_header(&uncle.parent_hash()).ok_or_else(|| Error::from(BlockError::UnknownUncleParent(uncle.parent_hash().clone())))?;
for _ in 0..depth { for _ in 0..depth {
match bc.block_details(&expected_uncle_parent) { match bc.block_details(&expected_uncle_parent) {
Some(details) => { Some(details) => {
@ -170,8 +170,8 @@ pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: &
return Err(From::from(BlockError::UncleParentNotInChain(uncle_parent.hash()))); return Err(From::from(BlockError::UncleParentNotInChain(uncle_parent.hash())));
} }
try!(verify_parent(&uncle, &uncle_parent)); verify_parent(&uncle, &uncle_parent)?;
try!(engine.verify_block_family(&uncle, &uncle_parent, Some(bytes))); engine.verify_block_family(&uncle, &uncle_parent, Some(bytes))?;
} }
} }
Ok(()) Ok(())
@ -234,12 +234,12 @@ fn verify_parent(header: &Header, parent: &Header) -> Result<(), Error> {
/// Verify block data against header: transactions root and uncles hash. /// Verify block data against header: transactions root and uncles hash.
fn verify_block_integrity(block: &[u8], transactions_root: &H256, uncles_hash: &H256) -> Result<(), Error> { fn verify_block_integrity(block: &[u8], transactions_root: &H256, uncles_hash: &H256) -> Result<(), Error> {
let block = UntrustedRlp::new(block); let block = UntrustedRlp::new(block);
let tx = try!(block.at(1)); let tx = block.at(1)?;
let expected_root = &ordered_trie_root(tx.iter().map(|r| r.as_raw().to_vec())); //TODO: get rid of vectors here let expected_root = &ordered_trie_root(tx.iter().map(|r| r.as_raw().to_vec())); //TODO: get rid of vectors here
if expected_root != transactions_root { if expected_root != transactions_root {
return Err(From::from(BlockError::InvalidTransactionsRoot(Mismatch { expected: expected_root.clone(), found: transactions_root.clone() }))) return Err(From::from(BlockError::InvalidTransactionsRoot(Mismatch { expected: expected_root.clone(), found: transactions_root.clone() })))
} }
let expected_uncles = &try!(block.at(2)).as_raw().sha3(); let expected_uncles = &block.at(2)?.as_raw().sha3();
if expected_uncles != uncles_hash { if expected_uncles != uncles_hash {
return Err(From::from(BlockError::InvalidUnclesHash(Mismatch { expected: expected_uncles.clone(), found: uncles_hash.clone() }))) return Err(From::from(BlockError::InvalidUnclesHash(Mismatch { expected: expected_uncles.clone(), found: uncles_hash.clone() })))
} }

View File

@ -158,7 +158,7 @@ pub mod aes {
let mut encryptor = CbcDecryptor::new(AesSafe128Decryptor::new(k), PkcsPadding, iv.to_vec()); let mut encryptor = CbcDecryptor::new(AesSafe128Decryptor::new(k), PkcsPadding, iv.to_vec());
let len = dest.len(); let len = dest.len();
let mut buffer = RefWriteBuffer::new(dest); let mut buffer = RefWriteBuffer::new(dest);
try!(encryptor.decrypt(&mut RefReadBuffer::new(encrypted), &mut buffer, true)); encryptor.decrypt(&mut RefReadBuffer::new(encrypted), &mut buffer, true)?;
Ok(len - buffer.remaining()) Ok(len - buffer.remaining())
} }
} }
@ -179,7 +179,7 @@ pub mod ecdh {
temp temp
}; };
let publ = try!(key::PublicKey::from_slice(context, &pdata)); let publ = key::PublicKey::from_slice(context, &pdata)?;
// no way to create SecretKey from raw byte array. // no way to create SecretKey from raw byte array.
let sec: &key::SecretKey = unsafe { ::std::mem::transmute(secret) }; let sec: &key::SecretKey = unsafe { ::std::mem::transmute(secret) };
let shared = ecdh::SharedSecret::new_raw(context, &publ, sec); let shared = ecdh::SharedSecret::new_raw(context, &publ, sec);
@ -206,7 +206,7 @@ pub mod ecies {
let r = Random.generate() let r = Random.generate()
.expect("context known to have key-generation capabilities; qed"); .expect("context known to have key-generation capabilities; qed");
let z = try!(ecdh::agree(r.secret(), public)); let z = ecdh::agree(r.secret(), public)?;
let mut key = [0u8; 32]; let mut key = [0u8; 32];
let mut mkey = [0u8; 32]; let mut mkey = [0u8; 32];
kdf(&z, &[0u8; 0], &mut key); kdf(&z, &[0u8; 0], &mut key);
@ -243,7 +243,7 @@ pub mod ecies {
let r = Random.generate() let r = Random.generate()
.expect("context known to have key-generation capabilities"); .expect("context known to have key-generation capabilities");
let z = try!(ecdh::agree(r.secret(), public)); let z = ecdh::agree(r.secret(), public)?;
let mut key = [0u8; 32]; let mut key = [0u8; 32];
let mut mkey = [0u8; 32]; let mut mkey = [0u8; 32];
kdf(&z, &[0u8; 0], &mut key); kdf(&z, &[0u8; 0], &mut key);
@ -274,7 +274,7 @@ pub mod ecies {
let e = &encrypted[1..]; let e = &encrypted[1..];
let p = Public::from_slice(&e[0..64]); let p = Public::from_slice(&e[0..64]);
let z = try!(ecdh::agree(secret, &p)); let z = ecdh::agree(secret, &p)?;
let mut key = [0u8; 32]; let mut key = [0u8; 32];
kdf(&z, &[0u8; 0], &mut key); kdf(&z, &[0u8; 0], &mut key);
let ekey = &key[0..16]; let ekey = &key[0..16];
@ -314,7 +314,7 @@ pub mod ecies {
let e = encrypted; let e = encrypted;
let p = Public::from_slice(&e[0..64]); let p = Public::from_slice(&e[0..64]);
let z = try!(ecdh::agree(secret, &p)); let z = ecdh::agree(secret, &p)?;
let mut key = [0u8; 32]; let mut key = [0u8; 32];
kdf(&z, &[0u8; 0], &mut key); kdf(&z, &[0u8; 0], &mut key);
let ekey = &key[0..16]; let ekey = &key[0..16];

View File

@ -160,37 +160,37 @@ fn execute<S, I>(command: I) -> Result<String, Error> where I: IntoIterator<Item
return if args.cmd_info { return if args.cmd_info {
let display_mode = DisplayMode::new(&args); let display_mode = DisplayMode::new(&args);
let secret = try!(args.arg_secret.parse().map_err(|_| EthkeyError::InvalidSecret)); let secret = args.arg_secret.parse().map_err(|_| EthkeyError::InvalidSecret)?;
let keypair = try!(KeyPair::from_secret(secret)); let keypair = KeyPair::from_secret(secret)?;
Ok(display(keypair, display_mode)) Ok(display(keypair, display_mode))
} else if args.cmd_generate { } else if args.cmd_generate {
let display_mode = DisplayMode::new(&args); let display_mode = DisplayMode::new(&args);
let keypair = if args.cmd_random { let keypair = if args.cmd_random {
Random.generate() Random.generate()
} else if args.cmd_prefix { } else if args.cmd_prefix {
let prefix = try!(args.arg_prefix.from_hex()); let prefix = args.arg_prefix.from_hex()?;
let iterations = try!(usize::from_str_radix(&args.arg_iterations, 10)); let iterations = usize::from_str_radix(&args.arg_iterations, 10)?;
Prefix::new(prefix, iterations).generate() Prefix::new(prefix, iterations).generate()
} else if args.cmd_brain { } else if args.cmd_brain {
Brain::new(args.arg_seed).generate() Brain::new(args.arg_seed).generate()
} else { } else {
unreachable!(); unreachable!();
}; };
Ok(display(try!(keypair), display_mode)) Ok(display(keypair?, display_mode))
} else if args.cmd_sign { } else if args.cmd_sign {
let secret = try!(args.arg_secret.parse().map_err(|_| EthkeyError::InvalidSecret)); let secret = args.arg_secret.parse().map_err(|_| EthkeyError::InvalidSecret)?;
let message = try!(args.arg_message.parse().map_err(|_| EthkeyError::InvalidMessage)); let message = args.arg_message.parse().map_err(|_| EthkeyError::InvalidMessage)?;
let signature = try!(sign(&secret, &message)); let signature = sign(&secret, &message)?;
Ok(format!("{}", signature)) Ok(format!("{}", signature))
} else if args.cmd_verify { } else if args.cmd_verify {
let signature = try!(args.arg_signature.parse().map_err(|_| EthkeyError::InvalidSignature)); let signature = args.arg_signature.parse().map_err(|_| EthkeyError::InvalidSignature)?;
let message = try!(args.arg_message.parse().map_err(|_| EthkeyError::InvalidMessage)); let message = args.arg_message.parse().map_err(|_| EthkeyError::InvalidMessage)?;
let ok = if args.cmd_public { let ok = if args.cmd_public {
let public = try!(args.arg_public.parse().map_err(|_| EthkeyError::InvalidPublic)); let public = args.arg_public.parse().map_err(|_| EthkeyError::InvalidPublic)?;
try!(verify_public(&public, &signature, &message)) verify_public(&public, &signature, &message)?
} else if args.cmd_address { } else if args.cmd_address {
let address = try!(args.arg_address.parse().map_err(|_| EthkeyError::InvalidAddress)); let address = args.arg_address.parse().map_err(|_| EthkeyError::InvalidAddress)?;
try!(verify_address(&address, &signature, &message)) verify_address(&address, &signature, &message)?
} else { } else {
unreachable!(); unreachable!();
}; };

View File

@ -35,8 +35,8 @@ pub struct KeyPair {
impl fmt::Display for KeyPair { impl fmt::Display for KeyPair {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(writeln!(f, "secret: {}", self.secret.to_hex())); writeln!(f, "secret: {}", self.secret.to_hex())?;
try!(writeln!(f, "public: {}", self.public.to_hex())); writeln!(f, "public: {}", self.public.to_hex())?;
write!(f, "address: {}", self.address().to_hex()) write!(f, "address: {}", self.address().to_hex())
} }
} }
@ -45,8 +45,8 @@ impl KeyPair {
/// Create a pair from secret key /// Create a pair from secret key
pub fn from_secret(secret: Secret) -> Result<KeyPair, Error> { pub fn from_secret(secret: Secret) -> Result<KeyPair, Error> {
let context = &SECP256K1; let context = &SECP256K1;
let s: key::SecretKey = try!(key::SecretKey::from_slice(context, &secret[..])); let s: key::SecretKey = key::SecretKey::from_slice(context, &secret[..])?;
let pub_key = try!(key::PublicKey::from_secret_key(context, &s)); let pub_key = key::PublicKey::from_secret_key(context, &s)?;
let serialized = pub_key.serialize_vec(context, false); let serialized = pub_key.serialize_vec(context, false);
let mut public = Public::default(); let mut public = Public::default();

View File

@ -34,7 +34,7 @@ impl Prefix {
impl Generator for Prefix { impl Generator for Prefix {
fn generate(self) -> Result<KeyPair, Error> { fn generate(self) -> Result<KeyPair, Error> {
for _ in 0..self.iterations { for _ in 0..self.iterations {
let keypair = try!(Random.generate()); let keypair = Random.generate()?;
if keypair.address().starts_with(&self.prefix) { if keypair.address().starts_with(&self.prefix) {
return Ok(keypair) return Ok(keypair)
} }

View File

@ -23,8 +23,8 @@ pub struct Random;
impl Generator for Random { impl Generator for Random {
fn generate(self) -> Result<KeyPair, Error> { fn generate(self) -> Result<KeyPair, Error> {
let context = &SECP256K1; let context = &SECP256K1;
let mut rng = try!(OsRng::new()); let mut rng = OsRng::new()?;
let (sec, publ) = try!(context.generate_keypair(&mut rng)); let (sec, publ) = context.generate_keypair(&mut rng)?;
Ok(KeyPair::from_keypair(sec, publ)) Ok(KeyPair::from_keypair(sec, publ))
} }

View File

@ -171,7 +171,7 @@ pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
let context = &SECP256K1; let context = &SECP256K1;
// no way to create from raw byte array. // no way to create from raw byte array.
let sec: &SecretKey = unsafe { mem::transmute(secret) }; let sec: &SecretKey = unsafe { mem::transmute(secret) };
let s = try!(context.sign_recoverable(&try!(SecpMessage::from_slice(&message[..])), sec)); let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, sec)?;
let (rec_id, data) = s.serialize_compact(context); let (rec_id, data) = s.serialize_compact(context);
let mut data_arr = [0; 65]; let mut data_arr = [0; 65];
@ -183,7 +183,7 @@ pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
pub fn verify_public(public: &Public, signature: &Signature, message: &Message) -> Result<bool, Error> { pub fn verify_public(public: &Public, signature: &Signature, message: &Message) -> Result<bool, Error> {
let context = &SECP256K1; let context = &SECP256K1;
let rsig = try!(RecoverableSignature::from_compact(context, &signature[0..64], try!(RecoveryId::from_i32(signature[64] as i32)))); let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let sig = rsig.to_standard(context); let sig = rsig.to_standard(context);
let pdata: [u8; 65] = { let pdata: [u8; 65] = {
@ -192,8 +192,8 @@ pub fn verify_public(public: &Public, signature: &Signature, message: &Message)
temp temp
}; };
let publ = try!(PublicKey::from_slice(context, &pdata)); let publ = PublicKey::from_slice(context, &pdata)?;
match context.verify(&try!(SecpMessage::from_slice(&message[..])), &sig, &publ) { match context.verify(&SecpMessage::from_slice(&message[..])?, &sig, &publ) {
Ok(_) => Ok(true), Ok(_) => Ok(true),
Err(SecpError::IncorrectSignature) => Ok(false), Err(SecpError::IncorrectSignature) => Ok(false),
Err(x) => Err(Error::from(x)) Err(x) => Err(Error::from(x))
@ -201,15 +201,15 @@ pub fn verify_public(public: &Public, signature: &Signature, message: &Message)
} }
pub fn verify_address(address: &Address, signature: &Signature, message: &Message) -> Result<bool, Error> { pub fn verify_address(address: &Address, signature: &Signature, message: &Message) -> Result<bool, Error> {
let public = try!(recover(signature, message)); let public = recover(signature, message)?;
let recovered_address = public_to_address(&public); let recovered_address = public_to_address(&public);
Ok(address == &recovered_address) Ok(address == &recovered_address)
} }
pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error> { pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error> {
let context = &SECP256K1; let context = &SECP256K1;
let rsig = try!(RecoverableSignature::from_compact(context, &signature[0..64], try!(RecoveryId::from_i32(signature[64] as i32)))); let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let pubkey = try!(context.recover(&try!(SecpMessage::from_slice(&message[..])), &rsig)); let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?;
let serialized = pubkey.serialize_vec(context, false); let serialized = pubkey.serialize_vec(context, false);
let mut public = Public::default(); let mut public = Public::default();

View File

@ -113,7 +113,7 @@ impl Crypto {
let (derived_left_bits, derived_right_bits) = match self.kdf { let (derived_left_bits, derived_right_bits) = match self.kdf {
Kdf::Pbkdf2(ref params) => crypto::derive_key_iterations(password, &params.salt, params.c), Kdf::Pbkdf2(ref params) => crypto::derive_key_iterations(password, &params.salt, params.c),
Kdf::Scrypt(ref params) => try!(crypto::derive_key_scrypt(password, &params.salt, params.n, params.p, params.r)), Kdf::Scrypt(ref params) => crypto::derive_key_scrypt(password, &params.salt, params.n, params.p, params.r)?,
}; };
let mac = crypto::derive_mac(&derived_right_bits, &self.ciphertext).keccak256(); let mac = crypto::derive_mac(&derived_right_bits, &self.ciphertext).keccak256();
@ -171,22 +171,22 @@ impl SafeAccount {
} }
pub fn sign(&self, password: &str, message: &Message) -> Result<Signature, Error> { pub fn sign(&self, password: &str, message: &Message) -> Result<Signature, Error> {
let secret = try!(self.crypto.secret(password)); let secret = self.crypto.secret(password)?;
sign(&secret, message).map_err(From::from) sign(&secret, message).map_err(From::from)
} }
pub fn decrypt(&self, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { pub fn decrypt(&self, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
let secret = try!(self.crypto.secret(password)); let secret = self.crypto.secret(password)?;
crypto::ecies::decrypt(&secret, shared_mac, message).map_err(From::from) crypto::ecies::decrypt(&secret, shared_mac, message).map_err(From::from)
} }
pub fn public(&self, password: &str) -> Result<Public, Error> { pub fn public(&self, password: &str) -> Result<Public, Error> {
let secret = try!(self.crypto.secret(password)); let secret = self.crypto.secret(password)?;
Ok(try!(KeyPair::from_secret(secret)).public().clone()) Ok(KeyPair::from_secret(secret)?.public().clone())
} }
pub fn change_password(&self, old_password: &str, new_password: &str, iterations: u32) -> Result<Self, Error> { pub fn change_password(&self, old_password: &str, new_password: &str, iterations: u32) -> Result<Self, Error> {
let secret = try!(self.crypto.secret(old_password)); let secret = self.crypto.secret(old_password)?;
let result = SafeAccount { let result = SafeAccount {
id: self.id.clone(), id: self.id.clone(),
version: self.version.clone(), version: self.version.clone(),

View File

@ -93,11 +93,11 @@ fn main() {
fn key_dir(location: &str) -> Result<Box<KeyDirectory>, Error> { fn key_dir(location: &str) -> Result<Box<KeyDirectory>, Error> {
let dir: Box<KeyDirectory> = match location { let dir: Box<KeyDirectory> = match location {
"parity" => Box::new(try!(ParityDirectory::create(DirectoryType::Main))), "parity" => Box::new(ParityDirectory::create(DirectoryType::Main)?),
"parity-test" => Box::new(try!(ParityDirectory::create(DirectoryType::Testnet))), "parity-test" => Box::new(ParityDirectory::create(DirectoryType::Testnet)?),
"geth" => Box::new(try!(GethDirectory::create(DirectoryType::Main))), "geth" => Box::new(GethDirectory::create(DirectoryType::Main)?),
"geth-test" => Box::new(try!(GethDirectory::create(DirectoryType::Testnet))), "geth-test" => Box::new(GethDirectory::create(DirectoryType::Testnet)?),
path => Box::new(try!(DiskDirectory::create(path))), path => Box::new(DiskDirectory::create(path)?),
}; };
Ok(dir) Ok(dir)
@ -112,9 +112,9 @@ fn format_accounts(accounts: &[Address]) -> String {
} }
fn load_password(path: &str) -> Result<String, Error> { fn load_password(path: &str) -> Result<String, Error> {
let mut file = try!(fs::File::open(path)); let mut file = fs::File::open(path)?;
let mut password = String::new(); let mut password = String::new();
try!(file.read_to_string(&mut password)); file.read_to_string(&mut password)?;
// drop EOF // drop EOF
let _ = password.pop(); let _ = password.pop();
Ok(password) Ok(password)
@ -125,48 +125,48 @@ fn execute<S, I>(command: I) -> Result<String, Error> where I: IntoIterator<Item
.and_then(|d| d.argv(command).decode()) .and_then(|d| d.argv(command).decode())
.unwrap_or_else(|e| e.exit()); .unwrap_or_else(|e| e.exit());
let store = try!(EthStore::open(try!(key_dir(&args.flag_dir)))); let store = EthStore::open(key_dir(&args.flag_dir)?)?;
return if args.cmd_insert { return if args.cmd_insert {
let secret = try!(args.arg_secret.parse().map_err(|_| Error::InvalidSecret)); let secret = args.arg_secret.parse().map_err(|_| Error::InvalidSecret)?;
let password = try!(load_password(&args.arg_password)); let password = load_password(&args.arg_password)?;
let address = try!(store.insert_account(secret, &password)); let address = store.insert_account(secret, &password)?;
Ok(format!("0x{:?}", address)) Ok(format!("0x{:?}", address))
} else if args.cmd_change_pwd { } else if args.cmd_change_pwd {
let address = try!(args.arg_address.parse().map_err(|_| Error::InvalidAccount)); let address = args.arg_address.parse().map_err(|_| Error::InvalidAccount)?;
let old_pwd = try!(load_password(&args.arg_old_pwd)); let old_pwd = load_password(&args.arg_old_pwd)?;
let new_pwd = try!(load_password(&args.arg_new_pwd)); let new_pwd = load_password(&args.arg_new_pwd)?;
let ok = store.change_password(&address, &old_pwd, &new_pwd).is_ok(); let ok = store.change_password(&address, &old_pwd, &new_pwd).is_ok();
Ok(format!("{}", ok)) Ok(format!("{}", ok))
} else if args.cmd_list { } else if args.cmd_list {
let accounts = try!(store.accounts()); let accounts = store.accounts()?;
Ok(format_accounts(&accounts)) Ok(format_accounts(&accounts))
} else if args.cmd_import { } else if args.cmd_import {
let src = try!(key_dir(&args.flag_src)); let src = key_dir(&args.flag_src)?;
let dst = try!(key_dir(&args.flag_dir)); let dst = key_dir(&args.flag_dir)?;
let accounts = try!(import_accounts(&*src, &*dst)); let accounts = import_accounts(&*src, &*dst)?;
Ok(format_accounts(&accounts)) Ok(format_accounts(&accounts))
} else if args.cmd_import_wallet { } else if args.cmd_import_wallet {
let wallet = try!(PresaleWallet::open(&args.arg_path)); let wallet = PresaleWallet::open(&args.arg_path)?;
let password = try!(load_password(&args.arg_password)); let password = load_password(&args.arg_password)?;
let kp = try!(wallet.decrypt(&password)); let kp = wallet.decrypt(&password)?;
let address = try!(store.insert_account(kp.secret().clone(), &password)); let address = store.insert_account(kp.secret().clone(), &password)?;
Ok(format!("0x{:?}", address)) Ok(format!("0x{:?}", address))
} else if args.cmd_remove { } else if args.cmd_remove {
let address = try!(args.arg_address.parse().map_err(|_| Error::InvalidAccount)); let address = args.arg_address.parse().map_err(|_| Error::InvalidAccount)?;
let password = try!(load_password(&args.arg_password)); let password = load_password(&args.arg_password)?;
let ok = store.remove_account(&address, &password).is_ok(); let ok = store.remove_account(&address, &password).is_ok();
Ok(format!("{}", ok)) Ok(format!("{}", ok))
} else if args.cmd_sign { } else if args.cmd_sign {
let address = try!(args.arg_address.parse().map_err(|_| Error::InvalidAccount)); let address = args.arg_address.parse().map_err(|_| Error::InvalidAccount)?;
let message = try!(args.arg_message.parse().map_err(|_| Error::InvalidMessage)); let message = args.arg_message.parse().map_err(|_| Error::InvalidMessage)?;
let password = try!(load_password(&args.arg_password)); let password = load_password(&args.arg_password)?;
let signature = try!(store.sign(&address, &password, &message)); let signature = store.sign(&address, &password, &message)?;
Ok(format!("0x{:?}", signature)) Ok(format!("0x{:?}", signature))
} else if args.cmd_public { } else if args.cmd_public {
let address = try!(args.arg_address.parse().map_err(|_| Error::InvalidAccount)); let address = args.arg_address.parse().map_err(|_| Error::InvalidAccount)?;
let password = try!(load_password(&args.arg_password)); let password = load_password(&args.arg_password)?;
let public = try!(store.public(&address, &password)); let public = store.public(&address, &password)?;
Ok(format!("0x{:?}", public)) Ok(format!("0x{:?}", public))
} else { } else {
Ok(format!("{}", USAGE)) Ok(format!("{}", USAGE))

View File

@ -29,8 +29,8 @@ fn restrict_permissions_to_owner(file_path: &Path) -> Result<(), i32> {
use std::ffi; use std::ffi;
use libc; use libc;
let cstr = try!(ffi::CString::new(&*file_path.to_string_lossy()) let cstr = ffi::CString::new(&*file_path.to_string_lossy())
.map_err(|_| -1)); .map_err(|_| -1)?;
match unsafe { libc::chmod(cstr.as_ptr(), libc::S_IWUSR | libc::S_IRUSR) } { match unsafe { libc::chmod(cstr.as_ptr(), libc::S_IWUSR | libc::S_IRUSR) } {
0 => Ok(()), 0 => Ok(()),
x => Err(x), x => Err(x),
@ -48,7 +48,7 @@ pub struct DiskDirectory {
impl DiskDirectory { impl DiskDirectory {
pub fn create<P>(path: P) -> Result<Self, Error> where P: AsRef<Path> { pub fn create<P>(path: P) -> Result<Self, Error> where P: AsRef<Path> {
try!(fs::create_dir_all(&path)); fs::create_dir_all(&path)?;
Ok(Self::at(path)) Ok(Self::at(path))
} }
@ -62,7 +62,7 @@ impl DiskDirectory {
fn files(&self) -> Result<HashMap<PathBuf, SafeAccount>, Error> { fn files(&self) -> Result<HashMap<PathBuf, SafeAccount>, Error> {
// it's not done using one iterator cause // it's not done using one iterator cause
// there is an issue with rustc and it takes tooo much time to compile // there is an issue with rustc and it takes tooo much time to compile
let paths = try!(fs::read_dir(&self.path)) let paths = fs::read_dir(&self.path)?
.flat_map(Result::ok) .flat_map(Result::ok)
.filter(|entry| { .filter(|entry| {
let metadata = entry.metadata().ok(); let metadata = entry.metadata().ok();
@ -102,7 +102,7 @@ impl DiskDirectory {
impl KeyDirectory for DiskDirectory { impl KeyDirectory for DiskDirectory {
fn load(&self) -> Result<Vec<SafeAccount>, Error> { fn load(&self) -> Result<Vec<SafeAccount>, Error> {
let accounts = try!(self.files()) let accounts = self.files()?
.into_iter() .into_iter()
.map(|(_, account)| account) .map(|(_, account)| account)
.collect(); .collect();
@ -134,8 +134,8 @@ impl KeyDirectory for DiskDirectory {
keyfile_path.push(filename.as_str()); keyfile_path.push(filename.as_str());
// save the file // save the file
let mut file = try!(fs::File::create(&keyfile_path)); let mut file = fs::File::create(&keyfile_path)?;
try!(keyfile.write(&mut file).map_err(|e| Error::Custom(format!("{:?}", e)))); keyfile.write(&mut file).map_err(|e| Error::Custom(format!("{:?}", e)))?;
if let Err(_) = restrict_permissions_to_owner(keyfile_path.as_path()) { if let Err(_) = restrict_permissions_to_owner(keyfile_path.as_path()) {
fs::remove_file(keyfile_path).expect("Expected to remove recently created file"); fs::remove_file(keyfile_path).expect("Expected to remove recently created file");
@ -149,7 +149,7 @@ impl KeyDirectory for DiskDirectory {
fn remove(&self, account: &SafeAccount) -> Result<(), Error> { fn remove(&self, account: &SafeAccount) -> Result<(), Error> {
// enumerate all entries in keystore // enumerate all entries in keystore
// and find entry with given address // and find entry with given address
let to_remove = try!(self.files()) let to_remove = self.files()?
.into_iter() .into_iter()
.find(|&(_, ref acc)| acc == account); .find(|&(_, ref acc)| acc == account);

View File

@ -66,7 +66,7 @@ pub struct GethDirectory {
impl GethDirectory { impl GethDirectory {
pub fn create(t: DirectoryType) -> Result<Self, Error> { pub fn create(t: DirectoryType) -> Result<Self, Error> {
let result = GethDirectory { let result = GethDirectory {
dir: try!(DiskDirectory::create(geth_keystore(t))), dir: DiskDirectory::create(geth_keystore(t))?,
}; };
Ok(result) Ok(result)

View File

@ -45,7 +45,7 @@ pub struct ParityDirectory {
impl ParityDirectory { impl ParityDirectory {
pub fn create(t: DirectoryType) -> Result<Self, Error> { pub fn create(t: DirectoryType) -> Result<Self, Error> {
let result = ParityDirectory { let result = ParityDirectory {
dir: try!(DiskDirectory::create(parity_keystore(t))), dir: DiskDirectory::create(parity_keystore(t))?,
}; };
Ok(result) Ok(result)

View File

@ -38,12 +38,12 @@ impl EthStore {
pub fn open_with_iterations(directory: Box<KeyDirectory>, iterations: u32) -> Result<Self, Error> { pub fn open_with_iterations(directory: Box<KeyDirectory>, iterations: u32) -> Result<Self, Error> {
Ok(EthStore { Ok(EthStore {
store: try!(EthMultiStore::open_with_iterations(directory, iterations)), store: EthMultiStore::open_with_iterations(directory, iterations)?,
}) })
} }
fn get(&self, address: &Address) -> Result<SafeAccount, Error> { fn get(&self, address: &Address) -> Result<SafeAccount, Error> {
let mut accounts = try!(self.store.get(address)).into_iter(); let mut accounts = self.store.get(address)?.into_iter();
accounts.next().ok_or(Error::InvalidAccount) accounts.next().ok_or(Error::InvalidAccount)
} }
} }
@ -66,68 +66,68 @@ impl SimpleSecretStore for EthStore {
} }
fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> { fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> {
let account = try!(self.get(address)); let account = self.get(address)?;
account.sign(password, message) account.sign(password, message)
} }
fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
let account = try!(self.get(account)); let account = self.get(account)?;
account.decrypt(password, shared_mac, message) account.decrypt(password, shared_mac, message)
} }
} }
impl SecretStore for EthStore { impl SecretStore for EthStore {
fn import_presale(&self, json: &[u8], password: &str) -> Result<Address, Error> { fn import_presale(&self, json: &[u8], password: &str) -> Result<Address, Error> {
let json_wallet = try!(json::PresaleWallet::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let json_wallet = json::PresaleWallet::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))?;
let wallet = PresaleWallet::from(json_wallet); let wallet = PresaleWallet::from(json_wallet);
let keypair = try!(wallet.decrypt(password).map_err(|_| Error::InvalidPassword)); let keypair = wallet.decrypt(password).map_err(|_| Error::InvalidPassword)?;
self.insert_account(keypair.secret().clone(), password) self.insert_account(keypair.secret().clone(), password)
} }
fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> { fn import_wallet(&self, json: &[u8], password: &str) -> Result<Address, Error> {
let json_keyfile = try!(json::KeyFile::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))); let json_keyfile = json::KeyFile::load(json).map_err(|_| Error::InvalidKeyFile("Invalid JSON format".to_owned()))?;
let mut safe_account = SafeAccount::from_file(json_keyfile, None); let mut safe_account = SafeAccount::from_file(json_keyfile, None);
let secret = try!(safe_account.crypto.secret(password).map_err(|_| Error::InvalidPassword)); let secret = safe_account.crypto.secret(password).map_err(|_| Error::InvalidPassword)?;
safe_account.address = try!(KeyPair::from_secret(secret)).address(); safe_account.address = KeyPair::from_secret(secret)?.address();
let address = safe_account.address.clone(); let address = safe_account.address.clone();
try!(self.store.import(safe_account)); self.store.import(safe_account)?;
Ok(address) Ok(address)
} }
fn test_password(&self, address: &Address, password: &str) -> Result<bool, Error> { fn test_password(&self, address: &Address, password: &str) -> Result<bool, Error> {
let account = try!(self.get(address)); let account = self.get(address)?;
Ok(account.check_password(password)) Ok(account.check_password(password))
} }
fn copy_account(&self, new_store: &SimpleSecretStore, address: &Address, password: &str, new_password: &str) -> Result<(), Error> { fn copy_account(&self, new_store: &SimpleSecretStore, address: &Address, password: &str, new_password: &str) -> Result<(), Error> {
let account = try!(self.get(address)); let account = self.get(address)?;
let secret = try!(account.crypto.secret(password)); let secret = account.crypto.secret(password)?;
try!(new_store.insert_account(secret, new_password)); new_store.insert_account(secret, new_password)?;
Ok(()) Ok(())
} }
fn public(&self, account: &Address, password: &str) -> Result<Public, Error> { fn public(&self, account: &Address, password: &str) -> Result<Public, Error> {
let account = try!(self.get(account)); let account = self.get(account)?;
account.public(password) account.public(password)
} }
fn uuid(&self, address: &Address) -> Result<Uuid, Error> { fn uuid(&self, address: &Address) -> Result<Uuid, Error> {
let account = try!(self.get(address)); let account = self.get(address)?;
Ok(account.id.into()) Ok(account.id.into())
} }
fn name(&self, address: &Address) -> Result<String, Error> { fn name(&self, address: &Address) -> Result<String, Error> {
let account = try!(self.get(address)); let account = self.get(address)?;
Ok(account.name.clone()) Ok(account.name.clone())
} }
fn meta(&self, address: &Address) -> Result<String, Error> { fn meta(&self, address: &Address) -> Result<String, Error> {
let account = try!(self.get(address)); let account = self.get(address)?;
Ok(account.meta.clone()) Ok(account.meta.clone())
} }
fn set_name(&self, address: &Address, name: String) -> Result<(), Error> { fn set_name(&self, address: &Address, name: String) -> Result<(), Error> {
let old = try!(self.get(address)); let old = self.get(address)?;
let mut account = old.clone(); let mut account = old.clone();
account.name = name; account.name = name;
@ -136,7 +136,7 @@ impl SecretStore for EthStore {
} }
fn set_meta(&self, address: &Address, meta: String) -> Result<(), Error> { fn set_meta(&self, address: &Address, meta: String) -> Result<(), Error> {
let old = try!(self.get(address)); let old = self.get(address)?;
let mut account = old.clone(); let mut account = old.clone();
account.meta = meta; account.meta = meta;
@ -176,13 +176,13 @@ impl EthMultiStore {
iterations: iterations, iterations: iterations,
cache: Default::default(), cache: Default::default(),
}; };
try!(store.reload_accounts()); store.reload_accounts()?;
Ok(store) Ok(store)
} }
fn reload_accounts(&self) -> Result<(), Error> { fn reload_accounts(&self) -> Result<(), Error> {
let mut cache = self.cache.write(); let mut cache = self.cache.write();
let accounts = try!(self.dir.load()); let accounts = self.dir.load()?;
let mut new_accounts = BTreeMap::new(); let mut new_accounts = BTreeMap::new();
for account in accounts { for account in accounts {
@ -203,9 +203,9 @@ impl EthMultiStore {
} }
} }
try!(self.reload_accounts()); self.reload_accounts()?;
let cache = self.cache.read(); let cache = self.cache.read();
let accounts = try!(cache.get(address).cloned().ok_or(Error::InvalidAccount)); let accounts = cache.get(address).cloned().ok_or(Error::InvalidAccount)?;
if accounts.is_empty() { if accounts.is_empty() {
Err(Error::InvalidAccount) Err(Error::InvalidAccount)
} else { } else {
@ -215,7 +215,7 @@ impl EthMultiStore {
fn import(&self, account: SafeAccount) -> Result<(), Error> { fn import(&self, account: SafeAccount) -> Result<(), Error> {
// save to file // save to file
let account = try!(self.dir.insert(account)); let account = self.dir.insert(account)?;
// update cache // update cache
let mut cache = self.cache.write(); let mut cache = self.cache.write();
@ -226,7 +226,7 @@ impl EthMultiStore {
fn update(&self, old: SafeAccount, new: SafeAccount) -> Result<(), Error> { fn update(&self, old: SafeAccount, new: SafeAccount) -> Result<(), Error> {
// save to file // save to file
let account = try!(self.dir.update(new)); let account = self.dir.update(new)?;
// update cache // update cache
let mut cache = self.cache.write(); let mut cache = self.cache.write();
@ -243,21 +243,21 @@ impl EthMultiStore {
impl SimpleSecretStore for EthMultiStore { impl SimpleSecretStore for EthMultiStore {
fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> {
let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)); let keypair = KeyPair::from_secret(secret).map_err(|_| Error::CreationFailed)?;
let id: [u8; 16] = Random::random(); let id: [u8; 16] = Random::random();
let account = SafeAccount::create(&keypair, id, password, self.iterations, "".to_owned(), "{}".to_owned()); let account = SafeAccount::create(&keypair, id, password, self.iterations, "".to_owned(), "{}".to_owned());
let address = account.address.clone(); let address = account.address.clone();
try!(self.import(account)); self.import(account)?;
Ok(address) Ok(address)
} }
fn accounts(&self) -> Result<Vec<Address>, Error> { fn accounts(&self) -> Result<Vec<Address>, Error> {
try!(self.reload_accounts()); self.reload_accounts()?;
Ok(self.cache.read().keys().cloned().collect()) Ok(self.cache.read().keys().cloned().collect())
} }
fn remove_account(&self, address: &Address, password: &str) -> Result<(), Error> { fn remove_account(&self, address: &Address, password: &str) -> Result<(), Error> {
let accounts = try!(self.get(address)); let accounts = self.get(address)?;
for account in accounts { for account in accounts {
// Skip if password is invalid // Skip if password is invalid
@ -266,7 +266,7 @@ impl SimpleSecretStore for EthMultiStore {
} }
// Remove from dir // Remove from dir
try!(self.dir.remove(&account)); self.dir.remove(&account)?;
// Remove from cache // Remove from cache
let mut cache = self.cache.write(); let mut cache = self.cache.write();
@ -288,17 +288,17 @@ impl SimpleSecretStore for EthMultiStore {
} }
fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> { fn change_password(&self, address: &Address, old_password: &str, new_password: &str) -> Result<(), Error> {
let accounts = try!(self.get(address)); let accounts = self.get(address)?;
for account in accounts { for account in accounts {
// Change password // Change password
let new_account = try!(account.change_password(old_password, new_password, self.iterations)); let new_account = account.change_password(old_password, new_password, self.iterations)?;
try!(self.update(account, new_account)); self.update(account, new_account)?;
} }
Ok(()) Ok(())
} }
fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> { fn sign(&self, address: &Address, password: &str, message: &Message) -> Result<Signature, Error> {
let accounts = try!(self.get(address)); let accounts = self.get(address)?;
for account in accounts { for account in accounts {
if account.check_password(password) { if account.check_password(password) {
return account.sign(password, message); return account.sign(password, message);
@ -309,7 +309,7 @@ impl SimpleSecretStore for EthMultiStore {
} }
fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> { fn decrypt(&self, account: &Address, password: &str, shared_mac: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {
let accounts = try!(self.get(account)); let accounts = self.get(account)?;
for account in accounts { for account in accounts {
if account.check_password(password) { if account.check_password(password) {
return account.decrypt(password, shared_mac, message); return account.decrypt(password, shared_mac, message);

View File

@ -20,14 +20,14 @@ use dir::{GethDirectory, KeyDirectory, DirectoryType};
use Error; use Error;
pub fn import_accounts(src: &KeyDirectory, dst: &KeyDirectory) -> Result<Vec<Address>, Error> { pub fn import_accounts(src: &KeyDirectory, dst: &KeyDirectory) -> Result<Vec<Address>, Error> {
let accounts = try!(src.load()); let accounts = src.load()?;
let existing_accounts = try!(dst.load()).into_iter().map(|a| a.address).collect::<HashSet<_>>(); let existing_accounts = dst.load()?.into_iter().map(|a| a.address).collect::<HashSet<_>>();
accounts.into_iter() accounts.into_iter()
.filter(|a| !existing_accounts.contains(&a.address)) .filter(|a| !existing_accounts.contains(&a.address))
.map(|a| { .map(|a| {
let address = a.address.clone(); let address = a.address.clone();
try!(dst.insert(a)); dst.insert(a)?;
Ok(address) Ok(address)
}).collect() }).collect()
} }
@ -55,15 +55,15 @@ pub fn import_geth_accounts(dst: &KeyDirectory, desired: HashSet<Address>, testn
}; };
let src = GethDirectory::open(t); let src = GethDirectory::open(t);
let accounts = try!(src.load()); let accounts = src.load()?;
let existing_accounts = try!(dst.load()).into_iter().map(|a| a.address).collect::<HashSet<_>>(); let existing_accounts = dst.load()?.into_iter().map(|a| a.address).collect::<HashSet<_>>();
accounts.into_iter() accounts.into_iter()
.filter(|a| !existing_accounts.contains(&a.address)) .filter(|a| !existing_accounts.contains(&a.address))
.filter(|a| desired.contains(&a.address)) .filter(|a| desired.contains(&a.address))
.map(|a| { .map(|a| {
let address = a.address.clone(); let address = a.address.clone();
try!(dst.insert(a)); dst.insert(a)?;
Ok(address) Ok(address)
}).collect() }).collect()
} }

View File

@ -17,8 +17,8 @@ impl Deserialize for Bytes {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer where D: Deserializer
{ {
let s = try!(String::deserialize(deserializer)); let s = String::deserialize(deserializer)?;
let data = try!(s.from_hex().map_err(|e| Error::custom(format!("Invalid hex value {}", e)))); let data = s.from_hex().map_err(|e| Error::custom(format!("Invalid hex value {}", e)))?;
Ok(Bytes(data)) Ok(Bytes(data))
} }
} }

View File

@ -90,13 +90,13 @@ impl Visitor for CryptoVisitor {
let mut mac = None; let mut mac = None;
loop { loop {
match try!(visitor.visit_key()) { match visitor.visit_key()? {
Some(CryptoField::Cipher) => { cipher = Some(try!(visitor.visit_value())); } Some(CryptoField::Cipher) => { cipher = Some(visitor.visit_value()?); }
Some(CryptoField::CipherParams) => { cipherparams = Some(try!(visitor.visit_value())); } Some(CryptoField::CipherParams) => { cipherparams = Some(visitor.visit_value()?); }
Some(CryptoField::CipherText) => { ciphertext = Some(try!(visitor.visit_value())); } Some(CryptoField::CipherText) => { ciphertext = Some(visitor.visit_value()?); }
Some(CryptoField::Kdf) => { kdf = Some(try!(visitor.visit_value())); } Some(CryptoField::Kdf) => { kdf = Some(visitor.visit_value()?); }
Some(CryptoField::KdfParams) => { kdfparams = Some(try!(visitor.visit_value())); } Some(CryptoField::KdfParams) => { kdfparams = Some(visitor.visit_value()?); }
Some(CryptoField::Mac) => { mac = Some(try!(visitor.visit_value())); } Some(CryptoField::Mac) => { mac = Some(visitor.visit_value()?); }
None => { break; } None => { break; }
} }
} }
@ -109,7 +109,7 @@ impl Visitor for CryptoVisitor {
let ciphertext = match ciphertext { let ciphertext = match ciphertext {
Some(ciphertext) => ciphertext, Some(ciphertext) => ciphertext,
None => try!(visitor.missing_field("ciphertext")), None => visitor.missing_field("ciphertext")?,
}; };
let kdf = match (kdf, kdfparams) { let kdf = match (kdf, kdfparams) {
@ -122,10 +122,10 @@ impl Visitor for CryptoVisitor {
let mac = match mac { let mac = match mac {
Some(mac) => mac, Some(mac) => mac,
None => try!(visitor.missing_field("mac")), None => visitor.missing_field("mac")?,
}; };
try!(visitor.end()); visitor.end()?;
let result = Crypto { let result = Crypto {
cipher: cipher, cipher: cipher,
@ -142,26 +142,26 @@ impl Serialize for Crypto {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer where S: Serializer
{ {
let mut state = try!(serializer.serialize_struct("Crypto", 6)); let mut state = serializer.serialize_struct("Crypto", 6)?;
match self.cipher { match self.cipher {
Cipher::Aes128Ctr(ref params) => { Cipher::Aes128Ctr(ref params) => {
try!(serializer.serialize_struct_elt(&mut state, "cipher", &CipherSer::Aes128Ctr)); serializer.serialize_struct_elt(&mut state, "cipher", &CipherSer::Aes128Ctr)?;
try!(serializer.serialize_struct_elt(&mut state, "cipherparams", params)); serializer.serialize_struct_elt(&mut state, "cipherparams", params)?;
}, },
} }
try!(serializer.serialize_struct_elt(&mut state, "ciphertext", &self.ciphertext)); serializer.serialize_struct_elt(&mut state, "ciphertext", &self.ciphertext)?;
match self.kdf { match self.kdf {
Kdf::Pbkdf2(ref params) => { Kdf::Pbkdf2(ref params) => {
try!(serializer.serialize_struct_elt(&mut state, "kdf", &KdfSer::Pbkdf2)); serializer.serialize_struct_elt(&mut state, "kdf", &KdfSer::Pbkdf2)?;
try!(serializer.serialize_struct_elt(&mut state, "kdfparams", params)); serializer.serialize_struct_elt(&mut state, "kdfparams", params)?;
}, },
Kdf::Scrypt(ref params) => { Kdf::Scrypt(ref params) => {
try!(serializer.serialize_struct_elt(&mut state, "kdf", &KdfSer::Scrypt)); serializer.serialize_struct_elt(&mut state, "kdf", &KdfSer::Scrypt)?;
try!(serializer.serialize_struct_elt(&mut state, "kdfparams", params)); serializer.serialize_struct_elt(&mut state, "kdfparams", params)?;
}, },
} }
try!(serializer.serialize_struct_elt(&mut state, "mac", &self.mac)); serializer.serialize_struct_elt(&mut state, "mac", &self.mac)?;
serializer.serialize_struct_end(state) serializer.serialize_struct_end(state)
} }
} }

View File

@ -62,7 +62,7 @@ impl fmt::Display for Uuid {
} }
fn copy_into(from: &str, into: &mut [u8]) -> Result<(), Error> { fn copy_into(from: &str, into: &mut [u8]) -> Result<(), Error> {
let from = try!(from.from_hex().map_err(|_| Error::InvalidUuid)); let from = from.from_hex().map_err(|_| Error::InvalidUuid)?;
if from.len() != into.len() { if from.len() != into.len() {
return Err(Error::InvalidUuid); return Err(Error::InvalidUuid);
@ -84,11 +84,11 @@ impl str::FromStr for Uuid {
let mut uuid = [0u8; 16]; let mut uuid = [0u8; 16];
try!(copy_into(parts[0], &mut uuid[0..4])); copy_into(parts[0], &mut uuid[0..4])?;
try!(copy_into(parts[1], &mut uuid[4..6])); copy_into(parts[1], &mut uuid[4..6])?;
try!(copy_into(parts[2], &mut uuid[6..8])); copy_into(parts[2], &mut uuid[6..8])?;
try!(copy_into(parts[3], &mut uuid[8..10])); copy_into(parts[3], &mut uuid[8..10])?;
try!(copy_into(parts[4], &mut uuid[10..16])); copy_into(parts[4], &mut uuid[10..16])?;
Ok(Uuid(uuid)) Ok(Uuid(uuid))
} }

View File

@ -134,7 +134,7 @@ impl Serialize for KdfSerParams {
impl Deserialize for KdfSerParams { impl Deserialize for KdfSerParams {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer { where D: Deserializer {
let v = try!(Value::deserialize(deserializer)); let v = Value::deserialize(deserializer)?;
Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(KdfSerParams::Pbkdf2) Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(KdfSerParams::Pbkdf2)
.or_else(|_| Deserialize::deserialize(&mut value::Deserializer::new(v)).map(KdfSerParams::Scrypt)) .or_else(|_| Deserialize::deserialize(&mut value::Deserializer::new(v)).map(KdfSerParams::Scrypt))

View File

@ -93,11 +93,11 @@ impl Visitor for KeyFileVisitor {
let mut meta = None; let mut meta = None;
loop { loop {
match try!(visitor.visit_key()) { match visitor.visit_key()? {
Some(KeyFileField::Id) => { id = Some(try!(visitor.visit_value())); } Some(KeyFileField::Id) => { id = Some(visitor.visit_value()?); }
Some(KeyFileField::Version) => { version = Some(try!(visitor.visit_value())); } Some(KeyFileField::Version) => { version = Some(visitor.visit_value()?); }
Some(KeyFileField::Crypto) => { crypto = Some(try!(visitor.visit_value())); } Some(KeyFileField::Crypto) => { crypto = Some(visitor.visit_value()?); }
Some(KeyFileField::Address) => { address = Some(try!(visitor.visit_value())); } Some(KeyFileField::Address) => { address = Some(visitor.visit_value()?); }
Some(KeyFileField::Name) => { name = visitor.visit_value().ok(); } // ignore anyhing that is not a string to be permissive. Some(KeyFileField::Name) => { name = visitor.visit_value().ok(); } // ignore anyhing that is not a string to be permissive.
Some(KeyFileField::Meta) => { meta = visitor.visit_value().ok(); } // ignore anyhing that is not a string to be permissive. Some(KeyFileField::Meta) => { meta = visitor.visit_value().ok(); } // ignore anyhing that is not a string to be permissive.
None => { break; } None => { break; }
@ -106,25 +106,25 @@ impl Visitor for KeyFileVisitor {
let id = match id { let id = match id {
Some(id) => id, Some(id) => id,
None => try!(visitor.missing_field("id")), None => visitor.missing_field("id")?,
}; };
let version = match version { let version = match version {
Some(version) => version, Some(version) => version,
None => try!(visitor.missing_field("version")), None => visitor.missing_field("version")?,
}; };
let crypto = match crypto { let crypto = match crypto {
Some(crypto) => crypto, Some(crypto) => crypto,
None => try!(visitor.missing_field("crypto")), None => visitor.missing_field("crypto")?,
}; };
let address = match address { let address = match address {
Some(address) => address, Some(address) => address,
None => try!(visitor.missing_field("address")), None => visitor.missing_field("address")?,
}; };
try!(visitor.end()); visitor.end()?;
let result = KeyFile { let result = KeyFile {
id: id, id: id,

View File

@ -32,9 +32,9 @@ impl From<json::PresaleWallet> for PresaleWallet {
impl PresaleWallet { impl PresaleWallet {
pub fn open<P>(path: P) -> Result<Self, Error> where P: AsRef<Path> { pub fn open<P>(path: P) -> Result<Self, Error> where P: AsRef<Path> {
let file = try!(fs::File::open(path)); let file = fs::File::open(path)?;
let presale = try!(json::PresaleWallet::load(file) let presale = json::PresaleWallet::load(file)
.map_err(|e| Error::InvalidKeyFile(format!("{}", e)))); .map_err(|e| Error::InvalidKeyFile(format!("{}", e)))?;
Ok(PresaleWallet::from(presale)) Ok(PresaleWallet::from(presale))
} }
@ -44,7 +44,7 @@ impl PresaleWallet {
pbkdf2(&mut h_mac, password.as_bytes(), 2000, &mut derived_key); pbkdf2(&mut h_mac, password.as_bytes(), 2000, &mut derived_key);
let mut key = vec![0; self.ciphertext.len()]; let mut key = vec![0; self.ciphertext.len()];
let len = try!(crypto::aes::decrypt_cbc(&derived_key, &self.iv, &self.ciphertext, &mut key).map_err(|_| Error::InvalidPassword)); let len = crypto::aes::decrypt_cbc(&derived_key, &self.iv, &self.ciphertext, &mut key).map_err(|_| Error::InvalidPassword)?;
let unpadded = &key[..len]; let unpadded = &key[..len];
let secret = Secret::from(unpadded.keccak256()); let secret = Secret::from(unpadded.keccak256());

View File

@ -36,7 +36,7 @@ impl TransientDir {
pub fn create() -> Result<Self, Error> { pub fn create() -> Result<Self, Error> {
let path = random_dir(); let path = random_dir();
let result = TransientDir { let result = TransientDir {
dir: try!(DiskDirectory::create(&path)), dir: DiskDirectory::create(&path)?,
path: path, path: path,
}; };

View File

@ -104,9 +104,9 @@ pub struct Success {
} }
impl fmt::Display for Success { impl fmt::Display for Success {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(writeln!(f, "Gas used: {:?}", self.gas_used)); writeln!(f, "Gas used: {:?}", self.gas_used)?;
try!(writeln!(f, "Output: {:?}", self.output)); writeln!(f, "Output: {:?}", self.output)?;
try!(writeln!(f, "Time: {}.{:.9}s", self.time.as_secs(), self.time.subsec_nanos())); writeln!(f, "Time: {}.{:.9}s", self.time.as_secs(), self.time.subsec_nanos())?;
Ok(()) Ok(())
} }
} }
@ -120,8 +120,8 @@ pub struct Failure {
} }
impl fmt::Display for Failure { impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(writeln!(f, "Error: {:?}", self.error)); writeln!(f, "Error: {:?}", self.error)?;
try!(writeln!(f, "Time: {}.{:.9}s", self.time.as_secs(), self.time.subsec_nanos())); writeln!(f, "Time: {}.{:.9}s", self.time.as_secs(), self.time.subsec_nanos())?;
Ok(()) Ok(())
} }
} }

View File

@ -114,16 +114,16 @@ impl<F: Fetch + 'static> HashFetch for Client<F> {
Ok(url) => { Ok(url) => {
let future = self.fetch.fetch(&url).then(move |result| { let future = self.fetch.fetch(&url).then(move |result| {
fn validate_hash(path: PathBuf, hash: H256, result: Result<Response, FetchError>) -> Result<PathBuf, Error> { fn validate_hash(path: PathBuf, hash: H256, result: Result<Response, FetchError>) -> Result<PathBuf, Error> {
let response = try!(result); let response = result?;
// Read the response // Read the response
let mut reader = io::BufReader::new(response); let mut reader = io::BufReader::new(response);
let mut writer = io::BufWriter::new(try!(fs::File::create(&path))); let mut writer = io::BufWriter::new(fs::File::create(&path)?);
try!(io::copy(&mut reader, &mut writer)); io::copy(&mut reader, &mut writer)?;
try!(writer.flush()); writer.flush()?;
// And validate the hash // And validate the hash
let mut file_reader = io::BufReader::new(try!(fs::File::open(&path))); let mut file_reader = io::BufReader::new(fs::File::open(&path)?);
let content_hash = try!(sha3(&mut file_reader)); let content_hash = sha3(&mut file_reader)?;
if content_hash != hash { if content_hash != hash {
Err(Error::HashMismatch{ got: content_hash, expected: hash }) Err(Error::HashMismatch{ got: content_hash, expected: hash })
} else { } else {

View File

@ -119,12 +119,12 @@ impl URLHintContract {
fn urlhint_address(&self) -> Option<Address> { fn urlhint_address(&self) -> Option<Address> {
let res = || { let res = || {
let get_address = try!(self.registrar.function("getAddress".into()).map_err(as_string)); let get_address = self.registrar.function("getAddress".into()).map_err(as_string)?;
let params = try!(get_address.encode_call( let params = get_address.encode_call(
vec![Token::FixedBytes((*"githubhint".sha3()).to_vec()), Token::String("A".into())] vec![Token::FixedBytes((*"githubhint".sha3()).to_vec()), Token::String("A".into())]
).map_err(as_string)); ).map_err(as_string)?;
let output = try!(self.client.call(try!(self.client.registrar()), params)); let output = self.client.call(self.client.registrar()?, params)?;
let result = try!(get_address.decode_output(output).map_err(as_string)); let result = get_address.decode_output(output).map_err(as_string)?;
match result.get(0) { match result.get(0) {
Some(&Token::Address(address)) if address != *Address::default() => Ok(address.into()), Some(&Token::Address(address)) if address != *Address::default() => Ok(address.into()),

View File

@ -162,7 +162,7 @@ fn cleanup(src_path: &str, attr: AttributeKind) -> Result<(), Error> {
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
let out_dir = env::var_os("OUT_DIR").unwrap(); let out_dir = env::var_os("OUT_DIR").unwrap();
let file_name = try!(PathBuf::from(src_path).file_name().ok_or(Error::InvalidFileName).map(|val| val.to_str().unwrap().to_owned())); let file_name = PathBuf::from(src_path).file_name().ok_or(Error::InvalidFileName).map(|val| val.to_str().unwrap().to_owned())?;
let mut registry = syntex::Registry::new(); let mut registry = syntex::Registry::new();
match attr { match attr {
@ -183,7 +183,7 @@ pub fn derive_ipc(src_path: &str) -> Result<(), Error> {
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
let out_dir = env::var_os("OUT_DIR").unwrap(); let out_dir = env::var_os("OUT_DIR").unwrap();
let file_name = try!(PathBuf::from(src_path).file_name().ok_or(Error::InvalidFileName).map(|val| val.to_str().unwrap().to_owned())); let file_name = PathBuf::from(src_path).file_name().ok_or(Error::InvalidFileName).map(|val| val.to_str().unwrap().to_owned())?;
let final_path = Path::new(&out_dir).join(&file_name); let final_path = Path::new(&out_dir).join(&file_name);
@ -217,7 +217,7 @@ pub fn derive_binary(src_path: &str) -> Result<(), Error> {
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
let out_dir = env::var_os("OUT_DIR").unwrap(); let out_dir = env::var_os("OUT_DIR").unwrap();
let file_name = try!(PathBuf::from(src_path).file_name().ok_or(Error::InvalidFileName).map(|val| val.to_str().unwrap().to_owned())); let file_name = PathBuf::from(src_path).file_name().ok_or(Error::InvalidFileName).map(|val| val.to_str().unwrap().to_owned())?;
let final_path = Path::new(&out_dir).join(&file_name); let final_path = Path::new(&out_dir).join(&file_name);
let mut registry = syntex::Registry::new(); let mut registry = syntex::Registry::new();

View File

@ -388,8 +388,7 @@ fn binary_expr_enum(
span: Span, span: Span,
enum_def: &ast::EnumDef, enum_def: &ast::EnumDef,
) -> Result<BinaryExpressions, Error> { ) -> Result<BinaryExpressions, Error> {
let arms: Vec<_> = try!( let arms: Vec<_> = try!(enum_def.variants.iter()
enum_def.variants.iter()
.enumerate() .enumerate()
.map(|(variant_index, variant)| { .map(|(variant_index, variant)| {
binary_expr_variant( binary_expr_variant(
@ -403,8 +402,7 @@ fn binary_expr_enum(
variant_index, variant_index,
) )
}) })
.collect() .collect());
);
let (size_arms, write_arms, mut read_arms) = ( let (size_arms, write_arms, mut read_arms) = (
arms.iter().map(|x| x.size.clone()).collect::<Vec<ast::Arm>>(), arms.iter().map(|x| x.size.clone()).collect::<Vec<ast::Arm>>(),

View File

@ -65,17 +65,17 @@ impl<S> Deref for GuardedSocket<S> where S: WithSocket<Socket> {
/// creates socket and connects endpoint to it /// creates socket and connects endpoint to it
/// for duplex (paired) connections with the service /// for duplex (paired) connections with the service
pub fn init_duplex_client<S>(socket_addr: &str) -> Result<GuardedSocket<S>, SocketError> where S: WithSocket<Socket> { pub fn init_duplex_client<S>(socket_addr: &str) -> Result<GuardedSocket<S>, SocketError> where S: WithSocket<Socket> {
let mut socket = try!(Socket::new(Protocol::Pair).map_err(|e| { let mut socket = Socket::new(Protocol::Pair).map_err(|e| {
warn!(target: "ipc", "Failed to create ipc socket: {:?}", e); warn!(target: "ipc", "Failed to create ipc socket: {:?}", e);
SocketError::DuplexLink SocketError::DuplexLink
})); })?;
socket.set_receive_timeout(DEFAULT_CONNECTION_TIMEOUT).unwrap(); socket.set_receive_timeout(DEFAULT_CONNECTION_TIMEOUT).unwrap();
let endpoint = try!(socket.connect(socket_addr).map_err(|e| { let endpoint = socket.connect(socket_addr).map_err(|e| {
warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", socket_addr, e); warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", socket_addr, e);
SocketError::DuplexLink SocketError::DuplexLink
})); })?;
Ok(GuardedSocket { Ok(GuardedSocket {
client: Arc::new(S::init(socket)), client: Arc::new(S::init(socket)),
@ -87,19 +87,19 @@ pub fn init_duplex_client<S>(socket_addr: &str) -> Result<GuardedSocket<S>, Sock
/// creates socket and connects endpoint to it /// creates socket and connects endpoint to it
/// for request-reply connections to the service /// for request-reply connections to the service
pub fn client<S>(socket_addr: &str, receive_timeout: Option<isize>) -> Result<GuardedSocket<S>, SocketError> where S: WithSocket<Socket> { pub fn client<S>(socket_addr: &str, receive_timeout: Option<isize>) -> Result<GuardedSocket<S>, SocketError> where S: WithSocket<Socket> {
let mut socket = try!(Socket::new(Protocol::Req).map_err(|e| { let mut socket = Socket::new(Protocol::Req).map_err(|e| {
warn!(target: "ipc", "Failed to create ipc socket: {:?}", e); warn!(target: "ipc", "Failed to create ipc socket: {:?}", e);
SocketError::RequestLink SocketError::RequestLink
})); })?;
if let Some(timeout) = receive_timeout { if let Some(timeout) = receive_timeout {
socket.set_receive_timeout(timeout).unwrap(); socket.set_receive_timeout(timeout).unwrap();
} }
let endpoint = try!(socket.connect(socket_addr).map_err(|e| { let endpoint = socket.connect(socket_addr).map_err(|e| {
warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", socket_addr, e); warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", socket_addr, e);
SocketError::RequestLink SocketError::RequestLink
})); })?;
trace!(target: "ipc", "Created client for {}", socket_addr); trace!(target: "ipc", "Created client for {}", socket_addr);
Ok(GuardedSocket { Ok(GuardedSocket {
@ -210,15 +210,15 @@ impl<S: ?Sized> Worker<S> where S: IpcInterface {
/// Add exclusive socket for paired client /// Add exclusive socket for paired client
/// Only one connection over this address is allowed /// Only one connection over this address is allowed
pub fn add_duplex(&mut self, addr: &str) -> Result<(), SocketError> { pub fn add_duplex(&mut self, addr: &str) -> Result<(), SocketError> {
let mut socket = try!(Socket::new(Protocol::Pair).map_err(|e| { let mut socket = Socket::new(Protocol::Pair).map_err(|e| {
warn!(target: "ipc", "Failed to create ipc socket: {:?}", e); warn!(target: "ipc", "Failed to create ipc socket: {:?}", e);
SocketError::DuplexLink SocketError::DuplexLink
})); })?;
let endpoint = try!(socket.bind(addr).map_err(|e| { let endpoint = socket.bind(addr).map_err(|e| {
warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", addr, e); warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", addr, e);
SocketError::DuplexLink SocketError::DuplexLink
})); })?;
self.sockets.push((socket, endpoint)); self.sockets.push((socket, endpoint));
@ -232,16 +232,16 @@ impl<S: ?Sized> Worker<S> where S: IpcInterface {
/// Add generic socket for request-reply style communications /// Add generic socket for request-reply style communications
/// with multiple clients /// with multiple clients
pub fn add_reqrep(&mut self, addr: &str) -> Result<(), SocketError> { pub fn add_reqrep(&mut self, addr: &str) -> Result<(), SocketError> {
let mut socket = try!(Socket::new(Protocol::Rep).map_err(|e| { let mut socket = Socket::new(Protocol::Rep).map_err(|e| {
warn!(target: "ipc", "Failed to create ipc socket: {:?}", e); warn!(target: "ipc", "Failed to create ipc socket: {:?}", e);
SocketError::DuplexLink SocketError::DuplexLink
})); })?;
let endpoint = try!(socket.bind(addr).map_err(|e| { let endpoint = socket.bind(addr).map_err(|e| {
warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", addr, e); warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", addr, e);
SocketError::DuplexLink SocketError::DuplexLink
})); })?;
self.sockets.push((socket, endpoint)); self.sockets.push((socket, endpoint));

View File

@ -121,7 +121,7 @@ impl<T> BinaryConvertable for Option<T> where T: BinaryConvertable {
fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> { fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> {
if buffer.len() == 0 { return Self::from_empty_bytes(); } if buffer.len() == 0 { return Self::from_empty_bytes(); }
Ok(Some(try!(T::from_bytes(buffer, length_stack)))) Ok(Some(T::from_bytes(buffer, length_stack)?))
} }
fn from_empty_bytes() -> Result<Self, BinaryConvertError> { fn from_empty_bytes() -> Result<Self, BinaryConvertError> {
@ -144,12 +144,12 @@ impl<E: BinaryConvertable> BinaryConvertable for Result<(), E> {
fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> { fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> {
match *self { match *self {
Ok(_) => Err(BinaryConvertError::empty()), Ok(_) => Err(BinaryConvertError::empty()),
Err(ref e) => Ok(try!(e.to_bytes(buffer, length_stack))), Err(ref e) => Ok(e.to_bytes(buffer, length_stack)?),
} }
} }
fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> { fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> {
Ok(Err(try!(E::from_bytes(&buffer, length_stack)))) Ok(Err(E::from_bytes(&buffer, length_stack)?))
} }
fn from_empty_bytes() -> Result<Self, BinaryConvertError> { fn from_empty_bytes() -> Result<Self, BinaryConvertError> {
@ -172,13 +172,13 @@ impl<R: BinaryConvertable> BinaryConvertable for Result<R, ()> {
fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> { fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> {
match *self { match *self {
Ok(ref r) => Ok(try!(r.to_bytes(buffer, length_stack))), Ok(ref r) => Ok(r.to_bytes(buffer, length_stack)?),
Err(_) => Err(BinaryConvertError::empty()), Err(_) => Err(BinaryConvertError::empty()),
} }
} }
fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> { fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> {
Ok(Ok(try!(R::from_bytes(&buffer, length_stack)))) Ok(Ok(R::from_bytes(&buffer, length_stack)?))
} }
fn from_empty_bytes() -> Result<Self, BinaryConvertError> { fn from_empty_bytes() -> Result<Self, BinaryConvertError> {
@ -203,14 +203,14 @@ impl<R: BinaryConvertable, E: BinaryConvertable> BinaryConvertable for Result<R,
Ok(ref r) => { Ok(ref r) => {
buffer[0] = 0; buffer[0] = 0;
if r.size() > 0 { if r.size() > 0 {
Ok(try!(r.to_bytes(&mut buffer[1..], length_stack))) Ok(r.to_bytes(&mut buffer[1..], length_stack)?)
} }
else { Ok(()) } else { Ok(()) }
}, },
Err(ref e) => { Err(ref e) => {
buffer[0] = 1; buffer[0] = 1;
if e.size() > 0 { if e.size() > 0 {
Ok(try!(e.to_bytes(&mut buffer[1..], length_stack))) Ok(e.to_bytes(&mut buffer[1..], length_stack)?)
} }
else { Ok(()) } else { Ok(()) }
}, },
@ -221,11 +221,11 @@ impl<R: BinaryConvertable, E: BinaryConvertable> BinaryConvertable for Result<R,
match buffer[0] { match buffer[0] {
0 => { 0 => {
match buffer.len() { match buffer.len() {
1 => Ok(Ok(try!(R::from_empty_bytes()))), 1 => Ok(Ok(R::from_empty_bytes()?)),
_ => Ok(Ok(try!(R::from_bytes(&buffer[1..], length_stack)))), _ => Ok(Ok(R::from_bytes(&buffer[1..], length_stack)?)),
} }
} }
1 => Ok(Err(try!(E::from_bytes(&buffer[1..], length_stack)))), 1 => Ok(Err(E::from_bytes(&buffer[1..], length_stack)?)),
_ => Err(BinaryConvertError::variant(buffer[0])) _ => Err(BinaryConvertError::variant(buffer[0]))
} }
} }
@ -260,13 +260,13 @@ impl<K, V> BinaryConvertable for BTreeMap<K, V> where K : BinaryConvertable + Or
if key_size > 0 { if key_size > 0 {
let item_end = offset + key_size; let item_end = offset + key_size;
try!(key.to_bytes(&mut buffer[offset..item_end], length_stack)); key.to_bytes(&mut buffer[offset..item_end], length_stack)?;
offset = item_end; offset = item_end;
} }
if val_size > 0 { if val_size > 0 {
let item_end = offset + key_size; let item_end = offset + key_size;
try!(val.to_bytes(&mut buffer[offset..item_end], length_stack)); val.to_bytes(&mut buffer[offset..item_end], length_stack)?;
offset = item_end; offset = item_end;
} }
} }
@ -282,29 +282,29 @@ impl<K, V> BinaryConvertable for BTreeMap<K, V> where K : BinaryConvertable + Or
loop { loop {
let key_size = match K::len_params() { let key_size = match K::len_params() {
0 => mem::size_of::<K>(), 0 => mem::size_of::<K>(),
_ => try!(length_stack.pop_front().ok_or(BinaryConvertError::length())), _ => length_stack.pop_front().ok_or(BinaryConvertError::length())?,
}; };
let key = if key_size == 0 { let key = if key_size == 0 {
try!(K::from_empty_bytes()) K::from_empty_bytes()?
} else { } else {
if index + key_size > buffer.len() { if index + key_size > buffer.len() {
return Err(BinaryConvertError::boundaries()) return Err(BinaryConvertError::boundaries())
} }
try!(K::from_bytes(&buffer[index..index+key_size], length_stack)) K::from_bytes(&buffer[index..index+key_size], length_stack)?
}; };
index = index + key_size; index = index + key_size;
let val_size = match V::len_params() { let val_size = match V::len_params() {
0 => mem::size_of::<V>(), 0 => mem::size_of::<V>(),
_ => try!(length_stack.pop_front().ok_or(BinaryConvertError::length())), _ => length_stack.pop_front().ok_or(BinaryConvertError::length())?,
}; };
let val = if val_size == 0 { let val = if val_size == 0 {
try!(V::from_empty_bytes()) V::from_empty_bytes()?
} else { } else {
if index + val_size > buffer.len() { if index + val_size > buffer.len() {
return Err(BinaryConvertError::boundaries()) return Err(BinaryConvertError::boundaries())
} }
try!(V::from_bytes(&buffer[index..index+val_size], length_stack)) V::from_bytes(&buffer[index..index+val_size], length_stack)?
}; };
result.insert(key, val); result.insert(key, val);
index = index + val_size; index = index + val_size;
@ -344,7 +344,7 @@ impl<T> BinaryConvertable for VecDeque<T> where T: BinaryConvertable {
}; };
if next_size > 0 { if next_size > 0 {
let item_end = offset + next_size; let item_end = offset + next_size;
try!(item.to_bytes(&mut buffer[offset..item_end], length_stack)); item.to_bytes(&mut buffer[offset..item_end], length_stack)?;
offset = item_end; offset = item_end;
} }
} }
@ -364,16 +364,16 @@ impl<T> BinaryConvertable for VecDeque<T> where T: BinaryConvertable {
loop { loop {
let next_size = match T::len_params() { let next_size = match T::len_params() {
0 => mem::size_of::<T>(), 0 => mem::size_of::<T>(),
_ => try!(length_stack.pop_front().ok_or(BinaryConvertError::length())), _ => length_stack.pop_front().ok_or(BinaryConvertError::length())?,
}; };
let item = if next_size == 0 { let item = if next_size == 0 {
try!(T::from_empty_bytes()) T::from_empty_bytes()?
} }
else { else {
if index + next_size > buffer.len() { if index + next_size > buffer.len() {
return Err(BinaryConvertError::boundaries()) return Err(BinaryConvertError::boundaries())
} }
try!(T::from_bytes(&buffer[index..index+next_size], length_stack)) T::from_bytes(&buffer[index..index+next_size], length_stack)?
}; };
result.push_back(item); result.push_back(item);
@ -413,7 +413,7 @@ impl<T> BinaryConvertable for Vec<T> where T: BinaryConvertable {
}; };
if next_size > 0 { if next_size > 0 {
let item_end = offset + next_size; let item_end = offset + next_size;
try!(item.to_bytes(&mut buffer[offset..item_end], length_stack)); item.to_bytes(&mut buffer[offset..item_end], length_stack)?;
offset = item_end; offset = item_end;
} }
} }
@ -433,16 +433,16 @@ impl<T> BinaryConvertable for Vec<T> where T: BinaryConvertable {
loop { loop {
let next_size = match T::len_params() { let next_size = match T::len_params() {
0 => mem::size_of::<T>(), 0 => mem::size_of::<T>(),
_ => try!(length_stack.pop_front().ok_or(BinaryConvertError::length())), _ => length_stack.pop_front().ok_or(BinaryConvertError::length())?,
}; };
let item = if next_size == 0 { let item = if next_size == 0 {
try!(T::from_empty_bytes()) T::from_empty_bytes()?
} }
else { else {
if index + next_size > buffer.len() { if index + next_size > buffer.len() {
return Err(BinaryConvertError::boundaries()) return Err(BinaryConvertError::boundaries())
} }
try!(T::from_bytes(&buffer[index..index+next_size], length_stack)) T::from_bytes(&buffer[index..index+next_size], length_stack)?
}; };
result.push(item); result.push(item);
@ -498,13 +498,13 @@ impl<T> BinaryConvertable for Range<T> where T: BinaryConvertable {
} }
fn to_bytes(&self, buffer: &mut[u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> { fn to_bytes(&self, buffer: &mut[u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> {
try!(self.start.to_bytes(&mut buffer[..mem::size_of::<T>()], length_stack)); self.start.to_bytes(&mut buffer[..mem::size_of::<T>()], length_stack)?;
try!(self.end.to_bytes(&mut buffer[mem::size_of::<T>() + 1..], length_stack)); self.end.to_bytes(&mut buffer[mem::size_of::<T>() + 1..], length_stack)?;
Ok(()) Ok(())
} }
fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> { fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> {
Ok(try!(T::from_bytes(&buffer[..mem::size_of::<T>()], length_stack))..try!(T::from_bytes(&buffer[mem::size_of::<T>()+1..], length_stack))) Ok(T::from_bytes(&buffer[..mem::size_of::<T>()], length_stack)?..T::from_bytes(&buffer[mem::size_of::<T>()+1..], length_stack)?)
} }
fn len_params() -> usize { fn len_params() -> usize {
@ -519,15 +519,15 @@ impl<T> BinaryConvertable for ::std::cell::RefCell<T> where T: BinaryConvertable
} }
fn from_empty_bytes() -> Result<Self, BinaryConvertError> { fn from_empty_bytes() -> Result<Self, BinaryConvertError> {
Ok(::std::cell::RefCell::new(try!(T::from_empty_bytes()))) Ok(::std::cell::RefCell::new(T::from_empty_bytes()?))
} }
fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> { fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> {
Ok(::std::cell::RefCell::new(try!(T::from_bytes(buffer, length_stack)))) Ok(::std::cell::RefCell::new(T::from_bytes(buffer, length_stack)?))
} }
fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> { fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> {
try!(self.borrow().to_bytes(buffer, length_stack)); self.borrow().to_bytes(buffer, length_stack)?;
Ok(()) Ok(())
} }
@ -542,15 +542,15 @@ impl<T> BinaryConvertable for ::std::cell::Cell<T> where T: BinaryConvertable +
} }
fn from_empty_bytes() -> Result<Self, BinaryConvertError> { fn from_empty_bytes() -> Result<Self, BinaryConvertError> {
Ok(::std::cell::Cell::new(try!(T::from_empty_bytes()))) Ok(::std::cell::Cell::new(T::from_empty_bytes()?))
} }
fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> { fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque<usize>) -> Result<Self, BinaryConvertError> {
Ok(::std::cell::Cell::new(try!(T::from_bytes(buffer, length_stack)))) Ok(::std::cell::Cell::new(T::from_bytes(buffer, length_stack)?))
} }
fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> { fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque<usize>) -> Result<(), BinaryConvertError> {
try!(self.get().to_bytes(buffer, length_stack)); self.get().to_bytes(buffer, length_stack)?;
Ok(()) Ok(())
} }
@ -596,34 +596,33 @@ pub fn deserialize_from<T, R>(r: &mut R) -> Result<T, BinaryError>
let fixed_size = mem::size_of::<T>(); let fixed_size = mem::size_of::<T>();
let mut payload_buffer = Vec::with_capacity(fixed_size); let mut payload_buffer = Vec::with_capacity(fixed_size);
unsafe { payload_buffer.set_len(fixed_size); } unsafe { payload_buffer.set_len(fixed_size); }
let bytes_read = try!(r.read(&mut payload_buffer)); let bytes_read = r.read(&mut payload_buffer)?;
if bytes_read != mem::size_of::<T>() { if bytes_read != mem::size_of::<T>() {
return Err(BinaryError::Serialization(BinaryConvertError::size(fixed_size, bytes_read))) return Err(BinaryError::Serialization(BinaryConvertError::size(fixed_size, bytes_read)))
} }
Ok(try!(T::from_bytes(&payload_buffer[..], &mut fake_stack))) Ok(T::from_bytes(&payload_buffer[..], &mut fake_stack)?)
}, },
_ => { _ => {
let mut payload = Vec::new(); let mut payload = Vec::new();
try!(r.read_to_end(&mut payload)); r.read_to_end(&mut payload)?;
let stack_len = try!(u64::from_bytes(&payload[0..8], &mut fake_stack)) as usize; let stack_len = u64::from_bytes(&payload[0..8], &mut fake_stack)? as usize;
let mut length_stack = VecDeque::<usize>::with_capacity(stack_len); let mut length_stack = VecDeque::<usize>::with_capacity(stack_len);
if stack_len > 0 { if stack_len > 0 {
for idx in 0..stack_len { for idx in 0..stack_len {
let stack_item = try!(u64::from_bytes(&payload[8 + idx*8..8 + (idx+1)*8], &mut fake_stack)); let stack_item = u64::from_bytes(&payload[8 + idx*8..8 + (idx+1)*8], &mut fake_stack)?;
length_stack.push_back(stack_item as usize); length_stack.push_back(stack_item as usize);
} }
} }
//try!(r.read(&mut size_buffer).map_err(|_| BinaryConvertError)); let size = u64::from_bytes(&payload[8+stack_len*8..16+stack_len*8], &mut fake_stack)? as usize;
let size = try!(u64::from_bytes(&payload[8+stack_len*8..16+stack_len*8], &mut fake_stack)) as usize;
match size { match size {
0 => { 0 => {
Ok(try!(T::from_empty_bytes())) Ok(T::from_empty_bytes()?)
}, },
_ => { _ => {
Ok(try!(T::from_bytes(&payload[16+stack_len*8..], &mut length_stack))) Ok(T::from_bytes(&payload[16+stack_len*8..], &mut length_stack)?)
} }
} }
}, },
@ -647,8 +646,8 @@ pub fn serialize_into<T, W>(t: &T, w: &mut W) -> Result<(), BinaryError>
let fixed_size = mem::size_of::<T>(); let fixed_size = mem::size_of::<T>();
let mut buffer = Vec::with_capacity(fixed_size); let mut buffer = Vec::with_capacity(fixed_size);
unsafe { buffer.set_len(fixed_size); } unsafe { buffer.set_len(fixed_size); }
try!(t.to_bytes(&mut buffer[..], &mut fake_stack)); t.to_bytes(&mut buffer[..], &mut fake_stack)?;
try!(w.write(&buffer[..])); w.write(&buffer[..])?;
Ok(()) Ok(())
}, },
_ => { _ => {
@ -657,37 +656,37 @@ pub fn serialize_into<T, W>(t: &T, w: &mut W) -> Result<(), BinaryError>
let size = t.size(); let size = t.size();
if size == 0 { if size == 0 {
try!(w.write(&size_buffer)); w.write(&size_buffer)?;
try!(w.write(&size_buffer)); w.write(&size_buffer)?;
return Ok(()); return Ok(());
} }
let mut buffer = Vec::with_capacity(size); let mut buffer = Vec::with_capacity(size);
unsafe { buffer.set_len(size); } unsafe { buffer.set_len(size); }
try!(t.to_bytes(&mut buffer[..], &mut length_stack)); t.to_bytes(&mut buffer[..], &mut length_stack)?;
let stack_len = length_stack.len(); let stack_len = length_stack.len();
try!((stack_len as u64).to_bytes(&mut size_buffer[..], &mut fake_stack)); (stack_len as u64).to_bytes(&mut size_buffer[..], &mut fake_stack)?;
try!(w.write(&size_buffer[..])); w.write(&size_buffer[..])?;
if stack_len > 0 { if stack_len > 0 {
let mut header_buffer = Vec::with_capacity(stack_len * 8); let mut header_buffer = Vec::with_capacity(stack_len * 8);
unsafe { header_buffer.set_len(stack_len * 8); }; unsafe { header_buffer.set_len(stack_len * 8); };
try!((stack_len as u64).to_bytes(&mut header_buffer[0..8], &mut fake_stack)); (stack_len as u64).to_bytes(&mut header_buffer[0..8], &mut fake_stack)?;
let mut idx = 0; let mut idx = 0;
loop { loop {
match length_stack.pop_front() { match length_stack.pop_front() {
Some(val) => try!((val as u64).to_bytes(&mut header_buffer[idx * 8..(idx+1) * 8], &mut fake_stack)), Some(val) => (val as u64).to_bytes(&mut header_buffer[idx * 8..(idx+1) * 8], &mut fake_stack)?,
None => { break; } None => { break; }
} }
idx = idx + 1; idx = idx + 1;
} }
try!(w.write(&header_buffer[..])); w.write(&header_buffer[..])?;
} }
try!((size as u64).to_bytes(&mut size_buffer[..], &mut fake_stack)); (size as u64).to_bytes(&mut size_buffer[..], &mut fake_stack)?;
try!(w.write(&size_buffer[..])); w.write(&size_buffer[..])?;
try!(w.write(&buffer[..])); w.write(&buffer[..])?;
Ok(()) Ok(())
}, },
@ -697,7 +696,7 @@ pub fn serialize_into<T, W>(t: &T, w: &mut W) -> Result<(), BinaryError>
pub fn serialize<T: BinaryConvertable>(t: &T) -> Result<Vec<u8>, BinaryError> { pub fn serialize<T: BinaryConvertable>(t: &T) -> Result<Vec<u8>, BinaryError> {
use std::io::Cursor; use std::io::Cursor;
let mut buff = Cursor::new(Vec::new()); let mut buff = Cursor::new(Vec::new());
try!(serialize_into(t, &mut buff)); serialize_into(t, &mut buff)?;
let into_inner = buff.into_inner(); let into_inner = buff.into_inner();
Ok(into_inner) Ok(into_inner)
} }

View File

@ -54,12 +54,12 @@ macro_rules! impl_hash {
let value = match value.len() { let value = match value.len() {
0 => $inner::from(0), 0 => $inner::from(0),
2 if value == "0x" => $inner::from(0), 2 if value == "0x" => $inner::from(0),
_ if value.starts_with("0x") => try!($inner::from_str(&value[2..]).map_err(|_| { _ if value.starts_with("0x") => $inner::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str()) Error::custom(format!("Invalid hex value {}.", value).as_str())
})), })?,
_ => try!($inner::from_str(value).map_err(|_| { _ => $inner::from_str(value).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str()) Error::custom(format!("Invalid hex value {}.", value).as_str())
})) })?,
}; };
Ok($name(value)) Ok($name(value))

View File

@ -46,16 +46,16 @@ impl Visitor for InputVisitor {
let mut result = BTreeMap::new(); let mut result = BTreeMap::new();
loop { loop {
let key_str: Option<String> = try!(visitor.visit_key()); let key_str: Option<String> = visitor.visit_key()?;
let key = match key_str { let key = match key_str {
Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(ref k) if k.starts_with("0x") => Bytes::from_str(k).map_err(Error::custom)?,
Some(k) => Bytes::new(k.into_bytes()), Some(k) => Bytes::new(k.into_bytes()),
None => { break; } None => { break; }
}; };
let val_str: Option<String> = try!(visitor.visit_value()); let val_str: Option<String> = visitor.visit_value()?;
let val = match val_str { let val = match val_str {
Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) if v.starts_with("0x") => Some(Bytes::from_str(v).map_err(Error::custom)?),
Some(v) => Some(Bytes::new(v.into_bytes())), Some(v) => Some(Bytes::new(v.into_bytes())),
None => None, None => None,
}; };
@ -63,7 +63,7 @@ impl Visitor for InputVisitor {
result.insert(key, val); result.insert(key, val);
} }
try!(visitor.end()); visitor.end()?;
let input = Input { let input = Input {
data: result data: result
@ -76,7 +76,7 @@ impl Visitor for InputVisitor {
let mut result = BTreeMap::new(); let mut result = BTreeMap::new();
loop { loop {
let keyval: Option<Vec<Option<String>>> = try!(visitor.visit()); let keyval: Option<Vec<Option<String>>> = visitor.visit()?;
let keyval = match keyval { let keyval = match keyval {
Some(k) => k, Some(k) => k,
_ => { break; }, _ => { break; },
@ -90,13 +90,13 @@ impl Visitor for InputVisitor {
let ref val_str: Option<String> = keyval[1]; let ref val_str: Option<String> = keyval[1];
let key = match *key_str { let key = match *key_str {
Some(ref k) if k.starts_with("0x") => try!(Bytes::from_str(k).map_err(Error::custom)), Some(ref k) if k.starts_with("0x") => Bytes::from_str(k).map_err(Error::custom)?,
Some(ref k) => Bytes::new(k.clone().into_bytes()), Some(ref k) => Bytes::new(k.clone().into_bytes()),
None => { break; } None => { break; }
}; };
let val = match *val_str { let val = match *val_str {
Some(ref v) if v.starts_with("0x") => Some(try!(Bytes::from_str(v).map_err(Error::custom))), Some(ref v) if v.starts_with("0x") => Some(Bytes::from_str(v).map_err(Error::custom)?),
Some(ref v) => Some(Bytes::new(v.clone().into_bytes())), Some(ref v) => Some(Bytes::new(v.clone().into_bytes())),
None => None, None => None,
}; };
@ -104,7 +104,7 @@ impl Visitor for InputVisitor {
result.insert(key, val); result.insert(key, val);
} }
try!(visitor.end()); visitor.end()?;
let input = Input { let input = Input {
data: result data: result

View File

@ -69,12 +69,12 @@ impl Visitor for UintVisitor {
let value = match value.len() { let value = match value.len() {
0 => U256::from(0), 0 => U256::from(0),
2 if value.starts_with("0x") => U256::from(0), 2 if value.starts_with("0x") => U256::from(0),
_ if value.starts_with("0x") => try!(U256::from_str(&value[2..]).map_err(|_| { _ if value.starts_with("0x") => U256::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_str()) Error::custom(format!("Invalid hex value {}.", value).as_str())
})), })?,
_ => try!(U256::from_dec_str(value).map_err(|_| { _ => U256::from_dec_str(value).map_err(|_| {
Error::custom(format!("Invalid decimal value {}.", value).as_str()) Error::custom(format!("Invalid decimal value {}.", value).as_str())
})) })?
}; };
Ok(Uint(value)) Ok(Uint(value))

View File

@ -86,10 +86,9 @@ pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> {
let mut open_options = fs::OpenOptions::new(); let mut open_options = fs::OpenOptions::new();
let maybe_file = match config.file.as_ref() { let maybe_file = match config.file.as_ref() {
Some(f) => Some(try!(open_options Some(f) => Some(open_options
.append(true).create(true).open(f) .append(true).create(true).open(f)
.map_err(|_| format!("Cannot write to log file given: {}", f)) .map_err(|_| format!("Cannot write to log file given: {}", f))?),
)),
None => None, None => None,
}; };

View File

@ -70,7 +70,7 @@ pub fn execute(cmd: AccountCmd) -> Result<String, String> {
} }
fn keys_dir(path: String, spec: SpecType) -> Result<DiskDirectory, 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); let mut path = PathBuf::from(&path);
path.push(spec.data_dir); path.push(spec.data_dir);
DiskDirectory::create(path).map_err(|e| format!("Could not open keys directory: {}", e)) 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> { fn new(n: NewAccount) -> Result<String, String> {
let password: String = match n.password_file { let password: String = match n.password_file {
Some(file) => try!(password_from_file(file)), Some(file) => password_from_file(file)?,
None => try!(password_prompt()), None => password_prompt()?,
}; };
let dir = Box::new(try!(keys_dir(n.path, n.spec))); let dir = Box::new(keys_dir(n.path, n.spec)?);
let secret_store = Box::new(try!(secret_store(dir, Some(n.iterations)))); let secret_store = Box::new(secret_store(dir, Some(n.iterations))?);
let acc_provider = AccountProvider::new(secret_store); 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)) Ok(format!("{:?}", new_account))
} }
fn list(list_cmd: ListAccounts) -> Result<String, String> { fn list(list_cmd: ListAccounts) -> Result<String, String> {
let dir = Box::new(try!(keys_dir(list_cmd.path, list_cmd.spec))); let dir = Box::new(keys_dir(list_cmd.path, list_cmd.spec)?);
let secret_store = Box::new(try!(secret_store(dir, None))); let secret_store = Box::new(secret_store(dir, None)?);
let acc_provider = AccountProvider::new(secret_store); let acc_provider = AccountProvider::new(secret_store);
let accounts = acc_provider.accounts(); let accounts = acc_provider.accounts();
let result = accounts.into_iter() let result = accounts.into_iter()
@ -110,11 +110,11 @@ fn list(list_cmd: ListAccounts) -> Result<String, String> {
} }
fn import(i: ImportAccounts) -> 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; let mut imported = 0;
for path in &i.from { for path in &i.from {
let from = DiskDirectory::at(path); 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)) Ok(format!("{} account(s) imported", imported))
} }
@ -123,8 +123,8 @@ fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> {
use std::io::ErrorKind; use std::io::ErrorKind;
use ethcore::ethstore::Error; use ethcore::ethstore::Error;
let dir = Box::new(try!(keys_dir(i.to, i.spec))); let dir = Box::new(keys_dir(i.to, i.spec)?);
let secret_store = Box::new(try!(secret_store(dir, None))); let secret_store = Box::new(secret_store(dir, None)?);
let geth_accounts = read_geth_accounts(i.testnet); let geth_accounts = read_geth_accounts(i.testnet);
match secret_store.import_geth_accounts(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())), 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(); let panic_handler = PanicHandler::new_in_arc();
// load spec file // load spec file
let spec = try!(cmd.spec.spec()); let spec = cmd.spec.spec()?;
// load genesis hash // load genesis hash
let genesis_hash = spec.genesis_header().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(); let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults // 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(); fdlimit::raise_fd_limit();
@ -169,20 +169,20 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let algorithm = cmd.pruning.to_algorithm(&user_defaults); let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on // 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 // 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. // prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm); let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path(); let snapshot_path = db_dirs.snapshot_path();
// execute upgrades // 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 // create dirs used by parity
try!(cmd.dirs.create_dirs(false, false)); cmd.dirs.create_dirs(false, false)?;
// prepare client config // prepare client config
let mut client_config = to_client_config( let mut client_config = to_client_config(
@ -202,14 +202,14 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
client_config.queue.verifier_settings = cmd.verifier_settings; client_config.queue.verifier_settings = cmd.verifier_settings;
// build client // build client
let service = try!(ClientService::start( let service = ClientService::start(
client_config, client_config,
&spec, &spec,
&client_path, &client_path,
&snapshot_path, &snapshot_path,
&cmd.dirs.ipc_path(), &cmd.dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec)), 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. // free up the spec in memory.
drop(spec); drop(spec);
@ -218,7 +218,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let client = service.client(); let client = service.client();
let mut instream: Box<io::Read> = match cmd.file_path { 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()), None => Box::new(io::stdin()),
}; };
@ -230,7 +230,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let format = match cmd.format { let format = match cmd.format {
Some(format) => format, Some(format) => format,
None => { 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] { match first_bytes[0] {
0xf9 => DataFormat::Binary, 0xf9 => DataFormat::Binary,
_ => DataFormat::Hex, _ => DataFormat::Hex,
@ -262,23 +262,23 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
let n = if first_read > 0 { let n = if first_read > 0 {
first_read first_read
} else { } 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; } if n == 0 { break; }
first_read = 0; 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); bytes.resize(s, 0);
try!(instream.read_exact(&mut bytes[n..]).map_err(|_| "Error reading from the file/stream.")); instream.read_exact(&mut bytes[n..]).map_err(|_| "Error reading from the file/stream.")?;
try!(do_import(bytes)); do_import(bytes)?;
} }
} }
DataFormat::Hex => { DataFormat::Hex => {
for line in BufReader::new(instream).lines() { 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}; let s = if first_read > 0 {from_utf8(&first_bytes).unwrap().to_owned() + &(s[..])} else {s};
first_read = 0; first_read = 0;
let bytes = try!(s.from_hex().map_err(|_| "Invalid hex in file/stream.")); let bytes = s.from_hex().map_err(|_| "Invalid hex in file/stream.")?;
try!(do_import(bytes)); do_import(bytes)?;
} }
} }
} }
@ -288,7 +288,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
user_defaults.pruning = algorithm; user_defaults.pruning = algorithm;
user_defaults.tracing = tracing; user_defaults.tracing = tracing;
user_defaults.fat_db = fat_db; user_defaults.fat_db = fat_db;
try!(user_defaults.save(&user_defaults_path)); user_defaults.save(&user_defaults_path)?;
let report = client.report(); let report = client.report();
@ -318,7 +318,7 @@ fn start_client(
) -> Result<ClientService, String> { ) -> Result<ClientService, String> {
// load spec file // load spec file
let spec = try!(spec.spec()); let spec = spec.spec()?;
// load genesis hash // load genesis hash
let genesis_hash = spec.genesis_header().hash(); let genesis_hash = spec.genesis_header().hash();
@ -330,7 +330,7 @@ fn start_client(
let user_defaults_path = db_dirs.user_defaults_path(); let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults // load user defaults
let user_defaults = try!(UserDefaults::load(&user_defaults_path)); let user_defaults = UserDefaults::load(&user_defaults_path)?;
fdlimit::raise_fd_limit(); fdlimit::raise_fd_limit();
@ -338,32 +338,32 @@ fn start_client(
let algorithm = pruning.to_algorithm(&user_defaults); let algorithm = pruning.to_algorithm(&user_defaults);
// check if tracing is on // 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 // 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. // prepare client and snapshot paths.
let client_path = db_dirs.client_path(algorithm); let client_path = db_dirs.client_path(algorithm);
let snapshot_path = db_dirs.snapshot_path(); let snapshot_path = db_dirs.snapshot_path();
// execute upgrades // 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 // create dirs used by parity
try!(dirs.create_dirs(false, false)); dirs.create_dirs(false, false)?;
// prepare client config // 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 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, client_config,
&spec, &spec,
&client_path, &client_path,
&snapshot_path, &snapshot_path,
&dirs.ipc_path(), &dirs.ipc_path(),
Arc::new(Miner::with_spec(&spec)), Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e))); ).map_err(|e| format!("Client service error: {:?}", e))?;
drop(spec); drop(spec);
Ok(service) Ok(service)
@ -371,7 +371,7 @@ fn start_client(
fn execute_export(cmd: ExportBlockchain) -> Result<(), String> { fn execute_export(cmd: ExportBlockchain) -> Result<(), String> {
// Setup panic handler // 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 panic_handler = PanicHandler::new_in_arc();
let format = cmd.format.unwrap_or_default(); let format = cmd.format.unwrap_or_default();
@ -379,18 +379,18 @@ fn execute_export(cmd: ExportBlockchain) -> Result<(), String> {
let client = service.client(); let client = service.client();
let mut out: Box<io::Write> = match cmd.file_path { 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()), None => Box::new(io::stdout()),
}; };
let from = try!(client.block_number(cmd.from_block).ok_or("From block could not be found")); let from = 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 to = client.block_number(cmd.to_block).ok_or("To block could not be found")?;
for i in from..(to + 1) { for i in from..(to + 1) {
if i % 10000 == 0 { if i % 10000 == 0 {
info!("#{}", i); 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")?;
match format { match format {
DataFormat::Binary => { out.write(&b).expect("Couldn't write to stream."); } 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."); } 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> { fn execute_export_state(cmd: ExportState) -> Result<(), String> {
// Setup panic handler // 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 panic_handler = PanicHandler::new_in_arc();
panic_handler.forward_from(&service); panic_handler.forward_from(&service);
let client = service.client(); let client = service.client();
let mut out: Box<io::Write> = match cmd.file_path { 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()), 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."); out.write_fmt(format_args!("{{ \"state\": [", )).expect("Couldn't write to stream.");
loop { 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() { if accounts.is_empty() {
break; break;
} }
@ -450,7 +450,7 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> {
out.write_fmt(format_args!(", \"storage\": {{")).expect("Write error"); out.write_fmt(format_args!(", \"storage\": {{")).expect("Write error");
let mut last_storage: Option<H256> = None; let mut last_storage: Option<H256> = None;
loop { 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() { if keys.is_empty() {
break; break;
} }
@ -482,14 +482,14 @@ fn execute_export_state(cmd: ExportState) -> Result<(), String> {
} }
pub fn kill_db(cmd: KillBlockchain) -> 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 genesis_hash = spec.genesis_header().hash();
let db_dirs = cmd.dirs.database(genesis_hash, None, spec.data_dir); let db_dirs = cmd.dirs.database(genesis_hash, None, spec.data_dir);
let user_defaults_path = db_dirs.user_defaults_path(); 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 algorithm = cmd.pruning.to_algorithm(&user_defaults);
let dir = db_dirs.db_path(algorithm); 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."); info!("Database deleted.");
Ok(()) Ok(())
} }

View File

@ -53,9 +53,7 @@ pub fn payload<B: ipc::BinaryConvertable>() -> Result<B, BootError> {
use std::io::Read; use std::io::Read;
let mut buffer = Vec::new(); 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) ipc::binary::deserialize::<B>(&buffer).map_err(BootError::DecodeArgs)
} }

View File

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

View File

@ -85,7 +85,7 @@ pub struct Configuration {
impl Configuration { impl Configuration {
pub fn parse<S: AsRef<str>>(command: &[S]) -> Result<Self, ArgsError> { 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 { let config = Configuration {
args: args, args: args,
@ -96,29 +96,29 @@ impl Configuration {
pub fn into_command(self) -> Result<Execute, String> { pub fn into_command(self) -> Result<Execute, String> {
let dirs = self.directories(); 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 pruning_history = self.args.flag_pruning_history;
let vm_type = try!(self.vm_type()); let vm_type = 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 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 = try!(self.update_policy()); let update_policy = self.update_policy()?;
let miner_options = try!(self.miner_options()); let miner_options = self.miner_options()?;
let logger_config = self.logger_config(); let logger_config = self.logger_config();
let http_conf = try!(self.http_config()); let http_conf = self.http_config()?;
let ipc_conf = try!(self.ipc_config()); let ipc_conf = self.ipc_config()?;
let net_conf = try!(self.net_config()); let net_conf = self.net_config()?;
let network_id = self.network_id(); let network_id = self.network_id();
let cache_config = self.cache_config(); let cache_config = self.cache_config();
let spec = try!(self.chain().parse()); let spec = self.chain().parse()?;
let tracing = try!(self.args.flag_tracing.parse()); let tracing = self.args.flag_tracing.parse()?;
let fat_db = try!(self.args.flag_fat_db.parse()); let fat_db = self.args.flag_fat_db.parse()?;
let compaction = try!(self.args.flag_db_compaction.parse()); let compaction = self.args.flag_db_compaction.parse()?;
let wal = !self.args.flag_fast_and_loose; let wal = !self.args.flag_fast_and_loose;
let warp_sync = self.args.flag_warp; let warp_sync = self.args.flag_warp;
let geth_compatibility = self.args.flag_geth; let geth_compatibility = self.args.flag_geth;
let ui_address = self.ui_port().map(|port| (self.ui_interface(), port)); let ui_address = self.ui_port().map(|port| (self.ui_interface(), port));
let dapps_conf = self.dapps_config(); let dapps_conf = self.dapps_config();
let signer_conf = self.signer_config(); let signer_conf = self.signer_config();
let format = try!(self.format()); let format = self.format()?;
let cmd = if self.args.flag_version { let cmd = if self.args.flag_version {
Cmd::Version Cmd::Version
@ -237,8 +237,8 @@ impl Configuration {
wal: wal, wal: wal,
tracing: tracing, tracing: tracing,
fat_db: fat_db, fat_db: fat_db,
from_block: try!(to_block_id(&self.args.flag_from)), from_block: to_block_id(&self.args.flag_from)?,
to_block: try!(to_block_id(&self.args.flag_to)), to_block: to_block_id(&self.args.flag_to)?,
check_seal: !self.args.flag_no_seal_check, check_seal: !self.args.flag_no_seal_check,
}; };
Cmd::Blockchain(BlockchainCmd::Export(export_cmd)) Cmd::Blockchain(BlockchainCmd::Export(export_cmd))
@ -255,7 +255,7 @@ impl Configuration {
wal: wal, wal: wal,
tracing: tracing, tracing: tracing,
fat_db: fat_db, 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, storage: !self.args.flag_no_storage,
code: !self.args.flag_no_code, code: !self.args.flag_no_code,
min_balance: self.args.flag_min_balance.and_then(|s| to_u256(&s).ok()), 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(), file_path: self.args.arg_file.clone(),
wal: wal, wal: wal,
kind: snapshot::Kind::Take, 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) Cmd::Snapshot(snapshot_cmd)
} else if self.args.cmd_restore { } else if self.args.cmd_restore {
@ -294,7 +294,7 @@ impl Configuration {
file_path: self.args.arg_file.clone(), file_path: self.args.arg_file.clone(),
wal: wal, wal: wal,
kind: snapshot::Kind::Restore, kind: snapshot::Kind::Restore,
block_at: try!(to_block_id("latest")), // unimportant. block_at: to_block_id("latest")?, // unimportant.
}; };
Cmd::Snapshot(restore_cmd) Cmd::Snapshot(restore_cmd)
} else { } else {
@ -319,9 +319,9 @@ impl Configuration {
ipc_conf: ipc_conf, ipc_conf: ipc_conf,
net_conf: net_conf, net_conf: net_conf,
network_id: network_id, network_id: network_id,
acc_conf: try!(self.accounts_config()), acc_conf: self.accounts_config()?,
gas_pricer: try!(self.gas_pricer_config()), gas_pricer: self.gas_pricer_config()?,
miner_extras: try!(self.miner_extras()), miner_extras: self.miner_extras()?,
update_policy: update_policy, update_policy: update_policy,
mode: mode, mode: mode,
tracing: tracing, tracing: tracing,
@ -362,12 +362,12 @@ impl Configuration {
fn miner_extras(&self) -> Result<MinerExtras, String> { fn miner_extras(&self) -> Result<MinerExtras, String> {
let extras = MinerExtras { let extras = MinerExtras {
author: try!(self.author()), author: self.author()?,
extra_data: try!(self.extra_data()), extra_data: self.extra_data()?,
gas_floor_target: try!(to_u256(&self.args.flag_gas_floor_target)), gas_floor_target: to_u256(&self.args.flag_gas_floor_target)?,
gas_ceil_target: try!(to_u256(&self.args.flag_gas_cap)), gas_ceil_target: to_u256(&self.args.flag_gas_cap)?,
transactions_limit: self.args.flag_tx_queue_size, transactions_limit: self.args.flag_tx_queue_size,
engine_signer: try!(self.engine_signer()), engine_signer: self.engine_signer()?,
}; };
Ok(extras) Ok(extras)
@ -383,7 +383,7 @@ impl Configuration {
fn format(&self) -> Result<Option<DataFormat>, String> { fn format(&self) -> Result<Option<DataFormat>, String> {
match self.args.flag_format { match self.args.flag_format {
Some(ref f) => Ok(Some(try!(f.parse()))), Some(ref f) => Ok(Some(f.parse()?)),
None => Ok(None), None => Ok(None),
} }
} }
@ -451,14 +451,14 @@ impl Configuration {
iterations: self.args.flag_keys_iterations, iterations: self.args.flag_keys_iterations,
testnet: self.args.flag_testnet, testnet: self.args.flag_testnet,
password_files: self.args.flag_password.clone(), 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) Ok(cfg)
} }
fn miner_options(&self) -> Result<MinerOptions, String> { 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 { let options = MinerOptions {
new_work_notify: self.work_notify(), new_work_notify: self.work_notify(),
@ -466,13 +466,13 @@ impl Configuration {
reseal_on_external_tx: reseal.external, reseal_on_external_tx: reseal.external,
reseal_on_own_tx: reseal.own, reseal_on_own_tx: reseal.own,
tx_gas_limit: match self.args.flag_tx_gas_limit { 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(), None => U256::max_value(),
}, },
tx_queue_size: self.args.flag_tx_queue_size, 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_gas_limit: to_gas_limit(&self.args.flag_tx_queue_gas)?,
tx_queue_strategy: try!(to_queue_strategy(&self.args.flag_tx_queue_strategy)), tx_queue_strategy: to_queue_strategy(&self.args.flag_tx_queue_strategy)?,
pending_set: try!(to_pending_set(&self.args.flag_relay_set)), pending_set: to_pending_set(&self.args.flag_relay_set)?,
reseal_min_period: Duration::from_millis(self.args.flag_reseal_min_period), reseal_min_period: Duration::from_millis(self.args.flag_reseal_min_period),
work_queue_size: self.args.flag_work_queue_size, work_queue_size: self.args.flag_work_queue_size,
enable_resubmission: !self.args.flag_remove_solved, enable_resubmission: !self.args.flag_remove_solved,
@ -513,18 +513,18 @@ impl Configuration {
fn gas_pricer_config(&self) -> Result<GasPricerConfig, String> { fn gas_pricer_config(&self) -> Result<GasPricerConfig, String> {
if let Some(d) = self.args.flag_gasprice.as_ref() { 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() { if "auto" == self.args.flag_usd_per_eth.as_str() {
return Ok(GasPricerConfig::Calibrated { return Ok(GasPricerConfig::Calibrated {
usd_per_tx: usd_per_tx, 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 wei_per_usd: f32 = 1.0e18 / usd_per_eth;
let gas_per_tx: f32 = 21000.0; let gas_per_tx: f32 = 21000.0;
let wei_per_gas: f32 = wei_per_usd * usd_per_tx / gas_per_tx; let wei_per_gas: f32 = wei_per_usd * usd_per_tx / gas_per_tx;
@ -552,8 +552,8 @@ impl Configuration {
match self.args.flag_reserved_peers { match self.args.flag_reserved_peers {
Some(ref path) => { Some(ref path) => {
let mut buffer = String::new(); let mut buffer = String::new();
let mut node_file = try!(File::open(path).map_err(|e| format!("Error opening reserved nodes file: {}", e))); let mut node_file = 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")); 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<_>>(); 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)) { 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)); return Err(format!("Invalid node address format given for a boot node: {}", invalid));
@ -569,7 +569,7 @@ impl Configuration {
let listen_address = Some(SocketAddr::new("0.0.0.0".parse().unwrap(), port)); 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 public_address = if self.args.flag_nat.starts_with("extip:") {
let host = &self.args.flag_nat[6..]; 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)) Some(SocketAddr::new(host, port))
} else { } else {
None None
@ -580,8 +580,8 @@ impl Configuration {
fn net_config(&self) -> Result<NetworkConfiguration, String> { fn net_config(&self) -> Result<NetworkConfiguration, String> {
let mut ret = NetworkConfiguration::new(); let mut ret = NetworkConfiguration::new();
ret.nat_enabled = self.args.flag_nat == "any" || self.args.flag_nat == "upnp"; ret.nat_enabled = self.args.flag_nat == "any" || self.args.flag_nat == "upnp";
ret.boot_nodes = try!(to_bootnodes(&self.args.flag_bootnodes)); ret.boot_nodes = to_bootnodes(&self.args.flag_bootnodes)?;
let (listen, public) = try!(self.net_addresses()); let (listen, public) = self.net_addresses()?;
ret.listen_address = listen.map(|l| format!("{}", l)); ret.listen_address = listen.map(|l| format!("{}", l));
ret.public_address = public.map(|p| format!("{}", p)); 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())); ret.use_secret = self.args.flag_node_key.as_ref().map(|s| s.parse::<Secret>().unwrap_or_else(|_| s.sha3()));
@ -589,12 +589,12 @@ impl Configuration {
ret.max_peers = self.max_peers(); ret.max_peers = self.max_peers();
ret.min_peers = self.min_peers(); ret.min_peers = self.min_peers();
ret.snapshot_peers = self.snapshot_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(); ret.max_pending_peers = self.max_pending_peers();
let mut net_path = PathBuf::from(self.directories().base); let mut net_path = PathBuf::from(self.directories().base);
net_path.push("network"); net_path.push("network");
ret.config_path = Some(net_path.to_str().unwrap().to_owned()); 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; ret.allow_non_reserved = !self.args.flag_reserved_only;
Ok(ret) Ok(ret)
} }
@ -651,7 +651,7 @@ impl Configuration {
} }
apis.push_str("personal"); apis.push_str("personal");
} }
try!(apis.parse()) apis.parse()?
}, },
}; };
@ -663,7 +663,7 @@ impl Configuration {
enabled: !self.args.flag_jsonrpc_off && !self.args.flag_no_jsonrpc, enabled: !self.args.flag_jsonrpc_off && !self.args.flag_no_jsonrpc,
interface: self.rpc_interface(), interface: self.rpc_interface(),
port: self.args.flag_rpcport.unwrap_or(self.args.flag_jsonrpc_port), 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(), hosts: self.rpc_hosts(),
cors: self.rpc_cors(), cors: self.rpc_cors(),
}; };

View File

@ -67,7 +67,7 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<We
} }
let url = format!("{}:{}", configuration.interface, configuration.port); 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 auth = configuration.user.as_ref().map(|username| {
let password = configuration.pass.as_ref().map_or_else(|| { let password = configuration.pass.as_ref().map_or_else(|| {
@ -80,7 +80,7 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<We
(username.to_owned(), password) (username.to_owned(), password)
}); });
Ok(Some(try!(setup_dapps_server(deps, configuration.dapps_path, &addr, configuration.hosts, auth)))) Ok(Some(setup_dapps_server(deps, configuration.dapps_path, &addr, configuration.hosts, auth)?))
} }
pub use self::server::WebappServer; pub use self::server::WebappServer;

View File

@ -59,14 +59,14 @@ impl Default for Directories {
impl Directories { impl Directories {
pub fn create_dirs(&self, dapps_enabled: bool, signer_enabled: bool) -> Result<(), String> { 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())); 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())); 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.keys).map_err(|e| e.to_string())?;
if signer_enabled { 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 { 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(()) Ok(())
} }

View File

@ -97,7 +97,7 @@ pub fn to_gas_limit(s: &str) -> Result<GasLimit, String> {
match s { match s {
"auto" => Ok(GasLimit::Auto), "auto" => Ok(GasLimit::Auto),
"off" => Ok(GasLimit::None), "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: "); print!("Type password: ");
flush_stdout(); 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: "); print!("Repeat password: ");
flush_stdout(); 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 { if password != password_repeat {
return Err("Passwords do not match!".into()); return Err("Passwords do not match!".into());
@ -304,7 +304,7 @@ pub fn password_prompt() -> Result<String, String> {
/// Read a password from password file. /// Read a password from password file.
pub fn password_from_file(path: String) -> Result<String, String> { 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 // use only first password from the file
passwords.get(0).map(String::to_owned) passwords.get(0).map(String::to_owned)
.ok_or_else(|| "Password file seems to be empty.".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. /// Reads passwords from files. Treats each line as a separate password.
pub fn passwords_from_files(files: &[String]) -> Result<Vec<String>, String> { pub fn passwords_from_files(files: &[String]) -> Result<Vec<String>, String> {
let passwords = files.iter().map(|filename| { 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 reader = BufReader::new(&file);
let lines = reader.lines() let lines = reader.lines()
.filter_map(|l| l.ok()) .filter_map(|l| l.ok())
@ -321,7 +321,7 @@ pub fn passwords_from_files(files: &[String]) -> Result<Vec<String>, String> {
.collect::<Vec<String>>(); .collect::<Vec<String>>();
Ok(lines) Ok(lines)
}).collect::<Result<Vec<Vec<String>>, String>>(); }).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)] #[cfg(test)]

View File

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

View File

@ -104,7 +104,7 @@ fn current_version(path: &Path) -> Result<u32, Error> {
Err(_) => Err(Error::UnknownDatabaseVersion), Err(_) => Err(Error::UnknownDatabaseVersion),
Ok(mut file) => { Ok(mut file) => {
let mut s = String::new(); 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) 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. /// Writes current database version to the file.
/// Creates a new file if the version file does not exist yet. /// Creates a new file if the version file does not exist yet.
fn update_version(path: &Path) -> Result<(), Error> { fn update_version(path: &Path) -> Result<(), Error> {
try!(fs::create_dir_all(path)); fs::create_dir_all(path)?;
let mut file = try!(File::create(version_file_path(path))); let mut file = File::create(version_file_path(path))?;
try!(file.write_all(format!("{}", CURRENT_VERSION).as_bytes())); file.write_all(format!("{}", CURRENT_VERSION).as_bytes())?;
Ok(()) Ok(())
} }
@ -145,7 +145,7 @@ pub fn default_migration_settings(compaction_profile: &CompactionProfile) -> Mig
/// Migrations on the consolidated database. /// Migrations on the consolidated database.
fn consolidated_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> { fn consolidated_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> {
let mut manager = MigrationManager::new(default_migration_settings(compaction_profile)); 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) Ok(manager)
} }
@ -171,16 +171,16 @@ fn consolidate_database(
wal: true, wal: true,
}; };
let old_path_str = try!(old_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 = try!(new_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 // open new DB with proper number of columns
db_config.columns = migration.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) // 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(()) Ok(())
} }
@ -198,20 +198,20 @@ fn migrate_database(version: u32, db_path: PathBuf, mut migrations: MigrationMan
let _ = fs::remove_dir_all(&backup_path); let _ = fs::remove_dir_all(&backup_path);
// migrate old database to the new one // 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 // create backup
try!(fs::rename(&db_path, &backup_path)); fs::rename(&db_path, &backup_path)?;
// replace the old database with the new one // replace the old database with the new one
if let Err(err) = fs::rename(&temp_path, &db_path) { if let Err(err) = fs::rename(&temp_path, &db_path) {
// if something went wrong, bring back backup // if something went wrong, bring back backup
try!(fs::rename(&backup_path, &db_path)); fs::rename(&backup_path, &db_path)?;
return Err(err.into()); return Err(err.into());
} }
// remove backup // remove backup
try!(fs::remove_dir_all(&backup_path)); fs::remove_dir_all(&backup_path)?;
Ok(()) Ok(())
} }
@ -223,7 +223,7 @@ fn exists(path: &Path) -> bool {
/// Migrates the database. /// Migrates the database.
pub fn migrate(path: &Path, pruning: Algorithm, compaction_profile: CompactionProfile) -> Result<(), Error> { pub fn migrate(path: &Path, pruning: Algorithm, compaction_profile: CompactionProfile) -> Result<(), Error> {
// read version file. // read version file.
let version = try!(current_version(path)); let version = current_version(path)?;
// migrate the databases. // migrate the databases.
// main db directory may already exists, so let's check if we have blocks dir // 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)) { if version < CONSOLIDATION_VERSION && exists(&legacy::blocks_database_path(path)) {
println!("Migrating database from version {} to {}", version, CONSOLIDATION_VERSION); 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)))); migrate_database(version, legacy::extras_database_path(path), legacy::extras_database_migrations(&compaction_profile)?)?;
try!(migrate_database(version, legacy::state_database_path(path), try!(legacy::state_database_migrations(pruning, &compaction_profile)))); migrate_database(version, legacy::state_database_path(path), 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::blocks_database_path(path), legacy::blocks_database_migrations(&compaction_profile)?)?;
let db_path = consolidated_database_path(path); let db_path = consolidated_database_path(path);
// Remove the database dir (it shouldn't exist anyway, but it might when migration was interrupted) // Remove the database dir (it shouldn't exist anyway, but it might when migration was interrupted)
let _ = fs::remove_dir_all(db_path.clone()); 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)); 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)); 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)); 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)); 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::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::blocks_database_path(path));
let _ = fs::remove_dir_all(legacy::extras_database_path(path)); let _ = fs::remove_dir_all(legacy::extras_database_path(path));
let _ = fs::remove_dir_all(legacy::state_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 // Further migrations
if version >= CONSOLIDATION_VERSION && version < CURRENT_VERSION && exists(&consolidated_database_path(path)) { 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); 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"); println!("Migration finished");
} }
@ -313,14 +313,14 @@ mod legacy {
/// Migrations on the blocks database. /// Migrations on the blocks database.
pub fn blocks_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> { pub fn blocks_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> {
let mut manager = MigrationManager::new(default_migration_settings(compaction_profile)); 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) Ok(manager)
} }
/// Migrations on the extras database. /// Migrations on the extras database.
pub fn extras_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> { pub fn extras_database_migrations(compaction_profile: &CompactionProfile) -> Result<MigrationManager, Error> {
let mut manager = MigrationManager::new(default_migration_settings(compaction_profile)); 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) Ok(manager)
} }
@ -333,7 +333,7 @@ mod legacy {
_ => return Err(Error::UnsupportedPruningMethod), _ => return Err(Error::UnsupportedPruningMethod),
}; };
try!(res.map_err(|_| Error::MigrationImpossible)); res.map_err(|_| Error::MigrationImpossible)?;
Ok(manager) Ok(manager)
} }
} }

View File

@ -171,13 +171,13 @@ pub fn sync
) )
-> Result<SyncModules, NetworkError> -> Result<SyncModules, NetworkError>
{ {
let eth_sync = try!(EthSync::new(Params { let eth_sync = EthSync::new(Params {
config: sync_cfg, config: sync_cfg,
chain: client, chain: client,
provider: provider, provider: provider,
snapshot_service: snapshot_service, snapshot_service: snapshot_service,
network_config: net_cfg, network_config: net_cfg,
})); })?;
Ok((eth_sync.clone() as Arc<SyncProvider>, eth_sync.clone() as Arc<ManageNetwork>, eth_sync.clone() as Arc<ChainNotify>)) 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::Expanse => Ok(ethereum::new_expanse()),
SpecType::Dev => Ok(Spec::new_instant()), SpecType::Dev => Ok(Spec::new_instant()),
SpecType::Custom(ref filename) => { 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) Spec::load(file)
} }
} }

View File

@ -31,15 +31,15 @@ pub struct ImportWallet {
pub fn execute(cmd: ImportWallet) -> Result<String, String> { pub fn execute(cmd: ImportWallet) -> Result<String, String> {
let password: String = match cmd.password_file { let password: String = match cmd.password_file {
Some(file) => try!(password_from_file(file)), Some(file) => password_from_file(file)?,
None => try!(password_prompt()), None => password_prompt()?,
}; };
let dir = Box::new(DiskDirectory::create(cmd.path).unwrap()); let dir = Box::new(DiskDirectory::create(cmd.path).unwrap());
let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap()); let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap());
let acc_provider = AccountProvider::new(secret_store); let acc_provider = AccountProvider::new(secret_store);
let wallet = try!(PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")); let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?;
let kp = try!(wallet.decrypt(&password).map_err(|_| "Invalid password.")); let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?;
let address = acc_provider.insert_account(*kp.secret(), &password).unwrap(); let address = acc_provider.insert_account(*kp.secret(), &password).unwrap();
Ok(format!("{:?}", address)) 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 url = format!("{}:{}", conf.interface, conf.port);
let addr = try!(url.parse().map_err(|_| format!("Invalid JSONRPC listen host/port given: {}", url))); let addr = 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)))) 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> { 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>>, allowed_hosts: Option<Vec<String>>,
apis: ApiSet apis: ApiSet
) -> Result<HttpServer, String> { ) -> 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 ph = dependencies.panic_handler.clone();
let start_result = server.start_http(url, cors_domains, allowed_hosts, ph); let start_result = server.start_http(url, cors_domains, allowed_hosts, ph);
match start_result { 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> { pub fn new_ipc(conf: IpcConfiguration, deps: &Dependencies) -> Result<Option<IpcServer>, String> {
if !conf.enabled { return Ok(None); } 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> { 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) { match server.start_ipc(addr) {
Err(IpcServerError::Io(io_error)) => Err(format!("RPC io error: {}", io_error)), Err(IpcServerError::Io(io_error)) => Err(format!("RPC io error: {}", io_error)),
Err(any_error) => Err(format!("Rpc error: {:?}", any_error)), Err(any_error) => Err(format!("Rpc error: {:?}", any_error)),

View File

@ -109,7 +109,7 @@ pub fn open_ui(dapps_conf: &dapps::Configuration, signer_conf: &signer::Configur
return Err("Cannot use UI command with UI turned off.".into()) 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 // Open a browser
url::open(&token.url); url::open(&token.url);
// Print a message // Print a message
@ -133,7 +133,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
raise_fd_limit(); raise_fd_limit();
// load spec // load spec
let spec = try!(cmd.spec.spec()); let spec = cmd.spec.spec()?;
// load genesis hash // load genesis hash
let genesis_hash = spec.genesis_header().hash(); let genesis_hash = spec.genesis_header().hash();
@ -145,19 +145,19 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let user_defaults_path = db_dirs.user_defaults_path(); let user_defaults_path = db_dirs.user_defaults_path();
// load user defaults // 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 // select pruning algorithm
let algorithm = cmd.pruning.to_algorithm(&user_defaults); let algorithm = cmd.pruning.to_algorithm(&user_defaults);
// check if tracing is on // 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 // 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 // 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); trace!(target: "mode", "mode is {:?}", mode);
let network_enabled = match mode { Mode::Dark(_) | Mode::Off => false, _ => true, }; let network_enabled = match mode { Mode::Dark(_) | Mode::Off => false, _ => true, };
@ -169,14 +169,14 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let snapshot_path = db_dirs.snapshot_path(); let snapshot_path = db_dirs.snapshot_path();
// execute upgrades // 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 // 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 // run in daemon mode
if let Some(pid_file) = cmd.daemon { if let Some(pid_file) = cmd.daemon {
try!(daemonize(pid_file)); daemonize(pid_file)?;
} }
// display info about used pruning algorithm // display info about used pruning algorithm
@ -214,10 +214,10 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
sync_config.warp_sync = cmd.warp_sync; sync_config.warp_sync = cmd.warp_sync;
sync_config.download_old_blocks = cmd.download_old_blocks; 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 // 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 // let the Engine access the accounts
spec.engine.register_account_provider(account_provider.clone()); spec.engine.register_account_provider(account_provider.clone());
@ -266,14 +266,14 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path()); let mut hypervisor = modules::hypervisor(&cmd.dirs.ipc_path());
// create client service. // create client service.
let service = try!(ClientService::start( let service = ClientService::start(
client_config, client_config,
&spec, &spec,
&client_path, &client_path,
&snapshot_path, &snapshot_path,
&cmd.dirs.ipc_path(), &cmd.dirs.ipc_path(),
miner.clone(), 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 the spec to free up genesis state.
drop(spec); drop(spec);
@ -289,7 +289,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let external_miner = Arc::new(ExternalMiner::default()); let external_miner = Arc::new(ExternalMiner::default());
// create sync object // create sync object
let (sync_provider, manage_network, chain_notify) = try!(modules::sync( let (sync_provider, manage_network, chain_notify) = modules::sync(
&mut hypervisor, &mut hypervisor,
sync_config, sync_config,
net_conf.into(), net_conf.into(),
@ -297,7 +297,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
snapshot_service.clone(), snapshot_service.clone(),
client.clone(), client.clone(),
&cmd.logger_config, &cmd.logger_config,
).map_err(|e| format!("Sync error: {}", e))); ).map_err(|e| format!("Sync error: {}", e))?;
service.add_notify(chain_notify.clone()); service.add_notify(chain_notify.clone());
@ -310,7 +310,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
let event_loop = EventLoop::spawn(); let event_loop = EventLoop::spawn();
// fetch service // 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 // the updater service
let updater = Updater::new( let updater = Updater::new(
@ -359,8 +359,8 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
}; };
// start rpc servers // start rpc servers
let http_server = try!(rpc::new_http(cmd.http_conf, &dependencies)); let http_server = rpc::new_http(cmd.http_conf, &dependencies)?;
let ipc_server = try!(rpc::new_ipc(cmd.ipc_conf, &dependencies)); let ipc_server = rpc::new_ipc(cmd.ipc_conf, &dependencies)?;
// the dapps server // the dapps server
let dapps_deps = dapps::Dependencies { let dapps_deps = dapps::Dependencies {
@ -372,14 +372,14 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
fetch: fetch.clone(), fetch: fetch.clone(),
signer: deps_for_rpc_apis.signer_service.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 // the signer server
let signer_deps = signer::Dependencies { let signer_deps = signer::Dependencies {
panic_handler: panic_handler.clone(), panic_handler: panic_handler.clone(),
apis: deps_for_rpc_apis.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 // the informant
let informant = Arc::new(Informant::new( let informant = Arc::new(Informant::new(
@ -397,7 +397,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
user_defaults.tracing = tracing; user_defaults.tracing = tracing;
user_defaults.fat_db = fat_db; user_defaults.fat_db = fat_db;
user_defaults.mode = mode; 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. // tell client how to save the default mode if it gets changed.
client.on_mode_change(move |mode: &Mode| { client.on_mode_change(move |mode: &Mode| {
@ -425,7 +425,7 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
// start ui // start ui
if cmd.ui { if cmd.ui {
try!(open_ui(&cmd.dapps_conf, &cmd.signer_conf)); open_ui(&cmd.dapps_conf, &cmd.signer_conf)?;
} }
// Handle exit // Handle exit
@ -477,9 +477,9 @@ fn prepare_account_provider(dirs: &Directories, data_dir: &str, cfg: AccountsCon
let path = dirs.keys_path(data_dir); let path = dirs.keys_path(data_dir);
upgrade_key_location(&dirs.legacy_keys_path(cfg.testnet), &path); 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( 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 { 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 { if !conf.enabled {
Ok(None) Ok(None)
} else { } 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> { 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> { 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); let auth_url = format!("http://{}:{}/#/auth?token={}", conf.interface, conf.port, code);
// And print in to the console // And print in to the console
Ok(NewToken { Ok(NewToken {
@ -101,18 +101,18 @@ Or use the generated token:
pub fn generate_new_token(path: String) -> io::Result<String> { pub fn generate_new_token(path: String) -> io::Result<String> {
let path = codes_path(path); 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(); codes.clear_garbage();
let code = try!(codes.generate_new()); let code = codes.generate_new()?;
try!(codes.to_file(&path)); codes.to_file(&path)?;
trace!("New key code created: {}", Colour::White.bold().paint(&code[..])); trace!("New key code created: {}", Colour::White.bold().paint(&code[..]));
Ok(code) Ok(code)
} }
fn do_start(conf: Configuration, deps: Dependencies) -> Result<SignerServer, String> { 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() .parse()
.map_err(|_| format!("Invalid port specified: {}", conf.port))); .map_err(|_| format!("Invalid port specified: {}", conf.port))?;
let start_result = { let start_result = {
let server = signer::ServerBuilder::new( let server = signer::ServerBuilder::new(

Some files were not shown because too many files have changed in this diff Show More