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.
This commit is contained in:
Martin Habovstiak 2021-11-03 10:20:34 +01:00
parent fe43e3c9d7
commit 779d4110c6
26 changed files with 154 additions and 121 deletions

1
clippy.toml Normal file
View File

@ -0,0 +1 @@
msrv = "1.29"

View File

@ -291,7 +291,7 @@ impl Block {
script::Instruction::PushBytes(b) if b.len() <= 8 => { script::Instruction::PushBytes(b) if b.len() <= 8 => {
// Expand the push to exactly 8 bytes (LE). // Expand the push to exactly 8 bytes (LE).
let mut full = [0; 8]; 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)) Ok(util::endian::slice_to_u64_le(&full))
} }
script::Instruction::PushBytes(b) if b.len() > 8 => { script::Instruction::PushBytes(b) if b.len() > 8 => {

View File

@ -129,7 +129,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x1d00ffff, bits: 0x1d00ffff,
nonce: 2083236893 nonce: 2083236893
}, },
txdata: txdata txdata,
} }
} }
Network::Testnet => { Network::Testnet => {
@ -142,7 +142,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x1d00ffff, bits: 0x1d00ffff,
nonce: 414098458 nonce: 414098458
}, },
txdata: txdata txdata,
} }
} }
Network::Signet => { Network::Signet => {
@ -155,7 +155,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x1e0377ae, bits: 0x1e0377ae,
nonce: 52613770 nonce: 52613770
}, },
txdata: txdata txdata,
} }
} }
Network::Regtest => { Network::Regtest => {
@ -168,7 +168,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x207fffff, bits: 0x207fffff,
nonce: 2 nonce: 2
}, },
txdata: txdata txdata,
} }
} }
} }

View File

@ -325,7 +325,7 @@ impl Script {
pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Script { pub fn new_witness_program(version: WitnessVersion, program: &[u8]) -> Script {
Builder::new() Builder::new()
.push_opcode(version.into()) .push_opcode(version.into())
.push_slice(&program) .push_slice(program)
.into_script() .into_script()
} }
@ -339,12 +339,12 @@ impl Script {
/// Returns 160-bit hash of the script /// Returns 160-bit hash of the script
pub fn script_hash(&self) -> ScriptHash { 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 /// Returns 256-bit hash of the script for P2WSH outputs
pub fn wscript_hash(&self) -> WScriptHash { pub fn wscript_hash(&self) -> WScriptHash {
WScriptHash::hash(&self.as_bytes()) WScriptHash::hash(self.as_bytes())
} }
/// The length in bytes of the script /// The length in bytes of the script

View File

@ -56,8 +56,8 @@ impl OutPoint {
#[inline] #[inline]
pub fn new(txid: Txid, vout: u32) -> OutPoint { pub fn new(txid: Txid, vout: u32) -> OutPoint {
OutPoint { OutPoint {
txid: txid, txid,
vout: vout, vout,
} }
} }
@ -153,7 +153,7 @@ fn parse_vout(s: &str) -> Result<u32, ParseOutPointError> {
return Err(ParseOutPointError::VoutNotCanonical); return Err(ParseOutPointError::VoutNotCanonical);
} }
} }
Ok(s.parse().map_err(ParseOutPointError::Vout)?) s.parse().map_err(ParseOutPointError::Vout)
} }
impl ::core::str::FromStr for OutPoint { 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")) Err(encode::Error::ParseFailed("witness flag set but no witnesses present"))
} else { } else {
Ok(Transaction { Ok(Transaction {
version: version, version,
input: input, input,
output: output, output,
lock_time: Decodable::consensus_decode(d)?, lock_time: Decodable::consensus_decode(d)?,
}) })
} }
@ -649,8 +649,8 @@ impl Decodable for Transaction {
// non-segwit // non-segwit
} else { } else {
Ok(Transaction { Ok(Transaction {
version: version, version,
input: input, input,
output: Decodable::consensus_decode(&mut d)?, output: Decodable::consensus_decode(&mut d)?,
lock_time: Decodable::consensus_decode(d)?, lock_time: Decodable::consensus_decode(d)?,
}) })
@ -715,17 +715,17 @@ impl fmt::Display for EcdsaSigHashType {
} }
impl str::FromStr for EcdsaSigHashType { impl str::FromStr for EcdsaSigHashType {
type Err = String; type Err = SigHashTypeParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.as_ref() { match s {
"SIGHASH_ALL" => Ok(EcdsaSigHashType::All), "SIGHASH_ALL" => Ok(EcdsaSigHashType::All),
"SIGHASH_NONE" => Ok(EcdsaSigHashType::None), "SIGHASH_NONE" => Ok(EcdsaSigHashType::None),
"SIGHASH_SINGLE" => Ok(EcdsaSigHashType::Single), "SIGHASH_SINGLE" => Ok(EcdsaSigHashType::Single),
"SIGHASH_ALL|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::AllPlusAnyoneCanPay), "SIGHASH_ALL|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::AllPlusAnyoneCanPay),
"SIGHASH_NONE|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::NonePlusAnyoneCanPay), "SIGHASH_NONE|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::NonePlusAnyoneCanPay),
"SIGHASH_SINGLE|SIGHASH_ANYONECANPAY" => Ok(EcdsaSigHashType::SinglePlusAnyoneCanPay), "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<EcdsaSigHashType> 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)] #[cfg(test)]
mod tests { mod tests {
use super::{OutPoint, ParseOutPointError, Transaction, TxIn, NonStandardSigHashType}; use super::{OutPoint, ParseOutPointError, Transaction, TxIn, NonStandardSigHashType};
@ -1116,7 +1134,7 @@ mod tests {
"SigHash_NONE", "SigHash_NONE",
]; ];
for s in sht_mistakes { 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));
} }
} }

