Meaningful changes from aggressive-clippy

I do want to enable a few specific lints, yet aggressive-clippy as a whole
isn't worthwhile.
This commit is contained in:
Luke Parker
2023-07-08 11:29:05 -04:00
parent 3c6cc42c23
commit 93b1656f86
39 changed files with 127 additions and 143 deletions

View File

@@ -134,7 +134,7 @@ fn test_secp256k1() {
)
.to_repr()
.iter()
.cloned()
.copied()
.collect::<Vec<_>>(),
hex::decode("acc83278035223c1ba464e2d11bfacfc872b2b23e1041cf5f6130da21e4d8068").unwrap()
);
@@ -167,7 +167,7 @@ f4e8cf80aec3f888d997900ac7e3e349944b5a6b47649fc32186d2f1238103c6\
)
.to_repr()
.iter()
.cloned()
.copied()
.collect::<Vec<_>>(),
hex::decode("f871dfcf6bcd199342651adc361b92c941cb6a0d8c8c1a3b91d79e2c1bf3722d").unwrap()
);

View File

@@ -1,5 +1,5 @@
use core::{
ops::{DerefMut, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
ops::{Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
iter::{Sum, Product},
};
@@ -234,7 +234,7 @@ impl FieldElement {
let mut bits = 0;
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
bits <<= 1;
let mut bit = u8_from_bool(bit.deref_mut());
let mut bit = u8_from_bool(&mut bit);
bits |= bit;
bit.zeroize();
@@ -300,7 +300,7 @@ impl Sum<FieldElement> for FieldElement {
impl<'a> Sum<&'a FieldElement> for FieldElement {
fn sum<I: Iterator<Item = &'a FieldElement>>(iter: I) -> FieldElement {
iter.cloned().sum()
iter.copied().sum()
}
}
@@ -316,7 +316,7 @@ impl Product<FieldElement> for FieldElement {
impl<'a> Product<&'a FieldElement> for FieldElement {
fn product<I: Iterator<Item = &'a FieldElement>>(iter: I) -> FieldElement {
iter.cloned().product()
iter.copied().product()
}
}

View File

@@ -4,7 +4,7 @@
use core::{
borrow::Borrow,
ops::{Deref, DerefMut, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
ops::{Deref, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
iter::{Iterator, Sum, Product},
hash::{Hash, Hasher},
};
@@ -201,7 +201,7 @@ impl Scalar {
let mut bits = 0;
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
bits <<= 1;
let mut bit = u8_from_bool(bit.deref_mut());
let mut bit = u8_from_bool(&mut bit);
bits |= bit;
bit.zeroize();
@@ -337,7 +337,7 @@ impl PrimeField for Scalar {
// methods does not
// We do not use one of its methods to ensure we write via zeroize
for mut bit in bits.iter_mut() {
bit.deref_mut().zeroize();
bit.zeroize();
}
res
}

View File

@@ -390,9 +390,10 @@ impl<C: Ciphersuite> Encryption<C> {
participant: Participant,
msg: EncryptionKeyMessage<C, M>,
) -> M {
if self.enc_keys.contains_key(&participant) {
panic!("Re-registering encryption key for a participant");
}
assert!(
!self.enc_keys.contains_key(&participant),
"Re-registering encryption key for a participant"
);
self.enc_keys.insert(participant, msg.enc_key);
msg.msg
}

View File

@@ -92,7 +92,8 @@ pub struct KeyGenMachine<C: Ciphersuite> {
impl<C: Ciphersuite> KeyGenMachine<C> {
/// Create a new machine to generate a key.
// The context string should be unique among multisigs.
///
/// The context string should be unique among multisigs.
pub fn new(params: ThresholdParams, context: String) -> KeyGenMachine<C> {
KeyGenMachine { params, context, _curve: PhantomData }
}
@@ -171,7 +172,6 @@ fn polynomial<F: PrimeField + Zeroize>(
/// channel.
///
/// If any participant sends multiple secret shares to another participant, they are faulty.
// This should presumably be written as SecretShare(Zeroizing<F::Repr>).
// It's unfortunately not possible as F::Repr doesn't have Zeroize as a bound.
// The encryption system also explicitly uses Zeroizing<M> so it can ensure anything being
@@ -353,7 +353,7 @@ impl<C: Ciphersuite> Zeroize for KeyMachine<C> {
fn zeroize(&mut self) {
self.params.zeroize();
self.secret.zeroize();
for (_, commitments) in self.commitments.iter_mut() {
for commitments in self.commitments.values_mut() {
commitments.zeroize();
}
self.encryption.zeroize();
@@ -499,7 +499,7 @@ impl<C: Ciphersuite> fmt::Debug for BlameMachine<C> {
impl<C: Ciphersuite> Zeroize for BlameMachine<C> {
fn zeroize(&mut self) {
for (_, commitments) in self.commitments.iter_mut() {
for commitments in self.commitments.values_mut() {
commitments.zeroize();
}
self.encryption.zeroize();
@@ -536,10 +536,9 @@ impl<C: Ciphersuite> BlameMachine<C> {
Err(DecryptionError::InvalidProof) => return recipient,
};
let share = match Option::<C::F>::from(C::F::from_repr(share_bytes.0)) {
Some(share) => share,
let Some(share) = Option::<C::F>::from(C::F::from_repr(share_bytes.0)) else {
// If this isn't a valid scalar, the sender is faulty
None => return sender,
return sender;
};
// If this isn't a valid share, the sender is faulty

View File

@@ -25,7 +25,7 @@ pub const PARTICIPANTS: u16 = 5;
pub const THRESHOLD: u16 = ((PARTICIPANTS * 2) / 3) + 1;
/// Clone a map without a specific value.
pub fn clone_without<K: Clone + std::cmp::Eq + std::hash::Hash, V: Clone>(
pub fn clone_without<K: Clone + core::cmp::Eq + core::hash::Hash, V: Clone>(
map: &HashMap<K, V>,
without: &K,
) -> HashMap<K, V> {
@@ -40,7 +40,7 @@ pub fn clone_without<K: Clone + std::cmp::Eq + std::hash::Hash, V: Clone>(
pub fn recover_key<C: Ciphersuite>(keys: &HashMap<Participant, ThresholdKeys<C>>) -> C::F {
let first = keys.values().next().expect("no keys provided");
assert!(keys.len() >= first.params().t().into(), "not enough keys provided");
let included = keys.keys().cloned().collect::<Vec<_>>();
let included = keys.keys().copied().collect::<Vec<_>>();
let group_private = keys.iter().fold(C::F::ZERO, |accum, (i, keys)| {
accum + (lagrange::<C::F>(*i, &included) * keys.secret_share().deref())

View File

@@ -24,9 +24,9 @@ pub fn test_musig<R: RngCore + CryptoRng, C: Ciphersuite>(rng: &mut R) {
const CONTEXT: &[u8] = b"MuSig Test";
// Empty signing set
assert!(musig::<C>(CONTEXT, &Zeroizing::new(C::F::ZERO), &[]).is_err());
musig::<C>(CONTEXT, &Zeroizing::new(C::F::ZERO), &[]).unwrap_err();
// Signing set we're not part of
assert!(musig::<C>(CONTEXT, &Zeroizing::new(C::F::ZERO), &[C::generator()]).is_err());
musig::<C>(CONTEXT, &Zeroizing::new(C::F::ZERO), &[C::generator()]).unwrap_err();
// Test with n keys
{

View File

@@ -1,6 +1,6 @@
use core::ops::{Deref, DerefMut};
#[cfg(feature = "serialize")]
use std::io::{Read, Write};
use std::io::{self, Read, Write};
use thiserror::Error;
@@ -51,15 +51,15 @@ fn u8_from_bool(bit_ref: &mut bool) -> u8 {
}
#[cfg(feature = "serialize")]
pub(crate) fn read_point<R: Read, G: PrimeGroup>(r: &mut R) -> std::io::Result<G> {
pub(crate) fn read_point<R: Read, G: PrimeGroup>(r: &mut R) -> io::Result<G> {
let mut repr = G::Repr::default();
r.read_exact(repr.as_mut())?;
let point = G::from_bytes(&repr);
let Some(point) = Option::<G>::from(point) else {
Err(std::io::Error::new(std::io::ErrorKind::Other, "invalid point"))?
Err(io::Error::new(io::ErrorKind::Other, "invalid point"))?
};
if point.to_bytes().as_ref() != repr.as_ref() {
Err(std::io::Error::new(std::io::ErrorKind::Other, "non-canonical point"))?;
Err(io::Error::new(io::ErrorKind::Other, "non-canonical point"))?;
}
Ok(point)
}
@@ -439,7 +439,7 @@ where
/// Write a Cross-Group Discrete Log Equality proof to a type satisfying std::io::Write.
#[cfg(feature = "serialize")]
pub fn write<W: Write>(&self, w: &mut W) -> std::io::Result<()> {
pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
for bit in &self.bits {
bit.write(w)?;
}
@@ -452,7 +452,7 @@ where
/// Read a Cross-Group Discrete Log Equality proof from a type satisfying std::io::Read.
#[cfg(feature = "serialize")]
pub fn read<R: Read>(r: &mut R) -> std::io::Result<Self> {
pub fn read<R: Read>(r: &mut R) -> io::Result<Self> {
let capacity = usize::try_from(G0::Scalar::CAPACITY.min(G1::Scalar::CAPACITY)).unwrap();
let bits_per_group = BitSignature::from(SIGNATURE).bits();

View File

@@ -77,7 +77,7 @@ fn test_dleq() {
assert!(proof
.verify(
&mut transcript(),
generators[.. i].iter().cloned().rev().collect::<Vec<_>>().as_ref(),
generators[.. i].iter().copied().rev().collect::<Vec<_>>().as_ref(),
&keys[.. i]
)
.is_err());
@@ -86,7 +86,7 @@ fn test_dleq() {
.verify(
&mut transcript(),
&generators[.. i],
keys[.. i].iter().cloned().rev().collect::<Vec<_>>().as_ref()
keys[.. i].iter().copied().rev().collect::<Vec<_>>().as_ref()
)
.is_err());
}

View File

@@ -80,7 +80,7 @@ macro_rules! field {
$DELTA: expr,
) => {
use core::{
ops::{DerefMut, Add, AddAssign, Neg, Sub, SubAssign, Mul, MulAssign},
ops::{Add, AddAssign, Neg, Sub, SubAssign, Mul, MulAssign},
iter::{Sum, Product},
};
@@ -150,7 +150,7 @@ macro_rules! field {
let mut bits = 0;
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
bits <<= 1;
let mut bit = u8_from_bool(bit.deref_mut());
let mut bit = u8_from_bool(&mut bit);
bits |= bit;
bit.zeroize();

View File

@@ -1,5 +1,5 @@
use core::{
ops::{DerefMut, Add, AddAssign, Neg, Sub, SubAssign, Mul, MulAssign},
ops::{Add, AddAssign, Neg, Sub, SubAssign, Mul, MulAssign},
iter::Sum,
};
@@ -232,7 +232,7 @@ impl Mul<Scalar> for Point {
let mut bits = 0;
for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
bits <<= 1;
let mut bit = u8_from_bool(bit.deref_mut());
let mut bit = u8_from_bool(&mut bit);
bits |= bit;
bit.zeroize();

View File

@@ -27,7 +27,7 @@ pub const PARTICIPANTS: u16 = 5;
pub const THRESHOLD: u16 = ((PARTICIPANTS * 2) / 3) + 1;
/// Clone a map without a specific value.
pub fn clone_without<K: Clone + std::cmp::Eq + std::hash::Hash, V: Clone>(
pub fn clone_without<K: Clone + core::cmp::Eq + core::hash::Hash, V: Clone>(
map: &HashMap<K, V>,
without: &K,
) -> HashMap<K, V> {
@@ -177,8 +177,8 @@ pub fn sign<R: RngCore + CryptoRng, M: PreprocessMachine>(
machines,
|rng, machines| {
// Cache and rebuild half of the machines
let mut included = machines.keys().cloned().collect::<Vec<_>>();
for i in included.drain(..) {
let included = machines.keys().cloned().collect::<Vec<_>>();
for i in included {
if (rng.next_u64() % 2) == 0 {
let cache = machines.remove(&i).unwrap().cache();
machines.insert(
@@ -226,7 +226,7 @@ pub fn test_offset_schnorr<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(rng: &m
let offset = C::F::from(5);
let offset_key = group_key + (C::generator() * offset);
for (_, keys) in keys.iter_mut() {
for keys in keys.values_mut() {
*keys = keys.offset(offset);
assert_eq!(keys.group_key(), offset_key);
}

View File

@@ -176,13 +176,8 @@ pub fn test_invalid_commitment<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
let nonce =
preprocess.commitments.nonces.get_mut(usize::try_from(rng.next_u64()).unwrap() % 2).unwrap();
let generators_len = nonce.generators.len();
*nonce
.generators
.get_mut(usize::try_from(rng.next_u64()).unwrap() % generators_len)
.unwrap()
.0
.get_mut(usize::try_from(rng.next_u64()).unwrap() % 2)
.unwrap() = C::G::random(&mut *rng);
nonce.generators[usize::try_from(rng.next_u64()).unwrap() % generators_len].0
[usize::try_from(rng.next_u64()).unwrap() % 2] = C::G::random(&mut *rng);
// The commitments are validated at time of deserialization (read_preprocess)
// Accordingly, serialize it and read it again to make sure that errors

View File

@@ -166,8 +166,8 @@ pub fn test_with_vectors<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(
}
let mut commitments = HashMap::new();
let mut machines = machines
.drain(..)
let machines = machines
.into_iter()
.enumerate()
.map(|(c, (i, machine))| {
let nonce = |i| {
@@ -224,8 +224,8 @@ pub fn test_with_vectors<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(
.collect::<Vec<_>>();
let mut shares = HashMap::new();
let mut machines = machines
.drain(..)
let machines = machines
.into_iter()
.enumerate()
.map(|(c, (i, machine))| {
let (machine, share) = machine
@@ -242,9 +242,9 @@ pub fn test_with_vectors<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(
shares.insert(*i, machine.read_share::<&[u8]>(&mut share.as_ref()).unwrap());
(i, machine)
})
.collect::<HashMap<_, _>>();
.collect::<Vec<_>>();
for (i, machine) in machines.drain() {
for (i, machine) in machines {
let sig = machine.complete(clone_without(&shares, i)).unwrap();
let mut serialized = sig.R.to_bytes().as_ref().to_vec();
serialized.extend(sig.s.to_repr().as_ref());
@@ -347,7 +347,7 @@ pub fn test_with_vectors<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(
machines.push((i, AlgorithmMachine::new(IetfSchnorr::<C, H>::ietf(), keys[i].clone())));
}
for (i, machine) in machines.drain(..) {
for (i, machine) in machines {
let (_, preprocess) = machine.preprocess(&mut frosts.clone());
// Calculate the expected nonces

View File

@@ -18,7 +18,7 @@ fn flat<Id: Copy + Zeroize, G: Group + Zeroize>(
where
<G as Group>::Scalar: PrimeFieldBits + Zeroize,
{
Zeroizing::new(slice.iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>())
Zeroizing::new(slice.iter().flat_map(|pairs| pairs.1.iter()).copied().collect::<Vec<_>>())
}
/// A batch verifier intended to verify a series of statements are each equivalent to zero.
@@ -35,7 +35,8 @@ where
<G as Group>::Scalar: PrimeFieldBits + Zeroize,
{
/// Create a new batch verifier, expected to verify the following amount of statements.
/// This is a size hint and is not required to be accurate.
///
/// `capacity` is a size hint and is not required to be accurate.
pub fn new(capacity: usize) -> BatchVerifier<Id, G> {
BatchVerifier(Zeroizing::new(Vec::with_capacity(capacity)))
}

View File

@@ -2,7 +2,6 @@
#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]
use core::ops::DerefMut;
#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc;
@@ -62,7 +61,7 @@ where
groupings.push(vec![0; (bits.len() + (w_usize - 1)) / w_usize]);
for (i, mut bit) in bits.iter_mut().enumerate() {
let mut bit = u8_from_bool(bit.deref_mut());
let mut bit = u8_from_bool(&mut bit);
groupings[p][i / w_usize] |= bit << (i % w_usize);
bit.zeroize();
}

View File

@@ -106,7 +106,7 @@ pub(crate) fn aggregate<C: Ciphersuite>() {
keys
.iter()
.map(|key| C::generator() * key.deref())
.zip(challenges.iter().cloned())
.zip(challenges.iter().copied())
.collect::<Vec<_>>()
.as_ref(),
));