From 779d4110c6430916755ca022812a775c0122d3c8 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Wed, 3 Nov 2021 10:20:34 +0100 Subject: [PATCH] Fixed a bunch of clippy lints, added clippy.toml This is the initial step towards using and maybe enforcing clippy. It does not fix all lints as some are not applicable. They may be explicitly ignored later. --- clippy.toml | 1 + src/blockdata/block.rs | 2 +- src/blockdata/constants.rs | 8 +++--- src/blockdata/script.rs | 6 ++--- src/blockdata/transaction.rs | 42 +++++++++++++++++++++++--------- src/consensus/encode.rs | 6 ++--- src/network/address.rs | 10 ++++---- src/network/message.rs | 32 ++++++++++++++++++------ src/network/message_blockdata.rs | 8 +++--- src/network/message_network.rs | 14 +++++------ src/util/address.rs | 34 +++++++++++++------------- src/util/amount.rs | 4 +-- src/util/base58.rs | 4 +-- src/util/bip143.rs | 8 +++--- src/util/bip158.rs | 10 ++++---- src/util/bip32.rs | 31 +++++++++++------------ src/util/contracthash.rs | 4 +-- src/util/ecdsa.rs | 20 +++++++-------- src/util/merkleblock.rs | 2 +- src/util/misc.rs | 6 ++--- src/util/mod.rs | 2 +- src/util/psbt/map/global.rs | 9 ++----- src/util/psbt/map/input.rs | 4 +-- src/util/psbt/map/output.rs | 2 +- src/util/psbt/raw.rs | 4 +-- src/util/sighash.rs | 2 +- 26 files changed, 154 insertions(+), 121 deletions(-) create mode 100644 clippy.toml diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 00000000..a8d2e37f --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +msrv = "1.29" diff --git a/src/blockdata/block.rs b/src/blockdata/block.rs index da5b6772..6abbfb8a 100644 --- a/src/blockdata/block.rs +++ b/src/blockdata/block.rs @@ -291,7 +291,7 @@ impl Block { script::Instruction::PushBytes(b) if b.len() <= 8 => { // Expand the push to exactly 8 bytes (LE). let mut full = [0; 8]; - full[0..b.len()].copy_from_slice(&b[..]); + full[0..b.len()].copy_from_slice(b); Ok(util::endian::slice_to_u64_le(&full)) } script::Instruction::PushBytes(b) if b.len() > 8 => { diff --git a/src/blockdata/constants.rs b/src/blockdata/constants.rs index bdf8e2ca..271557ad 100644 --- a/src/blockdata/constants.rs +++ b/src/blockdata/constants.rs @@ -129,7 +129,7 @@ pub fn genesis_block(network: Network) -> Block { bits: 0x1d00ffff, nonce: 2083236893 }, - txdata: txdata + txdata, } } Network::Testnet => { @@ -142,7 +142,7 @@ pub fn genesis_block(network: Network) -> Block { bits: 0x1d00ffff, nonce: 414098458 }, - txdata: txdata + txdata, } } Network::Signet => { @@ -155,7 +155,7 @@ pub fn genesis_block(network: Network) -> Block { bits: 0x1e0377ae, nonce: 52613770 }, - txdata: txdata + txdata, } } Network::Regtest => { @@ -168,7 +168,7 @@ pub fn genesis_block(network: Network) -> Block { bits: 0x207fffff, nonce: 2 }, - txdata: txdata + txdata, } } } diff --git a/src/blockdata/script.rs b/src/blockdata/script.rs index b5ba2040..d9a70cb3 100644 --- a/src/blockdata/script.rs +++ b/src/blockdata/script.rs @@ -325,7 +325,7 @@ impl Script { pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Script { Builder::new() .push_opcode(version.into()) - .push_slice(&program) + .push_slice(program) .into_script() } @@ -339,12 +339,12 @@ impl Script { /// Returns 160-bit hash of the script pub fn script_hash(&self) -> ScriptHash { - ScriptHash::hash(&self.as_bytes()) + ScriptHash::hash(self.as_bytes()) } /// Returns 256-bit hash of the script for P2WSH outputs pub fn wscript_hash(&self) -> WScriptHash { - WScriptHash::hash(&self.as_bytes()) + WScriptHash::hash(self.as_bytes()) } /// The length in bytes of the script diff --git a/src/blockdata/transaction.rs b/src/blockdata/transaction.rs index 045e0aba..eab393c3 100644 --- a/src/blockdata/transaction.rs +++ b/src/blockdata/transaction.rs @@ -56,8 +56,8 @@ impl OutPoint { #[inline] pub fn new(txid: Txid, vout: u32) -> OutPoint { OutPoint { - txid: txid, - vout: vout, + txid, + vout, } } @@ -153,7 +153,7 @@ fn parse_vout(s: &str) -> Result { return Err(ParseOutPointError::VoutNotCanonical); } } - Ok(s.parse().map_err(ParseOutPointError::Vout)?) + s.parse().map_err(ParseOutPointError::Vout) } impl ::core::str::FromStr for OutPoint { @@ -634,9 +634,9 @@ impl Decodable for Transaction { Err(encode::Error::ParseFailed("witness flag set but no witnesses present")) } else { Ok(Transaction { - version: version, - input: input, - output: output, + version, + input, + output, lock_time: Decodable::consensus_decode(d)?, }) } @@ -649,8 +649,8 @@ impl Decodable for Transaction { // non-segwit } else { Ok(Transaction { - version: version, - input: input, + version, + input, output: Decodable::consensus_decode(&mut d)?, lock_time: Decodable::consensus_decode(d)?, }) @@ -715,17 +715,17 @@ impl fmt::Display for EcdsaSigHashType { } impl str::FromStr for EcdsaSigHashType { - type Err = String; + type Err = SigHashTypeParseError; fn from_str(s: &str) -> Result { - match s.as_ref() { + match s { "SIGHASH_ALL" => Ok(EcdsaSigHashType::All), "SIGHASH_NONE" => Ok(EcdsaSigHashType::None), "SIGHASH_SINGLE" => Ok(EcdsaSigHashType::Single), "SIGHASH_ALL|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::AllPlusAnyoneCanPay), "SIGHASH_NONE|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::NonePlusAnyoneCanPay), "SIGHASH_SINGLE|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::SinglePlusAnyoneCanPay), - _ => Err("can't recognize SIGHASH string".to_string()) + _ => Err(SigHashTypeParseError { string: s.to_owned() }), } } } @@ -798,6 +798,24 @@ impl From for u32 { } } +/// Error returned when parsing `SigHashType` fails. +/// +/// This is currently returned for unrecognized sighash strings. +#[derive(Debug, Clone)] +pub struct SigHashTypeParseError { + string: String, +} + +impl fmt::Display for SigHashTypeParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "can't recognize SIGHASH string '{}'", self.string) + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(feature = "std")] +impl ::std::error::Error for SigHashTypeParseError {} + #[cfg(test)] mod tests { use super::{OutPoint, ParseOutPointError, Transaction, TxIn, NonStandardSigHashType}; @@ -1116,7 +1134,7 @@ mod tests { "SigHash_NONE", ]; for s in sht_mistakes { - assert_eq!(EcdsaSigHashType::from_str(s).unwrap_err(), "can't recognize SIGHASH string"); + assert_eq!(EcdsaSigHashType::from_str(s).unwrap_err().to_string(), format!("can't recognize SIGHASH string '{}'", s)); } } diff --git a/src/consensus/encode.rs b/src/consensus/encode.rs index e0cc3193..eea64036 100644 --- a/src/consensus/encode.rs +++ b/src/consensus/encode.rs @@ -461,7 +461,7 @@ impl Encodable for String { fn consensus_encode(&self, mut s: S) -> Result { let b = self.as_bytes(); let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?; - s.emit_slice(&b)?; + s.emit_slice(b)?; Ok(vi_len + b.len()) } } @@ -480,7 +480,7 @@ impl Encodable for Cow<'static, str> { fn consensus_encode(&self, mut s: S) -> Result { let b = self.as_bytes(); let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?; - s.emit_slice(&b)?; + s.emit_slice(b)?; Ok(vi_len + b.len()) } } @@ -601,7 +601,7 @@ impl_vec!(u64); pub(crate) fn consensus_encode_with_size(data: &[u8], mut s: S) -> Result { let vi_len = VarInt(data.len() as u64).consensus_encode(&mut s)?; - s.emit_slice(&data)?; + s.emit_slice(data)?; Ok(vi_len + data.len()) } diff --git a/src/network/address.rs b/src/network/address.rs index cd43cfba..b0f3a929 100644 --- a/src/network/address.rs +++ b/src/network/address.rs @@ -47,7 +47,7 @@ impl Address { 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 } + Address { address, port, services } } /// Extract socket address from an [Address] message. @@ -73,9 +73,9 @@ impl Address { fn addr_to_be(addr: [u16; 8]) -> [u16; 8] { // consensus_encode always encodes in LE, and we want to encode in BE. // this utility fn swap bytes before encoding so that the encoded result will be BE - let mut result = addr.clone(); - for i in 0..8 { - result[i] = result[i].swap_bytes(); + let mut result = addr; + for word in &mut result { + *word = word.swap_bytes(); } result } @@ -266,7 +266,7 @@ impl AddrV2Message { match self.addr { AddrV2::Ipv4(addr) => Ok(SocketAddr::V4(SocketAddrV4::new(addr, self.port))), AddrV2::Ipv6(addr) => Ok(SocketAddr::V6(SocketAddrV6::new(addr, self.port, 0, 0))), - _ => return Err(io::Error::from(io::ErrorKind::AddrNotAvailable)), + _ => Err(io::Error::from(io::ErrorKind::AddrNotAvailable)), } } } diff --git a/src/network/message.rs b/src/network/message.rs index fc6f5db8..8f8a850b 100644 --- a/src/network/message.rs +++ b/src/network/message.rs @@ -49,12 +49,12 @@ impl CommandString { /// - `&'static str` /// - `String` /// - /// Returns an empty error if and only if the string is + /// Returns an error if and only if the string is /// larger than 12 characters in length. - pub fn try_from>>(s: S) -> Result { + pub fn try_from>>(s: S) -> Result { let cow = s.into(); - if cow.as_ref().len() > 12 { - Err(()) + if cow.len() > 12 { + Err(CommandStringError { cow }) } else { Ok(CommandString(cow)) } @@ -82,7 +82,7 @@ impl Encodable for CommandString { let mut rawbytes = [0u8; 12]; let strbytes = self.0.as_bytes(); debug_assert!(strbytes.len() <= 12); - rawbytes[..strbytes.len()].clone_from_slice(&strbytes[..]); + rawbytes[..strbytes.len()].copy_from_slice(strbytes); rawbytes.consensus_encode(s) } } @@ -100,6 +100,24 @@ impl Decodable for CommandString { } } +/// Error returned when a command string is invalid. +/// +/// This is currently returned for command strings longer than 12. +#[derive(Clone, Debug)] +pub struct CommandStringError { + cow: Cow<'static, str>, +} + +impl fmt::Display for CommandStringError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "the command string '{}' has length {} which is larger than 12", self.cow, self.cow.len()) + } +} + +#[cfg_attr(docsrs, doc(cfg(feature = "std")))] +#[cfg(feature = "std")] +impl ::std::error::Error for CommandStringError { } + #[derive(Clone, Debug, PartialEq, Eq)] /// A Network message pub struct RawNetworkMessage { @@ -395,8 +413,8 @@ impl Decodable for RawNetworkMessage { } }; Ok(RawNetworkMessage { - magic: magic, - payload: payload + magic, + payload, }) } } diff --git a/src/network/message_blockdata.rs b/src/network/message_blockdata.rs index fc04434d..a5d37423 100644 --- a/src/network/message_blockdata.rs +++ b/src/network/message_blockdata.rs @@ -128,8 +128,8 @@ impl GetBlocksMessage { pub fn new(locator_hashes: Vec, stop_hash: BlockHash) -> GetBlocksMessage { GetBlocksMessage { version: constants::PROTOCOL_VERSION, - locator_hashes: locator_hashes, - stop_hash: stop_hash + locator_hashes, + stop_hash, } } } @@ -141,8 +141,8 @@ impl GetHeadersMessage { pub fn new(locator_hashes: Vec, stop_hash: BlockHash) -> GetHeadersMessage { GetHeadersMessage { version: constants::PROTOCOL_VERSION, - locator_hashes: locator_hashes, - stop_hash: stop_hash + locator_hashes, + stop_hash, } } } diff --git a/src/network/message_network.rs b/src/network/message_network.rs index e568bb71..4422ad0c 100644 --- a/src/network/message_network.rs +++ b/src/network/message_network.rs @@ -69,13 +69,13 @@ impl VersionMessage { ) -> VersionMessage { VersionMessage { version: constants::PROTOCOL_VERSION, - services: services, - timestamp: timestamp, - receiver: receiver, - sender: sender, - nonce: nonce, - user_agent: user_agent, - start_height: start_height, + services, + timestamp, + receiver, + sender, + nonce, + user_agent, + start_height, relay: false, } } diff --git a/src/util/address.rs b/src/util/address.rs index 3d01a2c3..f538e4f8 100644 --- a/src/util/address.rs +++ b/src/util/address.rs @@ -236,7 +236,7 @@ impl FromStr for WitnessVersion { type Err = Error; fn from_str(s: &str) -> Result { - let version = s.parse().map_err(|err| Error::UnparsableWitnessVersion(err))?; + let version = s.parse().map_err(Error::UnparsableWitnessVersion)?; WitnessVersion::from_num(version) } } @@ -282,7 +282,7 @@ impl WitnessVersion { 14 => WitnessVersion::V14, 15 => WitnessVersion::V15, 16 => WitnessVersion::V16, - wrong => Err(Error::InvalidWitnessVersion(wrong))?, + wrong => return Err(Error::InvalidWitnessVersion(wrong)), }) } @@ -315,7 +315,7 @@ impl WitnessVersion { pub fn from_instruction(instruction: Instruction) -> Result { match instruction { Instruction::Op(op) => WitnessVersion::from_opcode(op), - Instruction::PushBytes(bytes) if bytes.len() == 0 => Ok(WitnessVersion::V0), + Instruction::PushBytes(bytes) if bytes.is_empty() => Ok(WitnessVersion::V0), Instruction::PushBytes(_) => Err(Error::MalformedWitnessVersion), } } @@ -545,7 +545,7 @@ impl Address { #[inline] pub fn p2pkh(pk: &ecdsa::PublicKey, network: Network) -> Address { Address { - network: network, + network, payload: Payload::p2pkh(pk), } } @@ -557,7 +557,7 @@ impl Address { #[inline] pub fn p2sh(script: &script::Script, network: Network) -> Result { Ok(Address { - network: network, + network, payload: Payload::p2sh(script)?, }) } @@ -570,7 +570,7 @@ impl Address { /// Will only return an error if an uncompressed public key is provided. pub fn p2wpkh(pk: &ecdsa::PublicKey, network: Network) -> Result { Ok(Address { - network: network, + network, payload: Payload::p2wpkh(pk)?, }) } @@ -583,7 +583,7 @@ impl Address { /// Will only return an Error if an uncompressed public key is provided. pub fn p2shwpkh(pk: &ecdsa::PublicKey, network: Network) -> Result { Ok(Address { - network: network, + network, payload: Payload::p2shwpkh(pk)?, }) } @@ -591,7 +591,7 @@ impl Address { /// Creates a witness pay to script hash address. pub fn p2wsh(script: &script::Script, network: Network) -> Address { Address { - network: network, + network, payload: Payload::p2wsh(script), } } @@ -601,7 +601,7 @@ impl Address { /// This is a segwit address type that looks familiar (as p2sh) to legacy clients. pub fn p2shwsh(script: &script::Script, network: Network) -> Address { Address { - network: network, + network, payload: Payload::p2shwsh(script), } } @@ -627,7 +627,7 @@ impl Address { network: Network ) -> Address { Address { - network: network, + network, payload: Payload::p2tr_tweaked(output_key), } } @@ -670,7 +670,7 @@ impl Address { pub fn from_script(script: &script::Script, network: Network) -> Option
{ Some(Address { payload: Payload::from_script(script)?, - network: network, + network, }) } @@ -821,10 +821,10 @@ impl FromStr for Address { return Ok(Address { payload: Payload::WitnessProgram { - version: version, - program: program, + version, + program, }, - network: network, + network, }); } @@ -858,15 +858,15 @@ impl FromStr for Address { }; Ok(Address { - network: network, - payload: payload, + network, + payload, }) } } impl fmt::Debug for Address { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_string()) + fmt::Display::fmt(self, f) } } diff --git a/src/util/amount.rs b/src/util/amount.rs index c4f94558..fd59526e 100644 --- a/src/util/amount.rs +++ b/src/util/amount.rs @@ -325,7 +325,7 @@ impl Amount { return Err(ParseAmountError::InvalidFormat); } - Ok(Amount::from_str_in(amt_str, denom_str.parse()?)?) + Amount::from_str_in(amt_str, denom_str.parse()?) } /// Express this [Amount] as a floating-point value in the given denomination. @@ -612,7 +612,7 @@ impl SignedAmount { return Err(ParseAmountError::InvalidFormat); } - Ok(SignedAmount::from_str_in(amt_str, denom_str.parse()?)?) + SignedAmount::from_str_in(amt_str, denom_str.parse()?) } /// Express this [SignedAmount] as a floating-point value in the given denomination. diff --git a/src/util/base58.rs b/src/util/base58.rs index 94c4069e..51206200 100644 --- a/src/util/base58.rs +++ b/src/util/base58.rs @@ -231,7 +231,7 @@ pub fn encode_slice(data: &[u8]) -> String { /// Obtain a string with the base58check encoding of a slice /// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.) pub fn check_encode_slice(data: &[u8]) -> String { - let checksum = sha256d::Hash::hash(&data); + let checksum = sha256d::Hash::hash(data); encode_iter( data.iter() .cloned() @@ -242,7 +242,7 @@ pub fn check_encode_slice(data: &[u8]) -> String { /// Obtain a string with the base58check encoding of a slice /// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.) pub fn check_encode_slice_to_fmt(fmt: &mut fmt::Formatter, data: &[u8]) -> fmt::Result { - let checksum = sha256d::Hash::hash(&data); + let checksum = sha256d::Hash::hash(data); let iter = data.iter() .cloned() .chain(checksum[0..4].iter().cloned()); diff --git a/src/util/bip143.rs b/src/util/bip143.rs index a00da490..b3e284fa 100644 --- a/src/util/bip143.rs +++ b/src/util/bip143.rs @@ -80,9 +80,9 @@ impl SighashComponents { SighashComponents { tx_version: tx.version, tx_locktime: tx.lock_time, - hash_prevouts: hash_prevouts, - hash_sequence: hash_sequence, - hash_outputs: hash_outputs, + hash_prevouts, + hash_sequence, + hash_outputs, } } @@ -134,7 +134,7 @@ impl> SigHashCache { sighash_type: EcdsaSigHashType, ) -> Result<(), encode::Error> { self.cache - .segwit_encode_signing_data_to(writer, input_index, script_code, value, sighash_type.into()) + .segwit_encode_signing_data_to(writer, input_index, script_code, value, sighash_type) .expect("input_index greater than tx input len"); Ok(()) } diff --git a/src/util/bip158.rs b/src/util/bip158.rs index 4e117971..8af9e723 100644 --- a/src/util/bip158.rs +++ b/src/util/bip158.rs @@ -250,7 +250,7 @@ impl GCSFilterReader { let nm = n_elements.0 * self.m; let mut mapped = query.map(|e| map_to_range(self.filter.hash(e), nm)).collect::>(); // sort - mapped.sort(); + mapped.sort_unstable(); if mapped.is_empty() { return Ok(true); } @@ -290,7 +290,7 @@ impl GCSFilterReader { let nm = n_elements.0 * self.m; let mut mapped = query.map(|e| map_to_range(self.filter.hash(e), nm)).collect::>(); // sort - mapped.sort(); + mapped.sort_unstable(); mapped.dedup(); if mapped.is_empty() { return Ok(true); @@ -361,7 +361,7 @@ impl<'a> GCSFilterWriter<'a> { // map hashes to [0, n_elements * M) let mut mapped: Vec<_> = self.elements.iter() .map(|e| map_to_range(self.filter.hash(e.as_slice()), nm)).collect(); - mapped.sort(); + mapped.sort_unstable(); // write number of elements as varint let mut encoder = Vec::new(); @@ -435,7 +435,7 @@ impl<'a> BitStreamReader<'a> { pub fn new(reader: &'a mut dyn io::Read) -> BitStreamReader { BitStreamReader { buffer: [0u8], - reader: reader, + reader, offset: 8, } } @@ -473,7 +473,7 @@ impl<'a> BitStreamWriter<'a> { pub fn new(writer: &'a mut dyn io::Write) -> BitStreamWriter { BitStreamWriter { buffer: [0u8], - writer: writer, + writer, offset: 0, } } diff --git a/src/util/bip32.rs b/src/util/bip32.rs index a2ec9668..9675a3cf 100644 --- a/src/util/bip32.rs +++ b/src/util/bip32.rs @@ -38,15 +38,11 @@ impl_array_newtype!(ChainCode, u8, 32); impl_bytes_newtype!(ChainCode, 32); /// A fingerprint -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Fingerprint([u8; 4]); impl_array_newtype!(Fingerprint, u8, 4); impl_bytes_newtype!(Fingerprint, 4); -impl Default for Fingerprint { - fn default() -> Fingerprint { Fingerprint([0; 4]) } -} - /// Extended private key #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct ExtendedPrivKey { @@ -105,7 +101,7 @@ impl ChildNumber { /// [`Normal`]: #variant.Normal pub fn from_normal_idx(index: u32) -> Result { if index & (1 << 31) == 0 { - Ok(ChildNumber::Normal { index: index }) + Ok(ChildNumber::Normal { index }) } else { Err(Error::InvalidChildNumber(index)) } @@ -117,7 +113,7 @@ impl ChildNumber { /// [`Hardened`]: #variant.Hardened pub fn from_hardened_idx(index: u32) -> Result { if index & (1 << 31) == 0 { - Ok(ChildNumber::Hardened { index: index }) + Ok(ChildNumber::Hardened { index }) } else { Err(Error::InvalidChildNumber(index)) } @@ -341,6 +337,11 @@ impl DerivationPath { self.0.len() } + /// Returns `true` if the derivation path is empty + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + /// Returns derivation path for a master key (i.e. empty derivation path) pub fn master() -> DerivationPath { DerivationPath(vec![]) @@ -369,17 +370,17 @@ impl DerivationPath { /// Get an [Iterator] over the children of this [DerivationPath] /// starting with the given [ChildNumber]. pub fn children_from(&self, cn: ChildNumber) -> DerivationPathIterator { - DerivationPathIterator::start_from(&self, cn) + DerivationPathIterator::start_from(self, cn) } /// Get an [Iterator] over the unhardened children of this [DerivationPath]. pub fn normal_children(&self) -> DerivationPathIterator { - DerivationPathIterator::start_from(&self, ChildNumber::Normal{ index: 0 }) + DerivationPathIterator::start_from(self, ChildNumber::Normal{ index: 0 }) } /// Get an [Iterator] over the hardened children of this [DerivationPath]. pub fn hardened_children(&self) -> DerivationPathIterator { - DerivationPathIterator::start_from(&self, ChildNumber::Hardened{ index: 0 }) + DerivationPathIterator::start_from(self, ChildNumber::Hardened{ index: 0 }) } /// Concatenate `self` with `path` and return the resulting new path. @@ -501,7 +502,7 @@ impl ExtendedPrivKey { let hmac_result: Hmac = Hmac::from_engine(hmac_engine); Ok(ExtendedPrivKey { - network: network, + network, depth: 0, parent_fingerprint: Default::default(), child_number: ChildNumber::from_normal_idx(0)?, @@ -572,7 +573,7 @@ impl ExtendedPrivKey { }; Ok(ExtendedPrivKey { - network: network, + network, depth: data[4], parent_fingerprint: Fingerprint::from(&data[5..9]), child_number: endian::slice_to_u32_be(&data[9..13]).into(), @@ -672,7 +673,7 @@ impl ExtendedPubKey { parent_fingerprint: self.fingerprint(), child_number: i, public_key: pk, - chain_code: chain_code + chain_code, }) } @@ -744,7 +745,7 @@ impl FromStr for ExtendedPrivKey { return Err(base58::Error::InvalidLength(data.len()).into()); } - Ok(ExtendedPrivKey::decode(&data[..])?) + ExtendedPrivKey::decode(&data) } } @@ -764,7 +765,7 @@ impl FromStr for ExtendedPubKey { return Err(base58::Error::InvalidLength(data.len()).into()); } - Ok(ExtendedPubKey::decode(&data[..])?) + ExtendedPubKey::decode(&data) } } diff --git a/src/util/contracthash.rs b/src/util/contracthash.rs index a8e513f0..c08e9b57 100644 --- a/src/util/contracthash.rs +++ b/src/util/contracthash.rs @@ -183,7 +183,7 @@ pub fn compute_tweak(pk: &PublicKey, contract: &[u8]) -> Hmac { /// Tweak a secret key using some arbitrary data (calls `compute_tweak` internally) pub fn tweak_secret_key(secp: &Secp256k1, key: &PrivateKey, contract: &[u8]) -> Result { // Compute public key - let pk = PublicKey::from_private_key(secp, &key); + let pk = PublicKey::from_private_key(secp, key); // Compute tweak let hmac_sk = compute_tweak(&pk, contract); // Execute the tweak @@ -203,7 +203,7 @@ pub fn create_address(secp: &Secp256k1, let keys = tweak_keys(secp, keys, contract); let script = template.to_script(&keys)?; Ok(address::Address { - network: network, + network, payload: address::Payload::ScriptHash( ScriptHash::hash(&script[..]) ) diff --git a/src/util/ecdsa.rs b/src/util/ecdsa.rs index f1333225..54556a23 100644 --- a/src/util/ecdsa.rs +++ b/src/util/ecdsa.rs @@ -46,7 +46,7 @@ impl PublicKey { pub fn new(key: secp256k1::PublicKey) -> PublicKey { PublicKey { compressed: true, - key: key, + key, } } @@ -55,7 +55,7 @@ impl PublicKey { pub fn new_uncompressed(key: secp256k1::PublicKey) -> PublicKey { PublicKey { compressed: false, - key: key, + key, } } @@ -134,7 +134,7 @@ impl PublicKey { }; Ok(PublicKey { - compressed: compressed, + compressed, key: secp256k1::PublicKey::from_slice(data)?, }) } @@ -165,7 +165,7 @@ impl FromStr for PublicKey { fn from_str(s: &str) -> Result { let key = secp256k1::PublicKey::from_str(s)?; Ok(PublicKey { - key: key, + key, compressed: s.len() == 66 }) } @@ -188,8 +188,8 @@ impl PrivateKey { pub fn new(key: secp256k1::SecretKey, network: Network) -> PrivateKey { PrivateKey { compressed: true, - network: network, - key: key, + network, + key, } } @@ -198,8 +198,8 @@ impl PrivateKey { pub fn new_uncompressed(key: secp256k1::SecretKey, network: Network) -> PrivateKey { PrivateKey { compressed: false, - network: network, - key: key, + network, + key, } } @@ -266,8 +266,8 @@ impl PrivateKey { }; Ok(PrivateKey { - compressed: compressed, - network: network, + compressed, + network, key: secp256k1::SecretKey::from_slice(&data[1..33])?, }) } diff --git a/src/util/merkleblock.rs b/src/util/merkleblock.rs index 2029347c..7931862c 100644 --- a/src/util/merkleblock.rs +++ b/src/util/merkleblock.rs @@ -459,7 +459,7 @@ impl MerkleBlock { .map(match_txids) .collect(); - let pmt = PartialMerkleTree::from_txids(&block_txids, &matches); + let pmt = PartialMerkleTree::from_txids(block_txids, &matches); MerkleBlock { header: *header, txn: pmt, diff --git a/src/util/misc.rs b/src/util/misc.rs index 98a972e3..e9322eed 100644 --- a/src/util/misc.rs +++ b/src/util/misc.rs @@ -103,8 +103,8 @@ mod message_signing { /// Create a new [MessageSignature]. pub fn new(signature: RecoverableSignature, compressed: bool) -> MessageSignature { MessageSignature { - signature: signature, - compressed: compressed, + signature, + compressed, } } @@ -162,7 +162,7 @@ mod message_signing { address: &Address, msg_hash: sha256d::Hash ) -> Result { - let pubkey = self.recover_pubkey(&secp_ctx, msg_hash)?; + let pubkey = self.recover_pubkey(secp_ctx, msg_hash)?; Ok(match address.address_type() { Some(AddressType::P2pkh) => { *address == Address::p2pkh(&pubkey, address.network) diff --git a/src/util/mod.rs b/src/util/mod.rs index d3aa5d80..e111f495 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -125,7 +125,7 @@ pub(crate) fn read_to_end(mut d: D) -> Result, io::Error> { Ok(0) => break, Ok(n) => result.extend_from_slice(&buf[0..n]), Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}, - Err(e) => return Err(e.into()), + Err(e) => return Err(e), }; } Ok(result) diff --git a/src/util/psbt/map/global.rs b/src/util/psbt/map/global.rs index b772009a..52443686 100644 --- a/src/util/psbt/map/global.rs +++ b/src/util/psbt/map/global.rs @@ -155,13 +155,8 @@ impl Map for PartiallySignedTransaction { let (fingerprint2, derivation2) = entry.get().clone(); - if derivation1 == derivation2 && fingerprint1 == fingerprint2 - { - continue - } - else if - derivation1.len() < derivation2.len() && - derivation1[..] == derivation2[derivation2.len() - derivation1.len()..] + if (derivation1 == derivation2 && fingerprint1 == fingerprint2) || + (derivation1.len() < derivation2.len() && derivation1[..] == derivation2[derivation2.len() - derivation1.len()..]) { continue } diff --git a/src/util/psbt/map/input.rs b/src/util/psbt/map/input.rs index 2eca6d0c..e6481b4e 100644 --- a/src/util/psbt/map/input.rs +++ b/src/util/psbt/map/input.rs @@ -314,13 +314,13 @@ where return Err(psbt::Error::InvalidPreimageHashPair { preimage: val.into_boxed_slice(), hash: Box::from(key_val.borrow()), - hash_type: hash_type, + hash_type, } .into()); } empty_key.insert(val); Ok(()) } - btree_map::Entry::Occupied(_) => return Err(psbt::Error::DuplicateKey(raw_key).into()), + btree_map::Entry::Occupied(_) => Err(psbt::Error::DuplicateKey(raw_key).into()), } } diff --git a/src/util/psbt/map/output.rs b/src/util/psbt/map/output.rs index 96978ab4..119f8c61 100644 --- a/src/util/psbt/map/output.rs +++ b/src/util/psbt/map/output.rs @@ -80,7 +80,7 @@ impl Map for Output { } PSBT_OUT_PROPRIETARY => match self.proprietary.entry(raw::ProprietaryKey::from_key(raw_key.clone())?) { btree_map::Entry::Vacant(empty_key) => {empty_key.insert(raw_value);}, - btree_map::Entry::Occupied(_) => return Err(Error::DuplicateKey(raw_key.clone()).into()), + btree_map::Entry::Occupied(_) => return Err(Error::DuplicateKey(raw_key).into()), } _ => match self.unknown.entry(raw_key) { btree_map::Entry::Vacant(empty_key) => {empty_key.insert(raw_value);}, diff --git a/src/util/psbt/raw.rs b/src/util/psbt/raw.rs index 1a4f1fa1..3f9a8563 100644 --- a/src/util/psbt/raw.rs +++ b/src/util/psbt/raw.rs @@ -100,8 +100,8 @@ impl Decodable for Key { } Ok(Key { - type_value: type_value, - key: key, + type_value, + key, }) } } diff --git a/src/util/sighash.rs b/src/util/sighash.rs index 02a3286e..10e333ee 100644 --- a/src/util/sighash.rs +++ b/src/util/sighash.rs @@ -693,7 +693,7 @@ impl<'a> Annex<'a> { impl<'a> Encodable for Annex<'a> { fn consensus_encode(&self, writer: W) -> Result { - encode::consensus_encode_with_size(&self.0, writer) + encode::consensus_encode_with_size(self.0, writer) } }