View File

@ -461,7 +461,7 @@ impl Encodable for String {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
let b = self.as_bytes(); let b = self.as_bytes();
let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?; 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()) Ok(vi_len + b.len())
} }
} }
@ -480,7 +480,7 @@ impl Encodable for Cow<'static, str> {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
let b = self.as_bytes(); let b = self.as_bytes();
let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?; 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()) Ok(vi_len + b.len())
} }
} }
@ -601,7 +601,7 @@ impl_vec!(u64);
pub(crate) fn consensus_encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize, io::Error> { pub(crate) fn consensus_encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize, io::Error> {
let vi_len = VarInt(data.len() as u64).consensus_encode(&mut s)?; 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()) Ok(vi_len + data.len())
} }

View File

@ -47,7 +47,7 @@ impl Address {
SocketAddr::V4(addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()), SocketAddr::V4(addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
SocketAddr::V6(addr) => (addr.ip().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. /// Extract socket address from an [Address] message.
@ -73,9 +73,9 @@ impl Address {
fn addr_to_be(addr: [u16; 8]) -> [u16; 8] { fn addr_to_be(addr: [u16; 8]) -> [u16; 8] {
// consensus_encode always encodes in LE, and we want to encode in BE. // 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 // this utility fn swap bytes before encoding so that the encoded result will be BE
let mut result = addr.clone(); let mut result = addr;
for i in 0..8 { for word in &mut result {
result[i] = result[i].swap_bytes(); *word = word.swap_bytes();
} }
result result
} }
@ -266,7 +266,7 @@ impl AddrV2Message {
match self.addr { match self.addr {
AddrV2::Ipv4(addr) => Ok(SocketAddr::V4(SocketAddrV4::new(addr, self.port))), AddrV2::Ipv4(addr) => Ok(SocketAddr::V4(SocketAddrV4::new(addr, self.port))),
AddrV2::Ipv6(addr) => Ok(SocketAddr::V6(SocketAddrV6::new(addr, self.port, 0, 0))), 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)),
} }
} }
} }

View File

