From d78c94b2a24604f56dcc01aaea013825518c25a5 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 2 Aug 2019 10:50:32 +0100 Subject: [PATCH 1/8] Move Equihash validator into zcash_primitives --- librustzcash/src/rustzcash.rs | 3 +-- zcash_primitives/src/block.rs | 2 ++ {librustzcash/src => zcash_primitives/src/block}/equihash.rs | 0 3 files changed, 3 insertions(+), 2 deletions(-) rename {librustzcash/src => zcash_primitives/src/block}/equihash.rs (100%) diff --git a/librustzcash/src/rustzcash.rs b/librustzcash/src/rustzcash.rs index 14b5f00..68b7048 100644 --- a/librustzcash/src/rustzcash.rs +++ b/librustzcash/src/rustzcash.rs @@ -45,6 +45,7 @@ use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use zcash_primitives::{ + block::equihash, merkle_tree::CommitmentTreeWitness, note_encryption::sapling_ka_agree, primitives::{Diversifier, Note, PaymentAddress, ProofGenerationKey, ViewingKey}, @@ -58,8 +59,6 @@ use zcash_proofs::{ sapling::{SaplingProvingContext, SaplingVerificationContext}, }; -pub mod equihash; - #[cfg(test)] mod tests; diff --git a/zcash_primitives/src/block.rs b/zcash_primitives/src/block.rs index f2802b4..63e6a05 100644 --- a/zcash_primitives/src/block.rs +++ b/zcash_primitives/src/block.rs @@ -6,6 +6,8 @@ use std::ops::Deref; use crate::serialize::Vector; +pub mod equihash; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct BlockHash(pub [u8; 32]); diff --git a/librustzcash/src/equihash.rs b/zcash_primitives/src/block/equihash.rs similarity index 100% rename from librustzcash/src/equihash.rs rename to zcash_primitives/src/block/equihash.rs From d65fe2cda948195ee48f67923b33935a1a042374 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 2 Aug 2019 11:13:59 +0100 Subject: [PATCH 2/8] Address various clippy warnings/errors in bellman --- bellman/src/domain.rs | 22 ++++++----- bellman/src/gadgets/blake2s.rs | 4 +- bellman/src/gadgets/boolean.rs | 30 +++++++-------- bellman/src/gadgets/multieq.rs | 2 +- bellman/src/gadgets/num.rs | 12 +++--- bellman/src/gadgets/sha256.rs | 6 ++- bellman/src/gadgets/test/mod.rs | 6 +-- bellman/src/gadgets/uint32.rs | 66 +++++++++++++++----------------- bellman/src/groth16/generator.rs | 2 +- bellman/src/groth16/mod.rs | 18 ++++----- bellman/src/groth16/verifier.rs | 2 +- bellman/src/lib.rs | 5 ++- bellman/src/multicore.rs | 2 +- 13 files changed, 90 insertions(+), 87 deletions(-) diff --git a/bellman/src/domain.rs b/bellman/src/domain.rs index 808d2af..d5a86bd 100644 --- a/bellman/src/domain.rs +++ b/bellman/src/domain.rs @@ -26,15 +26,19 @@ pub struct EvaluationDomain> { minv: E::Fr, } -impl> EvaluationDomain { - pub fn as_ref(&self) -> &[G] { +impl> AsRef<[G]> for EvaluationDomain { + fn as_ref(&self) -> &[G] { &self.coeffs } +} - pub fn as_mut(&mut self) -> &mut [G] { +impl> AsMut<[G]> for EvaluationDomain { + fn as_mut(&mut self) -> &mut [G] { &mut self.coeffs } +} +impl> EvaluationDomain { pub fn into_coeffs(self) -> Vec { self.coeffs } @@ -64,9 +68,9 @@ impl> EvaluationDomain { coeffs.resize(m, G::group_zero()); Ok(EvaluationDomain { - coeffs: coeffs, - exp: exp, - omega: omega, + coeffs, + exp, + omega, omegainv: omega.inverse().unwrap(), geninv: E::Fr::multiplicative_generator().inverse().unwrap(), minv: E::Fr::from_str(&format!("{}", m)) @@ -291,7 +295,7 @@ fn serial_fft>(a: &mut [T], omega: &E::Fr, log_n: u let mut m = 1; for _ in 0..log_n { - let w_m = omega.pow(&[(n / (2 * m)) as u64]); + let w_m = omega.pow(&[u64::from(n / (2 * m))]); let mut k = 0; while k < n { @@ -337,12 +341,12 @@ fn parallel_fft>( let omega_step = omega.pow(&[(j as u64) << log_new_n]); let mut elt = E::Fr::one(); - for i in 0..(1 << log_new_n) { + for (i, tmp) in tmp.iter_mut().enumerate() { for s in 0..num_cpus { let idx = (i + (s << log_new_n)) % (1 << log_n); let mut t = a[idx]; t.group_mul_assign(&elt); - tmp[i].group_add_assign(&t); + tmp.group_add_assign(&t); elt.mul_assign(&omega_step); } elt.mul_assign(&omega_j); diff --git a/bellman/src/gadgets/blake2s.rs b/bellman/src/gadgets/blake2s.rs index c5cee23..beefe09 100644 --- a/bellman/src/gadgets/blake2s.rs +++ b/bellman/src/gadgets/blake2s.rs @@ -382,7 +382,7 @@ pub fn blake2s>( blocks.push(this_block); } - if blocks.len() == 0 { + if blocks.is_empty() { blocks.push((0..16).map(|_| UInt32::constant(0)).collect()); } @@ -433,7 +433,7 @@ mod test { let expected = hex!("c59f682376d137f3f255e671e207d1f2374ebe504e9314208a52d9f88d69e8c8"); let mut out = out.into_iter(); - for b in expected.into_iter() { + for b in expected.iter() { for i in 0..8 { let c = out.next().unwrap().get_value().unwrap(); diff --git a/bellman/src/gadgets/boolean.rs b/bellman/src/gadgets/boolean.rs index 414b290..b26bb19 100644 --- a/bellman/src/gadgets/boolean.rs +++ b/bellman/src/gadgets/boolean.rs @@ -60,7 +60,7 @@ impl AllocatedBit { Ok(AllocatedBit { variable: var, - value: value, + value, }) } @@ -93,7 +93,7 @@ impl AllocatedBit { Ok(AllocatedBit { variable: var, - value: value, + value, }) } @@ -302,7 +302,7 @@ pub fn field_into_boolean_vec_le, F: PrimeFie ) -> Result, SynthesisError> { let v = field_into_allocated_bits_le::(cs, value)?; - Ok(v.into_iter().map(|e| Boolean::from(e)).collect()) + Ok(v.into_iter().map(Boolean::from).collect()) } pub fn field_into_allocated_bits_le, F: PrimeField>( @@ -412,24 +412,24 @@ impl Boolean { } pub fn get_value(&self) -> Option { - match self { - &Boolean::Constant(c) => Some(c), - &Boolean::Is(ref v) => v.get_value(), - &Boolean::Not(ref v) => v.get_value().map(|b| !b), + match *self { + Boolean::Constant(c) => Some(c), + Boolean::Is(ref v) => v.get_value(), + Boolean::Not(ref v) => v.get_value().map(|b| !b), } } pub fn lc(&self, one: Variable, coeff: E::Fr) -> LinearCombination { - match self { - &Boolean::Constant(c) => { + match *self { + Boolean::Constant(c) => { if c { LinearCombination::::zero() + (coeff, one) } else { LinearCombination::::zero() } } - &Boolean::Is(ref v) => LinearCombination::::zero() + (coeff, v.get_variable()), - &Boolean::Not(ref v) => { + Boolean::Is(ref v) => LinearCombination::::zero() + (coeff, v.get_variable()), + Boolean::Not(ref v) => { LinearCombination::::zero() + (coeff, one) - (coeff, v.get_variable()) } } @@ -442,10 +442,10 @@ impl Boolean { /// Return a negated interpretation of this boolean. pub fn not(&self) -> Self { - match self { - &Boolean::Constant(c) => Boolean::Constant(!c), - &Boolean::Is(ref v) => Boolean::Not(v.clone()), - &Boolean::Not(ref v) => Boolean::Is(v.clone()), + match *self { + Boolean::Constant(c) => Boolean::Constant(!c), + Boolean::Is(ref v) => Boolean::Not(v.clone()), + Boolean::Not(ref v) => Boolean::Is(v.clone()), } } diff --git a/bellman/src/gadgets/multieq.rs b/bellman/src/gadgets/multieq.rs index 510802d..095017a 100644 --- a/bellman/src/gadgets/multieq.rs +++ b/bellman/src/gadgets/multieq.rs @@ -14,7 +14,7 @@ pub struct MultiEq> { impl> MultiEq { pub fn new(cs: CS) -> Self { MultiEq { - cs: cs, + cs, ops: 0, bits_used: 0, lhs: LinearCombination::zero(), diff --git a/bellman/src/gadgets/num.rs b/bellman/src/gadgets/num.rs index 84843c1..81f4fb3 100644 --- a/bellman/src/gadgets/num.rs +++ b/bellman/src/gadgets/num.rs @@ -78,7 +78,7 @@ impl AllocatedNum { E: Engine, CS: ConstraintSystem, { - assert!(v.len() > 0); + assert!(!v.is_empty()); // Let's keep this simple for now and just AND them all // manually @@ -132,7 +132,7 @@ impl AllocatedNum { current_run.push(a_bit.clone()); result.push(a_bit); } else { - if current_run.len() > 0 { + if !current_run.is_empty() { // This is the start of a run of zeros, but we need // to k-ary AND against `last_run` first. @@ -183,7 +183,7 @@ impl AllocatedNum { cs.enforce(|| "unpacking constraint", |lc| lc, |lc| lc, |_| lc); // Convert into booleans, and reverse for little-endian bit order - Ok(result.into_iter().map(|b| Boolean::from(b)).rev().collect()) + Ok(result.into_iter().map(Boolean::from).rev().collect()) } /// Convert the allocated number into its little-endian representation. @@ -208,7 +208,7 @@ impl AllocatedNum { cs.enforce(|| "unpacking constraint", |lc| lc, |lc| lc, |_| lc); - Ok(bits.into_iter().map(|b| Boolean::from(b)).collect()) + Ok(bits.into_iter().map(Boolean::from).collect()) } pub fn mul(&self, mut cs: CS, other: &Self) -> Result @@ -238,7 +238,7 @@ impl AllocatedNum { ); Ok(AllocatedNum { - value: value, + value, variable: var, }) } @@ -270,7 +270,7 @@ impl AllocatedNum { ); Ok(AllocatedNum { - value: value, + value, variable: var, }) } diff --git a/bellman/src/gadgets/sha256.rs b/bellman/src/gadgets/sha256.rs index cb057f8..e346a71 100644 --- a/bellman/src/gadgets/sha256.rs +++ b/bellman/src/gadgets/sha256.rs @@ -4,6 +4,7 @@ use super::uint32::UInt32; use crate::{ConstraintSystem, SynthesisError}; use pairing::Engine; +#[allow(clippy::unreadable_literal)] const ROUND_CONSTANTS: [u32; 64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, @@ -15,6 +16,7 @@ const ROUND_CONSTANTS: [u32; 64] = [ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; +#[allow(clippy::unreadable_literal)] const IV: [u32; 8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ]; @@ -130,7 +132,7 @@ where Ok(match self { Maybe::Concrete(ref v) => return Ok(v.clone()), Maybe::Deferred(mut v) => { - v.extend(others.into_iter().cloned()); + v.extend(others.iter().cloned()); UInt32::addmany(cs, &v)? } }) @@ -286,7 +288,7 @@ mod test { let expected = hex!("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); let mut out = out_bits.into_iter(); - for b in expected.into_iter() { + for b in expected.iter() { for i in (0..8).rev() { let c = out.next().unwrap().get_value().unwrap(); diff --git a/bellman/src/gadgets/test/mod.rs b/bellman/src/gadgets/test/mod.rs index 58ba040..eed676e 100644 --- a/bellman/src/gadgets/test/mod.rs +++ b/bellman/src/gadgets/test/mod.rs @@ -66,7 +66,7 @@ fn proc_lc(terms: &[(Variable, E::Fr)]) -> BTreeMap TestConstraintSystem { }; let powers_of_two = (0..E::Fr::NUM_BITS) - .map(|i| E::Fr::from_str("2").unwrap().pow(&[i as u64])) + .map(|i| E::Fr::from_str("2").unwrap().pow(&[u64::from(i)])) .collect::>(); let pp = |s: &mut String, lc: &LinearCombination| { @@ -286,7 +286,7 @@ impl TestConstraintSystem { } } - return true; + true } pub fn num_inputs(&self) -> usize { diff --git a/bellman/src/gadgets/uint32.rs b/bellman/src/gadgets/uint32.rs index ef3f44a..3467400 100644 --- a/bellman/src/gadgets/uint32.rs +++ b/bellman/src/gadgets/uint32.rs @@ -33,7 +33,7 @@ impl UInt32 { } UInt32 { - bits: bits, + bits, value: Some(value), } } @@ -69,10 +69,7 @@ impl UInt32 { }) .collect::, SynthesisError>>()?; - Ok(UInt32 { - bits: bits, - value: value, - }) + Ok(UInt32 { bits, value }) } pub fn into_bits_be(&self) -> Vec { @@ -98,7 +95,7 @@ impl UInt32 { } UInt32 { - value: value, + value, bits: bits.iter().rev().cloned().collect(), } } @@ -119,20 +116,20 @@ impl UInt32 { for b in new_bits.iter().rev() { value.as_mut().map(|v| *v <<= 1); - match b { - &Boolean::Constant(b) => { + match *b { + Boolean::Constant(b) => { if b { value.as_mut().map(|v| *v |= 1); } } - &Boolean::Is(ref b) => match b.get_value() { + Boolean::Is(ref b) => match b.get_value() { Some(true) => { value.as_mut().map(|v| *v |= 1); } Some(false) => {} None => value = None, }, - &Boolean::Not(ref b) => match b.get_value() { + Boolean::Not(ref b) => match b.get_value() { Some(false) => { value.as_mut().map(|v| *v |= 1); } @@ -143,7 +140,7 @@ impl UInt32 { } UInt32 { - value: value, + value, bits: new_bits, } } @@ -215,7 +212,7 @@ impl UInt32 { .collect::>()?; Ok(UInt32 { - bits: bits, + bits, value: new_value, }) } @@ -274,7 +271,7 @@ impl UInt32 { .collect::>()?; Ok(UInt32 { - bits: bits, + bits, value: new_value, }) } @@ -294,7 +291,7 @@ impl UInt32 { // Compute the maximum value of the sum so we allocate enough bits for // the result - let mut max_value = (operands.len() as u64) * (u32::max_value() as u64); + let mut max_value = (operands.len() as u64) * (u64::from(u32::max_value())); // Keep track of the resulting value let mut result_value = Some(0u64); @@ -310,7 +307,7 @@ impl UInt32 { // Accumulate the value match op.value { Some(val) => { - result_value.as_mut().map(|v| *v += val as u64); + result_value.as_mut().map(|v| *v += u64::from(val)); } None => { // If any of our operands have unknown value, we won't @@ -408,8 +405,8 @@ mod test { let b = UInt32::from_bits_be(&v); for (i, bit) in b.bits.iter().enumerate() { - match bit { - &Boolean::Constant(bit) => { + match *bit { + Boolean::Constant(bit) => { assert!(bit == ((b.value.unwrap() >> i) & 1 == 1)); } _ => unreachable!(), @@ -443,8 +440,8 @@ mod test { let b = UInt32::from_bits(&v); for (i, bit) in b.bits.iter().enumerate() { - match bit { - &Boolean::Constant(bit) => { + match *bit { + Boolean::Constant(bit) => { assert!(bit == ((b.value.unwrap() >> i) & 1 == 1)); } _ => unreachable!(), @@ -491,14 +488,14 @@ mod test { assert!(r.value == Some(expected)); for b in r.bits.iter() { - match b { - &Boolean::Is(ref b) => { + match *b { + Boolean::Is(ref b) => { assert!(b.get_value().unwrap() == (expected & 1 == 1)); } - &Boolean::Not(ref b) => { + Boolean::Not(ref b) => { assert!(!b.get_value().unwrap() == (expected & 1 == 1)); } - &Boolean::Constant(b) => { + Boolean::Constant(b) => { assert!(b == (expected & 1 == 1)); } } @@ -538,10 +535,10 @@ mod test { assert!(r.value == Some(expected)); for b in r.bits.iter() { - match b { - &Boolean::Is(_) => panic!(), - &Boolean::Not(_) => panic!(), - &Boolean::Constant(b) => { + match *b { + Boolean::Is(_) => panic!(), + Boolean::Not(_) => panic!(), + Boolean::Constant(b) => { assert!(b == (expected & 1 == 1)); } } @@ -576,8 +573,7 @@ mod test { let r = a_bit.xor(cs.namespace(|| "xor"), &b_bit).unwrap(); let r = { let mut cs = MultiEq::new(&mut cs); - let r = UInt32::addmany(cs.namespace(|| "addition"), &[r, c_bit, d_bit]).unwrap(); - r + UInt32::addmany(cs.namespace(|| "addition"), &[r, c_bit, d_bit]).unwrap() }; assert!(cs.is_satisfied()); @@ -585,14 +581,14 @@ mod test { assert!(r.value == Some(expected)); for b in r.bits.iter() { - match b { - &Boolean::Is(ref b) => { + match *b { + Boolean::Is(ref b) => { assert!(b.get_value().unwrap() == (expected & 1 == 1)); } - &Boolean::Not(ref b) => { + Boolean::Not(ref b) => { assert!(!b.get_value().unwrap() == (expected & 1 == 1)); } - &Boolean::Constant(_) => unreachable!(), + Boolean::Constant(_) => unreachable!(), } expected >>= 1; @@ -628,8 +624,8 @@ mod test { let mut tmp = num; for b in &b.bits { - match b { - &Boolean::Constant(b) => { + match *b { + Boolean::Constant(b) => { assert_eq!(b, tmp & 1 == 1); } _ => unreachable!(), diff --git a/bellman/src/groth16/generator.rs b/bellman/src/groth16/generator.rs index 2ece8b7..7ca6c9a 100644 --- a/bellman/src/groth16/generator.rs +++ b/bellman/src/groth16/generator.rs @@ -451,7 +451,7 @@ where }; Ok(Parameters { - vk: vk, + vk, h: Arc::new(h.into_iter().map(|e| e.into_affine()).collect()), l: Arc::new(l.into_iter().map(|e| e.into_affine()).collect()), diff --git a/bellman/src/groth16/mod.rs b/bellman/src/groth16/mod.rs index 9fa3bc8..44c6f22 100644 --- a/bellman/src/groth16/mod.rs +++ b/bellman/src/groth16/mod.rs @@ -90,7 +90,7 @@ impl Proof { } })?; - Ok(Proof { a: a, b: b, c: c }) + Ok(Proof { a, b, c }) } } @@ -208,13 +208,13 @@ impl VerifyingKey { } Ok(VerifyingKey { - alpha_g1: alpha_g1, - beta_g1: beta_g1, - beta_g2: beta_g2, - gamma_g2: gamma_g2, - delta_g1: delta_g1, - delta_g2: delta_g2, - ic: ic, + alpha_g1, + beta_g1, + beta_g2, + gamma_g2, + delta_g1, + delta_g2, + ic, }) } } @@ -376,7 +376,7 @@ impl Parameters { } Ok(Parameters { - vk: vk, + vk, h: Arc::new(h), l: Arc::new(l), a: Arc::new(a), diff --git a/bellman/src/groth16/verifier.rs b/bellman/src/groth16/verifier.rs index 065a3b0..5bc0581 100644 --- a/bellman/src/groth16/verifier.rs +++ b/bellman/src/groth16/verifier.rs @@ -49,7 +49,7 @@ pub fn verify_proof<'a, E: Engine>( (&acc.into_affine().prepare(), &pvk.neg_gamma_g2), (&proof.c.prepare(), &pvk.neg_delta_g2), ] - .into_iter(), + .iter(), )) .unwrap() == pvk.alpha_g1_beta_g2) diff --git a/bellman/src/lib.rs b/bellman/src/lib.rs index a75c85f..1445107 100644 --- a/bellman/src/lib.rs +++ b/bellman/src/lib.rs @@ -91,6 +91,7 @@ impl Add<(E::Fr, Variable)> for LinearCombination { impl Sub<(E::Fr, Variable)> for LinearCombination { type Output = LinearCombination; + #[allow(clippy::suspicious_arithmetic_impl)] fn sub(self, (mut coeff, var): (E::Fr, Variable)) -> LinearCombination { coeff.negate(); @@ -213,7 +214,7 @@ impl Error for SynthesisError { impl fmt::Display for SynthesisError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - if let &SynthesisError::IoError(ref e) = self { + if let SynthesisError::IoError(ref e) = *self { write!(f, "I/O error: ")?; e.fmt(f) } else { @@ -278,7 +279,7 @@ pub trait ConstraintSystem: Sized { fn get_root(&mut self) -> &mut Self::Root; /// Begin a namespace for this constraint system. - fn namespace<'a, NR, N>(&'a mut self, name_fn: N) -> Namespace<'a, E, Self::Root> + fn namespace(&mut self, name_fn: N) -> Namespace<'_, E, Self::Root> where NR: Into, N: FnOnce() -> NR, diff --git a/bellman/src/multicore.rs b/bellman/src/multicore.rs index e8b2dae..7ebc89a 100644 --- a/bellman/src/multicore.rs +++ b/bellman/src/multicore.rs @@ -23,7 +23,7 @@ mod implementation { // CPUs configured. pub(crate) fn new_with_cpus(cpus: usize) -> Worker { Worker { - cpus: cpus, + cpus, pool: CpuPool::new(cpus), } } From 3a8efd9e677ebfe6de7669b865a780ec89caabd6 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 2 Aug 2019 11:25:00 +0100 Subject: [PATCH 3/8] Address various clippy warnings/errors in zcash_primitives --- zcash_primitives/src/block.rs | 2 +- zcash_primitives/src/block/equihash.rs | 22 ++++------ zcash_primitives/src/constants.rs | 18 ++++---- zcash_primitives/src/jubjub/edwards.rs | 12 +++--- zcash_primitives/src/jubjub/fs.rs | 4 +- zcash_primitives/src/jubjub/mod.rs | 4 +- zcash_primitives/src/jubjub/montgomery.rs | 15 ++++--- zcash_primitives/src/keys.rs | 6 +-- zcash_primitives/src/merkle_tree.rs | 6 ++- zcash_primitives/src/note_encryption.rs | 6 +-- zcash_primitives/src/primitives.rs | 9 ++-- zcash_primitives/src/sapling.rs | 4 +- zcash_primitives/src/serialize.rs | 2 +- zcash_primitives/src/transaction/builder.rs | 6 +-- .../src/transaction/components.rs | 41 ++++++++----------- zcash_primitives/src/transaction/mod.rs | 23 ++++++----- zcash_primitives/src/transaction/sighash.rs | 14 +++---- zcash_primitives/src/zip32.rs | 10 ++--- 18 files changed, 97 insertions(+), 107 deletions(-) diff --git a/zcash_primitives/src/block.rs b/zcash_primitives/src/block.rs index 63e6a05..28a7441 100644 --- a/zcash_primitives/src/block.rs +++ b/zcash_primitives/src/block.rs @@ -13,7 +13,7 @@ pub struct BlockHash(pub [u8; 32]); impl fmt::Display for BlockHash { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut data = self.0.clone(); + let mut data = self.0; data.reverse(); formatter.write_str(&hex::encode(data)) } diff --git a/zcash_primitives/src/block/equihash.rs b/zcash_primitives/src/block/equihash.rs index d251bc1..9710dc9 100644 --- a/zcash_primitives/src/block/equihash.rs +++ b/zcash_primitives/src/block/equihash.rs @@ -60,10 +60,7 @@ impl Node { indices.extend(a.indices.iter()); indices }; - Node { - hash: hash, - indices: indices, - } + Node { hash, indices } } fn from_children_ref(a: &Node, b: &Node, trim: usize) -> Self { @@ -82,10 +79,7 @@ impl Node { indices.extend(b.indices.iter()); indices.extend(a.indices.iter()); } - Node { - hash: hash, - indices: indices, - } + Node { hash, indices } } fn indices_before(&self, other: &Node) -> bool { @@ -141,7 +135,7 @@ fn expand_array(vin: &[u8], bit_len: usize, byte_pad: usize) -> Vec { let mut j = 0; for b in vin { - acc_value = (acc_value << 8) | *b as u32; + acc_value = (acc_value << 8) | u32::from(*b); acc_bits += 8; // When we have bit_len or more bits in the accumulator, write the next @@ -197,7 +191,7 @@ fn distinct_indices(a: &Node, b: &Node) -> bool { } } } - return true; + true } fn validate_subtrees(p: &Params, a: &Node, b: &Node) -> bool { @@ -222,7 +216,7 @@ pub fn is_valid_solution_iterative( nonce: &[u8], indices: &[u32], ) -> bool { - let p = Params { n: n, k: k }; + let p = Params { n, k }; let mut state = initialise_state(p.n, p.k, p.hash_output()); state.update(input); @@ -249,7 +243,7 @@ pub fn is_valid_solution_iterative( } assert!(rows.len() == 1); - return rows[0].is_zero(hash_len); + rows[0].is_zero(hash_len) } fn tree_validator(p: &Params, state: &Blake2bState, indices: &[u32]) -> Option { @@ -281,7 +275,7 @@ pub fn is_valid_solution_recursive( nonce: &[u8], indices: &[u32], ) -> bool { - let p = Params { n: n, k: k }; + let p = Params { n, k }; let mut state = initialise_state(p.n, p.k, p.hash_output()); state.update(input); @@ -297,7 +291,7 @@ pub fn is_valid_solution_recursive( } pub fn is_valid_solution(n: u32, k: u32, input: &[u8], nonce: &[u8], soln: &[u8]) -> bool { - let p = Params { n: n, k: k }; + let p = Params { n, k }; let indices = indices_from_minimal(soln, p.collision_bit_length()); // Recursive validation is faster diff --git a/zcash_primitives/src/constants.rs b/zcash_primitives/src/constants.rs index c21184d..39d55f3 100644 --- a/zcash_primitives/src/constants.rs +++ b/zcash_primitives/src/constants.rs @@ -2,31 +2,31 @@ /// This is chosen to be some random string that we couldn't have anticipated when we designed /// the algorithm, for rigidity purposes. /// We deliberately use an ASCII hex string of 32 bytes here. -pub const GH_FIRST_BLOCK: &'static [u8; 64] = +pub const GH_FIRST_BLOCK: &[u8; 64] = b"096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0"; // BLAKE2s invocation personalizations /// BLAKE2s Personalization for CRH^ivk = BLAKE2s(ak | nk) -pub const CRH_IVK_PERSONALIZATION: &'static [u8; 8] = b"Zcashivk"; +pub const CRH_IVK_PERSONALIZATION: &[u8; 8] = b"Zcashivk"; /// BLAKE2s Personalization for PRF^nf = BLAKE2s(nk | rho) -pub const PRF_NF_PERSONALIZATION: &'static [u8; 8] = b"Zcash_nf"; +pub const PRF_NF_PERSONALIZATION: &[u8; 8] = b"Zcash_nf"; // Group hash personalizations /// BLAKE2s Personalization for Pedersen hash generators. -pub const PEDERSEN_HASH_GENERATORS_PERSONALIZATION: &'static [u8; 8] = b"Zcash_PH"; +pub const PEDERSEN_HASH_GENERATORS_PERSONALIZATION: &[u8; 8] = b"Zcash_PH"; /// BLAKE2s Personalization for the group hash for key diversification -pub const KEY_DIVERSIFICATION_PERSONALIZATION: &'static [u8; 8] = b"Zcash_gd"; +pub const KEY_DIVERSIFICATION_PERSONALIZATION: &[u8; 8] = b"Zcash_gd"; /// BLAKE2s Personalization for the spending key base point -pub const SPENDING_KEY_GENERATOR_PERSONALIZATION: &'static [u8; 8] = b"Zcash_G_"; +pub const SPENDING_KEY_GENERATOR_PERSONALIZATION: &[u8; 8] = b"Zcash_G_"; /// BLAKE2s Personalization for the proof generation key base point -pub const PROOF_GENERATION_KEY_BASE_GENERATOR_PERSONALIZATION: &'static [u8; 8] = b"Zcash_H_"; +pub const PROOF_GENERATION_KEY_BASE_GENERATOR_PERSONALIZATION: &[u8; 8] = b"Zcash_H_"; /// BLAKE2s Personalization for the value commitment generator for the value -pub const VALUE_COMMITMENT_GENERATOR_PERSONALIZATION: &'static [u8; 8] = b"Zcash_cv"; +pub const VALUE_COMMITMENT_GENERATOR_PERSONALIZATION: &[u8; 8] = b"Zcash_cv"; /// BLAKE2s Personalization for the nullifier position generator (for computing rho) -pub const NULLIFIER_POSITION_IN_TREE_GENERATOR_PERSONALIZATION: &'static [u8; 8] = b"Zcash_J_"; +pub const NULLIFIER_POSITION_IN_TREE_GENERATOR_PERSONALIZATION: &[u8; 8] = b"Zcash_J_"; diff --git a/zcash_primitives/src/jubjub/edwards.rs b/zcash_primitives/src/jubjub/edwards.rs index b3cdd64..233bfb7 100644 --- a/zcash_primitives/src/jubjub/edwards.rs +++ b/zcash_primitives/src/jubjub/edwards.rs @@ -132,9 +132,9 @@ impl Point { t.mul_assign(&y); Some(Point { - x: x, - y: y, - t: t, + x, + y, + t, z: E::Fr::one(), _marker: PhantomData, }) @@ -277,8 +277,8 @@ impl Point { Point { x: u, y: v, - t: t, - z: z, + t, + z, _marker: PhantomData, } } @@ -412,7 +412,7 @@ impl Point { b.mul_assign(&other.y); // C = d * t1 * t2 - let mut c = params.edwards_d().clone(); + let mut c = *params.edwards_d(); c.mul_assign(&self.t); c.mul_assign(&other.t); diff --git a/zcash_primitives/src/jubjub/fs.rs b/zcash_primitives/src/jubjub/fs.rs index 0d1578e..7cf4d79 100644 --- a/zcash_primitives/src/jubjub/fs.rs +++ b/zcash_primitives/src/jubjub/fs.rs @@ -321,8 +321,8 @@ impl Field for Fs { loop { let mut tmp = { let mut repr = [0u64; 4]; - for i in 0..4 { - repr[i] = rng.next_u64(); + for limb in &mut repr { + *limb = rng.next_u64(); } Fs(FsRepr(repr)) }; diff --git a/zcash_primitives/src/jubjub/mod.rs b/zcash_primitives/src/jubjub/mod.rs index 8d9e227..624592e 100644 --- a/zcash_primitives/src/jubjub/mod.rs +++ b/zcash_primitives/src/jubjub/mod.rs @@ -199,9 +199,9 @@ impl JubjubBls12 { ) .unwrap(), // A = 40962 - montgomery_a: montgomery_a, + montgomery_a, // 2A = 2.A - montgomery_2a: montgomery_2a, + montgomery_2a, // scaling factor = sqrt(4 / (a - d)) scale: Fr::from_str( "17814886934372412843466061268024708274627479829237077604635722030778476050649", diff --git a/zcash_primitives/src/jubjub/montgomery.rs b/zcash_primitives/src/jubjub/montgomery.rs index e0bc4bf..0ebedd2 100644 --- a/zcash_primitives/src/jubjub/montgomery.rs +++ b/zcash_primitives/src/jubjub/montgomery.rs @@ -64,12 +64,12 @@ impl Point { y.negate(); } - return Some(Point { - x: x, - y: y, + Some(Point { + x, + y, infinity: false, _marker: PhantomData, - }); + }) } None => None, } @@ -88,9 +88,8 @@ impl Point { let x = E::Fr::random(rng); let sign = rng.next_u32() % 2 != 0; - match Self::get_for_x(x, sign, params) { - Some(p) => return p, - None => {} + if let Some(p) = Self::get_for_x(x, sign, params) { + return p; } } } @@ -214,7 +213,7 @@ impl Point { let mut delta = E::Fr::one(); { - let mut tmp = params.montgomery_a().clone(); + let mut tmp = *params.montgomery_a(); tmp.mul_assign(&self.x); tmp.double(); delta.add_assign(&tmp); diff --git a/zcash_primitives/src/keys.rs b/zcash_primitives/src/keys.rs index ad86059..8c8a4b1 100644 --- a/zcash_primitives/src/keys.rs +++ b/zcash_primitives/src/keys.rs @@ -10,11 +10,11 @@ use blake2b_simd::{Hash as Blake2bHash, Params as Blake2bParams}; use ff::{PrimeField, PrimeFieldRepr}; use std::io::{self, Read, Write}; -pub const PRF_EXPAND_PERSONALIZATION: &'static [u8; 16] = b"Zcash_ExpandSeed"; +pub const PRF_EXPAND_PERSONALIZATION: &[u8; 16] = b"Zcash_ExpandSeed"; /// PRF^expand(sk, t) := BLAKE2b-512("Zcash_ExpandSeed", sk || t) pub fn prf_expand(sk: &[u8], t: &[u8]) -> Blake2bHash { - prf_expand_vec(sk, &vec![t]) + prf_expand_vec(sk, &[t]) } pub fn prf_expand_vec(sk: &[u8], ts: &[&[u8]]) -> Blake2bHash { @@ -111,7 +111,7 @@ impl Clone for FullViewingKey { ak: self.vk.ak.clone(), nk: self.vk.nk.clone(), }, - ovk: self.ovk.clone(), + ovk: self.ovk, } } } diff --git a/zcash_primitives/src/merkle_tree.rs b/zcash_primitives/src/merkle_tree.rs index 288ad21..2721ab6 100644 --- a/zcash_primitives/src/merkle_tree.rs +++ b/zcash_primitives/src/merkle_tree.rs @@ -486,8 +486,10 @@ impl CommitmentTreeWitness { // Given the position, let's finish constructing the authentication // path let mut tmp = position; - for i in 0..depth { - auth_path[i].as_mut().map(|p| p.1 = (tmp & 1) == 1); + for entry in auth_path.iter_mut() { + if let Some(p) = entry { + p.1 = (tmp & 1) == 1; + } tmp >>= 1; } diff --git a/zcash_primitives/src/note_encryption.rs b/zcash_primitives/src/note_encryption.rs index 5412945..0d0e83a 100644 --- a/zcash_primitives/src/note_encryption.rs +++ b/zcash_primitives/src/note_encryption.rs @@ -19,8 +19,8 @@ use std::str; use crate::{keys::OutgoingViewingKey, JUBJUB}; -pub const KDF_SAPLING_PERSONALIZATION: &'static [u8; 16] = b"Zcash_SaplingKDF"; -pub const PRF_OCK_PERSONALIZATION: &'static [u8; 16] = b"Zcash_Derive_ock"; +pub const KDF_SAPLING_PERSONALIZATION: &[u8; 16] = b"Zcash_SaplingKDF"; +pub const PRF_OCK_PERSONALIZATION: &[u8; 16] = b"Zcash_Derive_ock"; const COMPACT_NOTE_SIZE: usize = ( 1 + // version @@ -85,7 +85,7 @@ impl Default for Memo { impl PartialEq for Memo { fn eq(&self, rhs: &Memo) -> bool { - &self.0[..] == &rhs.0[..] + self.0[..] == rhs.0[..] } } diff --git a/zcash_primitives/src/primitives.rs b/zcash_primitives/src/primitives.rs index 10a6d6b..38a056a 100644 --- a/zcash_primitives/src/primitives.rs +++ b/zcash_primitives/src/primitives.rs @@ -97,10 +97,7 @@ impl ViewingKey { diversifier.g_d(params).map(|g_d| { let pk_d = g_d.mul(self.ivk(), params); - PaymentAddress { - pk_d: pk_d, - diversifier: diversifier, - } + PaymentAddress { pk_d, diversifier } }) } } @@ -145,9 +142,9 @@ impl PaymentAddress { params: &E::Params, ) -> Option> { self.g_d(params).map(|g_d| Note { - value: value, + value, r: randomness, - g_d: g_d, + g_d, pk_d: self.pk_d.clone(), }) } diff --git a/zcash_primitives/src/sapling.rs b/zcash_primitives/src/sapling.rs index d84eec2..8b8ef88 100644 --- a/zcash_primitives/src/sapling.rs +++ b/zcash_primitives/src/sapling.rs @@ -37,9 +37,9 @@ pub fn merkle_hash(depth: usize, lhs: &FrRepr, rhs: &FrRepr) -> FrRepr { pedersen_hash::( Personalization::MerkleTree(depth), lhs.iter() - .map(|&x| x) + .copied() .take(Fr::NUM_BITS as usize) - .chain(rhs.iter().map(|&x| x).take(Fr::NUM_BITS as usize)), + .chain(rhs.iter().copied().take(Fr::NUM_BITS as usize)), &JUBJUB, ) .into_xy() diff --git a/zcash_primitives/src/serialize.rs b/zcash_primitives/src/serialize.rs index 41778dc..4e0fb93 100644 --- a/zcash_primitives/src/serialize.rs +++ b/zcash_primitives/src/serialize.rs @@ -70,7 +70,7 @@ impl Vector { F: Fn(&mut R) -> io::Result, { let count = CompactSize::read(&mut reader)?; - (0..count).into_iter().map(|_| func(&mut reader)).collect() + (0..count).map(|_| func(&mut reader)).collect() } pub fn write(mut writer: W, vec: &[E], func: F) -> io::Result<()> diff --git a/zcash_primitives/src/transaction/builder.rs b/zcash_primitives/src/transaction/builder.rs index a5df4c8..1f30f99 100644 --- a/zcash_primitives/src/transaction/builder.rs +++ b/zcash_primitives/src/transaction/builder.rs @@ -153,7 +153,7 @@ impl TransactionMetadata { /// they added (via the first call to [`Builder::add_sapling_spend`]) is the first /// [`SpendDescription`] in the transaction. pub fn spend_index(&self, n: usize) -> Option { - self.spend_indices.get(n).map(|i| *i) + self.spend_indices.get(n).copied() } /// Returns the index within the transaction of the [`OutputDescription`] corresponding @@ -164,7 +164,7 @@ impl TransactionMetadata { /// they added (via the first call to [`Builder::add_sapling_output`]) is the first /// [`OutputDescription`] in the transaction. pub fn output_index(&self, n: usize) -> Option { - self.output_indices.get(n).map(|i| *i) + self.output_indices.get(n).copied() } } @@ -414,7 +414,7 @@ impl Builder { self.mtx.shielded_spends.push(SpendDescription { cv, - anchor: anchor, + anchor, nullifier, rk, zkproof, diff --git a/zcash_primitives/src/transaction/components.rs b/zcash_primitives/src/transaction/components.rs index 001ff42..c0410c4 100644 --- a/zcash_primitives/src/transaction/components.rs +++ b/zcash_primitives/src/transaction/components.rs @@ -166,12 +166,10 @@ impl SpendDescription { writer.write_all(&self.zkproof)?; match self.spend_auth_sig { Some(sig) => sig.write(&mut writer), - None => { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "Missing spend auth signature", - )); - } + None => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Missing spend auth signature", + )), } } } @@ -347,23 +345,20 @@ impl JSDescription { .map(|mac| reader.read_exact(mac)) .collect::>()?; - let proof = match use_groth { - true => { - // Consensus rules (§4.3): - // - Canonical encoding is enforced in librustzcash_sprout_verify() - // - Proof validity is enforced in librustzcash_sprout_verify() - let mut proof = [0; GROTH_PROOF_SIZE]; - reader.read_exact(&mut proof)?; - SproutProof::Groth(proof) - } - false => { - // Consensus rules (§4.3): - // - Canonical encoding is enforced by PHGRProof in zcashd - // - Proof validity is enforced by JSDescription::Verify() in zcashd - let mut proof = [0; PHGR_PROOF_SIZE]; - reader.read_exact(&mut proof)?; - SproutProof::PHGR(proof) - } + let proof = if use_groth { + // Consensus rules (§4.3): + // - Canonical encoding is enforced in librustzcash_sprout_verify() + // - Proof validity is enforced in librustzcash_sprout_verify() + let mut proof = [0; GROTH_PROOF_SIZE]; + reader.read_exact(&mut proof)?; + SproutProof::Groth(proof) + } else { + // Consensus rules (§4.3): + // - Canonical encoding is enforced by PHGRProof in zcashd + // - Proof validity is enforced by JSDescription::Verify() in zcashd + let mut proof = [0; PHGR_PROOF_SIZE]; + reader.read_exact(&mut proof)?; + SproutProof::PHGR(proof) }; let mut ciphertexts = [[0; 601]; ZC_NUM_JS_OUTPUTS]; diff --git a/zcash_primitives/src/transaction/mod.rs b/zcash_primitives/src/transaction/mod.rs index 567d689..10e935b 100644 --- a/zcash_primitives/src/transaction/mod.rs +++ b/zcash_primitives/src/transaction/mod.rs @@ -29,7 +29,7 @@ pub struct TxId(pub [u8; 32]); impl fmt::Display for TxId { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut data = self.0.clone(); + let mut data = self.0; data.reverse(); formatter.write_str(&hex::encode(data)) } @@ -164,9 +164,10 @@ impl Transaction { let overwintered = (header >> 31) == 1; let version = header & 0x7FFFFFFF; - let version_group_id = match overwintered { - true => reader.read_u32::()?, - false => 0, + let version_group_id = if overwintered { + reader.read_u32::()? + } else { + 0 }; let is_overwinter_v3 = overwintered @@ -185,9 +186,10 @@ impl Transaction { let vin = Vector::read(&mut reader, TxIn::read)?; let vout = Vector::read(&mut reader, TxOut::read)?; let lock_time = reader.read_u32::()?; - let expiry_height = match is_overwinter_v3 || is_sapling_v4 { - true => reader.read_u32::()?, - false => 0, + let expiry_height = if is_overwinter_v3 || is_sapling_v4 { + reader.read_u32::()? + } else { + 0 }; let (value_balance, shielded_spends, shielded_outputs) = if is_sapling_v4 { @@ -223,9 +225,10 @@ impl Transaction { }; let binding_sig = - match is_sapling_v4 && !(shielded_spends.is_empty() && shielded_outputs.is_empty()) { - true => Some(Signature::read(&mut reader)?), - false => None, + if is_sapling_v4 && !(shielded_spends.is_empty() && shielded_outputs.is_empty()) { + Some(Signature::read(&mut reader)?) + } else { + None }; Transaction::from_data(TransactionData { diff --git a/zcash_primitives/src/transaction/sighash.rs b/zcash_primitives/src/transaction/sighash.rs index 1b05658..41c6da2 100644 --- a/zcash_primitives/src/transaction/sighash.rs +++ b/zcash_primitives/src/transaction/sighash.rs @@ -9,13 +9,13 @@ use super::{ }; use crate::legacy::Script; -const ZCASH_SIGHASH_PERSONALIZATION_PREFIX: &'static [u8; 12] = b"ZcashSigHash"; -const ZCASH_PREVOUTS_HASH_PERSONALIZATION: &'static [u8; 16] = b"ZcashPrevoutHash"; -const ZCASH_SEQUENCE_HASH_PERSONALIZATION: &'static [u8; 16] = b"ZcashSequencHash"; -const ZCASH_OUTPUTS_HASH_PERSONALIZATION: &'static [u8; 16] = b"ZcashOutputsHash"; -const ZCASH_JOINSPLITS_HASH_PERSONALIZATION: &'static [u8; 16] = b"ZcashJSplitsHash"; -const ZCASH_SHIELDED_SPENDS_HASH_PERSONALIZATION: &'static [u8; 16] = b"ZcashSSpendsHash"; -const ZCASH_SHIELDED_OUTPUTS_HASH_PERSONALIZATION: &'static [u8; 16] = b"ZcashSOutputHash"; +const ZCASH_SIGHASH_PERSONALIZATION_PREFIX: &[u8; 12] = b"ZcashSigHash"; +const ZCASH_PREVOUTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZcashPrevoutHash"; +const ZCASH_SEQUENCE_HASH_PERSONALIZATION: &[u8; 16] = b"ZcashSequencHash"; +const ZCASH_OUTPUTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZcashOutputsHash"; +const ZCASH_JOINSPLITS_HASH_PERSONALIZATION: &[u8; 16] = b"ZcashJSplitsHash"; +const ZCASH_SHIELDED_SPENDS_HASH_PERSONALIZATION: &[u8; 16] = b"ZcashSSpendsHash"; +const ZCASH_SHIELDED_OUTPUTS_HASH_PERSONALIZATION: &[u8; 16] = b"ZcashSOutputHash"; pub const SIGHASH_ALL: u32 = 1; const SIGHASH_NONE: u32 = 2; diff --git a/zcash_primitives/src/zip32.rs b/zcash_primitives/src/zip32.rs index 8788809..7cd6148 100644 --- a/zcash_primitives/src/zip32.rs +++ b/zcash_primitives/src/zip32.rs @@ -16,8 +16,8 @@ use crate::{ JUBJUB, }; -pub const ZIP32_SAPLING_MASTER_PERSONALIZATION: &'static [u8; 16] = b"ZcashIP32Sapling"; -pub const ZIP32_SAPLING_FVFP_PERSONALIZATION: &'static [u8; 16] = b"ZcashSaplingFVFP"; +pub const ZIP32_SAPLING_MASTER_PERSONALIZATION: &[u8; 16] = b"ZcashIP32Sapling"; +pub const ZIP32_SAPLING_FVFP_PERSONALIZATION: &[u8; 16] = b"ZcashSaplingFVFP"; // Common helper functions @@ -83,9 +83,9 @@ impl ChildIndex { } fn to_index(&self) -> u32 { - match self { - &ChildIndex::Hardened(i) => i + (1 << 31), - &ChildIndex::NonHardened(i) => i, + match *self { + ChildIndex::Hardened(i) => i + (1 << 31), + ChildIndex::NonHardened(i) => i, } } } From 91541675e200bfc9f51d4327a4927fda846a2597 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 2 Aug 2019 11:40:10 +0100 Subject: [PATCH 4/8] Address various clippy warnings/errors in zcash_proofs --- zcash_proofs/src/circuit/ecc.rs | 16 +++++----- zcash_proofs/src/circuit/pedersen_hash.rs | 4 +-- zcash_proofs/src/circuit/sapling.rs | 6 ++-- zcash_proofs/src/circuit/sprout/input.rs | 4 +-- zcash_proofs/src/circuit/sprout/mod.rs | 37 +++++++++-------------- zcash_proofs/src/circuit/sprout/output.rs | 4 +-- zcash_proofs/src/hashreader.rs | 2 +- zcash_proofs/src/sapling/prover.rs | 12 ++++---- 8 files changed, 39 insertions(+), 46 deletions(-) diff --git a/zcash_proofs/src/circuit/ecc.rs b/zcash_proofs/src/circuit/ecc.rs index 4c07829..76b837d 100644 --- a/zcash_proofs/src/circuit/ecc.rs +++ b/zcash_proofs/src/circuit/ecc.rs @@ -41,16 +41,16 @@ where { let chunk_a = chunk .get(0) - .map(|e| e.clone()) - .unwrap_or(Boolean::constant(false)); + .cloned() + .unwrap_or_else(|| Boolean::constant(false)); let chunk_b = chunk .get(1) - .map(|e| e.clone()) - .unwrap_or(Boolean::constant(false)); + .cloned() + .unwrap_or_else(|| Boolean::constant(false)); let chunk_c = chunk .get(2) - .map(|e| e.clone()) - .unwrap_or(Boolean::constant(false)); + .cloned() + .unwrap_or_else(|| Boolean::constant(false)); let (x, y) = lookup3_xy( cs.namespace(|| format!("window table lookup {}", i)), @@ -58,7 +58,7 @@ where window, )?; - let p = EdwardsPoint { x: x, y: y }; + let p = EdwardsPoint { x, y }; if result.is_none() { result = Some(p); @@ -570,7 +570,7 @@ impl MontgomeryPoint { /// on the curve. Useful for constants and /// window table lookups. pub fn interpret_unchecked(x: Num, y: Num) -> Self { - MontgomeryPoint { x: x, y: y } + MontgomeryPoint { x, y } } /// Performs an affine point addition, not defined for diff --git a/zcash_proofs/src/circuit/pedersen_hash.rs b/zcash_proofs/src/circuit/pedersen_hash.rs index 326d3ce..e77d28b 100644 --- a/zcash_proofs/src/circuit/pedersen_hash.rs +++ b/zcash_proofs/src/circuit/pedersen_hash.rs @@ -9,7 +9,7 @@ fn get_constant_bools(person: &Personalization) -> Vec { person .get_bits() .into_iter() - .map(|e| Boolean::constant(e)) + .map(Boolean::constant) .collect() } @@ -65,7 +65,7 @@ where segment_windows = &segment_windows[1..]; - if segment_windows.len() == 0 { + if segment_windows.is_empty() { break; } diff --git a/zcash_proofs/src/circuit/sapling.rs b/zcash_proofs/src/circuit/sapling.rs index 0554ff4..d43a628 100644 --- a/zcash_proofs/src/circuit/sapling.rs +++ b/zcash_proofs/src/circuit/sapling.rs @@ -150,7 +150,7 @@ impl<'a, E: JubjubEngine> Circuit for Spend<'a, E> { // Witness nsk as bits let nsk = boolean::field_into_boolean_vec_le( cs.namespace(|| "nsk"), - self.proof_generation_key.as_ref().map(|k| k.nsk.clone()), + self.proof_generation_key.as_ref().map(|k| k.nsk), )?; // NB: We don't ensure that the bit representation of nsk @@ -642,7 +642,7 @@ fn test_input_circuit_with_bls12_381() { let mut cs = TestConstraintSystem::::new(); let instance = Spend { - params: params, + params, value_commitment: Some(value_commitment.clone()), proof_generation_key: Some(proof_generation_key.clone()), payment_address: Some(payment_address.clone()), @@ -738,7 +738,7 @@ fn test_output_circuit_with_bls12_381() { let mut cs = TestConstraintSystem::::new(); let instance = Output { - params: params, + params, value_commitment: Some(value_commitment.clone()), payment_address: Some(payment_address.clone()), commitment_randomness: Some(commitment_randomness), diff --git a/zcash_proofs/src/circuit/sprout/input.rs b/zcash_proofs/src/circuit/sprout/input.rs index ad6091f..a2726d4 100644 --- a/zcash_proofs/src/circuit/sprout/input.rs +++ b/zcash_proofs/src/circuit/sprout/input.rs @@ -54,7 +54,7 @@ impl InputNote { // Witness into the merkle tree let mut cur = cm.clone(); - for (i, layer) in auth_path.into_iter().enumerate() { + for (i, layer) in auth_path.iter().enumerate() { let cs = &mut cs.namespace(|| format!("layer {}", i)); let cur_is_right = AllocatedBit::alloc( @@ -112,7 +112,7 @@ impl InputNote { ); } - Ok(InputNote { mac: mac, nf: nf }) + Ok(InputNote { mac, nf }) } } diff --git a/zcash_proofs/src/circuit/sprout/mod.rs b/zcash_proofs/src/circuit/sprout/mod.rs index 358e1bb..f72d792 100644 --- a/zcash_proofs/src/circuit/sprout/mod.rs +++ b/zcash_proofs/src/circuit/sprout/mod.rs @@ -234,10 +234,7 @@ impl NoteValue { )?); } - Ok(NoteValue { - value: value, - bits: bits, - }) + Ok(NoteValue { value, bits }) } /// Encodes the bits of the value into little-endian @@ -247,7 +244,7 @@ impl NoteValue { .chunks(8) .flat_map(|v| v.iter().rev()) .cloned() - .map(|e| Boolean::from(e)) + .map(Boolean::from) .collect() } @@ -379,11 +376,11 @@ fn test_sprout_constraints() { let a_sk = Some(SpendingKey(get_u256(&mut test_vector))); inputs.push(JSInput { - value: value, - a_sk: a_sk, - rho: rho, - r: r, - auth_path: auth_path, + value, + a_sk, + rho, + r, + auth_path, }); } @@ -395,11 +392,7 @@ fn test_sprout_constraints() { get_u256(&mut test_vector); let r = Some(CommitmentRandomness(get_u256(&mut test_vector))); - outputs.push(JSOutput { - value: value, - a_pk: a_pk, - r: r, - }); + outputs.push(JSOutput { value, a_pk, r }); } let vpub_old = Some(test_vector.read_u64::().unwrap()); @@ -415,13 +408,13 @@ fn test_sprout_constraints() { let mac2 = get_u256(&mut test_vector); let js = JoinSplit { - vpub_old: vpub_old, - vpub_new: vpub_new, - h_sig: h_sig, - phi: phi, - inputs: inputs, - outputs: outputs, - rt: rt, + vpub_old, + vpub_new, + h_sig, + phi, + inputs, + outputs, + rt, }; js.synthesize(&mut cs).unwrap(); diff --git a/zcash_proofs/src/circuit/sprout/output.rs b/zcash_proofs/src/circuit/sprout/output.rs index a9a1e48..73a9851 100644 --- a/zcash_proofs/src/circuit/sprout/output.rs +++ b/zcash_proofs/src/circuit/sprout/output.rs @@ -11,7 +11,7 @@ pub struct OutputNote { } impl OutputNote { - pub fn compute<'a, E, CS>( + pub fn compute( mut cs: CS, a_pk: Option, value: &NoteValue, @@ -41,6 +41,6 @@ impl OutputNote { &r, )?; - Ok(OutputNote { cm: cm }) + Ok(OutputNote { cm }) } } diff --git a/zcash_proofs/src/hashreader.rs b/zcash_proofs/src/hashreader.rs index dbe686f..f8487b8 100644 --- a/zcash_proofs/src/hashreader.rs +++ b/zcash_proofs/src/hashreader.rs @@ -11,7 +11,7 @@ impl HashReader { /// Construct a new `HashReader` given an existing `reader` by value. pub fn new(reader: R) -> Self { HashReader { - reader: reader, + reader, hasher: State::new(), } } diff --git a/zcash_proofs/src/sapling/prover.rs b/zcash_proofs/src/sapling/prover.rs index 283e76b..e5116c6 100644 --- a/zcash_proofs/src/sapling/prover.rs +++ b/zcash_proofs/src/sapling/prover.rs @@ -65,7 +65,7 @@ impl SaplingProvingContext { // Accumulate the value commitment randomness in the context { - let mut tmp = rcv.clone(); + let mut tmp = rcv; tmp.add_assign(&self.bsk); // Update the context @@ -74,7 +74,7 @@ impl SaplingProvingContext { // Construct the value commitment let value_commitment = ValueCommitment:: { - value: value, + value, randomness: rcv, }; @@ -96,7 +96,7 @@ impl SaplingProvingContext { // Let's compute the nullifier while we have the position let note = Note { - value: value, + value, g_d: diversifier .g_d::(params) .expect("was a valid diversifier before"), @@ -200,7 +200,7 @@ impl SaplingProvingContext { // Accumulate the value commitment randomness in the context { - let mut tmp = rcv.clone(); + let mut tmp = rcv; tmp.negate(); // Outputs subtract from the total. tmp.add_assign(&self.bsk); @@ -210,7 +210,7 @@ impl SaplingProvingContext { // Construct the value commitment for the proof instance let value_commitment = ValueCommitment:: { - value: value, + value, randomness: rcv, }; @@ -220,7 +220,7 @@ impl SaplingProvingContext { value_commitment: Some(value_commitment.clone()), payment_address: Some(payment_address.clone()), commitment_randomness: Some(rcm), - esk: Some(esk.clone()), + esk: Some(esk), }; // Create proof From fe93f2ff6b385f9f30bf3c278351d1d1f162a9bb Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 2 Aug 2019 12:00:15 +0100 Subject: [PATCH 5/8] Rename into_ -> to_ where &self is used. --- bellman/src/gadgets/num.rs | 10 +++--- librustzcash/src/tests/key_agreement.rs | 2 +- librustzcash/src/tests/key_components.rs | 4 +-- zcash_primitives/src/jubjub/edwards.rs | 6 ++-- zcash_primitives/src/jubjub/mod.rs | 4 +-- zcash_primitives/src/jubjub/montgomery.rs | 4 +-- zcash_primitives/src/jubjub/tests.rs | 12 +++---- zcash_primitives/src/primitives.rs | 6 ++-- zcash_primitives/src/sapling.rs | 2 +- zcash_primitives/src/transaction/builder.rs | 2 +- zcash_primitives/src/zip32.rs | 2 +- zcash_proofs/examples/bench.rs | 4 +-- zcash_proofs/src/circuit/ecc.rs | 38 ++++++++++----------- zcash_proofs/src/circuit/pedersen_hash.rs | 4 +-- zcash_proofs/src/circuit/sapling.rs | 24 ++++++------- zcash_proofs/src/sapling/prover.rs | 8 ++--- zcash_proofs/src/sapling/verifier.rs | 8 ++--- 17 files changed, 70 insertions(+), 70 deletions(-) diff --git a/bellman/src/gadgets/num.rs b/bellman/src/gadgets/num.rs index 81f4fb3..eecccef 100644 --- a/bellman/src/gadgets/num.rs +++ b/bellman/src/gadgets/num.rs @@ -66,7 +66,7 @@ impl AllocatedNum { /// order, requiring that the representation /// strictly exists "in the field" (i.e., a /// congruency is not allowed.) - pub fn into_bits_le_strict(&self, mut cs: CS) -> Result, SynthesisError> + pub fn to_bits_le_strict(&self, mut cs: CS) -> Result, SynthesisError> where CS: ConstraintSystem, { @@ -189,7 +189,7 @@ impl AllocatedNum { /// Convert the allocated number into its little-endian representation. /// Note that this does not strongly enforce that the commitment is /// "in the field." - pub fn into_bits_le(&self, mut cs: CS) -> Result, SynthesisError> + pub fn to_bits_le(&self, mut cs: CS) -> Result, SynthesisError> where CS: ConstraintSystem, { @@ -522,7 +522,7 @@ mod test { let mut cs = TestConstraintSystem::::new(); let n = AllocatedNum::alloc(&mut cs, || Ok(negone)).unwrap(); - n.into_bits_le_strict(&mut cs).unwrap(); + n.to_bits_le_strict(&mut cs).unwrap(); assert!(cs.is_satisfied()); @@ -550,9 +550,9 @@ mod test { let n = AllocatedNum::alloc(&mut cs, || Ok(r)).unwrap(); let bits = if i % 2 == 0 { - n.into_bits_le(&mut cs).unwrap() + n.to_bits_le(&mut cs).unwrap() } else { - n.into_bits_le_strict(&mut cs).unwrap() + n.to_bits_le_strict(&mut cs).unwrap() }; assert!(cs.is_satisfied()); diff --git a/librustzcash/src/tests/key_agreement.rs b/librustzcash/src/tests/key_agreement.rs index d942e10..8f2c273 100644 --- a/librustzcash/src/tests/key_agreement.rs +++ b/librustzcash/src/tests/key_agreement.rs @@ -25,7 +25,7 @@ fn test_key_agreement() { let addr = loop { let mut d = [0; 11]; rng.fill_bytes(&mut d); - match vk.into_payment_address(Diversifier(d), ¶ms) { + match vk.to_payment_address(Diversifier(d), ¶ms) { Some(a) => break a, None => {} } diff --git a/librustzcash/src/tests/key_components.rs b/librustzcash/src/tests/key_components.rs index a034b9f..a15a40a 100644 --- a/librustzcash/src/tests/key_components.rs +++ b/librustzcash/src/tests/key_components.rs @@ -678,7 +678,7 @@ fn key_components() { } let pgk = ProofGenerationKey { ak, nsk }; - let fvk = pgk.into_viewing_key(&JUBJUB); + let fvk = pgk.to_viewing_key(&JUBJUB); { let mut vec = Vec::new(); fvk.nk.write(&mut vec).unwrap(); @@ -704,7 +704,7 @@ fn key_components() { let diversifier = Diversifier(tv.default_d); assert!(librustzcash_check_diversifier(&tv.default_d)); - let addr = fvk.into_payment_address(diversifier, &JUBJUB).unwrap(); + let addr = fvk.to_payment_address(diversifier, &JUBJUB).unwrap(); { let mut vec = Vec::new(); addr.pk_d.write(&mut vec).unwrap(); diff --git a/zcash_primitives/src/jubjub/edwards.rs b/zcash_primitives/src/jubjub/edwards.rs index 233bfb7..9ef50a2 100644 --- a/zcash_primitives/src/jubjub/edwards.rs +++ b/zcash_primitives/src/jubjub/edwards.rs @@ -168,7 +168,7 @@ impl Point { impl Point { pub fn write(&self, writer: W) -> io::Result<()> { - let (x, y) = self.into_xy(); + let (x, y) = self.to_xy(); assert_eq!(E::Fr::NUM_BITS, 255); @@ -183,7 +183,7 @@ impl Point { /// Convert from a Montgomery point pub fn from_montgomery(m: &montgomery::Point, params: &E::Params) -> Self { - match m.into_xy() { + match m.to_xy() { None => { // Map the point at infinity to the neutral element. Point::zero() @@ -306,7 +306,7 @@ impl Point { } } - pub fn into_xy(&self) -> (E::Fr, E::Fr) { + pub fn to_xy(&self) -> (E::Fr, E::Fr) { let zinv = self.z.inverse().unwrap(); let mut x = self.x; diff --git a/zcash_primitives/src/jubjub/mod.rs b/zcash_primitives/src/jubjub/mod.rs index 624592e..40938f3 100644 --- a/zcash_primitives/src/jubjub/mod.rs +++ b/zcash_primitives/src/jubjub/mod.rs @@ -384,7 +384,7 @@ impl JubjubBls12 { // coeffs = g, g*2, g*3, g*4 for _ in 0..4 { - coeffs.push(g.into_xy().expect("cannot produce O")); + coeffs.push(g.to_xy().expect("cannot produce O")); g = g.add(&gen, &tmp_params); } windows.push(coeffs); @@ -411,7 +411,7 @@ impl JubjubBls12 { let mut coeffs = vec![(Fr::zero(), Fr::one())]; let mut g = gen.clone(); for _ in 0..7 { - coeffs.push(g.into_xy()); + coeffs.push(g.to_xy()); g = g.add(&gen, &tmp_params); } windows.push(coeffs); diff --git a/zcash_primitives/src/jubjub/montgomery.rs b/zcash_primitives/src/jubjub/montgomery.rs index 0ebedd2..4e6c5e1 100644 --- a/zcash_primitives/src/jubjub/montgomery.rs +++ b/zcash_primitives/src/jubjub/montgomery.rs @@ -98,7 +98,7 @@ impl Point { impl Point { /// Convert from an Edwards point pub fn from_edwards(e: &edwards::Point, params: &E::Params) -> Self { - let (x, y) = e.into_xy(); + let (x, y) = e.to_xy(); if y == E::Fr::one() { // The only solution for y = 1 is x = 0. (0, 1) is @@ -177,7 +177,7 @@ impl Point { } } - pub fn into_xy(&self) -> Option<(E::Fr, E::Fr)> { + pub fn to_xy(&self) -> Option<(E::Fr, E::Fr)> { if self.infinity { None } else { diff --git a/zcash_primitives/src/jubjub/tests.rs b/zcash_primitives/src/jubjub/tests.rs index 1b4f8d1..b2c12ae 100644 --- a/zcash_primitives/src/jubjub/tests.rs +++ b/zcash_primitives/src/jubjub/tests.rs @@ -119,13 +119,13 @@ fn test_mul_associativity(params: &E::Params) { assert!(res2 == res3); assert!(res3 == res4); - let (x, y) = res1.into_xy(); + let (x, y) = res1.to_xy(); assert!(is_on_twisted_edwards_curve(x, y, params)); - let (x, y) = res2.into_xy(); + let (x, y) = res2.to_xy(); assert!(is_on_twisted_edwards_curve(x, y, params)); - let (x, y) = res3.into_xy(); + let (x, y) = res3.to_xy(); assert!(is_on_twisted_edwards_curve(x, y, params)); } } @@ -238,7 +238,7 @@ fn test_get_for(params: &E::Params) { let sign = rng.next_u32() % 2 == 1; if let Some(mut p) = edwards::Point::::get_for_y(y, sign, params) { - assert!(p.into_xy().0.into_repr().is_odd() == sign); + assert!(p.to_xy().0.into_repr().is_odd() == sign); p = p.negate(); assert!(edwards::Point::::get_for_y(y, !sign, params).unwrap() == p); } @@ -274,12 +274,12 @@ fn test_rand(params: &E::Params) { let e = edwards::Point::::rand(rng, params); { - let (x, y) = p.into_xy().unwrap(); + let (x, y) = p.to_xy().unwrap(); assert!(is_on_mont_curve(x, y, params)); } { - let (x, y) = e.into_xy(); + let (x, y) = e.to_xy(); assert!(is_on_twisted_edwards_curve(x, y, params)); } } diff --git a/zcash_primitives/src/primitives.rs b/zcash_primitives/src/primitives.rs index 38a056a..727402d 100644 --- a/zcash_primitives/src/primitives.rs +++ b/zcash_primitives/src/primitives.rs @@ -39,7 +39,7 @@ pub struct ProofGenerationKey { } impl ProofGenerationKey { - pub fn into_viewing_key(&self, params: &E::Params) -> ViewingKey { + pub fn to_viewing_key(&self, params: &E::Params) -> ViewingKey { ViewingKey { ak: self.ak.clone(), nk: params @@ -89,7 +89,7 @@ impl ViewingKey { E::Fs::from_repr(e).expect("should be a valid scalar") } - pub fn into_payment_address( + pub fn to_payment_address( &self, diversifier: Diversifier, params: &E::Params, @@ -242,6 +242,6 @@ impl Note { pub fn cm(&self, params: &E::Params) -> E::Fr { // The commitment is in the prime order subgroup, so mapping the // commitment to the x-coordinate is an injective encoding. - self.cm_full_point(params).into_xy().0 + self.cm_full_point(params).to_xy().0 } } diff --git a/zcash_primitives/src/sapling.rs b/zcash_primitives/src/sapling.rs index 8b8ef88..4f57a43 100644 --- a/zcash_primitives/src/sapling.rs +++ b/zcash_primitives/src/sapling.rs @@ -42,7 +42,7 @@ pub fn merkle_hash(depth: usize, lhs: &FrRepr, rhs: &FrRepr) -> FrRepr { .chain(rhs.iter().copied().take(Fr::NUM_BITS as usize)), &JUBJUB, ) - .into_xy() + .to_xy() .0 .into_repr() } diff --git a/zcash_primitives/src/transaction/builder.rs b/zcash_primitives/src/transaction/builder.rs index 1f30f99..281ccbf 100644 --- a/zcash_primitives/src/transaction/builder.rs +++ b/zcash_primitives/src/transaction/builder.rs @@ -394,7 +394,7 @@ impl Builder { let mut nullifier = [0u8; 32]; nullifier.copy_from_slice(&spend.note.nf( - &proof_generation_key.into_viewing_key(&JUBJUB), + &proof_generation_key.to_viewing_key(&JUBJUB), spend.witness.position, &JUBJUB, )); diff --git a/zcash_primitives/src/zip32.rs b/zcash_primitives/src/zip32.rs index 7cd6148..e287602 100644 --- a/zcash_primitives/src/zip32.rs +++ b/zcash_primitives/src/zip32.rs @@ -434,7 +434,7 @@ impl ExtendedFullViewingKey { Ok(ret) => ret, Err(()) => return Err(()), }; - match self.fvk.vk.into_payment_address(d_j, &JUBJUB) { + match self.fvk.vk.to_payment_address(d_j, &JUBJUB) { Some(addr) => Ok((j, addr)), None => Err(()), } diff --git a/zcash_proofs/examples/bench.rs b/zcash_proofs/examples/bench.rs index 62beb0a..2f48786 100644 --- a/zcash_proofs/examples/bench.rs +++ b/zcash_proofs/examples/bench.rs @@ -50,7 +50,7 @@ fn main() { nsk: nsk.clone(), }; - let viewing_key = proof_generation_key.into_viewing_key(jubjub_params); + let viewing_key = proof_generation_key.to_viewing_key(jubjub_params); let payment_address; @@ -61,7 +61,7 @@ fn main() { Diversifier(d) }; - if let Some(p) = viewing_key.into_payment_address(diversifier, jubjub_params) { + if let Some(p) = viewing_key.to_payment_address(diversifier, jubjub_params) { payment_address = p; break; } diff --git a/zcash_proofs/src/circuit/ecc.rs b/zcash_proofs/src/circuit/ecc.rs index 76b837d..ef5bedf 100644 --- a/zcash_proofs/src/circuit/ecc.rs +++ b/zcash_proofs/src/circuit/ecc.rs @@ -121,9 +121,9 @@ impl EdwardsPoint { { let mut tmp = vec![]; - let x = self.x.into_bits_le_strict(cs.namespace(|| "unpack x"))?; + let x = self.x.to_bits_le_strict(cs.namespace(|| "unpack x"))?; - let y = self.y.into_bits_le_strict(cs.namespace(|| "unpack y"))?; + let y = self.y.to_bits_le_strict(cs.namespace(|| "unpack y"))?; tmp.extend(y); tmp.push(x[0].clone()); @@ -141,7 +141,7 @@ impl EdwardsPoint { where CS: ConstraintSystem, { - let p = p.map(|p| p.into_xy()); + let p = p.map(|p| p.to_xy()); // Allocate x let x = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(p.get()?.0))?; @@ -688,8 +688,8 @@ mod test { let mut cs = TestConstraintSystem::::new(); let p = montgomery::Point::::rand(rng, params); - let (u, v) = edwards::Point::from_montgomery(&p, params).into_xy(); - let (x, y) = p.into_xy().unwrap(); + let (u, v) = edwards::Point::from_montgomery(&p, params).to_xy(); + let (x, y) = p.to_xy().unwrap(); let numx = AllocatedNum::alloc(cs.namespace(|| "mont x"), || Ok(x)).unwrap(); let numy = AllocatedNum::alloc(cs.namespace(|| "mont y"), || Ok(y)).unwrap(); @@ -728,7 +728,7 @@ mod test { let mut cs = TestConstraintSystem::::new(); let q = EdwardsPoint::witness(&mut cs, Some(p.clone()), ¶ms).unwrap(); - let p = p.into_xy(); + let p = p.to_xy(); assert!(cs.is_satisfied()); assert_eq!(q.x.get_value().unwrap(), p.0); @@ -737,7 +737,7 @@ mod test { for _ in 0..100 { let p = edwards::Point::::rand(rng, ¶ms); - let (x, y) = p.into_xy(); + let (x, y) = p.to_xy(); let mut cs = TestConstraintSystem::::new(); let numx = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(x)).unwrap(); @@ -779,7 +779,7 @@ mod test { let p = params.generator(FixedGenerators::NoteCommitmentRandomness); let s = Fs::random(rng); let q = p.mul(s, params); - let (x1, y1) = q.into_xy(); + let (x1, y1) = q.to_xy(); let mut s_bits = BitIterator::new(s.into_repr()).collect::>(); s_bits.reverse(); @@ -823,8 +823,8 @@ mod test { let s = Fs::random(rng); let q = p.mul(s, params); - let (x0, y0) = p.into_xy(); - let (x1, y1) = q.into_xy(); + let (x0, y0) = p.to_xy(); + let (x1, y1) = q.to_xy(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); @@ -873,7 +873,7 @@ mod test { let p = edwards::Point::::rand(rng, params); - let (x0, y0) = p.into_xy(); + let (x0, y0) = p.to_xy(); let num_x0 = AllocatedNum::alloc(cs.namespace(|| "x0"), || Ok(x0)).unwrap(); let num_y0 = AllocatedNum::alloc(cs.namespace(|| "y0"), || Ok(y0)).unwrap(); @@ -941,9 +941,9 @@ mod test { let p3 = p1.add(&p2, params); - let (x0, y0) = p1.into_xy(); - let (x1, y1) = p2.into_xy(); - let (x2, y2) = p3.into_xy(); + let (x0, y0) = p1.to_xy(); + let (x1, y1) = p2.to_xy(); + let (x2, y2) = p3.to_xy(); let mut cs = TestConstraintSystem::::new(); @@ -1002,8 +1002,8 @@ mod test { let p1 = edwards::Point::::rand(rng, params); let p2 = p1.double(params); - let (x0, y0) = p1.into_xy(); - let (x1, y1) = p2.into_xy(); + let (x0, y0) = p1.to_xy(); + let (x1, y1) = p2.to_xy(); let mut cs = TestConstraintSystem::::new(); @@ -1053,9 +1053,9 @@ mod test { let p3 = p1.add(&p2, params); - let (x0, y0) = p1.into_xy().unwrap(); - let (x1, y1) = p2.into_xy().unwrap(); - let (x2, y2) = p3.into_xy().unwrap(); + let (x0, y0) = p1.to_xy().unwrap(); + let (x1, y1) = p2.to_xy().unwrap(); + let (x2, y2) = p3.to_xy().unwrap(); let mut cs = TestConstraintSystem::::new(); diff --git a/zcash_proofs/src/circuit/pedersen_hash.rs b/zcash_proofs/src/circuit/pedersen_hash.rs index e77d28b..409f30e 100644 --- a/zcash_proofs/src/circuit/pedersen_hash.rs +++ b/zcash_proofs/src/circuit/pedersen_hash.rs @@ -189,7 +189,7 @@ mod test { input.clone().into_iter(), params, ) - .into_xy(); + .to_xy(); assert_eq!(res.get_x().get_value().unwrap(), expected.0); assert_eq!(res.get_y().get_value().unwrap(), expected.1); @@ -200,7 +200,7 @@ mod test { input.into_iter(), params, ) - .into_xy(); + .to_xy(); assert!(res.get_x().get_value().unwrap() != unexpected.0); assert!(res.get_y().get_value().unwrap() != unexpected.1); diff --git a/zcash_proofs/src/circuit/sapling.rs b/zcash_proofs/src/circuit/sapling.rs index d43a628..de6887b 100644 --- a/zcash_proofs/src/circuit/sapling.rs +++ b/zcash_proofs/src/circuit/sapling.rs @@ -336,8 +336,8 @@ impl<'a, E: JubjubEngine> Circuit for Spend<'a, E> { // they will be unable to find an authentication path in the // tree with high probability. let mut preimage = vec![]; - preimage.extend(xl.into_bits_le(cs.namespace(|| "xl into bits"))?); - preimage.extend(xr.into_bits_le(cs.namespace(|| "xr into bits"))?); + preimage.extend(xl.to_bits_le(cs.namespace(|| "xl into bits"))?); + preimage.extend(xr.to_bits_le(cs.namespace(|| "xr into bits"))?); // Compute the new subtree value cur = pedersen_hash::pedersen_hash( @@ -464,7 +464,7 @@ impl<'a, E: JubjubEngine> Circuit for Output<'a, E> { // they would like. { // Just grab pk_d from the witness - let pk_d = self.payment_address.as_ref().map(|e| e.pk_d.into_xy()); + let pk_d = self.payment_address.as_ref().map(|e| e.pk_d.to_xy()); // Witness the y-coordinate, encoded as little // endian bits (to match the representation) @@ -567,7 +567,7 @@ fn test_input_circuit_with_bls12_381() { nsk: nsk.clone(), }; - let viewing_key = proof_generation_key.into_viewing_key(params); + let viewing_key = proof_generation_key.to_viewing_key(params); let payment_address; @@ -578,7 +578,7 @@ fn test_input_circuit_with_bls12_381() { Diversifier(d) }; - if let Some(p) = viewing_key.into_payment_address(diversifier, params) { + if let Some(p) = viewing_key.to_payment_address(diversifier, params) { payment_address = p; break; } @@ -590,8 +590,8 @@ fn test_input_circuit_with_bls12_381() { let ar = fs::Fs::random(rng); { - let rk = viewing_key.rk(ar, params).into_xy(); - let expected_value_cm = value_commitment.cm(params).into_xy(); + let rk = viewing_key.rk(ar, params).to_xy(); + let expected_value_cm = value_commitment.cm(params).to_xy(); let note = Note { value: value_commitment.value, g_d: g_d.clone(), @@ -626,7 +626,7 @@ fn test_input_circuit_with_bls12_381() { .chain(rhs.into_iter().take(Fr::NUM_BITS as usize)), params, ) - .into_xy() + .to_xy() .0; if b { @@ -714,7 +714,7 @@ fn test_output_circuit_with_bls12_381() { nsk: nsk.clone(), }; - let viewing_key = proof_generation_key.into_viewing_key(params); + let viewing_key = proof_generation_key.to_viewing_key(params); let payment_address; @@ -725,7 +725,7 @@ fn test_output_circuit_with_bls12_381() { Diversifier(d) }; - if let Some(p) = viewing_key.into_payment_address(diversifier, params) { + if let Some(p) = viewing_key.to_payment_address(diversifier, params) { payment_address = p; break; } @@ -759,13 +759,13 @@ fn test_output_circuit_with_bls12_381() { .expect("should be valid") .cm(params); - let expected_value_cm = value_commitment.cm(params).into_xy(); + let expected_value_cm = value_commitment.cm(params).to_xy(); let expected_epk = payment_address .g_d(params) .expect("should be valid") .mul(esk, params); - let expected_epk_xy = expected_epk.into_xy(); + let expected_epk_xy = expected_epk.to_xy(); assert_eq!(cs.num_inputs(), 6); assert_eq!(cs.get_input(0, "ONE"), Fr::one()); diff --git a/zcash_proofs/src/sapling/prover.rs b/zcash_proofs/src/sapling/prover.rs index e5116c6..0603424 100644 --- a/zcash_proofs/src/sapling/prover.rs +++ b/zcash_proofs/src/sapling/prover.rs @@ -79,10 +79,10 @@ impl SaplingProvingContext { }; // Construct the viewing key - let viewing_key = proof_generation_key.into_viewing_key(params); + let viewing_key = proof_generation_key.to_viewing_key(params); // Construct the payment address with the viewing key / diversifier - let payment_address = match viewing_key.into_payment_address(diversifier, params) { + let payment_address = match viewing_key.to_payment_address(diversifier, params) { Some(p) => p, None => return Err(()), }; @@ -130,12 +130,12 @@ impl SaplingProvingContext { // Construct public input for circuit let mut public_input = [Fr::zero(); 7]; { - let (x, y) = rk.0.into_xy(); + let (x, y) = rk.0.to_xy(); public_input[0] = x; public_input[1] = y; } { - let (x, y) = value_commitment.cm(params).into_xy(); + let (x, y) = value_commitment.cm(params).to_xy(); public_input[2] = x; public_input[3] = y; } diff --git a/zcash_proofs/src/sapling/verifier.rs b/zcash_proofs/src/sapling/verifier.rs index 0801023..5199bd8 100644 --- a/zcash_proofs/src/sapling/verifier.rs +++ b/zcash_proofs/src/sapling/verifier.rs @@ -82,12 +82,12 @@ impl SaplingVerificationContext { // Construct public input for circuit let mut public_input = [Fr::zero(); 7]; { - let (x, y) = rk.0.into_xy(); + let (x, y) = rk.0.to_xy(); public_input[0] = x; public_input[1] = y; } { - let (x, y) = cv.into_xy(); + let (x, y) = cv.to_xy(); public_input[2] = x; public_input[3] = y; } @@ -146,12 +146,12 @@ impl SaplingVerificationContext { // Construct public input for circuit let mut public_input = [Fr::zero(); 5]; { - let (x, y) = cv.into_xy(); + let (x, y) = cv.to_xy(); public_input[0] = x; public_input[1] = y; } { - let (x, y) = epk.into_xy(); + let (x, y) = epk.to_xy(); public_input[2] = x; public_input[3] = y; } From 90165486983018853d03eb4a85ec6e0a7287361c Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Fri, 2 Aug 2019 12:03:38 +0100 Subject: [PATCH 6/8] Take self directly in into_* functions --- bellman/src/gadgets/blake2s.rs | 2 +- bellman/src/gadgets/uint32.rs | 10 ++++++---- zcash_proofs/src/circuit/ecc.rs | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/bellman/src/gadgets/blake2s.rs b/bellman/src/gadgets/blake2s.rs index beefe09..672f139 100644 --- a/bellman/src/gadgets/blake2s.rs +++ b/bellman/src/gadgets/blake2s.rs @@ -404,7 +404,7 @@ pub fn blake2s>( )?; } - Ok(h.iter().flat_map(|b| b.into_bits()).collect()) + Ok(h.into_iter().flat_map(|b| b.into_bits()).collect()) } #[cfg(test)] diff --git a/bellman/src/gadgets/uint32.rs b/bellman/src/gadgets/uint32.rs index 3467400..5a93e75 100644 --- a/bellman/src/gadgets/uint32.rs +++ b/bellman/src/gadgets/uint32.rs @@ -72,8 +72,10 @@ impl UInt32 { Ok(UInt32 { bits, value }) } - pub fn into_bits_be(&self) -> Vec { - self.bits.iter().rev().cloned().collect() + pub fn into_bits_be(self) -> Vec { + let mut ret = self.bits; + ret.reverse(); + ret } pub fn from_bits_be(bits: &[Boolean]) -> Self { @@ -101,8 +103,8 @@ impl UInt32 { } /// Turns this `UInt32` into its little-endian byte order representation. - pub fn into_bits(&self) -> Vec { - self.bits.clone() + pub fn into_bits(self) -> Vec { + self.bits } /// Converts a little-endian byte order representation of bits into a diff --git a/zcash_proofs/src/circuit/ecc.rs b/zcash_proofs/src/circuit/ecc.rs index ef5bedf..fa4913a 100644 --- a/zcash_proofs/src/circuit/ecc.rs +++ b/zcash_proofs/src/circuit/ecc.rs @@ -508,7 +508,7 @@ impl MontgomeryPoint { /// a point in the birationally equivalent twisted /// Edwards curve. pub fn into_edwards( - &self, + self, mut cs: CS, params: &E::Params, ) -> Result, SynthesisError> From 7c1d4d9a5b63330d71884dc78fefcefaf8b384d5 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Sun, 18 Aug 2019 23:56:15 +0100 Subject: [PATCH 7/8] Log distinct error cases in Equihash verification --- Cargo.lock | 10 ++++++++++ zcash_primitives/Cargo.toml | 1 + zcash_primitives/src/block/equihash.rs | 7 ++++--- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d6f658a..623bcc0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -317,6 +317,14 @@ dependencies = [ "zcash_proofs 0.0.0", ] +[[package]] +name = "log" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "nodrop" version = "0.1.13" @@ -535,6 +543,7 @@ dependencies = [ "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "hex-literal 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "pairing 0.14.2", "rand 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -594,6 +603,7 @@ dependencies = [ "checksum hex-literal-impl 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "520870c3213943eb8d7803e80180d12a6c7ceb4ae74602544529d1643dc4ddda" "checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14" "checksum libc 0.2.61 (registry+https://github.com/rust-lang/crates.io-index)" = "c665266eb592905e8503ba3403020f4b8794d26263f412ca33171600eca9a6fa" +"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945" "checksum num-bigint 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "57450397855d951f1a41305e54851b1a7b8f5d2e349543a02a2effe25459f718" "checksum num-integer 0.1.41 (registry+https://github.com/rust-lang/crates.io-index)" = "b85e541ef8255f6cf42bbfe4ef361305c6c135d10919ecc26126c4e5ae94bc09" diff --git a/zcash_primitives/Cargo.toml b/zcash_primitives/Cargo.toml index 5e1bf91..7019dec 100644 --- a/zcash_primitives/Cargo.toml +++ b/zcash_primitives/Cargo.toml @@ -16,6 +16,7 @@ ff = { path = "../ff" } fpe = "0.2" hex = "0.3" lazy_static = "1" +log = "0.4" pairing = { path = "../pairing" } rand = "0.7" rand_core = "0.5" diff --git a/zcash_primitives/src/block/equihash.rs b/zcash_primitives/src/block/equihash.rs index 9710dc9..2a3bb66 100644 --- a/zcash_primitives/src/block/equihash.rs +++ b/zcash_primitives/src/block/equihash.rs @@ -1,5 +1,6 @@ use blake2b_simd::{Hash as Blake2bHash, Params as Blake2bParams, State as Blake2bState}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; +use log::error; use std::io::Cursor; use std::mem::size_of; @@ -196,13 +197,13 @@ fn distinct_indices(a: &Node, b: &Node) -> bool { fn validate_subtrees(p: &Params, a: &Node, b: &Node) -> bool { if !has_collision(a, b, p.collision_byte_length()) { - // error!("Invalid solution: invalid collision length between StepRows"); + error!("Invalid solution: invalid collision length between StepRows"); false } else if b.indices_before(a) { - // error!("Invalid solution: Index tree incorrectly ordered"); + error!("Invalid solution: Index tree incorrectly ordered"); false } else if !distinct_indices(a, b) { - // error!("Invalid solution: duplicate indices"); + error!("Invalid solution: duplicate indices"); false } else { true From 0c7eb84d36e41e562f6a9a092c67d772f46f6fc5 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 19 Aug 2019 00:21:10 +0100 Subject: [PATCH 8/8] impl FromStr for Memo Memo::from_str was previously shadowing a built-in trait method. --- zcash_primitives/src/note_encryption.rs | 37 +++++++++++++++---------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/zcash_primitives/src/note_encryption.rs b/zcash_primitives/src/note_encryption.rs index 0d0e83a..2644016 100644 --- a/zcash_primitives/src/note_encryption.rs +++ b/zcash_primitives/src/note_encryption.rs @@ -106,11 +106,6 @@ impl Memo { } } - /// Returns a `Memo` containing the given string, or `None` if the string is too long. - pub fn from_str(memo: &str) -> Option { - Memo::from_bytes(memo.as_bytes()) - } - /// Returns the underlying bytes of the `Memo`. pub fn as_bytes(&self) -> &[u8] { &self.0[..] @@ -134,6 +129,15 @@ impl Memo { } } +impl str::FromStr for Memo { + type Err = (); + + /// Returns a `Memo` containing the given string, or an error if the string is too long. + fn from_str(memo: &str) -> Result { + Memo::from_bytes(memo.as_bytes()).ok_or(()) + } +} + pub fn generate_esk(rng: &mut R) -> Fs { // create random 64 byte buffer let mut buffer = [0u8; 64]; @@ -557,6 +561,7 @@ mod tests { use pairing::bls12_381::{Bls12, Fr, FrRepr}; use rand_core::{CryptoRng, RngCore}; use rand_os::OsRng; + use std::str::FromStr; use super::{ kdf_sapling, prf_ock, sapling_ka_agree, try_sapling_compact_note_decryption, @@ -661,16 +666,18 @@ mod tests { 0x74, 0x20, 0x65, 0x6e, 0x6f, 0x75, 0x67, 0x68 ]) ); - assert!(Memo::from_str( - "thiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiis \ - iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiis \ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ - veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeryyyyyyyyyyyyyyyyyyyyyyyyyy \ - looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong \ - meeeeeeeeeeeeeeeeeeemooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo \ - but it's now a bit too long" - ) - .is_none()); + assert_eq!( + Memo::from_str( + "thiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiis \ + iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiis \ + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ + veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeryyyyyyyyyyyyyyyyyyyyyyyyyy \ + looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong \ + meeeeeeeeeeeeeeeeeeemooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo \ + but it's now a bit too long" + ), + Err(()) + ); } #[test]