Skip to content

Commit

Permalink
Further expand clippy workspace lints
Browse files Browse the repository at this point in the history
Achieves a notable amount of reduced async and clones.
  • Loading branch information
kayabaNerve committed Dec 17, 2023
1 parent ea3af28 commit 065d314
Show file tree
Hide file tree
Showing 113 changed files with 596 additions and 724 deletions.
26 changes: 26 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,29 @@ inefficient_to_string = "deny"
invalid_upcast_comparisons = "deny"
large_stack_arrays = "deny"
linkedlist = "deny"
macro_use_imports = "deny"
manual_instant_elapsed = "deny"
manual_let_else = "deny"
manual_ok_or = "deny"
manual_string_new = "deny"
map_unwrap_or = "deny"
match_bool = "deny"
match_same_arms = "deny"
missing_fields_in_debug = "deny"
needless_continue = "deny"
needless_pass_by_value = "deny"
ptr_cast_constness = "deny"
range_minus_one = "deny"
range_plus_one = "deny"
redundant_closure_for_method_calls = "deny"
redundant_else = "deny"
string_add_assign = "deny"
unchecked_duration_subtraction = "deny"
uninlined_format_args = "deny"
unnecessary_box_returns = "deny"
unnecessary_join = "deny"
unnecessary_wraps = "deny"
unnested_or_patterns = "deny"
unused_async = "deny"
unused_self = "deny"
zero_sized_map_values = "deny"
4 changes: 2 additions & 2 deletions coins/bitcoin/src/tests/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ fn test_algorithm() {
Schnorr::<RecommendedTranscript>::new(RecommendedTranscript::new(b"bitcoin-serai sign test"));
let sig = sign(
&mut OsRng,
algo.clone(),
&algo,
keys.clone(),
algorithm_machines(&mut OsRng, algo, &keys),
algorithm_machines(&mut OsRng, &algo, &keys),
Hash::hash(MESSAGE).as_ref(),
);

Expand Down
8 changes: 4 additions & 4 deletions coins/bitcoin/src/wallet/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl SignableTransaction {
pub fn new(
mut inputs: Vec<ReceivedOutput>,
payments: &[(Address, u64)],
change: Option<Address>,
change: Option<&Address>,
data: Option<Vec<u8>>,
fee_per_weight: u64,
) -> Result<SignableTransaction, TransactionError> {
Expand All @@ -140,7 +140,7 @@ impl SignableTransaction {
}
}

if data.as_ref().map(|data| data.len()).unwrap_or(0) > 80 {
if data.as_ref().map_or(0, Vec::len) > 80 {
Err(TransactionError::TooMuchData)?;
}

Expand Down Expand Up @@ -212,7 +212,7 @@ impl SignableTransaction {
}

// If there's a change address, check if there's change to give it
if let Some(change) = change.as_ref() {
if let Some(change) = change {
let weight_with_change = Self::calculate_weight(tx_ins.len(), payments, Some(change));
let fee_with_change = fee_per_weight * weight_with_change;
if let Some(value) = input_sat.checked_sub(payment_sat + fee_with_change) {
Expand Down Expand Up @@ -263,7 +263,7 @@ impl SignableTransaction {
/// Returns None if the wrong keys are used.
pub fn multisig(
self,
keys: ThresholdKeys<Secp256k1>,
keys: &ThresholdKeys<Secp256k1>,
mut transcript: RecommendedTranscript,
) -> Option<TransactionMachine> {
transcript.domain_separate(b"bitcoin_transaction");
Expand Down
16 changes: 8 additions & 8 deletions coins/bitcoin/tests/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,14 @@ fn keys() -> (HashMap<Participant, ThresholdKeys<Secp256k1>>, ProjectivePoint) {

fn sign(
keys: &HashMap<Participant, ThresholdKeys<Secp256k1>>,
tx: SignableTransaction,
tx: &SignableTransaction,
) -> Transaction {
let mut machines = HashMap::new();
for i in (1 ..= THRESHOLD).map(|i| Participant::new(i).unwrap()) {
machines.insert(
i,
tx.clone()
.multisig(keys[&i].clone(), RecommendedTranscript::new(b"bitcoin-serai Test Transaction"))
.multisig(&keys[&i].clone(), RecommendedTranscript::new(b"bitcoin-serai Test Transaction"))
.unwrap(),
);
}
Expand Down Expand Up @@ -206,7 +206,7 @@ async_sequential! {
// No change
assert!(SignableTransaction::new(inputs.clone(), &[(addr(), 1000)], None, None, FEE).is_ok());
// Consolidation TX
assert!(SignableTransaction::new(inputs.clone(), &[], Some(addr()), None, FEE).is_ok());
assert!(SignableTransaction::new(inputs.clone(), &[], Some(&addr()), None, FEE).is_ok());
// Data
assert!(SignableTransaction::new(inputs.clone(), &[], None, Some(vec![]), FEE).is_ok());
// No outputs
Expand All @@ -229,7 +229,7 @@ async_sequential! {
);

assert_eq!(
SignableTransaction::new(inputs.clone(), &[], Some(addr()), None, 0),
SignableTransaction::new(inputs.clone(), &[], Some(&addr()), None, 0),
Err(TransactionError::TooLowFee),
);

Expand Down Expand Up @@ -274,13 +274,13 @@ async_sequential! {
let tx = SignableTransaction::new(
vec![output.clone(), offset_output.clone()],
&payments,
Some(change_addr.clone()),
Some(&change_addr),
None,
FEE
).unwrap();
let needed_fee = tx.needed_fee();
let expected_id = tx.txid();
let tx = sign(&keys, tx);
let tx = sign(&keys, &tx);

assert_eq!(tx.output.len(), 3);

Expand Down Expand Up @@ -341,10 +341,10 @@ async_sequential! {

let tx = sign(
&keys,
SignableTransaction::new(
&SignableTransaction::new(
vec![output],
&[],
Some(Address::<NetworkChecked>::new(Network::Regtest, address_payload(key).unwrap())),
Some(&Address::<NetworkChecked>::new(Network::Regtest, address_payload(key).unwrap())),
Some(data.clone()),
FEE
).unwrap()
Expand Down
4 changes: 2 additions & 2 deletions coins/ethereum/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ async fn test_ecrecover_hack() {
let algo = IetfSchnorr::<Secp256k1, crypto::EthereumHram>::ietf();
let sig = sign(
&mut OsRng,
algo.clone(),
&algo,
keys.clone(),
algorithm_machines(&mut OsRng, algo, &keys),
algorithm_machines(&mut OsRng, &algo, &keys),
full_message,
);
let mut processed_sig =
Expand Down
13 changes: 4 additions & 9 deletions coins/ethereum/tests/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,8 @@ fn test_signing() {
const MESSAGE: &[u8] = b"Hello, World!";

let algo = IetfSchnorr::<Secp256k1, EthereumHram>::ietf();
let _sig = sign(
&mut OsRng,
algo,
keys.clone(),
algorithm_machines(&mut OsRng, IetfSchnorr::<Secp256k1, EthereumHram>::ietf(), &keys),
MESSAGE,
);
let _sig =
sign(&mut OsRng, &algo, keys.clone(), algorithm_machines(&mut OsRng, &algo, &keys), MESSAGE);
}

#[test]
Expand All @@ -79,9 +74,9 @@ fn test_ecrecover_hack() {
let algo = IetfSchnorr::<Secp256k1, EthereumHram>::ietf();
let sig = sign(
&mut OsRng,
algo.clone(),
&algo,
keys.clone(),
algorithm_machines(&mut OsRng, algo, &keys),
algorithm_machines(&mut OsRng, &algo, &keys),
full_message,
);

Expand Down
4 changes: 2 additions & 2 deletions coins/monero/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ fn serialize(generators_string: &mut String, points: &[EdwardsPoint]) {
fn generators(prefix: &'static str, path: &str) {
let generators = bulletproofs_generators(prefix.as_bytes());
#[allow(non_snake_case)]
let mut G_str = "".to_string();
let mut G_str = String::new();
serialize(&mut G_str, &generators.G);
#[allow(non_snake_case)]
let mut H_str = "".to_string();
let mut H_str = String::new();
serialize(&mut H_str, &generators.H);

let path = Path::new(&env::var("OUT_DIR").unwrap()).join(path);
Expand Down
2 changes: 1 addition & 1 deletion coins/monero/src/bin/reserialize_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ mod binaries {
assert!(batch.verify_vartime());
}

println!("Deserialized, hashed, and reserialized {block_i} with {} TXs", txs_len);
println!("Deserialized, hashed, and reserialized {block_i} with {txs_len} TXs");
}
}

Expand Down
4 changes: 2 additions & 2 deletions coins/monero/src/ringct/bulletproofs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std_shims::{

use rand_core::{RngCore, CryptoRng};

use zeroize::Zeroize;
use zeroize::{Zeroize, Zeroizing};

use curve25519_dalek::edwards::EdwardsPoint;
use multiexp::BatchVerifier;
Expand Down Expand Up @@ -91,7 +91,7 @@ impl Bulletproofs {
Bulletproofs::Plus(
AggregateRangeStatement::new(outputs.iter().map(|com| DfgPoint(com.calculate())).collect())
.unwrap()
.prove(rng, AggregateRangeWitness::new(outputs).unwrap())
.prove(rng, &Zeroizing::new(AggregateRangeWitness::new(outputs).unwrap()))
.unwrap(),
)
})
Expand Down
2 changes: 1 addition & 1 deletion coins/monero/src/ringct/bulletproofs/original.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ impl OriginalStruct {
let A = normalize(&self.A);
let S = normalize(&self.S);

let commitments = commitments.iter().map(|c| c.mul_by_cofactor()).collect::<Vec<_>>();
let commitments = commitments.iter().map(EdwardsPoint::mul_by_cofactor).collect::<Vec<_>>();

// Verify it
let mut proof = Vec::with_capacity(4 + commitments.len());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std_shims::vec::Vec;

use rand_core::{RngCore, CryptoRng};

use zeroize::{Zeroize, ZeroizeOnDrop};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use multiexp::{multiexp, multiexp_vartime, BatchVerifier};
use group::{
Expand Down Expand Up @@ -142,7 +142,7 @@ impl AggregateRangeStatement {
A_terms.push((y_mn_plus_one, commitment_accum));
A_terms.push((
((y_pows * z) - (d.sum() * y_mn_plus_one * z) - (y_pows * z.square())),
generators.g(),
Generators::g(),
));

(y, d_descending_y, y_mn_plus_one, z, ScalarVector(z_pow), A + multiexp_vartime(&A_terms))
Expand All @@ -151,7 +151,7 @@ impl AggregateRangeStatement {
pub(crate) fn prove<R: RngCore + CryptoRng>(
self,
rng: &mut R,
witness: AggregateRangeWitness,
witness: &AggregateRangeWitness,
) -> Option<AggregateRangeProof> {
// Check for consistency with the witness
if self.V.len() != witness.values.len() {
Expand Down Expand Up @@ -202,7 +202,7 @@ impl AggregateRangeStatement {
for (i, a_r) in a_r.0.iter().enumerate() {
A_terms.push((*a_r, generators.generator(GeneratorsList::HBold1, i)));
}
A_terms.push((alpha, generators.h()));
A_terms.push((alpha, Generators::h()));
let mut A = multiexp(&A_terms);
A_terms.zeroize();

Expand All @@ -222,7 +222,7 @@ impl AggregateRangeStatement {
Some(AggregateRangeProof {
A,
wip: WipStatement::new(generators, A_hat, y)
.prove(rng, transcript, WipWitness::new(a_l, a_r, alpha).unwrap())
.prove(rng, transcript, &Zeroizing::new(WipWitness::new(a_l, a_r, alpha).unwrap()))
.unwrap(),
})
}
Expand Down
16 changes: 5 additions & 11 deletions coins/monero/src/ringct/bulletproofs/plus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ pub(crate) enum GeneratorsList {
// TODO: Table these
#[derive(Clone, Debug)]
pub(crate) struct Generators {
g: EdwardsPoint,

g_bold1: &'static [EdwardsPoint],
h_bold1: &'static [EdwardsPoint],
}
Expand All @@ -47,18 +45,18 @@ impl Generators {
#[allow(clippy::new_without_default)]
pub(crate) fn new() -> Self {
let gens = generators::GENERATORS();
Generators { g: dalek_ff_group::EdwardsPoint(crate::H()), g_bold1: &gens.G, h_bold1: &gens.H }
Generators { g_bold1: &gens.G, h_bold1: &gens.H }
}

pub(crate) fn len(&self) -> usize {
self.g_bold1.len()
}

pub(crate) fn g(&self) -> EdwardsPoint {
self.g
pub(crate) fn g() -> EdwardsPoint {
dalek_ff_group::EdwardsPoint(crate::H())
}

pub(crate) fn h(&self) -> EdwardsPoint {
pub(crate) fn h() -> EdwardsPoint {
EdwardsPoint::generator()
}

Expand All @@ -74,11 +72,7 @@ impl Generators {
let generators = padded_pow_of_2(generators);
assert!(generators <= self.g_bold1.len());

Generators {
g: self.g,
g_bold1: &self.g_bold1[.. generators],
h_bold1: &self.h_bold1[.. generators],
}
Generators { g_bold1: &self.g_bold1[.. generators], h_bold1: &self.h_bold1[.. generators] }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ impl WipStatement {
self,
rng: &mut R,
mut transcript: Scalar,
witness: WipWitness,
witness: &WipWitness,
) -> Option<WipProof> {
let WipStatement { generators, P, mut y } = self;
#[cfg(not(debug_assertions))]
Expand All @@ -198,7 +198,7 @@ impl WipStatement {
if generators.len() != witness.a.len() {
return None;
}
let (g, h) = (generators.g(), generators.h());
let (g, h) = (Generators::g(), Generators::h());
let mut g_bold = vec![];
let mut h_bold = vec![];
for i in 0 .. generators.len() {
Expand Down Expand Up @@ -345,7 +345,7 @@ impl WipStatement {
) -> bool {
let WipStatement { generators, P, y } = self;

let (g, h) = (generators.g(), generators.h());
let (g, h) = (Generators::g(), Generators::h());

// Verify the L/R lengths
{
Expand Down
8 changes: 4 additions & 4 deletions coins/monero/src/ringct/clsag/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ fn core(
msg: &[u8; 32],
D: &EdwardsPoint,
s: &[Scalar],
A_c1: Mode,
A_c1: &Mode,
) -> ((EdwardsPoint, Scalar, Scalar), Scalar) {
let n = ring.len();

Expand Down Expand Up @@ -164,7 +164,7 @@ fn core(
Mode::Verify(c1) => {
start = 0;
end = n;
c = c1;
c = *c1;
}
}

Expand Down Expand Up @@ -226,7 +226,7 @@ impl Clsag {
s.push(random_scalar(rng));
}
let ((D, p, c), c1) =
core(&input.decoys.ring, I, &pseudo_out, msg, &D, &s, Mode::Sign(r, A, AH));
core(&input.decoys.ring, I, &pseudo_out, msg, &D, &s, &Mode::Sign(r, A, AH));

(Clsag { D, s, c1 }, pseudo_out, p, c * z)
}
Expand Down Expand Up @@ -301,7 +301,7 @@ impl Clsag {
Err(ClsagError::InvalidD)?;
}

let (_, c1) = core(ring, I, pseudo_out, msg, &D, &self.s, Mode::Verify(self.c1));
let (_, c1) = core(ring, I, pseudo_out, msg, &D, &self.s, &Mode::Verify(self.c1));
if c1 != self.c1 {
Err(ClsagError::InvalidC1)?;
}
Expand Down
Loading

0 comments on commit 065d314

Please sign in to comment.