Merge rust-bitcoin/rust-bitcoin#6963: Clean up Pedantic Clippy Lints
What changed, and why it matters
This is a routine code-cleanup pull request that fixes style warnings reported by the Clippy linter. It replaces verbose match/if-let blocks with shorter Option combinators, removes an obsolete lint rule, and uses explicit integer conversion helpers. There is no security bug being fixed and no behavior change intended.
No security action required. Treat as normal maintenance/refactoring code review.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit applies pedantic Clippy lint fixes across the rust-bitcoin workspace: Option::map_or/map_or_else/unwrap_or_else/is_some_and, let-else syntax, explicit From casts (u64::from, i32::from, etc.), iterator borrow shorthand, and removal of the deprecated from_iter_instead_of_collect lint. All changes are idiomatic refactorings with no functional or API changes. No vulnerability, bug fix, or security-relevant correction is present in the diff.
Changed components
Cargo.toml lint configurationaddresses cratebitcoin crate (bip158, opcodes, script, transaction, sighash, policy, sign_message)p2p crate (address, bip434, merkle_tree, message)primitives crate (block, witness)units crate (amount, relative locktime)Inspect captured patch +63 / −90
### Cargo.toml
@@ -48,7 +48,6 @@ filter_map_next = "warn"
flat_map_option = "warn"
float_cmp = "allow" # Bitcoin floats are typically limited to 8 decimal places and we want them exact.
fn_params_excessive_bools = "warn"
-from_iter_instead_of_collect = "warn"
if_not_else = "warn"
ignored_unit_patterns = "warn"
implicit_clone = "warn"
### addresses/src/lib.rs
@@ -1280,10 +1280,7 @@ impl<U: NetworkValidationUnchecked> FromStr for Address<U> {
let address = Address::from_base58_str(s).map_err(ParseError::Base58)?;
Ok(Self::from_inner(address.to_inner()))
} else {
- let hrp = match s.rfind('1') {
- Some(pos) => &s[..pos],
- None => s,
- };
+ let hrp = s.rfind('1').map_or(s, |pos| &s[..pos]);
Err(UnknownHrpError(hrp.into()))
.map_err(Bech32Error::UnknownHrp)
.map_err(ParseError::Bech32)
### bitcoin/src/bip158.rs
@@ -445,7 +445,7 @@ impl<'a, R: BufRead + ?Sized> BitStreamReader<'a, R> {
}
let bits = cmp::min(8 - self.offset, nbits);
data <<= bits;
- data |= ((self.buffer[0] << self.offset) >> (8 - bits)) as u64;
+ data |= u64::from((self.buffer[0] << self.offset) >> (8 - bits));
self.offset += bits;
nbits -= bits;
}
### bitcoin/src/blockdata/opcodes.rs
@@ -387,10 +387,10 @@ crate::internal_macros::define_extension_trait! {
// 16 opcodes of PushNum class
(op, _) if op.to_u8() >= OP_1.to_u8() && op.to_u8() <= OP_16.to_u8() =>
- Class::PushNum(1 + self.to_u8() as i32 - OP_1.to_u8() as i32),
+ Class::PushNum(1 + i32::from(self.to_u8()) - i32::from(OP_1.to_u8())),
// 76 opcodes of PushBytes class
- (op, _) if op.to_u8() <= OP_PUSHBYTES_75.to_u8() => Class::PushBytes(self.to_u8() as u32),
+ (op, _) if op.to_u8() <= OP_PUSHBYTES_75.to_u8() => Class::PushBytes(u32::from(self.to_u8())),
// opcodes of Ordinary class: 61 for Legacy and 60 for TapScript context
(_, _) => Class::Ordinary(Ordinary::with(self)),
### bitcoin/src/blockdata/script/instruction.rs
@@ -128,12 +128,9 @@ impl<'a> Instructions<'a> {
len: PushDataLenLen,
min_push_len: usize,
) -> Option<Result<Instruction<'a>, Error>> {
- let n = match script::read_push_data_len(&mut self.data, len) {
- Ok(n) => n,
- Err(_) => {
- self.kill();
- return Some(Err(Error::EarlyEndOfScript));
- }
+ let Ok(n) = script::read_push_data_len(&mut self.data, len) else {
+ self.kill();
+ return Some(Err(Error::EarlyEndOfScript));
};
let n = match usize::try_from(n) {
Ok(n) => n,
### bitcoin/src/blockdata/script/mod.rs
@@ -168,7 +168,7 @@ pub fn read_scriptint_non_minimal(v: &[u8]) -> Result<i32, ScriptIntError> {
// Caller to guarantee that `v` is not empty.
fn scriptint_parse(v: &[u8]) -> i64 {
- let (mut ret, sh) = v.iter().fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8));
+ let (mut ret, sh) = v.iter().fold((0, 0), |(acc, sh), n| (acc + (i64::from(*n) << sh), sh + 8));
if v[v.len() - 1] & 0x80 != 0 {
ret &= (1 << (sh - 1)) - 1;
ret = -ret;
### bitcoin/src/blockdata/script/owned.rs
@@ -250,7 +250,7 @@ impl<'a, Tg> Extend<Instruction<'a>> for ScriptBuf<Tg> {
let iter = iter.into_iter();
// Most of Bitcoin scripts have only a few opcodes, so we can avoid reallocations in many
// cases.
- if iter.size_hint().1.map(|max| max < 6).unwrap_or(false) {
+ if iter.size_hint().1.is_some_and(|max| max < 6) {
let mut iter = iter.fuse();
// `MaybeUninit` might be faster but we don't want to introduce more `unsafe` than
// required.
### bitcoin/src/blockdata/script/push_bytes.rs
@@ -62,9 +62,8 @@ crate::internal_macros::define_extension_trait! {
/// need to return data. In practice, if the max_size parameter is 4 or less, this function
/// will always return a value that can fit into an i32, and can thus be safely cast.
fn read_scriptint_internal(bytes: &PushBytes, max_size: usize) -> Result<i64, ScriptIntError> {
- let last = match bytes.as_bytes().last() {
- Some(last) => last,
- None => return Ok(0),
+ let Some(last) = bytes.as_bytes().last() else {
+ return Ok(0);
};
if bytes.len() > max_size {
return Err(ScriptIntError::NumericOverflow);
### bitcoin/src/blockdata/transaction.rs
@@ -528,7 +528,7 @@ impl TransactionExtPriv for Transaction {
1
} else if witness_program.is_p2wsh() {
// Treat the last item of the witness as the witnessScript
- witness.last().map(WitnessScript::from_bytes).map(|s| s.count_sigops()).unwrap_or(0)
+ witness.last().map(WitnessScript::from_bytes).map_or(0, |s| s.count_sigops())
} else {
0
}
@@ -656,7 +656,7 @@ where
(
count + 1,
weight + prediction.total_weight().to_wu() as usize,
- with_witnesses + (prediction.witness_size > 0) as usize,
+ with_witnesses + usize::from(prediction.witness_size > 0),
)
});
### bitcoin/src/crypto/sighash.rs
@@ -845,7 +845,7 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
common_cache.get_or_insert_with(|| {
let mut enc_prevouts = sha256::Hash::engine();
let mut enc_sequences = sha256::Hash::engine();
- for txin in tx.inputs.iter() {
+ for txin in &tx.inputs {
hashes::encode_to_engine(&txin.previous_output, &mut enc_prevouts);
hashes::encode_to_engine(&txin.sequence, &mut enc_sequences);
}
@@ -854,7 +854,7 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
sequences: sha256::Hash::from_engine(enc_sequences),
outputs: {
let mut enc = sha256::Hash::engine();
- for txout in tx.outputs.iter() {
+ for txout in &tx.outputs {
io::encode_to_writer(txout, &mut enc).unwrap();
}
sha256::Hash::from_engine(enc)
### bitcoin/src/policy.rs
@@ -57,6 +57,7 @@ pub(crate) const MAX_OP_RETURN_RELAY: usize = 83;
/// The virtual transaction size, as computed by default by bitcoind node.
pub fn get_virtual_tx_size(weight: i64, n_sigops: i64) -> i64 {
- (cmp::max(weight, n_sigops * DEFAULT_BYTES_PER_SIGOP as i64) + WITNESS_SCALE_FACTOR as i64 - 1)
+ (cmp::max(weight, n_sigops * i64::from(DEFAULT_BYTES_PER_SIGOP)) + WITNESS_SCALE_FACTOR as i64
+ - 1)
/ WITNESS_SCALE_FACTOR as i64
}
### bitcoin/src/sign_message.rs
@@ -65,7 +65,7 @@ mod message_signing {
if bytes[0] < 27 {
return Err(secp256k1::Error::InvalidRecoveryId);
};
- let recid = RecoveryId::try_from(((bytes[0] - 27) & 0x03) as i32)?;
+ let recid = RecoveryId::try_from(i32::from((bytes[0] - 27) & 0x03))?;
Ok(Self {
signature: RecoverableSignature::from_compact(&bytes[1..], recid)?,
compressed: ((bytes[0] - 27) & 0x04) != 0,
### bitcoin/tests/bip158.rs
@@ -28,7 +28,7 @@ fn blockfilters() {
let mut txmap = HashMap::new();
let mut si = scripts.iter();
for tx in block.transactions().iter().skip(1) {
- for input in tx.inputs.iter() {
+ for input in &tx.inputs {
txmap.insert(
input.previous_output,
ScriptPubKeyBuf::from(hex(si.next().unwrap().as_str().unwrap())),
@@ -37,11 +37,7 @@ fn blockfilters() {
}
let filter = BlockFilter::new_script_filter(&block, |o| {
- if let Some(s) = txmap.get(o) {
- Ok(s.clone())
- } else {
- Err(Error::UtxoMissing(*o))
- }
+ txmap.get(o).map_or_else(|| Err(Error::UtxoMissing(*o)), |s| Ok(s.clone()))
})
.unwrap();
@@ -53,11 +49,7 @@ fn blockfilters() {
assert!(filter
.match_all(
*block_hash,
- &mut txmap.values().filter_map(|s| if !s.is_empty() {
- Some(s.as_bytes())
- } else {
- None
- })
+ &mut txmap.values().filter_map(|s| (!s.is_empty()).then_some(s.as_bytes()))
)
.unwrap());
### p2p/src/address.rs
@@ -72,11 +72,10 @@ impl Address {
}
let ipv6 =
Ipv6Addr::new(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], addr[6], addr[7]);
- if let Some(ipv4) = ipv6.to_ipv4() {
- Ok(SocketAddr::V4(SocketAddrV4::new(ipv4, self.port)))
- } else {
- Ok(SocketAddr::V6(SocketAddrV6::new(ipv6, self.port, 0, 0)))
- }
+ ipv6.to_ipv4().map_or_else(
+ || Ok(SocketAddr::V6(SocketAddrV6::new(ipv6, self.port, 0, 0))),
+ |ipv4| Ok(SocketAddr::V4(SocketAddrV4::new(ipv4, self.port))),
+ )
}
}
### p2p/src/bip434.rs
@@ -88,7 +88,7 @@ impl encoding::Decoder for FeatureIdDecoder {
let feature_string = String::from_utf8(feature_id)
.map_err(|_| FeatureIdError::NotAscii)
.map_err(FeatureIdDecoderError::Malformed)?;
- Ok(feature_string.parse().map_err(FeatureIdDecoderError::Malformed)?)
+ feature_string.parse().map_err(FeatureIdDecoderError::Malformed)
}
}
### p2p/src/merkle_tree.rs
@@ -276,19 +276,19 @@ impl PartialMerkleTree {
// An empty set will not work
if self.num_transactions == 0 {
return Err(MerkleBlockError::NoTransactions);
- };
+ }
// check for excessively high numbers of transactions
if u64::from(self.num_transactions) > Weight::MAX_BLOCK / Weight::MIN_TRANSACTION {
return Err(MerkleBlockError::TooManyTransactions);
}
// there can never be more hashes provided than one for every txid
if self.hashes.len() as u32 > self.num_transactions {
return Err(MerkleBlockError::TooManyHashes);
- };
+ }
// there must be at least one bit per node in the partial tree, and at least one node per hash
if self.bits.len() < self.hashes.len() {
return Err(MerkleBlockError::NotEnoughBits);
- };
+ }
let height = self.calc_tree_height();
@@ -764,7 +764,7 @@ mod tests {
if include {
match_txid1.push(tx_ids[j]);
- };
+ }
}
// Build the partial Merkle tree
### p2p/src/message.rs
@@ -1307,11 +1307,10 @@ impl encoding::Decoder for NetworkMessageDecoder {
#[inline]
fn read_limit(&self) -> usize {
- match self.payload_len {
- Some(expected) =>
- self.inner.read_limit().min(expected.saturating_sub(self.bytes_consumed)),
- None => self.inner.read_limit(),
- }
+ self.payload_len.map_or_else(
+ || self.inner.read_limit(),
+ |expected| self.inner.read_limit().min(expected.saturating_sub(self.bytes_consumed)),
+ )
}
}
### primitives/src/block.rs
@@ -309,10 +309,7 @@ impl Block<Unchecked> {
/// Checks if Merkle root of header matches Merkle root of the transaction list.
#[inline]
pub fn check_merkle_root(&self) -> bool {
- match compute_merkle_root(&self.transactions) {
- Some(merkle_root) => self.header.merkle_root == merkle_root,
- None => false,
- }
+ compute_merkle_root(&self.transactions) == Some(self.header.merkle_root)
}
/// Computes the witness commitment for a list of transactions.
@@ -675,15 +672,11 @@ fn witness_commitment_from_coinbase(coinbase: &Transaction) -> Option<WitnessCom
}
// Commitment is in the last output that starts with magic bytes.
- if let Some(pos) = coinbase.outputs.iter().rposition(|o| {
- o.script_pubkey.len() >= 38 && o.script_pubkey.as_bytes()[0..6] == WITNESS_COMMITMENT_MAGIC
- }) {
- let bytes =
- <[u8; 32]>::try_from(&coinbase.outputs[pos].script_pubkey.as_bytes()[6..38]).unwrap();
+ coinbase.outputs.iter().rev().find_map(|o| {
+ let payload = o.script_pubkey.as_bytes().strip_prefix(&WITNESS_COMMITMENT_MAGIC)?;
+ let bytes = <[u8; 32]>::try_from(payload.get(..32)?).ok()?;
Some(WitnessCommitment::from_byte_array(bytes))
- } else {
- None
- }
+ })
}
/// Bitcoin block header.
### primitives/src/witness.rs
@@ -595,10 +595,7 @@ impl encoding::Decoder for WitnessDecoder {
self.witness_count_decoder.read_limit()
} else {
// Reading an element.
- match self.element_bytes_remaining {
- None => self.element_length_decoder.read_limit(),
- Some(remaining) => remaining,
- }
+ self.element_bytes_remaining.unwrap_or_else(|| self.element_length_decoder.read_limit())
}
}
}
### units/src/amount/mod.rs
@@ -219,7 +219,7 @@ impl FromStr for Denomination {
if CONFUSING_FORMS.contains(&s) {
return Err(PossiblyConfusingDenominationError(s.into())).map_err(E::PossiblyConfusing);
- };
+ }
let form = Self::forms(s);
### units/src/locktime/relative/mod.rs
@@ -475,17 +475,17 @@ impl NumberOfBlocks {
chain_tip: crate::BlockHeight,
utxo_mined_at: Option<crate::BlockHeight>,
) -> Result<bool, InvalidHeightError> {
- match utxo_mined_at {
- Some(mined_at) => chain_tip
- .checked_sub(mined_at)
- .ok_or(InvalidHeightError { chain_tip, utxo_mined_at: mined_at })
- .map(|diff| u32::from(self.to_count()).saturating_sub(1) <= diff.to_u32()),
- None => {
- // We want 0-value relative timelocks to be able to go into transactions in the
- // mempool if their parent is also in the mempool.
- Ok(self == Self::ZERO)
- }
- }
+ utxo_mined_at.map_or(
+ // We want 0-value relative timelocks to be able to go into transactions in the
+ // mempool if their parent is also in the mempool.
+ Ok(self == Self::ZERO),
+ |mined_at| {
+ chain_tip
+ .checked_sub(mined_at)
+ .ok_or(InvalidHeightError { chain_tip, utxo_mined_at: mined_at })
+ .map(|diff| u32::from(self.to_count()).saturating_sub(1) <= diff.to_u32())
+ },
+ )
}
}
@@ -625,17 +625,17 @@ impl NumberOf512Seconds {
chain_tip: crate::BlockMtp,
utxo_mined_at: Option<crate::BlockMtp>,
) -> Result<bool, InvalidTimeError> {
- match utxo_mined_at {
- Some(mined_at) => chain_tip
- .checked_sub(mined_at)
- .ok_or(InvalidTimeError { chain_tip, utxo_mined_at: mined_at })
- .map(|diff| self.to_seconds() <= diff.to_u32()),
- None => {
- // We want 0-value relative timelocks to be able to go into transactions in the
- // mempool if their parent is also in the mempool.
- Ok(self == Self::ZERO)
- }
- }
+ utxo_mined_at.map_or(
+ // We want 0-value relative timelocks to be able to go into transactions in the
+ // mempool if their parent is also in the mempool.
+ Ok(self == Self::ZERO),
+ |mined_at| {
+ chain_tip
+ .checked_sub(mined_at)
+ .ok_or(InvalidTimeError { chain_tip, utxo_mined_at: mined_at })
+ .map(|diff| self.to_seconds() <= diff.to_u32())
+ },
+ )
}
}
Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.