@ -49,12 +49,12 @@ impl CommandString {
/// - `&'static str` /// - `&'static str`
/// - `String` /// - `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. /// larger than 12 characters in length.
pub fn try_from<S: Into<Cow<'static, str>>>(s: S) -> Result<CommandString, ()> { pub fn try_from<S: Into<Cow<'static, str>>>(s: S) -> Result<CommandString, CommandStringError> {
let cow = s.into(); let cow = s.into();
if cow.as_ref().len() > 12 { if cow.len() > 12 {
Err(()) Err(CommandStringError { cow })
} else { } else {
Ok(CommandString(cow)) Ok(CommandString(cow))
} }
@ -82,7 +82,7 @@ impl Encodable for CommandString {
let mut rawbytes = [0u8; 12]; let mut rawbytes = [0u8; 12];
let strbytes = self.0.as_bytes(); let strbytes = self.0.as_bytes();
debug_assert!(strbytes.len() <= 12); debug_assert!(strbytes.len() <= 12);
rawbytes[..strbytes.len()].clone_from_slice(&strbytes[..]); rawbytes[..strbytes.len()].copy_from_slice(strbytes);
rawbytes.consensus_encode(s) 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)] #[derive(Clone, Debug, PartialEq, Eq)]
/// A Network message /// A Network message
pub struct RawNetworkMessage { pub struct RawNetworkMessage {
@ -395,8 +413,8 @@ impl Decodable for RawNetworkMessage {
} }
}; };
Ok(RawNetworkMessage { Ok(RawNetworkMessage {
magic: magic, magic,
payload: payload payload,
}) })
} }
} }

View File

@ -128,8 +128,8 @@ impl GetBlocksMessage {
pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetBlocksMessage { pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetBlocksMessage {
GetBlocksMessage { GetBlocksMessage {
version: constants::PROTOCOL_VERSION, version: constants::PROTOCOL_VERSION,
locator_hashes: locator_hashes, locator_hashes,
stop_hash: stop_hash stop_hash,
} }
} }
} }
@ -141,8 +141,8 @@ impl GetHeadersMessage {
pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetHeadersMessage { pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetHeadersMessage {
GetHeadersMessage { GetHeadersMessage {
version: constants::PROTOCOL_VERSION, version: constants::PROTOCOL_VERSION,
locator_hashes: locator_hashes, locator_hashes,
stop_hash: stop_hash stop_hash,
} }
} }
} }

View File

@ -69,13 +69,13 @@ impl VersionMessage {
) -> VersionMessage { ) -> VersionMessage {
VersionMessage { VersionMessage {
version: constants::PROTOCOL_VERSION, version: constants::PROTOCOL_VERSION,
services: services, services,
timestamp: timestamp, timestamp,
receiver: receiver, receiver,
sender: sender, sender,
nonce: nonce, nonce,
user_agent: user_agent, user_agent,
start_height: start_height, start_height,
relay: false, relay: false,
} }
} }

View File

