diff --git a/src/blockdata/block.rs b/src/blockdata/block.rs index 059ab9ae..c081609b 100644 --- a/src/blockdata/block.rs +++ b/src/blockdata/block.rs @@ -78,7 +78,7 @@ impl Block { if self.txdata.iter().all(|t| t.input.iter().all(|i| i.witness.is_empty())) { return true; } - if self.txdata.len() > 0 { + if !self.txdata.is_empty() { let coinbase = &self.txdata[0]; if coinbase.is_coin_base() { // commitment is in the last output that starts with below magic diff --git a/src/consensus/encode.rs b/src/consensus/encode.rs index 4f81c42f..e3a38396 100644 --- a/src/consensus/encode.rs +++ b/src/consensus/encode.rs @@ -162,7 +162,7 @@ pub fn serialize_hex(data: &T) -> String { /// Deserialize an object from a vector, will error if said deserialization /// doesn't consume the entire vector. -pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result { +pub fn deserialize(data: &[u8]) -> Result { let (rv, consumed) = deserialize_partial(data)?; // Fail if data are not consumed entirely. @@ -175,8 +175,8 @@ pub fn deserialize<'a, T: Decodable>(data: &'a [u8]) -> Result { /// Deserialize an object from a vector, but will not report an error if said deserialization /// doesn't consume the entire vector. -pub fn deserialize_partial<'a, T: Decodable>( - data: &'a [u8], +pub fn deserialize_partial( + data: &[u8], ) -> Result<(T, usize), Error> { let mut decoder = Cursor::new(data); let rv = Decodable::consensus_decode(&mut decoder)?; diff --git a/src/network/address.rs b/src/network/address.rs index f9dcbf0b..6edc5bb5 100644 --- a/src/network/address.rs +++ b/src/network/address.rs @@ -41,9 +41,9 @@ const ONION : [u16; 3] = [0xFD87, 0xD87E, 0xEB43]; impl Address { /// Create an address message for a socket pub fn new (socket :&SocketAddr, services: ServiceFlags) -> Address { - let (address, port) = match socket { - &SocketAddr::V4(ref addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()), - &SocketAddr::V6(ref addr) => (addr.ip().segments(), addr.port()) + let (address, port) = match *socket { + SocketAddr::V4(addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()), + SocketAddr::V6(addr) => (addr.ip().segments(), addr.port()) }; Address { address: address, port: port, services: services } } diff --git a/src/network/message.rs b/src/network/message.rs index 5710023c..5147252b 100644 --- a/src/network/message.rs +++ b/src/network/message.rs @@ -72,9 +72,7 @@ impl Encodable for CommandString { if strbytes.len() > 12 { return Err(encode::Error::UnrecognizedNetworkCommand(self.0.clone().into_owned())); } - for x in 0..strbytes.len() { - rawbytes[x] = strbytes[x]; - } + rawbytes[..strbytes.len()].clone_from_slice(&strbytes[..]); rawbytes.consensus_encode(s) } } diff --git a/src/util/address.rs b/src/util/address.rs index 7715736f..dcb418d5 100644 --- a/src/util/address.rs +++ b/src/util/address.rs @@ -18,26 +18,22 @@ //! # Example: creating a new address from a randomly-generated key pair //! //! ```rust -//! extern crate secp256k1; -//! extern crate bitcoin; //! //! use bitcoin::network::constants::Network; //! use bitcoin::util::address::Address; //! use bitcoin::util::key; -//! use secp256k1::Secp256k1; -//! use secp256k1::rand::thread_rng; +//! use bitcoin::secp256k1::Secp256k1; +//! use bitcoin::secp256k1::rand::thread_rng; //! -//! fn main() { -//! // Generate random key pair -//! let s = Secp256k1::new(); -//! let public_key = key::PublicKey { -//! compressed: true, -//! key: s.generate_keypair(&mut thread_rng()).1, -//! }; +//! // Generate random key pair +//! let s = Secp256k1::new(); +//! let public_key = key::PublicKey { +//! compressed: true, +//! key: s.generate_keypair(&mut thread_rng()).1, +//! }; //! -//! // Generate pay-to-pubkey-hash address -//! let address = Address::p2pkh(&public_key, Network::Bitcoin); -//! } +//! // Generate pay-to-pubkey-hash address +//! let address = Address::p2pkh(&public_key, Network::Bitcoin); //! ``` use std::fmt::{self, Display, Formatter}; @@ -219,7 +215,7 @@ impl Payload { assert!(ver.to_u8() <= 16); let mut verop = ver.to_u8(); if verop > 0 { - verop = 0x50 + verop; + verop += 0x50; } script::Builder::new().push_opcode(verop.into()).push_slice(&prog) } @@ -406,7 +402,7 @@ impl Display for Address { /// Returns the same slice when no prefix is found. fn find_bech32_prefix(bech32: &str) -> &str { // Split at the last occurrence of the separator character '1'. - match bech32.rfind("1") { + match bech32.rfind('1') { None => bech32, Some(sep) => bech32.split_at(sep).0, } @@ -427,7 +423,7 @@ impl FromStr for Address { if let Some(network) = bech32_network { // decode as bech32 let (_, payload) = bech32::decode(s)?; - if payload.len() == 0 { + if payload.is_empty() { return Err(Error::EmptyBech32Payload); } diff --git a/src/util/amount.rs b/src/util/amount.rs index 31cb31f6..1fea2b15 100644 --- a/src/util/amount.rs +++ b/src/util/amount.rs @@ -19,6 +19,7 @@ use std::error; use std::fmt::{self, Write}; use std::ops; use std::str::FromStr; +use std::cmp::Ordering; /// A set of denominations in which amounts can be expressed. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] @@ -131,7 +132,7 @@ impl error::Error for ParseAmountError { fn is_too_precise(s: &str, precision: usize) -> bool { - s.contains(".") || precision >= s.len() || s.chars().rev().take(precision).any(|d| d != '0') + s.contains('.') || precision >= s.len() || s.chars().rev().take(precision).any(|d| d != '0') } /// Parse decimal string in the given denomination into a satoshi value and a @@ -140,14 +141,14 @@ fn parse_signed_to_satoshi( mut s: &str, denom: Denomination, ) -> Result<(bool, u64), ParseAmountError> { - if s.len() == 0 { + if s.is_empty() { return Err(ParseAmountError::InvalidFormat); } if s.len() > 50 { return Err(ParseAmountError::InputTooLarge); } - let is_negative = s.chars().next().unwrap() == '-'; + let is_negative = s.starts_with('-'); if is_negative { if s.len() == 1 { return Err(ParseAmountError::InvalidFormat); @@ -229,27 +230,29 @@ fn fmt_satoshi_in( f.write_str("-")?; } - if denom.precision() > 0 { - // add zeroes in the end - let width = denom.precision() as usize; - write!(f, "{}{:0width$}", satoshi, 0, width = width)?; - } else if denom.precision() < 0 { - // need to inject a comma in the number - let nb_decimals = denom.precision().abs() as usize; - let real = format!("{:0width$}", satoshi, width = nb_decimals); - if real.len() == nb_decimals { - write!(f, "0.{}", &real[real.len() - nb_decimals..])?; - } else { - write!( - f, - "{}.{}", - &real[0..(real.len() - nb_decimals)], - &real[real.len() - nb_decimals..] - )?; + let precision = denom.precision(); + match precision.cmp(&0) { + Ordering::Greater => { + // add zeroes in the end + let width = precision as usize; + write!(f, "{}{:0width$}", satoshi, 0, width = width)?; } - } else { - // denom.precision() == 0 - write!(f, "{}", satoshi)?; + Ordering::Less => { + // need to inject a comma in the number + let nb_decimals = precision.abs() as usize; + let real = format!("{:0width$}", satoshi, width = nb_decimals); + if real.len() == nb_decimals { + write!(f, "0.{}", &real[real.len() - nb_decimals..])?; + } else { + write!( + f, + "{}.{}", + &real[0..(real.len() - nb_decimals)], + &real[real.len() - nb_decimals..] + )?; + } + } + Ordering::Equal => write!(f, "{}", satoshi)?, } Ok(()) } @@ -327,7 +330,7 @@ impl Amount { /// If you want to parse only the amount without the denomination, /// use [from_str_in]. pub fn from_str_with_denomination(s: &str) -> Result { - let mut split = s.splitn(3, " "); + let mut split = s.splitn(3, ' '); let amt_str = split.next().unwrap(); let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?; if split.next().is_some() { @@ -614,7 +617,7 @@ impl SignedAmount { return Err(ParseAmountError::TooBig); } Ok(match negative { - true => SignedAmount(-1 * satoshi as i64), + true => SignedAmount(-(satoshi as i64)), false => SignedAmount(satoshi as i64), }) } @@ -624,7 +627,7 @@ impl SignedAmount { /// If you want to parse only the amount without the denomination, /// use [from_str_in]. pub fn from_str_with_denomination(s: &str) -> Result { - let mut split = s.splitn(3, " "); + let mut split = s.splitn(3, ' '); let amt_str = split.next().unwrap(); let denom_str = split.next().ok_or(ParseAmountError::InvalidFormat)?; if split.next().is_some() { diff --git a/src/util/base58.rs b/src/util/base58.rs index 68a0a2b7..2134b5c6 100644 --- a/src/util/base58.rs +++ b/src/util/base58.rs @@ -103,7 +103,7 @@ impl SmallVec { } } -static BASE58_CHARS: &'static [u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +static BASE58_CHARS: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BASE58_DIGITS: [Option; 128] = [ None, None, None, None, None, None, None, None, // 0-7 diff --git a/src/util/bip158.rs b/src/util/bip158.rs index d196a11d..4cb896a5 100644 --- a/src/util/bip158.rs +++ b/src/util/bip158.rs @@ -49,6 +49,8 @@ use std::collections::HashSet; use std::error; use std::fmt::{Display, Formatter}; use std::io::Cursor; +use std::cmp::Ordering; + use hashes::{Hash, siphash24}; use hash_types::{BlockHash, FilterHash}; @@ -260,17 +262,17 @@ impl GCSFilterReader { let mut remaining = n_elements.0 - 1; for p in mapped { loop { - if data == p { - return Ok(true); - } else if data < p { - if remaining > 0 { - data += self.filter.golomb_rice_decode(&mut reader)?; - remaining -= 1; - } else { - return Ok(false); + match data.cmp(&p) { + Ordering::Equal => return Ok(true), + Ordering::Less => { + if remaining > 0 { + data += self.filter.golomb_rice_decode(&mut reader)?; + remaining -= 1; + } else { + return Ok(false); + } } - } else { - break; + Ordering::Greater => break, } } } @@ -301,17 +303,17 @@ impl GCSFilterReader { let mut remaining = n_elements.0 - 1; for p in mapped { loop { - if data == p { - break; - } else if data < p { - if remaining > 0 { - data += self.filter.golomb_rice_decode(&mut reader)?; - remaining -= 1; - } else { - return Ok(false); - } - } else { - return Ok(false); + match data.cmp(&p) { + Ordering::Equal => break, + Ordering::Less => { + if remaining > 0 { + data += self.filter.golomb_rice_decode(&mut reader)?; + remaining -= 1; + } else { + return Ok(false); + } + }, + Ordering::Greater => return Ok(false), } } } @@ -423,7 +425,7 @@ impl GCSFilter { q += 1; } let r = reader.read(self.p)?; - return Ok((q << self.p) + r); + Ok((q << self.p) + r) } /// Hash an arbitrary slice with siphash using parameters of this filter diff --git a/src/util/bip32.rs b/src/util/bip32.rs index d66167ec..be3e189c 100644 --- a/src/util/bip32.rs +++ b/src/util/bip32.rs @@ -179,13 +179,11 @@ impl FromStr for ChildNumber { type Err = Error; fn from_str(inp: &str) -> Result { - Ok(match inp.chars().last().map_or(false, |l| l == '\'' || l == 'h') { - true => ChildNumber::from_hardened_idx( - inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)? - )?, - false => ChildNumber::from_normal_idx( - inp.parse().map_err(|_| Error::InvalidChildNumberFormat)? - )?, + let is_hardened = inp.chars().last().map_or(false, |l| l == '\'' || l == 'h'); + Ok(if is_hardened { + ChildNumber::from_hardened_idx(inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)?)? + } else { + ChildNumber::from_normal_idx(inp.parse().map_err(|_| Error::InvalidChildNumberFormat)?)? }) } } @@ -258,7 +256,7 @@ impl FromStr for DerivationPath { type Err = Error; fn from_str(path: &str) -> Result { - let mut parts = path.split("/"); + let mut parts = path.split('/'); // First parts must be `m`. if parts.next().unwrap() != "m" { return Err(Error::InvalidDerivationPathFormat); @@ -292,11 +290,7 @@ impl<'a> Iterator for DerivationPathIterator<'a> { type Item = DerivationPath; fn next(&mut self) -> Option { - if self.next_child.is_none() { - return None; - } - - let ret = self.next_child.unwrap(); + let ret = self.next_child?; self.next_child = ret.increment().ok(); Some(self.base.child(ret)) } diff --git a/src/util/hash.rs b/src/util/hash.rs index ba7b6d20..fa089135 100644 --- a/src/util/hash.rs +++ b/src/util/hash.rs @@ -30,7 +30,7 @@ pub fn bitcoin_merkle_root_inline(data: &mut [T]) -> T ::Engine: io::Write, { // Base case - if data.len() < 1 { + if data.is_empty() { return Default::default(); } if data.len() < 2 { diff --git a/src/util/merkleblock.rs b/src/util/merkleblock.rs index 2c097d9b..d4ce3973 100644 --- a/src/util/merkleblock.rs +++ b/src/util/merkleblock.rs @@ -25,12 +25,10 @@ //! # Examples //! //! ```rust -//! extern crate bitcoin; //! use bitcoin::hash_types::Txid; //! use bitcoin::hashes::hex::FromHex; //! use bitcoin::{Block, MerkleBlock}; //! -//! # fn main() { //! // Get the proof from a bitcoind by running in the terminal: //! // $ TXID="5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2" //! // $ bitcoin-cli gettxoutproof [\"$TXID\"] @@ -52,7 +50,6 @@ //! ); //! assert_eq!(1, index.len()); //! assert_eq!(1, index[0]); -//! # } //! ``` use std::collections::HashSet; @@ -133,12 +130,10 @@ impl PartialMerkleTree { /// # Examples /// /// ```rust - /// extern crate bitcoin; /// use bitcoin::hash_types::Txid; /// use bitcoin::hashes::hex::FromHex; /// use bitcoin::util::merkleblock::PartialMerkleTree; /// - /// # fn main() { /// // Block 80000 /// let txids: Vec = [ /// "c06fbab289f723c6261d3030ddb6be121f7d2508d77862bb1e484f5cd7f92b25", @@ -152,7 +147,6 @@ impl PartialMerkleTree { /// let matches = vec![false, true]; /// let tree = PartialMerkleTree::from_txids(&txids, &matches); /// assert!(tree.extract_matches(&mut vec![], &mut vec![]).is_ok()); - /// # } /// ``` pub fn from_txids(txids: &[Txid], matches: &[bool]) -> Self { // We can never have zero txs in a merkle block, we always need the coinbase tx @@ -271,7 +265,7 @@ impl PartialMerkleTree { if height == 0 || !parent_of_match { // If at height 0, or nothing interesting below, store hash and stop let hash = self.calc_hash(height, pos, txids); - self.hashes.push(hash.into()); + self.hashes.push(hash); } else { // Otherwise, don't store any hash, but descend into the subtrees self.traverse_and_build(height - 1, pos * 2, txids, matches); @@ -407,12 +401,10 @@ impl MerkleBlock { /// # Examples /// /// ```rust - /// extern crate bitcoin; /// use bitcoin::hash_types::Txid; /// use bitcoin::hashes::hex::FromHex; /// use bitcoin::{Block, MerkleBlock}; /// - /// # fn main() { /// // Block 80000 /// let block_bytes = Vec::from_hex("01000000ba8b9cda965dd8e536670f9ddec10e53aab14b20bacad2\ /// 7b9137190000000000190760b278fe7b8565fda3b968b918d5fd997f993b23674c0af3b6fde300b38f33\ @@ -437,7 +429,6 @@ impl MerkleBlock { /// let mut index: Vec = vec![]; /// assert!(mb.extract_matches(&mut matches, &mut index).is_ok()); /// assert_eq!(txid, matches[0]); - /// # } /// ``` pub fn from_block(block: &Block, match_txids: &HashSet) -> Self { let header = block.header; diff --git a/src/util/misc.rs b/src/util/misc.rs index f5c2a545..2ee4fb0c 100644 --- a/src/util/misc.rs +++ b/src/util/misc.rs @@ -20,14 +20,14 @@ use hashes::{sha256d, Hash}; use blockdata::opcodes; use consensus::encode; -static MSG_SIGN_PREFIX: &'static [u8] = b"\x18Bitcoin Signed Message:\n"; +static MSG_SIGN_PREFIX: &[u8] = b"\x18Bitcoin Signed Message:\n"; /// Search for `needle` in the vector `haystack` and remove every /// instance of it, returning the number of instances removed. /// Loops through the vector opcode by opcode, skipping pushed data. pub fn script_find_and_remove(haystack: &mut Vec, needle: &[u8]) -> usize { if needle.len() > haystack.len() { return 0; } - if needle.len() == 0 { return 0; } + if needle.is_empty() { return 0; } let mut top = haystack.len() - needle.len(); let mut n_deleted = 0; diff --git a/src/util/psbt/macros.rs b/src/util/psbt/macros.rs index 80f6678d..5109b94f 100644 --- a/src/util/psbt/macros.rs +++ b/src/util/psbt/macros.rs @@ -104,7 +104,7 @@ macro_rules! impl_psbtmap_consensus_enc_dec_oding { macro_rules! impl_psbt_insert_pair { ($slf:ident.$unkeyed_name:ident <= <$raw_key:ident: _>|<$raw_value:ident: $unkeyed_value_type:ty>) => { if $raw_key.key.is_empty() { - if let None = $slf.$unkeyed_name { + if $slf.$unkeyed_name.is_none() { let val: $unkeyed_value_type = ::util::psbt::serialize::Deserialize::deserialize(&$raw_value)?; $slf.$unkeyed_name = Some(val)