From b2594087db73c1590c5fe018d8e38e02098ca452 Mon Sep 17 00:00:00 2001 From: Jean Pierre Dudey Date: Sun, 12 Aug 2018 12:47:31 -0400 Subject: [PATCH] Use the `?` (try) instead of the `try!` macro. Signed-off-by: Jean Pierre Dudey --- src/blockdata/opcodes.rs | 2 +- src/blockdata/script.rs | 36 ++++++++-------- src/blockdata/transaction.rs | 50 +++++++++++------------ src/internal_macros.rs | 36 ++++++++-------- src/network/address.rs | 10 ++--- src/network/encodable.rs | 70 ++++++++++++++++---------------- src/network/listener.rs | 4 +- src/network/message.rs | 42 +++++++++---------- src/network/message_blockdata.rs | 8 ++-- src/network/message_network.rs | 4 +- src/network/serialize.rs | 4 +- src/network/socket.rs | 6 +-- src/util/address.rs | 2 +- src/util/base58.rs | 2 +- src/util/bip32.rs | 26 ++++++------ src/util/contracthash.rs | 14 +++---- src/util/decimal.rs | 4 +- src/util/hash.rs | 8 ++-- src/util/misc.rs | 4 +- src/util/privkey.rs | 6 +-- src/util/uint.rs | 8 ++-- 21 files changed, 173 insertions(+), 173 deletions(-) diff --git a/src/blockdata/opcodes.rs b/src/blockdata/opcodes.rs index d46509c..037577a 100644 --- a/src/blockdata/opcodes.rs +++ b/src/blockdata/opcodes.rs @@ -609,7 +609,7 @@ display_from_debug!(All); impl ConsensusDecodable for All { #[inline] fn consensus_decode(d: &mut D) -> Result { - Ok(All::from(try!(d.read_u8()))) + Ok(All::from(d.read_u8()?)) } } diff --git a/src/blockdata/script.rs b/src/blockdata/script.rs index 068cee2..bf5dce5 100644 --- a/src/blockdata/script.rs +++ b/src/blockdata/script.rs @@ -49,7 +49,7 @@ impl fmt::Debug for Script { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut index = 0; - try!(f.write_str("Script(")); + f.write_str("Script(")?; while index < self.0.len() { let opcode = opcodes::All::from(self.0[index]); index += 1; @@ -60,55 +60,55 @@ impl fmt::Debug for Script { match opcode { opcodes::All::OP_PUSHDATA1 => { if self.0.len() < index + 1 { - try!(f.write_str("")); + f.write_str("")?; break; } match read_uint(&self.0[index..], 1) { Ok(n) => { index += 1; n as usize } - Err(_) => { try!(f.write_str("")); break; } + Err(_) => { f.write_str("")?; break; } } } opcodes::All::OP_PUSHDATA2 => { if self.0.len() < index + 2 { - try!(f.write_str("")); + f.write_str("")?; break; } match read_uint(&self.0[index..], 2) { Ok(n) => { index += 2; n as usize } - Err(_) => { try!(f.write_str("")); break; } + Err(_) => { f.write_str("")?; break; } } } opcodes::All::OP_PUSHDATA4 => { if self.0.len() < index + 4 { - try!(f.write_str("")); + f.write_str("")?; break; } match read_uint(&self.0[index..], 4) { Ok(n) => { index += 4; n as usize } - Err(_) => { try!(f.write_str("")); break; } + Err(_) => { f.write_str("")?; break; } } } _ => 0 } }; - if index > 1 { try!(f.write_str(" ")); } + if index > 1 { f.write_str(" ")?; } // Write the opcode if opcode == opcodes::All::OP_PUSHBYTES_0 { - try!(f.write_str("OP_0")); + f.write_str("OP_0")?; } else { - try!(write!(f, "{:?}", opcode)); + write!(f, "{:?}", opcode)?; } // Write any pushdata if data_len > 0 { - try!(f.write_str(" ")); + f.write_str(" ")?; if index + data_len <= self.0.len() { for ch in &self.0[index..index + data_len] { - try!(write!(f, "{:02x}", ch)); + write!(f, "{:02x}", ch)?; } index += data_len; } else { - try!(f.write_str("")); + f.write_str("")?; break; } } @@ -126,7 +126,7 @@ impl fmt::Display for Script { impl fmt::LowerHex for Script { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for &ch in self.0.iter() { - try!(write!(f, "{:02x}", ch)); + write!(f, "{:02x}", ch)?; } Ok(()) } @@ -135,7 +135,7 @@ impl fmt::LowerHex for Script { impl fmt::UpperHex for Script { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for &ch in self.0.iter() { - try!(write!(f, "{:02X}", ch)); + write!(f, "{:02X}", ch)?; } Ok(()) } @@ -586,8 +586,8 @@ impl serde::Deserialize for Script { fn visit_str(&mut self, hex_str: &str) -> Result where E: serde::de::Error { - let raw_vec: Vec = try!(::hex::decode(hex_str) - .map_err(|_| serde::de::Error::syntax("bad script hex"))); + let raw_vec: Vec = ::hex::decode(hex_str) + .map_err(|_| serde::de::Error::syntax("bad script hex"))?; Ok(Script::from(raw_vec)) } } @@ -607,7 +607,7 @@ impl ConsensusEncodable for Script { impl ConsensusDecodable for Script { #[inline] fn consensus_decode(d: &mut D) -> Result { - Ok(Script(try!(ConsensusDecodable::consensus_decode(d)))) + Ok(Script(ConsensusDecodable::consensus_decode(d)?)) } } diff --git a/src/blockdata/transaction.rs b/src/blockdata/transaction.rs index dd26918..f5d6260 100644 --- a/src/blockdata/transaction.rs +++ b/src/blockdata/transaction.rs @@ -293,19 +293,19 @@ impl_consensus_encoding!(TxOut, value, script_pubkey); impl ConsensusEncodable for TxIn { fn consensus_encode(&self, s: &mut S) -> Result <(), S::Error> { - try!(self.prev_hash.consensus_encode(s)); - try!(self.prev_index.consensus_encode(s)); - try!(self.script_sig.consensus_encode(s)); + self.prev_hash.consensus_encode(s)?; + self.prev_index.consensus_encode(s)?; + self.script_sig.consensus_encode(s)?; self.sequence.consensus_encode(s) } } impl ConsensusDecodable for TxIn { fn consensus_decode(d: &mut D) -> Result { Ok(TxIn { - prev_hash: try!(ConsensusDecodable::consensus_decode(d)), - prev_index: try!(ConsensusDecodable::consensus_decode(d)), - script_sig: try!(ConsensusDecodable::consensus_decode(d)), - sequence: try!(ConsensusDecodable::consensus_decode(d)), + prev_hash: ConsensusDecodable::consensus_decode(d)?, + prev_index: ConsensusDecodable::consensus_decode(d)?, + script_sig: ConsensusDecodable::consensus_decode(d)?, + sequence: ConsensusDecodable::consensus_decode(d)?, witness: vec![], }) } @@ -313,7 +313,7 @@ impl ConsensusDecodable for TxIn { impl ConsensusEncodable for Transaction { fn consensus_encode(&self, s: &mut S) -> Result <(), S::Error> { - try!(self.version.consensus_encode(s)); + self.version.consensus_encode(s)?; let mut have_witness = false; for input in &self.input { if !input.witness.is_empty() { @@ -322,15 +322,15 @@ impl ConsensusEncodable for Transaction { } } if !have_witness { - try!(self.input.consensus_encode(s)); - try!(self.output.consensus_encode(s)); + self.input.consensus_encode(s)?; + self.output.consensus_encode(s)?; } else { - try!(0u8.consensus_encode(s)); - try!(1u8.consensus_encode(s)); - try!(self.input.consensus_encode(s)); - try!(self.output.consensus_encode(s)); + 0u8.consensus_encode(s)?; + 1u8.consensus_encode(s)?; + self.input.consensus_encode(s)?; + self.output.consensus_encode(s)?; for input in &self.input { - try!(input.witness.consensus_encode(s)); + input.witness.consensus_encode(s)?; } } self.lock_time.consensus_encode(s) @@ -339,11 +339,11 @@ impl ConsensusEncodable for Transaction { impl ConsensusDecodable for Transaction { fn consensus_decode(d: &mut D) -> Result { - let version: u32 = try!(ConsensusDecodable::consensus_decode(d)); - let input: Vec = try!(ConsensusDecodable::consensus_decode(d)); + let version: u32 = ConsensusDecodable::consensus_decode(d)?; + let input: Vec = ConsensusDecodable::consensus_decode(d)?; // segwit if input.is_empty() { - let segwit_flag: u8 = try!(ConsensusDecodable::consensus_decode(d)); + let segwit_flag: u8 = ConsensusDecodable::consensus_decode(d)?; match segwit_flag { // Empty tx 0 => { @@ -351,21 +351,21 @@ impl ConsensusDecodable for Transaction { version: version, input: input, output: vec![], - lock_time: try!(ConsensusDecodable::consensus_decode(d)), + lock_time: ConsensusDecodable::consensus_decode(d)?, }) } // BIP144 input witnesses 1 => { - let mut input: Vec = try!(ConsensusDecodable::consensus_decode(d)); - let output: Vec = try!(ConsensusDecodable::consensus_decode(d)); + let mut input: Vec = ConsensusDecodable::consensus_decode(d)?; + let output: Vec = ConsensusDecodable::consensus_decode(d)?; for txin in input.iter_mut() { - txin.witness = try!(ConsensusDecodable::consensus_decode(d)); + txin.witness = ConsensusDecodable::consensus_decode(d)?; } Ok(Transaction { version: version, input: input, output: output, - lock_time: try!(ConsensusDecodable::consensus_decode(d)) + lock_time: ConsensusDecodable::consensus_decode(d)?, }) } // We don't support anything else @@ -378,8 +378,8 @@ impl ConsensusDecodable for Transaction { Ok(Transaction { version: version, input: input, - output: try!(ConsensusDecodable::consensus_decode(d)), - lock_time: try!(ConsensusDecodable::consensus_decode(d)), + output: ConsensusDecodable::consensus_decode(d)?, + lock_time: ConsensusDecodable::consensus_decode(d)?, }) } } diff --git a/src/internal_macros.rs b/src/internal_macros.rs index 7785b7c..ac4b281 100644 --- a/src/internal_macros.rs +++ b/src/internal_macros.rs @@ -17,7 +17,7 @@ macro_rules! impl_consensus_encoding { impl ::network::encodable::ConsensusEncodable for $thing { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - $( try!(self.$field.consensus_encode(s)); )+ + $( self.$field.consensus_encode(s)?; )+ Ok(()) } } @@ -27,7 +27,7 @@ macro_rules! impl_consensus_encoding { fn consensus_decode(d: &mut D) -> Result<$thing, D::Error> { use network::encodable::ConsensusDecodable; Ok($thing { - $( $field: try!(ConsensusDecodable::consensus_decode(d)), )+ + $( $field: ConsensusDecodable::consensus_decode(d)?, )+ }) } } @@ -47,7 +47,7 @@ macro_rules! impl_newtype_consensus_encoding { impl ::network::encodable::ConsensusDecodable for $thing { #[inline] fn consensus_decode(d: &mut D) -> Result<$thing, D::Error> { - Ok($thing(try!(ConsensusDecodable::consensus_decode(d)))) + Ok($thing(ConsensusDecodable::consensus_decode(d)?)) } } ); @@ -193,12 +193,12 @@ macro_rules! impl_array_newtype_encodable { { let mut ret: [$ty; $len] = [0; $len]; for item in ret.iter_mut() { - *item = match try!(v.visit()) { + *item = match v.visit()? { Some(c) => c, None => return Err(::serde::de::Error::end_of_stream()) }; } - try!(v.end()); + v.end()?; Ok($thing(ret)) } } @@ -312,13 +312,13 @@ macro_rules! __rust_jsonrpc_internal__define_anything_type { } fn visit_seq(&mut self, v: V) -> Result { - let _: Vec = try!(::serde::de::impls::VecVisitor::new().visit_seq(v)); + let _: Vec = ::serde::de::impls::VecVisitor::new().visit_seq(v)?; Ok(Anything) } fn visit_map(&mut self, mut v: V) -> Result { - while let Some((Anything, Anything)) = try!(v.visit()) { } - try!(v.end()); + while let Some((Anything, Anything)) = v.visit()? { } + v.end()?; Ok(Anything) } } @@ -382,18 +382,18 @@ macro_rules! serde_struct_impl { $(let mut $fe = None;)* loop { - match try!(v.visit_key()) { - Some(Enum::Unknown__Field) => { let _: Anything = try!(v.visit_value()); } - $(Some(Enum::$fe) => { $fe = Some(try!(v.visit_value())); })* + match v.visit_key()? { + Some(Enum::Unknown__Field) => { let _: Anything = v.visit_value()?; } + $(Some(Enum::$fe) => { $fe = Some(v.visit_value()?); })* None => { break; } } } $(let $fe = match $fe { Some(x) => x, - None => try!(v.missing_field(stringify!($fe))), + None => v.missing_field(stringify!($fe))?, };)* - try!(v.end()); + v.end()?; Ok($name{ $($fe: $fe),* }) } } @@ -431,7 +431,7 @@ macro_rules! serde_struct_impl { // Use the last alternate name for serialization; in the common case // with zero or one alternates this does the RIght Thing let names = [stringify!($fe), $($alt),*]; - Ok(Some(try!(serializer.visit_struct_elt(names[names.len() - 1], &self.value.$fe)))) + Ok(Some(serializer.visit_struct_elt(names[names.len() - 1], &self.value.$fe)?)) })* State::Finished => { Ok(None) @@ -513,10 +513,10 @@ macro_rules! serde_struct_enum_impl { )* loop { - match try!(v.visit_key()) { - Some(Enum::Unknown__Field) => { let _: Anything = try!(v.visit_value()); } + match v.visit_key()? { + Some(Enum::Unknown__Field) => { let _: Anything = v.visit_value()?; } $($(Some(Enum::$varname($varname::$fe)) => { - $fe = Some(try!(v.visit_value())); })*)* + $fe = Some(v.visit_value()?); })*)* None => { break; } } } @@ -530,7 +530,7 @@ macro_rules! serde_struct_enum_impl { // sets otherwise. if $structname { $(let $fe = $fe.unwrap();)* - try!(v.end()); + v.end()?; return Ok($name::$varname($structname { $($fe: $fe),* })) } )* diff --git a/src/network/address.rs b/src/network/address.rs index 36335f9..06d549c 100644 --- a/src/network/address.rs +++ b/src/network/address.rs @@ -75,8 +75,8 @@ fn addr_to_be(addr: [u16; 8]) -> [u16; 8] { impl ConsensusEncodable for Address { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - try!(self.services.consensus_encode(s)); - try!(addr_to_be(self.address).consensus_encode(s)); + self.services.consensus_encode(s)?; + addr_to_be(self.address).consensus_encode(s)?; self.port.to_be().consensus_encode(s) } } @@ -85,9 +85,9 @@ impl ConsensusDecodable for Address { #[inline] fn consensus_decode(d: &mut D) -> Result { Ok(Address { - services: try!(ConsensusDecodable::consensus_decode(d)), - address: addr_to_be(try!(ConsensusDecodable::consensus_decode(d))), - port: u16::from_be(try!(ConsensusDecodable::consensus_decode(d))) + services: ConsensusDecodable::consensus_decode(d)?, + address: addr_to_be(ConsensusDecodable::consensus_decode(d)?), + port: u16::from_be(ConsensusDecodable::consensus_decode(d)?) }) } } diff --git a/src/network/encodable.rs b/src/network/encodable.rs index fc843bc..fde86bb 100644 --- a/src/network/encodable.rs +++ b/src/network/encodable.rs @@ -103,9 +103,9 @@ impl ConsensusEncodable for VarInt { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { match self.0 { 0...0xFC => { (self.0 as u8).consensus_encode(s) } - 0xFD...0xFFFF => { try!(s.emit_u8(0xFD)); (self.0 as u16).consensus_encode(s) } - 0x10000...0xFFFFFFFF => { try!(s.emit_u8(0xFE)); (self.0 as u32).consensus_encode(s) } - _ => { try!(s.emit_u8(0xFF)); (self.0 as u64).consensus_encode(s) } + 0xFD...0xFFFF => { s.emit_u8(0xFD)?; (self.0 as u16).consensus_encode(s) } + 0x10000...0xFFFFFFFF => { s.emit_u8(0xFE)?; (self.0 as u32).consensus_encode(s) } + _ => { s.emit_u8(0xFF)?; (self.0 as u64).consensus_encode(s) } } } } @@ -113,7 +113,7 @@ impl ConsensusEncodable for VarInt { impl ConsensusDecodable for VarInt { #[inline] fn consensus_decode(d: &mut D) -> Result { - let n = try!(d.read_u8()); + let n = d.read_u8()?; match n { 0xFF => d.read_u64().map(|n| VarInt(u64::from_le(n))), 0xFE => d.read_u32().map(|n| VarInt(u32::from_le(n) as u64)), @@ -145,7 +145,7 @@ impl ConsensusEncodable for String { impl ConsensusDecodable for String { #[inline] fn consensus_decode(d: &mut D) -> Result { - String::from_utf8(try!(ConsensusDecodable::consensus_decode(d))) + String::from_utf8(ConsensusDecodable::consensus_decode(d)?) .map_err(|_| d.error("String was not valid UTF8".to_owned())) } } @@ -157,7 +157,7 @@ macro_rules! impl_array { impl> ConsensusEncodable for [T; $size] { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - for i in self.iter() { try!(i.consensus_encode(s)); } + for i in self.iter() { i.consensus_encode(s)?; } Ok(()) } } @@ -166,9 +166,9 @@ macro_rules! impl_array { #[inline] fn consensus_decode(d: &mut D) -> Result<[T; $size], D::Error> { // Set everything to the first decode - let mut ret = [try!(ConsensusDecodable::consensus_decode(d)); $size]; + let mut ret = [ConsensusDecodable::consensus_decode(d)?; $size]; // Set the rest - for item in ret.iter_mut().take($size).skip(1) { *item = try!(ConsensusDecodable::consensus_decode(d)); } + for item in ret.iter_mut().take($size).skip(1) { *item = ConsensusDecodable::consensus_decode(d)?; } Ok(ret) } } @@ -185,8 +185,8 @@ impl_array!(32); impl> ConsensusEncodable for [T] { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - try!(VarInt(self.len() as u64).consensus_encode(s)); - for c in self.iter() { try!(c.consensus_encode(s)); } + VarInt(self.len() as u64).consensus_encode(s)?; + for c in self.iter() { c.consensus_encode(s)?; } Ok(()) } } @@ -202,15 +202,15 @@ impl> ConsensusEncodable for Vec> ConsensusDecodable for Vec { #[inline] fn consensus_decode(d: &mut D) -> Result, D::Error> { - let VarInt(len): VarInt = try!(ConsensusDecodable::consensus_decode(d)); - let byte_size = try!((len as usize) + let VarInt(len): VarInt = ConsensusDecodable::consensus_decode(d)?; + let byte_size = (len as usize) .checked_mul(mem::size_of::()) - .ok_or(d.error("Invalid length".to_owned()))); + .ok_or(d.error("Invalid length".to_owned()))?; if byte_size > MAX_VEC_SIZE { return Err(d.error(format!("tried to allocate vec of size {} (max {})", byte_size, MAX_VEC_SIZE))); } let mut ret = Vec::with_capacity(len as usize); - for _ in 0..len { ret.push(try!(ConsensusDecodable::consensus_decode(d))); } + for _ in 0..len { ret.push(ConsensusDecodable::consensus_decode(d)?); } Ok(ret) } } @@ -223,13 +223,13 @@ impl> ConsensusEncodable for Box<[ impl> ConsensusDecodable for Box<[T]> { #[inline] fn consensus_decode(d: &mut D) -> Result, D::Error> { - let VarInt(len): VarInt = try!(ConsensusDecodable::consensus_decode(d)); + let VarInt(len): VarInt = ConsensusDecodable::consensus_decode(d)?; let len = len as usize; if len > MAX_VEC_SIZE { return Err(d.error(format!("tried to allocate vec of size {} (max {})", len, MAX_VEC_SIZE))); } let mut ret = Vec::with_capacity(len); - for _ in 0..len { ret.push(try!(ConsensusDecodable::consensus_decode(d))); } + for _ in 0..len { ret.push(ConsensusDecodable::consensus_decode(d)?); } Ok(ret.into_boxed_slice()) } } @@ -240,10 +240,10 @@ impl> ConsensusEncodable for Optio fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { match *self { Some(ref data) => { - try!(1u8.consensus_encode(s)); - try!(data.consensus_encode(s)); + 1u8.consensus_encode(s)?; + data.consensus_encode(s)?; } - None => { try!(0u8.consensus_encode(s)); } + None => { 0u8.consensus_encode(s)?; } } Ok(()) } @@ -252,9 +252,9 @@ impl> ConsensusEncodable for Optio impl> ConsensusDecodable for Option { #[inline] fn consensus_decode(d: &mut D) -> Result, D::Error> { - let bit: u8 = try!(ConsensusDecodable::consensus_decode(d)); + let bit: u8 = ConsensusDecodable::consensus_decode(d)?; Ok(if bit != 0 { - Some(try!(ConsensusDecodable::consensus_decode(d))) + Some(ConsensusDecodable::consensus_decode(d)?) } else { None }) @@ -272,11 +272,11 @@ fn sha2_checksum(data: &[u8]) -> [u8; 4] { impl ConsensusEncodable for CheckedData { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - try!((self.0.len() as u32).consensus_encode(s)); - try!(sha2_checksum(&self.0).consensus_encode(s)); + (self.0.len() as u32).consensus_encode(s)?; + sha2_checksum(&self.0).consensus_encode(s)?; // We can't just pass to the slice encoder since it'll insert a length for ch in &self.0 { - try!(ch.consensus_encode(s)); + ch.consensus_encode(s)?; } Ok(()) } @@ -285,10 +285,10 @@ impl ConsensusEncodable for CheckedData { impl ConsensusDecodable for CheckedData { #[inline] fn consensus_decode(d: &mut D) -> Result { - let len: u32 = try!(ConsensusDecodable::consensus_decode(d)); - let checksum: [u8; 4] = try!(ConsensusDecodable::consensus_decode(d)); + let len: u32 = ConsensusDecodable::consensus_decode(d)?; + let checksum: [u8; 4] = ConsensusDecodable::consensus_decode(d)?; let mut ret = Vec::with_capacity(len as usize); - for _ in 0..len { ret.push(try!(ConsensusDecodable::consensus_decode(d))); } + for _ in 0..len { ret.push(ConsensusDecodable::consensus_decode(d)?); } let expected_checksum = sha2_checksum(&ret); if expected_checksum != checksum { Err(d.error(format!("bad checksum {:?} (expected {:?})", checksum, expected_checksum))) @@ -306,7 +306,7 @@ macro_rules! tuple_encode { #[allow(non_snake_case)] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { let &($(ref $x),*) = self; - $( try!($x.consensus_encode(s)); )* + $( $x.consensus_encode(s)?; )* Ok(()) } } @@ -315,7 +315,7 @@ macro_rules! tuple_encode { #[inline] #[allow(non_snake_case)] fn consensus_decode(d: &mut D) -> Result<($($x),*), D::Error> { - Ok(($(try!({let $x = ConsensusDecodable::consensus_decode(d); $x })),*)) + Ok(($({let $x = ConsensusDecodable::consensus_decode(d)?; $x }),*)) } } ); @@ -347,10 +347,10 @@ impl ConsensusEncodable for HashMap { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - try!(VarInt(self.len() as u64).consensus_encode(s)); + VarInt(self.len() as u64).consensus_encode(s)?; for (key, value) in self.iter() { - try!(key.consensus_encode(s)); - try!(value.consensus_encode(s)); + key.consensus_encode(s)?; + value.consensus_encode(s)?; } Ok(()) } @@ -363,12 +363,12 @@ impl ConsensusDecodable for HashMap { #[inline] fn consensus_decode(d: &mut D) -> Result, D::Error> { - let VarInt(len): VarInt = try!(ConsensusDecodable::consensus_decode(d)); + let VarInt(len): VarInt = ConsensusDecodable::consensus_decode(d)?; let mut ret = HashMap::with_capacity(len as usize); for _ in 0..len { - ret.insert(try!(ConsensusDecodable::consensus_decode(d)), - try!(ConsensusDecodable::consensus_decode(d))); + ret.insert(ConsensusDecodable::consensus_decode(d)?, + ConsensusDecodable::consensus_decode(d)?); } Ok(ret) } diff --git a/src/network/listener.rs b/src/network/listener.rs index 0dc29cb..5fd7fb3 100644 --- a/src/network/listener.rs +++ b/src/network/listener.rs @@ -47,8 +47,8 @@ pub trait Listener { let (recv_tx, recv_rx) = channel(); // Send version message to peer - let version_message = try!(sock.version_message(0)); - try!(sock.send_message(version_message)); + let version_message = sock.version_message(0)?; + sock.send_message(version_message)?; // Message loop thread::spawn(move || { diff --git a/src/network/message.rs b/src/network/message.rs index 02084e1..50872a4 100644 --- a/src/network/message.rs +++ b/src/network/message.rs @@ -56,7 +56,7 @@ impl ConsensusEncodable for CommandString { impl ConsensusDecodable for CommandString { #[inline] fn consensus_decode(d: &mut D) -> Result { - let rawbytes: [u8; 12] = try!(ConsensusDecodable::consensus_decode(d)); + let rawbytes: [u8; 12] = ConsensusDecodable::consensus_decode(d)?; let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None })); Ok(CommandString(rv)) } @@ -148,9 +148,9 @@ impl RawNetworkMessage { impl ConsensusEncodable for RawNetworkMessage { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - try!(self.magic.consensus_encode(s)); - try!(CommandString(self.command()).consensus_encode(s)); - try!(CheckedData(match self.payload { + self.magic.consensus_encode(s)?; + CommandString(self.command()).consensus_encode(s)?; + CheckedData(match self.payload { NetworkMessage::Version(ref dat) => serialize(dat), NetworkMessage::Verack => Ok(vec![]), NetworkMessage::Addr(ref dat) => serialize(dat), @@ -167,7 +167,7 @@ impl ConsensusEncodable for RawNetworkMessage { NetworkMessage::Ping(ref dat) => serialize(dat), NetworkMessage::Pong(ref dat) => serialize(dat), NetworkMessage::Alert(ref dat) => serialize(dat) - }.unwrap()).consensus_encode(s)); + }.unwrap()).consensus_encode(s)?; Ok(()) } } @@ -176,28 +176,28 @@ impl ConsensusEncodable for RawNetworkMessage { // is there a more generic way to handle this? impl> ConsensusDecodable for RawNetworkMessage { fn consensus_decode(d: &mut D) -> Result { - let magic = try!(ConsensusDecodable::consensus_decode(d)); - let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d)); - let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d)); + let magic = ConsensusDecodable::consensus_decode(d)?; + let CommandString(cmd): CommandString= ConsensusDecodable::consensus_decode(d)?; + let CheckedData(raw_payload): CheckedData = ConsensusDecodable::consensus_decode(d)?; let mut mem_d = RawDecoder::new(Cursor::new(raw_payload)); let payload = match &cmd[..] { - "version" => NetworkMessage::Version(try!(propagate_err("version".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), + "version" => NetworkMessage::Version(propagate_err("version".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), "verack" => NetworkMessage::Verack, - "addr" => NetworkMessage::Addr(try!(propagate_err("addr".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "inv" => NetworkMessage::Inv(try!(propagate_err("inv".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "getdata" => NetworkMessage::GetData(try!(propagate_err("getdata".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "notfound" => NetworkMessage::NotFound(try!(propagate_err("notfound".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "getblocks" => NetworkMessage::GetBlocks(try!(propagate_err("getblocks".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "getheaders" => NetworkMessage::GetHeaders(try!(propagate_err("getheaders".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), + "addr" => NetworkMessage::Addr(propagate_err("addr".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "inv" => NetworkMessage::Inv(propagate_err("inv".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "getdata" => NetworkMessage::GetData(propagate_err("getdata".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "notfound" => NetworkMessage::NotFound(propagate_err("notfound".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "getblocks" => NetworkMessage::GetBlocks(propagate_err("getblocks".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "getheaders" => NetworkMessage::GetHeaders(propagate_err("getheaders".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), "mempool" => NetworkMessage::MemPool, - "block" => NetworkMessage::Block(try!(propagate_err("block".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "headers" => NetworkMessage::Headers(try!(propagate_err("headers".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), + "block" => NetworkMessage::Block(propagate_err("block".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "headers" => NetworkMessage::Headers(propagate_err("headers".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), "getaddr" => NetworkMessage::GetAddr, - "ping" => NetworkMessage::Ping(try!(propagate_err("ping".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "pong" => NetworkMessage::Pong(try!(propagate_err("pong".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "tx" => NetworkMessage::Tx(try!(propagate_err("tx".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), - "alert" => NetworkMessage::Alert(try!(propagate_err("alert".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d)))), + "ping" => NetworkMessage::Ping(propagate_err("ping".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "pong" => NetworkMessage::Pong(propagate_err("pong".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "tx" => NetworkMessage::Tx(propagate_err("tx".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), + "alert" => NetworkMessage::Alert(propagate_err("alert".to_owned(), ConsensusDecodable::consensus_decode(&mut mem_d))?), cmd => return Err(d.error(format!("unrecognized network command `{}`", cmd))) }; Ok(RawNetworkMessage { diff --git a/src/network/message_blockdata.rs b/src/network/message_blockdata.rs index a4c2e79..28f17ea 100644 --- a/src/network/message_blockdata.rs +++ b/src/network/message_blockdata.rs @@ -104,13 +104,13 @@ impl_consensus_encoding!(GetHeadersMessage, version, locator_hashes, stop_hash); impl ConsensusEncodable for Inventory { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { - try!(match self.inv_type { + match self.inv_type { InvType::Error => 0u32, InvType::Transaction => 1, InvType::Block => 2, InvType::WitnessBlock => 0x40000002, InvType::WitnessTransaction => 0x40000001 - }.consensus_encode(s)); + }.consensus_encode(s)?; self.hash.consensus_encode(s) } } @@ -118,7 +118,7 @@ impl ConsensusEncodable for Inventory { impl ConsensusDecodable for Inventory { #[inline] fn consensus_decode(d: &mut D) -> Result { - let int_type: u32 = try!(ConsensusDecodable::consensus_decode(d)); + let int_type: u32 = ConsensusDecodable::consensus_decode(d)?; Ok(Inventory { inv_type: match int_type { 0 => InvType::Error, @@ -127,7 +127,7 @@ impl ConsensusDecodable for Inventory { // TODO do not fail here _ => { panic!("bad inventory type field") } }, - hash: try!(ConsensusDecodable::consensus_decode(d)) + hash: ConsensusDecodable::consensus_decode(d)? }) } } diff --git a/src/network/message_network.rs b/src/network/message_network.rs index 1229d4a..93c4dfa 100644 --- a/src/network/message_network.rs +++ b/src/network/message_network.rs @@ -54,8 +54,8 @@ impl VersionMessage { // TODO: we have fixed services and relay to 0 /// Constructs a new `version` message pub fn new(timestamp: i64, mut socket: Socket, nonce: u64, start_height: i32) -> Result { - let recv_addr = try!(socket.receiver_address()); - let send_addr = try!(socket.sender_address()); + let recv_addr = socket.receiver_address()?; + let send_addr = socket.sender_address()?; Ok(VersionMessage { version: constants::PROTOCOL_VERSION, diff --git a/src/network/serialize.rs b/src/network/serialize.rs index e626405..9d8c66d 100644 --- a/src/network/serialize.rs +++ b/src/network/serialize.rs @@ -45,7 +45,7 @@ pub fn serialize(data: &T) -> Result, util::Error> where T: ConsensusEncodable>>>, { let mut encoder = RawEncoder::new(Cursor::new(vec![])); - try!(data.consensus_encode(&mut encoder)); + data.consensus_encode(&mut encoder)?; Ok(encoder.into_inner().into_inner()) } @@ -53,7 +53,7 @@ pub fn serialize(data: &T) -> Result, util::Error> pub fn serialize_hex(data: &T) -> Result where T: ConsensusEncodable>>> { - let serial = try!(serialize(data)); + let serial = serialize(data)?; Ok(hex_encode(serial)) } diff --git a/src/network/socket.rs b/src/network/socket.rs index 0b2239f..c101ba0 100644 --- a/src/network/socket.rs +++ b/src/network/socket.rs @@ -144,8 +144,8 @@ impl Socket { /// Produce a version message appropriate for this socket pub fn version_message(&mut self, start_height: i32) -> Result { - let recv_addr = try!(self.receiver_address()); - let send_addr = try!(self.sender_address()); + let recv_addr = self.receiver_address()?; + let send_addr = self.sender_address()?; let timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(dur) => dur, Err(err) => err.duration(), @@ -168,7 +168,7 @@ impl Socket { pub fn send_message(&mut self, payload: NetworkMessage) -> Result<(), util::Error> { with_socket!(self, sock, { let message = RawNetworkMessage { magic: self.magic, payload: payload }; - try!(message.consensus_encode(&mut RawEncoder::new(&mut *sock))); + message.consensus_encode(&mut RawEncoder::new(&mut *sock))?; sock.flush().map_err(util::Error::Io) }) } diff --git a/src/util/address.rs b/src/util/address.rs index 6bcc7b4..3173cba 100644 --- a/src/util/address.rs +++ b/src/util/address.rs @@ -274,7 +274,7 @@ impl FromStr for Address { } // Base 58 - let data = try!(base58::from_check(s)); + let data = base58::from_check(s)?; if data.len() != 21 { return Err(Error::Base58(base58::Error::InvalidLength(data.len()))); diff --git a/src/util/base58.rs b/src/util/base58.rs index 976cd10..a50be08 100644 --- a/src/util/base58.rs +++ b/src/util/base58.rs @@ -119,7 +119,7 @@ pub fn from(data: &str) -> Result, Error> { /// Decode a base58check-encoded string pub fn from_check(data: &str) -> Result, Error> { - let mut ret: Vec = try!(from(data)); + let mut ret: Vec = from(data)?; if ret.len() < 4 { return Err(Error::TooShort(ret.len())); } diff --git a/src/util/bip32.rs b/src/util/bip32.rs index 24d7eb4..9c345cf 100644 --- a/src/util/bip32.rs +++ b/src/util/bip32.rs @@ -241,7 +241,7 @@ impl ExtendedPrivKey { depth: 0, parent_fingerprint: Default::default(), child_number: ChildNumber::from_normal_idx(0), - secret_key: try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)), + secret_key: SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?, chain_code: ChainCode::from(&result[32..]) }) } @@ -251,7 +251,7 @@ impl ExtendedPrivKey { -> Result { let mut sk = *master; for &num in path.iter() { - sk = try!(sk.ckd_priv(secp, num)); + sk = sk.ckd_priv(secp, num)?; } Ok(sk) } @@ -276,8 +276,8 @@ impl ExtendedPrivKey { hmac.input(&be_n); hmac.raw_result(&mut result); - let mut sk = try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)); - try!(sk.add_assign(secp, &self.secret_key).map_err(Error::Ecdsa)); + let mut sk = SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?; + sk.add_assign(secp, &self.secret_key).map_err(Error::Ecdsa)?; Ok(ExtendedPrivKey { network: self.network, @@ -342,7 +342,7 @@ impl ExtendedPubKey { let mut result = [0; 64]; hmac.raw_result(&mut result); - let secret_key = try!(SecretKey::from_slice(secp, &result[..32])); + let secret_key = SecretKey::from_slice(secp, &result[..32])?; let chain_code = ChainCode::from(&result[32..]); Ok((secret_key, chain_code)) } @@ -351,9 +351,9 @@ impl ExtendedPubKey { /// Public->Public child key derivation pub fn ckd_pub(&self, secp: &Secp256k1, i: ChildNumber) -> Result { - let (sk, chain_code) = try!(self.ckd_pub_tweak(secp, i)); + let (sk, chain_code) = self.ckd_pub_tweak(secp, i)?; let mut pk = self.public_key.clone(); - try!(pk.add_exp_assign(secp, &sk).map_err(Error::Ecdsa)); + pk.add_exp_assign(secp, &sk).map_err(Error::Ecdsa)?; Ok(ExtendedPubKey { network: self.network, @@ -411,7 +411,7 @@ impl FromStr for ExtendedPrivKey { fn from_str(inp: &str) -> Result { let s = Secp256k1::with_caps(secp256k1::ContextFlag::None); - let data = try!(base58::from_check(inp)); + let data = base58::from_check(inp)?; if data.len() != 78 { return Err(base58::Error::InvalidLength(data.len())); @@ -432,9 +432,9 @@ impl FromStr for ExtendedPrivKey { parent_fingerprint: Fingerprint::from(&data[5..9]), child_number: child_number, chain_code: ChainCode::from(&data[13..45]), - secret_key: try!(SecretKey::from_slice(&s, + secret_key: SecretKey::from_slice(&s, &data[46..78]).map_err(|e| - base58::Error::Other(e.to_string()))) + base58::Error::Other(e.to_string()))? }) } } @@ -462,7 +462,7 @@ impl FromStr for ExtendedPubKey { fn from_str(inp: &str) -> Result { let s = Secp256k1::with_caps(secp256k1::ContextFlag::None); - let data = try!(base58::from_check(inp)); + let data = base58::from_check(inp)?; if data.len() != 78 { return Err(base58::Error::InvalidLength(data.len())); @@ -483,9 +483,9 @@ impl FromStr for ExtendedPubKey { parent_fingerprint: Fingerprint::from(&data[5..9]), child_number: child_number, chain_code: ChainCode::from(&data[13..45]), - public_key: try!(PublicKey::from_slice(&s, + public_key: PublicKey::from_slice(&s, &data[45..78]).map_err(|e| - base58::Error::Other(e.to_string()))) + base58::Error::Other(e.to_string()))? }) } } diff --git a/src/util/contracthash.rs b/src/util/contracthash.rs index 3a6a856..70b328a 100644 --- a/src/util/contracthash.rs +++ b/src/util/contracthash.rs @@ -177,8 +177,8 @@ pub fn tweak_keys(secp: &Secp256k1, keys: &[PublicKey], contract: &[u8]) -> Resu let mut hmac = hmac::Hmac::new(sha2::Sha256::new(), &key.serialize()); hmac.input(contract); hmac.raw_result(&mut hmac_raw); - let hmac_sk = try!(SecretKey::from_slice(secp, &hmac_raw).map_err(Error::BadTweak)); - try!(key.add_exp_assign(secp, &hmac_sk).map_err(Error::Secp)); + let hmac_sk = SecretKey::from_slice(secp, &hmac_raw).map_err(Error::BadTweak)?; + key.add_exp_assign(secp, &hmac_sk).map_err(Error::Secp)?; ret.push(key); } Ok(ret) @@ -196,12 +196,12 @@ pub fn compute_tweak(secp: &Secp256k1, pk: &PublicKey, contract: &[u8]) -> Resul /// Tweak a secret key using some arbitrary data (calls `compute_tweak` internally) pub fn tweak_secret_key(secp: &Secp256k1, key: &SecretKey, contract: &[u8]) -> Result { // Compute public key - let pk = try!(PublicKey::from_secret_key(secp, &key).map_err(Error::Secp)); + let pk = PublicKey::from_secret_key(secp, &key).map_err(Error::Secp)?; // Compute tweak - let hmac_sk = try!(compute_tweak(secp, &pk, contract)); + let hmac_sk = compute_tweak(secp, &pk, contract)?; // Execute the tweak let mut key = *key; - try!(key.add_assign(&secp, &hmac_sk).map_err(Error::Secp)); + key.add_assign(&secp, &hmac_sk).map_err(Error::Secp)?; // Return Ok(key) } @@ -213,8 +213,8 @@ pub fn create_address(secp: &Secp256k1, keys: &[PublicKey], template: &Template) -> Result { - let keys = try!(tweak_keys(secp, keys, contract)); - let script = try!(template.to_script(&keys)); + let keys = tweak_keys(secp, keys, contract)?; + let script = template.to_script(&keys)?; Ok(address::Address { network: network, payload: address::Payload::ScriptHash( diff --git a/src/util/decimal.rs b/src/util/decimal.rs index 7694050..938a803 100644 --- a/src/util/decimal.rs +++ b/src/util/decimal.rs @@ -141,7 +141,7 @@ impl ser::Serialize for Decimal { impl de::Deserialize for Decimal { // Deserialize through strason for the same reason as in `Serialize` fn deserialize(d: &mut D) -> Result { - let json: Json = try!(de::Deserialize::deserialize(d)); + let json: Json = de::Deserialize::deserialize(d)?; match json.num() { Some(s) => { // We know this will be a well-formed Json number, so we can @@ -259,7 +259,7 @@ impl ser::Serialize for UDecimal { impl de::Deserialize for UDecimal { // Deserialize through strason for the same reason as in `Serialize` fn deserialize(d: &mut D) -> Result { - let json: Json = try!(de::Deserialize::deserialize(d)); + let json: Json = de::Deserialize::deserialize(d)?; match json.num() { Some(s) => { // We know this will be a well-formed Json number, so we can diff --git a/src/util/hash.rs b/src/util/hash.rs index 134f98e..61caacb 100644 --- a/src/util/hash.rs +++ b/src/util/hash.rs @@ -360,7 +360,7 @@ impl fmt::Debug for Sha256dHash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &Sha256dHash(data) = self; for ch in data.iter() { - try!(write!(f, "{:02x}", ch)); + write!(f, "{:02x}", ch)?; } Ok(()) } @@ -371,7 +371,7 @@ impl fmt::Debug for Hash160 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &Hash160(data) = self; for ch in data.iter() { - try!(write!(f, "{:02x}", ch)); + write!(f, "{:02x}", ch)?; } Ok(()) } @@ -394,7 +394,7 @@ impl fmt::LowerHex for Sha256dHash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &Sha256dHash(data) = self; for ch in data.iter().rev() { - try!(write!(f, "{:02x}", ch)); + write!(f, "{:02x}", ch)?; } Ok(()) } @@ -405,7 +405,7 @@ impl fmt::UpperHex for Sha256dHash { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &Sha256dHash(data) = self; for ch in data.iter().rev() { - try!(write!(f, "{:02X}", ch)); + write!(f, "{:02X}", ch)?; } Ok(()) } diff --git a/src/util/misc.rs b/src/util/misc.rs index 3ee7f61..0e9fa2f 100644 --- a/src/util/misc.rs +++ b/src/util/misc.rs @@ -25,7 +25,7 @@ pub fn hex_bytes(s: &str) -> Result, Error> { let mut v = vec![]; let mut iter = s.chars().pair(); // Do the parsing - try!(iter.by_ref().fold(Ok(()), |e, (f, s)| + iter.by_ref().fold(Ok(()), |e, (f, s)| if e.is_err() { e } else { match (f.to_digit(16), s.to_digit(16)) { @@ -40,7 +40,7 @@ pub fn hex_bytes(s: &str) -> Result, Error> { (Some(f), Some(s)) => { v.push((f * 0x10 + s) as u8); Ok(()) } } } - )); + )?; // Check that there was no remainder match iter.remainder() { Some(_) => Err(Error::Detail( diff --git a/src/util/privkey.rs b/src/util/privkey.rs index b8447e7..3d611aa 100644 --- a/src/util/privkey.rs +++ b/src/util/privkey.rs @@ -113,7 +113,7 @@ impl FromStr for Privkey { type Err = Error; fn from_str(s: &str) -> Result { - let data = try!(base58::from_check(s)); + let data = base58::from_check(s)?; let compressed = match data.len() { 33 => false, @@ -128,8 +128,8 @@ impl FromStr for Privkey { }; let secp = Secp256k1::without_caps(); - let key = try!(SecretKey::from_slice(&secp, &data[1..33]) - .map_err(|_| base58::Error::Other("Secret key out of range".to_owned()))); + let key = SecretKey::from_slice(&secp, &data[1..33]) + .map_err(|_| base58::Error::Other("Secret key out of range".to_owned()))?; Ok(Privkey { compressed: compressed, diff --git a/src/util/uint.rs b/src/util/uint.rs index eb026d4..fe664e4 100644 --- a/src/util/uint.rs +++ b/src/util/uint.rs @@ -321,9 +321,9 @@ macro_rules! construct_uint { impl fmt::Debug for $name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &$name(ref data) = self; - try!(write!(f, "0x")); + write!(f, "0x")?; for ch in data.iter().rev() { - try!(write!(f, "{:016x}", ch)); + write!(f, "{:016x}", ch)?; } Ok(()) } @@ -339,7 +339,7 @@ macro_rules! construct_uint { #[inline] fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { let &$name(ref data) = self; - for word in data.iter() { try!(word.consensus_encode(s)); } + for word in data.iter() { word.consensus_encode(s)?; } Ok(()) } } @@ -347,7 +347,7 @@ macro_rules! construct_uint { impl ::network::encodable::ConsensusDecodable for $name { fn consensus_decode(d: &mut D) -> Result<$name, D::Error> { use network::encodable::ConsensusDecodable; - let ret: [u64; $n_words] = try!(ConsensusDecodable::consensus_decode(d)); + let ret: [u64; $n_words] = ConsensusDecodable::consensus_decode(d)?; Ok($name(ret)) } }