@ -236,7 +236,7 @@ impl FromStr for WitnessVersion {
type Err = Error; type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let version = s.parse().map_err(|err| Error::UnparsableWitnessVersion(err))?; let version = s.parse().map_err(Error::UnparsableWitnessVersion)?;
WitnessVersion::from_num(version) WitnessVersion::from_num(version)
} }
} }
@ -282,7 +282,7 @@ impl WitnessVersion {
14 => WitnessVersion::V14, 14 => WitnessVersion::V14,
15 => WitnessVersion::V15, 15 => WitnessVersion::V15,
16 => WitnessVersion::V16, 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<Self, Error> { pub fn from_instruction(instruction: Instruction) -> Result<Self, Error> {
match instruction { match instruction {
Instruction::Op(op) => WitnessVersion::from_opcode(op), 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), Instruction::PushBytes(_) => Err(Error::MalformedWitnessVersion),
} }
} }
@ -545,7 +545,7 @@ impl Address {
#[inline] #[inline]
pub fn p2pkh(pk: &ecdsa::PublicKey, network: Network) -> Address { pub fn p2pkh(pk: &ecdsa::PublicKey, network: Network) -> Address {
Address { Address {
network: network, network,
payload: Payload::p2pkh(pk), payload: Payload::p2pkh(pk),
} }
} }
@ -557,7 +557,7 @@ impl Address {
#[inline] #[inline]
pub fn p2sh(script: &script::Script, network: Network) -> Result<Address, Error> { pub fn p2sh(script: &script::Script, network: Network) -> Result<Address, Error> {
Ok(Address { Ok(Address {
network: network, network,
payload: Payload::p2sh(script)?, payload: Payload::p2sh(script)?,
}) })
} }
@ -570,7 +570,7 @@ impl Address {
/// Will only return an error if an uncompressed public key is provided. /// Will only return an error if an uncompressed public key is provided.
pub fn p2wpkh(pk: &ecdsa::PublicKey, network: Network) -> Result<Address, Error> { pub fn p2wpkh(pk: &ecdsa::PublicKey, network: Network) -> Result<Address, Error> {
Ok(Address { Ok(Address {
network: network, network,
payload: Payload::p2wpkh(pk)?, payload: Payload::p2wpkh(pk)?,
}) })
} }
@ -583,7 +583,7 @@ impl Address {
/// Will only return an Error if an uncompressed public key is provided. /// Will only return an Error if an uncompressed public key is provided.
pub fn p2shwpkh(pk: &ecdsa::PublicKey, network: Network) -> Result<Address, Error> { pub fn p2shwpkh(pk: &ecdsa::PublicKey, network: Network) -> Result<Address, Error> {
Ok(Address { Ok(Address {
network: network, network,
payload: Payload::p2shwpkh(pk)?, payload: Payload::p2shwpkh(pk)?,
}) })
} }
@ -591,7 +591,7 @@ impl Address {
/// Creates a witness pay to script hash address. /// Creates a witness pay to script hash address.
pub fn p2wsh(script: &script::Script, network: Network) -> Address { pub fn p2wsh(script: &script::Script, network: Network) -> Address {
Address { Address {
network: network, network,
payload: Payload::p2wsh(script), payload: Payload::p2wsh(script),
} }
} }
@ -601,7 +601,7 @@ impl Address {
/// This is a segwit address type that looks familiar (as p2sh) to legacy clients. /// This is a segwit address type that looks familiar (as p2sh) to legacy clients.
pub fn p2shwsh(script: &script::Script, network: Network) -> Address { pub fn p2shwsh(script: &script::Script, network: Network) -> Address {
Address { Address {
network: network, network,
payload: Payload::p2shwsh(script), payload: Payload::p2shwsh(script),
} }
} }
@ -627,7 +627,7 @@ impl Address {
network: Network network: Network
) -> Address { ) -> Address {
Address { Address {
network: network, network,
payload: Payload::p2tr_tweaked(output_key), payload: Payload::p2tr_tweaked(output_key),
} }
} }
@ -670,7 +670,7 @@ impl Address {
pub fn from_script(script: &script::Script, network: Network) -> Option<Address> { pub fn from_script(script: &script::Script, network: Network) -> Option<Address> {
Some(Address { Some(Address {
payload: Payload::from_script(script)?, payload: Payload::from_script(script)?,
network: network, network,
}) })
} }
@ -821,10 +821,10 @@ impl FromStr for Address {
return Ok(Address { return Ok(Address {
payload: Payload::WitnessProgram { payload: Payload::WitnessProgram {
version: version, version,
program: program, program,
}, },
network: network, network,
}); });
} }
@ -858,15 +858,15 @@ impl FromStr for Address {
}; };
Ok(Address { Ok(Address {
network: network, network,
payload: payload, payload,
}) })
} }
} }
impl fmt::Debug for Address { impl fmt::Debug for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string()) fmt::Display::fmt(self, f)
} }
} }

View File

