8000 Fixed a bunch of clippy lints, added clippy.toml by Kixunil · Pull Request #686 · rust-bitcoin/rust-bitcoin · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fixed a bunch of clippy lints, added clippy.toml #686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
8000 Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
msrv = "1.29"
2 changes: 1 addition & 1 deletion src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
8 changes: 4 additions & 4 deletions src/blockdata/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x1d00ffff,
nonce: 2083236893
},
txdata: txdata
txdata,
}
}
Network::Testnet => {
Expand All @@ -142,7 +142,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x1d00ffff,
nonce: 414098458
},
txdata: txdata
txdata,
}
}
Network::Signet => {
Expand All @@ -155,7 +155,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x1e0377ae,
nonce: 52613770
},
txdata: txdata
txdata,
}
}
Network::Regtest => {
Expand All @@ -168,7 +168,7 @@ pub fn genesis_block(network: Network) -> Block {
bits: 0x207fffff,
nonce: 2
},
txdata: txdata
txdata,
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/blockdata/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand All @@ -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
Expand Down
42 changes: 30 additions & 12 deletions src/blockdata/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ impl OutPoint {
#[inline]
pub fn new(txid: Txid, vout: u32) -> OutPoint {
OutPoint {
txid: txid,
vout: vout,
txid,
vout,
}
}

Expand Down Expand Up @@ -153,7 +153,7 @@ fn parse_vout(s: &str) -> Result<u32, ParseOutPointError> {
return Err(ParseOutPointError::VoutNotCanonical);
}
}
Ok(s.parse().map_err(ParseOutPointError::Vout)?)
s.parse().map_err(ParseOutPointError::Vout)
}

impl ::core::str::FromStr for OutPoint {
Expand Down Expand Up @@ -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)?,
})
}
Expand All @@ -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)?,
})
Expand Down Expand Up @@ -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<Self, Self::Err> {
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() }),
}
}
}
Expand Down Expand Up @@ -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)]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#[derive(ParialEq, Eq, PartialOrd, Ord)], according to our new contributing guidelines :)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH, I'm not really convinced errors should commit to Ord/PartialOrd. Maybe Eq is fine.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about Hash?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there's Eq there should be Hash, I believe.

In this specific case I'm not even sure about Eq. Are two errors carrying information saying "can't recognize sighash string" (by their existence) that were caused by different input (which they write for ease of debugging) equal or not?

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};
Expand Down Expand Up @@ -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));
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/consensus/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ impl Encodable for String {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
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())
}
}
Expand All @@ -480,7 +480,7 @@ impl Encodable for Cow<'static, str> {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, io::Error> {
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())
}
}
Expand Down Expand Up @@ -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> {
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())
}

Expand Down
10 changes: 5 additions & 5 deletions src/network/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}
Expand Down Expand Up @@ -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)),
}
}
}
Expand Down
32 changes: 25 additions & 7 deletions src/network/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: 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();
if cow.as_ref().len() > 12 {
Err(())
if cow.len() > 12 {
Err(CommandStringError { cow })
} else {
Ok(CommandString(cow))
}
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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)]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ibid

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I still think #[derive(PartialEq, Eq)] will be nice to have

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 {
Expand Down Expand Up @@ -395,8 +413,8 @@ impl Decodable for RawNetworkMessage {
}
};
Ok(RawNetworkMessage {
magic: magic,
payload: payload
magic,
payload,
})
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/network/message_blockdata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ impl GetBlocksMessage {
pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetBlocksMessage {
GetBlocksMessage {
version: constants::PROTOCOL_VERSION,
locator_hashes: locator_hashes,
stop_hash: stop_hash
locator_hashes,
stop_hash,
}
}
}
Expand All @@ -141,8 +141,8 @@ impl GetHeadersMessage {
pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetHeadersMessage {
GetHeadersMessage {
version: constants::PROTOCOL_VERSION,
locator_hashes: locator_hashes,
stop_hash: stop_hash
locator_hashes,
stop_hash,
}
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/network/message_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down
Loading
0