Use the `?` (try) instead of the `try!` macro.

Signed-off-by: Jean Pierre Dudey <jeandudey@hotmail.com>
This commit is contained in:
Jean Pierre Dudey 2018-08-12 12:47:31 -04:00
parent 24c0f1a3fc
commit b2594087db
21 changed files with 173 additions and 173 deletions

View File

@ -609,7 +609,7 @@ display_from_debug!(All);
impl<D: SimpleDecoder> ConsensusDecodable<D> for All { impl<D: SimpleDecoder> ConsensusDecodable<D> for All {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<All, D::Error> { fn consensus_decode(d: &mut D) -> Result<All, D::Error> {
Ok(All::from(try!(d.read_u8()))) Ok(All::from(d.read_u8()?))
} }
} }

View File

@ -49,7 +49,7 @@ impl fmt::Debug for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut index = 0; let mut index = 0;
try!(f.write_str("Script(")); f.write_str("Script(")?;
while index < self.0.len() { while index < self.0.len() {
let opcode = opcodes::All::from(self.0[index]); let opcode = opcodes::All::from(self.0[index]);
index += 1; index += 1;
@ -60,55 +60,55 @@ impl fmt::Debug for Script {
match opcode { match opcode {
opcodes::All::OP_PUSHDATA1 => { opcodes::All::OP_PUSHDATA1 => {
if self.0.len() < index + 1 { if self.0.len() < index + 1 {
try!(f.write_str("<unexpected end>")); f.write_str("<unexpected end>")?;
break; break;
} }
match read_uint(&self.0[index..], 1) { match read_uint(&self.0[index..], 1) {
Ok(n) => { index += 1; n as usize } Ok(n) => { index += 1; n as usize }
Err(_) => { try!(f.write_str("<bad length>")); break; } Err(_) => { f.write_str("<bad length>")?; break; }
} }
} }
opcodes::All::OP_PUSHDATA2 => { opcodes::All::OP_PUSHDATA2 => {
if self.0.len() < index + 2 { if self.0.len() < index + 2 {
try!(f.write_str("<unexpected end>")); f.write_str("<unexpected end>")?;
break; break;
} }
match read_uint(&self.0[index..], 2) { match read_uint(&self.0[index..], 2) {
Ok(n) => { index += 2; n as usize } Ok(n) => { index += 2; n as usize }
Err(_) => { try!(f.write_str("<bad length>")); break; } Err(_) => { f.write_str("<bad length>")?; break; }
} }
} }
opcodes::All::OP_PUSHDATA4 => { opcodes::All::OP_PUSHDATA4 => {
if self.0.len() < index + 4 { if self.0.len() < index + 4 {
try!(f.write_str("<unexpected end>")); f.write_str("<unexpected end>")?;
break; break;
} }
match read_uint(&self.0[index..], 4) { match read_uint(&self.0[index..], 4) {
Ok(n) => { index += 4; n as usize } Ok(n) => { index += 4; n as usize }
Err(_) => { try!(f.write_str("<bad length>")); break; } Err(_) => { f.write_str("<bad length>")?; break; }
} }
} }
_ => 0 _ => 0
} }
}; };
if index > 1 { try!(f.write_str(" ")); } if index > 1 { f.write_str(" ")?; }
// Write the opcode // Write the opcode
if opcode == opcodes::All::OP_PUSHBYTES_0 { if opcode == opcodes::All::OP_PUSHBYTES_0 {
try!(f.write_str("OP_0")); f.write_str("OP_0")?;
} else { } else {
try!(write!(f, "{:?}", opcode)); write!(f, "{:?}", opcode)?;
} }
// Write any pushdata // Write any pushdata
if data_len > 0 { if data_len > 0 {
try!(f.write_str(" ")); f.write_str(" ")?;
if index + data_len <= self.0.len() { if index + data_len <= self.0.len() {
for ch in &self.0[index..index + data_len] { for ch in &self.0[index..index + data_len] {
try!(write!(f, "{:02x}", ch)); write!(f, "{:02x}", ch)?;
} }
index += data_len; index += data_len;
} else { } else {
try!(f.write_str("<push past end>")); f.write_str("<push past end>")?;
break; break;
} }
} }
@ -126,7 +126,7 @@ impl fmt::Display for Script {
impl fmt::LowerHex for Script { impl fmt::LowerHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &ch in self.0.iter() { for &ch in self.0.iter() {
try!(write!(f, "{:02x}", ch)); write!(f, "{:02x}", ch)?;
} }
Ok(()) Ok(())
} }
@ -135,7 +135,7 @@ impl fmt::LowerHex for Script {
impl fmt::UpperHex for Script { impl fmt::UpperHex for Script {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for &ch in self.0.iter() { for &ch in self.0.iter() {
try!(write!(f, "{:02X}", ch)); write!(f, "{:02X}", ch)?;
} }
Ok(()) Ok(())
} }
@ -586,8 +586,8 @@ impl serde::Deserialize for Script {
fn visit_str<E>(&mut self, hex_str: &str) -> Result<Script, E> fn visit_str<E>(&mut self, hex_str: &str) -> Result<Script, E>
where E: serde::de::Error where E: serde::de::Error
{ {
let raw_vec: Vec<u8> = try!(::hex::decode(hex_str) let raw_vec: Vec<u8> = ::hex::decode(hex_str)
.map_err(|_| serde::de::Error::syntax("bad script hex"))); .map_err(|_| serde::de::Error::syntax("bad script hex"))?;
Ok(Script::from(raw_vec)) Ok(Script::from(raw_vec))
} }
} }
@ -607,7 +607,7 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for Script {
impl<D: SimpleDecoder> ConsensusDecodable<D> for Script { impl<D: SimpleDecoder> ConsensusDecodable<D> for Script {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<Script, D::Error> { fn consensus_decode(d: &mut D) -> Result<Script, D::Error> {
Ok(Script(try!(ConsensusDecodable::consensus_decode(d)))) Ok(Script(ConsensusDecodable::consensus_decode(d)?))
} }
} }

View File

@ -293,19 +293,19 @@ impl_consensus_encoding!(TxOut, value, script_pubkey);
impl<S: SimpleEncoder> ConsensusEncodable<S> for TxIn { impl<S: SimpleEncoder> ConsensusEncodable<S> for TxIn {
fn consensus_encode(&self, s: &mut S) -> Result <(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result <(), S::Error> {
try!(self.prev_hash.consensus_encode(s)); self.prev_hash.consensus_encode(s)?;
try!(self.prev_index.consensus_encode(s)); self.prev_index.consensus_encode(s)?;
try!(self.script_sig.consensus_encode(s)); self.script_sig.consensus_encode(s)?;
self.sequence.consensus_encode(s) self.sequence.consensus_encode(s)
} }
} }
impl<D: SimpleDecoder> ConsensusDecodable<D> for TxIn { impl<D: SimpleDecoder> ConsensusDecodable<D> for TxIn {
fn consensus_decode(d: &mut D) -> Result<TxIn, D::Error> { fn consensus_decode(d: &mut D) -> Result<TxIn, D::Error> {
Ok(TxIn { Ok(TxIn {
prev_hash: try!(ConsensusDecodable::consensus_decode(d)), prev_hash: ConsensusDecodable::consensus_decode(d)?,
prev_index: try!(ConsensusDecodable::consensus_decode(d)), prev_index: ConsensusDecodable::consensus_decode(d)?,
script_sig: try!(ConsensusDecodable::consensus_decode(d)), script_sig: ConsensusDecodable::consensus_decode(d)?,
sequence: try!(ConsensusDecodable::consensus_decode(d)), sequence: ConsensusDecodable::consensus_decode(d)?,
witness: vec![], witness: vec![],
}) })
} }
@ -313,7 +313,7 @@ impl<D: SimpleDecoder> ConsensusDecodable<D> for TxIn {
impl<S: SimpleEncoder> ConsensusEncodable<S> for Transaction { impl<S: SimpleEncoder> ConsensusEncodable<S> for Transaction {
fn consensus_encode(&self, s: &mut S) -> Result <(), S::Error> { 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; let mut have_witness = false;
for input in &self.input { for input in &self.input {
if !input.witness.is_empty() { if !input.witness.is_empty() {
@ -322,15 +322,15 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for Transaction {
} }
} }
if !have_witness { if !have_witness {
try!(self.input.consensus_encode(s)); self.input.consensus_encode(s)?;
try!(self.output.consensus_encode(s)); self.output.consensus_encode(s)?;
} else { } else {
try!(0u8.consensus_encode(s)); 0u8.consensus_encode(s)?;
try!(1u8.consensus_encode(s)); 1u8.consensus_encode(s)?;
try!(self.input.consensus_encode(s)); self.input.consensus_encode(s)?;
try!(self.output.consensus_encode(s)); self.output.consensus_encode(s)?;
for input in &self.input { for input in &self.input {
try!(input.witness.consensus_encode(s)); input.witness.consensus_encode(s)?;
} }
} }
self.lock_time.consensus_encode(s) self.lock_time.consensus_encode(s)
@ -339,11 +339,11 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for Transaction {
impl<D: SimpleDecoder> ConsensusDecodable<D> for Transaction { impl<D: SimpleDecoder> ConsensusDecodable<D> for Transaction {
fn consensus_decode(d: &mut D) -> Result<Transaction, D::Error> { fn consensus_decode(d: &mut D) -> Result<Transaction, D::Error> {
let version: u32 = try!(ConsensusDecodable::consensus_decode(d)); let version: u32 = ConsensusDecodable::consensus_decode(d)?;
let input: Vec<TxIn> = try!(ConsensusDecodable::consensus_decode(d)); let input: Vec<TxIn> = ConsensusDecodable::consensus_decode(d)?;
// segwit // segwit
if input.is_empty() { if input.is_empty() {
let segwit_flag: u8 = try!(ConsensusDecodable::consensus_decode(d)); let segwit_flag: u8 = ConsensusDecodable::consensus_decode(d)?;
match segwit_flag { match segwit_flag {
// Empty tx // Empty tx
0 => { 0 => {
@ -351,21 +351,21 @@ impl<D: SimpleDecoder> ConsensusDecodable<D> for Transaction {
version: version, version: version,
input: input, input: input,
output: vec![], output: vec![],
lock_time: try!(ConsensusDecodable::consensus_decode(d)), lock_time: ConsensusDecodable::consensus_decode(d)?,
}) })
} }
// BIP144 input witnesses // BIP144 input witnesses
1 => { 1 => {
let mut input: Vec<TxIn> = try!(ConsensusDecodable::consensus_decode(d)); let mut input: Vec<TxIn> = ConsensusDecodable::consensus_decode(d)?;
let output: Vec<TxOut> = try!(ConsensusDecodable::consensus_decode(d)); let output: Vec<TxOut> = ConsensusDecodable::consensus_decode(d)?;
for txin in input.iter_mut() { for txin in input.iter_mut() {
txin.witness = try!(ConsensusDecodable::consensus_decode(d)); txin.witness = ConsensusDecodable::consensus_decode(d)?;
} }
Ok(Transaction { Ok(Transaction {
version: version, version: version,
input: input, input: input,
output: output, output: output,
lock_time: try!(ConsensusDecodable::consensus_decode(d)) lock_time: ConsensusDecodable::consensus_decode(d)?,
}) })
} }
// We don't support anything else // We don't support anything else
@ -378,8 +378,8 @@ impl<D: SimpleDecoder> ConsensusDecodable<D> for Transaction {
Ok(Transaction { Ok(Transaction {
version: version, version: version,
input: input, input: input,
output: try!(ConsensusDecodable::consensus_decode(d)), output: ConsensusDecodable::consensus_decode(d)?,
lock_time: try!(ConsensusDecodable::consensus_decode(d)), lock_time: ConsensusDecodable::consensus_decode(d)?,
}) })
} }
} }

View File

@ -17,7 +17,7 @@ macro_rules! impl_consensus_encoding {
impl<S: ::network::serialize::SimpleEncoder> ::network::encodable::ConsensusEncodable<S> for $thing { impl<S: ::network::serialize::SimpleEncoder> ::network::encodable::ConsensusEncodable<S> for $thing {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
$( try!(self.$field.consensus_encode(s)); )+ $( self.$field.consensus_encode(s)?; )+
Ok(()) Ok(())
} }
} }
@ -27,7 +27,7 @@ macro_rules! impl_consensus_encoding {
fn consensus_decode(d: &mut D) -> Result<$thing, D::Error> { fn consensus_decode(d: &mut D) -> Result<$thing, D::Error> {
use network::encodable::ConsensusDecodable; use network::encodable::ConsensusDecodable;
Ok($thing { Ok($thing {
$( $field: try!(ConsensusDecodable::consensus_decode(d)), )+ $( $field: ConsensusDecodable::consensus_decode(d)?, )+
}) })
} }
} }
@ -47,7 +47,7 @@ macro_rules! impl_newtype_consensus_encoding {
impl<D: ::network::serialize::SimpleDecoder> ::network::encodable::ConsensusDecodable<D> for $thing { impl<D: ::network::serialize::SimpleDecoder> ::network::encodable::ConsensusDecodable<D> for $thing {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<$thing, D::Error> { 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]; let mut ret: [$ty; $len] = [0; $len];
for item in ret.iter_mut() { for item in ret.iter_mut() {
*item = match try!(v.visit()) { *item = match v.visit()? {
Some(c) => c, Some(c) => c,
None => return Err(::serde::de::Error::end_of_stream()) None => return Err(::serde::de::Error::end_of_stream())
}; };
} }
try!(v.end()); v.end()?;
Ok($thing(ret)) Ok($thing(ret))
} }
} }
@ -312,13 +312,13 @@ macro_rules! __rust_jsonrpc_internal__define_anything_type {
} }
fn visit_seq<V: ::serde::de::SeqVisitor>(&mut self, v: V) -> Result<Anything, V::Error> { fn visit_seq<V: ::serde::de::SeqVisitor>(&mut self, v: V) -> Result<Anything, V::Error> {
let _: Vec<Anything> = try!(::serde::de::impls::VecVisitor::new().visit_seq(v)); let _: Vec<Anything> = ::serde::de::impls::VecVisitor::new().visit_seq(v)?;
Ok(Anything) Ok(Anything)
} }
fn visit_map<V: ::serde::de::MapVisitor>(&mut self, mut v: V) -> Result<Anything, V::Error> { fn visit_map<V: ::serde::de::MapVisitor>(&mut self, mut v: V) -> Result<Anything, V::Error> {
while let Some((Anything, Anything)) = try!(v.visit()) { } while let Some((Anything, Anything)) = v.visit()? { }
try!(v.end()); v.end()?;
Ok(Anything) Ok(Anything)
} }
} }
@ -382,18 +382,18 @@ macro_rules! serde_struct_impl {
$(let mut $fe = None;)* $(let mut $fe = None;)*
loop { loop {
match try!(v.visit_key()) { match v.visit_key()? {
Some(Enum::Unknown__Field) => { let _: Anything = try!(v.visit_value()); } Some(Enum::Unknown__Field) => { let _: Anything = v.visit_value()?; }
$(Some(Enum::$fe) => { $fe = Some(try!(v.visit_value())); })* $(Some(Enum::$fe) => { $fe = Some(v.visit_value()?); })*
None => { break; } None => { break; }
} }
} }
$(let $fe = match $fe { $(let $fe = match $fe {
Some(x) => x, 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),* }) Ok($name{ $($fe: $fe),* })
} }
} }
@ -431,7 +431,7 @@ macro_rules! serde_struct_impl {
// Use the last alternate name for serialization; in the common case // Use the last alternate name for serialization; in the common case
// with zero or one alternates this does the RIght Thing // with zero or one alternates this does the RIght Thing
let names = [stringify!($fe), $($alt),*]; 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 => { State::Finished => {
Ok(None) Ok(None)
@ -513,10 +513,10 @@ macro_rules! serde_struct_enum_impl {
)* )*
loop { loop {
match try!(v.visit_key()) { match v.visit_key()? {
Some(Enum::Unknown__Field) => { let _: Anything = try!(v.visit_value()); } Some(Enum::Unknown__Field) => { let _: Anything = v.visit_value()?; }
$($(Some(Enum::$varname($varname::$fe)) => { $($(Some(Enum::$varname($varname::$fe)) => {
$fe = Some(try!(v.visit_value())); })*)* $fe = Some(v.visit_value()?); })*)*
None => { break; } None => { break; }
} }
} }
@ -530,7 +530,7 @@ macro_rules! serde_struct_enum_impl {
// sets otherwise. // sets otherwise.
if $structname { if $structname {
$(let $fe = $fe.unwrap();)* $(let $fe = $fe.unwrap();)*
try!(v.end()); v.end()?;
return Ok($name::$varname($structname { $($fe: $fe),* })) return Ok($name::$varname($structname { $($fe: $fe),* }))
} }
)* )*

View File

@ -75,8 +75,8 @@ fn addr_to_be(addr: [u16; 8]) -> [u16; 8] {
impl<S: SimpleEncoder> ConsensusEncodable<S> for Address { impl<S: SimpleEncoder> ConsensusEncodable<S> for Address {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
try!(self.services.consensus_encode(s)); self.services.consensus_encode(s)?;
try!(addr_to_be(self.address).consensus_encode(s)); addr_to_be(self.address).consensus_encode(s)?;
self.port.to_be().consensus_encode(s) self.port.to_be().consensus_encode(s)
} }
} }
@ -85,9 +85,9 @@ impl<D: SimpleDecoder> ConsensusDecodable<D> for Address {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<Address, D::Error> { fn consensus_decode(d: &mut D) -> Result<Address, D::Error> {
Ok(Address { Ok(Address {
services: try!(ConsensusDecodable::consensus_decode(d)), services: ConsensusDecodable::consensus_decode(d)?,
address: addr_to_be(try!(ConsensusDecodable::consensus_decode(d))), address: addr_to_be(ConsensusDecodable::consensus_decode(d)?),
port: u16::from_be(try!(ConsensusDecodable::consensus_decode(d))) port: u16::from_be(ConsensusDecodable::consensus_decode(d)?)
}) })
} }
} }

View File

@ -103,9 +103,9 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for VarInt {
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
match self.0 { match self.0 {
0...0xFC => { (self.0 as u8).consensus_encode(s) } 0...0xFC => { (self.0 as u8).consensus_encode(s) }
0xFD...0xFFFF => { try!(s.emit_u8(0xFD)); (self.0 as u16).consensus_encode(s) } 0xFD...0xFFFF => { 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) } 0x10000...0xFFFFFFFF => { s.emit_u8(0xFE)?; (self.0 as u32).consensus_encode(s) }
_ => { try!(s.emit_u8(0xFF)); (self.0 as u64).consensus_encode(s) } _ => { s.emit_u8(0xFF)?; (self.0 as u64).consensus_encode(s) }
} }
} }
} }
@ -113,7 +113,7 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for VarInt {
impl<D: SimpleDecoder> ConsensusDecodable<D> for VarInt { impl<D: SimpleDecoder> ConsensusDecodable<D> for VarInt {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<VarInt, D::Error> { fn consensus_decode(d: &mut D) -> Result<VarInt, D::Error> {
let n = try!(d.read_u8()); let n = d.read_u8()?;
match n { match n {
0xFF => d.read_u64().map(|n| VarInt(u64::from_le(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)), 0xFE => d.read_u32().map(|n| VarInt(u32::from_le(n) as u64)),
@ -145,7 +145,7 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for String {
impl<D: SimpleDecoder> ConsensusDecodable<D> for String { impl<D: SimpleDecoder> ConsensusDecodable<D> for String {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<String, D::Error> { fn consensus_decode(d: &mut D) -> Result<String, D::Error> {
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())) .map_err(|_| d.error("String was not valid UTF8".to_owned()))
} }
} }
@ -157,7 +157,7 @@ macro_rules! impl_array {
impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for [T; $size] { impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for [T; $size] {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { 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(()) Ok(())
} }
} }
@ -166,9 +166,9 @@ macro_rules! impl_array {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<[T; $size], D::Error> { fn consensus_decode(d: &mut D) -> Result<[T; $size], D::Error> {
// Set everything to the first decode // 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 // 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) Ok(ret)
} }
} }
@ -185,8 +185,8 @@ impl_array!(32);
impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for [T] { impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for [T] {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { 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 c in self.iter() { try!(c.consensus_encode(s)); } for c in self.iter() { c.consensus_encode(s)?; }
Ok(()) Ok(())
} }
} }
@ -202,15 +202,15 @@ impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for Vec<T
impl<D: SimpleDecoder, T: ConsensusDecodable<D>> ConsensusDecodable<D> for Vec<T> { impl<D: SimpleDecoder, T: ConsensusDecodable<D>> ConsensusDecodable<D> for Vec<T> {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<Vec<T>, D::Error> { fn consensus_decode(d: &mut D) -> Result<Vec<T>, D::Error> {
let VarInt(len): VarInt = try!(ConsensusDecodable::consensus_decode(d)); let VarInt(len): VarInt = ConsensusDecodable::consensus_decode(d)?;
let byte_size = try!((len as usize) let byte_size = (len as usize)
.checked_mul(mem::size_of::<T>()) .checked_mul(mem::size_of::<T>())
.ok_or(d.error("Invalid length".to_owned()))); .ok_or(d.error("Invalid length".to_owned()))?;
if byte_size > MAX_VEC_SIZE { if byte_size > MAX_VEC_SIZE {
return Err(d.error(format!("tried to allocate vec of size {} (max {})", 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); 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) Ok(ret)
} }
} }
@ -223,13 +223,13 @@ impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for Box<[
impl<D: SimpleDecoder, T: ConsensusDecodable<D>> ConsensusDecodable<D> for Box<[T]> { impl<D: SimpleDecoder, T: ConsensusDecodable<D>> ConsensusDecodable<D> for Box<[T]> {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<Box<[T]>, D::Error> { fn consensus_decode(d: &mut D) -> Result<Box<[T]>, D::Error> {
let VarInt(len): VarInt = try!(ConsensusDecodable::consensus_decode(d)); let VarInt(len): VarInt = ConsensusDecodable::consensus_decode(d)?;
let len = len as usize; let len = len as usize;
if len > MAX_VEC_SIZE { if len > MAX_VEC_SIZE {
return Err(d.error(format!("tried to allocate vec of size {} (max {})", 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); 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()) Ok(ret.into_boxed_slice())
} }
} }
@ -240,10 +240,10 @@ impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for Optio
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
match *self { match *self {
Some(ref data) => { Some(ref data) => {
try!(1u8.consensus_encode(s)); 1u8.consensus_encode(s)?;
try!(data.consensus_encode(s)); data.consensus_encode(s)?;
} }
None => { try!(0u8.consensus_encode(s)); } None => { 0u8.consensus_encode(s)?; }
} }
Ok(()) Ok(())
} }
@ -252,9 +252,9 @@ impl<S: SimpleEncoder, T: ConsensusEncodable<S>> ConsensusEncodable<S> for Optio
impl<D: SimpleDecoder, T:ConsensusDecodable<D>> ConsensusDecodable<D> for Option<T> { impl<D: SimpleDecoder, T:ConsensusDecodable<D>> ConsensusDecodable<D> for Option<T> {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<Option<T>, D::Error> { fn consensus_decode(d: &mut D) -> Result<Option<T>, D::Error> {
let bit: u8 = try!(ConsensusDecodable::consensus_decode(d)); let bit: u8 = ConsensusDecodable::consensus_decode(d)?;
Ok(if bit != 0 { Ok(if bit != 0 {
Some(try!(ConsensusDecodable::consensus_decode(d))) Some(ConsensusDecodable::consensus_decode(d)?)
} else { } else {
None None
}) })
@ -272,11 +272,11 @@ fn sha2_checksum(data: &[u8]) -> [u8; 4] {
impl<S: SimpleEncoder> ConsensusEncodable<S> for CheckedData { impl<S: SimpleEncoder> ConsensusEncodable<S> for CheckedData {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
try!((self.0.len() as u32).consensus_encode(s)); (self.0.len() as u32).consensus_encode(s)?;
try!(sha2_checksum(&self.0).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 // We can't just pass to the slice encoder since it'll insert a length
for ch in &self.0 { for ch in &self.0 {
try!(ch.consensus_encode(s)); ch.consensus_encode(s)?;
} }
Ok(()) Ok(())
} }
@ -285,10 +285,10 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for CheckedData {
impl<D: SimpleDecoder> ConsensusDecodable<D> for CheckedData { impl<D: SimpleDecoder> ConsensusDecodable<D> for CheckedData {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<CheckedData, D::Error> { fn consensus_decode(d: &mut D) -> Result<CheckedData, D::Error> {
let len: u32 = try!(ConsensusDecodable::consensus_decode(d)); let len: u32 = ConsensusDecodable::consensus_decode(d)?;
let checksum: [u8; 4] = try!(ConsensusDecodable::consensus_decode(d)); let checksum: [u8; 4] = ConsensusDecodable::consensus_decode(d)?;
let mut ret = Vec::with_capacity(len as usize); 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); let expected_checksum = sha2_checksum(&ret);
if expected_checksum != checksum { if expected_checksum != checksum {
Err(d.error(format!("bad checksum {:?} (expected {:?})", checksum, expected_checksum))) Err(d.error(format!("bad checksum {:?} (expected {:?})", checksum, expected_checksum)))
@ -306,7 +306,7 @@ macro_rules! tuple_encode {
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
let &($(ref $x),*) = self; let &($(ref $x),*) = self;
$( try!($x.consensus_encode(s)); )* $( $x.consensus_encode(s)?; )*
Ok(()) Ok(())
} }
} }
@ -315,7 +315,7 @@ macro_rules! tuple_encode {
#[inline] #[inline]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn consensus_decode(d: &mut D) -> Result<($($x),*), D::Error> { 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<S, K, V> ConsensusEncodable<S> for HashMap<K, V>
{ {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { 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() { for (key, value) in self.iter() {
try!(key.consensus_encode(s)); key.consensus_encode(s)?;
try!(value.consensus_encode(s)); value.consensus_encode(s)?;
} }
Ok(()) Ok(())
} }
@ -363,12 +363,12 @@ impl<D, K, V> ConsensusDecodable<D> for HashMap<K, V>
{ {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<HashMap<K, V>, D::Error> { fn consensus_decode(d: &mut D) -> Result<HashMap<K, V>, 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); let mut ret = HashMap::with_capacity(len as usize);
for _ in 0..len { for _ in 0..len {
ret.insert(try!(ConsensusDecodable::consensus_decode(d)), ret.insert(ConsensusDecodable::consensus_decode(d)?,
try!(ConsensusDecodable::consensus_decode(d))); ConsensusDecodable::consensus_decode(d)?);
} }
Ok(ret) Ok(ret)
} }

View File

@ -47,8 +47,8 @@ pub trait Listener {
let (recv_tx, recv_rx) = channel(); let (recv_tx, recv_rx) = channel();
// Send version message to peer // Send version message to peer
let version_message = try!(sock.version_message(0)); let version_message = sock.version_message(0)?;
try!(sock.send_message(version_message)); sock.send_message(version_message)?;
// Message loop // Message loop
thread::spawn(move || { thread::spawn(move || {

View File

@ -56,7 +56,7 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for CommandString {
impl<D: SimpleDecoder> ConsensusDecodable<D> for CommandString { impl<D: SimpleDecoder> ConsensusDecodable<D> for CommandString {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<CommandString, D::Error> { fn consensus_decode(d: &mut D) -> Result<CommandString, D::Error> {
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 })); let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| if u > 0 { Some(u as char) } else { None }));
Ok(CommandString(rv)) Ok(CommandString(rv))
} }
@ -148,9 +148,9 @@ impl RawNetworkMessage {
impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage { impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage {
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
try!(self.magic.consensus_encode(s)); self.magic.consensus_encode(s)?;
try!(CommandString(self.command()).consensus_encode(s)); CommandString(self.command()).consensus_encode(s)?;
try!(CheckedData(match self.payload { CheckedData(match self.payload {
NetworkMessage::Version(ref dat) => serialize(dat), NetworkMessage::Version(ref dat) => serialize(dat),
NetworkMessage::Verack => Ok(vec![]), NetworkMessage::Verack => Ok(vec![]),
NetworkMessage::Addr(ref dat) => serialize(dat), NetworkMessage::Addr(ref dat) => serialize(dat),
@ -167,7 +167,7 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage {
NetworkMessage::Ping(ref dat) => serialize(dat), NetworkMessage::Ping(ref dat) => serialize(dat),
NetworkMessage::Pong(ref dat) => serialize(dat), NetworkMessage::Pong(ref dat) => serialize(dat),
NetworkMessage::Alert(ref dat) => serialize(dat) NetworkMessage::Alert(ref dat) => serialize(dat)
}.unwrap()).consensus_encode(s)); }.unwrap()).consensus_encode(s)?;
Ok(()) Ok(())
} }
} }
@ -176,28 +176,28 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for RawNetworkMessage {
// is there a more generic way to handle this? // is there a more generic way to handle this?
impl<D: SimpleDecoder<Error=util::Error>> ConsensusDecodable<D> for RawNetworkMessage { impl<D: SimpleDecoder<Error=util::Error>> ConsensusDecodable<D> for RawNetworkMessage {
fn consensus_decode(d: &mut D) -> Result<RawNetworkMessage, D::Error> { fn consensus_decode(d: &mut D) -> Result<RawNetworkMessage, D::Error> {
let magic = try!(ConsensusDecodable::consensus_decode(d)); let magic = ConsensusDecodable::consensus_decode(d)?;
let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d)); let CommandString(cmd): CommandString= ConsensusDecodable::consensus_decode(d)?;
let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d)); let CheckedData(raw_payload): CheckedData = ConsensusDecodable::consensus_decode(d)?;
let mut mem_d = RawDecoder::new(Cursor::new(raw_payload)); let mut mem_d = RawDecoder::new(Cursor::new(raw_payload));
let payload = match &cmd[..] { 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, "verack" => NetworkMessage::Verack,
"addr" => NetworkMessage::Addr(try!(propagate_err("addr".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(try!(propagate_err("inv".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(try!(propagate_err("getdata".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(try!(propagate_err("notfound".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(try!(propagate_err("getblocks".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(try!(propagate_err("getheaders".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, "mempool" => NetworkMessage::MemPool,
"block" => NetworkMessage::Block(try!(propagate_err("block".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(try!(propagate_err("headers".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, "getaddr" => NetworkMessage::GetAddr,
"ping" => NetworkMessage::Ping(try!(propagate_err("ping".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(try!(propagate_err("pong".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(try!(propagate_err("tx".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(try!(propagate_err("alert".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))) cmd => return Err(d.error(format!("unrecognized network command `{}`", cmd)))
}; };
Ok(RawNetworkMessage { Ok(RawNetworkMessage {

View File

@ -104,13 +104,13 @@ impl_consensus_encoding!(GetHeadersMessage, version, locator_hashes, stop_hash);
impl<S: SimpleEncoder> ConsensusEncodable<S> for Inventory { impl<S: SimpleEncoder> ConsensusEncodable<S> for Inventory {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
try!(match self.inv_type { match self.inv_type {
InvType::Error => 0u32, InvType::Error => 0u32,
InvType::Transaction => 1, InvType::Transaction => 1,
InvType::Block => 2, InvType::Block => 2,
InvType::WitnessBlock => 0x40000002, InvType::WitnessBlock => 0x40000002,
InvType::WitnessTransaction => 0x40000001 InvType::WitnessTransaction => 0x40000001
}.consensus_encode(s)); }.consensus_encode(s)?;
self.hash.consensus_encode(s) self.hash.consensus_encode(s)
} }
} }
@ -118,7 +118,7 @@ impl<S: SimpleEncoder> ConsensusEncodable<S> for Inventory {
impl<D: SimpleDecoder> ConsensusDecodable<D> for Inventory { impl<D: SimpleDecoder> ConsensusDecodable<D> for Inventory {
#[inline] #[inline]
fn consensus_decode(d: &mut D) -> Result<Inventory, D::Error> { fn consensus_decode(d: &mut D) -> Result<Inventory, D::Error> {
let int_type: u32 = try!(ConsensusDecodable::consensus_decode(d)); let int_type: u32 = ConsensusDecodable::consensus_decode(d)?;
Ok(Inventory { Ok(Inventory {
inv_type: match int_type { inv_type: match int_type {
0 => InvType::Error, 0 => InvType::Error,
@ -127,7 +127,7 @@ impl<D: SimpleDecoder> ConsensusDecodable<D> for Inventory {
// TODO do not fail here // TODO do not fail here
_ => { panic!("bad inventory type field") } _ => { panic!("bad inventory type field") }
}, },
hash: try!(ConsensusDecodable::consensus_decode(d)) hash: ConsensusDecodable::consensus_decode(d)?
}) })
} }
} }

View File

@ -54,8 +54,8 @@ impl VersionMessage {
// TODO: we have fixed services and relay to 0 // TODO: we have fixed services and relay to 0
/// Constructs a new `version` message /// Constructs a new `version` message
pub fn new(timestamp: i64, mut socket: Socket, nonce: u64, start_height: i32) -> Result<VersionMessage, util::Error> { pub fn new(timestamp: i64, mut socket: Socket, nonce: u64, start_height: i32) -> Result<VersionMessage, util::Error> {
let recv_addr = try!(socket.receiver_address()); let recv_addr = socket.receiver_address()?;
let send_addr = try!(socket.sender_address()); let send_addr = socket.sender_address()?;
Ok(VersionMessage { Ok(VersionMessage {
version: constants::PROTOCOL_VERSION, version: constants::PROTOCOL_VERSION,

View File

@ -45,7 +45,7 @@ pub fn serialize<T: ?Sized>(data: &T) -> Result<Vec<u8>, util::Error>
where T: ConsensusEncodable<RawEncoder<Cursor<Vec<u8>>>>, where T: ConsensusEncodable<RawEncoder<Cursor<Vec<u8>>>>,
{ {
let mut encoder = RawEncoder::new(Cursor::new(vec![])); 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()) Ok(encoder.into_inner().into_inner())
} }
@ -53,7 +53,7 @@ pub fn serialize<T: ?Sized>(data: &T) -> Result<Vec<u8>, util::Error>
pub fn serialize_hex<T: ?Sized>(data: &T) -> Result<String, util::Error> pub fn serialize_hex<T: ?Sized>(data: &T) -> Result<String, util::Error>
where T: ConsensusEncodable<RawEncoder<Cursor<Vec<u8>>>> where T: ConsensusEncodable<RawEncoder<Cursor<Vec<u8>>>>
{ {
let serial = try!(serialize(data)); let serial = serialize(data)?;
Ok(hex_encode(serial)) Ok(hex_encode(serial))
} }

View File

@ -144,8 +144,8 @@ impl Socket {
/// Produce a version message appropriate for this socket /// Produce a version message appropriate for this socket
pub fn version_message(&mut self, start_height: i32) -> Result<NetworkMessage, util::Error> { pub fn version_message(&mut self, start_height: i32) -> Result<NetworkMessage, util::Error> {
let recv_addr = try!(self.receiver_address()); let recv_addr = self.receiver_address()?;
let send_addr = try!(self.sender_address()); let send_addr = self.sender_address()?;
let timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) { let timestamp = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(dur) => dur, Ok(dur) => dur,
Err(err) => err.duration(), Err(err) => err.duration(),
@ -168,7 +168,7 @@ impl Socket {
pub fn send_message(&mut self, payload: NetworkMessage) -> Result<(), util::Error> { pub fn send_message(&mut self, payload: NetworkMessage) -> Result<(), util::Error> {
with_socket!(self, sock, { with_socket!(self, sock, {
let message = RawNetworkMessage { magic: self.magic, payload: payload }; 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) sock.flush().map_err(util::Error::Io)
}) })
} }

View File

@ -274,7 +274,7 @@ impl FromStr for Address {
} }
// Base 58 // Base 58
let data = try!(base58::from_check(s)); let data = base58::from_check(s)?;
if data.len() != 21 { if data.len() != 21 {
return Err(Error::Base58(base58::Error::InvalidLength(data.len()))); return Err(Error::Base58(base58::Error::InvalidLength(data.len())));

View File

@ -119,7 +119,7 @@ pub fn from(data: &str) -> Result<Vec<u8>, Error> {
/// Decode a base58check-encoded string /// Decode a base58check-encoded string
pub fn from_check(data: &str) -> Result<Vec<u8>, Error> { pub fn from_check(data: &str) -> Result<Vec<u8>, Error> {
let mut ret: Vec<u8> = try!(from(data)); let mut ret: Vec<u8> = from(data)?;
if ret.len() < 4 { if ret.len() < 4 {
return Err(Error::TooShort(ret.len())); return Err(Error::TooShort(ret.len()));
} }

View File

@ -241,7 +241,7 @@ impl ExtendedPrivKey {
depth: 0, depth: 0,
parent_fingerprint: Default::default(), parent_fingerprint: Default::default(),
child_number: ChildNumber::from_normal_idx(0), 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..]) chain_code: ChainCode::from(&result[32..])
}) })
} }
@ -251,7 +251,7 @@ impl ExtendedPrivKey {
-> Result<ExtendedPrivKey, Error> { -> Result<ExtendedPrivKey, Error> {
let mut sk = *master; let mut sk = *master;
for &num in path.iter() { for &num in path.iter() {
sk = try!(sk.ckd_priv(secp, num)); sk = sk.ckd_priv(secp, num)?;
} }
Ok(sk) Ok(sk)
} }
@ -276,8 +276,8 @@ impl ExtendedPrivKey {
hmac.input(&be_n); hmac.input(&be_n);
hmac.raw_result(&mut result); hmac.raw_result(&mut result);
let mut sk = try!(SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)); let mut sk = SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?;
try!(sk.add_assign(secp, &self.secret_key).map_err(Error::Ecdsa)); sk.add_assign(secp, &self.secret_key).map_err(Error::Ecdsa)?;
Ok(ExtendedPrivKey { Ok(ExtendedPrivKey {
network: self.network, network: self.network,
@ -342,7 +342,7 @@ impl ExtendedPubKey {
let mut result = [0; 64]; let mut result = [0; 64];
hmac.raw_result(&mut result); 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..]); let chain_code = ChainCode::from(&result[32..]);
Ok((secret_key, chain_code)) Ok((secret_key, chain_code))
} }
@ -351,9 +351,9 @@ impl ExtendedPubKey {
/// Public->Public child key derivation /// Public->Public child key derivation
pub fn ckd_pub(&self, secp: &Secp256k1, i: ChildNumber) -> Result<ExtendedPubKey, Error> { pub fn ckd_pub(&self, secp: &Secp256k1, i: ChildNumber) -> Result<ExtendedPubKey, Error> {
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(); 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 { Ok(ExtendedPubKey {
network: self.network, network: self.network,
@ -411,7 +411,7 @@ impl FromStr for ExtendedPrivKey {
fn from_str(inp: &str) -> Result<ExtendedPrivKey, base58::Error> { fn from_str(inp: &str) -> Result<ExtendedPrivKey, base58::Error> {
let s = Secp256k1::with_caps(secp256k1::ContextFlag::None); 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 { if data.len() != 78 {
return Err(base58::Error::InvalidLength(data.len())); return Err(base58::Error::InvalidLength(data.len()));
@ -432,9 +432,9 @@ impl FromStr for ExtendedPrivKey {
parent_fingerprint: Fingerprint::from(&data[5..9]), parent_fingerprint: Fingerprint::from(&data[5..9]),
child_number: child_number, child_number: child_number,
chain_code: ChainCode::from(&data[13..45]), 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| &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<ExtendedPubKey, base58::Error> { fn from_str(inp: &str) -> Result<ExtendedPubKey, base58::Error> {
let s = Secp256k1::with_caps(secp256k1::ContextFlag::None); 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 { if data.len() != 78 {
return Err(base58::Error::InvalidLength(data.len())); return Err(base58::Error::InvalidLength(data.len()));
@ -483,9 +483,9 @@ impl FromStr for ExtendedPubKey {
parent_fingerprint: Fingerprint::from(&data[5..9]), parent_fingerprint: Fingerprint::from(&data[5..9]),
child_number: child_number, child_number: child_number,
chain_code: ChainCode::from(&data[13..45]), 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| &data[45..78]).map_err(|e|
base58::Error::Other(e.to_string()))) base58::Error::Other(e.to_string()))?
}) })
} }
} }

View File

@ -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()); let mut hmac = hmac::Hmac::new(sha2::Sha256::new(), &key.serialize());
hmac.input(contract); hmac.input(contract);
hmac.raw_result(&mut hmac_raw); hmac.raw_result(&mut hmac_raw);
let hmac_sk = try!(SecretKey::from_slice(secp, &hmac_raw).map_err(Error::BadTweak)); let hmac_sk = SecretKey::from_slice(secp, &hmac_raw).map_err(Error::BadTweak)?;
try!(key.add_exp_assign(secp, &hmac_sk).map_err(Error::Secp)); key.add_exp_assign(secp, &hmac_sk).map_err(Error::Secp)?;
ret.push(key); ret.push(key);
} }
Ok(ret) 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) /// Tweak a secret key using some arbitrary data (calls `compute_tweak` internally)
pub fn tweak_secret_key(secp: &Secp256k1, key: &SecretKey, contract: &[u8]) -> Result<SecretKey, Error> { pub fn tweak_secret_key(secp: &Secp256k1, key: &SecretKey, contract: &[u8]) -> Result<SecretKey, Error> {
// Compute public key // 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 // Compute tweak
let hmac_sk = try!(compute_tweak(secp, &pk, contract)); let hmac_sk = compute_tweak(secp, &pk, contract)?;
// Execute the tweak // Execute the tweak
let mut key = *key; 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 // Return
Ok(key) Ok(key)
} }
@ -213,8 +213,8 @@ pub fn create_address(secp: &Secp256k1,
keys: &[PublicKey], keys: &[PublicKey],
template: &Template) template: &Template)
-> Result<address::Address, Error> { -> Result<address::Address, Error> {
let keys = try!(tweak_keys(secp, keys, contract)); let keys = tweak_keys(secp, keys, contract)?;
let script = try!(template.to_script(&keys)); let script = template.to_script(&keys)?;
Ok(address::Address { Ok(address::Address {
network: network, network: network,
payload: address::Payload::ScriptHash( payload: address::Payload::ScriptHash(

View File

@ -141,7 +141,7 @@ impl ser::Serialize for Decimal {
impl de::Deserialize for Decimal { impl de::Deserialize for Decimal {
// Deserialize through strason for the same reason as in `Serialize` // Deserialize through strason for the same reason as in `Serialize`
fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<Decimal, D::Error> { fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<Decimal, D::Error> {
let json: Json = try!(de::Deserialize::deserialize(d)); let json: Json = de::Deserialize::deserialize(d)?;
match json.num() { match json.num() {
Some(s) => { Some(s) => {
// We know this will be a well-formed Json number, so we can // 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 { impl de::Deserialize for UDecimal {
// Deserialize through strason for the same reason as in `Serialize` // Deserialize through strason for the same reason as in `Serialize`
fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<UDecimal, D::Error> { fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<UDecimal, D::Error> {
let json: Json = try!(de::Deserialize::deserialize(d)); let json: Json = de::Deserialize::deserialize(d)?;
match json.num() { match json.num() {
Some(s) => { Some(s) => {
// We know this will be a well-formed Json number, so we can // We know this will be a well-formed Json number, so we can

View File

@ -360,7 +360,7 @@ impl fmt::Debug for Sha256dHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Sha256dHash(data) = self; let &Sha256dHash(data) = self;
for ch in data.iter() { for ch in data.iter() {
try!(write!(f, "{:02x}", ch)); write!(f, "{:02x}", ch)?;
} }
Ok(()) Ok(())
} }
@ -371,7 +371,7 @@ impl fmt::Debug for Hash160 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Hash160(data) = self; let &Hash160(data) = self;
for ch in data.iter() { for ch in data.iter() {
try!(write!(f, "{:02x}", ch)); write!(f, "{:02x}", ch)?;
} }
Ok(()) Ok(())
} }
@ -394,7 +394,7 @@ impl fmt::LowerHex for Sha256dHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Sha256dHash(data) = self; let &Sha256dHash(data) = self;
for ch in data.iter().rev() { for ch in data.iter().rev() {
try!(write!(f, "{:02x}", ch)); write!(f, "{:02x}", ch)?;
} }
Ok(()) Ok(())
} }
@ -405,7 +405,7 @@ impl fmt::UpperHex for Sha256dHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Sha256dHash(data) = self; let &Sha256dHash(data) = self;
for ch in data.iter().rev() { for ch in data.iter().rev() {
try!(write!(f, "{:02X}", ch)); write!(f, "{:02X}", ch)?;
} }
Ok(()) Ok(())
} }

View File

@ -25,7 +25,7 @@ pub fn hex_bytes(s: &str) -> Result<Vec<u8>, Error> {
let mut v = vec![]; let mut v = vec![];
let mut iter = s.chars().pair(); let mut iter = s.chars().pair();
// Do the parsing // 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 } if e.is_err() { e }
else { else {
match (f.to_digit(16), s.to_digit(16)) { match (f.to_digit(16), s.to_digit(16)) {
@ -40,7 +40,7 @@ pub fn hex_bytes(s: &str) -> Result<Vec<u8>, Error> {
(Some(f), Some(s)) => { v.push((f * 0x10 + s) as u8); Ok(()) } (Some(f), Some(s)) => { v.push((f * 0x10 + s) as u8); Ok(()) }
} }
} }
)); )?;
// Check that there was no remainder // Check that there was no remainder
match iter.remainder() { match iter.remainder() {
Some(_) => Err(Error::Detail( Some(_) => Err(Error::Detail(

View File

@ -113,7 +113,7 @@ impl FromStr for Privkey {
type Err = Error; type Err = Error;
fn from_str(s: &str) -> Result<Privkey, Error> { fn from_str(s: &str) -> Result<Privkey, Error> {
let data = try!(base58::from_check(s)); let data = base58::from_check(s)?;
let compressed = match data.len() { let compressed = match data.len() {
33 => false, 33 => false,
@ -128,8 +128,8 @@ impl FromStr for Privkey {
}; };
let secp = Secp256k1::without_caps(); let secp = Secp256k1::without_caps();
let key = try!(SecretKey::from_slice(&secp, &data[1..33]) let key = SecretKey::from_slice(&secp, &data[1..33])
.map_err(|_| base58::Error::Other("Secret key out of range".to_owned()))); .map_err(|_| base58::Error::Other("Secret key out of range".to_owned()))?;
Ok(Privkey { Ok(Privkey {
compressed: compressed, compressed: compressed,

View File

@ -321,9 +321,9 @@ macro_rules! construct_uint {
impl fmt::Debug for $name { impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &$name(ref data) = self; let &$name(ref data) = self;
try!(write!(f, "0x")); write!(f, "0x")?;
for ch in data.iter().rev() { for ch in data.iter().rev() {
try!(write!(f, "{:016x}", ch)); write!(f, "{:016x}", ch)?;
} }
Ok(()) Ok(())
} }
@ -339,7 +339,7 @@ macro_rules! construct_uint {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> { fn consensus_encode(&self, s: &mut S) -> Result<(), S::Error> {
let &$name(ref data) = self; 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(()) Ok(())
} }
} }
@ -347,7 +347,7 @@ macro_rules! construct_uint {
impl<D: ::network::serialize::SimpleDecoder> ::network::encodable::ConsensusDecodable<D> for $name { impl<D: ::network::serialize::SimpleDecoder> ::network::encodable::ConsensusDecodable<D> for $name {
fn consensus_decode(d: &mut D) -> Result<$name, D::Error> { fn consensus_decode(d: &mut D) -> Result<$name, D::Error> {
use network::encodable::ConsensusDecodable; 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)) Ok($name(ret))
} }
} }