@ -325,7 +325,7 @@ impl Amount {
return Err(ParseAmountError::InvalidFormat); 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. /// Express this [Amount] as a floating-point value in the given denomination.
@ -612,7 +612,7 @@ impl SignedAmount {
return Err(ParseAmountError::InvalidFormat); 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. /// Express this [SignedAmount] as a floating-point value in the given denomination.

View File

@ -231,7 +231,7 @@ pub fn encode_slice(data: &[u8]) -> String {
/// Obtain a string with the base58check encoding of a slice /// 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.) /// (Tack the first 4 256-digits of the object's Bitcoin hash onto the end.)
pub fn check_encode_slice(data: &[u8]) -> String { pub fn check_encode_slice(data: &[u8]) -> String {
let checksum = sha256d::Hash::hash(&data); let checksum = sha256d::Hash::hash(data);
encode_iter( encode_iter(
data.iter() data.iter()
.cloned() .cloned()
@ -242,7 +242,7 @@ pub fn check_encode_slice(data: &[u8]) -> String {
/// Obtain a string with the base58check encoding of a slice /// 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.) /// (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 { 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() let iter = data.iter()
.cloned() .cloned()
.chain(checksum[0..4].iter().cloned()); .chain(checksum[0..4].iter().cloned());

View File

@ -80,9 +80,9 @@ impl SighashComponents {
SighashComponents { SighashComponents {
tx_version: tx.version, tx_version: tx.version,
tx_locktime: tx.lock_time, tx_locktime: tx.lock_time,
hash_prevouts: hash_prevouts, hash_prevouts,
hash_sequence: hash_sequence, hash_sequence,
hash_outputs: hash_outputs, hash_outputs,
} }
} }
@ -134,7 +134,7 @@ impl<R: Deref<Target=Transaction>> SigHashCache<R> {
sighash_type: EcdsaSigHashType, sighash_type: EcdsaSigHashType,
) -> Result<(), encode::Error> { ) -> Result<(), encode::Error> {
self.cache 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"); .expect("input_index greater than tx input len");
Ok(()) Ok(())
} }

View File

@ -250,7 +250,7 @@ impl GCSFilterReader {
let nm = n_elements.0 * self.m; let nm = n_elements.0 * self.m;
let mut mapped = query.map(|e| map_to_range(self.filter.hash(e), nm)).collect::<Vec<_>>(); let mut mapped = query.map(|e| map_to_range(self.filter.hash(e), nm)).collect::<Vec<_>>();
// sort // sort
mapped.sort(); mapped.sort_unstable();
if mapped.is_empty() { if mapped.is_empty() {
return Ok(true); return Ok(true);
} }
@ -290,7 +290,7 @@ impl GCSFilterReader {
let nm = n_elements.0 * self.m; let nm = n_elements.0 * self.m;
let mut mapped = query.map(|e| map_to_range(self.filter.hash(e), nm)).collect::<Vec<_>>(); let mut mapped = query.map(|e| map_to_range(self.filter.hash(e), nm)).collect::<Vec<_>>();
// sort // sort
mapped.sort(); mapped.sort_unstable();
mapped.dedup(); mapped.dedup();
if mapped.is_empty() { if mapped.is_empty() {
return Ok(true); return Ok(true);
@ -361,7 +361,7 @@ impl<'a> GCSFilterWriter<'a> {
// map hashes to [0, n_elements * M) // map hashes to [0, n_elements * M)
let mut mapped: Vec<_> = self.elements.iter() let mut mapped: Vec<_> = self.elements.iter()
.map(|e| map_to_range(self.filter.hash(e.as_slice()), nm)).collect(); .map(|e| map_to_range(self.filter.hash(e.as_slice()), nm)).collect();
mapped.sort(); mapped.sort_unstable();
// write number of elements as varint // write number of elements as varint
let mut encoder = Vec::new(); let mut encoder = Vec::new();
@ -435,7 +435,7 @@ impl<'a> BitStreamReader<'a> {
pub fn new(reader: &'a mut dyn io::Read) -> BitStreamReader { pub fn new(reader: &'a mut dyn io::Read) -> BitStreamReader {
BitStreamReader { BitStreamReader {
buffer: [0u8], buffer: [0u8],
reader: reader, reader,
offset: 8, offset: 8,
} }
} }
@ -473,7 +473,7 @@ impl<'a> BitStreamWriter<'a> {
pub fn new(writer: &'a mut dyn io::Write) -> BitStreamWriter { pub fn new(writer: &'a mut dyn io::Write) -> BitStreamWriter {
BitStreamWriter { BitStreamWriter {
buffer: [0u8], buffer: [0u8],
writer: writer, writer,
offset: 0, offset: 0,
} }
} }

View File

@ -38,15 +38,11 @@ impl_array_newtype!(ChainCode, u8, 32);
impl_bytes_newtype!(ChainCode, 32); impl_bytes_newtype!(ChainCode, 32);
/// A fingerprint /// A fingerprint
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Fingerprint([u8; 4]); pub struct Fingerprint([u8; 4]);
impl_array_newtype!(Fingerprint, u8, 4); impl_array_newtype!(Fingerprint, u8, 4);
impl_bytes_newtype!(Fingerprint, 4); impl_bytes_newtype!(Fingerprint, 4);
impl Default for Fingerprint {
fn default() -> Fingerprint { Fingerprint([0; 4]) }
}
/// Extended private key /// Extended private key
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct ExtendedPrivKey { pub struct ExtendedPrivKey {
@ -105,7 +101,7 @@ impl ChildNumber {
/// [`Normal`]: #variant.Normal /// [`Normal`]: #variant.Normal
pub fn from_normal_idx(index: u32) -> Result<Self, Error> { pub fn from_normal_idx(index: u32) -> Result<Self, Error> {
if index & (1 << 31) == 0 { if index & (1 << 31) == 0 {
Ok(ChildNumber::Normal { index: index }) Ok(ChildNumber::Normal { index })
} else { } else {
Err(Error::InvalidChildNumber(index)) Err(Error::InvalidChildNumber(index))
} }
@ -117,7 +113,7 @@ impl ChildNumber {
/// [`Hardened`]: #variant.Hardened /// [`Hardened`]: #variant.Hardened
pub fn from_hardened_idx(index: u32) -> Result<Self, Error> { pub fn from_hardened_idx(index: u32) -> Result<Self, Error> {
if index & (1 << 31) == 0 { if index & (1 << 31) == 0 {
Ok(ChildNumber::Hardened { index: index }) Ok(ChildNumber::Hardened { index })
} else { } else {
Err(Error::InvalidChildNumber(index)) Err(Error::InvalidChildNumber(index))
} }
@ -341,6 +337,11 @@ impl DerivationPath {
self.0.len() 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) /// Returns derivation path for a master key (i.e. empty derivation path)
pub fn master() -> DerivationPath { pub fn master() -> DerivationPath {
DerivationPath(vec![]) DerivationPath(vec![])
@ -369,17 +370,17 @@ impl DerivationPath {
/// Get an [Iterator] over the children of this [DerivationPath] /// Get an [Iterator] over the children of this [DerivationPath]
/// starting with the given [ChildNumber]. /// starting with the given [ChildNumber].
pub fn children_from(&self, cn: ChildNumber) -> DerivationPathIterator { 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]. /// Get an [Iterator] over the unhardened children of this [DerivationPath].
pub fn normal_children(&self) -> DerivationPathIterator { 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]. /// Get an [Iterator] over the hardened children of this [DerivationPath].
pub fn hardened_children(&self) -> DerivationPathIterator { 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. /// Concatenate `self` with `path` and return the resulting new path.
@ -501,7 +502,7 @@ impl ExtendedPrivKey {
let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine); let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
Ok(ExtendedPrivKey { Ok(ExtendedPrivKey {
network: network, network,
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)?,
@ -572,7 +573,7 @@ impl ExtendedPrivKey {
}; };
Ok(ExtendedPrivKey { Ok(ExtendedPrivKey {
network: network, network,
depth: data[4], depth: data[4],
parent_fingerprint: Fingerprint::from(&data[5..9]), parent_fingerprint: Fingerprint::from(&data[5..9]),
child_number: endian::slice_to_u32_be(&data[9..13]).into(), child_number: endian::slice_to_u32_be(&data[9..13]).into(),
@ -672,7 +673,7 @@ impl ExtendedPubKey {
parent_fingerprint: self.fingerprint(), parent_fingerprint: self.fingerprint(),
child_number: i, child_number: i,
public_key: pk, 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()); 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()); return Err(base58::Error::InvalidLength(data.len()).into());
} }
Ok(ExtendedPubKey::decode(&data[..])?) ExtendedPubKey::decode(&data)
} }
} }

View File

@ -183,7 +183,7 @@ pub fn compute_tweak(pk: &PublicKey, contract: &[u8]) -> Hmac<sha256::Hash> {
/// 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<C: secp256k1::Signing>(secp: &Secp256k1<C>, key: &PrivateKey, contract: &[u8]) -> Result<PrivateKey, Error> { pub fn tweak_secret_key<C: secp256k1::Signing>(secp: &Secp256k1<C>, key: &PrivateKey, contract: &[u8]) -> Result<PrivateKey, Error> {
// Compute public key // Compute public key
let pk = PublicKey::from_private_key(secp, &key); let pk = PublicKey::from_private_key(secp, key);
// Compute tweak // Compute tweak
let hmac_sk = compute_tweak(&pk, contract); let hmac_sk = compute_tweak(&pk, contract);
// Execute the tweak // Execute the tweak
@ -203,7 +203,7 @@ pub fn create_address<C: secp256k1::Verification>(secp: &Secp256k1<C>,
let keys = tweak_keys(secp, keys, contract); let keys = tweak_keys(secp, keys, contract);
let script = template.to_script(&keys)?; let script = template.to_script(&keys)?;
Ok(address::Address { Ok(address::Address {
network: network, network,
payload: address::Payload::ScriptHash( payload: address::Payload::ScriptHash(
ScriptHash::hash(&script[..]) ScriptHash::hash(&script[..])
) )

View File

@ -46,7 +46,7 @@ impl PublicKey {
pub fn new(key: secp256k1::PublicKey) -> PublicKey { pub fn new(key: secp256k1::PublicKey) -> PublicKey {
PublicKey { PublicKey {
compressed: true, compressed: true,
key: key, key,
} }
} }
@ -55,7 +55,7 @@ impl PublicKey {
pub fn new_uncompressed(key: secp256k1::PublicKey) -> PublicKey { pub fn new_uncompressed(key: secp256k1::PublicKey) -> PublicKey {
PublicKey { PublicKey {
compressed: false, compressed: false,
key: key, key,
} }
} }
@ -134,7 +134,7 @@ impl PublicKey {
}; };
Ok(PublicKey { Ok(PublicKey {
compressed: compressed, compressed,
key: secp256k1::PublicKey::from_slice(data)?, key: secp256k1::PublicKey::from_slice(data)?,
}) })
} }
@ -165,7 +165,7 @@ impl FromStr for PublicKey {
fn from_str(s: &str) -> Result<PublicKey, Error> { fn from_str(s: &str) -> Result<PublicKey, Error> {
let key = secp256k1::PublicKey::from_str(s)?; let key = secp256k1::PublicKey::from_str(s)?;
Ok(PublicKey { Ok(PublicKey {
key: key, key,
compressed: s.len() == 66 compressed: s.len() == 66
}) })
} }
@ -188,8 +188,8 @@ impl PrivateKey {
pub fn new(key: secp256k1::SecretKey, network: Network) -> PrivateKey { pub fn new(key: secp256k1::SecretKey, network: Network) -> PrivateKey {
PrivateKey { PrivateKey {
compressed: true, compressed: true,
network: network, network,
key: key, key,
} }
} }
@ -198,8 +198,8 @@ impl PrivateKey {
pub fn new_uncompressed(key: secp256k1::SecretKey, network: Network) -> PrivateKey { pub fn new_uncompressed(key: secp256k1::SecretKey, network: Network) -> PrivateKey {
PrivateKey { PrivateKey {
compressed: false, compressed: false,
network: network, network,
key: key, key,
} }
} }
@ -266,8 +266,8 @@ impl PrivateKey {
}; };
Ok(PrivateKey { Ok(PrivateKey {
compressed: compressed, compressed,
network: network, network,
key: secp256k1::SecretKey::from_slice(&data[1..33])?, key: secp256k1::SecretKey::from_slice(&data[1..33])?,
}) })
} }

View File

@ -459,7 +459,7 @@ impl MerkleBlock {
.map(match_txids) .map(match_txids)
.collect(); .collect();
let pmt = PartialMerkleTree::from_txids(&block_txids, &matches); let pmt = PartialMerkleTree::from_txids(block_txids, &matches);
MerkleBlock { MerkleBlock {
header: *header, header: *header,
txn: pmt, txn: pmt,

View File

@ -103,8 +103,8 @@ mod message_signing {
/// Create a new [MessageSignature]. /// Create a new [MessageSignature].
pub fn new(signature: RecoverableSignature, compressed: bool) -> MessageSignature { pub fn new(signature: RecoverableSignature, compressed: bool) -> MessageSignature {
MessageSignature { MessageSignature {
signature: signature, signature,
compressed: compressed, compressed,
} }
} }
@ -162,7 +162,7 @@ mod message_signing {
address: &Address, address: &Address,
msg_hash: sha256d::Hash msg_hash: sha256d::Hash
) -> Result<bool, secp256k1::Error> { ) -> Result<bool, secp256k1::Error> {
let pubkey = self.recover_pubkey(&secp_ctx, msg_hash)?; let pubkey = self.recover_pubkey(secp_ctx, msg_hash)?;
Ok(match address.address_type() { Ok(match address.address_type() {
Some(AddressType::P2pkh) => { Some(AddressType::P2pkh) => {
*address == Address::p2pkh(&pubkey, address.network) *address == Address::p2pkh(&pubkey, address.network)

View File

@ -125,7 +125,7 @@ pub(crate) fn read_to_end<D: io::Read>(mut d: D) -> Result<Vec<u8>, io::Error> {
Ok(0) => break, Ok(0) => break,
Ok(n) => result.extend_from_slice(&buf[0..n]), Ok(n) => result.extend_from_slice(&buf[0..n]),
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {},
Err(e) => return Err(e.into()), Err(e) => return Err(e),
}; };
} }
Ok(result) Ok(result)

View File

@ -155,13 +155,8 @@ impl Map for PartiallySignedTransaction {
let (fingerprint2, derivation2) = entry.get().clone(); let (fingerprint2, derivation2) = entry.get().clone();
if derivation1 == derivation2 && fingerprint1 == fingerprint2 if (derivation1 == derivation2 && fingerprint1 == fingerprint2) ||
{ (derivation1.len() < derivation2.len() && derivation1[..] == derivation2[derivation2.len() - derivation1.len()..])
continue
}
else if
derivation1.len() < derivation2.len() &&
derivation1[..] == derivation2[derivation2.len() - derivation1.len()..]
{ {
continue continue
} }

View File

@ -314,13 +314,13 @@ where
return Err(psbt::Error::InvalidPreimageHashPair { return Err(psbt::Error::InvalidPreimageHashPair {
preimage: val.into_boxed_slice(), preimage: val.into_boxed_slice(),
hash: Box::from(key_val.borrow()), hash: Box::from(key_val.borrow()),
hash_type: hash_type, hash_type,
} }
.into()); .into());
} }
empty_key.insert(val); empty_key.insert(val);
Ok(()) Ok(())
} }
btree_map::Entry::Occupied(_) => return Err(psbt::Error::DuplicateKey(raw_key).into()), btree_map::Entry::Occupied(_) => Err(psbt::Error::DuplicateKey(raw_key).into()),
} }
} }

View File

@ -80,7 +80,7 @@ impl Map for Output {
} }
PSBT_OUT_PROPRIETARY => match self.proprietary.entry(raw::ProprietaryKey::from_key(raw_key.clone())?) { 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::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) { _ => match self.unknown.entry(raw_key) {
btree_map::Entry::Vacant(empty_key) => {empty_key.insert(raw_value);}, btree_map::Entry::Vacant(empty_key) => {empty_key.insert(raw_value);},

View File

@ -100,8 +100,8 @@ impl Decodable for Key {
} }
Ok(Key { Ok(Key {
type_value: type_value, type_value,
key: key, key,
}) })
} }
} }

View File

@ -693,7 +693,7 @@ impl<'a> Annex<'a> {
impl<'a> Encodable for Annex<'a> { impl<'a> Encodable for Annex<'a> {
fn consensus_encode<W: io::Write>(&self, writer: W) -> Result<usize, io::Error> { fn consensus_encode<W: io::Write>(&self, writer: W) -> Result<usize, io::Error> {
encode::consensus_encode_with_size(&self.0, writer) encode::consensus_encode_with_size(self.0, writer)
} }
} }