From 258aabfbfde85aa407b0764974d7f006fc7efd6e Mon Sep 17 00:00:00 2001 From: howardwu Date: Thu, 24 Jun 2021 20:36:43 -0700 Subject: [PATCH 01/13] Introduce traits FftField and FftParameters for all fields --- algorithms/src/fft/domain.rs | 4 +- algorithms/src/fft/tests.rs | 3 +- curves/src/bls12_377/fq.rs | 50 ++++++++----- curves/src/bls12_377/fr.rs | 53 +++++++++---- curves/src/bls12_377/tests.rs | 2 + curves/src/bw6_761/fq.rs | 79 +++++++++++++------- curves/src/edwards_bls12/fr.rs | 37 ++++++--- curves/src/edwards_sw6/fr.rs | 41 ++++++---- curves/src/sw6/fq.rs | 40 +++++----- fields/src/fp_256.rs | 24 ++++-- fields/src/fp_320.rs | 24 ++++-- fields/src/fp_384.rs | 24 ++++-- fields/src/fp_768.rs | 26 +++++-- fields/src/fp_832.rs | 26 +++++-- fields/src/traits/fft_field.rs | 103 ++++++++++++++++++++++++++ fields/src/traits/fft_parameters.rs | 43 +++++++++++ fields/src/traits/field.rs | 6 +- fields/src/traits/field_parameters.rs | 12 +-- fields/src/traits/mod.rs | 6 ++ fields/src/traits/prime_field.rs | 19 +++-- r1cs/src/test_fr.rs | 53 +++++++++---- 21 files changed, 511 insertions(+), 164 deletions(-) create mode 100644 fields/src/traits/fft_field.rs create mode 100644 fields/src/traits/fft_parameters.rs diff --git a/algorithms/src/fft/domain.rs b/algorithms/src/fft/domain.rs index 8d6367476c..3b72c0aad8 100644 --- a/algorithms/src/fft/domain.rs +++ b/algorithms/src/fft/domain.rs @@ -27,7 +27,7 @@ //! by performing an O(n log n) FFT over such a domain. use crate::fft::{multicore::Worker, SparsePolynomial}; -use snarkvm_fields::{batch_inversion, FieldParameters, PrimeField}; +use snarkvm_fields::{batch_inversion, FftParameters, PrimeField}; use snarkvm_utilities::{errors::SerializationError, serialize::*}; use rand::Rng; @@ -555,7 +555,7 @@ impl Iterator for Elements { mod tests { use crate::fft::{DensePolynomial, EvaluationDomain}; use snarkvm_curves::bls12_377::Fr; - use snarkvm_fields::{Field, One, PrimeField, Zero}; + use snarkvm_fields::{FftField, Field, One, Zero}; use snarkvm_utilities::UniformRand; use rand::{thread_rng, Rng}; diff --git a/algorithms/src/fft/tests.rs b/algorithms/src/fft/tests.rs index b606aa2598..2a2582810f 100644 --- a/algorithms/src/fft/tests.rs +++ b/algorithms/src/fft/tests.rs @@ -16,6 +16,7 @@ use crate::fft::domain::*; use snarkvm_curves::{bls12_377::Bls12_377, traits::PairingEngine}; +use snarkvm_fields::FftField; use snarkvm_utilities::rand::UniformRand; /// Test multiplying various (low degree) polynomials together and @@ -60,7 +61,7 @@ fn fft_composition() { #[test] fn parallel_fft_consistency() { use crate::fft::multicore::*; - use snarkvm_fields::{Field, One, PrimeField}; + use snarkvm_fields::{Field, One}; use rand::Rng; use std::cmp::min; diff --git a/curves/src/bls12_377/fq.rs b/curves/src/bls12_377/fq.rs index 5cd8b6953e..91561499c8 100644 --- a/curves/src/bls12_377/fq.rs +++ b/curves/src/bls12_377/fq.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp384, Fp384Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp384, Fp384Parameters}; use snarkvm_utilities::biginteger::BigInteger384 as BigInteger; pub type Fq = Fp384; @@ -23,11 +23,27 @@ pub struct FqParameters; impl Fp384Parameters for FqParameters {} -impl FieldParameters for FqParameters { +impl FftParameters for FqParameters { type BigInteger = BigInteger; + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 2022196864061697551u64, + 17419102863309525423u64, + 8564289679875062096u64, + 17152078065055548215u64, + 17966377291017729567u64, + 68610905582439508u64, + ]); + #[rustfmt::skip] + const TWO_ADICITY: u32 = 46u32; +} + +impl FieldParameters for FqParameters { + #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - // GENERATOR = -5 + /// GENERATOR = -5 + #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 0xfc0b8000000002fa, 0x97d39cf6e000018b, @@ -36,8 +52,10 @@ impl FieldParameters for FqParameters { 0xbaf1ec35813f9eb, 0x9974a2c0945ad2, ]); + #[rustfmt::skip] const INV: u64 = 9586122913090633727u64; - // MODULUS = 258664426012969094010652733694893533536393512754914660539884262666720468348340822774968888139573360124440321458177 + /// MODULUS = 258664426012969094010652733694893533536393512754914660539884262666720468348340822774968888139573360124440321458177 + #[rustfmt::skip] const MODULUS: BigInteger = BigInteger([ 0x8508c00000000001, 0x170b5d4430000000, @@ -46,7 +64,9 @@ impl FieldParameters for FqParameters { 0xc63b05c06ca1493b, 0x1ae3a4617c510ea, ]); + #[rustfmt::skip] const MODULUS_BITS: u32 = 377; + #[rustfmt::skip] const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 0x4284600000000000, 0xb85aea218000000, @@ -55,6 +75,7 @@ impl FieldParameters for FqParameters { 0x631d82e03650a49d, 0xd71d230be28875, ]); + #[rustfmt::skip] const R: BigInteger = BigInteger([ 202099033278250856u64, 5854854902718660529u64, @@ -63,6 +84,7 @@ impl FieldParameters for FqParameters { 5545221690922665192u64, 39800542322357402u64, ]); + #[rustfmt::skip] const R2: BigInteger = BigInteger([ 0xb786686c9400cd22, 0x329fcaab00431b1, @@ -71,19 +93,13 @@ impl FieldParameters for FqParameters { 0x837e92f041790bf9, 0x6dfccb1e914b88, ]); + #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 7; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 2022196864061697551u64, - 17419102863309525423u64, - 8564289679875062096u64, - 17152078065055548215u64, - 17966377291017729567u64, - 68610905582439508u64, - ]); // T and T_MINUS_ONE_DIV_TWO, where MODULUS - 1 = 2^S * T - // T = (MODULUS - 1) // 2^S = - // 3675842578061421676390135839012792950148785745837396071634149488243117337281387659330802195819009059 + /// T = (MODULUS - 1) // 2^S = + /// 3675842578061421676390135839012792950148785745837396071634149488243117337281387659330802195819009059 + #[rustfmt::skip] const T: BigInteger = BigInteger([ 0x7510c00000021423, 0x88bee82520005c2d, @@ -92,9 +108,9 @@ impl FieldParameters for FqParameters { 0xe9185f1443ab18ec, 0x6b8, ]); - const TWO_ADICITY: u32 = 46u32; - // (T - 1) // 2 = - // 1837921289030710838195067919506396475074392872918698035817074744121558668640693829665401097909504529 + /// (T - 1) // 2 = + /// 1837921289030710838195067919506396475074392872918698035817074744121558668640693829665401097909504529 + #[rustfmt::skip] const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 0xba88600000010a11, 0xc45f741290002e16, diff --git a/curves/src/bls12_377/fr.rs b/curves/src/bls12_377/fr.rs index 41e30c8f87..8b5e88958d 100644 --- a/curves/src/bls12_377/fr.rs +++ b/curves/src/bls12_377/fr.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp256, Fp256Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp256, Fp256Parameters}; use snarkvm_utilities::biginteger::BigInteger256 as BigInteger; pub type Fr = Fp256; @@ -23,61 +23,86 @@ pub struct FrParameters; impl Fp256Parameters for FrParameters {} -impl FieldParameters for FrParameters { +impl FftParameters for FrParameters { type BigInteger = BigInteger; + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0x3c3d3ca739381fb2, + 0x9a14cda3ec99772b, + 0xd7aacc7c59724826, + 0xd1ba211c5cc349c, + ]); + #[rustfmt::skip] + const TWO_ADICITY: u32 = 47; +} + +impl FieldParameters for FrParameters { + #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - // GENERATOR = 11 + /// GENERATOR = 11 + #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 1855201571499933546u64, 8511318076631809892u64, 6222514765367795509u64, 1122129207579058019u64, ]); + #[rustfmt::skip] const INV: u64 = 725501752471715839u64; - // MODULUS = 8444461749428370424248824938781546531375899335154063827935233455917409239041 + /// MODULUS = 8444461749428370424248824938781546531375899335154063827935233455917409239041 + #[rustfmt::skip] const MODULUS: BigInteger = BigInteger([ 725501752471715841u64, 6461107452199829505u64, 6968279316240510977u64, 1345280370688173398u64, ]); + #[rustfmt::skip] const MODULUS_BITS: u32 = 253; /// (r - 1)/2 = /// 4222230874714185212124412469390773265687949667577031913967616727958704619520 + #[rustfmt::skip] const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 0x8508c00000000000, 0xacd53b7f68000000, 0x305a268f2e1bd800, 0x955b2af4d1652ab, ]); + #[rustfmt::skip] const R: BigInteger = BigInteger([ 9015221291577245683u64, 8239323489949974514u64, 1646089257421115374u64, 958099254763297437u64, ]); + #[rustfmt::skip] const R2: BigInteger = BigInteger([ 2726216793283724667u64, 14712177743343147295u64, 12091039717619697043u64, 81024008013859129u64, ]); + #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 3; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 0x3c3d3ca739381fb2, - 0x9a14cda3ec99772b, - 0xd7aacc7c59724826, - 0xd1ba211c5cc349c, - ]); // T and T_MINUS_ONE_DIV_TWO, where r - 1 = 2^s * t /// t = (r - 1) / 2^s = /// 60001509534603559531609739528203892656505753216962260608619555 - const T: BigInteger = BigInteger([0xedfda00000021423, 0x9a3cb86f6002b354, 0xcabd34594aacc168, 0x2556]); - const TWO_ADICITY: u32 = 47; + #[rustfmt::skip] + const T: BigInteger = BigInteger([ + 0xedfda00000021423, + 0x9a3cb86f6002b354, + 0xcabd34594aacc168, + 0x2556, + ]); /// (t - 1) / 2 = /// 30000754767301779765804869764101946328252876608481130304309777 - const T_MINUS_ONE_DIV_TWO: BigInteger = - BigInteger([0x76fed00000010a11, 0x4d1e5c37b00159aa, 0x655e9a2ca55660b4, 0x12ab]); + #[rustfmt::skip] + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x76fed00000010a11, + 0x4d1e5c37b00159aa, + 0x655e9a2ca55660b4, + 0x12ab, + ]); } diff --git a/curves/src/bls12_377/tests.rs b/curves/src/bls12_377/tests.rs index 1d647da3d3..c350a0f23d 100644 --- a/curves/src/bls12_377/tests.rs +++ b/curves/src/bls12_377/tests.rs @@ -46,6 +46,8 @@ use crate::{ use snarkvm_fields::{ fp6_3over2::Fp6Parameters, tests_field::{field_serialization_test, field_test, frobenius_test, primefield_test, sqrt_field_test}, + FftField, + FftParameters, Field, FieldParameters, Fp2Parameters, diff --git a/curves/src/bw6_761/fq.rs b/curves/src/bw6_761/fq.rs index 808e681b34..399abd24fc 100644 --- a/curves/src/bw6_761/fq.rs +++ b/curves/src/bw6_761/fq.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp768, Fp768Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp768, Fp768Parameters}; use snarkvm_utilities::biginteger::BigInteger768 as BigInteger; pub type Fq = Fp768; @@ -23,12 +23,40 @@ pub struct FqParameters; impl Fp768Parameters for FqParameters {} -impl FieldParameters for FqParameters { +impl FftParameters for FqParameters { type BigInteger = BigInteger; + /// least_quadratic_nonresidue(MODULUS) in Sage. + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 17481284903592032950u64, + 10104133845767975835u64, + 8607375506753517913u64, + 13706168424391191299u64, + 9580010308493592354u64, + 14241333420363995524u64, + 6665632285037357566u64, + 5559902898979457045u64, + 15504799981718861253u64, + 8332096944629367896u64, + 18005297320867222879u64, + 58811391084848524u64, + ]); + // The internal representation of this type is six 64-bit unsigned + // integers in little-endian order. Values are always in + // Montgomery form; i.e., Scalar(a) = aR mod p, with R=2^768. + + /// (MODULUS - 1) % 2^TWO_ADICITY == 0 + #[rustfmt::skip] + const TWO_ADICITY: u32 = 1; +} + +impl FieldParameters for FqParameters { + #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - // GENERATOR = 2 - // primitive_root(MODULUS) + /// GENERATOR = 2 + /// primitive_root(MODULUS) + #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 289919226011913130u64, 13019990545710127566u64, @@ -43,9 +71,11 @@ impl FieldParameters for FqParameters { 12632664537138156478u64, 46143195394855163u64, ]); - // (-1/MODULUS) % 2^64 + /// (-1/MODULUS) % 2^64 + #[rustfmt::skip] const INV: u64 = 744663313386281181u64; - // MODULUS = 6891450384315732539396789682275657542479668912536150109513790160209623422243491736087683183289411687640864567753786613451161759120554247759349511699125301598951605099378508850372543631423596795951899700429969112842764913119068299 + /// MODULUS = 6891450384315732539396789682275657542479668912536150109513790160209623422243491736087683183289411687640864567753786613451161759120554247759349511699125301598951605099378508850372543631423596795951899700429969112842764913119068299 + #[rustfmt::skip] const MODULUS: BigInteger = BigInteger([ 0xf49d00000000008b, 0xe6913e6870000082, @@ -60,7 +90,10 @@ impl FieldParameters for FqParameters { 0xd187c94004faff3e, 0x122e824fb83ce0a, ]); + #[rustfmt::skip] const MODULUS_BITS: u32 = 761; + /// (MODULUS - 1) / 2 + #[rustfmt::skip] const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 0x7a4e800000000045, 0xf3489f3438000041, @@ -75,6 +108,8 @@ impl FieldParameters for FqParameters { 0x68c3e4a0027d7f9f, 0x9174127dc1e705, ]); + /// 2^768 % MODULUS + #[rustfmt::skip] const R: BigInteger = BigInteger([ 144959613005956565u64, 6509995272855063783u64, @@ -89,6 +124,8 @@ impl FieldParameters for FqParameters { 15539704305423854047u64, 23071597697427581u64, ]); + /// R^2 + #[rustfmt::skip] const R2: BigInteger = BigInteger([ 14305184132582319705u64, 8868935336694416555u64, @@ -103,24 +140,13 @@ impl FieldParameters for FqParameters { 10311846026977660324u64, 48736111365249031u64, ]); + /// Gap to 64-bit machine word + #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 7; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 17481284903592032950u64, - 10104133845767975835u64, - 8607375506753517913u64, - 13706168424391191299u64, - 9580010308493592354u64, - 14241333420363995524u64, - 6665632285037357566u64, - 5559902898979457045u64, - 15504799981718861253u64, - 8332096944629367896u64, - 18005297320867222879u64, - 58811391084848524u64, - ]); - // T = - // 3445725192157866269698394841137828771239834456268075054756895080104811711121745868043841591644705843820432283876893306725580879560277123879674755849562650799475802549689254425186271815711798397975949850214984556421382456559534149 - // (MODULUS - 1) / 2 ^ TWO_ADICITY + /// T = + /// 3445725192157866269698394841137828771239834456268075054756895080104811711121745868043841591644705843820432283876893306725580879560277123879674755849562650799475802549689254425186271815711798397975949850214984556421382456559534149 + /// (MODULUS - 1) / 2 ^ TWO_ADICITY + #[rustfmt::skip] const T: BigInteger = BigInteger([ 0x7a4e800000000045, 0xf3489f3438000041, @@ -135,10 +161,9 @@ impl FieldParameters for FqParameters { 0x68c3e4a0027d7f9f, 0x9174127dc1e705, ]); - // (MODULUS - 1) % 2^TWO_ADICITY == 0 - const TWO_ADICITY: u32 = 1; - // (T - 1)/2 = - // 1722862596078933134849197420568914385619917228134037527378447540052405855560872934021920795822352921910216141938446653362790439780138561939837377924781325399737901274844627212593135907855899198987974925107492278210691228279767074 + /// (T - 1)/2 = + /// 1722862596078933134849197420568914385619917228134037527378447540052405855560872934021920795822352921910216141938446653362790439780138561939837377924781325399737901274844627212593135907855899198987974925107492278210691228279767074 + #[rustfmt::skip] const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 0xbd27400000000022, 0xf9a44f9a1c000020, diff --git a/curves/src/edwards_bls12/fr.rs b/curves/src/edwards_bls12/fr.rs index a39d9bcd48..90017a00cc 100644 --- a/curves/src/edwards_bls12/fr.rs +++ b/curves/src/edwards_bls12/fr.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp256, Fp256Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp256, Fp256Parameters}; use snarkvm_utilities::biginteger::BigInteger256 as BigInteger; pub type Fr = Fp256; @@ -23,52 +23,67 @@ pub struct FrParameters; impl Fp256Parameters for FrParameters {} -impl FieldParameters for FrParameters { +impl FftParameters for FrParameters { type BigInteger = BigInteger; + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 15170730761708361161u64, + 13670723686578117817u64, + 12803492266614043665u64, + 50861023252832611u64, + ]); + const TWO_ADICITY: u32 = 1; +} + +impl FieldParameters for FrParameters { + #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - // 5 + /// 70865795004005329077606947863872807680085016823885970091001235374859923341923 + #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 11289572479685143826u64, 11383637369941080925u64, 2288212753973340071u64, 82014976407880291u64, ]); + #[rustfmt::skip] const INV: u64 = 9659935179256617473u64; - // MODULUS = 2111115437357092606062206234695386632838870926408408195193685246394721360383 + /// MODULUS = 2111115437357092606062206234695386632838870926408408195193685246394721360383 + #[rustfmt::skip] const MODULUS: BigInteger = BigInteger([ 13356249993388743167u64, 5950279507993463550u64, 10965441865914903552u64, 336320092672043349u64, ]); + #[rustfmt::skip] const MODULUS_BITS: u32 = 251; + #[rustfmt::skip] const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 6678124996694371583u64, 2975139753996731775u64, 14706092969812227584u64, 168160046336021674u64, ]); + #[rustfmt::skip] const R: BigInteger = BigInteger([ 16632263305389933622u64, 10726299895124897348u64, 16608693673010411502u64, 285459069419210737u64, ]); + #[rustfmt::skip] const R2: BigInteger = BigInteger([ 3987543627614508126u64, 17742427666091596403u64, 14557327917022607905u64, 322810149704226881u64, ]); + #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 5; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 15170730761708361161u64, - 13670723686578117817u64, - 12803492266614043665u64, - 50861023252832611u64, - ]); + #[rustfmt::skip] const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); - const TWO_ADICITY: u32 = 1; + #[rustfmt::skip] const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); } diff --git a/curves/src/edwards_sw6/fr.rs b/curves/src/edwards_sw6/fr.rs index b1f8cc2841..6b3e5228c7 100644 --- a/curves/src/edwards_sw6/fr.rs +++ b/curves/src/edwards_sw6/fr.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp384, Fp384Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp384, Fp384Parameters}; use snarkvm_utilities::biginteger::BigInteger384 as BigInteger; pub type Fr = Fp384; @@ -23,11 +23,26 @@ pub struct FrParameters; impl Fp384Parameters for FrParameters {} -impl FieldParameters for FrParameters { +impl FftParameters for FrParameters { type BigInteger = BigInteger; + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 12119792640622387781u64, + 8318439284650634613u64, + 6931324077796168275u64, + 12851391603681523141u64, + 6881015057611215092u64, + 1893962574900431u64, + ]); + const TWO_ADICITY: u32 = 2u32; +} + +impl FieldParameters for FrParameters { + #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - // 2 + /// 2 + #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 1999556893213776791u64, 13750542494830678672u64, @@ -36,8 +51,10 @@ impl FieldParameters for FrParameters { 15997990832658725900u64, 3914639203155617u64, ]); + #[rustfmt::skip] const INV: u64 = 16242011933465909059u64; - // MODULUS = 32333053251621136751331591711861691692049189094364332567435817881934511297123972799646723302813083835942624121493 + /// MODULUS = 32333053251621136751331591711861691692049189094364332567435817881934511297123972799646723302813083835942624121493 + #[rustfmt::skip] const MODULUS: BigInteger = BigInteger([ 4684667634276979349u64, 3748803659444032385u64, @@ -46,7 +63,9 @@ impl FieldParameters for FrParameters { 6397188139321141543u64, 15137289088311837u64, ]); + #[rustfmt::skip] const MODULUS_BITS: u32 = 374; + #[rustfmt::skip] const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 11565705853993265482u64, 1874401829722016192u64, @@ -55,6 +74,7 @@ impl FieldParameters for FrParameters { 12421966106515346579u64, 7568644544155918u64, ]); + #[rustfmt::skip] const R: BigInteger = BigInteger([ 12565484300600153878u64, 8749673077137355528u64, @@ -63,6 +83,7 @@ impl FieldParameters for FrParameters { 11197589485989933721u64, 9525964145733727u64, ]); + #[rustfmt::skip] const R2: BigInteger = BigInteger([ 17257035094703902127u64, 16096159112880350050u64, @@ -71,16 +92,10 @@ impl FieldParameters for FrParameters { 1125865524035793947u64, 1586246138566285u64, ]); + #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 10; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 12119792640622387781u64, - 8318439284650634613u64, - 6931324077796168275u64, - 12851391603681523141u64, - 6881015057611215092u64, - 1893962574900431u64, - ]); + #[rustfmt::skip] const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); - const TWO_ADICITY: u32 = 2u32; + #[rustfmt::skip] const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); } diff --git a/curves/src/sw6/fq.rs b/curves/src/sw6/fq.rs index 1806d6cdff..0d89c071c8 100644 --- a/curves/src/sw6/fq.rs +++ b/curves/src/sw6/fq.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp832, Fp832Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp832, Fp832Parameters}; use snarkvm_utilities::biginteger::BigInteger832 as BigInteger; pub type Fq = Fp832; @@ -23,9 +23,29 @@ pub struct FqParameters; impl Fp832Parameters for FqParameters {} -impl FieldParameters for FqParameters { +impl FftParameters for FqParameters { type BigInteger = BigInteger; + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 18044746167194862600u64, + 63590321303744709u64, + 5009346151370959890u64, + 2859114157767503991u64, + 8301813204852325413u64, + 5629414263664332594u64, + 2637340888701394641u64, + 17433538052687852753u64, + 2230763098934759248u64, + 3785382115983092023u64, + 8895511354022222370u64, + 15792083141709071785u64, + 1328u64, + ]); + const TWO_ADICITY: u32 = 3; +} + +impl FieldParameters for FqParameters { const CAPACITY: u32 = Self::MODULUS_BITS - 1; /// GENERATOR = 13 const GENERATOR: BigInteger = BigInteger([ @@ -107,21 +127,6 @@ impl FieldParameters for FqParameters { 7833u64, ]); const REPR_SHAVE_BITS: u32 = 50; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 18044746167194862600u64, - 63590321303744709u64, - 5009346151370959890u64, - 2859114157767503991u64, - 8301813204852325413u64, - 5629414263664332594u64, - 2637340888701394641u64, - 17433538052687852753u64, - 2230763098934759248u64, - 3785382115983092023u64, - 8895511354022222370u64, - 15792083141709071785u64, - 1328u64, - ]); // T = // 2796234287359462116293342775812631866846949933162148072772937078455846756557253067529059877268485152522256821925480238069737214402829166671516844553287632810960290821869823500141573291432819154425935511163079134531347828686569665103197 const T: BigInteger = BigInteger([ @@ -139,7 +144,6 @@ impl FieldParameters for FqParameters { 0x189a44c7757f1283, 0x709, ]); - const TWO_ADICITY: u32 = 3; // (T - 1)/2 = // 1398117143679731058146671387906315933423474966581074036386468539227923378278626533764529938634242576261128410962740119034868607201414583335758422276643816405480145410934911750070786645716409577212967755581539567265673914343284832551598 const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ diff --git a/fields/src/fp_256.rs b/fields/src/fp_256.rs index 5a2ed313bf..3b47c00f3c 100644 --- a/fields/src/fp_256.rs +++ b/fields/src/fp_256.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger256 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -320,13 +320,27 @@ impl PrimeField for Fp256

{ } #[inline] - fn multiplicative_generator() -> Self { - Fp256::

(P::GENERATOR, PhantomData) + fn root_of_unity() -> Self { + Fp256::

(P::ROOT_OF_UNITY, PhantomData) } +} + +impl FftField for Fp256

{ + type FftParameters = P; #[inline] - fn root_of_unity() -> Self { - Fp256::

(P::ROOT_OF_UNITY, PhantomData) + fn two_adic_root_of_unity() -> Self { + Self(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn large_subgroup_root_of_unity() -> Option { + Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData)) + } + + #[inline] + fn multiplicative_generator() -> Self { + Self(P::GENERATOR, PhantomData) } } diff --git a/fields/src/fp_320.rs b/fields/src/fp_320.rs index c02c0f9550..bd9e38235a 100644 --- a/fields/src/fp_320.rs +++ b/fields/src/fp_320.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger320 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -356,13 +356,27 @@ impl PrimeField for Fp320

{ } #[inline] - fn multiplicative_generator() -> Self { - Fp320::

(P::GENERATOR, PhantomData) + fn root_of_unity() -> Self { + Fp320::

(P::ROOT_OF_UNITY, PhantomData) } +} + +impl FftField for Fp320

{ + type FftParameters = P; #[inline] - fn root_of_unity() -> Self { - Fp320::

(P::ROOT_OF_UNITY, PhantomData) + fn two_adic_root_of_unity() -> Self { + Self(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn large_subgroup_root_of_unity() -> Option { + Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData)) + } + + #[inline] + fn multiplicative_generator() -> Self { + Self(P::GENERATOR, PhantomData) } } diff --git a/fields/src/fp_384.rs b/fields/src/fp_384.rs index e58df976e7..5c4c402b92 100644 --- a/fields/src/fp_384.rs +++ b/fields/src/fp_384.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger384 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -386,13 +386,27 @@ impl PrimeField for Fp384

{ } #[inline] - fn multiplicative_generator() -> Self { - Fp384::

(P::GENERATOR, PhantomData) + fn root_of_unity() -> Self { + Fp384::

(P::ROOT_OF_UNITY, PhantomData) } +} + +impl FftField for Fp384

{ + type FftParameters = P; #[inline] - fn root_of_unity() -> Self { - Fp384::

(P::ROOT_OF_UNITY, PhantomData) + fn two_adic_root_of_unity() -> Self { + Self(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn large_subgroup_root_of_unity() -> Option { + Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData)) + } + + #[inline] + fn multiplicative_generator() -> Self { + Self(P::GENERATOR, PhantomData) } } diff --git a/fields/src/fp_768.rs b/fields/src/fp_768.rs index 9d5c9ca086..a65d99a494 100644 --- a/fields/src/fp_768.rs +++ b/fields/src/fp_768.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger768 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -698,11 +698,6 @@ impl PrimeField for Fp768

{ r.0 } - #[inline] - fn multiplicative_generator() -> Self { - Fp768::

(P::GENERATOR, PhantomData) - } - #[inline] fn root_of_unity() -> Self { Fp768::

(P::ROOT_OF_UNITY, PhantomData) @@ -729,6 +724,25 @@ impl PrimeField for Fp768

{ } } +impl FftField for Fp768

{ + type FftParameters = P; + + #[inline] + fn two_adic_root_of_unity() -> Self { + Self(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn large_subgroup_root_of_unity() -> Option { + Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData)) + } + + #[inline] + fn multiplicative_generator() -> Self { + Self(P::GENERATOR, PhantomData) + } +} + impl SquareRootField for Fp768

{ #[inline] fn legendre(&self) -> LegendreSymbol { diff --git a/fields/src/fp_832.rs b/fields/src/fp_832.rs index df3b416ae2..4dc5f5d72f 100644 --- a/fields/src/fp_832.rs +++ b/fields/src/fp_832.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger832 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -667,11 +667,6 @@ impl PrimeField for Fp832

{ r.0 } - #[inline] - fn multiplicative_generator() -> Self { - Fp832::

(P::GENERATOR, PhantomData) - } - #[inline] fn root_of_unity() -> Self { Fp832::

(P::ROOT_OF_UNITY, PhantomData) @@ -698,6 +693,25 @@ impl PrimeField for Fp832

{ } } +impl FftField for Fp832

{ + type FftParameters = P; + + #[inline] + fn two_adic_root_of_unity() -> Self { + Self(P::ROOT_OF_UNITY, PhantomData) + } + + #[inline] + fn large_subgroup_root_of_unity() -> Option { + Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData)) + } + + #[inline] + fn multiplicative_generator() -> Self { + Self(P::GENERATOR, PhantomData) + } +} + impl SquareRootField for Fp832

{ #[inline] fn legendre(&self) -> LegendreSymbol { diff --git a/fields/src/traits/fft_field.rs b/fields/src/traits/fft_field.rs new file mode 100644 index 0000000000..6de5f5bcee --- /dev/null +++ b/fields/src/traits/fft_field.rs @@ -0,0 +1,103 @@ +// Copyright (C) 2019-2021 Aleo Systems Inc. +// This file is part of the snarkVM library. + +// The snarkVM library is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// The snarkVM library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with the snarkVM library. If not, see . + +use crate::traits::{FftParameters, Field}; + +/// The interface for fields that are able to be used in FFTs. +pub trait FftField: Field + From + From + From + From + From { + type FftParameters: FftParameters; + + /// Returns the 2^s root of unity. + fn two_adic_root_of_unity() -> Self; + + /// Returns the 2^s * small_subgroup_base^small_subgroup_base_adicity root of unity + /// if a small subgroup is defined. + fn large_subgroup_root_of_unity() -> Option; + + /// Returns the multiplicative generator of `char()` - 1 order. + fn multiplicative_generator() -> Self; + + /// Returns the root of unity of order n, if one exists. + /// If no small multiplicative subgroup is defined, this is the 2-adic root of unity of order n + /// (for n a power of 2). + /// If a small multiplicative subgroup is defined, this is the root of unity of order n for + /// the larger subgroup generated by `FftParams::LARGE_SUBGROUP_ROOT_OF_UNITY` + /// (for n = 2^i * FftParams::SMALL_SUBGROUP_BASE^j for some i, j). + fn get_root_of_unity(n: usize) -> Option { + let mut omega: Self; + if let Some(large_subgroup_root_of_unity) = Self::large_subgroup_root_of_unity() { + let q = Self::FftParameters::SMALL_SUBGROUP_BASE + .expect("LARGE_SUBGROUP_ROOT_OF_UNITY should only be set in conjunction with SMALL_SUBGROUP_BASE") + as usize; + let small_subgroup_base_adicity = Self::FftParameters::SMALL_SUBGROUP_BASE_ADICITY.expect( + "LARGE_SUBGROUP_ROOT_OF_UNITY should only be set in conjunction with SMALL_SUBGROUP_BASE_ADICITY", + ); + + let q_adicity = Self::k_adicity(q, n); + let q_part = q.pow(q_adicity); + + let two_adicity = Self::k_adicity(2, n); + let two_part = 1 << two_adicity; + + if n != two_part * q_part + || (two_adicity > Self::FftParameters::TWO_ADICITY) + || (q_adicity > small_subgroup_base_adicity) + { + return None; + } + + omega = large_subgroup_root_of_unity; + for _ in q_adicity..small_subgroup_base_adicity { + omega = omega.pow(&[q as u64]); + } + + for _ in two_adicity..Self::FftParameters::TWO_ADICITY { + omega.square_in_place(); + } + } else { + // Compute the next power of 2. + let size = n.next_power_of_two() as u64; + let log_size_of_group = size.trailing_zeros(); + + if n != size as usize || log_size_of_group > Self::FftParameters::TWO_ADICITY { + return None; + } + + // Compute the generator for the multiplicative subgroup. + // It should be 2^(log_size_of_group) root of unity. + omega = Self::two_adic_root_of_unity(); + for _ in log_size_of_group..Self::FftParameters::TWO_ADICITY { + omega.square_in_place(); + } + } + Some(omega) + } + + /// Calculates the k-adicity of n, i.e., the number of trailing 0s in a base-k + /// representation. + fn k_adicity(k: usize, mut n: usize) -> u32 { + let mut r = 0; + while n > 1 { + if n % k == 0 { + r += 1; + n /= k; + } else { + return r; + } + } + r + } +} diff --git a/fields/src/traits/fft_parameters.rs b/fields/src/traits/fft_parameters.rs new file mode 100644 index 0000000000..27ae5dd1c9 --- /dev/null +++ b/fields/src/traits/fft_parameters.rs @@ -0,0 +1,43 @@ +// Copyright (C) 2019-2021 Aleo Systems Inc. +// This file is part of the snarkVM library. + +// The snarkVM library is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// The snarkVM library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with the snarkVM library. If not, see . + +use snarkvm_utilities::biginteger::BigInteger; + +/// A trait that defines parameters for a field that can be used for FFTs. +pub trait FftParameters: 'static + Send + Sync + Sized { + type BigInteger: BigInteger; + + /// Let `N` be the size of the multiplicative group defined by the field. + /// Then `TWO_ADICITY` is the two-adicity of `N`, i.e. the integer `s` + /// such that `N = 2^s * t` for some odd integer `t`. + /// 2^s * t = MODULUS - 1 with t odd. This is the two-adicity of the prime. + const TWO_ADICITY: u32; + + /// 2^s root of unity computed by GENERATOR^t + const ROOT_OF_UNITY: Self::BigInteger; + + /// An integer `b` such that there exists a multiplicative subgroup + /// of size `b^k` for some integer `k`. + const SMALL_SUBGROUP_BASE: Option = None; + + /// The integer `k` such that there exists a multiplicative subgroup + /// of size `Self::SMALL_SUBGROUP_BASE^k`. + const SMALL_SUBGROUP_BASE_ADICITY: Option = None; + + /// GENERATOR^((MODULUS-1) / (2^s * + /// SMALL_SUBGROUP_BASE^SMALL_SUBGROUP_BASE_ADICITY)) Used for mixed-radix FFT. + const LARGE_SUBGROUP_ROOT_OF_UNITY: Option = None; +} diff --git a/fields/src/traits/field.rs b/fields/src/traits/field.rs index c434448a56..2c2d3a2fd3 100644 --- a/fields/src/traits/field.rs +++ b/fields/src/traits/field.rs @@ -38,7 +38,8 @@ use serde::{Deserialize, Serialize}; /// The interface for a generic field. pub trait Field: - ToBytes + 'static + + ToBytes + FromBytes + Copy + Clone @@ -47,12 +48,12 @@ pub trait Field: + Default + Send + Sync - + 'static + Eq + One + Ord + Neg + UniformRand + + Zero + Sized + Hash + From @@ -75,7 +76,6 @@ pub trait Field: + CanonicalDeserializeWithFlags + Serialize + for<'a> Deserialize<'a> - + Zero { /// Returns the characteristic of the field. fn characteristic<'a>() -> &'a [u64]; diff --git a/fields/src/traits/field_parameters.rs b/fields/src/traits/field_parameters.rs index 6d2f9213e7..a91256e4a9 100644 --- a/fields/src/traits/field_parameters.rs +++ b/fields/src/traits/field_parameters.rs @@ -14,12 +14,10 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_utilities::biginteger::*; +use crate::traits::FftParameters; /// A trait that defines parameters for a prime field. -pub trait FieldParameters: 'static + Send + Sync + Sized { - type BigInteger: BigInteger; - +pub trait FieldParameters: 'static + FftParameters { /// The modulus of the field. const MODULUS: Self::BigInteger; @@ -50,12 +48,6 @@ pub trait FieldParameters: 'static + Send + Sync + Sized { /// (Should equal `SELF::MODULUS_BITS - 1`) const CAPACITY: u32; - /// 2^s * t = MODULUS - 1 with t odd. This is the two-adicity of the prime. - const TWO_ADICITY: u32; - - /// 2^s root of unity computed by GENERATOR^t - const ROOT_OF_UNITY: Self::BigInteger; - /// t for 2^s * t = MODULUS - 1 const T: Self::BigInteger; diff --git a/fields/src/traits/mod.rs b/fields/src/traits/mod.rs index 6d83a63f21..2968aa2f38 100644 --- a/fields/src/traits/mod.rs +++ b/fields/src/traits/mod.rs @@ -14,6 +14,12 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . +mod fft_field; +pub use fft_field::*; + +mod fft_parameters; +pub use fft_parameters::*; + mod field; pub use field::*; diff --git a/fields/src/traits/prime_field.rs b/fields/src/traits/prime_field.rs index d52c289ddf..3c97172b8c 100644 --- a/fields/src/traits/prime_field.rs +++ b/fields/src/traits/prime_field.rs @@ -14,14 +14,14 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, FieldParameters}; +use crate::{FftField, Field, FieldParameters}; use snarkvm_utilities::biginteger::BigInteger; use std::str::FromStr; /// The interface for a prime field. #[allow(clippy::wrong_self_convention)] -pub trait PrimeField: Field + FromStr { +pub trait PrimeField: FftField::Parameters> + Field + FromStr { type Parameters: FieldParameters; type BigInteger: BigInteger; @@ -37,9 +37,6 @@ pub trait PrimeField: Field + FromStr { /// Returns the underlying raw representation of the prime field element. fn into_repr_raw(&self) -> Self::BigInteger; - /// Returns the multiplicative generator of `char()` - 1 order. - fn multiplicative_generator() -> Self; - /// Returns the 2^s root of unity. fn root_of_unity() -> Self; @@ -55,12 +52,20 @@ pub trait PrimeField: Field + FromStr { /// Returns the trace. fn trace() -> Self::BigInteger { - Self::Parameters::T + // TODO (howardwu): This function has been disabled as + // `snarkvm_curves::edwards_bls12::Fr` and `snarkvm_curves::edwards_sw6::Fr` + // do NOT implement `FieldParameters::T` or `FieldParameters::T_MINUS_ONE_DIV_TWO`. + unimplemented!() + // Self::Parameters::T } /// Returns the trace minus one divided by two. fn trace_minus_one_div_two() -> Self::BigInteger { - Self::Parameters::T_MINUS_ONE_DIV_TWO + // TODO (howardwu): This function has been disabled as + // `snarkvm_curves::edwards_bls12::Fr` and `snarkvm_curves::edwards_sw6::Fr` + // do NOT implement `FieldParameters::T` or `FieldParameters::T_MINUS_ONE_DIV_TWO`. + unimplemented!() + // Self::Parameters::T_MINUS_ONE_DIV_TWO } /// Returns the modulus minus one divided by two. diff --git a/r1cs/src/test_fr.rs b/r1cs/src/test_fr.rs index a895402cc2..cae77fff8f 100644 --- a/r1cs/src/test_fr.rs +++ b/r1cs/src/test_fr.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::{FieldParameters, Fp256, Fp256Parameters}; +use snarkvm_fields::{FftParameters, FieldParameters, Fp256, Fp256Parameters}; use snarkvm_utilities::biginteger::BigInteger256 as BigInteger; /// This field is the scalar field (Fr) of BLS12-377. @@ -24,61 +24,86 @@ pub struct FrParameters; impl Fp256Parameters for FrParameters {} -impl FieldParameters for FrParameters { +impl FftParameters for FrParameters { type BigInteger = BigInteger; + #[rustfmt::skip] + const ROOT_OF_UNITY: BigInteger = BigInteger([ + 0x3c3d3ca739381fb2, + 0x9a14cda3ec99772b, + 0xd7aacc7c59724826, + 0xd1ba211c5cc349c, + ]); + #[rustfmt::skip] + const TWO_ADICITY: u32 = 47; +} + +impl FieldParameters for FrParameters { + #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - // GENERATOR = 11 + /// GENERATOR = 11 + #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 1855201571499933546u64, 8511318076631809892u64, 6222514765367795509u64, 1122129207579058019u64, ]); + #[rustfmt::skip] const INV: u64 = 725501752471715839u64; - // MODULUS = 8444461749428370424248824938781546531375899335154063827935233455917409239041 + /// MODULUS = 8444461749428370424248824938781546531375899335154063827935233455917409239041 + #[rustfmt::skip] const MODULUS: BigInteger = BigInteger([ 725501752471715841u64, 6461107452199829505u64, 6968279316240510977u64, 1345280370688173398u64, ]); + #[rustfmt::skip] const MODULUS_BITS: u32 = 253; /// (r - 1)/2 = /// 4222230874714185212124412469390773265687949667577031913967616727958704619520 + #[rustfmt::skip] const MODULUS_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ 0x8508c00000000000, 0xacd53b7f68000000, 0x305a268f2e1bd800, 0x955b2af4d1652ab, ]); + #[rustfmt::skip] const R: BigInteger = BigInteger([ 9015221291577245683u64, 8239323489949974514u64, 1646089257421115374u64, 958099254763297437u64, ]); + #[rustfmt::skip] const R2: BigInteger = BigInteger([ 2726216793283724667u64, 14712177743343147295u64, 12091039717619697043u64, 81024008013859129u64, ]); + #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 3; - const ROOT_OF_UNITY: BigInteger = BigInteger([ - 0x3c3d3ca739381fb2, - 0x9a14cda3ec99772b, - 0xd7aacc7c59724826, - 0xd1ba211c5cc349c, - ]); // T and T_MINUS_ONE_DIV_TWO, where r - 1 = 2^s * t /// t = (r - 1) / 2^s = /// 60001509534603559531609739528203892656505753216962260608619555 - const T: BigInteger = BigInteger([0xedfda00000021423, 0x9a3cb86f6002b354, 0xcabd34594aacc168, 0x2556]); - const TWO_ADICITY: u32 = 47; + #[rustfmt::skip] + const T: BigInteger = BigInteger([ + 0xedfda00000021423, + 0x9a3cb86f6002b354, + 0xcabd34594aacc168, + 0x2556, + ]); /// (t - 1) / 2 = /// 30000754767301779765804869764101946328252876608481130304309777 - const T_MINUS_ONE_DIV_TWO: BigInteger = - BigInteger([0x76fed00000010a11, 0x4d1e5c37b00159aa, 0x655e9a2ca55660b4, 0x12ab]); + #[rustfmt::skip] + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 0x76fed00000010a11, + 0x4d1e5c37b00159aa, + 0x655e9a2ca55660b4, + 0x12ab, + ]); } From 8873c10fc552c6088348c4a8a39a06c560c0d908 Mon Sep 17 00:00:00 2001 From: howardwu Date: Thu, 24 Jun 2021 20:42:08 -0700 Subject: [PATCH 02/13] Rename FftParameters::ROOT_OF_UNITY to FftParameters::TWO_ADIC_ROOT_OF_UNITY --- curves/src/bls12_377/fq.rs | 6 +++--- curves/src/bls12_377/fr.rs | 6 +++--- curves/src/bw6_761/fq.rs | 16 ++++++++-------- curves/src/edwards_bls12/fr.rs | 4 ++-- curves/src/edwards_sw6/fr.rs | 4 ++-- curves/src/sw6/fq.rs | 4 ++-- fields/src/fp_256.rs | 4 ++-- fields/src/fp_320.rs | 4 ++-- fields/src/fp_384.rs | 4 ++-- fields/src/fp_768.rs | 4 ++-- fields/src/fp_832.rs | 4 ++-- fields/src/traits/fft_parameters.rs | 2 +- r1cs/src/test_fr.rs | 6 +++--- 13 files changed, 34 insertions(+), 34 deletions(-) diff --git a/curves/src/bls12_377/fq.rs b/curves/src/bls12_377/fq.rs index 91561499c8..5f47458ad9 100644 --- a/curves/src/bls12_377/fq.rs +++ b/curves/src/bls12_377/fq.rs @@ -27,7 +27,9 @@ impl FftParameters for FqParameters { type BigInteger = BigInteger; #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADICITY: u32 = 46u32; + #[rustfmt::skip] + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 2022196864061697551u64, 17419102863309525423u64, 8564289679875062096u64, @@ -35,8 +37,6 @@ impl FftParameters for FqParameters { 17966377291017729567u64, 68610905582439508u64, ]); - #[rustfmt::skip] - const TWO_ADICITY: u32 = 46u32; } impl FieldParameters for FqParameters { diff --git a/curves/src/bls12_377/fr.rs b/curves/src/bls12_377/fr.rs index 8b5e88958d..c2572f3a73 100644 --- a/curves/src/bls12_377/fr.rs +++ b/curves/src/bls12_377/fr.rs @@ -27,14 +27,14 @@ impl FftParameters for FrParameters { type BigInteger = BigInteger; #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADICITY: u32 = 47; + #[rustfmt::skip] + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 0x3c3d3ca739381fb2, 0x9a14cda3ec99772b, 0xd7aacc7c59724826, 0xd1ba211c5cc349c, ]); - #[rustfmt::skip] - const TWO_ADICITY: u32 = 47; } impl FieldParameters for FrParameters { diff --git a/curves/src/bw6_761/fq.rs b/curves/src/bw6_761/fq.rs index 399abd24fc..6bad3b56a8 100644 --- a/curves/src/bw6_761/fq.rs +++ b/curves/src/bw6_761/fq.rs @@ -26,9 +26,16 @@ impl Fp768Parameters for FqParameters {} impl FftParameters for FqParameters { type BigInteger = BigInteger; + // The internal representation of this type is six 64-bit unsigned + // integers in little-endian order. Values are always in + // Montgomery form; i.e., Scalar(a) = aR mod p, with R=2^768. + + /// (MODULUS - 1) % 2^TWO_ADICITY == 0 + #[rustfmt::skip] + const TWO_ADICITY: u32 = 1; /// least_quadratic_nonresidue(MODULUS) in Sage. #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 17481284903592032950u64, 10104133845767975835u64, 8607375506753517913u64, @@ -42,13 +49,6 @@ impl FftParameters for FqParameters { 18005297320867222879u64, 58811391084848524u64, ]); - // The internal representation of this type is six 64-bit unsigned - // integers in little-endian order. Values are always in - // Montgomery form; i.e., Scalar(a) = aR mod p, with R=2^768. - - /// (MODULUS - 1) % 2^TWO_ADICITY == 0 - #[rustfmt::skip] - const TWO_ADICITY: u32 = 1; } impl FieldParameters for FqParameters { diff --git a/curves/src/edwards_bls12/fr.rs b/curves/src/edwards_bls12/fr.rs index 90017a00cc..7aca1523d4 100644 --- a/curves/src/edwards_bls12/fr.rs +++ b/curves/src/edwards_bls12/fr.rs @@ -26,14 +26,14 @@ impl Fp256Parameters for FrParameters {} impl FftParameters for FrParameters { type BigInteger = BigInteger; + const TWO_ADICITY: u32 = 1; #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 15170730761708361161u64, 13670723686578117817u64, 12803492266614043665u64, 50861023252832611u64, ]); - const TWO_ADICITY: u32 = 1; } impl FieldParameters for FrParameters { diff --git a/curves/src/edwards_sw6/fr.rs b/curves/src/edwards_sw6/fr.rs index 6b3e5228c7..3638245e32 100644 --- a/curves/src/edwards_sw6/fr.rs +++ b/curves/src/edwards_sw6/fr.rs @@ -26,8 +26,9 @@ impl Fp384Parameters for FrParameters {} impl FftParameters for FrParameters { type BigInteger = BigInteger; + const TWO_ADICITY: u32 = 2u32; #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 12119792640622387781u64, 8318439284650634613u64, 6931324077796168275u64, @@ -35,7 +36,6 @@ impl FftParameters for FrParameters { 6881015057611215092u64, 1893962574900431u64, ]); - const TWO_ADICITY: u32 = 2u32; } impl FieldParameters for FrParameters { diff --git a/curves/src/sw6/fq.rs b/curves/src/sw6/fq.rs index 0d89c071c8..a6b76f04cb 100644 --- a/curves/src/sw6/fq.rs +++ b/curves/src/sw6/fq.rs @@ -26,8 +26,9 @@ impl Fp832Parameters for FqParameters {} impl FftParameters for FqParameters { type BigInteger = BigInteger; + const TWO_ADICITY: u32 = 3; #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 18044746167194862600u64, 63590321303744709u64, 5009346151370959890u64, @@ -42,7 +43,6 @@ impl FftParameters for FqParameters { 15792083141709071785u64, 1328u64, ]); - const TWO_ADICITY: u32 = 3; } impl FieldParameters for FqParameters { diff --git a/fields/src/fp_256.rs b/fields/src/fp_256.rs index 3b47c00f3c..1c5dad8d13 100644 --- a/fields/src/fp_256.rs +++ b/fields/src/fp_256.rs @@ -321,7 +321,7 @@ impl PrimeField for Fp256

{ #[inline] fn root_of_unity() -> Self { - Fp256::

(P::ROOT_OF_UNITY, PhantomData) + Fp256::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } } @@ -330,7 +330,7 @@ impl FftField for Fp256

{ #[inline] fn two_adic_root_of_unity() -> Self { - Self(P::ROOT_OF_UNITY, PhantomData) + Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] diff --git a/fields/src/fp_320.rs b/fields/src/fp_320.rs index bd9e38235a..30ca549101 100644 --- a/fields/src/fp_320.rs +++ b/fields/src/fp_320.rs @@ -357,7 +357,7 @@ impl PrimeField for Fp320

{ #[inline] fn root_of_unity() -> Self { - Fp320::

(P::ROOT_OF_UNITY, PhantomData) + Fp320::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } } @@ -366,7 +366,7 @@ impl FftField for Fp320

{ #[inline] fn two_adic_root_of_unity() -> Self { - Self(P::ROOT_OF_UNITY, PhantomData) + Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] diff --git a/fields/src/fp_384.rs b/fields/src/fp_384.rs index 5c4c402b92..68c824ed28 100644 --- a/fields/src/fp_384.rs +++ b/fields/src/fp_384.rs @@ -387,7 +387,7 @@ impl PrimeField for Fp384

{ #[inline] fn root_of_unity() -> Self { - Fp384::

(P::ROOT_OF_UNITY, PhantomData) + Fp384::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } } @@ -396,7 +396,7 @@ impl FftField for Fp384

{ #[inline] fn two_adic_root_of_unity() -> Self { - Self(P::ROOT_OF_UNITY, PhantomData) + Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] diff --git a/fields/src/fp_768.rs b/fields/src/fp_768.rs index a65d99a494..14f895c998 100644 --- a/fields/src/fp_768.rs +++ b/fields/src/fp_768.rs @@ -700,7 +700,7 @@ impl PrimeField for Fp768

{ #[inline] fn root_of_unity() -> Self { - Fp768::

(P::ROOT_OF_UNITY, PhantomData) + Fp768::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] @@ -729,7 +729,7 @@ impl FftField for Fp768

{ #[inline] fn two_adic_root_of_unity() -> Self { - Self(P::ROOT_OF_UNITY, PhantomData) + Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] diff --git a/fields/src/fp_832.rs b/fields/src/fp_832.rs index 4dc5f5d72f..ac6696190d 100644 --- a/fields/src/fp_832.rs +++ b/fields/src/fp_832.rs @@ -669,7 +669,7 @@ impl PrimeField for Fp832

{ #[inline] fn root_of_unity() -> Self { - Fp832::

(P::ROOT_OF_UNITY, PhantomData) + Fp832::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] @@ -698,7 +698,7 @@ impl FftField for Fp832

{ #[inline] fn two_adic_root_of_unity() -> Self { - Self(P::ROOT_OF_UNITY, PhantomData) + Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) } #[inline] diff --git a/fields/src/traits/fft_parameters.rs b/fields/src/traits/fft_parameters.rs index 27ae5dd1c9..340a1319e7 100644 --- a/fields/src/traits/fft_parameters.rs +++ b/fields/src/traits/fft_parameters.rs @@ -27,7 +27,7 @@ pub trait FftParameters: 'static + Send + Sync + Sized { const TWO_ADICITY: u32; /// 2^s root of unity computed by GENERATOR^t - const ROOT_OF_UNITY: Self::BigInteger; + const TWO_ADIC_ROOT_OF_UNITY: Self::BigInteger; /// An integer `b` such that there exists a multiplicative subgroup /// of size `b^k` for some integer `k`. diff --git a/r1cs/src/test_fr.rs b/r1cs/src/test_fr.rs index cae77fff8f..72ac77326c 100644 --- a/r1cs/src/test_fr.rs +++ b/r1cs/src/test_fr.rs @@ -28,14 +28,14 @@ impl FftParameters for FrParameters { type BigInteger = BigInteger; #[rustfmt::skip] - const ROOT_OF_UNITY: BigInteger = BigInteger([ + const TWO_ADICITY: u32 = 47; + #[rustfmt::skip] + const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ 0x3c3d3ca739381fb2, 0x9a14cda3ec99772b, 0xd7aacc7c59724826, 0xd1ba211c5cc349c, ]); - #[rustfmt::skip] - const TWO_ADICITY: u32 = 47; } impl FieldParameters for FrParameters { From e4e30bbf2e716d686e24bbeb8c515e2178309ce8 Mon Sep 17 00:00:00 2001 From: howardwu Date: Thu, 24 Jun 2021 21:06:36 -0700 Subject: [PATCH 03/13] Update FFT EvaluationDomain to support FftField --- algorithms/src/fft/domain.rs | 54 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/algorithms/src/fft/domain.rs b/algorithms/src/fft/domain.rs index 3b72c0aad8..44653fa212 100644 --- a/algorithms/src/fft/domain.rs +++ b/algorithms/src/fft/domain.rs @@ -27,7 +27,7 @@ //! by performing an O(n log n) FFT over such a domain. use crate::fft::{multicore::Worker, SparsePolynomial}; -use snarkvm_fields::{batch_inversion, FftParameters, PrimeField}; +use snarkvm_fields::{batch_inversion, FftField, FftParameters}; use snarkvm_utilities::{errors::SerializationError, serialize::*}; use rand::Rng; @@ -51,7 +51,7 @@ fn log2(number: usize) -> usize { /// only for fields that have a large multiplicative subgroup of size that is /// a power-of-2. #[derive(Copy, Clone, Hash, Eq, PartialEq, CanonicalSerialize, CanonicalDeserialize)] -pub struct EvaluationDomain { +pub struct EvaluationDomain { /// The size of the domain. pub size: u64, /// `log_2(self.size)`. @@ -68,13 +68,13 @@ pub struct EvaluationDomain { pub generator_inv: F, } -impl fmt::Debug for EvaluationDomain { +impl fmt::Debug for EvaluationDomain { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Multiplicative subgroup of size {}", self.size) } } -impl EvaluationDomain { +impl EvaluationDomain { fn calculate_chunk_size(size: usize) -> usize { match size / rayon::current_num_threads() { 0 => 1, @@ -98,19 +98,19 @@ impl EvaluationDomain { let size = num_coeffs.next_power_of_two() as u64; let log_size_of_group = size.trailing_zeros(); - if log_size_of_group >= F::Parameters::TWO_ADICITY { + // libfqfft uses > https://github.com/scipr-lab/libfqfft/blob/e0183b2cef7d4c5deb21a6eaf3fe3b586d738fe0/libfqfft/evaluation_domain/domains/basic_radix2_domain.tcc#L33 + if log_size_of_group > F::FftParameters::TWO_ADICITY { return None; } // Compute the generator for the multiplicative subgroup. - // It should be 2^(log_size_of_group) root of unity. - let mut group_gen = F::root_of_unity(); - for _ in log_size_of_group..F::Parameters::TWO_ADICITY { - group_gen.square_in_place(); - } + // It should be the 2^(log_size_of_group) root of unity. + let group_gen = F::get_root_of_unity(size as usize)?; + + // Check that it is indeed the 2^(log_size_of_group) root of unity. + debug_assert_eq!(group_gen.pow([size]), F::one()); - let size_as_bigint = F::BigInteger::from(size); - let size_as_field_element = F::from_repr(size_as_bigint)?; + let size_as_field_element = F::from(size); let size_inv = size_as_field_element.inverse()?; Some(EvaluationDomain { @@ -128,7 +128,7 @@ impl EvaluationDomain { /// having `num_coeffs` coefficients. pub fn compute_size_of_domain(num_coeffs: usize) -> Option { let size = num_coeffs.next_power_of_two(); - if size.trailing_zeros() < F::Parameters::TWO_ADICITY { + if size.trailing_zeros() <= F::FftParameters::TWO_ADICITY { Some(size) } else { None @@ -140,27 +140,27 @@ impl EvaluationDomain { self.size as usize } - /// Compute a FFT. + /// Compute an FFT. pub fn fft(&self, coeffs: &[F]) -> Vec { let mut coeffs = coeffs.to_vec(); self.fft_in_place(&mut coeffs); coeffs } - /// Compute a FFT, modifying the vector in place. + /// Compute an FFT, modifying the vector in place. pub fn fft_in_place(&self, coeffs: &mut Vec) { coeffs.resize(self.size(), F::zero()); best_fft(coeffs, &Worker::new(), self.group_gen, self.log_size_of_group) } - /// Compute a IFFT. + /// Compute an IFFT. pub fn ifft(&self, evals: &[F]) -> Vec { let mut evals = evals.to_vec(); self.ifft_in_place(&mut evals); evals } - /// Compute a IFFT, modifying the vector in place. + /// Compute an IFFT, modifying the vector in place. #[inline] pub fn ifft_in_place(&self, evals: &mut Vec) { evals.resize(self.size(), F::zero()); @@ -168,28 +168,28 @@ impl EvaluationDomain { cfg_iter_mut!(evals).for_each(|val| *val *= &self.size_inv); } - /// Compute a FFT over a coset of the domain. + /// Compute an FFT over a coset of the domain. pub fn coset_fft(&self, coeffs: &[F]) -> Vec { let mut coeffs = coeffs.to_vec(); self.coset_fft_in_place(&mut coeffs); coeffs } - /// Compute a FFT over a coset of the domain, modifying the input vector + /// Compute an FFT over a coset of the domain, modifying the input vector /// in place. pub fn coset_fft_in_place(&self, coeffs: &mut Vec) { Self::distribute_powers(coeffs, F::multiplicative_generator()); self.fft_in_place(coeffs); } - /// Compute a IFFT over a coset of the domain. + /// Compute an IFFT over a coset of the domain. pub fn coset_ifft(&self, evals: &[F]) -> Vec { let mut evals = evals.to_vec(); self.coset_ifft_in_place(&mut evals); evals } - /// Compute a IFFT over a coset of the domain, modifying the input vector in place. + /// Compute an IFFT over a coset of the domain, modifying the input vector in place. pub fn coset_ifft_in_place(&self, evals: &mut Vec) { self.ifft_in_place(evals); Self::distribute_powers(evals, self.generator_inv); @@ -415,12 +415,12 @@ impl EvaluationDomain { #[allow(unused_variables)] #[cfg(not(feature = "parallel"))] -fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { +fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { serial_radix2_fft(a, omega, log_n); } #[cfg(feature = "parallel")] -fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { +fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { let log_cpus = worker.log_num_cpus(); if log_n <= log_cpus { @@ -431,7 +431,7 @@ fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { } #[allow(clippy::many_single_char_names)] -pub(crate) fn serial_radix2_fft(a: &mut [F], omega: F, log_n: u32) { +pub(crate) fn serial_radix2_fft(a: &mut [F], omega: F, log_n: u32) { #[inline] fn bitreverse(mut n: u32, l: u32) -> u32 { let mut r = 0; @@ -477,7 +477,7 @@ pub(crate) fn serial_radix2_fft(a: &mut [F], omega: F, log_n: u32 } #[cfg(feature = "parallel")] -pub(crate) fn parallel_radix2_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32, log_cpus: u32) { +pub(crate) fn parallel_radix2_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32, log_cpus: u32) { assert!(log_n >= log_cpus); let num_cpus = 1 << log_cpus; @@ -530,13 +530,13 @@ pub(crate) fn parallel_radix2_fft(a: &mut [F], worker: &Worker, o } /// An iterator over the elements of the domain. -pub struct Elements { +pub struct Elements { cur_elem: F, cur_pow: u64, domain: EvaluationDomain, } -impl Iterator for Elements { +impl Iterator for Elements { type Item = F; fn next(&mut self) -> Option { From ea84da7862db19b7f3919871584477db96729c19 Mon Sep 17 00:00:00 2001 From: howardwu Date: Thu, 24 Jun 2021 22:44:52 -0700 Subject: [PATCH 04/13] Adds Field arithmetic without reference, adds DomainCoeff to FFT --- algorithms/src/fft/domain.rs | 188 ++++++------ algorithms/src/fft/mod.rs | 23 +- algorithms/src/fft/multicore.rs | 100 ------- algorithms/src/fft/tests.rs | 7 +- algorithms/src/snark/gm17/r1cs_to_sap.rs | 2 +- algorithms/tests/snark/mimc.rs | 2 +- .../short_weierstrass_jacobian.rs | 10 +- fields/src/fp12_2over3over2.rs | 3 + fields/src/fp2.rs | 7 +- fields/src/fp3.rs | 3 + fields/src/fp6_2over3.rs | 3 + fields/src/fp6_3over2.rs | 3 + fields/src/fp_256.rs | 17 +- fields/src/fp_320.rs | 17 +- fields/src/fp_384.rs | 17 +- fields/src/fp_768.rs | 17 +- fields/src/fp_832.rs | 17 +- fields/src/lib.rs | 8 +- fields/src/macros.rs | 268 ++++++++++++++++++ fields/src/traits/field.rs | 14 +- fields/src/traits/prime_field.rs | 4 +- marlin/src/ahp/prover/prover.rs | 2 +- .../src/constraints/lagrange_interpolation.rs | 2 +- 23 files changed, 503 insertions(+), 231 deletions(-) delete mode 100644 algorithms/src/fft/multicore.rs diff --git a/algorithms/src/fft/domain.rs b/algorithms/src/fft/domain.rs index 44653fa212..713ac60863 100644 --- a/algorithms/src/fft/domain.rs +++ b/algorithms/src/fft/domain.rs @@ -26,7 +26,7 @@ //! This allows us to perform polynomial operations in O(n) //! by performing an O(n log n) FFT over such a domain. -use crate::fft::{multicore::Worker, SparsePolynomial}; +use crate::fft::{DomainCoeff, SparsePolynomial}; use snarkvm_fields::{batch_inversion, FftField, FftParameters}; use snarkvm_utilities::{errors::SerializationError, serialize::*}; @@ -75,13 +75,6 @@ impl fmt::Debug for EvaluationDomain { } impl EvaluationDomain { - fn calculate_chunk_size(size: usize) -> usize { - match size / rayon::current_num_threads() { - 0 => 1, - chunk_size => chunk_size, - } - } - /// Sample an element that is *not* in the domain. pub fn sample_element_outside_domain(&self, rng: &mut R) -> F { let mut t = F::rand(rng); @@ -141,20 +134,20 @@ impl EvaluationDomain { } /// Compute an FFT. - pub fn fft(&self, coeffs: &[F]) -> Vec { + pub fn fft>(&self, coeffs: &[T]) -> Vec { let mut coeffs = coeffs.to_vec(); self.fft_in_place(&mut coeffs); coeffs } /// Compute an FFT, modifying the vector in place. - pub fn fft_in_place(&self, coeffs: &mut Vec) { - coeffs.resize(self.size(), F::zero()); - best_fft(coeffs, &Worker::new(), self.group_gen, self.log_size_of_group) + pub fn fft_in_place>(&self, coeffs: &mut Vec) { + coeffs.resize(self.size(), T::zero()); + best_fft(coeffs, self.group_gen, self.log_size_of_group) } /// Compute an IFFT. - pub fn ifft(&self, evals: &[F]) -> Vec { + pub fn ifft>(&self, evals: &[T]) -> Vec { let mut evals = evals.to_vec(); self.ifft_in_place(&mut evals); evals @@ -162,14 +155,14 @@ impl EvaluationDomain { /// Compute an IFFT, modifying the vector in place. #[inline] - pub fn ifft_in_place(&self, evals: &mut Vec) { - evals.resize(self.size(), F::zero()); - best_fft(evals, &Worker::new(), self.group_gen_inv, self.log_size_of_group); - cfg_iter_mut!(evals).for_each(|val| *val *= &self.size_inv); + pub fn ifft_in_place>(&self, evals: &mut Vec) { + evals.resize(self.size(), T::zero()); + best_fft(evals, self.group_gen_inv, self.log_size_of_group); + cfg_iter_mut!(evals).for_each(|val| *val *= self.size_inv); } /// Compute an FFT over a coset of the domain. - pub fn coset_fft(&self, coeffs: &[F]) -> Vec { + pub fn coset_fft>(&self, coeffs: &[T]) -> Vec { let mut coeffs = coeffs.to_vec(); self.coset_fft_in_place(&mut coeffs); coeffs @@ -177,36 +170,30 @@ impl EvaluationDomain { /// Compute an FFT over a coset of the domain, modifying the input vector /// in place. - pub fn coset_fft_in_place(&self, coeffs: &mut Vec) { + pub fn coset_fft_in_place>(&self, coeffs: &mut Vec) { Self::distribute_powers(coeffs, F::multiplicative_generator()); self.fft_in_place(coeffs); } /// Compute an IFFT over a coset of the domain. - pub fn coset_ifft(&self, evals: &[F]) -> Vec { + pub fn coset_ifft>(&self, evals: &[T]) -> Vec { let mut evals = evals.to_vec(); self.coset_ifft_in_place(&mut evals); evals } /// Compute an IFFT over a coset of the domain, modifying the input vector in place. - pub fn coset_ifft_in_place(&self, evals: &mut Vec) { + pub fn coset_ifft_in_place>(&self, evals: &mut Vec) { self.ifft_in_place(evals); Self::distribute_powers(evals, self.generator_inv); } - fn distribute_powers(coeffs: &mut Vec, g: F) { - Worker::new().scope(coeffs.len(), |scope, chunk| { - for (i, v) in coeffs.chunks_mut(chunk).enumerate() { - scope.spawn(move |_| { - let mut u = g.pow(&[(i * chunk) as u64]); - for v in v.iter_mut() { - *v *= &u; - u *= &g; - } - }); - } - }); + fn distribute_powers>(coeffs: &mut Vec, g: F) { + let mut pow = F::one(); + coeffs.iter_mut().for_each(|c| { + *c *= pow; + pow *= &g + }) } /// Evaluate all the lagrange polynomials defined by this domain at the point @@ -241,7 +228,7 @@ impl EvaluationDomain { batch_inversion(u.as_mut_slice()); cfg_iter_mut!(u).zip(ls).for_each(|(tau_minus_r, l)| { - *tau_minus_r = l * tau_minus_r; + *tau_minus_r = l * &*tau_minus_r; }); u } @@ -277,11 +264,7 @@ impl EvaluationDomain { .inverse() .unwrap(); - Worker::new().scope(evals.len(), |scope, chunk| { - for evals in evals.chunks_mut(chunk) { - scope.spawn(move |_| evals.iter_mut().for_each(|eval| *eval *= &i)); - } - }); + cfg_iter_mut!(evals).for_each(|eval| *eval *= &i); } /// Given an index which assumes the first elements of this domain are the elements of @@ -316,15 +299,10 @@ impl EvaluationDomain { #[must_use] pub fn mul_polynomials_in_evaluation_domain(&self, self_evals: &[F], other_evals: &[F]) -> Vec { assert_eq!(self_evals.len(), other_evals.len()); + let mut result = self_evals.to_vec(); - let chunk_size = Self::calculate_chunk_size(self.size()); - cfg_chunks_mut!(result, chunk_size) - .zip(cfg_chunks!(other_evals, chunk_size)) - .for_each(|(a, b)| { - for (a, b) in a.iter_mut().zip(b) { - *a *= b; - } - }); + cfg_iter_mut!(result).zip(other_evals).for_each(|(a, b)| *a *= b); + result } @@ -415,23 +393,24 @@ impl EvaluationDomain { #[allow(unused_variables)] #[cfg(not(feature = "parallel"))] -fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { +fn best_fft, F: FftField>(a: &mut [T], omega: F, log_n: u32) { serial_radix2_fft(a, omega, log_n); } #[cfg(feature = "parallel")] -fn best_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32) { - let log_cpus = worker.log_num_cpus(); +fn best_fft, F: FftField>(a: &mut [T], omega: F, log_n: u32) { + let num_cpus = rayon::current_num_threads(); + let log_cpus = log2_floor(num_cpus); if log_n <= log_cpus { - serial_radix2_fft(a, omega, log_n); + serial_radix2_fft::(a, omega, log_n); } else { - parallel_radix2_fft(a, worker, omega, log_n, log_cpus); + parallel_radix2_fft::(a, omega, log_n, log_cpus); } } #[allow(clippy::many_single_char_names)] -pub(crate) fn serial_radix2_fft(a: &mut [F], omega: F, log_n: u32) { +pub(crate) fn serial_radix2_fft, F: FftField>(a: &mut [T], omega: F, log_n: u32) { #[inline] fn bitreverse(mut n: u32, l: u32) -> u32 { let mut r = 0; @@ -461,11 +440,11 @@ pub(crate) fn serial_radix2_fft(a: &mut [F], omega: F, log_n: u32) let mut w = F::one(); for j in 0..m { let mut t = a[(k + j + m) as usize]; - t *= &w; + t *= w; let mut tmp = a[(k + j) as usize]; - tmp -= &t; + tmp -= t; a[(k + j + m) as usize] = tmp; - a[(k + j) as usize] += &t; + a[(k + j) as usize] += t; w.mul_assign(&w_m); } @@ -477,56 +456,42 @@ pub(crate) fn serial_radix2_fft(a: &mut [F], omega: F, log_n: u32) } #[cfg(feature = "parallel")] -pub(crate) fn parallel_radix2_fft(a: &mut [F], worker: &Worker, omega: F, log_n: u32, log_cpus: u32) { +pub(crate) fn parallel_radix2_fft, F: FftField>(a: &mut [T], omega: F, log_n: u32, log_cpus: u32) { assert!(log_n >= log_cpus); - let num_cpus = 1 << log_cpus; - let log_new_n = log_n - log_cpus; - let mut tmp = vec![vec![F::zero(); 1 << log_new_n]; num_cpus]; - let new_omega = omega.pow(&[num_cpus as u64]); - - worker.scope(0, |scope, _| { - let a = &*a; - - for (j, tmp) in tmp.iter_mut().enumerate() { - scope.spawn(move |_| { - // Shuffle into a sub-FFT - let omega_j = omega.pow(&[j as u64]); - let omega_step = omega.pow(&[(j as u64) << log_new_n]); - - let mut elt = F::one(); - for (i, x) in tmp.iter_mut().enumerate().take(1 << log_new_n) { - for s in 0..num_cpus { - let idx = (i + (s << log_new_n)) % (1 << log_n); - let mut t = a[idx]; - t *= &elt; - *x += &t; - elt *= &omega_step; - } - elt *= &omega_j; - } - - // Perform sub-FFT - serial_radix2_fft(tmp, new_omega, log_new_n); - }); + let m = a.len(); + let num_chunks = 1 << (log_cpus as usize); + assert_eq!(m % num_chunks, 0); + let m_div_num_chunks = m / num_chunks; + + let mut tmp = vec![vec![T::zero(); m_div_num_chunks]; num_chunks]; + let new_omega = omega.pow(&[num_chunks as u64]); + let new_two_adicity = F::k_adicity(2, m_div_num_chunks); + + tmp.par_iter_mut().enumerate().for_each(|(j, tmp)| { + // Shuffle into a sub-FFT + let omega_j = omega.pow(&[j as u64]); + let omega_step = omega.pow(&[(j * m_div_num_chunks) as u64]); + + let mut elt = F::one(); + for i in 0..m_div_num_chunks { + for s in 0..num_chunks { + let idx = (i + (s * m_div_num_chunks)) % m; + let mut t = a[idx]; + t *= elt; + tmp[i] += t; + elt *= &omega_step; + } + elt *= &omega_j; } - }); - // TODO: does this hurt or help? - worker.scope(a.len(), |scope, chunk| { - let tmp = &tmp; - - for (idx, a) in a.chunks_mut(chunk).enumerate() { - scope.spawn(move |_| { - let mut idx = idx * chunk; - let mask = (1 << log_cpus) - 1; - for a in a { - *a = tmp[idx & mask][idx >> log_cpus]; - idx += 1; - } - }); - } + // Perform sub-FFT + serial_radix2_fft(tmp, new_omega, new_two_adicity); }); + + a.iter_mut() + .enumerate() + .for_each(|(i, a)| *a = tmp[i % num_chunks][i / num_chunks]); } /// An iterator over the elements of the domain. @@ -551,6 +516,27 @@ impl Iterator for Elements { } } +pub(crate) fn log2_floor(num: usize) -> u32 { + assert!(num > 0); + let mut pow = 0; + while (1 << (pow + 1)) <= num { + pow += 1; + } + pow +} + +#[test] +fn test_log2_floor() { + assert_eq!(log2_floor(1), 0); + assert_eq!(log2_floor(2), 1); + assert_eq!(log2_floor(3), 1); + assert_eq!(log2_floor(4), 2); + assert_eq!(log2_floor(5), 2); + assert_eq!(log2_floor(6), 2); + assert_eq!(log2_floor(7), 2); + assert_eq!(log2_floor(8), 3); +} + #[cfg(test)] mod tests { use crate::fft::{DensePolynomial, EvaluationDomain}; diff --git a/algorithms/src/fft/mod.rs b/algorithms/src/fft/mod.rs index ac4950bf79..35e36013ee 100644 --- a/algorithms/src/fft/mod.rs +++ b/algorithms/src/fft/mod.rs @@ -26,7 +26,26 @@ pub use evaluations::Evaluations; pub mod polynomial; pub use polynomial::{DenseOrSparsePolynomial, DensePolynomial, SparsePolynomial}; -pub(crate) mod multicore; - #[cfg(test)] mod tests; + +use snarkvm_fields::FftField; + +/// Types that can be FFT-ed must implement this trait. +pub trait DomainCoeff: + Copy + Send + Sync + snarkvm_fields::Zero + core::ops::AddAssign + core::ops::SubAssign + core::ops::MulAssign +{ +} + +impl DomainCoeff for T +where + F: FftField, + T: Copy + + Send + + Sync + + snarkvm_fields::Zero + + core::ops::AddAssign + + core::ops::SubAssign + + core::ops::MulAssign, +{ +} diff --git a/algorithms/src/fft/multicore.rs b/algorithms/src/fft/multicore.rs deleted file mode 100644 index ef3d3ab8f8..0000000000 --- a/algorithms/src/fft/multicore.rs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the snarkVM library. - -// The snarkVM library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The snarkVM library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the snarkVM library. If not, see . - -//! This is an interface for dealing with the kinds of -//! parallel computations involved in `snark`. It's -//! currently just a thin wrapper around `rayon`. -#[cfg(feature = "parallel")] -use rayon::{ - Scope, - {self}, -}; - -#[allow(dead_code)] -#[derive(Copy, Clone)] -pub(crate) struct Worker { - cpus: usize, -} - -impl Worker { - #[cfg(not(feature = "parallel"))] - pub(crate) fn new() -> Worker { - Self { cpus: 1 } - } - - #[cfg(feature = "parallel")] - pub(crate) fn new() -> Worker { - Self { - cpus: rayon::current_num_threads(), - } - } - - #[allow(dead_code)] - pub(crate) fn log_num_cpus(&self) -> u32 { - log2_floor(self.cpus) - } - - #[cfg(not(feature = "parallel"))] - pub(crate) fn scope<'a, F: 'a + Send + FnOnce(&SerialScope, usize) -> R, R: Send>( - &self, - elements: usize, - f: F, - ) -> R { - f(&SerialScope {}, elements) - } - - #[cfg(feature = "parallel")] - pub(crate) fn scope<'a, F: 'a + Send + FnOnce(&Scope<'a>, usize) -> R, R: Send>(&self, elements: usize, f: F) -> R { - let chunk_size = match elements < self.cpus { - true => 1, - false => elements / self.cpus, - }; - rayon::scope(move |scope| f(scope, chunk_size)) - } -} - -/// Represents a serial scope which can be used to mimic any number of tasks. -#[cfg(not(feature = "parallel"))] -pub struct SerialScope {} - -#[cfg(not(feature = "parallel"))] -impl SerialScope { - /// Spawns a serial job. - pub fn spawn(&self, body: Function) { - body(self) - } -} - -pub(crate) fn log2_floor(num: usize) -> u32 { - assert!(num > 0); - let mut pow = 0; - while (1 << (pow + 1)) <= num { - pow += 1; - } - pow -} - -#[test] -fn test_log2_floor() { - assert_eq!(log2_floor(1), 0); - assert_eq!(log2_floor(2), 1); - assert_eq!(log2_floor(3), 1); - assert_eq!(log2_floor(4), 2); - assert_eq!(log2_floor(5), 2); - assert_eq!(log2_floor(6), 2); - assert_eq!(log2_floor(7), 2); - assert_eq!(log2_floor(8), 3); -} diff --git a/algorithms/src/fft/tests.rs b/algorithms/src/fft/tests.rs index 2a2582810f..465a50a998 100644 --- a/algorithms/src/fft/tests.rs +++ b/algorithms/src/fft/tests.rs @@ -60,7 +60,6 @@ fn fft_composition() { #[cfg(feature = "parallel")] #[test] fn parallel_fft_consistency() { - use crate::fft::multicore::*; use snarkvm_fields::{Field, One}; use rand::Rng; @@ -95,8 +94,6 @@ fn parallel_fft_consistency() { } fn test_basic_consistency(rng: &mut R, max_coeffs: u32) { - let worker = Worker::new(); - for _ in 0..5 { for log_d in 0..max_coeffs { let d = 1 << log_d; @@ -104,10 +101,10 @@ fn parallel_fft_consistency() { let mut v1 = (0..d).map(|_| E::Fr::rand(rng)).collect::>(); let mut v2 = v1.clone(); - let domain = EvaluationDomain::new(v1.len()).unwrap(); + let domain = EvaluationDomain::::new(v1.len()).unwrap(); for log_cpus in log_d..min(log_d + 1, 3) { - parallel_radix2_fft(&mut v1, &worker, domain.group_gen, log_d, log_cpus); + parallel_radix2_fft(&mut v1, domain.group_gen, log_d, log_cpus); serial_radix2_fft(&mut v2, domain.group_gen, log_d); assert_eq!(v1, v2); diff --git a/algorithms/src/snark/gm17/r1cs_to_sap.rs b/algorithms/src/snark/gm17/r1cs_to_sap.rs index 424cb69ee9..324573f897 100644 --- a/algorithms/src/snark/gm17/r1cs_to_sap.rs +++ b/algorithms/src/snark/gm17/r1cs_to_sap.rs @@ -210,7 +210,7 @@ impl R1CStoSAP { let d1_double = d1.double(); let mut h: Vec = vec![d1_double; domain_size]; cfg_iter_mut!(h).zip(&a).for_each(|(h_i, a_i)| *h_i *= a_i); - h[0].sub_assign(&d2); + h[0].sub_assign(d2); let d1d1 = d1.square(); h[0].sub_assign(&d1d1); h.push(d1d1); diff --git a/algorithms/tests/snark/mimc.rs b/algorithms/tests/snark/mimc.rs index c397490e0a..231ca73014 100644 --- a/algorithms/tests/snark/mimc.rs +++ b/algorithms/tests/snark/mimc.rs @@ -58,7 +58,7 @@ fn mimc(mut xl: F, mut xr: F, constants: &[F]) -> F { for c in constants.iter().take(MIMC_ROUNDS) { let mut tmp1 = xl; - tmp1.add_assign(&c); + tmp1.add_assign(c); let mut tmp2 = tmp1; tmp2.square_in_place(); tmp2.mul_assign(&tmp1); diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs index bb76f402d6..ca5a97addf 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs @@ -448,20 +448,20 @@ impl ProjectiveCurve for GroupProjective

{ let d = ((self.x + &b).square() - &a - &c).double(); // E = 3*A - let e = a + a.double_in_place(); + let e = a + &*a.double_in_place(); // F = E^2 let f = e.square(); // Z3 = 2*Y1*Z1 - self.z.mul_assign(&self.y); + self.z *= &self.y; self.z.double_in_place(); // X3 = F-2*D self.x = f - &d - &d; // Y3 = E*(D-X3)-8*C - self.y = (d - &self.x) * &e - c.double_in_place().double_in_place().double_in_place(); + self.y = (d - &self.x) * &e - &*c.double_in_place().double_in_place().double_in_place(); self } else { // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l @@ -490,7 +490,7 @@ impl ProjectiveCurve for GroupProjective

{ self.x = t; // Y3 = M*(S-T)-8*YYYY let old_y = self.y; - self.y = m * &(s - &t) - yyyy.double_in_place().double_in_place().double_in_place(); + self.y = m * &(s - &t) - &*yyyy.double_in_place().double_in_place().double_in_place(); // Z3 = (Y1+Z1)^2-YY-ZZ self.z = (old_y + &self.z).square() - &yy - &zz; self @@ -687,7 +687,7 @@ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ self.x = r.square() - &j - &(v.double()); // Y3 = r*(V - X3) - 2*S1*J - self.y = r * &(v - &self.x) - (s1 * &j).double_in_place(); + self.y = r * &(v - &self.x) - &*(s1 * &j).double_in_place(); // Z3 = ((Z1+Z2)^2 - Z1Z1 - Z2Z2)*H self.z = ((self.z + &other.z).square() - &z1z1 - &z2z2) * &h; diff --git a/fields/src/fp12_2over3over2.rs b/fields/src/fp12_2over3over2.rs index 5c949f8371..ccf90099f3 100644 --- a/fields/src/fp12_2over3over2.rs +++ b/fields/src/fp12_2over3over2.rs @@ -368,6 +368,9 @@ impl Neg for Fp12

{ } } +impl_additive_ops_from_ref!(Fp12, Fp12Parameters); +impl_multiplicative_ops_from_ref!(Fp12, Fp12Parameters); + impl<'a, P: Fp12Parameters> Add<&'a Self> for Fp12

{ type Output = Self; diff --git a/fields/src/fp2.rs b/fields/src/fp2.rs index f4ad4d40fc..b470a869ec 100644 --- a/fields/src/fp2.rs +++ b/fields/src/fp2.rs @@ -88,8 +88,8 @@ impl Fp2

{ } pub fn mul_by_fp(&mut self, element: &P::Fp) { - self.c0.mul_assign(&element); - self.c1.mul_assign(&element); + self.c0.mul_assign(element); + self.c1.mul_assign(element); } } @@ -338,6 +338,9 @@ impl Distribution> for Standard { } } +impl_additive_ops_from_ref!(Fp2, Fp2Parameters); +impl_multiplicative_ops_from_ref!(Fp2, Fp2Parameters); + impl<'a, P: Fp2Parameters> Add<&'a Fp2

> for Fp2

{ type Output = Self; diff --git a/fields/src/fp3.rs b/fields/src/fp3.rs index a4eab351d0..bb93cc7c84 100644 --- a/fields/src/fp3.rs +++ b/fields/src/fp3.rs @@ -388,6 +388,9 @@ impl Distribution> for Standard { } } +impl_additive_ops_from_ref!(Fp3, Fp3Parameters); +impl_multiplicative_ops_from_ref!(Fp3, Fp3Parameters); + impl<'a, P: Fp3Parameters> Add<&'a Fp3

> for Fp3

{ type Output = Self; diff --git a/fields/src/fp6_2over3.rs b/fields/src/fp6_2over3.rs index 4ec43b2444..a749b8c858 100644 --- a/fields/src/fp6_2over3.rs +++ b/fields/src/fp6_2over3.rs @@ -392,6 +392,9 @@ impl Distribution> for Standard { } } +impl_additive_ops_from_ref!(Fp6, Fp6Parameters); +impl_multiplicative_ops_from_ref!(Fp6, Fp6Parameters); + impl<'a, P: Fp6Parameters> Add<&'a Fp6

> for Fp6

{ type Output = Self; diff --git a/fields/src/fp6_3over2.rs b/fields/src/fp6_3over2.rs index 907e3c6a6b..12f38fc1d1 100644 --- a/fields/src/fp6_3over2.rs +++ b/fields/src/fp6_3over2.rs @@ -336,6 +336,9 @@ impl Neg for Fp6

{ } } +impl_additive_ops_from_ref!(Fp6, Fp6Parameters); +impl_multiplicative_ops_from_ref!(Fp6, Fp6Parameters); + impl<'a, P: Fp6Parameters> Add<&'a Self> for Fp6

{ type Output = Self; diff --git a/fields/src/fp_256.rs b/fields/src/fp_256.rs index 1c5dad8d13..d6dbad5af5 100644 --- a/fields/src/fp_256.rs +++ b/fields/src/fp_256.rs @@ -14,7 +14,19 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{ + impl_additive_ops_from_ref, + impl_multiplicative_ops_from_ref, + FftField, + Field, + FieldError, + FieldParameters, + LegendreSymbol, + One, + PrimeField, + SquareRootField, + Zero, +}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger256 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -386,6 +398,9 @@ impl_prime_field_from_int!(Fp256, u8, Fp256Parameters); impl_prime_field_standard_sample!(Fp256, Fp256Parameters); +impl_additive_ops_from_ref!(Fp256, Fp256Parameters); +impl_multiplicative_ops_from_ref!(Fp256, Fp256Parameters); + impl ToBytes for Fp256

{ #[inline] fn write(&self, writer: W) -> IoResult<()> { diff --git a/fields/src/fp_320.rs b/fields/src/fp_320.rs index 30ca549101..f4b8a3a1d2 100644 --- a/fields/src/fp_320.rs +++ b/fields/src/fp_320.rs @@ -14,7 +14,19 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{ + impl_additive_ops_from_ref, + impl_multiplicative_ops_from_ref, + FftField, + Field, + FieldError, + FieldParameters, + LegendreSymbol, + One, + PrimeField, + SquareRootField, + Zero, +}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger320 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -434,6 +446,9 @@ impl_prime_field_from_int!(Fp320, u8, Fp320Parameters); impl_prime_field_standard_sample!(Fp320, Fp320Parameters); +impl_additive_ops_from_ref!(Fp320, Fp320Parameters); +impl_multiplicative_ops_from_ref!(Fp320, Fp320Parameters); + impl ToBytes for Fp320

{ #[inline] fn write(&self, writer: W) -> IoResult<()> { diff --git a/fields/src/fp_384.rs b/fields/src/fp_384.rs index 68c824ed28..22de464eae 100644 --- a/fields/src/fp_384.rs +++ b/fields/src/fp_384.rs @@ -14,7 +14,19 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{ + impl_additive_ops_from_ref, + impl_multiplicative_ops_from_ref, + FftField, + Field, + FieldError, + FieldParameters, + LegendreSymbol, + One, + PrimeField, + SquareRootField, + Zero, +}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger384 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -461,6 +473,9 @@ impl_prime_field_from_int!(Fp384, u8, Fp384Parameters); impl_prime_field_standard_sample!(Fp384, Fp384Parameters); +impl_additive_ops_from_ref!(Fp384, Fp384Parameters); +impl_multiplicative_ops_from_ref!(Fp384, Fp384Parameters); + impl ToBytes for Fp384

{ #[inline] fn write(&self, writer: W) -> IoResult<()> { diff --git a/fields/src/fp_768.rs b/fields/src/fp_768.rs index 14f895c998..5e7fd970b4 100644 --- a/fields/src/fp_768.rs +++ b/fields/src/fp_768.rs @@ -14,7 +14,19 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{ + impl_additive_ops_from_ref, + impl_multiplicative_ops_from_ref, + FftField, + Field, + FieldError, + FieldParameters, + LegendreSymbol, + One, + PrimeField, + SquareRootField, + Zero, +}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger768 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -796,6 +808,9 @@ impl_prime_field_from_int!(Fp768, u8, Fp768Parameters); impl_prime_field_standard_sample!(Fp768, Fp768Parameters); +impl_additive_ops_from_ref!(Fp768, Fp768Parameters); +impl_multiplicative_ops_from_ref!(Fp768, Fp768Parameters); + impl ToBytes for Fp768

{ #[inline] fn write(&self, writer: W) -> IoResult<()> { diff --git a/fields/src/fp_832.rs b/fields/src/fp_832.rs index ac6696190d..ab8e478bad 100644 --- a/fields/src/fp_832.rs +++ b/fields/src/fp_832.rs @@ -14,7 +14,19 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{FftField, Field, FieldError, FieldParameters, LegendreSymbol, One, PrimeField, SquareRootField, Zero}; +use crate::{ + impl_additive_ops_from_ref, + impl_multiplicative_ops_from_ref, + FftField, + Field, + FieldError, + FieldParameters, + LegendreSymbol, + One, + PrimeField, + SquareRootField, + Zero, +}; use snarkvm_utilities::{ biginteger::{arithmetic as fa, BigInteger as _BigInteger, BigInteger832 as BigInteger}, bytes::{FromBytes, ToBytes}, @@ -765,6 +777,9 @@ impl_prime_field_from_int!(Fp832, u8, Fp832Parameters); impl_prime_field_standard_sample!(Fp832, Fp832Parameters); +impl_additive_ops_from_ref!(Fp832, Fp832Parameters); +impl_multiplicative_ops_from_ref!(Fp832, Fp832Parameters); + impl ToBytes for Fp832

{ #[inline] fn write(&self, writer: W) -> IoResult<()> { diff --git a/fields/src/lib.rs b/fields/src/lib.rs index 3bda63a000..575164b50b 100644 --- a/fields/src/lib.rs +++ b/fields/src/lib.rs @@ -98,7 +98,7 @@ pub fn batch_inversion(v: &mut [F]) { let mut prod = Vec::with_capacity(v.len()); let mut tmp = F::one(); for f in v.iter().filter(|f| !f.is_zero()) { - tmp.mul_assign(&f); + tmp.mul_assign(f); prod.push(tmp); } @@ -115,9 +115,9 @@ pub fn batch_inversion(v: &mut [F]) { // Backwards, skip last element, fill in one for last term. .zip(prod.into_iter().rev().skip(1).chain(Some(F::one()))) { - // tmp := tmp * g.z; g.z := tmp * s = 1/z - let newtmp = tmp * &f; + // tmp := tmp * f; f := tmp * s = 1/f + let new_tmp = tmp * *f; *f = tmp * &s; - tmp = newtmp; + tmp = new_tmp; } } diff --git a/fields/src/macros.rs b/fields/src/macros.rs index 24531c0069..d61f62bc46 100644 --- a/fields/src/macros.rs +++ b/fields/src/macros.rs @@ -329,3 +329,271 @@ macro_rules! impl_field_from_random_bytes_with_flags { } }; } + +// Implements AddAssign on Self by deferring to an implementation on &Self +#[macro_export] +macro_rules! impl_additive_ops_from_ref { + ($type: ident, $params: ident) => { + #[allow(unused_qualifications)] + impl core::ops::Add for $type

{ + type Output = Self; + + #[inline] + fn add(self, other: Self) -> Self { + let mut result = self; + result.add_assign(&other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::Sub for $type

{ + type Output = Self; + + #[inline] + fn sub(self, other: Self) -> Self { + let mut result = self; + result.sub_assign(&other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::Add<&&Self> for $type

{ + type Output = Self; + + #[inline] + fn add(self, other: &&Self) -> Self { + let mut result = self; + result.add_assign(*other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::Sub<&&Self> for $type

{ + type Output = Self; + + #[inline] + fn sub(self, other: &&Self) -> Self { + let mut result = self; + result.sub_assign(*other); + result + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::Add<&'a mut Self> for $type

{ + type Output = Self; + + #[inline] + fn add(self, other: &'a mut Self) -> Self { + let mut result = self; + result.add_assign(&*other); + result + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::Sub<&'a mut Self> for $type

{ + type Output = Self; + + #[inline] + fn sub(self, other: &'a mut Self) -> Self { + let mut result = self; + result.sub_assign(&*other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::AddAssign for $type

{ + fn add_assign(&mut self, other: Self) { + self.add_assign(&other) + } + } + + #[allow(unused_qualifications)] + impl core::ops::SubAssign for $type

{ + fn sub_assign(&mut self, other: Self) { + self.sub_assign(&other) + } + } + + #[allow(unused_qualifications)] + impl core::ops::AddAssign<&&Self> for $type

{ + fn add_assign(&mut self, other: &&Self) { + self.add_assign(*other) + } + } + + #[allow(unused_qualifications)] + impl core::ops::SubAssign<&&Self> for $type

{ + fn sub_assign(&mut self, other: &&Self) { + self.sub_assign(*other) + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::AddAssign<&'a mut Self> for $type

{ + fn add_assign(&mut self, other: &'a mut Self) { + self.add_assign(&*other) + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::SubAssign<&'a mut Self> for $type

{ + fn sub_assign(&mut self, other: &'a mut Self) { + self.sub_assign(&*other) + } + } + + #[allow(unused_qualifications)] + impl core::iter::Sum for $type

{ + fn sum>(iter: I) -> Self { + iter.fold(Self::zero(), core::ops::Add::add) + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::iter::Sum<&'a Self> for $type

{ + fn sum>(iter: I) -> Self { + iter.fold(Self::zero(), core::ops::Add::add) + } + } + }; +} + +// Implements AddAssign on Self by deferring to an implementation on &Self +#[macro_export] +macro_rules! impl_multiplicative_ops_from_ref { + ($type: ident, $params: ident) => { + #[allow(unused_qualifications)] + impl core::ops::Mul for $type

{ + type Output = Self; + + #[inline] + fn mul(self, other: Self) -> Self { + let mut result = self; + result.mul_assign(&other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::Div for $type

{ + type Output = Self; + + #[inline] + fn div(self, other: Self) -> Self { + let mut result = self; + result.div_assign(&other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::Mul<&&Self> for $type

{ + type Output = Self; + + #[inline] + fn mul(self, other: &&Self) -> Self { + let mut result = self; + result.mul_assign(*other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::Div<&&Self> for $type

{ + type Output = Self; + + #[inline] + fn div(self, other: &&Self) -> Self { + let mut result = self; + result.div_assign(*other); + result + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::Mul<&'a mut Self> for $type

{ + type Output = Self; + + #[inline] + fn mul(self, other: &'a mut Self) -> Self { + let mut result = self; + result.mul_assign(&*other); + result + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::Div<&'a mut Self> for $type

{ + type Output = Self; + + #[inline] + fn div(self, other: &'a mut Self) -> Self { + let mut result = self; + result.div_assign(&*other); + result + } + } + + #[allow(unused_qualifications)] + impl core::ops::MulAssign for $type

{ + fn mul_assign(&mut self, other: Self) { + self.mul_assign(&other) + } + } + + #[allow(unused_qualifications)] + impl core::ops::DivAssign for $type

{ + fn div_assign(&mut self, other: Self) { + self.div_assign(&other) + } + } + + #[allow(unused_qualifications)] + impl core::ops::MulAssign<&&Self> for $type

{ + fn mul_assign(&mut self, other: &&Self) { + self.mul_assign(*other) + } + } + + #[allow(unused_qualifications)] + impl core::ops::DivAssign<&&Self> for $type

{ + fn div_assign(&mut self, other: &&Self) { + self.div_assign(*other) + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::MulAssign<&'a mut Self> for $type

{ + fn mul_assign(&mut self, other: &'a mut Self) { + self.mul_assign(&*other) + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::ops::DivAssign<&'a mut Self> for $type

{ + fn div_assign(&mut self, other: &'a mut Self) { + self.div_assign(&*other) + } + } + + #[allow(unused_qualifications)] + impl core::iter::Product for $type

{ + fn product>(iter: I) -> Self { + iter.fold(Self::one(), core::ops::Mul::mul) + } + } + + #[allow(unused_qualifications)] + impl<'a, P: $params> core::iter::Product<&'a Self> for $type

{ + fn product>(iter: I) -> Self { + iter.fold(Self::one(), Mul::mul) + } + } + }; +} diff --git a/fields/src/traits/field.rs b/fields/src/traits/field.rs index 2c2d3a2fd3..6e9847fa7a 100644 --- a/fields/src/traits/field.rs +++ b/fields/src/traits/field.rs @@ -61,6 +61,14 @@ pub trait Field: + From + From + From + + Add + + Sub + + Mul + + Div + + AddAssign + + SubAssign + + MulAssign + + DivAssign + for<'a> Add<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> + for<'a> Mul<&'a Self, Output = Self> @@ -69,6 +77,10 @@ pub trait Field: + for<'a> SubAssign<&'a Self> + for<'a> MulAssign<&'a Self> + for<'a> DivAssign<&'a Self> + + core::iter::Sum + + for<'a> core::iter::Sum<&'a Self> + + core::iter::Product + + for<'a> core::iter::Product<&'a Self> + CanonicalSerialize + ConstantSerializedSize + CanonicalSerializeWithFlags @@ -98,7 +110,7 @@ pub trait Field: #[must_use] fn inverse(&self) -> Option; - // Sets `self` to `self`'s inverse if it exists. Otherwise it is a no-op. + /// Sets `self` to `self`'s inverse if it exists. Otherwise it is a no-op. fn inverse_in_place(&mut self) -> Option<&mut Self>; /// Exponentiates this element by a power of the base prime modulus via diff --git a/fields/src/traits/prime_field.rs b/fields/src/traits/prime_field.rs index 3c97172b8c..afb2f918cd 100644 --- a/fields/src/traits/prime_field.rs +++ b/fields/src/traits/prime_field.rs @@ -14,14 +14,14 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{FftField, Field, FieldParameters}; +use crate::{FftField, FieldParameters}; use snarkvm_utilities::biginteger::BigInteger; use std::str::FromStr; /// The interface for a prime field. #[allow(clippy::wrong_self_convention)] -pub trait PrimeField: FftField::Parameters> + Field + FromStr { +pub trait PrimeField: FftField::Parameters> + FromStr { type Parameters: FieldParameters; type BigInteger: BigInteger; diff --git a/marlin/src/ahp/prover/prover.rs b/marlin/src/ahp/prover/prover.rs index 49247ece30..7163c84c4f 100644 --- a/marlin/src/ahp/prover/prover.rs +++ b/marlin/src/ahp/prover/prover.rs @@ -427,7 +427,7 @@ impl AHPForR1CS { .zip(&z_poly_evals.evaluations) .zip(&t_poly_m_evals.evaluations) .for_each(|(((a, b), &c), d)| { - *a *= &b; + *a *= b; *a -= &(c * d); }); let rhs = r_alpha_evals.interpolate(); diff --git a/marlin/src/constraints/lagrange_interpolation.rs b/marlin/src/constraints/lagrange_interpolation.rs index 02fe4bbb11..05e692717b 100644 --- a/marlin/src/constraints/lagrange_interpolation.rs +++ b/marlin/src/constraints/lagrange_interpolation.rs @@ -116,7 +116,7 @@ impl LagrangeInterpolator { .zip(self.poly_evaluations.iter()) .take(poly_evaluations_size) { - interpolation += &(*lagrange_coeff * &poly_evaluation); + interpolation += &(*lagrange_coeff * poly_evaluation); } interpolation } From 553e36749af766b7afafd76f46c53ff9be2c5184 Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 01:50:45 -0700 Subject: [PATCH 05/13] Adds Group arithmetic operators on both Affine and Projective --- algorithms/benches/msm/variable_base.rs | 2 +- algorithms/src/crh/bowe_hopwood_pedersen.rs | 4 +- .../crh/bowe_hopwood_pedersen_parameters.rs | 2 +- algorithms/src/crh/pedersen.rs | 2 +- algorithms/src/encoding/elligator2.rs | 26 +- algorithms/src/encryption/group.rs | 26 +- algorithms/src/fft/domain.rs | 2 +- algorithms/src/fft/polynomial/dense.rs | 10 +- algorithms/src/fft/polynomial/sparse.rs | 6 +- algorithms/src/msm/fixed_base.rs | 4 +- algorithms/src/msm/tests.rs | 4 +- algorithms/src/msm/variable_base/mod.rs | 3 +- algorithms/src/msm/variable_base/standard.rs | 8 +- algorithms/src/signature/schnorr.rs | 16 +- algorithms/src/snark/gm17/generator.rs | 41 +-- algorithms/src/snark/gm17/prover.rs | 48 +-- algorithms/src/snark/gm17/r1cs_to_sap.rs | 40 +-- algorithms/src/snark/gm17/tests.rs | 2 +- algorithms/src/snark/gm17/verifier.rs | 16 +- algorithms/src/snark/groth16/generator.rs | 19 +- algorithms/src/snark/groth16/prover.rs | 23 +- algorithms/src/snark/groth16/r1cs_to_qap.rs | 8 +- algorithms/src/snark/groth16/verifier.rs | 11 +- algorithms/tests/snark/mimc.rs | 8 +- curves/benches/bls12_377/ec.rs | 4 +- curves/benches/bls12_377/fq.rs | 2 +- curves/benches/bls12_377/fq12.rs | 2 +- curves/benches/bls12_377/fq2.rs | 2 +- curves/benches/bls12_377/fr.rs | 2 +- curves/benches/bw6_761/ec.rs | 4 +- curves/benches/bw6_761/fq.rs | 2 +- curves/benches/bw6_761/fq3.rs | 2 +- curves/benches/bw6_761/fq6.rs | 2 +- curves/benches/bw6_761/fr.rs | 2 +- curves/src/bls12_377/tests.rs | 42 +-- curves/src/bw6_761/tests.rs | 4 +- curves/src/edwards_bls12/tests.rs | 1 + curves/src/edwards_sw6/tests.rs | 2 +- .../short_weierstrass_jacobian.rs | 334 +++++++++++------- .../short_weierstrass_projective.rs | 258 +++++++++----- .../templates/twisted_edwards_extended/mod.rs | 172 +++++---- curves/src/traits/group.rs | 33 +- curves/src/traits/pairing_engine.rs | 55 +-- curves/src/traits/tests_curve.rs | 33 +- curves/src/traits/tests_group.rs | 34 +- fields/src/fp12_2over3over2.rs | 19 +- fields/src/fp2.rs | 11 +- fields/src/fp3.rs | 15 +- fields/src/fp6_2over3.rs | 9 +- fields/src/fp6_3over2.rs | 25 +- fields/src/fp_256.rs | 3 +- fields/src/fp_320.rs | 3 +- fields/src/fp_384.rs | 3 +- fields/src/fp_768.rs | 3 +- fields/src/fp_832.rs | 3 +- fields/src/traits/field.rs | 2 +- gadgets/src/curves/bls12_377.rs | 35 +- .../curves/templates/twisted_edwards/mod.rs | 2 +- .../curves/templates/twisted_edwards/test.rs | 16 +- gadgets/src/curves/tests_curve.rs | 4 +- gadgets/src/fields/fp.rs | 5 +- .../fiat_shamir_poseidon_sponge.rs | 4 +- polycommit/src/kzg10/data_structures.rs | 9 +- polycommit/src/kzg10/mod.rs | 24 +- polycommit/src/marlin_pc/data_structures.rs | 2 +- polycommit/src/marlin_pc/mod.rs | 24 +- polycommit/src/sonic_pc/data_structures.rs | 5 +- polycommit/src/sonic_pc/mod.rs | 28 +- r1cs/src/test_constraint_system.rs | 2 +- 69 files changed, 848 insertions(+), 731 deletions(-) diff --git a/algorithms/benches/msm/variable_base.rs b/algorithms/benches/msm/variable_base.rs index da108e85b4..b5f70592be 100644 --- a/algorithms/benches/msm/variable_base.rs +++ b/algorithms/benches/msm/variable_base.rs @@ -33,7 +33,7 @@ fn variable_base(c: &mut Criterion) { let mut rng = XorShiftRng::seed_from_u64(234872845u64); - let v = (0..SAMPLES).map(|_| Fr::rand(&mut rng).into_repr()).collect::>(); + let v = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect::>(); let g = (0..SAMPLES) .map(|_| G1Projective::rand(&mut rng).into_affine()) .collect::>(); diff --git a/algorithms/src/crh/bowe_hopwood_pedersen.rs b/algorithms/src/crh/bowe_hopwood_pedersen.rs index 5302668ccb..787aae9aa6 100644 --- a/algorithms/src/crh/bowe_hopwood_pedersen.rs +++ b/algorithms/src/crh/bowe_hopwood_pedersen.rs @@ -164,9 +164,9 @@ impl CRH for BoweHopwoodPedersenCRH { &generator [(chunk_bits[0] as usize) | (chunk_bits[1] as usize) << 1 | (chunk_bits[2] as usize) << 2] }) - .fold(G::zero(), |a, b| a + &b) + .fold(G::zero(), |a, b| a + b) }) - .fold(G::zero(), |a, b| a + &b); + .fold(G::zero(), |a, b| a + b); end_timer!(eval_time); diff --git a/algorithms/src/crh/bowe_hopwood_pedersen_parameters.rs b/algorithms/src/crh/bowe_hopwood_pedersen_parameters.rs index aff35d13ee..4058ff9985 100644 --- a/algorithms/src/crh/bowe_hopwood_pedersen_parameters.rs +++ b/algorithms/src/crh/bowe_hopwood_pedersen_parameters.rs @@ -55,7 +55,7 @@ impl BoweHopwoodPedersenCRHParameters { encoded += g; } if (i & 0x02) != 0 { - encoded += &g.double(); + encoded += g.double(); } if (i & 0x04) != 0 { encoded = encoded.neg(); diff --git a/algorithms/src/crh/pedersen.rs b/algorithms/src/crh/pedersen.rs index 9df639eade..a4bfb2f0e8 100644 --- a/algorithms/src/crh/pedersen.rs +++ b/algorithms/src/crh/pedersen.rs @@ -85,7 +85,7 @@ impl CRH for PedersenCRH { } encoded }) - .fold(G::zero(), |a, b| a + &b); + .fold(G::zero(), |a, b| a + b); Ok(result) } diff --git a/algorithms/src/encoding/elligator2.rs b/algorithms/src/encoding/elligator2.rs index 1b7ba32d04..da08b253ff 100644 --- a/algorithms/src/encoding/elligator2.rs +++ b/algorithms/src/encoding/elligator2.rs @@ -73,22 +73,22 @@ impl P::BaseField::zero(), LegendreSymbol::QuadraticResidue => -value, @@ -119,7 +119,7 @@ impl Result, EncryptionError> { - let record_view_key = public_key.0.mul(&randomness); + let record_view_key = public_key.0.mul(*randomness); let affine = record_view_key.into_affine(); debug_assert!(affine.is_in_correct_subgroup_assuming_on_curve()); @@ -182,12 +182,12 @@ impl blinding_exponents.push(val), None => return Err(EncryptionError::MissingInverse), }; - i += &one; + i += one; } Ok(blinding_exponents) @@ -199,12 +199,12 @@ impl Result, EncryptionError> { - let record_view_key = public_key.0.mul(&randomness); + let record_view_key = public_key.0.mul(*randomness); let mut c_0 = G::zero(); for (bit, base_power) in bytes_to_bits(&to_bytes![randomness]?).zip_eq(&self.parameters.generator_powers) { if bit { - c_0 += &base_power; + c_0 += base_power; } } let mut ciphertext = vec![c_0]; @@ -216,13 +216,13 @@ impl record_view_key.mul(val), + let h_i = match &(z + i).inverse() { + Some(val) => record_view_key.mul(*val), None => return Err(EncryptionError::MissingInverse), }; @@ -259,7 +259,7 @@ impl DensePolynomial { let mapping = cfg_into_iter!(powers_of_point) .zip(&self.coeffs) .map(|(power, coeff)| power * coeff); - cfg_reduce!(mapping, || zero, |a, b| a + &b) + cfg_reduce!(mapping, || zero, |a, b| a + b) } /// Outputs a polynomial of degree `d` where each coefficient is sampled uniformly at random @@ -131,7 +131,7 @@ impl DensePolynomial { let mut result = vec![F::zero(); self.degree() + other.degree() + 1]; for (i, self_coeff) in self.coeffs.iter().enumerate() { for (j, other_coeff) in other.coeffs.iter().enumerate() { - result[i + j] += &(*self_coeff * other_coeff); + result[i + j] += *self_coeff * other_coeff; } } DensePolynomial::from_coefficients_vec(result) @@ -225,13 +225,13 @@ impl<'a, 'b, F: Field> AddAssign<(F, &'a DensePolynomial)> for DensePolynomia // return } else if self.degree() >= other.degree() { for (a, b) in self.coeffs.iter_mut().zip(&other.coeffs) { - *a += &(f * b); + *a += f * b; } } else { // Add the necessary number of zero coefficients. self.coeffs.resize(other.coeffs.len(), F::zero()); for (a, b) in self.coeffs.iter_mut().zip(&other.coeffs) { - *a += &(f * b); + *a += f * b; } // If the leading coefficient ends up being zero, pop it off. while self.coeffs.last().unwrap().is_zero() { @@ -482,7 +482,7 @@ mod tests { let point: Fr = Fr::from(10u64); let mut total = Fr::zero(); for (i, coeff) in p.coeffs.iter().enumerate() { - total += &(point.pow(&[i as u64]) * coeff); + total += point.pow(&[i as u64]) * coeff; } assert_eq!(p.evaluate(point), total); } diff --git a/algorithms/src/fft/polynomial/sparse.rs b/algorithms/src/fft/polynomial/sparse.rs index a7cfd33b51..929d4b8b33 100644 --- a/algorithms/src/fft/polynomial/sparse.rs +++ b/algorithms/src/fft/polynomial/sparse.rs @@ -90,7 +90,7 @@ impl SparsePolynomial { } let mut total = F::zero(); for (i, c) in &self.coeffs { - total += &(*c * &point.pow(&[*i as u64])); + total += *c * &point.pow(&[*i as u64]); } total } @@ -104,7 +104,7 @@ impl SparsePolynomial { for (i, self_coeff) in self.coeffs.iter() { for (j, other_coeff) in other.coeffs.iter() { let cur_coeff = result.entry(i + j).or_insert_with(F::zero); - *cur_coeff += &(*self_coeff * other_coeff); + *cur_coeff += *self_coeff * other_coeff; } } let mut result = result.into_iter().collect::>(); @@ -151,7 +151,7 @@ mod tests { for size in 2..10 { let domain_size = 1 << size; let domain = EvaluationDomain::new(domain_size).unwrap(); - let two = Fr::one() + &Fr::one(); + let two = Fr::one() + Fr::one(); let sparse_poly = SparsePolynomial::from_coefficients_vec(vec![(0, two), (1, two)]); let evals1 = sparse_poly.evaluate_over_domain_by_ref(domain); diff --git a/algorithms/src/msm/fixed_base.rs b/algorithms/src/msm/fixed_base.rs index 00be6731ab..e461ab0cb1 100644 --- a/algorithms/src/msm/fixed_base.rs +++ b/algorithms/src/msm/fixed_base.rs @@ -45,7 +45,7 @@ impl FixedBaseMSM { let cur_in_window = if outer == outerc - 1 { last_in_window } else { in_window }; for x in m.iter_mut().take(cur_in_window) { *x = g_inner; - g_inner += &g_outer; + g_inner += g_outer; } for _ in 0..window { g_outer.double_in_place(); @@ -73,7 +73,7 @@ impl FixedBaseMSM { inner |= 1 << i; } } - res += &multiples_of_g[outer][inner]; + res += multiples_of_g[outer][inner]; } res } diff --git a/algorithms/src/msm/tests.rs b/algorithms/src/msm/tests.rs index 7b475e6f5d..72f5db905c 100644 --- a/algorithms/src/msm/tests.rs +++ b/algorithms/src/msm/tests.rs @@ -20,7 +20,7 @@ use snarkvm_curves::{ traits::{AffineCurve, ProjectiveCurve}, }; use snarkvm_fields::{PrimeField, Zero}; -use snarkvm_utilities::rand::UniformRand; +use snarkvm_utilities::{rand::UniformRand, BitIteratorBE}; use rand::SeedableRng; use rand_xorshift::XorShiftRng; @@ -32,7 +32,7 @@ fn naive_variable_base_msm( let mut acc = G::Projective::zero(); for (base, scalar) in bases.iter().zip(scalars.iter()) { - acc += &base.mul(*scalar); + acc += base.mul_bits(BitIteratorBE::new(*scalar)); } acc } diff --git a/algorithms/src/msm/variable_base/mod.rs b/algorithms/src/msm/variable_base/mod.rs index 1fe275de08..f6aa8af447 100644 --- a/algorithms/src/msm/variable_base/mod.rs +++ b/algorithms/src/msm/variable_base/mod.rs @@ -16,6 +16,7 @@ use snarkvm_curves::traits::AffineCurve; use snarkvm_fields::{PrimeField, Zero}; +use snarkvm_utilities::BitIteratorBE; mod standard; @@ -34,7 +35,7 @@ impl VariableBaseMSM { let mut acc = G::Projective::zero(); for (base, scalar) in bases.iter().zip(scalars.iter()) { - acc += &base.mul(*scalar); + acc += base.mul_bits(BitIteratorBE::new(*scalar)); } acc } diff --git a/algorithms/src/msm/variable_base/standard.rs b/algorithms/src/msm/variable_base/standard.rs index d4f721687c..819882edf9 100644 --- a/algorithms/src/msm/variable_base/standard.rs +++ b/algorithms/src/msm/variable_base/standard.rs @@ -14,12 +14,12 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_curves::traits::AffineCurve; +use snarkvm_curves::{traits::AffineCurve, Group}; use snarkvm_fields::{FieldParameters, PrimeField, Zero}; +use snarkvm_utilities::BigInteger; #[cfg(feature = "parallel")] use rayon::prelude::*; -use snarkvm_utilities::BigInteger; pub fn msm_standard( bases: &[G], @@ -81,9 +81,9 @@ pub fn msm_standard( let mut running_sum = G::Projective::zero(); for b in buckets.into_iter().rev() { - running_sum += &b; + running_sum += b; // running_sum.add_assign_mixed(&b); - res += &running_sum; + res += running_sum; } res diff --git a/algorithms/src/signature/schnorr.rs b/algorithms/src/signature/schnorr.rs index 7592b4eb56..902b6c636a 100644 --- a/algorithms/src/signature/schnorr.rs +++ b/algorithms/src/signature/schnorr.rs @@ -142,7 +142,7 @@ where let mut public_key = G::zero(); for (bit, base_power) in bytes_to_bits(&to_bytes![private_key]?).zip_eq(&self.parameters.generator_powers) { if bit { - public_key += &base_power; + public_key += base_power; } } end_timer!(keygen_time); @@ -167,7 +167,7 @@ where for (bit, base_power) in bytes_to_bits(&to_bytes![random_scalar]?).zip_eq(&self.parameters.generator_powers) { if bit { - prover_commitment += &base_power; + prover_commitment += base_power; } } @@ -210,12 +210,12 @@ where let mut claimed_prover_commitment = G::zero(); for (bit, base_power) in bytes_to_bits(&to_bytes![prover_response]?).zip_eq(&self.parameters.generator_powers) { if bit { - claimed_prover_commitment += &base_power; + claimed_prover_commitment += base_power; } } - let public_key_times_verifier_challenge = public_key.0.mul(verifier_challenge); - claimed_prover_commitment += &public_key_times_verifier_challenge; + let public_key_times_verifier_challenge = public_key.0.mul(*verifier_challenge); + claimed_prover_commitment += public_key_times_verifier_challenge; let mut hash_input = Vec::new(); hash_input.extend_from_slice(&self.parameters.salt); @@ -245,10 +245,10 @@ where let mut encoded = G::zero(); for (bit, base_power) in bytes_to_bits(&to_bytes![randomness]?).zip_eq(&self.parameters.generator_powers) { if bit { - encoded += &base_power; + encoded += base_power; } } - randomized_pk += &encoded; + randomized_pk += encoded; end_timer!(rand_pk_time); @@ -265,7 +265,7 @@ where let mut multiplier = ::ScalarField::zero(); for bit in bytes_to_bits(randomness) { if bit { - multiplier += &base; + multiplier += base; } base.double_in_place(); } diff --git a/algorithms/src/snark/gm17/generator.rs b/algorithms/src/snark/gm17/generator.rs index 502ce50b64..9b9a1b4a87 100644 --- a/algorithms/src/snark/gm17/generator.rs +++ b/algorithms/src/snark/gm17/generator.rs @@ -16,7 +16,7 @@ use super::{r1cs_to_sap::R1CStoSAP, ProvingKey, VerifyingKey}; use crate::{fft::EvaluationDomain, msm::FixedBaseMSM}; -use snarkvm_curves::traits::{AffineCurve, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::traits::{PairingEngine, ProjectiveCurve}; use snarkvm_fields::{Field, One, PrimeField, Zero}; use snarkvm_r1cs::{ errors::SynthesisError, @@ -28,6 +28,7 @@ use snarkvm_r1cs::{ }; use snarkvm_utilities::rand::UniformRand; +use core::ops::Mul; use rand::Rng; #[cfg(feature = "parallel")] @@ -242,14 +243,14 @@ where // Compute the G_gamma-query let g_gamma_time = start_timer!(|| "Calculate G gamma"); let gamma_z = zt * γ - let alpha_beta = alpha + β + let alpha_beta = alpha + beta; let ab_gamma_z = alpha_beta * &gamma * &zt; - let g_gamma = g.into_affine().mul(gamma.into_repr()); - let g_gamma_z = g.into_affine().mul(gamma_z.into_repr()); - let h_gamma = h.into_affine().mul(gamma.into_repr()); - let h_gamma_z = h_gamma.into_affine().mul(zt.into_repr()); - let g_ab_gamma_z = g.into_affine().mul(ab_gamma_z.into_repr()); - let g_gamma2_z2 = g.into_affine().mul(gamma_z.square().into_repr()); + let g_gamma = g.into_affine().mul(gamma); + let g_gamma_z = g.into_affine().mul(gamma_z); + let h_gamma = h.into_affine().mul(gamma); + let h_gamma_z = h_gamma.mul(zt); + let g_ab_gamma_z = g.into_affine().mul(ab_gamma_z); + let g_gamma2_z2 = g.into_affine().mul(gamma_z.square()); // Compute the vector G_gamma2_z_t := Z(t) * t^i * gamma^2 * G let gamma2_z_t = gamma_z * γ @@ -270,7 +271,7 @@ where g_window, &g_table, &cfg_into_iter!(0..sap_num_variables + 1) - .map(|i| c[i] * &gamma + &(a[i] * &alpha_beta)) + .map(|i| c[i] * &gamma + (a[i] * &alpha_beta)) .collect::>(), ); let (verifier_query, c_query_1) = result.split_at_mut(assembly.num_public_variables); @@ -293,7 +294,7 @@ where // Compute H_gamma window table let h_gamma_time = start_timer!(|| "Compute H table"); let h_gamma_window = FixedBaseMSM::get_mul_window_size(non_zero_a); - let h_gamma_table = FixedBaseMSM::get_window_table::(scalar_bits, h_gamma_window, h_gamma); + let h_gamma_table = FixedBaseMSM::get_window_table::(scalar_bits, h_gamma_window, h_gamma.into()); end_timer!(h_gamma_time); // Compute the B-query @@ -306,16 +307,16 @@ where // Generate R1CS verification key let verifying_key_time = start_timer!(|| "Generate the R1CS verification key"); - let g_alpha = g.into_affine().mul(alpha.into_repr()); - let h_beta = h.into_affine().mul(beta.into_repr()); + let g_alpha = g.into_affine().mul(alpha); + let h_beta = h.into_affine().mul(beta); end_timer!(verifying_key_time); let vk = VerifyingKey:: { h_g2: h.into_affine(), - g_alpha_g1: g_alpha.into_affine(), - h_beta_g2: h_beta.into_affine(), - g_gamma_g1: g_gamma.into_affine(), - h_gamma_g2: h_gamma.into_affine(), + g_alpha_g1: g_alpha, + h_beta_g2: h_beta, + g_gamma_g1: g_gamma, + h_gamma_g2: h_gamma, query: cfg_into_iter!(verifier_query).map(|e| e.into_affine()).collect(), }; @@ -333,10 +334,10 @@ where b_query: b_query.into_iter().map(Into::into).collect(), c_query_1: c_query_1.iter().copied().map(Into::into).collect(), c_query_2: c_query_2.into_iter().map(Into::into).collect(), - g_gamma_z: g_gamma_z.into_affine(), - h_gamma_z: h_gamma_z.into_affine(), - g_ab_gamma_z: g_ab_gamma_z.into_affine(), - g_gamma2_z2: g_gamma2_z2.into_affine(), + g_gamma_z, + h_gamma_z, + g_ab_gamma_z, + g_gamma2_z2, g_gamma2_z_t: g_gamma2_z_t.into_iter().map(Into::into).collect(), }) } diff --git a/algorithms/src/snark/gm17/prover.rs b/algorithms/src/snark/gm17/prover.rs index e4d3515982..69db83404f 100644 --- a/algorithms/src/snark/gm17/prover.rs +++ b/algorithms/src/snark/gm17/prover.rs @@ -28,9 +28,9 @@ use snarkvm_r1cs::{ }; use snarkvm_utilities::rand::UniformRand; +use core::ops::{AddAssign, Mul, MulAssign}; use rand::Rng; use smallvec::SmallVec; -use std::ops::{AddAssign, MulAssign}; #[cfg(feature = "parallel")] use rayon::prelude::*; @@ -62,10 +62,10 @@ fn evaluate( } if coeff.is_one() { - acc.add_assign(&tmp); + acc.add_assign(tmp); } else { tmp.mul_assign(&coeff); - acc.add_assign(&tmp); + acc.add_assign(tmp); } } @@ -284,11 +284,11 @@ where let r_g = params.get_g_gamma_z()?.mul(r); let d1_g = params.get_g_gamma_z()?.mul(d1); - let mut g_a = r_g; - g_a.add_assign(¶ms.get_a_query_full()?[0].into_projective()); - g_a.add_assign(&d1_g); - g_a.add_assign(&a_inputs_acc); - g_a.add_assign(&a_aux_acc); + let mut g_a = r_g.into_projective(); + g_a.add_assign(params.get_a_query_full()?[0].into_projective()); + g_a.add_assign(d1_g.into_projective()); + g_a.add_assign(a_inputs_acc); + g_a.add_assign(a_aux_acc); end_timer!(a_acc_time); // Compute B @@ -301,16 +301,16 @@ where let r_h = params.get_h_gamma_z()?.mul(r); let d1_h = params.get_h_gamma_z()?.mul(d1); - let mut g_b = r_h; - g_b.add_assign(¶ms.get_b_query_full()?[0].into_projective()); - g_b.add_assign(&d1_h); - g_b.add_assign(&b_inputs_acc); - g_b.add_assign(&b_aux_acc); + let mut g_b = r_h.into_projective(); + g_b.add_assign(params.get_b_query_full()?[0].into_projective()); + g_b.add_assign(d1_h.into_projective()); + g_b.add_assign(b_inputs_acc); + g_b.add_assign(b_aux_acc); end_timer!(b_acc_time); // Compute C let c_acc_time = start_timer!(|| "Compute C"); - let r_2 = r + &r; + let r_2 = r + r; let r2 = r * &r; let d1_r_2 = d1 * &r_2; @@ -325,7 +325,7 @@ where let c2_inputs_acc = VariableBaseMSM::multi_scalar_mul(c2_inputs_source, &input_assignment); let c2_aux_acc = VariableBaseMSM::multi_scalar_mul(c2_aux_source, &aux_assignment); - let c2_acc = c2_inputs_acc + &c2_aux_acc; + let c2_acc = c2_inputs_acc + c2_aux_acc; end_timer!(c2_acc_time); // Compute G @@ -335,7 +335,7 @@ where let g_inputs_acc = VariableBaseMSM::multi_scalar_mul(g_inputs_source, &h_input); let g_aux_acc = VariableBaseMSM::multi_scalar_mul(g_aux_source, &h_aux); - let g_acc = g_inputs_acc + &g_aux_acc; + let g_acc = g_inputs_acc + g_aux_acc; end_timer!(g_acc_time); let r2_g_gamma2_z2 = params.get_g_gamma2_z2()?.mul(r2); @@ -348,14 +348,14 @@ where r_c2_exp.mul_assign(r); let mut g_c = c1_acc; - g_c.add_assign(&r2_g_gamma2_z2); - g_c.add_assign(&r_g_ab_gamma_z); - g_c.add_assign(&d1_g_ab_gamma_z); - g_c.add_assign(&r_c0); - g_c.add_assign(&r2_d1_g_gamma2_z2); - g_c.add_assign(&r_c2_exp); - g_c.add_assign(&d2_g_gamma2_z_t0); - g_c.add_assign(&g_acc); + g_c.add_assign(r2_g_gamma2_z2.into_projective()); + g_c.add_assign(r_g_ab_gamma_z.into_projective()); + g_c.add_assign(d1_g_ab_gamma_z.into_projective()); + g_c.add_assign(r_c0.into_projective()); + g_c.add_assign(r2_d1_g_gamma2_z2.into_projective()); + g_c.add_assign(r_c2_exp); + g_c.add_assign(d2_g_gamma2_z_t0.into_projective()); + g_c.add_assign(g_acc); end_timer!(c_acc_time); end_timer!(prover_time); diff --git a/algorithms/src/snark/gm17/r1cs_to_sap.rs b/algorithms/src/snark/gm17/r1cs_to_sap.rs index 324573f897..725dc8d9a6 100644 --- a/algorithms/src/snark/gm17/r1cs_to_sap.rs +++ b/algorithms/src/snark/gm17/r1cs_to_sap.rs @@ -23,7 +23,7 @@ use snarkvm_r1cs::{ Index, }; -use std::ops::{AddAssign, SubAssign}; +use core::ops::{AddAssign, SubAssign}; #[cfg(feature = "parallel")] use rayon::prelude::*; @@ -62,7 +62,7 @@ impl R1CStoSAP { for i in 0..assembly.num_constraints { let u_2i = u[2 * i]; let u_2i_plus_1 = u[2 * i + 1]; - let u_add = u_2i + &u_2i_plus_1; + let u_add = u_2i + u_2i_plus_1; let u_sub = u_2i - &u_2i_plus_1; for &(ref coeff, index) in assembly.at[i].iter() { @@ -71,7 +71,7 @@ impl R1CStoSAP { Index::Private(i) => assembly.num_public_variables + i, }; - a[index] += &(u_add * coeff); + a[index] += u_add * coeff; } for &(ref coeff, index) in assembly.bt[i].iter() { @@ -80,7 +80,7 @@ impl R1CStoSAP { Index::Private(i) => assembly.num_public_variables + i, }; - a[index] += &(u_sub * coeff); + a[index] += u_sub * coeff; } for &(ref coeff, index) in assembly.ct[i].iter() { @@ -89,30 +89,30 @@ impl R1CStoSAP { Index::Private(i) => assembly.num_public_variables + i, }; - c[index] += &((u_2i * coeff).double().double()); + c[index] += (u_2i * coeff).double().double(); } - c[extra_var_offset + i].add_assign(&u_add); + c[extra_var_offset + i].add_assign(u_add); } - a[0].add_assign(&u[extra_constr_offset]); - c[0].add_assign(&u[extra_constr_offset]); + a[0].add_assign(u[extra_constr_offset]); + c[0].add_assign(u[extra_constr_offset]); for i in 1..assembly.num_public_variables { // First extra constraint - a[i].add_assign(&u[extra_constr_offset + 2 * i - 1]); - a[0].add_assign(&u[extra_constr_offset + 2 * i - 1]); + a[i].add_assign(u[extra_constr_offset + 2 * i - 1]); + a[0].add_assign(u[extra_constr_offset + 2 * i - 1]); let t_four = u[extra_constr_offset + 2 * i - 1].double().double(); - c[i].add_assign(&t_four); - c[extra_var_offset2 + i].add_assign(&u[extra_constr_offset + 2 * i - 1]); + c[i].add_assign(t_four); + c[extra_var_offset2 + i].add_assign(u[extra_constr_offset + 2 * i - 1]); // Second extra constraint - a[i].add_assign(&u[extra_constr_offset + 2 * i]); + a[i].add_assign(u[extra_constr_offset + 2 * i]); a[0].sub_assign(&u[extra_constr_offset + 2 * i]); - c[extra_var_offset2 + i].add_assign(&u[extra_constr_offset + 2 * i]); + c[extra_var_offset2 + i].add_assign(u[extra_constr_offset + 2 * i]); } Ok((a, c, zt, sap_num_variables, domain_size)) @@ -137,7 +137,7 @@ impl R1CStoSAP { Index::Public(i) => assignment[i], Index::Private(i) => assignment[num_input + i], }; - acc += &(val * &coeff); + acc += val * &coeff; } acc } @@ -186,7 +186,7 @@ impl R1CStoSAP { .zip(&prover.bt) .for_each(|((chunk, at_i), bt_i)| { chunk[0] = evaluate_constraint::(&at_i, &full_input_assignment, prover.num_public_variables); - chunk[0].add_assign(&evaluate_constraint::( + chunk[0].add_assign(evaluate_constraint::( &bt_i, &full_input_assignment, prover.num_public_variables, @@ -201,7 +201,7 @@ impl R1CStoSAP { }); a[extra_constr_offset] = one; for i in 1..prover.num_public_variables { - a[extra_constr_offset + 2 * i - 1] = full_input_assignment[i] + &one; + a[extra_constr_offset + 2 * i - 1] = full_input_assignment[i] + one; a[extra_constr_offset + 2 * i] = full_input_assignment[i] - &one; } @@ -230,7 +230,7 @@ impl R1CStoSAP { tmp.double_in_place(); let assignment = full_input_assignment[extra_var_offset + i]; - chunk[0] = tmp + &assignment; + chunk[0] = tmp + assignment; chunk[1] = assignment; }); c[extra_constr_offset] = one; @@ -240,7 +240,7 @@ impl R1CStoSAP { tmp.double_in_place(); let assignment = full_input_assignment[extra_var_offset2 + i]; - c[extra_constr_offset + 2 * i - 1] = tmp + &assignment; + c[extra_constr_offset + 2 * i - 1] = tmp + assignment; c[extra_constr_offset + 2 * i] = assignment; } @@ -254,7 +254,7 @@ impl R1CStoSAP { cfg_iter_mut!(h[..domain_size - 1]) .enumerate() - .for_each(|(i, e)| e.add_assign(&aa[i])); + .for_each(|(i, e)| e.add_assign(aa[i])); Ok((full_input_assignment, h, domain_size)) } diff --git a/algorithms/src/snark/gm17/tests.rs b/algorithms/src/snark/gm17/tests.rs index dc889f1a64..771fc4f438 100644 --- a/algorithms/src/snark/gm17/tests.rs +++ b/algorithms/src/snark/gm17/tests.rs @@ -143,7 +143,7 @@ mod gm17 { } let mut sum = Fr::one(); - sum.add_assign(&Fr::one()); + sum.add_assign(Fr::one()); let circuit = R1CSCircuit::new(Fr::one(), sum, Fr::one()); let rng = &mut thread_rng(); diff --git a/algorithms/src/snark/gm17/verifier.rs b/algorithms/src/snark/gm17/verifier.rs index 96ca89a751..dd1d655a96 100644 --- a/algorithms/src/snark/gm17/verifier.rs +++ b/algorithms/src/snark/gm17/verifier.rs @@ -16,12 +16,12 @@ use crate::snark::gm17::{PreparedVerifyingKey, Proof, VerifyingKey}; use snarkvm_curves::traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve}; -use snarkvm_fields::{One, PrimeField}; +use snarkvm_fields::One; use snarkvm_r1cs::errors::SynthesisError; -use std::{ +use core::{ iter, - ops::{AddAssign, MulAssign, Neg}, + ops::{AddAssign, Mul, MulAssign, Neg}, }; pub fn prepare_verifying_key(vk: VerifyingKey) -> PreparedVerifyingKey { @@ -55,24 +55,24 @@ pub fn verify_proof( // e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma}) * // e(C, H) where psi = \sum_{i=0}^l input_i pvk.query[i] - let mut g_psi = pvk.query()[0].into_projective(); + let mut g_psi = pvk.query()[0]; for (i, b) in public_inputs.iter().zip(pvk.query().iter().skip(1)) { - g_psi.add_assign(&b.mul(i.into_repr())); + g_psi.add_assign(b.mul(*i)); } let mut test1_a_g_alpha = proof.a.into_projective(); - test1_a_g_alpha.add_assign(&pvk.g_alpha.into_projective()); + test1_a_g_alpha.add_assign(pvk.g_alpha.into_projective()); let test1_a_g_alpha = test1_a_g_alpha.into_affine(); let mut test1_b_h_beta = proof.b.into_projective(); - test1_b_h_beta.add_assign(&pvk.h_beta.into_projective()); + test1_b_h_beta.add_assign(pvk.h_beta.into_projective()); let test1_b_h_beta = test1_b_h_beta.into_affine(); let test1_r1 = pvk.g_alpha_h_beta_ml; let test1_r2 = E::miller_loop( [ (&test1_a_g_alpha.neg().prepare(), &test1_b_h_beta.prepare()), - (&g_psi.into_affine().prepare(), &pvk.h_gamma_pc), + (&g_psi.prepare(), &pvk.h_gamma_pc), (&proof.c.prepare(), &pvk.h_pc), ] .iter() diff --git a/algorithms/src/snark/groth16/generator.rs b/algorithms/src/snark/groth16/generator.rs index 5d63780ba7..825869cfd1 100644 --- a/algorithms/src/snark/groth16/generator.rs +++ b/algorithms/src/snark/groth16/generator.rs @@ -16,12 +16,13 @@ use super::{push_constraints, r1cs_to_qap::R1CStoQAP, ProvingKey, VerifyingKey}; use crate::{cfg_into_iter, cfg_iter, fft::EvaluationDomain, msm::FixedBaseMSM}; -use snarkvm_curves::traits::{Group, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::traits::{PairingEngine, ProjectiveCurve}; use snarkvm_fields::{Field, One, PrimeField, Zero}; use snarkvm_profiler::{end_timer, start_timer}; use snarkvm_r1cs::{ConstraintSynthesizer, ConstraintSystem, Index, LinearCombination, SynthesisError, Variable}; use snarkvm_utilities::{errors::SerializationError, rand::UniformRand, serialize::*}; +use core::ops::Mul; use rand::Rng; #[cfg(feature = "parallel")] @@ -193,13 +194,13 @@ where let gamma_abc = cfg_iter!(a[0..assembly.num_public_variables]) .zip(&b[0..assembly.num_public_variables]) .zip(&c[0..assembly.num_public_variables]) - .map(|((a, b), c)| (beta * a + &(alpha * b) + c) * &gamma_inverse) + .map(|((a, b), c)| (beta * a + (alpha * b) + c) * &gamma_inverse) .collect::>(); let l = cfg_iter!(a) .zip(&b) .zip(&c) - .map(|((a, b), c)| (beta * a + &(alpha * b) + c) * &delta_inverse) + .map(|((a, b), c)| (beta * a + (alpha * b) + c) * &delta_inverse) .collect::>(); let g1_generator = E::G1Projective::rand(rng); @@ -214,11 +215,11 @@ where // Generate the R1CS proving key let proving_key_time = start_timer!(|| "Generate the R1CS proving key"); - let alpha_g1 = g1_generator.mul(&alpha); - let beta_g1 = g1_generator.mul(&beta); - let beta_g2 = g2_generator.mul(&beta); - let delta_g1 = g1_generator.mul(&delta); - let delta_g2 = g2_generator.mul(&delta); + let alpha_g1 = g1_generator.mul(alpha); + let beta_g1 = g1_generator.mul(beta); + let beta_g2 = g2_generator.mul(beta); + let delta_g1 = g1_generator.mul(delta); + let delta_g2 = g2_generator.mul(delta); // Compute the A-query let a_time = start_timer!(|| "Calculate A"); @@ -264,7 +265,7 @@ where // Generate R1CS verification key let verifying_key_time = start_timer!(|| "Generate the R1CS verification key"); - let gamma_g2 = g2_generator.mul(&gamma); + let gamma_g2 = g2_generator.mul(gamma); let gamma_abc_g1 = FixedBaseMSM::multi_scalar_mul::(scalar_bits, g1_window, &g1_table, &gamma_abc); drop(g1_table); diff --git a/algorithms/src/snark/groth16/prover.rs b/algorithms/src/snark/groth16/prover.rs index 0c31364c58..c7e99d36b5 100644 --- a/algorithms/src/snark/groth16/prover.rs +++ b/algorithms/src/snark/groth16/prover.rs @@ -16,7 +16,7 @@ use super::{push_constraints, r1cs_to_qap::R1CStoQAP, Proof, ProvingKey}; use crate::{cfg_into_iter, msm::VariableBaseMSM}; -use snarkvm_curves::traits::{AffineCurve, Group, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::traits::{AffineCurve, PairingEngine, ProjectiveCurve}; use snarkvm_fields::{One, PrimeField, Zero}; use snarkvm_r1cs::errors::SynthesisError; @@ -24,6 +24,7 @@ use snarkvm_profiler::{end_timer, start_timer}; use snarkvm_r1cs::{ConstraintSynthesizer, ConstraintSystem, Index, LinearCombination, Variable}; use snarkvm_utilities::rand::UniformRand; +use core::ops::Mul; use rand::Rng; #[cfg(feature = "parallel")] @@ -180,7 +181,7 @@ where let a_query = ¶ms.a_query; let r_g1 = params.delta_g1.mul(r); - let g_a = calculate_coeff(r_g1, a_query, params.vk.alpha_g1, &assignment); + let g_a = calculate_coeff(r_g1.into(), a_query, params.vk.alpha_g1, &assignment); end_timer!(a_acc_time); @@ -190,7 +191,7 @@ where let s_g1 = params.delta_g1.mul(s); let b_query = ¶ms.b_g1_query; - let g1_b = calculate_coeff(s_g1, b_query, params.beta_g1, &assignment); + let g1_b = calculate_coeff(s_g1.into(), b_query, params.beta_g1, &assignment); end_timer!(b_g1_acc_time); @@ -203,7 +204,7 @@ where let b_g2_acc_time = start_timer!(|| "Compute B in G2"); let b_query = ¶ms.b_g2_query; let s_g2 = params.vk.delta_g2.mul(s); - let g2_b = calculate_coeff(s_g2, &b_query, params.vk.beta_g2, &assignment); + let g2_b = calculate_coeff(s_g2.into(), &b_query, params.vk.beta_g2, &assignment); end_timer!(b_g2_acc_time); @@ -216,15 +217,15 @@ where let l_aux_source = ¶ms.l_query; let l_aux_acc = VariableBaseMSM::multi_scalar_mul(l_aux_source, &aux_assignment); - let s_g_a = g_a.mul(&s); - let r_g1_b = g1_b.mul(&r); - let r_s_delta_g1 = params.delta_g1.into_projective().mul(&r).mul(&s); + let s_g_a = g_a.mul(s); + let r_g1_b = g1_b.mul(r); + let r_s_delta_g1 = params.delta_g1.into_projective().mul(r).mul(s); let mut g_c = s_g_a; - g_c += &r_g1_b; + g_c += r_g1_b; g_c -= &r_s_delta_g1; - g_c += &l_aux_acc; - g_c += &h_acc; + g_c += l_aux_acc; + g_c += h_acc; end_timer!(c_acc_time); end_timer!(prover_time); @@ -248,7 +249,7 @@ fn calculate_coeff( let mut res = initial; res.add_assign_mixed(&el); - res += &acc; + res += acc; res.add_assign_mixed(&vk_param); res diff --git a/algorithms/src/snark/groth16/r1cs_to_qap.rs b/algorithms/src/snark/groth16/r1cs_to_qap.rs index 8db8b75ee5..cdb138d634 100644 --- a/algorithms/src/snark/groth16/r1cs_to_qap.rs +++ b/algorithms/src/snark/groth16/r1cs_to_qap.rs @@ -34,7 +34,7 @@ fn evaluate_constraint(terms: &[(E::Fr, Index)], assignment: & Index::Public(i) => assignment[i], Index::Private(i) => assignment[num_input + i], }; - acc += &(val * &coeff); + acc += val * &coeff; } acc } @@ -77,7 +77,7 @@ impl R1CStoQAP { Index::Private(i) => assembly.num_public_variables + i, }; - a[index] += &(*x * coeff); + a[index] += *x * coeff; } for &(ref coeff, index) in assembly.bt[i].iter() { let index = match index { @@ -85,7 +85,7 @@ impl R1CStoQAP { Index::Private(i) => assembly.num_public_variables + i, }; - b[index] += &(u[i] * coeff); + b[index] += u[i] * coeff; } for &(ref coeff, index) in assembly.ct[i].iter() { let index = match index { @@ -93,7 +93,7 @@ impl R1CStoQAP { Index::Private(i) => assembly.num_public_variables + i, }; - c[index] += &(u[i] * coeff); + c[index] += u[i] * coeff; } } diff --git a/algorithms/src/snark/groth16/verifier.rs b/algorithms/src/snark/groth16/verifier.rs index 310bf3458e..9845f2c3ce 100644 --- a/algorithms/src/snark/groth16/verifier.rs +++ b/algorithms/src/snark/groth16/verifier.rs @@ -15,11 +15,10 @@ // along with the snarkVM library. If not, see . use super::{PreparedVerifyingKey, Proof, VerifyingKey}; -use snarkvm_curves::traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve}; -use snarkvm_fields::PrimeField; +use snarkvm_curves::traits::{PairingCurve, PairingEngine}; use snarkvm_r1cs::errors::SynthesisError; -use core::ops::{AddAssign, Neg}; +use core::ops::{AddAssign, Mul, Neg}; pub fn prepare_verifying_key(vk: VerifyingKey) -> PreparedVerifyingKey { let alpha_g1_beta_g2 = E::pairing(vk.alpha_g1, vk.beta_g2); @@ -43,15 +42,15 @@ pub fn verify_proof( return Err(SynthesisError::MalformedVerifyingKey); } - let mut g_ic = pvk.gamma_abc_g1()[0].into_projective(); + let mut g_ic = pvk.gamma_abc_g1()[0]; for (i, b) in public_inputs.iter().zip(pvk.gamma_abc_g1().iter().skip(1)) { - g_ic.add_assign(&b.mul(i.into_repr())); + g_ic.add_assign(b.mul(*i)); } let qap = E::miller_loop( [ (&proof.a.prepare(), &proof.b.prepare()), - (&g_ic.into_affine().prepare(), &pvk.gamma_g2_neg_pc), + (&g_ic.prepare(), &pvk.gamma_g2_neg_pc), (&proof.c.prepare(), &pvk.delta_g2_neg_pc), ] .iter() diff --git a/algorithms/tests/snark/mimc.rs b/algorithms/tests/snark/mimc.rs index 231ca73014..337888355f 100644 --- a/algorithms/tests/snark/mimc.rs +++ b/algorithms/tests/snark/mimc.rs @@ -62,7 +62,7 @@ fn mimc(mut xl: F, mut xr: F, constants: &[F]) -> F { let mut tmp2 = tmp1; tmp2.square_in_place(); tmp2.mul_assign(&tmp1); - tmp2.add_assign(&xr); + tmp2.add_assign(xr); xr = xl; xl = tmp2; } @@ -99,7 +99,7 @@ impl<'a, F: Field> ConstraintSynthesizer for MiMCDemo<'a, F> { // tmp = (xL + Ci)^2 let tmp_value = xl_value.map(|mut e| { - e.add_assign(&self.constants[i]); + e.add_assign(self.constants[i]); e.square_in_place(); e }); @@ -116,9 +116,9 @@ impl<'a, F: Field> ConstraintSynthesizer for MiMCDemo<'a, F> { // new_xL = xR + tmp * (xL + Ci) // new_xL - xR = tmp * (xL + Ci) let new_xl_value = xl_value.map(|mut e| { - e.add_assign(&self.constants[i]); + e.add_assign(self.constants[i]); e.mul_assign(&tmp_value.unwrap()); - e.add_assign(&xr_value.unwrap()); + e.add_assign(xr_value.unwrap()); e }); diff --git a/curves/benches/bls12_377/ec.rs b/curves/benches/bls12_377/ec.rs index d326d6a763..db58d56292 100644 --- a/curves/benches/bls12_377/ec.rs +++ b/curves/benches/bls12_377/ec.rs @@ -59,7 +59,7 @@ pub(crate) mod g1 { c.bench_function("bls12_377: g1_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) @@ -151,7 +151,7 @@ pub(crate) mod g2 { c.bench_function("bls12_377: g2_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bls12_377/fq.rs b/curves/benches/bls12_377/fq.rs index 56fddfaa56..3cc5645c94 100644 --- a/curves/benches/bls12_377/fq.rs +++ b/curves/benches/bls12_377/fq.rs @@ -147,7 +147,7 @@ pub(crate) fn bench_fq_add_assign(c: &mut Criterion) { c.bench_function("bls12_377: fq_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bls12_377/fq12.rs b/curves/benches/bls12_377/fq12.rs index d97c1081a7..dedbda3068 100644 --- a/curves/benches/bls12_377/fq12.rs +++ b/curves/benches/bls12_377/fq12.rs @@ -36,7 +36,7 @@ pub(crate) fn bench_fq12_add_assign(c: &mut Criterion) { c.bench_function("bls12_377: fq12_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bls12_377/fq2.rs b/curves/benches/bls12_377/fq2.rs index 6586f61741..6bb08fef9e 100644 --- a/curves/benches/bls12_377/fq2.rs +++ b/curves/benches/bls12_377/fq2.rs @@ -36,7 +36,7 @@ pub(crate) fn bench_fq2_add_assign(c: &mut Criterion) { c.bench_function("bls12_377: fq2_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bls12_377/fr.rs b/curves/benches/bls12_377/fr.rs index 4248b59673..6d6102c22b 100644 --- a/curves/benches/bls12_377/fr.rs +++ b/curves/benches/bls12_377/fr.rs @@ -147,7 +147,7 @@ pub(crate) fn bench_fr_add_assign(c: &mut Criterion) { c.bench_function("bls12_377: fr_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bw6_761/ec.rs b/curves/benches/bw6_761/ec.rs index c08299cfc5..b8370fe1a9 100644 --- a/curves/benches/bw6_761/ec.rs +++ b/curves/benches/bw6_761/ec.rs @@ -60,7 +60,7 @@ pub(crate) mod g1 { c.bench_function("bw6_761: g1_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) @@ -152,7 +152,7 @@ pub(crate) mod g2 { c.bench_function("bw6_761: g2_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bw6_761/fq.rs b/curves/benches/bw6_761/fq.rs index b68c35e230..64f437b054 100644 --- a/curves/benches/bw6_761/fq.rs +++ b/curves/benches/bw6_761/fq.rs @@ -147,7 +147,7 @@ pub fn bench_fq_add_assign(c: &mut Criterion) { c.bench_function("bw6_761: fq_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bw6_761/fq3.rs b/curves/benches/bw6_761/fq3.rs index 5057ec7beb..a8150231e7 100644 --- a/curves/benches/bw6_761/fq3.rs +++ b/curves/benches/bw6_761/fq3.rs @@ -36,7 +36,7 @@ pub fn bench_fq3_add_assign(c: &mut Criterion) { c.bench_function("bw6_761: fq3_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bw6_761/fq6.rs b/curves/benches/bw6_761/fq6.rs index b51bc97665..3c99b68aea 100644 --- a/curves/benches/bw6_761/fq6.rs +++ b/curves/benches/bw6_761/fq6.rs @@ -36,7 +36,7 @@ pub fn bench_fq6_add_assign(c: &mut Criterion) { c.bench_function("bw6_761: fq6_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/benches/bw6_761/fr.rs b/curves/benches/bw6_761/fr.rs index 3151bb5e56..c8b0e5092a 100644 --- a/curves/benches/bw6_761/fr.rs +++ b/curves/benches/bw6_761/fr.rs @@ -147,7 +147,7 @@ pub fn bench_fr_add_assign(c: &mut Criterion) { c.bench_function("bw6_761: fr_add_assign", |c| { c.iter(|| { let mut tmp = v[count].0; - tmp.add_assign(&v[count].1); + tmp.add_assign(v[count].1); count = (count + 1) % SAMPLES; tmp }) diff --git a/curves/src/bls12_377/tests.rs b/curves/src/bls12_377/tests.rs index c350a0f23d..45d14e8e88 100644 --- a/curves/src/bls12_377/tests.rs +++ b/curves/src/bls12_377/tests.rs @@ -178,12 +178,12 @@ fn test_fq_add_assign() { let c = Fq::rand(&mut rng); let mut tmp1 = a; - tmp1.add_assign(&b); - tmp1.add_assign(&c); + tmp1.add_assign(b); + tmp1.add_assign(c); let mut tmp2 = b; - tmp2.add_assign(&c); - tmp2.add_assign(&a); + tmp2.add_assign(c); + tmp2.add_assign(a); assert!(tmp1.is_valid()); assert!(tmp2.is_valid()); @@ -206,7 +206,7 @@ fn test_fq_sub_assign() { let mut tmp2 = b; tmp2.sub_assign(&a); - tmp1.add_assign(&tmp2); + tmp1.add_assign(tmp2); assert!(tmp1.is_zero()); } } @@ -241,16 +241,16 @@ fn test_fq_mul_assign() { let mut c = Fq::rand(&mut rng); let mut tmp1 = a; - tmp1.add_assign(&b); - tmp1.add_assign(&c); + tmp1.add_assign(b); + tmp1.add_assign(c); tmp1.mul_assign(&r); a.mul_assign(&r); b.mul_assign(&r); c.mul_assign(&r); - a.add_assign(&b); - a.add_assign(&c); + a.add_assign(b); + a.add_assign(c); assert_eq!(tmp1, a); } @@ -299,7 +299,7 @@ fn test_fq_double_in_place() { // Ensure doubling a is equivalent to adding a to itself. let mut a = Fq::rand(&mut rng); let mut b = a; - b.add_assign(&a); + b.add_assign(a); a.double_in_place(); assert_eq!(a, b); } @@ -319,7 +319,7 @@ fn test_fq_negate() { // Ensure (a - (-a)) = 0. let mut a = Fq::rand(&mut rng); let b = -a; - a.add_assign(&b); + a.add_assign(b); assert!(a.is_zero()); } @@ -432,17 +432,17 @@ fn test_fq2_ordering() { let mut b = a; assert!(a.cmp(&b) == Ordering::Equal); - b.c0.add_assign(&Fq::one()); + b.c0.add_assign(Fq::one()); assert!(a.cmp(&b) == Ordering::Less); - a.c0.add_assign(&Fq::one()); + a.c0.add_assign(Fq::one()); assert!(a.cmp(&b) == Ordering::Equal); - b.c1.add_assign(&Fq::one()); + b.c1.add_assign(Fq::one()); assert!(a.cmp(&b) == Ordering::Less); - a.c0.add_assign(&Fq::one()); + a.c0.add_assign(Fq::one()); assert!(a.cmp(&b) == Ordering::Less); - a.c1.add_assign(&Fq::one()); + a.c1.add_assign(Fq::one()); assert!(a.cmp(&b) == Ordering::Greater); - b.c0.add_assign(&Fq::one()); + b.c0.add_assign(Fq::one()); assert!(a.cmp(&b) == Ordering::Equal); } @@ -606,8 +606,8 @@ fn test_bilinearity() { let b: G2Projective = rand::random(); let s: Fr = rand::random(); - let sa = a * &s; - let sb = b * &s; + let sa = a * s; + let sb = b * s; let ans1 = Bls12_377::pairing(sa, b); let ans2 = Bls12_377::pairing(a, sb); @@ -634,7 +634,7 @@ fn test_g1_generator_raw() { let mut rhs = x; rhs.square_in_place(); rhs.mul_assign(&x); - rhs.add_assign(&Bls12_377G1Parameters::COEFF_B); + rhs.add_assign(Bls12_377G1Parameters::COEFF_B); if let Some(y) = rhs.sqrt() { let p = G1Affine::new(x, if y < -y { y } else { -y }, false); @@ -653,6 +653,6 @@ fn test_g1_generator_raw() { } i += 1; - x.add_assign(&Fq::one()); + x.add_assign(Fq::one()); } } diff --git a/curves/src/bw6_761/tests.rs b/curves/src/bw6_761/tests.rs index a3e275da74..f6a4dee512 100644 --- a/curves/src/bw6_761/tests.rs +++ b/curves/src/bw6_761/tests.rs @@ -122,8 +122,8 @@ fn test_bilinearity() { let b: G2Projective = rand::random(); let s: Fr = rand::random(); - let sa = a * &s; - let sb = b * &s; + let sa = a * s; + let sb = b * s; let ans1 = BW6_761::pairing(sa, b); let ans2 = BW6_761::pairing(a, sb); diff --git a/curves/src/edwards_bls12/tests.rs b/curves/src/edwards_bls12/tests.rs index 40dff7f063..ac82a2d139 100644 --- a/curves/src/edwards_bls12/tests.rs +++ b/curves/src/edwards_bls12/tests.rs @@ -21,6 +21,7 @@ use crate::{ tests_curve::curve_tests, tests_group::group_test, AffineCurve, + Group, MontgomeryModelParameters, ProjectiveCurve, TEModelParameters, diff --git a/curves/src/edwards_sw6/tests.rs b/curves/src/edwards_sw6/tests.rs index c352d97a7c..ea92cb5112 100644 --- a/curves/src/edwards_sw6/tests.rs +++ b/curves/src/edwards_sw6/tests.rs @@ -17,7 +17,7 @@ use crate::{ edwards_sw6::*, templates::twisted_edwards_extended::tests::{edwards_test, montgomery_conversion_test}, - traits::{tests_curve::curve_tests, tests_group::group_test, AffineCurve, ProjectiveCurve}, + traits::{tests_curve::curve_tests, tests_group::group_test, AffineCurve, Group, ProjectiveCurve}, }; use snarkvm_fields::tests_field::{field_serialization_test, field_test, primefield_test}; diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs index ca5a97addf..6beb6538c5 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs @@ -17,9 +17,9 @@ use crate::{ impl_sw_curve_serializer, impl_sw_from_random_bytes, - traits::{AffineCurve, ProjectiveCurve, SWModelParameters as Parameters}, + traits::{AffineCurve, Group, ProjectiveCurve, SWModelParameters as Parameters}, }; -use snarkvm_fields::{Field, One, PrimeField, SquareRootField, Zero}; +use snarkvm_fields::{impl_additive_ops_from_ref, Field, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ bititerator::BitIteratorBE, bytes::{FromBytes, ToBytes}, @@ -80,17 +80,6 @@ impl GroupAffine

{ self.mul_bits(BitIteratorBE::new(P::COFACTOR)) } - pub(crate) fn mul_bits>(&self, bits: BitIteratorBE) -> GroupProjective

{ - let mut res = GroupProjective::zero(); - for i in bits { - res.double_in_place(); - if i { - res.add_assign_mixed(self) - } - } - res - } - pub fn is_on_curve(&self) -> bool { if self.is_zero() { true @@ -118,7 +107,6 @@ impl Zero for GroupAffine

{ impl AffineCurve for GroupAffine

{ type BaseField = P::BaseField; type Projective = GroupProjective

; - type ScalarField = P::ScalarField; impl_sw_from_random_bytes!(); @@ -153,14 +141,15 @@ impl AffineCurve for GroupAffine

{ unimplemented!() } - fn add(self, _other: &Self) -> Self { - unimplemented!() - } - - #[inline] - fn mul::BigInteger>>(&self, by: S) -> GroupProjective

{ - let bits = BitIteratorBE::new(by.into()); - self.mul_bits(bits) + fn mul_bits>(&self, bits: BitIteratorBE) -> GroupProjective

{ + let mut res = GroupProjective::zero(); + for i in bits { + res.double_in_place(); + if i { + res.add_assign_mixed(self) + } + } + res } fn mul_by_cofactor_to_projective(&self) -> Self::Projective { @@ -202,6 +191,24 @@ impl AffineCurve for GroupAffine

{ } } +impl Group for GroupAffine

{ + type ScalarField = P::ScalarField; + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp += self; + tmp + } + + #[inline] + fn double_in_place(&mut self) { + let tmp = *self; + *self = tmp.double(); + } +} + impl Neg for GroupAffine

{ type Output = Self; @@ -215,6 +222,56 @@ impl Neg for GroupAffine

{ } } +impl_additive_ops_from_ref!(GroupAffine, Parameters); + +impl<'a, P: Parameters> Add<&'a Self> for GroupAffine

{ + type Output = Self; + + fn add(self, other: &'a Self) -> Self { + let mut copy = self; + copy += other; + copy + } +} + +impl<'a, P: Parameters> AddAssign<&'a Self> for GroupAffine

{ + fn add_assign(&mut self, other: &'a Self) { + let mut projective = GroupProjective::from(*self); + projective.add_assign_mixed(other); + *self = projective.into(); + } +} + +impl<'a, P: Parameters> Sub<&'a Self> for GroupAffine

{ + type Output = Self; + + fn sub(self, other: &'a Self) -> Self { + let mut copy = self; + copy -= other; + copy + } +} + +impl<'a, P: Parameters> SubAssign<&'a Self> for GroupAffine

{ + fn sub_assign(&mut self, other: &'a Self) { + *self += &(-(*other)); + } +} + +impl Mul for GroupAffine

{ + type Output = Self; + + fn mul(self, other: P::ScalarField) -> Self { + self.mul_bits(BitIteratorBE::new(other.into_repr())).into() + } +} + +impl MulAssign for GroupAffine

{ + fn mul_assign(&mut self, other: P::ScalarField) { + *self = self.mul(other).into() + } +} + impl ToBytes for GroupAffine

{ #[inline] fn write(&self, mut writer: W) -> IoResult<()> { @@ -245,6 +302,20 @@ impl Default for GroupAffine

{ } } +impl Distribution> for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> GroupAffine

{ + loop { + let x = P::BaseField::rand(rng); + let greatest = rng.gen(); + + if let Some(p) = GroupAffine::from_x_coordinate(x, greatest) { + return p.scale_by_cofactor().into(); + } + } + } +} + #[derive(Derivative)] #[derivative( Copy(bound = "P: Parameters"), @@ -289,7 +360,7 @@ impl PartialEq for GroupProjective

{ impl Distribution> for Standard { #[inline] fn sample(&self, rng: &mut R) -> GroupProjective

{ - let res = GroupProjective::prime_subgroup_generator() * &P::ScalarField::rand(rng); + let res = GroupProjective::prime_subgroup_generator() * P::ScalarField::rand(rng); debug_assert!(res.into_affine().is_in_correct_subgroup_assuming_on_curve()); res } @@ -351,7 +422,6 @@ impl Zero for GroupProjective

{ impl ProjectiveCurve for GroupProjective

{ type Affine = GroupAffine

; type BaseField = P::BaseField; - type ScalarField = P::ScalarField; #[inline] fn prime_subgroup_generator() -> Self { @@ -428,75 +498,6 @@ impl ProjectiveCurve for GroupProjective

{ } } - #[allow(clippy::many_single_char_names)] - fn double_in_place(&mut self) -> &mut Self { - if self.is_zero() { - return self; - } - - if P::COEFF_A.is_zero() { - // A = X1^2 - let mut a = self.x.square(); - - // B = Y1^2 - let b = self.y.square(); - - // C = B^2 - let mut c = b.square(); - - // D = 2*((X1+B)2-A-C) - let d = ((self.x + &b).square() - &a - &c).double(); - - // E = 3*A - let e = a + &*a.double_in_place(); - - // F = E^2 - let f = e.square(); - - // Z3 = 2*Y1*Z1 - self.z *= &self.y; - self.z.double_in_place(); - - // X3 = F-2*D - self.x = f - &d - &d; - - // Y3 = E*(D-X3)-8*C - self.y = (d - &self.x) * &e - &*c.double_in_place().double_in_place().double_in_place(); - self - } else { - // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l - // XX = X1^2 - let xx = self.x.square(); - - // YY = Y1^2 - let yy = self.y.square(); - - // YYYY = YY^2 - let mut yyyy = yy.square(); - - // ZZ = Z1^2 - let zz = self.z.square(); - - // S = 2*((X1+YY)^2-XX-YYYY) - let s = ((self.x + &yy).square() - &xx - &yyyy).double(); - - // M = 3*XX+a*ZZ^2 - let m = xx + &xx + &xx + &P::mul_by_a(&zz.square()); - - // T = M^2-2*S - let t = m.square() - &s.double(); - - // X3 = T - self.x = t; - // Y3 = M*(S-T)-8*YYYY - let old_y = self.y; - self.y = m * &(s - &t) - &*yyyy.double_in_place().double_in_place().double_in_place(); - // Z3 = (Y1+Z1)^2-YY-ZZ - self.z = (old_y + &self.z).square() - &yy - &zz; - self - } - } - #[allow(clippy::many_single_char_names)] fn add_assign_mixed(&mut self, other: &Self::Affine) { if other.is_zero() { @@ -536,7 +537,8 @@ impl ProjectiveCurve for GroupProjective

{ // I = 4*HH let mut i = hh; - i.double_in_place().double_in_place(); + i.double_in_place(); + i.double_in_place(); // J = H*I let mut j = h * &i; @@ -568,26 +570,6 @@ impl ProjectiveCurve for GroupProjective

{ } } - fn mul_assign::BigInteger>>(&mut self, other: S) { - let mut res = Self::zero(); - - let mut found_one = false; - - for i in BitIteratorBE::new(other.into()) { - if found_one { - res.double_in_place(); - } else { - found_one = i; - } - - if i { - res.add_assign(self); - } - } - - *self = res; - } - #[inline] fn into_affine(&self) -> GroupAffine

{ (*self).into() @@ -604,6 +586,93 @@ impl ProjectiveCurve for GroupProjective

{ } } +impl Group for GroupProjective

{ + type ScalarField = P::ScalarField; + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp.double_in_place(); + tmp + } + + #[inline] + fn double_in_place(&mut self) { + if self.is_zero() { + return; + } + + if P::COEFF_A.is_zero() { + // A = X1^2 + let mut a = self.x.square(); + + // B = Y1^2 + let b = self.y.square(); + + // C = B^2 + let mut c = b.square(); + + // D = 2*((X1+B)2-A-C) + let d = ((self.x + &b).square() - &a - &c).double(); + + // E = 3*A + let old_a = a; + a.double_in_place(); + let e = old_a + a; + + // F = E^2 + let f = e.square(); + + // Z3 = 2*Y1*Z1 + self.z *= &self.y; + self.z.double_in_place(); + + // X3 = F-2*D + self.x = f - &d - &d; + + // Y3 = E*(D-X3)-8*C + c.double_in_place(); + c.double_in_place(); + c.double_in_place(); + self.y = (d - &self.x) * &e - c; + } else { + // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + // XX = X1^2 + let xx = self.x.square(); + + // YY = Y1^2 + let yy = self.y.square(); + + // YYYY = YY^2 + let mut yyyy = yy.square(); + + // ZZ = Z1^2 + let zz = self.z.square(); + + // S = 2*((X1+YY)^2-XX-YYYY) + let s = ((self.x + &yy).square() - &xx - &yyyy).double(); + + // M = 3*XX+a*ZZ^2 + let m = xx + &xx + &xx + &P::mul_by_a(&zz.square()); + + // T = M^2-2*S + let t = m.square() - &s.double(); + + // X3 = T + self.x = t; + // Y3 = M*(S-T)-8*YYYY + let old_y = self.y; + yyyy.double_in_place(); + yyyy.double_in_place(); + yyyy.double_in_place(); + self.y = m * &(s - &t) - yyyy; + // Z3 = (Y1+Z1)^2-YY-ZZ + self.z = (old_y + &self.z).square() - &yy - &zz; + } + } +} + impl Neg for GroupProjective

{ type Output = Self; @@ -617,6 +686,8 @@ impl Neg for GroupProjective

{ } } +impl_additive_ops_from_ref!(GroupProjective, Parameters); + impl<'a, P: Parameters> Add<&'a Self> for GroupProjective

{ type Output = Self; @@ -687,7 +758,7 @@ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ self.x = r.square() - &j - &(v.double()); // Y3 = r*(V - X3) - 2*S1*J - self.y = r * &(v - &self.x) - &*(s1 * &j).double_in_place(); + self.y = r * &(v - &self.x) - (s1 * &j).double(); // Z3 = ((Z1+Z2)^2 - Z1Z1 - Z2Z2)*H self.z = ((self.z + &other.z).square() - &z1z1 - &z2z2) * &h; @@ -712,21 +783,36 @@ impl<'a, P: Parameters> SubAssign<&'a Self> for GroupProjective

{ } } -impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupProjective

{ +impl Mul for GroupProjective

{ type Output = Self; + /// Performs scalar multiplication of this element. #[inline] - fn mul(self, other: &'a P::ScalarField) -> Self { - let mut copy = self; - copy *= other; - copy + fn mul(self, other: P::ScalarField) -> Self { + let mut res = Self::zero(); + + let mut found_one = false; + + for i in BitIteratorBE::new(other.into_repr()) { + if found_one { + res.double_in_place(); + } else { + found_one = i; + } + + if i { + res += self; + } + } + + res } } -impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupProjective

{ - #[inline] - fn mul_assign(&mut self, other: &'a P::ScalarField) { - as ProjectiveCurve>::mul_assign(self, *other); +impl MulAssign for GroupProjective

{ + /// Performs scalar multiplication of this element. + fn mul_assign(&mut self, other: P::ScalarField) { + *self = *self * other } } diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs index 791c8fcd16..5daf1fd361 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs @@ -17,9 +17,9 @@ use crate::{ impl_sw_curve_serializer, impl_sw_from_random_bytes, - traits::{AffineCurve, ProjectiveCurve, SWModelParameters as Parameters}, + traits::{AffineCurve, Group, ProjectiveCurve, SWModelParameters as Parameters}, }; -use snarkvm_fields::{Field, One, PrimeField, SquareRootField, Zero}; +use snarkvm_fields::{impl_additive_ops_from_ref, Field, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ bititerator::BitIteratorBE, bytes::{FromBytes, ToBytes}, @@ -80,17 +80,6 @@ impl GroupAffine

{ self.mul_bits(BitIteratorBE::new(P::COFACTOR)) } - pub(crate) fn mul_bits>(&self, bits: BitIteratorBE) -> ::Projective { - let mut res = GroupProjective::zero(); - for i in bits { - res.double_in_place(); - if i { - res.add_assign_mixed(self) - } - } - res - } - /// Checks that the current point is on the elliptic curve. pub fn is_on_curve(&self) -> bool { if self.is_zero() { @@ -117,7 +106,6 @@ impl Zero for GroupAffine

{ impl AffineCurve for GroupAffine

{ type BaseField = P::BaseField; type Projective = GroupProjective

; - type ScalarField = P::ScalarField; impl_sw_from_random_bytes!(); @@ -151,13 +139,15 @@ impl AffineCurve for GroupAffine

{ unimplemented!() } - fn add(self, _other: &Self) -> Self { - unimplemented!() - } - - fn mul::BigInteger>>(&self, by: S) -> GroupProjective

{ - let bits = BitIteratorBE::new(by.into()); - self.mul_bits(bits) + fn mul_bits>(&self, bits: BitIteratorBE) -> ::Projective { + let mut res = GroupProjective::zero(); + for i in bits { + res.double_in_place(); + if i { + res.add_assign_mixed(self) + } + } + res } fn mul_by_cofactor_to_projective(&self) -> Self::Projective { @@ -198,6 +188,24 @@ impl AffineCurve for GroupAffine

{ } } +impl Group for GroupAffine

{ + type ScalarField = P::ScalarField; + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp += self; + tmp + } + + #[inline] + fn double_in_place(&mut self) { + let tmp = *self; + *self = tmp.double(); + } +} + impl Neg for GroupAffine

{ type Output = Self; @@ -210,6 +218,56 @@ impl Neg for GroupAffine

{ } } +impl_additive_ops_from_ref!(GroupAffine, Parameters); + +impl<'a, P: Parameters> Add<&'a Self> for GroupAffine

{ + type Output = Self; + + fn add(self, other: &'a Self) -> Self { + let mut copy = self; + copy += other; + copy + } +} + +impl<'a, P: Parameters> AddAssign<&'a Self> for GroupAffine

{ + fn add_assign(&mut self, other: &'a Self) { + let mut projective = GroupProjective::from(*self); + projective.add_assign_mixed(other); + *self = projective.into(); + } +} + +impl<'a, P: Parameters> Sub<&'a Self> for GroupAffine

{ + type Output = Self; + + fn sub(self, other: &'a Self) -> Self { + let mut copy = self; + copy -= other; + copy + } +} + +impl<'a, P: Parameters> SubAssign<&'a Self> for GroupAffine

{ + fn sub_assign(&mut self, other: &'a Self) { + *self += &(-(*other)); + } +} + +impl Mul for GroupAffine

{ + type Output = Self; + + fn mul(self, other: P::ScalarField) -> Self { + self.mul_bits(BitIteratorBE::new(other.into_repr())).into() + } +} + +impl MulAssign for GroupAffine

{ + fn mul_assign(&mut self, other: P::ScalarField) { + *self = self.mul(other).into() + } +} + impl ToBytes for GroupAffine

{ #[inline] fn write(&self, mut writer: W) -> IoResult<()> { @@ -241,6 +299,20 @@ impl Default for GroupAffine

{ } } +impl Distribution> for Standard { + #[inline] + fn sample(&self, rng: &mut R) -> GroupAffine

{ + loop { + let x = P::BaseField::rand(rng); + let greatest = rng.gen(); + + if let Some(p) = GroupAffine::from_x_coordinate(x, greatest) { + return p.scale_by_cofactor().into(); + } + } + } +} + #[derive(Derivative)] #[derivative( Copy(bound = "P: Parameters"), @@ -280,7 +352,7 @@ impl PartialEq for GroupProjective

{ impl Distribution> for Standard { #[inline] fn sample(&self, rng: &mut R) -> GroupProjective

{ - let res = GroupProjective::prime_subgroup_generator() * &P::ScalarField::rand(rng); + let res = GroupProjective::prime_subgroup_generator() * P::ScalarField::rand(rng); debug_assert!(res.into_affine().is_in_correct_subgroup_assuming_on_curve()); res } @@ -341,7 +413,6 @@ impl Zero for GroupProjective

{ impl ProjectiveCurve for GroupProjective

{ type Affine = GroupAffine

; type BaseField = P::BaseField; - type ScalarField = P::ScalarField; #[inline] fn prime_subgroup_generator() -> Self { @@ -402,44 +473,6 @@ impl ProjectiveCurve for GroupProjective

{ } } - #[allow(clippy::many_single_char_names)] - fn double_in_place(&mut self) -> &mut Self { - if self.is_zero() { - self - } else { - // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#doubling-dbl-2007-bl - - // XX = X1^2 - let xx = self.x.square(); - // ZZ = Z1^2 - let zz = self.z.square(); - // w = a*ZZ + 3*XX - let w = P::mul_by_a(&zz) + &(xx + &xx.double()); - // s = 2*Y1*Z1 - let mut s = self.y * &(self.z); - s.double_in_place(); - // sss = s^3 - let mut sss = s.square(); - sss *= &s; - // R = Y1*s - let r = self.y * &s; - // RR = R2 - let rr = r.square(); - // B = (X1+R)^2-XX-RR - let b = (self.x + &r).square() - &xx - &rr; - // h = w2-2*B - let h = w.square() - &(b + &b); - // X3 = h*s - self.x = h * &s; - // Y3 = w*(B-h)-2*RR - self.y = w * &(b - &h) - &(rr + &rr); - // Z3 = sss - self.z = sss; - - self - } - } - fn add_assign_mixed(&mut self, other: &Self::Affine) { if other.is_zero() { return; @@ -480,26 +513,6 @@ impl ProjectiveCurve for GroupProjective

{ } } - fn mul_assign::BigInteger>>(&mut self, other: S) { - let mut res = Self::zero(); - - let mut found_one = false; - - for i in BitIteratorBE::new(other.into()) { - if found_one { - res.double_in_place(); - } else { - found_one = i; - } - - if i { - res.add_assign(self); - } - } - - *self = res; - } - fn into_affine(&self) -> GroupAffine

{ (*self).into() } @@ -513,6 +526,54 @@ impl ProjectiveCurve for GroupProjective

{ } } +impl Group for GroupProjective

{ + type ScalarField = P::ScalarField; + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp.double_in_place(); + tmp + } + + #[inline] + fn double_in_place(&mut self) { + if self.is_zero() { + return; + } else { + // https://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#doubling-dbl-2007-bl + + // XX = X1^2 + let xx = self.x.square(); + // ZZ = Z1^2 + let zz = self.z.square(); + // w = a*ZZ + 3*XX + let w = P::mul_by_a(&zz) + &(xx + &xx.double()); + // s = 2*Y1*Z1 + let mut s = self.y * &(self.z); + s.double_in_place(); + // sss = s^3 + let mut sss = s.square(); + sss *= &s; + // R = Y1*s + let r = self.y * &s; + // RR = R2 + let rr = r.square(); + // B = (X1+R)^2-XX-RR + let b = (self.x + &r).square() - &xx - &rr; + // h = w2-2*B + let h = w.square() - &(b + &b); + // X3 = h*s + self.x = h * &s; + // Y3 = w*(B-h)-2*RR + self.y = w * &(b - &h) - &(rr + &rr); + // Z3 = sss + self.z = sss; + } + } +} + impl Neg for GroupProjective

{ type Output = Self; @@ -525,6 +586,8 @@ impl Neg for GroupProjective

{ } } +impl_additive_ops_from_ref!(GroupProjective, Parameters); + impl<'a, P: Parameters> Add<&'a Self> for GroupProjective

{ type Output = Self; @@ -597,19 +660,36 @@ impl<'a, P: Parameters> SubAssign<&'a Self> for GroupProjective

{ } } -impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupProjective

{ +impl Mul for GroupProjective

{ type Output = Self; - fn mul(self, other: &'a P::ScalarField) -> Self { - let mut copy = self; - copy *= other; - copy + /// Performs scalar multiplication of this element. + #[inline] + fn mul(self, other: P::ScalarField) -> Self { + let mut res = Self::zero(); + + let mut found_one = false; + + for i in BitIteratorBE::new(other.into_repr()) { + if found_one { + res.double_in_place(); + } else { + found_one = i; + } + + if i { + res += self; + } + } + + res } } -impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupProjective

{ - fn mul_assign(&mut self, other: &'a P::ScalarField) { - as ProjectiveCurve>::mul_assign(self, other.into_repr()); +impl MulAssign for GroupProjective

{ + /// Performs scalar multiplication of this element. + fn mul_assign(&mut self, other: P::ScalarField) { + *self = *self * other } } diff --git a/curves/src/templates/twisted_edwards_extended/mod.rs b/curves/src/templates/twisted_edwards_extended/mod.rs index df049618d7..019a8bf2e8 100644 --- a/curves/src/templates/twisted_edwards_extended/mod.rs +++ b/curves/src/templates/twisted_edwards_extended/mod.rs @@ -18,12 +18,13 @@ use crate::{ impl_edwards_curve_serializer, traits::{ AffineCurve, + Group, MontgomeryModelParameters as MontgomeryParameters, ProjectiveCurve, TEModelParameters as Parameters, }, }; -use snarkvm_fields::{Field, One, PrimeField, SquareRootField, Zero}; +use snarkvm_fields::{impl_additive_ops_from_ref, Field, One, PrimeField, SquareRootField, Zero}; use snarkvm_utilities::{ bititerator::BitIteratorBE, bytes::{FromBytes, ToBytes}, @@ -81,18 +82,6 @@ impl GroupAffine

{ self.mul_bits(BitIteratorBE::new(P::COFACTOR)) } - #[must_use] - pub(crate) fn mul_bits>(&self, bits: BitIteratorBE) -> ::Projective { - let mut res = GroupProjective::zero(); - for i in bits { - res.double_in_place(); - if i { - res.add_assign_mixed(self) - } - } - res - } - /// Checks that the current point is on the elliptic curve. pub fn is_on_curve(&self) -> bool { let x2 = self.x.square(); @@ -118,7 +107,6 @@ impl Zero for GroupAffine

{ impl AffineCurve for GroupAffine

{ type BaseField = P::BaseField; type Projective = GroupProjective

; - type ScalarField = P::ScalarField; fn prime_subgroup_generator() -> Self { Self::new(P::AFFINE_GENERATOR_COEFFS.0, P::AFFINE_GENERATOR_COEFFS.1) @@ -177,14 +165,15 @@ impl AffineCurve for GroupAffine

{ } } - fn add(self, other: &Self) -> Self { - let mut copy = self; - copy += other; - copy - } - - fn mul::BigInteger>>(&self, by: S) -> GroupProjective

{ - self.mul_bits(BitIteratorBE::new(by.into())) + fn mul_bits>(&self, bits: BitIteratorBE) -> ::Projective { + let mut res = GroupProjective::zero(); + for i in bits { + res.double_in_place(); + if i { + res.add_assign_mixed(self) + } + } + res } fn mul_by_cofactor_to_projective(&self) -> Self::Projective { @@ -224,6 +213,24 @@ impl AffineCurve for GroupAffine

{ } } +impl Group for GroupAffine

{ + type ScalarField = P::ScalarField; + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp += self; + tmp + } + + #[inline] + fn double_in_place(&mut self) { + let tmp = *self; + *self = tmp.double(); + } +} + impl Neg for GroupAffine

{ type Output = Self; @@ -232,6 +239,8 @@ impl Neg for GroupAffine

{ } } +impl_additive_ops_from_ref!(GroupAffine, Parameters); + impl<'a, P: Parameters> Add<&'a Self> for GroupAffine

{ type Output = Self; @@ -276,19 +285,17 @@ impl<'a, P: Parameters> SubAssign<&'a Self> for GroupAffine

{ } } -impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupAffine

{ +impl Mul for GroupAffine

{ type Output = Self; - fn mul(self, other: &'a P::ScalarField) -> Self { - let mut copy = self; - copy *= other; - copy + fn mul(self, other: P::ScalarField) -> Self { + self.mul_bits(BitIteratorBE::new(other.into_repr())).into() } } -impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupAffine

{ - fn mul_assign(&mut self, other: &'a P::ScalarField) { - *self = ::mul(self, other.into_repr()).into_affine(); +impl MulAssign for GroupAffine

{ + fn mul_assign(&mut self, other: P::ScalarField) { + *self = self.mul(other).into() } } @@ -330,31 +337,6 @@ impl Distribution> for Standard { } } -mod group_impl { - use super::*; - use crate::traits::Group; - - impl Group for GroupAffine

{ - type ScalarField = P::ScalarField; - - #[inline] - #[must_use] - fn double(&self) -> Self { - let mut tmp = *self; - tmp += self; - tmp - } - - #[inline] - fn double_in_place(&mut self) -> &mut Self { - let mut tmp = *self; - tmp += self; - *self = tmp; - self - } - } -} - ////////////////////////////////////////////////////////////////////////////// #[derive(Derivative)] @@ -467,7 +449,6 @@ impl Zero for GroupProjective

{ impl ProjectiveCurve for GroupProjective

{ type Affine = GroupAffine

; type BaseField = P::BaseField; - type ScalarField = P::ScalarField; fn prime_subgroup_generator() -> Self { GroupAffine::prime_subgroup_generator().into() @@ -527,12 +508,6 @@ impl ProjectiveCurve for GroupProjective

{ } } - fn double_in_place(&mut self) -> &mut Self { - let tmp = *self; - *self += &tmp; - self - } - #[allow(clippy::many_single_char_names)] fn add_assign_mixed(&mut self, other: &Self::Affine) { // A = X1*X2 @@ -561,26 +536,6 @@ impl ProjectiveCurve for GroupProjective

{ self.z = f * &g; } - fn mul_assign::BigInteger>>(&mut self, other: S) { - let mut res = Self::zero(); - - let mut found_one = false; - - for i in BitIteratorBE::new(other.into()) { - if found_one { - res.double_in_place(); - } else { - found_one = i; - } - - if i { - res.add_assign(self); - } - } - - *self = res; - } - fn into_affine(&self) -> GroupAffine

{ (*self).into() } @@ -594,6 +549,24 @@ impl ProjectiveCurve for GroupProjective

{ } } +impl Group for GroupProjective

{ + type ScalarField = P::ScalarField; + + #[inline] + #[must_use] + fn double(&self) -> Self { + let mut tmp = *self; + tmp += self; + tmp + } + + #[inline] + fn double_in_place(&mut self) { + let tmp = *self; + *self = tmp.double(); + } +} + impl Neg for GroupProjective

{ type Output = Self; @@ -604,6 +577,8 @@ impl Neg for GroupProjective

{ } } +impl_additive_ops_from_ref!(GroupProjective, Parameters); + impl<'a, P: Parameters> Add<&'a Self> for GroupProjective

{ type Output = Self; @@ -676,19 +651,36 @@ impl<'a, P: Parameters> SubAssign<&'a Self> for GroupProjective

{ } } -impl<'a, P: Parameters> Mul<&'a P::ScalarField> for GroupProjective

{ +impl Mul for GroupProjective

{ type Output = Self; - fn mul(self, other: &'a P::ScalarField) -> Self { - let mut copy = self; - copy *= other; - copy + /// Performs scalar multiplication of this element. + #[inline] + fn mul(self, other: P::ScalarField) -> Self { + let mut res = Self::zero(); + + let mut found_one = false; + + for i in BitIteratorBE::new(other.into_repr()) { + if found_one { + res.double_in_place(); + } else { + found_one = i; + } + + if i { + res += self; + } + } + + res } } -impl<'a, P: Parameters> MulAssign<&'a P::ScalarField> for GroupProjective

{ - fn mul_assign(&mut self, other: &'a P::ScalarField) { - ::mul_assign(self, other.into_repr()); +impl MulAssign for GroupProjective

{ + /// Performs scalar multiplication of this element. + fn mul_assign(&mut self, other: P::ScalarField) { + *self = *self * other } } diff --git a/curves/src/traits/group.rs b/curves/src/traits/group.rs index 7202f2186f..50ef1d268b 100644 --- a/curves/src/traits/group.rs +++ b/curves/src/traits/group.rs @@ -14,9 +14,8 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_fields::PrimeField; +use snarkvm_fields::{PrimeField, SquareRootField}; use snarkvm_utilities::{ - bititerator::BitIteratorBE, bytes::{FromBytes, ToBytes}, rand::UniformRand, }; @@ -24,7 +23,7 @@ use snarkvm_utilities::{ use std::{ fmt::{Debug, Display}, hash::Hash, - ops::{Add, AddAssign, Neg, Sub, SubAssign}, + ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign}, }; use snarkvm_fields::Zero; @@ -45,35 +44,23 @@ pub trait Group: + Neg + UniformRand + Zero + + Add + + Sub + + Mul + + AddAssign + + SubAssign + + MulAssign + for<'a> Add<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> + for<'a> AddAssign<&'a Self> + for<'a> SubAssign<&'a Self> { - type ScalarField: PrimeField + Into<::BigInteger>; + type ScalarField: PrimeField + SquareRootField + Into<::BigInteger>; /// Returns `self + self`. #[must_use] fn double(&self) -> Self; /// Sets `self := self + self`. - fn double_in_place(&mut self) -> &mut Self; - - #[must_use] - fn mul(&self, other: &Self::ScalarField) -> Self { - let mut copy = *self; - copy.mul_assign(other); - copy - } - - fn mul_assign(&mut self, other: &Self::ScalarField) { - let mut res = Self::zero(); - for i in BitIteratorBE::new(other.into_repr()) { - res.double_in_place(); - if i { - res += self; - } - } - *self = res - } + fn double_in_place(&mut self); } diff --git a/curves/src/traits/pairing_engine.rs b/curves/src/traits/pairing_engine.rs index f91ab56244..0d68c5c1e8 100644 --- a/curves/src/traits/pairing_engine.rs +++ b/curves/src/traits/pairing_engine.rs @@ -21,13 +21,14 @@ use snarkvm_utilities::{ bytes::{FromBytes, ToBytes}, rand::UniformRand, serialize::*, + BitIteratorBE, }; use std::{ fmt::{Debug, Display}, hash::Hash, iter, - ops::{Add, AddAssign, Neg, Sub, SubAssign}, + ops::Neg, }; use snarkvm_fields::Zero; @@ -110,7 +111,8 @@ pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send { /// Projective representation of an elliptic curve point guaranteed to be /// in the correct prime order subgroup. pub trait ProjectiveCurve: - Eq + Group + + Eq + Sized + ToBytes + FromBytes @@ -129,13 +131,8 @@ pub trait ProjectiveCurve: + Zero + 'static + Neg - + for<'a> Add<&'a Self, Output = Self> - + for<'a> Sub<&'a Self, Output = Self> - + for<'a> AddAssign<&'a Self> - + for<'a> SubAssign<&'a Self> + From<::Affine> { - type ScalarField: PrimeField + SquareRootField + Into<::BigInteger>; type BaseField: Field; type Affine: AffineCurve + From + Into; @@ -159,22 +156,9 @@ pub trait ProjectiveCurve: #[must_use] fn is_normalized(&self) -> bool; - /// Doubles this element. - #[must_use] - fn double(&self) -> Self { - let mut copy = *self; - copy.double_in_place(); - copy - } - - fn double_in_place(&mut self) -> &mut Self; - /// Adds an affine element to this element. fn add_assign_mixed(&mut self, other: &Self::Affine); - /// Performs scalar multiplication of this element. - fn mul_assign::BigInteger>>(&mut self, other: S); - /// Converts this element into its affine representation. #[must_use] #[allow(clippy::wrong_self_convention)] @@ -196,7 +180,8 @@ pub trait ProjectiveCurve: /// in the correct prime order subgroup. #[allow(clippy::wrong_self_convention)] pub trait AffineCurve: - Eq + Group + + Eq + Sized + ToBytes + FromBytes @@ -216,7 +201,6 @@ pub trait AffineCurve: + 'static + From<::Projective> { - type ScalarField: PrimeField + SquareRootField + Into<::BigInteger>; type BaseField: Field; type Projective: ProjectiveCurve + From + Into; @@ -238,13 +222,6 @@ pub trait AffineCurve: /// largest y-coordinate be selected. fn from_y_coordinate(y: Self::BaseField, greatest: bool) -> Option; - /// Performs the standard addition operation of this element with a given other element. - fn add(self, other: &Self) -> Self; - - /// Performs scalar multiplication of this element with mixed addition. - #[must_use] - fn mul::BigInteger>>(&self, other: S) -> Self::Projective; - /// Multiply this element by the cofactor and output the /// resulting projective element. #[must_use] @@ -259,6 +236,9 @@ pub trait AffineCurve: /// random group elements from a hash-function or RNG output. fn from_random_bytes(bytes: &[u8]) -> Option; + /// Multiply this element by a scalar field element in BigInteger form. + fn mul_bits>(&self, bits: BitIteratorBE) -> Self::Projective; + /// Multiply this element by the cofactor. #[must_use] fn mul_by_cofactor(&self) -> Self { @@ -301,23 +281,6 @@ pub trait PairingCurve: AffineCurve { fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult; } -impl Group for C { - type ScalarField = C::ScalarField; - - #[inline] - #[must_use] - fn double(&self) -> Self { - let mut tmp = *self; - tmp += self; - tmp - } - - #[inline] - fn double_in_place(&mut self) -> &mut Self { - ::double_in_place(self) - } -} - pub trait ModelParameters: Send + Sync + 'static { type BaseField: Field + SquareRootField; type ScalarField: PrimeField + SquareRootField + Into<::BigInteger>; diff --git a/curves/src/traits/tests_curve.rs b/curves/src/traits/tests_curve.rs index 7271dfcc71..fbef8112e7 100644 --- a/curves/src/traits/tests_curve.rs +++ b/curves/src/traits/tests_curve.rs @@ -15,11 +15,12 @@ // along with the snarkVM library. If not, see . use crate::traits::{AffineCurve, ProjectiveCurve}; -use snarkvm_fields::{PrimeField, Zero}; +use snarkvm_fields::Zero; use snarkvm_utilities::rand::UniformRand; use rand::SeedableRng; use rand_xorshift::XorShiftRng; +use std::ops::{AddAssign, Mul}; pub const ITERATIONS: usize = 5; @@ -37,7 +38,7 @@ fn random_addition_test() { // a + a should equal the doubling { let mut aplusa = a; - aplusa.add_assign(&a); + aplusa.add_assign(a); let mut aplusamixed = a; aplusamixed.add_assign_mixed(&a.into_affine()); @@ -111,22 +112,22 @@ fn random_multiplication_test() { // s ( a + b ) let mut tmp1 = a; - tmp1.add_assign(&b); - tmp1.mul_assign(s.into_repr()); + tmp1.add_assign(b); + tmp1.mul_assign(s); // sa + sb - a.mul_assign(s.into_repr()); - b.mul_assign(s.into_repr()); + a.mul_assign(s); + b.mul_assign(s); let mut tmp2 = a; - tmp2.add_assign(&b); + tmp2.add_assign(b); // Affine multiplication - let mut tmp3 = a_affine.mul(s.into_repr()); - tmp3.add_assign(&b_affine.mul(s.into_repr())); + let mut tmp3 = a_affine.mul(s); + tmp3.add_assign(b_affine.mul(s)); assert_eq!(tmp1, tmp2); - assert_eq!(tmp1, tmp3); + assert_eq!(tmp1, tmp3.into()); } } @@ -139,7 +140,7 @@ fn random_doubling_test() { // 2(a + b) let mut tmp1 = a; - tmp1.add_assign(&b); + tmp1.add_assign(b); tmp1.double_in_place(); // 2a + 2b @@ -147,7 +148,7 @@ fn random_doubling_test() { b.double_in_place(); let mut tmp2 = a; - tmp2.add_assign(&b); + tmp2.add_assign(b); let mut tmp3 = a; tmp3.add_assign_mixed(&b.into_affine()); @@ -174,7 +175,7 @@ fn random_negation_test() { t2.mul_assign(sneg); let mut t3 = t1; - t3.add_assign(&t2); + t3.add_assign(t2); println!("t3 = {}", t3); assert!(t3.is_zero()); @@ -247,19 +248,19 @@ pub fn curve_tests() { { let mut r = G::rand(&mut rng); let rcopy = r; - r.add_assign(&G::zero()); + r.add_assign(G::zero()); assert_eq!(r, rcopy); r.add_assign_mixed(&G::Affine::zero()); assert_eq!(r, rcopy); let mut z = G::zero(); - z.add_assign(&G::zero()); + z.add_assign(G::zero()); assert!(z.is_zero()); z.add_assign_mixed(&G::Affine::zero()); assert!(z.is_zero()); let mut z2 = z; - z2.add_assign(&r); + z2.add_assign(r); z.add_assign_mixed(&r.into_affine()); diff --git a/curves/src/traits/tests_group.rs b/curves/src/traits/tests_group.rs index 426fbbdf91..7f2d394eea 100644 --- a/curves/src/traits/tests_group.rs +++ b/curves/src/traits/tests_group.rs @@ -30,12 +30,12 @@ pub fn group_test(a: G, mut b: G) { let fr_two = fr_one + &fr_one; assert!(zero == zero); assert_eq!(zero.is_zero(), true); - assert_eq!(a.mul(&fr_one), a); - assert_eq!(a.mul(&fr_two), a + &a); - assert_eq!(a.mul(&fr_zero), zero); - assert_eq!(a.mul(&fr_zero) - &a, -a); - assert_eq!(a.mul(&fr_one) - &a, zero); - assert_eq!(a.mul(&fr_two) - &a, a); + assert_eq!(a.mul(fr_one), a); + assert_eq!(a.mul(fr_two), a + &a); + assert_eq!(a.mul(fr_zero), zero); + assert_eq!(a.mul(fr_zero) - &a, -a); + assert_eq!(a.mul(fr_one) - &a, zero); + assert_eq!(a.mul(fr_two) - &a, a); // a == a assert!(a == a); @@ -67,27 +67,27 @@ pub fn group_test(a: G, mut b: G) { let fr_rand1 = G::ScalarField::rand(&mut rng); let fr_rand2 = G::ScalarField::rand(&mut rng); - let a_rand1 = a.mul(&fr_rand1); - let a_rand2 = a.mul(&fr_rand2); + let a_rand1 = a.mul(fr_rand1); + let a_rand2 = a.mul(fr_rand2); let fr_three = fr_two + &fr_rand1; - let a_two = a.mul(&fr_two); + let a_two = a.mul(fr_two); assert_eq!(a_two, a.double(), "(a * 2) != a.double()"); - let a_six = a.mul(&(fr_three * &fr_two)); - assert_eq!(a_two.mul(&fr_three), a_six, "(a * 2) * 3 != a * (2 * 3)"); + let a_six = a.mul(fr_three * &fr_two); + assert_eq!(a_two.mul(fr_three), a_six, "(a * 2) * 3 != a * (2 * 3)"); assert_eq!( - a_rand1.mul(&fr_rand2), - a_rand2.mul(&fr_rand1), + a_rand1.mul(fr_rand2), + a_rand2.mul(fr_rand1), "(a * r1) * r2 != (a * r2) * r1" ); assert_eq!( - a_rand2.mul(&fr_rand1), - a.mul(&(fr_rand1 * &fr_rand2)), + a_rand2.mul(fr_rand1), + a.mul(fr_rand1 * &fr_rand2), "(a * r2) * r1 != a * (r1 * r2)" ); assert_eq!( - a_rand1.mul(&fr_rand2), - a.mul(&(fr_rand1 * &fr_rand2)), + a_rand1.mul(fr_rand2), + a.mul(fr_rand1 * &fr_rand2), "(a * r1) * r2 != a * (r1 * r2)" ); } diff --git a/fields/src/fp12_2over3over2.rs b/fields/src/fp12_2over3over2.rs index ccf90099f3..bc6dff4b18 100644 --- a/fields/src/fp12_2over3over2.rs +++ b/fields/src/fp12_2over3over2.rs @@ -114,13 +114,13 @@ impl Fp12

{ bb.mul_by_1(c4); let mut o = *c1; o.add_assign(c4); - self.c1.add_assign(&self.c0); + self.c1.add_assign(self.c0); self.c1.mul_by_01(c0, &o); self.c1.sub_assign(&aa); self.c1.sub_assign(&bb); self.c0 = bb; self.c0 = Self::mul_fp6_by_nonresidue(&self.c0); - self.c0.add_assign(&aa); + self.c0.add_assign(aa); } pub fn cyclotomic_square(&self) -> Self { @@ -283,10 +283,9 @@ impl Field for Fp12

{ Self::from_random_bytes_with_flags(bytes).map(|f| f.0) } - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { self.c0.double_in_place(); self.c1.double_in_place(); - self } fn frobenius_map(&mut self, power: usize) { @@ -308,14 +307,14 @@ impl Field for Fp12

{ let mut ab = self.c0; ab.mul_assign(&self.c1); let mut c0c1 = self.c0; - c0c1.add_assign(&self.c1); + c0c1.add_assign(self.c1); let mut c0 = self.c1; c0 = Self::mul_fp6_by_nonresidue(&c0); - c0.add_assign(&self.c0); + c0.add_assign(self.c0); c0.mul_assign(&c0c1); c0.sub_assign(&ab); self.c1 = ab; - self.c1.add_assign(&ab); + self.c1.add_assign(ab); ab = Self::mul_fp6_by_nonresidue(&ab); c0.sub_assign(&ab); self.c0 = c0; @@ -377,7 +376,7 @@ impl<'a, P: Fp12Parameters> Add<&'a Self> for Fp12

{ #[inline] fn add(self, other: &Self) -> Self { let mut result = self; - result.add_assign(&other); + result.add_assign(other); result } } @@ -418,8 +417,8 @@ impl<'a, P: Fp12Parameters> Div<&'a Self> for Fp12

{ impl<'a, P: Fp12Parameters> AddAssign<&'a Self> for Fp12

{ #[inline] fn add_assign(&mut self, other: &Self) { - self.c0.add_assign(&other.c0); - self.c1.add_assign(&other.c1); + self.c0.add_assign(other.c0); + self.c1.add_assign(other.c1); } } diff --git a/fields/src/fp2.rs b/fields/src/fp2.rs index b470a869ec..032fea79d4 100644 --- a/fields/src/fp2.rs +++ b/fields/src/fp2.rs @@ -83,7 +83,7 @@ impl Fp2

{ let t0 = self.c0.square(); let mut t1 = self.c1.square(); t1 = -P::mul_fp_by_nonresidue(&t1); - t1.add_assign(&t0); + t1.add_assign(t0); t1 } @@ -124,10 +124,9 @@ impl Field for Fp2

{ result } - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { self.c0.double_in_place(); self.c1.double_in_place(); - self } fn square(&self) -> Self { @@ -347,7 +346,7 @@ impl<'a, P: Fp2Parameters> Add<&'a Fp2

> for Fp2

{ #[inline] fn add(self, other: &Self) -> Self { let mut result = self; - result.add_assign(&other); + result.add_assign(other); result } } @@ -388,8 +387,8 @@ impl<'a, P: Fp2Parameters> Div<&'a Fp2

> for Fp2

{ impl<'a, P: Fp2Parameters> AddAssign<&'a Self> for Fp2

{ #[inline] fn add_assign(&mut self, other: &Self) { - self.c0.add_assign(&other.c0); - self.c1.add_assign(&other.c1); + self.c0.add_assign(other.c0); + self.c1.add_assign(other.c1); } } diff --git a/fields/src/fp3.rs b/fields/src/fp3.rs index bb93cc7c84..cd5916c29a 100644 --- a/fields/src/fp3.rs +++ b/fields/src/fp3.rs @@ -153,11 +153,10 @@ impl Field for Fp3

{ result } - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { self.c0.double_in_place(); self.c1.double_in_place(); self.c2.double_in_place(); - self } #[inline] @@ -239,11 +238,11 @@ impl Field for Fp3

{ let mut a2 = self.c1; a2.mul_assign(&s2); let mut a3 = a1; - a3.add_assign(&a2); + a3.add_assign(a2); a3 = P::mul_fp_by_nonresidue(&a3); let mut t6 = self.c0; t6.mul_assign(&s0); - t6.add_assign(&a3); + t6.add_assign(a3); t6.inverse_in_place(); let mut c0 = t6; @@ -397,7 +396,7 @@ impl<'a, P: Fp3Parameters> Add<&'a Fp3

> for Fp3

{ #[inline] fn add(self, other: &Self) -> Self { let mut result = self; - result.add_assign(&other); + result.add_assign(other); result } } @@ -438,9 +437,9 @@ impl<'a, P: Fp3Parameters> Div<&'a Fp3

> for Fp3

{ impl<'a, P: Fp3Parameters> AddAssign<&'a Self> for Fp3

{ #[inline] fn add_assign(&mut self, other: &Self) { - self.c0.add_assign(&other.c0); - self.c1.add_assign(&other.c1); - self.c2.add_assign(&other.c2); + self.c0.add_assign(other.c0); + self.c1.add_assign(other.c1); + self.c2.add_assign(other.c2); } } diff --git a/fields/src/fp6_2over3.rs b/fields/src/fp6_2over3.rs index a749b8c858..9b57380983 100644 --- a/fields/src/fp6_2over3.rs +++ b/fields/src/fp6_2over3.rs @@ -222,10 +222,9 @@ impl Field for Fp6

{ result } - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { self.c0.double_in_place(); self.c1.double_in_place(); - self } fn square(&self) -> Self { @@ -401,7 +400,7 @@ impl<'a, P: Fp6Parameters> Add<&'a Fp6

> for Fp6

{ #[inline] fn add(self, other: &Self) -> Self { let mut result = self; - result.add_assign(&other); + result.add_assign(other); result } } @@ -442,8 +441,8 @@ impl<'a, P: Fp6Parameters> Div<&'a Fp6

> for Fp6

{ impl<'a, P: Fp6Parameters> AddAssign<&'a Self> for Fp6

{ #[inline] fn add_assign(&mut self, other: &Self) { - self.c0.add_assign(&other.c0); - self.c1.add_assign(&other.c1); + self.c0.add_assign(other.c0); + self.c1.add_assign(other.c1); } } diff --git a/fields/src/fp6_3over2.rs b/fields/src/fp6_3over2.rs index 12f38fc1d1..3f4f9abb8c 100644 --- a/fields/src/fp6_3over2.rs +++ b/fields/src/fp6_3over2.rs @@ -99,7 +99,7 @@ impl Fp6

{ let mut t1 = *c1; { let mut tmp = self.c1; - tmp.add_assign(&self.c2); + tmp.add_assign(self.c2); t1.mul_assign(&tmp); t1.sub_assign(&b_b); @@ -109,7 +109,7 @@ impl Fp6

{ let mut t2 = *c1; { let mut tmp = self.c0; - tmp.add_assign(&self.c1); + tmp.add_assign(self.c1); t2.mul_assign(&tmp); t2.sub_assign(&b_b); @@ -129,29 +129,29 @@ impl Fp6

{ let mut t1 = *c1; { let mut tmp = self.c1; - tmp.add_assign(&self.c2); + tmp.add_assign(self.c2); t1.mul_assign(&tmp); t1.sub_assign(&b_b); t1 = P::mul_fp2_by_nonresidue(&t1); - t1.add_assign(&a_a); + t1.add_assign(a_a); } let mut t3 = *c0; { let mut tmp = self.c0; - tmp.add_assign(&self.c2); + tmp.add_assign(self.c2); t3.mul_assign(&tmp); t3.sub_assign(&a_a); - t3.add_assign(&b_b); + t3.add_assign(b_b); } let mut t2 = *c0; t2.add_assign(c1); { let mut tmp = self.c0; - tmp.add_assign(&self.c1); + tmp.add_assign(self.c1); t2.mul_assign(&tmp); t2.sub_assign(&a_a); @@ -196,11 +196,10 @@ impl Field for Fp6

{ result } - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { self.c0.double_in_place(); self.c1.double_in_place(); self.c2.double_in_place(); - self } #[inline] @@ -255,7 +254,7 @@ impl Field for Fp6

{ { let mut c0s = self.c0; c0s.square_in_place(); - c0.add_assign(&c0s); + c0.add_assign(c0s); } let mut c1 = self.c2; c1.square_in_place(); @@ -277,11 +276,11 @@ impl Field for Fp6

{ tmp1.mul_assign(&c1); let mut tmp2 = self.c1; tmp2.mul_assign(&c2); - tmp1.add_assign(&tmp2); + tmp1.add_assign(tmp2); tmp1 = P::mul_fp2_by_nonresidue(&tmp1); tmp2 = self.c0; tmp2.mul_assign(&c0); - tmp1.add_assign(&tmp2); + tmp1.add_assign(tmp2); match tmp1.inverse() { Some(t) => Some(Self::new(t * &c0, t * &c1, t * &c2)), @@ -345,7 +344,7 @@ impl<'a, P: Fp6Parameters> Add<&'a Self> for Fp6

{ #[inline] fn add(self, other: &Self) -> Self { let mut result = self; - result.add_assign(&other); + result.add_assign(other); result } } diff --git a/fields/src/fp_256.rs b/fields/src/fp_256.rs index d6dbad5af5..bea140568d 100644 --- a/fields/src/fp_256.rs +++ b/fields/src/fp_256.rs @@ -170,12 +170,11 @@ impl Field for Fp256

{ } #[inline] - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); - self } #[inline] diff --git a/fields/src/fp_320.rs b/fields/src/fp_320.rs index f4b8a3a1d2..8ee8a29930 100644 --- a/fields/src/fp_320.rs +++ b/fields/src/fp_320.rs @@ -186,12 +186,11 @@ impl Field for Fp320

{ } #[inline] - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); - self } #[inline] diff --git a/fields/src/fp_384.rs b/fields/src/fp_384.rs index 22de464eae..bb2b2f870b 100644 --- a/fields/src/fp_384.rs +++ b/fields/src/fp_384.rs @@ -204,12 +204,11 @@ impl Field for Fp384

{ } #[inline] - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); - self } #[inline] diff --git a/fields/src/fp_768.rs b/fields/src/fp_768.rs index 5e7fd970b4..27fbd51b25 100644 --- a/fields/src/fp_768.rs +++ b/fields/src/fp_768.rs @@ -349,12 +349,11 @@ impl Field for Fp768

{ } #[inline] - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); - self } #[inline] diff --git a/fields/src/fp_832.rs b/fields/src/fp_832.rs index ab8e478bad..858d9ef917 100644 --- a/fields/src/fp_832.rs +++ b/fields/src/fp_832.rs @@ -381,12 +381,11 @@ impl Field for Fp832

{ } #[inline] - fn double_in_place(&mut self) -> &mut Self { + fn double_in_place(&mut self) { // This cannot exceed the backing capacity. self.0.mul2(); // However, it may need to be reduced. self.reduce(); - self } #[inline] diff --git a/fields/src/traits/field.rs b/fields/src/traits/field.rs index 6e9847fa7a..73d5826b61 100644 --- a/fields/src/traits/field.rs +++ b/fields/src/traits/field.rs @@ -97,7 +97,7 @@ pub trait Field: fn double(&self) -> Self; /// Doubles `self` in place. - fn double_in_place(&mut self) -> &mut Self; + fn double_in_place(&mut self); /// Returns `self * self`. #[must_use] diff --git a/gadgets/src/curves/bls12_377.rs b/gadgets/src/curves/bls12_377.rs index 2d2983e3ec..7abd4b68c3 100644 --- a/gadgets/src/curves/bls12_377.rs +++ b/gadgets/src/curves/bls12_377.rs @@ -14,8 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use snarkvm_curves::bls12_377::{Bls12_377Parameters, Fq, Fq12Parameters, Fq2Parameters, Fq6Parameters}; - use crate::{ curves::templates::bls12::{ Bls12PairingGadget, @@ -26,6 +24,7 @@ use crate::{ }, fields::{Fp12Gadget, Fp2Gadget, Fp6Gadget, FpGadget}, }; +use snarkvm_curves::bls12_377::{Bls12_377Parameters, Fq, Fq12Parameters, Fq2Parameters, Fq6Parameters}; pub type FqGadget = FpGadget; pub type Fq2Gadget = Fp2Gadget; @@ -39,20 +38,7 @@ pub type PairingGadget = Bls12PairingGadget; #[cfg(test)] mod test { - use rand::{ - SeedableRng, - {self}, - }; - use rand_xorshift::XorShiftRng; - - use snarkvm_curves::{ - bls12_377::{Fq, Fr, G1Projective as G1, G2Projective as G2}, - traits::{AffineCurve, ProjectiveCurve}, - }; - use snarkvm_fields::PrimeField; - use snarkvm_r1cs::{ConstraintSystem, TestConstraintSystem}; - use snarkvm_utilities::{bititerator::BitIteratorBE, rand::UniformRand}; - + use super::*; use crate::{ bits::boolean::{AllocatedBit, Boolean}, traits::{ @@ -63,8 +49,21 @@ mod test { select::CondSelectGadget, }, }; + use snarkvm_curves::{ + bls12_377::{Fq, Fr, G1Projective as G1, G2Projective as G2}, + traits::ProjectiveCurve, + Group, + }; + use snarkvm_fields::PrimeField; + use snarkvm_r1cs::{ConstraintSystem, TestConstraintSystem}; + use snarkvm_utilities::{bititerator::BitIteratorBE, rand::UniformRand}; - use super::*; + use core::ops::Mul; + use rand::{ + SeedableRng, + {self}, + }; + use rand_xorshift::XorShiftRng; #[test] fn bls12_g1_constraint_costs() { @@ -154,7 +153,7 @@ mod test { // Check mul_bits let scalar = Fr::rand(&mut rng); - let native_result = aa.into_affine().mul(scalar) + &b; + let native_result = aa.mul(scalar) + &b; let native_result = native_result.into_affine(); let mut scalar: Vec = BitIteratorBE::new(scalar.into_repr()).collect(); diff --git a/gadgets/src/curves/templates/twisted_edwards/mod.rs b/gadgets/src/curves/templates/twisted_edwards/mod.rs index 487ef29bae..28ecd77383 100644 --- a/gadgets/src/curves/templates/twisted_edwards/mod.rs +++ b/gadgets/src/curves/templates/twisted_edwards/mod.rs @@ -120,7 +120,7 @@ mod montgomery_affine_impl { let mut t0 = self.x.get_value().get()?; let mut t1 = t0; t0.sub_assign(&P::BaseField::one()); - t1.add_assign(&P::BaseField::one()); + t1.add_assign(P::BaseField::one()); match t1.inverse() { Some(t1) => { diff --git a/gadgets/src/curves/templates/twisted_edwards/test.rs b/gadgets/src/curves/templates/twisted_edwards/test.rs index d356feac02..0b203a0f4e 100644 --- a/gadgets/src/curves/templates/twisted_edwards/test.rs +++ b/gadgets/src/curves/templates/twisted_edwards/test.rs @@ -14,8 +14,11 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use rand::thread_rng; - +use crate::{ + bits::boolean::{AllocatedBit, Boolean}, + curves::tests_group::group_test, + traits::{alloc::AllocGadget, curves::GroupGadget, select::CondSelectGadget}, +}; use snarkvm_curves::{ templates::twisted_edwards_extended::GroupAffine as TEAffine, traits::{Group, TEModelParameters}, @@ -24,11 +27,8 @@ use snarkvm_fields::{Field, PrimeField}; use snarkvm_r1cs::ConstraintSystem; use snarkvm_utilities::{bititerator::BitIteratorBE, rand::UniformRand}; -use crate::{ - bits::boolean::{AllocatedBit, Boolean}, - curves::tests_group::group_test, - traits::{alloc::AllocGadget, curves::GroupGadget, select::CondSelectGadget}, -}; +use core::ops::Mul; +use rand::thread_rng; pub(crate) fn edwards_test(cs: &mut CS) where @@ -47,7 +47,7 @@ where // Check mul_bits let scalar: as Group>::ScalarField = UniformRand::rand(&mut thread_rng()); - let native_result = a.mul(&scalar); + let native_result = a.mul(scalar); let mut scalar: Vec = BitIteratorBE::new(scalar.into_repr()).collect(); // Get the scalar bits into little-endian form. diff --git a/gadgets/src/curves/tests_curve.rs b/gadgets/src/curves/tests_curve.rs index c539b0da35..04237c13e5 100644 --- a/gadgets/src/curves/tests_curve.rs +++ b/gadgets/src/curves/tests_curve.rs @@ -45,8 +45,8 @@ fn bls12_377_gadget_bilinearity_test() { let b: G2Projective = G2Projective::prime_subgroup_generator(); let s: Fr = Fr::one() + &Fr::one(); - let sa = a.mul(&s); - let sb = b.mul(&s); + let sa = a.mul(s); + let sb = b.mul(s); let a_g = G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap(); let b_g = G2Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap(); diff --git a/gadgets/src/fields/fp.rs b/gadgets/src/fields/fp.rs index 0a64a4f606..c7b44be22f 100644 --- a/gadgets/src/fields/fp.rs +++ b/gadgets/src/fields/fp.rs @@ -152,7 +152,10 @@ impl AllocatedFp { } fn double_in_place>(&mut self, _cs: CS) -> &mut Self { - self.value.as_mut().map(|val| val.double_in_place()); + self.value.as_mut().map(|val| { + val.double_in_place(); + val + }); self.variable.double_in_place(); self } diff --git a/marlin/src/fiat_shamir/fiat_shamir_poseidon_sponge.rs b/marlin/src/fiat_shamir/fiat_shamir_poseidon_sponge.rs index 8cec6e0646..49d0c51e40 100644 --- a/marlin/src/fiat_shamir/fiat_shamir_poseidon_sponge.rs +++ b/marlin/src/fiat_shamir/fiat_shamir_poseidon_sponge.rs @@ -73,7 +73,7 @@ impl PoseidonSponge { fn apply_ark(&self, state: &mut [F], round_number: usize) { for (i, state_elem) in state.iter_mut().enumerate() { - state_elem.add_assign(&self.ark[round_number][i]); + state_elem.add_assign(self.ark[round_number][i]); } } @@ -83,7 +83,7 @@ impl PoseidonSponge { let mut cur = F::zero(); for (j, state_elem) in state.iter().enumerate() { let term = state_elem.mul(&self.mds[i][j]); - cur.add_assign(&term); + cur.add_assign(term); } new_state.push(cur); } diff --git a/polycommit/src/kzg10/data_structures.rs b/polycommit/src/kzg10/data_structures.rs index 324c9cd9b3..b1e91cc4d2 100644 --- a/polycommit/src/kzg10/data_structures.rs +++ b/polycommit/src/kzg10/data_structures.rs @@ -16,7 +16,10 @@ use crate::{impl_bytes, BTreeMap, *}; use core::ops::{Add, AddAssign}; -use snarkvm_curves::traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::{ + traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve}, + Group, +}; use snarkvm_fields::{ConstraintFieldError, PrimeField, ToConstraintField, Zero}; use snarkvm_utilities::{ bytes::ToBytes, @@ -25,6 +28,8 @@ use snarkvm_utilities::{ serialize::{CanonicalDeserialize, CanonicalSerialize}, }; +use core::ops::Mul; + /// `UniversalParams` are the universal parameters for the KZG10 scheme. #[derive(Derivative)] #[derivative(Default(bound = ""), Clone(bound = ""), Debug(bound = ""))] @@ -183,7 +188,7 @@ impl PCCommitment for Commitment { impl<'a, E: PairingEngine> AddAssign<(E::Fr, &'a Commitment)> for Commitment { #[inline] fn add_assign(&mut self, (f, other): (E::Fr, &'a Commitment)) { - let mut other = other.0.mul(f.into_repr()); + let mut other = other.0.mul(f).into_projective(); other.add_assign_mixed(&self.0); self.0 = other.into(); } diff --git a/polycommit/src/kzg10/mod.rs b/polycommit/src/kzg10/mod.rs index 5dcdd9d53c..d6a6a25687 100644 --- a/polycommit/src/kzg10/mod.rs +++ b/polycommit/src/kzg10/mod.rs @@ -26,11 +26,11 @@ use snarkvm_algorithms::{ cfg_iter, msm::{FixedBaseMSM, VariableBaseMSM}, }; -use snarkvm_curves::traits::{AffineCurve, Group, PairingCurve, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve}; use snarkvm_fields::{One, PrimeField, Zero}; use snarkvm_utilities::rand::UniformRand; -use core::marker::PhantomData; +use core::{marker::PhantomData, ops::Mul}; use rand_core::RngCore; #[cfg(feature = "parallel")] @@ -89,7 +89,7 @@ impl KZG10 { ); // Add an additional power of gamma_g, because we want to be able to support // up to D queries. - powers_of_gamma_g.push(powers_of_gamma_g.last().unwrap().mul(&beta)); + powers_of_gamma_g.push(powers_of_gamma_g.last().unwrap().mul(beta)); end_timer!(gamma_g_time); let powers_of_g = E::G1Projective::batch_normalization_into_affine(powers_of_g); @@ -131,7 +131,7 @@ impl KZG10 { end_timer!(prepared_neg_powers_of_h_time); - let beta_h = h.mul(&beta).into_affine(); + let beta_h = h.mul(beta).into_affine(); let h = h.into_affine(); let prepared_h = h.prepare(); let prepared_beta_h = beta_h.prepare(); @@ -290,13 +290,13 @@ impl KZG10 { proof: &Proof, ) -> Result { let check_time = start_timer!(|| "Checking evaluation"); - let mut inner = commitment.0.into_projective() - &vk.g.into_projective().mul(&value); + let mut inner = commitment.0.into_projective() - &vk.g.into_projective().mul(value); if let Some(random_v) = proof.random_v { - inner -= &vk.gamma_g.mul(random_v); + inner -= &vk.gamma_g.mul(random_v).into(); } let lhs = E::pairing(inner, vk.h); - let inner = vk.beta_h.into_projective() - &vk.h.mul(point); + let inner = vk.beta_h.into_projective() - &vk.h.mul(point).into(); let rhs = E::pairing(proof.w, inner); end_timer!(check_time, || format!("Result: {}", lhs == rhs)); @@ -328,21 +328,21 @@ impl KZG10 { let mut gamma_g_multiplier = E::Fr::zero(); for (((c, z), v), proof) in commitments.iter().zip(points).zip(values).zip(proofs) { let w = proof.w; - let mut temp = w.mul(*z); + let mut temp = w.mul(*z).into_projective(); temp.add_assign_mixed(&c.0); let c = temp; g_multiplier += &(randomizer * v); if let Some(random_v) = proof.random_v { gamma_g_multiplier += &(randomizer * &random_v); } - total_c += &c.mul(&randomizer); - total_w += &w.mul(randomizer.into_repr()); + total_c += &c.mul(randomizer).into(); + total_w += &w.mul(randomizer).into(); // We don't need to sample randomizers from the full field, // only from 128-bit strings. randomizer = u128::rand(rng).into(); } - total_c -= &g.mul(&g_multiplier); - total_c -= &gamma_g.mul(&gamma_g_multiplier); + total_c -= &g.mul(g_multiplier); + total_c -= &gamma_g.mul(gamma_g_multiplier); end_timer!(combination_time); let to_affine_time = start_timer!(|| "Converting results to affine for pairing"); diff --git a/polycommit/src/marlin_pc/data_structures.rs b/polycommit/src/marlin_pc/data_structures.rs index 3528f5c105..e455d5628f 100644 --- a/polycommit/src/marlin_pc/data_structures.rs +++ b/polycommit/src/marlin_pc/data_structures.rs @@ -24,7 +24,7 @@ use crate::{ PCVerifierKey, Vec, }; -use snarkvm_curves::{traits::PairingEngine, ProjectiveCurve}; +use snarkvm_curves::{traits::PairingEngine, Group}; use snarkvm_fields::{ConstraintFieldError, PrimeField, ToConstraintField}; use snarkvm_utilities::{ bytes::{FromBytes, ToBytes}, diff --git a/polycommit/src/marlin_pc/mod.rs b/polycommit/src/marlin_pc/mod.rs index 6044fddca3..c9e75560c0 100644 --- a/polycommit/src/marlin_pc/mod.rs +++ b/polycommit/src/marlin_pc/mod.rs @@ -36,9 +36,13 @@ use crate::{ Vec, }; use snarkvm_curves::traits::{AffineCurve, PairingEngine, ProjectiveCurve}; -use snarkvm_fields::{Field, One, PrimeField, Zero}; +use snarkvm_fields::{Field, One, Zero}; -use core::{convert::TryInto, marker::PhantomData}; +use core::{ + convert::TryInto, + marker::PhantomData, + ops::{Mul, MulAssign}, +}; use rand_core::RngCore; mod data_structures; @@ -979,11 +983,11 @@ impl MarlinKZG10 { if coeff.is_one() { combined_comm.add_assign_mixed(&comm.comm.0); } else { - combined_comm += &comm.comm.0.mul(coeff); + combined_comm += &comm.comm.0.mul(coeff).into(); } if let Some(shifted_comm) = &comm.shifted_comm { - let cur = shifted_comm.0.mul(coeff.into_repr()); + let cur = shifted_comm.0.mul(coeff).into_projective(); combined_shifted_comm = Some(combined_shifted_comm.map_or(cur, |c| c + &cur)); } } @@ -1098,7 +1102,7 @@ impl MarlinKZG10 { let commitment = labeled_commitment.commitment(); assert_eq!(degree_bound.is_some(), commitment.shifted_comm.is_some()); - combined_comm += &commitment.comm.0.mul(challenge_i); + combined_comm += &commitment.comm.0.mul(challenge_i).into(); combined_value += &(value * &challenge_i); if let Some(degree_bound) = degree_bound { @@ -1108,8 +1112,8 @@ impl MarlinKZG10 { let shift_power = vk .get_shift_power(degree_bound) .ok_or(Error::UnsupportedDegreeBound(degree_bound))?; - let mut adjusted_comm = shifted_comm - &shift_power.mul(value); - adjusted_comm.mul_assign(challenge_i_1.into_repr()); + let mut adjusted_comm = shifted_comm - &shift_power.mul(value).into(); + adjusted_comm.mul_assign(challenge_i_1); combined_comm += &adjusted_comm; } challenge_i *= &opening_challenge.square(); @@ -1138,7 +1142,7 @@ impl MarlinKZG10 { let challenge_i = opening_challenges(opening_challenge_counter); opening_challenge_counter += 1; - combined_comm += &commitment.comm.0.mul(challenge_i); + combined_comm += &commitment.comm.0.mul(challenge_i).into(); combined_value += &(value * &challenge_i); if let Some(degree_bound) = degree_bound { @@ -1151,9 +1155,9 @@ impl MarlinKZG10 { .get_shift_power(degree_bound) .ok_or(Error::UnsupportedDegreeBound(degree_bound))?; - let mut adjusted_comm = shifted_comm - &shift_power.mul(value); + let mut adjusted_comm = shifted_comm - &shift_power.mul(value).into(); - adjusted_comm.mul_assign(challenge_i_1.into_repr()); + adjusted_comm.mul_assign(challenge_i_1); combined_comm += &adjusted_comm; } } diff --git a/polycommit/src/sonic_pc/data_structures.rs b/polycommit/src/sonic_pc/data_structures.rs index 14992e76f6..4899f99559 100644 --- a/polycommit/src/sonic_pc/data_structures.rs +++ b/polycommit/src/sonic_pc/data_structures.rs @@ -24,7 +24,10 @@ use crate::{ PCVerifierKey, Vec, }; -use snarkvm_curves::traits::{PairingCurve, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::{ + traits::{PairingCurve, PairingEngine}, + Group, +}; use snarkvm_fields::{ConstraintFieldError, ToConstraintField}; use snarkvm_utilities::{ bytes::{FromBytes, ToBytes}, diff --git a/polycommit/src/sonic_pc/mod.rs b/polycommit/src/sonic_pc/mod.rs index 1bf67c67a4..09d9f7b76a 100644 --- a/polycommit/src/sonic_pc/mod.rs +++ b/polycommit/src/sonic_pc/mod.rs @@ -38,11 +38,11 @@ use crate::{ ToString, Vec, }; -use snarkvm_curves::traits::{AffineCurve, Group, PairingCurve, PairingEngine, ProjectiveCurve}; +use snarkvm_curves::traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve}; use snarkvm_fields::{One, Zero}; use snarkvm_utilities::rand::UniformRand; -use core::{convert::TryInto, iter::FromIterator, marker::PhantomData}; +use core::{convert::TryInto, iter::FromIterator, marker::PhantomData, ops::Mul}; use rand_core::RngCore; mod data_structures; @@ -436,7 +436,7 @@ impl PolynomialCommitment for SonicKZG10 { hiding_bound = core::cmp::max(hiding_bound, cur_poly.hiding_bound()); poly += (*coeff, cur_poly.polynomial()); randomness += (*coeff, cur_rand); - comm += &curr_comm.commitment().0.into_projective().mul(coeff); + comm += &curr_comm.commitment().0.into_projective().mul(*coeff); } let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); @@ -522,7 +522,7 @@ impl PolynomialCommitment for SonicKZG10 { } else if cur_comm.degree_bound().is_some() { return Err(Self::Error::EquationHasDegreeBounds(lc_label)); } - combined_comm += &cur_comm.commitment().0.mul(*coeff); + combined_comm += &cur_comm.commitment().0.mul(*coeff).into(); } } @@ -886,10 +886,10 @@ impl SonicKZG10 { let degree_bound = labeled_comm.degree_bound(); // Applying opening challenge and randomness (used in batch_checking) - let mut comm_with_challenge: E::G1Projective = comm.0.mul(curr_challenge); + let mut comm_with_challenge: E::G1Projective = comm.0.mul(curr_challenge).into(); if let Some(randomizer) = randomizer { - comm_with_challenge = comm_with_challenge.mul(&randomizer); + comm_with_challenge = comm_with_challenge.mul(randomizer); } // Accumulate values in the BTreeMap @@ -905,12 +905,12 @@ impl SonicKZG10 { } if let Some(randomizer) = randomizer { - witness = witness.mul(&randomizer); - adjusted_witness = adjusted_witness.mul(&randomizer); + witness = witness.mul(randomizer); + adjusted_witness = adjusted_witness.mul(randomizer); } *combined_witness += &witness; - *combined_adjusted_witness += &adjusted_witness; + *combined_adjusted_witness += &adjusted_witness.into(); end_timer!(acc_time); } @@ -943,10 +943,10 @@ impl SonicKZG10 { let degree_bound = labeled_comm.degree_bound(); // Applying opening challenge and randomness (used in batch_checking) - let mut comm_with_challenge: E::G1Projective = comm.0.mul(curr_challenge); + let mut comm_with_challenge: E::G1Projective = comm.0.mul(curr_challenge).into(); if let Some(randomizer) = randomizer { - comm_with_challenge = comm_with_challenge.mul(&randomizer); + comm_with_challenge = comm_with_challenge.mul(randomizer); } // Accumulate values in the BTreeMap @@ -963,12 +963,12 @@ impl SonicKZG10 { } if let Some(randomizer) = randomizer { - witness = proof.w.mul(randomizer); - adjusted_witness = adjusted_witness.mul(&randomizer); + witness = proof.w.into_projective().mul(randomizer); + adjusted_witness = adjusted_witness.mul(randomizer); } *combined_witness += &witness; - *combined_adjusted_witness += &adjusted_witness; + *combined_adjusted_witness += &adjusted_witness.into(); end_timer!(acc_time); } diff --git a/r1cs/src/test_constraint_system.rs b/r1cs/src/test_constraint_system.rs index af50b7f97d..77155d64cb 100644 --- a/r1cs/src/test_constraint_system.rs +++ b/r1cs/src/test_constraint_system.rs @@ -202,7 +202,7 @@ impl TestConstraintSystem { let coeff = self.interned_fields.get_index(interned_coeff).unwrap(); tmp.mul_assign(coeff); - acc.add_assign(&tmp); + acc.add_assign(tmp); } acc From ba17066d9199ab1631323a6e3e8adfec69ec9a66 Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 19:06:42 -0700 Subject: [PATCH 06/13] Clean up Projective and Affine traits --- curves/src/traits/pairing_engine.rs | 48 ++--------------------------- 1 file changed, 3 insertions(+), 45 deletions(-) diff --git a/curves/src/traits/pairing_engine.rs b/curves/src/traits/pairing_engine.rs index 0d68c5c1e8..0286efe627 100644 --- a/curves/src/traits/pairing_engine.rs +++ b/curves/src/traits/pairing_engine.rs @@ -16,22 +16,9 @@ use crate::traits::Group; use snarkvm_fields::{Field, PrimeField, SquareRootField}; -use snarkvm_utilities::{ - biginteger::BigInteger, - bytes::{FromBytes, ToBytes}, - rand::UniformRand, - serialize::*, - BitIteratorBE, -}; - -use std::{ - fmt::{Debug, Display}, - hash::Hash, - iter, - ops::Neg, -}; - -use snarkvm_fields::Zero; +use snarkvm_utilities::{biginteger::BigInteger, bytes::ToBytes, rand::UniformRand, serialize::*, BitIteratorBE}; + +use std::{fmt::Debug, iter}; pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send { /// This is the scalar field of the G1/G2 groups. @@ -112,25 +99,10 @@ pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send { /// in the correct prime order subgroup. pub trait ProjectiveCurve: Group - + Eq + Sized - + ToBytes - + FromBytes + CanonicalSerialize + ConstantSerializedSize + CanonicalDeserialize - + Copy - + Clone - + Default - + Send - + Sync - + Hash - + Debug - + Display - + UniformRand - + Zero - + 'static - + Neg + From<::Affine> { type BaseField: Field; @@ -181,24 +153,10 @@ pub trait ProjectiveCurve: #[allow(clippy::wrong_self_convention)] pub trait AffineCurve: Group - + Eq + Sized - + ToBytes - + FromBytes + CanonicalSerialize + ConstantSerializedSize + CanonicalDeserialize - + Copy - + Clone - + Default - + Send - + Sync - + Hash - + Debug - + Display - + Neg - + Zero - + 'static + From<::Projective> { type BaseField: Field; From 11f150b48cdbb20b60a61d28b42e82f3e7014dd6 Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 19:07:25 -0700 Subject: [PATCH 07/13] Update CI to Rust 1.53.0 --- .circleci/config.yml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ede98eb5f3..5265890593 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -44,7 +44,7 @@ jobs: rust-stable: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: 2xlarge steps: - checkout @@ -93,7 +93,7 @@ jobs: snarkvm-algorithms: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -108,7 +108,7 @@ jobs: snarkvm-curves: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -123,7 +123,7 @@ jobs: snarkvm-derives: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -138,7 +138,7 @@ jobs: snarkvm-dpc: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -153,7 +153,7 @@ jobs: snarkvm-fields: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -168,7 +168,7 @@ jobs: snarkvm-gadgets: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -183,7 +183,7 @@ jobs: snarkvm-marlin: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -198,7 +198,7 @@ jobs: snarkvm-parameters: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -213,7 +213,7 @@ jobs: snarkvm-polycommit: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -228,7 +228,7 @@ jobs: snarkvm-posw: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -243,7 +243,7 @@ jobs: snarkvm-profiler: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -258,7 +258,7 @@ jobs: snarkvm-r1cs: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout @@ -273,7 +273,7 @@ jobs: snarkvm-utilities: docker: - - image: cimg/rust:1.51.0 + - image: cimg/rust:1.53.0 resource_class: xlarge steps: - checkout From ea099009c80a7dff8d324ce8aa69f275fbabc07a Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 19:31:06 -0700 Subject: [PATCH 08/13] Clippy --- curves/src/edwards_bls12/tests.rs | 18 +++++++------- .../short_weierstrass_jacobian.rs | 2 +- .../short_weierstrass_projective.rs | 4 ++-- .../templates/twisted_edwards_extended/mod.rs | 6 ++--- curves/src/traits/pairing_engine.rs | 2 +- curves/src/traits/tests_curve.rs | 2 +- curves/src/traits/tests_group.rs | 4 ++-- fields/src/fp6_2over3.rs | 24 +++++++++---------- fields/src/tests_field.rs | 8 +++---- .../curves/templates/twisted_edwards/mod.rs | 10 ++++---- gadgets/src/fields/fp12.rs | 6 ++--- .../allocated_nonnative_field_var.rs | 4 ++-- marlin/src/ahp/ahp.rs | 4 ++-- marlin/src/ahp/prover/prover.rs | 10 ++++---- marlin/src/ahp/verifier/verifier.rs | 2 +- r1cs/src/linear_combination.rs | 8 +++---- snarkvm/updater.rs | 4 ++-- 17 files changed, 59 insertions(+), 59 deletions(-) diff --git a/curves/src/edwards_bls12/tests.rs b/curves/src/edwards_bls12/tests.rs index ac82a2d139..8dda4e682c 100644 --- a/curves/src/edwards_bls12/tests.rs +++ b/curves/src/edwards_bls12/tests.rs @@ -131,7 +131,7 @@ fn test_edwards_to_montgomery_point() { let v2 = v.square(); let u2 = u.square(); let u3 = u2 * &u; - assert_eq!(B * &v2, u3 + &(A * &u2) + &u); + assert_eq!(B * &v2, u3 + (A * &u2) + &u); } // Edwards element (x, y) @@ -157,8 +157,8 @@ fn print_montgomery_to_weierstrass_parameters() { let two = Fq::one() + &Fq::one(); let three = Fq::one() + &two; - let nine = three + &(three + &three); - let twenty_seven = nine + &(nine + &nine); + let nine = three + (three + &three); + let twenty_seven = nine + (nine + &nine); let a2 = A.square(); let a3 = A * &a2; @@ -243,7 +243,7 @@ fn test_isomorphism() { let v3 = v2 * &v; let av2 = a * &v2; let bv = b * &v; - let e = (v3 + &(av2 + &bv)).legendre(); + let e = (v3 + (av2 + &bv)).legendre(); // Let x = ev - ((1 - e) * A/2). let two = Fq::one().double(); @@ -258,7 +258,7 @@ fn test_isomorphism() { let x3 = x2 * &x; let ax2 = a * &x2; let bx = b * &x; - let value = (x3 + &(ax2 + &bx)).sqrt().unwrap(); + let value = (x3 + (ax2 + &bx)).sqrt().unwrap(); let y = match e { LegendreSymbol::Zero => Fq::zero(), LegendreSymbol::QuadraticResidue => -value, @@ -274,7 +274,7 @@ fn test_isomorphism() { let v2 = v.square(); let u2 = u.square(); let u3 = u2 * &u; - assert_eq!(v2, u3 + &(a * &u2) + &(b * &u)); + assert_eq!(v2, u3 + (a * &u2) + (b * &u)); } // Convert the alternate Montgomery element (u, v) to Montgomery element (s, t). @@ -288,7 +288,7 @@ fn test_isomorphism() { let t2 = t.square(); let s2 = s.square(); let s3 = s2 * &s; - assert_eq!(B * &t2, s3 + &(A * &s2) + &s); + assert_eq!(B * &t2, s3 + (A * &s2) + &s); } (s, t) @@ -323,7 +323,7 @@ fn test_isomorphism() { let v2 = v.square(); let u2 = u.square(); let u3 = u2 * &u; - assert_eq!(B * &v2, u3 + &(A * &u2) + &u); + assert_eq!(B * &v2, u3 + (A * &u2) + &u); } let u = u * &B.inverse().unwrap(); @@ -335,7 +335,7 @@ fn test_isomorphism() { let v2 = v.square(); let u2 = u.square(); let u3 = u2 * &u; - assert_eq!(v2, u3 + &(a * &u2) + &(b * &u)); + assert_eq!(v2, u3 + (a * &u2) + (b * &u)); } (u, v) diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs index 6beb6538c5..850e7953b6 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs @@ -801,7 +801,7 @@ impl Mul for GroupProjective

{ } if i { - res += self; + res += &self; } } diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs index 5daf1fd361..3d87da450c 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs @@ -549,7 +549,7 @@ impl Group for GroupProjective

{ // ZZ = Z1^2 let zz = self.z.square(); // w = a*ZZ + 3*XX - let w = P::mul_by_a(&zz) + &(xx + &xx.double()); + let w = P::mul_by_a(&zz) + (xx + &xx.double()); // s = 2*Y1*Z1 let mut s = self.y * &(self.z); s.double_in_place(); @@ -678,7 +678,7 @@ impl Mul for GroupProjective

{ } if i { - res += self; + res += &self; } } diff --git a/curves/src/templates/twisted_edwards_extended/mod.rs b/curves/src/templates/twisted_edwards_extended/mod.rs index 019a8bf2e8..9cfdcfc2ab 100644 --- a/curves/src/templates/twisted_edwards_extended/mod.rs +++ b/curves/src/templates/twisted_edwards_extended/mod.rs @@ -88,7 +88,7 @@ impl GroupAffine

{ let y2 = self.y.square(); let lhs = y2 + &P::mul_by_a(&x2); - let rhs = P::BaseField::one() + &(P::COEFF_D * &(x2 * &y2)); + let rhs = P::BaseField::one() + (P::COEFF_D * &(x2 * &y2)); lhs == rhs } @@ -207,7 +207,7 @@ impl AffineCurve for GroupAffine

{ let y2 = self.y.square(); let lhs = y2 + &P::mul_by_a(&x2); - let rhs = P::BaseField::one() + &(P::COEFF_D * &(x2 * &y2)); + let rhs = P::BaseField::one() + (P::COEFF_D * &(x2 * &y2)); lhs == rhs } @@ -669,7 +669,7 @@ impl Mul for GroupProjective

{ } if i { - res += self; + res += &self; } } diff --git a/curves/src/traits/pairing_engine.rs b/curves/src/traits/pairing_engine.rs index 0286efe627..8dc946bb19 100644 --- a/curves/src/traits/pairing_engine.rs +++ b/curves/src/traits/pairing_engine.rs @@ -16,7 +16,7 @@ use crate::traits::Group; use snarkvm_fields::{Field, PrimeField, SquareRootField}; -use snarkvm_utilities::{biginteger::BigInteger, bytes::ToBytes, rand::UniformRand, serialize::*, BitIteratorBE}; +use snarkvm_utilities::{biginteger::BigInteger, bytes::ToBytes, serialize::*, BitIteratorBE}; use std::{fmt::Debug, iter}; diff --git a/curves/src/traits/tests_curve.rs b/curves/src/traits/tests_curve.rs index fbef8112e7..b1ab163258 100644 --- a/curves/src/traits/tests_curve.rs +++ b/curves/src/traits/tests_curve.rs @@ -56,7 +56,7 @@ fn random_addition_test() { tmp[0] = (a + &b) + &c; // a + (b + c) - tmp[1] = a + &(b + &c); + tmp[1] = a + (b + &c); // (a + c) + b tmp[2] = (a + &c) + &b; diff --git a/curves/src/traits/tests_group.rs b/curves/src/traits/tests_group.rs index 7f2d394eea..3fbde63a4c 100644 --- a/curves/src/traits/tests_group.rs +++ b/curves/src/traits/tests_group.rs @@ -56,9 +56,9 @@ pub fn group_test(a: G, mut b: G) { // a - b = -(b - a) assert_eq!(a - &b, -(b - &a)); // (a + b) + a = a + (b + a) - assert_eq!((a + &b) + &a, a + &(b + &a)); + assert_eq!((a + &b) + &a, a + (b + &a)); // (a + b).double() = (a + b) + (b + a) - assert_eq!((a + &b).double(), (a + &b) + &(b + &a)); + assert_eq!((a + &b).double(), (a + &b) + (b + &a)); // Check that double_in_place and double give the same result let original_b = b; diff --git a/fields/src/fp6_2over3.rs b/fields/src/fp6_2over3.rs index 9b57380983..44e00355e7 100644 --- a/fields/src/fp6_2over3.rs +++ b/fields/src/fp6_2over3.rs @@ -103,12 +103,12 @@ impl Fp6

{ let mut tmp2 = x4; tmp2.mul_assign(&::NONRESIDUE); - self.c0.c0 = x0 * &z0 + &(tmp1 * &z5) + &(tmp2 * &z4); - self.c0.c1 = x0 * &z1 + &(x3 * &z3) + &(tmp2 * &z5); - self.c0.c2 = x0 * &z2 + &(x3 * &z4) + &(x4 * &z3); - self.c1.c0 = x0 * &z3 + &(x3 * &z0) + &(tmp2 * &z2); - self.c1.c1 = x0 * &z4 + &(x3 * &z1) + &(x4 * &z0); - self.c1.c2 = x0 * &z5 + &(x3 * &z2) + &(x4 * &z1); + self.c0.c0 = x0 * &z0 + (tmp1 * &z5) + (tmp2 * &z4); + self.c0.c1 = x0 * &z1 + (x3 * &z3) + (tmp2 * &z5); + self.c0.c2 = x0 * &z2 + (x3 * &z4) + (x4 * &z3); + self.c1.c0 = x0 * &z3 + (x3 * &z0) + (tmp2 * &z2); + self.c1.c1 = x0 * &z4 + (x3 * &z1) + (x4 * &z0); + self.c1.c2 = x0 * &z5 + (x3 * &z2) + (x4 * &z1); } pub fn mul_by_014( @@ -133,12 +133,12 @@ impl Fp6

{ let mut tmp2 = x4; tmp2.mul_assign(&::NONRESIDUE); - self.c0.c0 = x0 * &z0 + &(tmp1 * &z2) + &(tmp2 * &z4); - self.c0.c1 = x0 * &z1 + &(x1 * &z0) + &(tmp2 * &z5); - self.c0.c2 = x0 * &z2 + &(x1 * &z1) + &(x4 * &z3); - self.c1.c0 = x0 * &z3 + &(tmp1 * &z5) + &(tmp2 * &z2); - self.c1.c1 = x0 * &z4 + &(x1 * &z3) + &(x4 * &z0); - self.c1.c2 = x0 * &z5 + &(x1 * &z4) + &(x4 * &z1); + self.c0.c0 = x0 * &z0 + (tmp1 * &z2) + (tmp2 * &z4); + self.c0.c1 = x0 * &z1 + (x1 * &z0) + (tmp2 * &z5); + self.c0.c2 = x0 * &z2 + (x1 * &z1) + (x4 * &z3); + self.c1.c0 = x0 * &z3 + (tmp1 * &z5) + (tmp2 * &z2); + self.c1.c1 = x0 * &z4 + (x1 * &z3) + (x4 * &z0); + self.c1.c2 = x0 * &z5 + (x1 * &z4) + (x4 * &z1); } /// Multiply by quadratic nonresidue v. diff --git a/fields/src/tests_field.rs b/fields/src/tests_field.rs index 72474112a0..de681e9652 100644 --- a/fields/src/tests_field.rs +++ b/fields/src/tests_field.rs @@ -165,7 +165,7 @@ fn random_expansion_tests(rng: &mut R) { let c = F::rand(rng); let t0 = (a + &b) * &c; - let t2 = a * &c + &(b * &c); + let t2 = a * &c + (b * &c); assert_eq!(t0, t2); } @@ -306,9 +306,9 @@ pub fn field_test(a: F, b: F) { // a - b = -(b - a) assert_eq!(a - &b, -(b - &a)); // (a + b) + a = a + (b + a) - assert_eq!((a + &b) + &a, a + &(b + &a)); + assert_eq!((a + &b) + &a, a + (b + &a)); // (a + b).double() = (a + b) + (b + a) - assert_eq!((a + &b).double(), (a + &b) + &(b + &a)); + assert_eq!((a + &b).double(), (a + &b) + (b + &a)); // a * 0 = 0 assert_eq!(a * &zero, zero); @@ -327,7 +327,7 @@ pub fn field_test(a: F, b: F) { // (a * b) * a = a * (b * a) assert_eq!((a * &b) * &a, a * &(b * &a)); // (a + b)^2 = a^2 + 2ab + b^2 - assert_eq!((a + &b).square(), a.square() + &((a * &b) + &(a * &b)) + &b.square()); + assert_eq!((a + &b).square(), a.square() + ((a * &b) + (a * &b)) + &b.square()); // (a - b)^2 = (-(b - a))^2 assert_eq!((a - &b).square(), (-(b - &a)).square()); diff --git a/gadgets/src/curves/templates/twisted_edwards/mod.rs b/gadgets/src/curves/templates/twisted_edwards/mod.rs index 28ecd77383..1c6302d891 100644 --- a/gadgets/src/curves/templates/twisted_edwards/mod.rs +++ b/gadgets/src/curves/templates/twisted_edwards/mod.rs @@ -180,7 +180,7 @@ mod montgomery_affine_impl { let yprime = FG::alloc(cs.ns(|| "yprime"), || { Ok(-(self.y.get_value().get()? - + &(lambda.get_value().get()? * &(xprime.get_value().get()? - &self.x.get_value().get()?)))) + + (lambda.get_value().get()? * &(xprime.get_value().get()? - &self.x.get_value().get()?)))) })?; let xres = self.x.sub(cs.ns(|| "xres"), &xprime)?; @@ -315,7 +315,7 @@ mod affine_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + &(a * &v0.get_value().get()?) - &v1.get_value().get()?; + let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; let t1 = P::BaseField::one() - &v2.get_value().get()?; Ok(t0 * &t1.inverse().get()?) })?; @@ -377,7 +377,7 @@ mod affine_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + &(a * &v0.get_value().get()?) - &v1.get_value().get()?; + let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; let t1 = P::BaseField::one() - &v2.get_value().get()?; Ok(t0 * &t1.inverse().get()?) })?; @@ -705,7 +705,7 @@ mod projective_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + &(a * &v0.get_value().get()?) - &v1.get_value().get()?; + let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; let t1 = P::BaseField::one() - &v2.get_value().get()?; Ok(t0 * &t1.inverse().get()?) })?; @@ -768,7 +768,7 @@ mod projective_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + &(a * &v0.get_value().get()?) - &v1.get_value().get()?; + let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; let t1 = P::BaseField::one() - &v2.get_value().get()?; Ok(t0 * &t1.inverse().get()?) })?; diff --git a/gadgets/src/fields/fp12.rs b/gadgets/src/fields/fp12.rs index 592aa23fcf..03678c9ddf 100644 --- a/gadgets/src/fields/fp12.rs +++ b/gadgets/src/fields/fp12.rs @@ -157,7 +157,7 @@ where // t0 + t1*y = (z0 + z1*y)^2 = a^2 let tmp = z0.mul(cs.ns(|| "first mul"), &z1)?; let t0 = { - // (z0 + &z1) * &(z0 + &(fp2_nr * &z1)) - &tmp - &(tmp * &fp2_nr); + // (z0 + &z1) * &(z0 + (fp2_nr * &z1)) - &tmp - &(tmp * &fp2_nr); let mut cs = cs.ns(|| "t0"); let tmp1 = z0.add(cs.ns(|| "tmp1"), &z1)?; let tmp2 = z1 @@ -173,7 +173,7 @@ where // t2 + t3*y = (z2 + z3*y)^2 = b^2 let tmp = z2.mul(cs.ns(|| "second mul"), &z3)?; let t2 = { - // (z2 + &z3) * &(z2 + &(fp2_nr * &z3)) - &tmp - &(tmp * &fp2_nr); + // (z2 + &z3) * &(z2 + (fp2_nr * &z3)) - &tmp - &(tmp * &fp2_nr); let mut cs = cs.ns(|| "t2"); let tmp1 = z2.add(cs.ns(|| "tmp1"), &z3)?; let tmp2 = z3 @@ -189,7 +189,7 @@ where // t4 + t5*y = (z4 + z5*y)^2 = c^2 let tmp = z4.mul(cs.ns(|| "third mul"), &z5)?; let t4 = { - // (z4 + &z5) * &(z4 + &(fp2_nr * &z5)) - &tmp - &(tmp * &fp2_nr); + // (z4 + &z5) * &(z4 + (fp2_nr * &z5)) - &tmp - &(tmp * &fp2_nr); let mut cs = cs.ns(|| "t4"); let tmp1 = z4.add(cs.ns(|| "tmp1"), &z5)?; let tmp2 = z5 diff --git a/gadgets/src/nonnative/allocated_nonnative_field_var.rs b/gadgets/src/nonnative/allocated_nonnative_field_var.rs index 492b686e61..943bfa980d 100644 --- a/gadgets/src/nonnative/allocated_nonnative_field_var.rs +++ b/gadgets/src/nonnative/allocated_nonnative_field_var.rs @@ -267,8 +267,8 @@ impl AllocatedNonNativeFieldVar< let result = AllocatedNonNativeFieldVar:: { limbs, num_of_additions_over_normal_form: self.num_of_additions_over_normal_form - + &(other.num_of_additions_over_normal_form + &BaseField::one()) - + &(other.num_of_additions_over_normal_form + &BaseField::one()), + + (other.num_of_additions_over_normal_form + &BaseField::one()) + + (other.num_of_additions_over_normal_form + &BaseField::one()), is_in_the_normal_form: false, target_phantom: PhantomData, }; diff --git a/marlin/src/ahp/ahp.rs b/marlin/src/ahp/ahp.rs index 85dc7388c2..2ae1a79d9c 100644 --- a/marlin/src/ahp/ahp.rs +++ b/marlin/src/ahp/ahp.rs @@ -189,7 +189,7 @@ impl AHPForR1CS { vec![ (F::one(), "mask_poly".into()), - (r_alpha_at_beta * &(eta_a + &(eta_c * &z_b_at_beta)), "z_a".into()), + (r_alpha_at_beta * &(eta_a + (eta_c * &z_b_at_beta)), "z_a".into()), (r_alpha_at_beta * &eta_b * &z_b_at_beta, LCTerm::One), (-t_at_beta * &v_X_at_beta, "w".into()), @@ -246,7 +246,7 @@ impl AHPForR1CS { a *= v_H_at_alpha * &v_H_at_beta; let b_at_gamma = a_denom_at_gamma * &b_denom_at_gamma * &c_denom_at_gamma; - let b_expr_at_gamma = b_at_gamma * &(gamma * &g_2_at_gamma + &(t_at_beta / &k_size)); + let b_expr_at_gamma = b_at_gamma * &(gamma * &g_2_at_gamma + (t_at_beta / &k_size)); a -= &LinearCombination::new("b_expr", vec![(b_expr_at_gamma, LCTerm::One)]); a -= &LinearCombination::new("h_2", vec![(v_K_at_gamma, "h_2")]); diff --git a/marlin/src/ahp/prover/prover.rs b/marlin/src/ahp/prover/prover.rs index 7163c84c4f..63a1692b68 100644 --- a/marlin/src/ahp/prover/prover.rs +++ b/marlin/src/ahp/prover/prover.rs @@ -366,7 +366,7 @@ impl AHPForR1CS { cfg_iter_mut!(summed_z_m_coeffs) .zip(&z_a_poly.polynomial().coeffs) .zip(&z_b_poly.polynomial().coeffs) - .for_each(|((c, a), b)| *c += &(eta_a * a + &(eta_b * b))); + .for_each(|((c, a), b)| *c += &(eta_a * a + (eta_b * b))); let summed_z_m = Polynomial::from_coefficients_vec(summed_z_m_coeffs); end_timer!(summed_z_m_poly_time); @@ -525,8 +525,8 @@ impl AHPForR1CS { for i in 0..domain_k.size() { let t = eta_a * &a_star.evals_on_K.val[i] * &inverses_a[i] - + &(eta_b * &b_star.evals_on_K.val[i] * &inverses_b[i]) - + &(eta_c * &c_star.evals_on_K.val[i] * &inverses_c[i]); + + (eta_b * &b_star.evals_on_K.val[i] * &inverses_b[i]) + + (eta_c * &c_star.evals_on_K.val[i] * &inverses_c[i]); let f_at_kappa = v_H_at_beta * &v_H_at_alpha * &t; f_vals_on_K.push(f_at_kappa); } @@ -565,8 +565,8 @@ impl AHPForR1CS { let a_poly_on_B = cfg_into_iter!(0..domain_b.size()) .map(|i| { let t = eta_a * &a_star.evals_on_B.val.evaluations[i] * &b_denom[i] * &c_denom[i] - + &(eta_b * &b_star.evals_on_B.val.evaluations[i] * &a_denom[i] * &c_denom[i]) - + &(eta_c * &c_star.evals_on_B.val.evaluations[i] * &a_denom[i] * &b_denom[i]); + + (eta_b * &b_star.evals_on_B.val.evaluations[i] * &a_denom[i] * &c_denom[i]) + + (eta_c * &c_star.evals_on_B.val.evaluations[i] * &a_denom[i] * &b_denom[i]); v_H_at_beta * &v_H_at_alpha * &t }) .collect(); diff --git a/marlin/src/ahp/verifier/verifier.rs b/marlin/src/ahp/verifier/verifier.rs index a1ef828853..6b69230fee 100644 --- a/marlin/src/ahp/verifier/verifier.rs +++ b/marlin/src/ahp/verifier/verifier.rs @@ -200,7 +200,7 @@ impl AHPForR1CS { // let h_lc = LinearCombination::new("b_poly", vec![(v_K_at_gamma, "h_2")]); // // // This LC is the only one that is evaluated: - // let inner_sumcheck = a_poly_lc - (b_lc * (gamma * &g_2_at_gamma + &(t_at_beta / &k_size))) - h_lc + // let inner_sumcheck = a_poly_lc - (b_lc * (gamma * &g_2_at_gamma + (t_at_beta / &k_size))) - h_lc // main_lc.set_label("inner_sumcheck"); query_set.insert(("g_2".into(), gamma)); query_set.insert(("a_denom".into(), gamma)); diff --git a/r1cs/src/linear_combination.rs b/r1cs/src/linear_combination.rs index 85a6cdb49c..8dd9d057bd 100644 --- a/r1cs/src/linear_combination.rs +++ b/r1cs/src/linear_combination.rs @@ -385,7 +385,7 @@ impl Add<(F, &LinearCombination)> for &LinearCombination { self, other, |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + &(mul_coeff * &other_coeff), + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), ) } } @@ -406,7 +406,7 @@ impl<'a, F: Field> Add<(F, &'a LinearCombination)> for LinearCombination { &self, other, |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + &(mul_coeff * &other_coeff), + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), ) } } @@ -426,7 +426,7 @@ impl Add<(F, LinearCombination)> for &LinearCombination { self, &other, |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + &(mul_coeff * &other_coeff), + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), ) } } @@ -447,7 +447,7 @@ impl Add<(F, Self)> for LinearCombination { &self, &other, |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + &(mul_coeff * &other_coeff), + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), ) } } diff --git a/snarkvm/updater.rs b/snarkvm/updater.rs index 5d2790d31e..1807bba57b 100644 --- a/snarkvm/updater.rs +++ b/snarkvm/updater.rs @@ -48,7 +48,7 @@ impl Updater { .repo_owner(Self::SNARKVM_REPO_OWNER) .repo_name(Self::SNARKVM_REPO_NAME) .bin_name(Self::SNARKVM_BIN_NAME) - .current_version(&env!("CARGO_PKG_VERSION")) + .current_version(env!("CARGO_PKG_VERSION")) .show_download_progress(show_output) .no_confirm(true) .show_output(show_output) @@ -64,7 +64,7 @@ impl Updater { .repo_owner(Self::SNARKVM_REPO_OWNER) .repo_name(Self::SNARKVM_REPO_NAME) .bin_name(Self::SNARKVM_BIN_NAME) - .current_version(&env!("CARGO_PKG_VERSION")) + .current_version(env!("CARGO_PKG_VERSION")) .build()?; let current_version = updater.current_version(); From 47c0cb28fcd9f643a7ab9f0abeb786b0599ad8d3 Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 19:38:50 -0700 Subject: [PATCH 09/13] Clippy --- .../templates/short_weierstrass/short_weierstrass_jacobian.rs | 3 ++- .../short_weierstrass/short_weierstrass_projective.rs | 3 ++- curves/src/templates/twisted_edwards_extended/mod.rs | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs index 850e7953b6..3428941a48 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs @@ -787,6 +787,7 @@ impl Mul for GroupProjective

{ type Output = Self; /// Performs scalar multiplication of this element. + #[allow(clippy::suspicious_arithmetic_impl)] #[inline] fn mul(self, other: P::ScalarField) -> Self { let mut res = Self::zero(); @@ -801,7 +802,7 @@ impl Mul for GroupProjective

{ } if i { - res += &self; + res += self; } } diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs index 3d87da450c..1a6f8167b3 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs @@ -664,6 +664,7 @@ impl Mul for GroupProjective

{ type Output = Self; /// Performs scalar multiplication of this element. + #[allow(clippy::suspicious_arithmetic_impl)] #[inline] fn mul(self, other: P::ScalarField) -> Self { let mut res = Self::zero(); @@ -678,7 +679,7 @@ impl Mul for GroupProjective

{ } if i { - res += &self; + res += self; } } diff --git a/curves/src/templates/twisted_edwards_extended/mod.rs b/curves/src/templates/twisted_edwards_extended/mod.rs index 9cfdcfc2ab..272049232c 100644 --- a/curves/src/templates/twisted_edwards_extended/mod.rs +++ b/curves/src/templates/twisted_edwards_extended/mod.rs @@ -655,6 +655,7 @@ impl Mul for GroupProjective

{ type Output = Self; /// Performs scalar multiplication of this element. + #[allow(clippy::suspicious_arithmetic_impl)] #[inline] fn mul(self, other: P::ScalarField) -> Self { let mut res = Self::zero(); @@ -669,7 +670,7 @@ impl Mul for GroupProjective

{ } if i { - res += &self; + res += self; } } From 452bff7edb23fa743dde0ff2e7e5a2dad9ed9d9f Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 19:59:09 -0700 Subject: [PATCH 10/13] Clippy --- algorithms/benches/snark/gm17.rs | 2 +- algorithms/examples/snark/constraints.rs | 4 +- algorithms/src/encoding/elligator2.rs | 78 +++++------ algorithms/src/encryption/group.rs | 2 +- algorithms/src/fft/domain.rs | 14 +- algorithms/src/fft/polynomial/mod.rs | 2 +- algorithms/src/fft/polynomial/sparse.rs | 2 +- algorithms/src/signature/schnorr.rs | 4 +- algorithms/src/snark/gm17/generator.rs | 16 +-- algorithms/src/snark/gm17/prover.rs | 4 +- algorithms/src/snark/gm17/r1cs_to_sap.rs | 6 +- algorithms/src/snark/gm17/tests.rs | 2 +- algorithms/src/snark/groth16/generator.rs | 6 +- algorithms/src/snark/groth16/r1cs_to_qap.rs | 2 +- algorithms/src/snark/groth16/tests.rs | 2 +- curves/src/bls12_377/tests.rs | 2 +- curves/src/bw6_761/fq3.rs | 4 +- curves/src/edwards_bls12/tests.rs | 132 +++++++++--------- curves/src/edwards_sw6/tests.rs | 4 +- curves/src/sw6/fq3.rs | 2 +- curves/src/sw6/parameters.rs | 34 ++--- curves/src/sw6/tests.rs | 4 +- curves/src/templates/bls12/bls12.rs | 4 +- curves/src/templates/bls12/g2.rs | 40 +++--- curves/src/templates/bw6/bw6.rs | 50 +++---- curves/src/templates/bw6/g2.rs | 40 +++--- .../short_weierstrass_jacobian.rs | 72 +++++----- .../short_weierstrass_projective.rs | 68 ++++----- .../templates/twisted_edwards_extended/mod.rs | 96 ++++++------- .../twisted_edwards_extended/tests.rs | 4 +- curves/src/traits/tests_curve.rs | 8 +- curves/src/traits/tests_group.rs | 38 ++--- fields/src/fp12_2over3over2.rs | 62 ++++---- fields/src/fp2.rs | 24 ++-- fields/src/fp3.rs | 32 ++--- fields/src/fp6_2over3.rs | 44 +++--- fields/src/fp6_3over2.rs | 26 ++-- fields/src/lib.rs | 2 +- fields/src/macros.rs | 2 +- fields/src/tests_field.rs | 58 ++++---- gadgets/src/algorithms/snark/groth16.rs | 2 +- gadgets/src/algorithms/snark/tests.rs | 2 +- gadgets/src/bits/boolean.rs | 6 +- gadgets/src/curves/bls12_377.rs | 6 +- gadgets/src/curves/templates/bls12/affine.rs | 16 +-- gadgets/src/curves/templates/bls12/g2.rs | 6 +- .../curves/templates/twisted_edwards/mod.rs | 106 +++++++------- gadgets/src/curves/tests_curve.rs | 2 +- gadgets/src/curves/tests_field.rs | 29 ++-- gadgets/src/fields/fp12.rs | 6 +- gadgets/src/fields/fp2.rs | 8 +- gadgets/src/fields/fp6_3over2.rs | 12 +- ...llocated_nonnative_field_mul_result_var.rs | 12 +- .../allocated_nonnative_field_var.rs | 22 +-- gadgets/src/nonnative/reduce.rs | 10 +- gadgets/tests/nonnative/arithmetic_tests.rs | 32 ++--- .../nonnative/to_constraint_field_test.rs | 2 +- marlin/src/ahp/ahp.rs | 46 +++--- marlin/src/ahp/prover/prover.rs | 34 ++--- marlin/src/ahp/verifier/verifier.rs | 2 +- .../src/constraints/lagrange_interpolation.rs | 4 +- .../fiat_shamir_algebraic_sponge.rs | 6 +- .../fiat_shamir_algebraic_sponge_gadget.rs | 4 +- polycommit/src/kzg10/mod.rs | 4 +- polycommit/src/lib.rs | 4 +- polycommit/src/marlin_pc/mod.rs | 14 +- polycommit/src/sonic_pc/mod.rs | 10 +- r1cs/src/linear_combination.rs | 32 ++--- r1cs/src/test_constraint_system.rs | 8 +- 69 files changed, 716 insertions(+), 729 deletions(-) diff --git a/algorithms/benches/snark/gm17.rs b/algorithms/benches/snark/gm17.rs index 0c4ca6f2f6..9e780b0cef 100644 --- a/algorithms/benches/snark/gm17.rs +++ b/algorithms/benches/snark/gm17.rs @@ -54,7 +54,7 @@ impl ConstraintSynthesizer for Benchmark { let new_entry = { let (input_1_val, input_1_var) = variables[i]; let (input_2_val, input_2_var) = variables[i + 1]; - let result_val = input_1_val.and_then(|input_1| input_2_val.map(|input_2| input_1 * &input_2)); + let result_val = input_1_val.and_then(|input_1| input_2_val.map(|input_2| input_1 * input_2)); let result_var = cs.alloc( || format!("result_{}", i), || result_val.ok_or(SynthesisError::AssignmentMissing), diff --git a/algorithms/examples/snark/constraints.rs b/algorithms/examples/snark/constraints.rs index a478b892e2..14970e8962 100644 --- a/algorithms/examples/snark/constraints.rs +++ b/algorithms/examples/snark/constraints.rs @@ -47,7 +47,7 @@ impl ConstraintSynthesizer for Benchmark { for i in 0..self.num_constraints - 1 { if i % 2 != 0 { - let c_val = a_val * &b_val; + let c_val = a_val * b_val; let c_var = cs.alloc(|| format!("{}", i), || Ok(c_val))?; cs.enforce( @@ -63,7 +63,7 @@ impl ConstraintSynthesizer for Benchmark { b_val = c_val; b_var = c_var; } else { - let c_val = a_val + &b_val; + let c_val = a_val + b_val; let c_var = cs.alloc(|| format!("{}", i), || Ok(c_val))?; cs.enforce( diff --git a/algorithms/src/encoding/elligator2.rs b/algorithms/src/encoding/elligator2.rs index da08b253ff..c00c59200a 100644 --- a/algorithms/src/encoding/elligator2.rs +++ b/algorithms/src/encoding/elligator2.rs @@ -50,8 +50,8 @@ impl -(a * &two.inverse().unwrap()), + LegendreSymbol::Zero => -(a * two.inverse().unwrap()), LegendreSymbol::QuadraticResidue => v, - LegendreSymbol::QuadraticNonResidue => (-v) - &a, + LegendreSymbol::QuadraticNonResidue => (-v) - a, }; // Let y = -e * sqrt(x^3 + Ax^2 + Bx). let x2 = x.square(); - let x3 = x2 * &x; - let ax2 = a * &x2; - let bx = b * &x; + let x3 = x2 * x; + let ax2 = a * x2; + let bx = b * x; let value = (x3 + (ax2 + bx)).sqrt().unwrap(); let y = match e { LegendreSymbol::Zero => P::BaseField::zero(), @@ -118,14 +118,14 @@ impl EvaluationDomain { } u } else { - let mut l = (t_size - &one) * &self.size_inv; + let mut l = (t_size - one) * self.size_inv; let mut r = one; let mut u = vec![F::zero(); size]; let mut ls = vec![F::zero(); size]; for i in 0..size { - u[i] = tau - &r; + u[i] = tau - r; ls[i] = l; l *= &self.group_gen; r *= &self.group_gen; @@ -228,7 +228,7 @@ impl EvaluationDomain { batch_inversion(u.as_mut_slice()); cfg_iter_mut!(u).zip(ls).for_each(|(tau_minus_r, l)| { - *tau_minus_r = l * &*tau_minus_r; + *tau_minus_r = l * *tau_minus_r; }); u } @@ -243,7 +243,7 @@ impl EvaluationDomain { /// This evaluates the vanishing polynomial for this domain at tau. /// For multiplicative subgroups, this polynomial is `z(X) = X^self.size - 1`. pub fn evaluate_vanishing_polynomial(&self, tau: F) -> F { - tau.pow(&[self.size]) - &F::one() + tau.pow(&[self.size]) - F::one() } /// Return an iterator over the elements of the domain. @@ -350,7 +350,7 @@ impl EvaluationDomain { if log_powers.len() <= LOG_ROOTS_OF_UNITY_PARALLEL_SIZE { powers[0] = F::one(); for i in 1..powers.len() { - powers[i] = powers[i - 1] * &log_powers[0]; + powers[i] = powers[i - 1] * log_powers[0]; } return; } @@ -609,7 +609,7 @@ mod tests { // Do lagrange interpolation, and compare against the actual evaluation let mut interpolated_evaluation = Fr::zero(); for i in 0..domain_size { - interpolated_evaluation += lagrange_coefficients[i] * &polynomial_evaluations[i]; + interpolated_evaluation += lagrange_coefficients[i] * polynomial_evaluations[i]; } assert_eq!(actual_evaluations, interpolated_evaluation); } @@ -675,7 +675,7 @@ mod tests { let polynomial_evaluations = domain.fft(&random_polynomial.coeffs); let polynomial_coset_evaluations = domain.coset_fft(&random_polynomial.coeffs); for (i, x) in domain.elements().enumerate() { - let coset_x = Fr::multiplicative_generator() * &x; + let coset_x = Fr::multiplicative_generator() * x; assert_eq!(polynomial_evaluations[i], random_polynomial.evaluate(x)); assert_eq!(polynomial_coset_evaluations[i], random_polynomial.evaluate(coset_x)); diff --git a/algorithms/src/fft/polynomial/mod.rs b/algorithms/src/fft/polynomial/mod.rs index 87792c7976..112c0f8027 100644 --- a/algorithms/src/fft/polynomial/mod.rs +++ b/algorithms/src/fft/polynomial/mod.rs @@ -122,7 +122,7 @@ impl DenseOrSparsePolynomial<'_, F> { // Can unwrap here because we know self is not zero. let divisor_leading_inv = divisor.leading_coefficient().unwrap().inverse().unwrap(); while !remainder.is_zero() && remainder.degree() >= divisor.degree() { - let cur_q_coeff = *remainder.coeffs.last().unwrap() * &divisor_leading_inv; + let cur_q_coeff = *remainder.coeffs.last().unwrap() * divisor_leading_inv; let cur_q_degree = remainder.degree() - divisor.degree(); quotient[cur_q_degree] = cur_q_coeff; diff --git a/algorithms/src/fft/polynomial/sparse.rs b/algorithms/src/fft/polynomial/sparse.rs index 929d4b8b33..d6c3f507e4 100644 --- a/algorithms/src/fft/polynomial/sparse.rs +++ b/algorithms/src/fft/polynomial/sparse.rs @@ -90,7 +90,7 @@ impl SparsePolynomial { } let mut total = F::zero(); for (i, c) in &self.coeffs { - total += *c * &point.pow(&[*i as u64]); + total += *c * point.pow(&[*i as u64]); } total } diff --git a/algorithms/src/signature/schnorr.rs b/algorithms/src/signature/schnorr.rs index 902b6c636a..31c0737dc9 100644 --- a/algorithms/src/signature/schnorr.rs +++ b/algorithms/src/signature/schnorr.rs @@ -184,7 +184,7 @@ where }; // k - xe; - let prover_response = random_scalar - &(verifier_challenge * private_key); + let prover_response = random_scalar - (verifier_challenge * private_key); let signature = SchnorrOutput { prover_response, verifier_challenge, @@ -271,7 +271,7 @@ where } let new_sig = SchnorrOutput { - prover_response: *prover_response - &(*verifier_challenge * &multiplier), + prover_response: *prover_response - (*verifier_challenge * multiplier), verifier_challenge: *verifier_challenge, }; end_timer!(rand_signature_time); diff --git a/algorithms/src/snark/gm17/generator.rs b/algorithms/src/snark/gm17/generator.rs index 9b9a1b4a87..2c2835f16f 100644 --- a/algorithms/src/snark/gm17/generator.rs +++ b/algorithms/src/snark/gm17/generator.rs @@ -236,15 +236,15 @@ where scalar_bits, g_window, &g_table, - &cfg_iter!(a).map(|a| *a * &gamma).collect::>(), + &cfg_iter!(a).map(|a| *a * gamma).collect::>(), ); end_timer!(a_time); // Compute the G_gamma-query let g_gamma_time = start_timer!(|| "Calculate G gamma"); - let gamma_z = zt * γ + let gamma_z = zt * gamma; let alpha_beta = alpha + beta; - let ab_gamma_z = alpha_beta * &gamma * &zt; + let ab_gamma_z = alpha_beta * gamma * zt; let g_gamma = g.into_affine().mul(gamma); let g_gamma_z = g.into_affine().mul(gamma_z); let h_gamma = h.into_affine().mul(gamma); @@ -253,13 +253,13 @@ where let g_gamma2_z2 = g.into_affine().mul(gamma_z.square()); // Compute the vector G_gamma2_z_t := Z(t) * t^i * gamma^2 * G - let gamma2_z_t = gamma_z * γ + let gamma2_z_t = gamma_z * gamma; let mut g_gamma2_z_t = FixedBaseMSM::multi_scalar_mul::( scalar_bits, g_window, &g_table, &cfg_into_iter!(0..m_raw + 1) - .map(|i| gamma2_z_t * &(t.pow([i as u64]))) + .map(|i| gamma2_z_t * (t.pow([i as u64]))) .collect::>(), ); end_timer!(g_gamma_time); @@ -271,7 +271,7 @@ where g_window, &g_table, &cfg_into_iter!(0..sap_num_variables + 1) - .map(|i| c[i] * &gamma + (a[i] * &alpha_beta)) + .map(|i| c[i] * gamma + (a[i] * alpha_beta)) .collect::>(), ); let (verifier_query, c_query_1) = result.split_at_mut(assembly.num_public_variables); @@ -279,13 +279,13 @@ where // Compute the C_2-query let c2_time = start_timer!(|| "Calculate C2"); - let double_gamma2_z = (zt * &gamma.square()).double(); + let double_gamma2_z = (zt * gamma.square()).double(); let mut c_query_2 = FixedBaseMSM::multi_scalar_mul::( scalar_bits, g_window, &g_table, &cfg_into_iter!(0..sap_num_variables + 1) - .map(|i| a[i] * &double_gamma2_z) + .map(|i| a[i] * double_gamma2_z) .collect::>(), ); drop(g_table); diff --git a/algorithms/src/snark/gm17/prover.rs b/algorithms/src/snark/gm17/prover.rs index 69db83404f..475b635ac0 100644 --- a/algorithms/src/snark/gm17/prover.rs +++ b/algorithms/src/snark/gm17/prover.rs @@ -311,8 +311,8 @@ where // Compute C let c_acc_time = start_timer!(|| "Compute C"); let r_2 = r + r; - let r2 = r * &r; - let d1_r_2 = d1 * &r_2; + let r2 = r * r; + let d1_r_2 = d1 * r_2; let c1_acc_time = start_timer!(|| "Compute C1"); let (_, c1_aux_source) = params.get_c_query_1(0)?; diff --git a/algorithms/src/snark/gm17/r1cs_to_sap.rs b/algorithms/src/snark/gm17/r1cs_to_sap.rs index 725dc8d9a6..39862137ca 100644 --- a/algorithms/src/snark/gm17/r1cs_to_sap.rs +++ b/algorithms/src/snark/gm17/r1cs_to_sap.rs @@ -63,7 +63,7 @@ impl R1CStoSAP { let u_2i = u[2 * i]; let u_2i_plus_1 = u[2 * i + 1]; let u_add = u_2i + u_2i_plus_1; - let u_sub = u_2i - &u_2i_plus_1; + let u_sub = u_2i - u_2i_plus_1; for &(ref coeff, index) in assembly.at[i].iter() { let index = match index { @@ -137,7 +137,7 @@ impl R1CStoSAP { Index::Public(i) => assignment[i], Index::Private(i) => assignment[num_input + i], }; - acc += val * &coeff; + acc += val * coeff; } acc } @@ -202,7 +202,7 @@ impl R1CStoSAP { a[extra_constr_offset] = one; for i in 1..prover.num_public_variables { a[extra_constr_offset + 2 * i - 1] = full_input_assignment[i] + one; - a[extra_constr_offset + 2 * i] = full_input_assignment[i] - &one; + a[extra_constr_offset + 2 * i] = full_input_assignment[i] - one; } domain.ifft_in_place(&mut a); diff --git a/algorithms/src/snark/gm17/tests.rs b/algorithms/src/snark/gm17/tests.rs index 771fc4f438..5e30324b3c 100644 --- a/algorithms/src/snark/gm17/tests.rs +++ b/algorithms/src/snark/gm17/tests.rs @@ -87,7 +87,7 @@ mod bw6 { let a = BW6Fr::rand(rng); let b = BW6Fr::rand(rng); - let c = a * &b; + let c = a * b; let proof = create_random_proof(&MySillyCircuit { a: Some(a), b: Some(b) }, ¶ms, rng).unwrap(); let pvk = prepare_verifying_key::(params.vk); diff --git a/algorithms/src/snark/groth16/generator.rs b/algorithms/src/snark/groth16/generator.rs index 825869cfd1..93b630e3a9 100644 --- a/algorithms/src/snark/groth16/generator.rs +++ b/algorithms/src/snark/groth16/generator.rs @@ -194,13 +194,13 @@ where let gamma_abc = cfg_iter!(a[0..assembly.num_public_variables]) .zip(&b[0..assembly.num_public_variables]) .zip(&c[0..assembly.num_public_variables]) - .map(|((a, b), c)| (beta * a + (alpha * b) + c) * &gamma_inverse) + .map(|((a, b), c)| (beta * a + (alpha * b) + c) * gamma_inverse) .collect::>(); let l = cfg_iter!(a) .zip(&b) .zip(&c) - .map(|((a, b), c)| (beta * a + (alpha * b) + c) * &delta_inverse) + .map(|((a, b), c)| (beta * a + (alpha * b) + c) * delta_inverse) .collect::>(); let g1_generator = E::G1Projective::rand(rng); @@ -249,7 +249,7 @@ where g1_window, &g1_table, &cfg_into_iter!(0..m_raw - 1) - .map(|i| zt * &delta_inverse * &t.pow([i as u64])) + .map(|i| zt * delta_inverse * t.pow([i as u64])) .collect::>(), ); diff --git a/algorithms/src/snark/groth16/r1cs_to_qap.rs b/algorithms/src/snark/groth16/r1cs_to_qap.rs index cdb138d634..59f927c525 100644 --- a/algorithms/src/snark/groth16/r1cs_to_qap.rs +++ b/algorithms/src/snark/groth16/r1cs_to_qap.rs @@ -34,7 +34,7 @@ fn evaluate_constraint(terms: &[(E::Fr, Index)], assignment: & Index::Public(i) => assignment[i], Index::Private(i) => assignment[num_input + i], }; - acc += val * &coeff; + acc += val * coeff; } acc } diff --git a/algorithms/src/snark/groth16/tests.rs b/algorithms/src/snark/groth16/tests.rs index f819a7696d..e14a777af9 100644 --- a/algorithms/src/snark/groth16/tests.rs +++ b/algorithms/src/snark/groth16/tests.rs @@ -93,7 +93,7 @@ mod bw6_761 { let a = Fr::rand(rng); let b = Fr::rand(rng); - let c = a * &b; + let c = a * b; let proof = create_random_proof(&MySillyCircuit { a: Some(a), b: Some(b) }, ¶meters, rng).unwrap(); let pvk = prepare_verifying_key::(parameters.vk); diff --git a/curves/src/bls12_377/tests.rs b/curves/src/bls12_377/tests.rs index 45d14e8e88..81e8d56aab 100644 --- a/curves/src/bls12_377/tests.rs +++ b/curves/src/bls12_377/tests.rs @@ -478,7 +478,7 @@ fn test_fq2_mul_nonresidue() { for _ in 0..1000 { let mut a = Fq2::rand(&mut rng); let mut b = a; - a = quadratic_non_residue * &a; + a = quadratic_non_residue * a; b.mul_assign(&nqr); assert_eq!(a, b); diff --git a/curves/src/bw6_761/fq3.rs b/curves/src/bw6_761/fq3.rs index 33c0c3d569..a4c60323d3 100644 --- a/curves/src/bw6_761/fq3.rs +++ b/curves/src/bw6_761/fq3.rs @@ -223,7 +223,7 @@ impl Fp3Parameters for Fq3Parameters { #[inline(always)] fn mul_fp_by_nonresidue(fe: &Self::Fp) -> Self::Fp { let original = -(*fe); - let double = original + &original; - double + &double + let double = original + original; + double + double } } diff --git a/curves/src/edwards_bls12/tests.rs b/curves/src/edwards_bls12/tests.rs index 8dda4e682c..bf95205c0b 100644 --- a/curves/src/edwards_bls12/tests.rs +++ b/curves/src/edwards_bls12/tests.rs @@ -94,9 +94,9 @@ fn test_conversion() { let b: EdwardsAffine = rand::random(); let a_b = { use crate::traits::Group; - (a + &b).double().double() + (a + b).double().double() }; - let a_b2 = (a.into_projective() + &b.into_projective()).double().double(); + let a_b2 = (a.into_projective() + b.into_projective()).double().double(); assert_eq!(a_b, a_b2.into_affine()); assert_eq!(a_b.into_projective(), a_b2); } @@ -114,11 +114,11 @@ fn test_edwards_to_montgomery_point() { // Montgomery element (u, v) let (u, v) = { - let numerator = Fq::one() + &y; - let denominator = Fq::one() - &y; + let numerator = Fq::one() + y; + let denominator = Fq::one() - y; - let u = numerator * &(denominator.inverse().unwrap()); - let v = numerator * &((denominator * &x).inverse().unwrap()); + let u = numerator * (denominator.inverse().unwrap()); + let v = numerator * ((denominator * x).inverse().unwrap()); (u, v) }; @@ -130,17 +130,17 @@ fn test_edwards_to_montgomery_point() { // Enforce B * v^2 == u^3 + A * u^2 + u let v2 = v.square(); let u2 = u.square(); - let u3 = u2 * &u; - assert_eq!(B * &v2, u3 + (A * &u2) + &u); + let u3 = u2 * u; + assert_eq!(B * v2, u3 + (A * u2) + u); } // Edwards element (x, y) let (x_reconstructed, y_reconstructed) = { - let x = u * &v.inverse().unwrap(); + let x = u * v.inverse().unwrap(); - let numerator = u - &Fq::one(); - let denominator = u + &Fq::one(); - let y = numerator * &denominator.inverse().unwrap(); + let numerator = u - Fq::one(); + let denominator = u + Fq::one(); + let y = numerator * denominator.inverse().unwrap(); (x, y) }; @@ -155,25 +155,25 @@ fn print_montgomery_to_weierstrass_parameters() { const A: Fq = ::COEFF_A; const B: Fq = ::COEFF_B; - let two = Fq::one() + &Fq::one(); - let three = Fq::one() + &two; - let nine = three + (three + &three); - let twenty_seven = nine + (nine + &nine); + let two = Fq::one() + Fq::one(); + let three = Fq::one() + two; + let nine = three + (three + three); + let twenty_seven = nine + (nine + nine); let a2 = A.square(); - let a3 = A * &a2; + let a3 = A * a2; let b2 = B.square(); - let b3 = B * &b2; + let b3 = B * b2; // Let a = (3 - A^2) / (3 * B^2). - let numerator = three - &a2; - let denominator = three * &b2; - let a = numerator * &denominator.inverse().unwrap(); + let numerator = three - a2; + let denominator = three * b2; + let a = numerator * denominator.inverse().unwrap(); // Let b = (2 * A^3 - 9 * A) / (27 * B^3). - let numerator = (two * &a3) - &(nine * &A); - let denominator = twenty_seven * &b3; - let b = numerator * &denominator.inverse().unwrap(); + let numerator = (two * a3) - (nine * A); + let denominator = twenty_seven * b3; + let b = numerator * denominator.inverse().unwrap(); println!("A - {}\nB - {}", a, b); } @@ -203,8 +203,8 @@ fn test_isomorphism() { // Compute the parameters for the alternate Montgomery form: v^2 == u^3 + A * u^2 + B * u. let (a, b) = { - let a = A * &B.inverse().unwrap(); - let b = Fq::one() * &B.square().inverse().unwrap(); + let a = A * B.inverse().unwrap(); + let b = Fq::one() * B.square().inverse().unwrap(); (a, b) }; @@ -218,7 +218,7 @@ fn test_isomorphism() { let u = ::COEFF_D; // Let ur2 = u * r^2; - let ur2 = r.square() * &u; + let ur2 = r.square() * u; { // Verify r is nonzero. @@ -228,37 +228,37 @@ fn test_isomorphism() { assert!(u.legendre().is_qnr()); // Verify 1 + ur^2 != 0. - assert_ne!(Fq::one() + &ur2, Fq::zero()); + assert_ne!(Fq::one() + ur2, Fq::zero()); // Verify A^2 * ur^2 != B(1 + ur^2)^2. let a2 = a.square(); - assert_ne!(a2 * &ur2, (Fq::one() + &ur2).square() * &b); + assert_ne!(a2 * ur2, (Fq::one() + ur2).square() * b); } // Let v = -A / (1 + ur^2). - let v = (Fq::one() + &ur2).inverse().unwrap() * &(-a); + let v = (Fq::one() + ur2).inverse().unwrap() * (-a); // Let e = legendre(v^3 + Av^2 + Bv). let v2 = v.square(); - let v3 = v2 * &v; - let av2 = a * &v2; - let bv = b * &v; - let e = (v3 + (av2 + &bv)).legendre(); + let v3 = v2 * v; + let av2 = a * v2; + let bv = b * v; + let e = (v3 + (av2 + bv)).legendre(); // Let x = ev - ((1 - e) * A/2). let two = Fq::one().double(); let x = match e { - LegendreSymbol::Zero => -(a * &two.inverse().unwrap()), + LegendreSymbol::Zero => -(a * two.inverse().unwrap()), LegendreSymbol::QuadraticResidue => v, - LegendreSymbol::QuadraticNonResidue => (-v) - &a, + LegendreSymbol::QuadraticNonResidue => (-v) - a, }; // Let y = -e * sqrt(x^3 + Ax^2 + Bx). let x2 = x.square(); - let x3 = x2 * &x; - let ax2 = a * &x2; - let bx = b * &x; - let value = (x3 + (ax2 + &bx)).sqrt().unwrap(); + let x3 = x2 * x; + let ax2 = a * x2; + let bx = b * x; + let value = (x3 + (ax2 + bx)).sqrt().unwrap(); let y = match e { LegendreSymbol::Zero => Fq::zero(), LegendreSymbol::QuadraticResidue => -value, @@ -273,22 +273,22 @@ fn test_isomorphism() { // Enforce v^2 == u^3 + A * u^2 + B * u let v2 = v.square(); let u2 = u.square(); - let u3 = u2 * &u; - assert_eq!(v2, u3 + (a * &u2) + (b * &u)); + let u3 = u2 * u; + assert_eq!(v2, u3 + (a * u2) + (b * u)); } // Convert the alternate Montgomery element (u, v) to Montgomery element (s, t). let (s, t) = { - let s = u * &B; - let t = v * &B; + let s = u * B; + let t = v * B; // Ensure (s, t) is a valid Montgomery element { // Enforce B * t^2 == s^3 + A * s^2 + s let t2 = t.square(); let s2 = s.square(); - let s3 = s2 * &s; - assert_eq!(B * &t2, s3 + (A * &s2) + &s); + let s3 = s2 * s; + assert_eq!(B * t2, s3 + (A * s2) + s); } (s, t) @@ -296,11 +296,11 @@ fn test_isomorphism() { // Convert the Montgomery element (s, t) to the twisted Edwards element (x, y). let (x, y) = { - let x = s * &t.inverse().unwrap(); + let x = s * t.inverse().unwrap(); - let numerator = s - &Fq::one(); - let denominator = s + &Fq::one(); - let y = numerator * &denominator.inverse().unwrap(); + let numerator = s - Fq::one(); + let denominator = s + Fq::one(); + let y = numerator * denominator.inverse().unwrap(); (x, y) }; @@ -311,31 +311,31 @@ fn test_isomorphism() { // Convert the twisted Edwards element (x, y) to the alternate Montgomery element (u, v) let (u_reconstructed, v_reconstructed) = { - let numerator = Fq::one() + &y; - let denominator = Fq::one() - &y; + let numerator = Fq::one() + y; + let denominator = Fq::one() - y; - let u = numerator * &(denominator.inverse().unwrap()); - let v = numerator * &((denominator * &x).inverse().unwrap()); + let u = numerator * (denominator.inverse().unwrap()); + let v = numerator * ((denominator * x).inverse().unwrap()); // Ensure (u, v) is a valid Montgomery element { // Enforce B * v^2 == u^3 + A * u^2 + u let v2 = v.square(); let u2 = u.square(); - let u3 = u2 * &u; - assert_eq!(B * &v2, u3 + (A * &u2) + &u); + let u3 = u2 * u; + assert_eq!(B * v2, u3 + (A * u2) + u); } - let u = u * &B.inverse().unwrap(); - let v = v * &B.inverse().unwrap(); + let u = u * B.inverse().unwrap(); + let v = v * B.inverse().unwrap(); // Ensure (u, v) is a valid alternate Montgomery element. { // Enforce v^2 == u^3 + A * u^2 + B * u let v2 = v.square(); let u2 = u.square(); - let u3 = u2 * &u; - assert_eq!(v2, u3 + (a * &u2) + (b * &u)); + let u3 = u2 * u; + assert_eq!(v2, u3 + (a * u2) + (b * u)); } (u, v) @@ -364,20 +364,20 @@ fn test_isomorphism() { } // Verify -ux(x + A) is a residue. - assert_eq!((-(u * &x) * &(x + &a)).legendre(), LegendreSymbol::QuadraticResidue); + assert_eq!((-(u * x) * (x + a)).legendre(), LegendreSymbol::QuadraticResidue); } println!("\ngroup legendre - {:?}", y.legendre()); // Let value1 = sqrt(-x / ((x + A) * u)). let numerator = -x; - let denominator = (x + &a) * &u; - let value1 = (numerator * &denominator.inverse().unwrap()).sqrt(); + let denominator = (x + a) * u; + let value1 = (numerator * denominator.inverse().unwrap()).sqrt(); // Let value2 = sqrt(-(x + A) / ux)). - let numerator = -x - &a; - let denominator = x * &u; - let value2 = (numerator * &denominator.inverse().unwrap()).sqrt(); + let numerator = -x - a; + let denominator = x * u; + let value2 = (numerator * denominator.inverse().unwrap()).sqrt(); let mut recovered_value = None; diff --git a/curves/src/edwards_sw6/tests.rs b/curves/src/edwards_sw6/tests.rs index ea92cb5112..c8279ce4f0 100644 --- a/curves/src/edwards_sw6/tests.rs +++ b/curves/src/edwards_sw6/tests.rs @@ -76,9 +76,9 @@ fn test_conversion() { let b: EdwardsAffine = rand::random(); let a_b = { use crate::traits::Group; - (a + &b).double().double() + (a + b).double().double() }; - let a_b2 = (a.into_projective() + &b.into_projective()).double().double(); + let a_b2 = (a.into_projective() + b.into_projective()).double().double(); assert_eq!(a_b, a_b2.into_affine()); assert_eq!(a_b.into_projective(), a_b2); } diff --git a/curves/src/sw6/fq3.rs b/curves/src/sw6/fq3.rs index 75bc2c2af2..8ad6d31e25 100644 --- a/curves/src/sw6/fq3.rs +++ b/curves/src/sw6/fq3.rs @@ -226,6 +226,6 @@ impl Fp3Parameters for Fq3Parameters { let mut four_fe = fe.double(); four_fe.double_in_place(); let eight_fe = four_fe.double(); - eight_fe + &four_fe + &original + eight_fe + four_fe + original } } diff --git a/curves/src/sw6/parameters.rs b/curves/src/sw6/parameters.rs index 15100bebce..b4b082f6ef 100644 --- a/curves/src/sw6/parameters.rs +++ b/curves/src/sw6/parameters.rs @@ -100,40 +100,40 @@ impl SW6 { old_ry = ry; let old_rx_square = old_rx.square(); - let old_rx_square_3 = old_rx_square.double() + &old_rx_square; - let old_rx_square_3_a = old_rx_square_3 + &SW6G2Parameters::COEFF_A; + let old_rx_square_3 = old_rx_square.double() + old_rx_square; + let old_rx_square_3_a = old_rx_square_3 + SW6G2Parameters::COEFF_A; let old_ry_double_inverse = old_ry.double().inverse().unwrap(); - let gamma = old_rx_square_3_a * &old_ry_double_inverse; - let gamma_twist = gamma * &TWIST; - let gamma_old_rx = gamma * &old_rx; + let gamma = old_rx_square_3_a * old_ry_double_inverse; + let gamma_twist = gamma * TWIST; + let gamma_old_rx = gamma * old_rx; let mut gamma_twist_px = gamma_twist; gamma_twist_px.mul_assign_by_fp(&px); let x = py_twist_squared; - let y = gamma_old_rx - &old_ry - &gamma_twist_px; + let y = gamma_old_rx - old_ry - gamma_twist_px; let ell_rr_at_p = Fq6::new(x, y); - rx = gamma.square() - &old_rx.double(); - ry = gamma * &(old_rx - &rx) - &old_ry; - f = f.square() * &ell_rr_at_p; + rx = gamma.square() - old_rx.double(); + ry = gamma * (old_rx - rx) - old_ry; + f = f.square() * ell_rr_at_p; if bit { old_rx = rx; old_ry = ry; - let gamma = (old_ry - &qy) * &((old_rx - &qx).inverse().unwrap()); - let gamma_twist = gamma * &TWIST; - let gamma_qx = gamma * &qx; + let gamma = (old_ry - qy) * ((old_rx - qx).inverse().unwrap()); + let gamma_twist = gamma * TWIST; + let gamma_qx = gamma * qx; let mut gamma_twist_px = gamma_twist; gamma_twist_px.mul_assign_by_fp(&px); let x = py_twist_squared; - let y = gamma_qx - &qy - &gamma_twist_px; + let y = gamma_qx - qy - gamma_twist_px; let ell_rq_at_p = Fq6::new(x, y); - rx = gamma.square() - &old_rx - &qx; - ry = gamma * &(old_rx - &rx) - &old_ry; + rx = gamma.square() - old_rx - qx; + ry = gamma * (old_rx - rx) - old_ry; f *= &ell_rq_at_p; } } @@ -159,7 +159,7 @@ impl SW6 { let mut alpha = elt_q3_over_elt; alpha.frobenius_map(1); // beta = elt^((q^3-1)*(q+1) - alpha * &elt_q3_over_elt + alpha * elt_q3_over_elt } fn final_exponentiation_last(elt: &Fq6, elt_inv: &Fq6) -> Fq6 { @@ -172,7 +172,7 @@ impl SW6 { false => elt.cyclotomic_exp(&FINAL_EXPONENT_LAST_CHUNK_ABS_OF_W0), }; - w1_part * &w0_part + w1_part * w0_part } } diff --git a/curves/src/sw6/tests.rs b/curves/src/sw6/tests.rs index 6462ca17fc..d4bb5cf196 100644 --- a/curves/src/sw6/tests.rs +++ b/curves/src/sw6/tests.rs @@ -111,8 +111,8 @@ fn test_bilinearity() { let b: G2Projective = rand::random(); let s: Fr = rand::random(); - let sa = a * &s; - let sb = b * &s; + let sa = a * s; + let sb = b * s; let ans1 = SW6::pairing(sa, b); let ans2 = SW6::pairing(a, sb); diff --git a/curves/src/templates/bls12/bls12.rs b/curves/src/templates/bls12/bls12.rs index 009582fb5a..f190c5c779 100644 --- a/curves/src/templates/bls12/bls12.rs +++ b/curves/src/templates/bls12/bls12.rs @@ -175,7 +175,7 @@ where Some(mut f2) => { // f2 = f^(-1); // r = f^(p^6 - 1) - let mut r = f1 * &f2; + let mut r = f1 * f2; // f2 = f^(p^6 - 1) f2 = r; @@ -194,7 +194,7 @@ where let mut y5 = Self::exp_by_x(r); let mut y1 = y5.cyclotomic_square(); - let mut y3 = y0 * &y5; + let mut y3 = y0 * y5; y0 = Self::exp_by_x(y3); let y2 = Self::exp_by_x(y0); let mut y4 = Self::exp_by_x(y2); diff --git a/curves/src/templates/bls12/g2.rs b/curves/src/templates/bls12/g2.rs index 32828a32c3..e6bc37ed1b 100644 --- a/curves/src/templates/bls12/g2.rs +++ b/curves/src/templates/bls12/g2.rs @@ -116,25 +116,25 @@ fn doubling_step(r: &mut G2HomProjective, two_inv: &B::Fp // Formula for line function when working with // homogeneous projective coordinates. - let mut a = r.x * &r.y; + let mut a = r.x * r.y; a.mul_by_fp(two_inv); let b = r.y.square(); let c = r.z.square(); - let e = B::G2Parameters::COEFF_B * &(c.double() + &c); - let f = e.double() + &e; - let mut g = b + &f; + let e = B::G2Parameters::COEFF_B * (c.double() + c); + let f = e.double() + e; + let mut g = b + f; g.mul_by_fp(two_inv); - let h = (r.y + &r.z).square() - &(b + &c); - let i = e - &b; + let h = (r.y + r.z).square() - (b + c); + let i = e - b; let j = r.x.square(); let e_square = e.square(); - r.x = a * &(b - &f); - r.y = g.square() - &(e_square.double() + &e_square); - r.z = b * &h; + r.x = a * (b - f); + r.y = g.square() - (e_square.double() + e_square); + r.z = b * h; match B::TWIST_TYPE { - TwistType::M => (i, j.double() + &j, -h), - TwistType::D => (-h, j.double() + &j, i), + TwistType::M => (i, j.double() + j, -h), + TwistType::D => (-h, j.double() + j, i), } } @@ -142,18 +142,18 @@ fn doubling_step(r: &mut G2HomProjective, two_inv: &B::Fp fn addition_step(r: &mut G2HomProjective, q: &G2Affine) -> CoeffTriplet { // Formula for line function when working with // homogeneous projective coordinates. - let theta = r.y - &(q.y * &r.z); - let lambda = r.x - &(q.x * &r.z); + let theta = r.y - (q.y * r.z); + let lambda = r.x - (q.x * r.z); let c = theta.square(); let d = lambda.square(); - let e = lambda * &d; - let f = r.z * &c; - let g = r.x * &d; - let h = e + &f - &g.double(); - r.x = lambda * &h; - r.y = theta * &(g - &h) - &(e * &r.y); + let e = lambda * d; + let f = r.z * c; + let g = r.x * d; + let h = e + f - g.double(); + r.x = lambda * h; + r.y = theta * (g - h) - (e * r.y); r.z *= &e; - let j = theta * &q.x - &(lambda * &q.y); + let j = theta * q.x - (lambda * q.y); match B::TWIST_TYPE { TwistType::M => (j, -theta, lambda), diff --git a/curves/src/templates/bw6/bw6.rs b/curves/src/templates/bw6/bw6.rs index eafefe14e1..d65c45acd3 100644 --- a/curves/src/templates/bw6/bw6.rs +++ b/curves/src/templates/bw6/bw6.rs @@ -108,7 +108,7 @@ impl BW6

{ let mut alpha = elt_q3_over_elt; alpha.frobenius_map(1); // beta = elt^((q^3-1)*(q+1) - alpha * &elt_q3_over_elt + alpha * elt_q3_over_elt } fn final_exponentiation_last_chunk(f: &Fp6) -> Fp6 { @@ -151,68 +151,68 @@ impl BW6

{ // step 5 let mut f5p_p3 = f5p; f5p_p3.conjugate(); - let result1 = f3p * &f6p * &f5p_p3; + let result1 = f3p * f6p * f5p_p3; // step 6 let result2 = result1.square(); - let f4_2p = f4 * &f2p; - let mut tmp1_p3 = f0 * &f1 * &f3 * &f4_2p * &f8p; + let f4_2p = f4 * f2p; + let mut tmp1_p3 = f0 * f1 * f3 * f4_2p * f8p; tmp1_p3.conjugate(); - let result3 = result2 * &f5 * &f0p * &tmp1_p3; + let result3 = result2 * f5 * f0p * tmp1_p3; // step 7 let result4 = result3.square(); let mut f7_p3 = f7; f7_p3.conjugate(); - let result5 = result4 * &f9p * &f7_p3; + let result5 = result4 * f9p * f7_p3; // step 8 let result6 = result5.square(); - let f2_4p = f2 * &f4p; - let f4_2p_5p = f4_2p * &f5p; - let mut tmp2_p3 = f2_4p * &f3 * &f3p; + let f2_4p = f2 * f4p; + let f4_2p_5p = f4_2p * f5p; + let mut tmp2_p3 = f2_4p * f3 * f3p; tmp2_p3.conjugate(); - let result7 = result6 * &f4_2p_5p * &f6 * &f7p * &tmp2_p3; + let result7 = result6 * f4_2p_5p * f6 * f7p * tmp2_p3; // step 9 let result8 = result7.square(); - let mut tmp3_p3 = f0p * &f9p; + let mut tmp3_p3 = f0p * f9p; tmp3_p3.conjugate(); - let result9 = result8 * &f0 * &f7 * &f1p * &tmp3_p3; + let result9 = result8 * f0 * f7 * f1p * tmp3_p3; // step 10 let result10 = result9.square(); - let f6p_8p = f6p * &f8p; - let f5_7p = f5 * &f7p; + let f6p_8p = f6p * f8p; + let f5_7p = f5 * f7p; let mut tmp4_p3 = f6p_8p; tmp4_p3.conjugate(); - let result11 = result10 * &f5_7p * &f2p * &tmp4_p3; + let result11 = result10 * f5_7p * f2p * tmp4_p3; // step 11 let result12 = result11.square(); - let f3_6 = f3 * &f6; - let f1_7 = f1 * &f7; - let mut tmp5_p3 = f1_7 * &f2; + let f3_6 = f3 * f6; + let f1_7 = f1 * f7; + let mut tmp5_p3 = f1_7 * f2; tmp5_p3.conjugate(); - let result13 = result12 * &f3_6 * &f9p * &tmp5_p3; + let result13 = result12 * f3_6 * f9p * tmp5_p3; // step 12 let result14 = result13.square(); - let mut tmp6_p3 = f4_2p * &f5_7p * &f6p_8p; + let mut tmp6_p3 = f4_2p * f5_7p * f6p_8p; tmp6_p3.conjugate(); - let result15 = result14 * &f0 * &f0p * &f3p * &f5p * &tmp6_p3; + let result15 = result14 * f0 * f0p * f3p * f5p * tmp6_p3; // step 13 let result16 = result15.square(); let mut tmp7_p3 = f3_6; tmp7_p3.conjugate(); - let result17 = result16 * &f1p * &tmp7_p3; + let result17 = result16 * f1p * tmp7_p3; // step 14 let result18 = result17.square(); - let mut tmp8_p3 = f2_4p * &f4_2p_5p * &f9p; + let mut tmp8_p3 = f2_4p * f4_2p_5p * f9p; tmp8_p3.conjugate(); - result18 * &f1_7 * &f5_7p * &f0p * &tmp8_p3 + result18 * f1_7 * f5_7p * f0p * tmp8_p3 } } @@ -318,7 +318,7 @@ where f_2.frobenius_map(1); - f_1 * &f_2 + f_1 * f_2 } fn final_exponentiation(f: &Self::Fqk) -> Option { diff --git a/curves/src/templates/bw6/g2.rs b/curves/src/templates/bw6/g2.rs index 53782c791e..5c5318fc57 100644 --- a/curves/src/templates/bw6/g2.rs +++ b/curves/src/templates/bw6/g2.rs @@ -153,24 +153,24 @@ fn doubling_step(r: &mut G2HomProjective) -> (B::Fp, B::Fp, // Formula for line function when working with // homogeneous projective coordinates, as described in https://eprint.iacr.org/2013/722.pdf. - let a = r.x * &r.y; + let a = r.x * r.y; let b = r.y.square(); let b4 = b.double().double(); let c = r.z.square(); - let e = B::G2Parameters::COEFF_B * &(c.double() + &c); - let f = e.double() + &e; - let g = b + &f; - let h = (r.y + &r.z).square() - &(b + &c); - let i = e - &b; + let e = B::G2Parameters::COEFF_B * (c.double() + c); + let f = e.double() + e; + let g = b + f; + let h = (r.y + r.z).square() - (b + c); + let i = e - b; let j = r.x.square(); let e2_square = e.double().square(); - r.x = a.double() * &(b - &f); - r.y = g.square() - &(e2_square.double() + &e2_square); - r.z = b4 * &h; + r.x = a.double() * (b - f); + r.y = g.square() - (e2_square.double() + e2_square); + r.z = b4 * h; match B::TWIST_TYPE { - TwistType::M => (i, j.double() + &j, -h), - TwistType::D => (-h, j.double() + &j, i), + TwistType::M => (i, j.double() + j, -h), + TwistType::D => (-h, j.double() + j, i), } } @@ -178,18 +178,18 @@ fn doubling_step(r: &mut G2HomProjective) -> (B::Fp, B::Fp, fn addition_step(r: &mut G2HomProjective, q: &G2Affine) -> (B::Fp, B::Fp, B::Fp) { // Formula for line function when working with // homogeneous projective coordinates, as described in https://eprint.iacr.org/2013/722.pdf. - let theta = r.y - &(q.y * &r.z); - let lambda = r.x - &(q.x * &r.z); + let theta = r.y - (q.y * r.z); + let lambda = r.x - (q.x * r.z); let c = theta.square(); let d = lambda.square(); - let e = lambda * &d; - let f = r.z * &c; - let g = r.x * &d; - let h = e + &f - &g.double(); - r.x = lambda * &h; - r.y = theta * &(g - &h) - &(e * &r.y); + let e = lambda * d; + let f = r.z * c; + let g = r.x * d; + let h = e + f - g.double(); + r.x = lambda * h; + r.y = theta * (g - h) - (e * r.y); r.z *= &e; - let j = theta * &q.x - &(lambda * &q.y); + let j = theta * q.x - (lambda * q.y); match B::TWIST_TYPE { TwistType::M => (j, -theta, lambda), diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs index 3428941a48..f86b671655 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_jacobian.rs @@ -86,7 +86,7 @@ impl GroupAffine

{ } else { // Check that the point is on the curve let y2 = self.y.square(); - let x3b = P::add_b(&((self.x.square() * &self.x) + &P::mul_by_a(&self.x))); + let x3b = P::add_b(&((self.x.square() * self.x) + P::mul_by_a(&self.x))); y2 == x3b } } @@ -122,7 +122,7 @@ impl AffineCurve for GroupAffine

{ /// largest y-coordinate be selected. fn from_x_coordinate(x: Self::BaseField, greatest: bool) -> Option { // Compute x^3 + ax + b - let x3b = P::add_b(&((x.square() * &x) + &P::mul_by_a(&x))); + let x3b = P::add_b(&((x.square() * x) + P::mul_by_a(&x))); x3b.sqrt().map(|y| { let negy = -y; @@ -185,7 +185,7 @@ impl AffineCurve for GroupAffine

{ } else { // Check that the point is on the curve let y2 = self.y.square(); - let x3b = P::add_b(&((self.x.square() * &self.x) + &P::mul_by_a(&self.x))); + let x3b = P::add_b(&((self.x.square() * self.x) + P::mul_by_a(&self.x))); y2 == x3b } } @@ -353,7 +353,7 @@ impl PartialEq for GroupProjective

{ let z1 = self.z.square(); let z2 = other.z.square(); - !(self.x * &z2 != other.x * &z1 || self.y * &(z2 * &other.z) != other.y * &(z1 * &self.z)) + !(self.x * z2 != other.x * z1 || self.y * (z2 * other.z) != other.y * (z1 * self.z)) } } @@ -470,8 +470,8 @@ impl ProjectiveCurve for GroupProjective

{ ) { // tmp := tmp * g.z; g.z := tmp * s = 1/z - let newtmp = tmp * &g.z; - g.z = tmp * &s; + let newtmp = tmp * g.z; + g.z = tmp * s; tmp = newtmp; } #[cfg(not(feature = "parallel"))] @@ -480,7 +480,7 @@ impl ProjectiveCurve for GroupProjective

{ for g in v.iter_mut().filter(|g| !g.is_normalized()) { let z2 = g.z.square(); // 1/z g.x *= &z2; // x/z^2 - g.y *= &(z2 * &g.z); // y/z^3 + g.y *= &(z2 * g.z); // y/z^3 g.z = P::BaseField::one(); // z = 1 } } @@ -492,7 +492,7 @@ impl ProjectiveCurve for GroupProjective

{ v.par_iter_mut().filter(|g| !g.is_normalized()).for_each(|g| { let z2 = g.z.square(); // 1/z g.x *= &z2; // x/z^2 - g.y *= &(z2 * &g.z); // y/z^3 + g.y *= &(z2 * g.z); // y/z^3 g.z = P::BaseField::one(); // z = 1 }); } @@ -518,10 +518,10 @@ impl ProjectiveCurve for GroupProjective

{ let z1z1 = self.z.square(); // U2 = X2*Z1Z1 - let u2 = other.x * &z1z1; + let u2 = other.x * z1z1; // S2 = Y2*Z1*Z1Z1 - let s2 = (other.y * &self.z) * &z1z1; + let s2 = (other.y * self.z) * z1z1; if self.x == u2 && self.y == s2 { // The two points are equal, so we double. @@ -530,7 +530,7 @@ impl ProjectiveCurve for GroupProjective

{ // If we're adding -a and a together, self.z becomes zero as H becomes zero. // H = U2-X1 - let h = u2 - &self.x; + let h = u2 - self.x; // HH = H^2 let hh = h.square(); @@ -541,13 +541,13 @@ impl ProjectiveCurve for GroupProjective

{ i.double_in_place(); // J = H*I - let mut j = h * &i; + let mut j = h * i; // r = 2*(S2-Y1) - let r = (s2 - &self.y).double(); + let r = (s2 - self.y).double(); // V = X1*I - let v = self.x * &i; + let v = self.x * i; // X3 = r^2 - J - 2*V self.x = r.square(); @@ -558,7 +558,7 @@ impl ProjectiveCurve for GroupProjective

{ // Y3 = r*(V-X3)-2*Y1*J j *= &self.y; // J = 2*Y1*J j.double_in_place(); - self.y = v - &self.x; + self.y = v - self.x; self.y *= &r; self.y -= &j; @@ -614,7 +614,7 @@ impl Group for GroupProjective

{ let mut c = b.square(); // D = 2*((X1+B)2-A-C) - let d = ((self.x + &b).square() - &a - &c).double(); + let d = ((self.x + b).square() - a - c).double(); // E = 3*A let old_a = a; @@ -629,13 +629,13 @@ impl Group for GroupProjective

{ self.z.double_in_place(); // X3 = F-2*D - self.x = f - &d - &d; + self.x = f - d - d; // Y3 = E*(D-X3)-8*C c.double_in_place(); c.double_in_place(); c.double_in_place(); - self.y = (d - &self.x) * &e - c; + self.y = (d - self.x) * e - c; } else { // http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l // XX = X1^2 @@ -651,13 +651,13 @@ impl Group for GroupProjective

{ let zz = self.z.square(); // S = 2*((X1+YY)^2-XX-YYYY) - let s = ((self.x + &yy).square() - &xx - &yyyy).double(); + let s = ((self.x + yy).square() - xx - yyyy).double(); // M = 3*XX+a*ZZ^2 - let m = xx + &xx + &xx + &P::mul_by_a(&zz.square()); + let m = xx + xx + xx + P::mul_by_a(&zz.square()); // T = M^2-2*S - let t = m.square() - &s.double(); + let t = m.square() - s.double(); // X3 = T self.x = t; @@ -666,9 +666,9 @@ impl Group for GroupProjective

{ yyyy.double_in_place(); yyyy.double_in_place(); yyyy.double_in_place(); - self.y = m * &(s - &t) - yyyy; + self.y = m * (s - t) - yyyy; // Z3 = (Y1+Z1)^2-YY-ZZ - self.z = (old_y + &self.z).square() - &yy - &zz; + self.z = (old_y + self.z).square() - yy - zz; } } } @@ -722,16 +722,16 @@ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ let z2z2 = other.z.square(); // U1 = X1*Z2Z2 - let u1 = self.x * &z2z2; + let u1 = self.x * z2z2; // U2 = X2*Z1Z1 - let u2 = other.x * &z1z1; + let u2 = other.x * z1z1; // S1 = Y1*Z2*Z2Z2 - let s1 = self.y * &other.z * &z2z2; + let s1 = self.y * other.z * z2z2; // S2 = Y2*Z1*Z1Z1 - let s2 = other.y * &self.z * &z1z1; + let s2 = other.y * self.z * z1z1; if u1 == u2 && s1 == s2 { // The two points are equal, so we double. @@ -740,28 +740,28 @@ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ // If we're adding -a and a together, self.z becomes zero as H becomes zero. // H = U2-U1 - let h = u2 - &u1; + let h = u2 - u1; // I = (2*H)^2 let i = (h.double()).square(); // J = H*I - let j = h * &i; + let j = h * i; // r = 2*(S2-S1) - let r = (s2 - &s1).double(); + let r = (s2 - s1).double(); // V = U1*I - let v = u1 * &i; + let v = u1 * i; // X3 = r^2 - J - 2*V - self.x = r.square() - &j - &(v.double()); + self.x = r.square() - j - (v.double()); // Y3 = r*(V - X3) - 2*S1*J - self.y = r * &(v - &self.x) - (s1 * &j).double(); + self.y = r * (v - self.x) - (s1 * j).double(); // Z3 = ((Z1+Z2)^2 - Z1Z1 - Z2Z2)*H - self.z = ((self.z + &other.z).square() - &z1z1 - &z2z2) * &h; + self.z = ((self.z + other.z).square() - z1z1 - z2z2) * h; } } } @@ -846,10 +846,10 @@ impl From> for GroupAffine

{ let zinv_squared = zinv.square(); // X/Z^2 - let x = p.x * &zinv_squared; + let x = p.x * zinv_squared; // Y/Z^3 - let y = p.y * &(zinv_squared * &zinv); + let y = p.y * (zinv_squared * zinv); GroupAffine::new(x, y, false) } diff --git a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs index 1a6f8167b3..3a3cbe9e27 100644 --- a/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs +++ b/curves/src/templates/short_weierstrass/short_weierstrass_projective.rs @@ -87,7 +87,7 @@ impl GroupAffine

{ } else { // Check that the point is on the curve let y2 = self.y.square(); - let x3b = P::add_b(&((self.x.square() * &self.x) + &P::mul_by_a(&self.x))); + let x3b = P::add_b(&((self.x.square() * self.x) + P::mul_by_a(&self.x))); y2 == x3b } } @@ -120,7 +120,7 @@ impl AffineCurve for GroupAffine

{ /// largest y-coordinate be selected. fn from_x_coordinate(x: Self::BaseField, greatest: bool) -> Option { // Compute x^3 + ax + b - let x3b = P::add_b(&((x.square() * &x) + &P::mul_by_a(&x))); + let x3b = P::add_b(&((x.square() * x) + P::mul_by_a(&x))); x3b.sqrt().map(|y| { let negy = -y; @@ -182,7 +182,7 @@ impl AffineCurve for GroupAffine

{ } else { // Check that the point is on the curve let y2 = self.y.square(); - let x3b = P::add_b(&((self.x.square() * &self.x) + &P::mul_by_a(&self.x))); + let x3b = P::add_b(&((self.x.square() * self.x) + P::mul_by_a(&self.x))); y2 == x3b } } @@ -345,7 +345,7 @@ impl PartialEq for GroupProjective

{ } // x1/z1 == x2/z2 <==> x1 * z2 == x2 * z1 - (self.x * &other.z) == (other.x * &self.z) && (self.y * &other.z) == (other.y * &self.z) + (self.x * other.z) == (other.x * self.z) && (self.y * other.z) == (other.y * self.z) } } @@ -460,8 +460,8 @@ impl ProjectiveCurve for GroupProjective

{ ) { // tmp := tmp * g.z; g.z := tmp * s = 1/z - let newtmp = tmp * &g.z; - g.z = tmp * &s; + let newtmp = tmp * g.z; + g.z = tmp * s; tmp = newtmp; } @@ -482,8 +482,8 @@ impl ProjectiveCurve for GroupProjective

{ self.z = P::BaseField::one(); return; } - let mut v = other.x * &self.z; - let mut u = other.y * &self.z; + let mut v = other.x * self.z; + let mut u = other.y * self.z; if u == self.y && v == self.x { // x1 / z1 == x2 / z2 <==> x1 * z2 == x2 * z1; // Here, z2 = 1, so we have x1 == x2 * z1; @@ -499,17 +499,17 @@ impl ProjectiveCurve for GroupProjective

{ // vv = v2 let vv = v.square(); // vvv = v*vv - let vvv = v * &vv; + let vvv = v * vv; // r = vv*X1 - let r = vv * &self.x; + let r = vv * self.x; // a = uu*Z1-vvv-2*r - let a = uu * &self.z - &vvv - &r.double(); + let a = uu * self.z - vvv - r.double(); // X3 = v*a - self.x = v * &a; + self.x = v * a; // Y3 = u*(R-A)-vvv*Y1 - self.y = u * &(r - &a) - &(vvv * &self.y); + self.y = u * (r - a) - (vvv * self.y); // Z3 = vvv*Z1 - self.z = vvv * &self.z; + self.z = vvv * self.z; } } @@ -549,25 +549,25 @@ impl Group for GroupProjective

{ // ZZ = Z1^2 let zz = self.z.square(); // w = a*ZZ + 3*XX - let w = P::mul_by_a(&zz) + (xx + &xx.double()); + let w = P::mul_by_a(&zz) + (xx + xx.double()); // s = 2*Y1*Z1 - let mut s = self.y * &(self.z); + let mut s = self.y * (self.z); s.double_in_place(); // sss = s^3 let mut sss = s.square(); sss *= &s; // R = Y1*s - let r = self.y * &s; + let r = self.y * s; // RR = R2 let rr = r.square(); // B = (X1+R)^2-XX-RR - let b = (self.x + &r).square() - &xx - &rr; + let b = (self.x + r).square() - xx - rr; // h = w2-2*B - let h = w.square() - &(b + &b); + let h = w.square() - (b + b); // X3 = h*s - self.x = h * &s; + self.x = h * s; // Y3 = w*(B-h)-2*RR - self.y = w * &(b - &h) - &(rr + &rr); + self.y = w * (b - h) - (rr + rr); // Z3 = sss self.z = sss; } @@ -615,31 +615,31 @@ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ self.double_in_place(); } else { // Y1Z2 = Y1*Z2 - let y1z2 = self.y * &other.z; + let y1z2 = self.y * other.z; // X1Z2 = X1*Z2 - let x1z2 = self.x * &other.z; + let x1z2 = self.x * other.z; // Z1Z2 = Z1*Z2 - let z1z2 = self.z * &other.z; + let z1z2 = self.z * other.z; // u = Y2*Z1-Y1Z2 - let u = (self.z * &other.y) - &y1z2; + let u = (self.z * other.y) - y1z2; // uu = u^2 let uu = u.square(); // v = X2*Z1-X1Z2 - let v = (self.z * &other.x) - &x1z2; + let v = (self.z * other.x) - x1z2; // vv = v^2 let vv = v.square(); // vvv = v*vv - let vvv = v * &vv; + let vvv = v * vv; // R = vv*X1Z2 - let r = vv * &x1z2; + let r = vv * x1z2; // A = uu*Z1Z2-vvv-2*R - let a = (uu * &z1z2) - &(vvv + &r + &r); + let a = (uu * z1z2) - (vvv + r + r); // X3 = v*A - self.x = v * &a; + self.x = v * a; // Y3 = u*(R-A)-vvv*Y1Z2 - self.y = ((r - &a) * &u) - &(vvv * &y1z2); + self.y = ((r - a) * u) - (vvv * y1z2); // Z3 = vvv*Z1Z2 - self.z = vvv * &z1z2; + self.z = vvv * z1z2; } } } @@ -718,8 +718,8 @@ impl From> for GroupAffine

{ } else { // Z is nonzero, so it must have an inverse in a field. let z_inv = p.z.inverse().unwrap(); - let x = p.x * &z_inv; - let y = p.y * &z_inv; + let x = p.x * z_inv; + let y = p.y * z_inv; GroupAffine::new(x, y, false) } } diff --git a/curves/src/templates/twisted_edwards_extended/mod.rs b/curves/src/templates/twisted_edwards_extended/mod.rs index 272049232c..b142a91ded 100644 --- a/curves/src/templates/twisted_edwards_extended/mod.rs +++ b/curves/src/templates/twisted_edwards_extended/mod.rs @@ -87,8 +87,8 @@ impl GroupAffine

{ let x2 = self.x.square(); let y2 = self.y.square(); - let lhs = y2 + &P::mul_by_a(&x2); - let rhs = P::BaseField::one() + (P::COEFF_D * &(x2 * &y2)); + let lhs = y2 + P::mul_by_a(&x2); + let rhs = P::BaseField::one() + (P::COEFF_D * (x2 * y2)); lhs == rhs } @@ -121,9 +121,9 @@ impl AffineCurve for GroupAffine

{ // y = sqrt( (a * x^2 - 1) / (d * x^2 - 1) ) let x2 = x.square(); let one = Self::BaseField::one(); - let numerator = P::mul_by_a(&x2) - &one; - let denominator = P::COEFF_D * &x2 - &one; - let y2 = denominator.inverse().map(|denom| denom * &numerator); + let numerator = P::mul_by_a(&x2) - one; + let denominator = P::COEFF_D * x2 - one; + let y2 = denominator.inverse().map(|denom| denom * numerator); y2.and_then(|y2| y2.sqrt()).map(|y| { let negy = -y; let y = if (y < negy) ^ greatest { y } else { negy }; @@ -140,9 +140,9 @@ impl AffineCurve for GroupAffine

{ // x = sqrt( (1 - y^2) / (a - d * y^2) ) let y2 = y.square(); let one = Self::BaseField::one(); - let numerator = one - &y2; - let denominator = P::mul_by_a(&one) - &(P::COEFF_D * &y2); - let x2 = denominator.inverse().map(|denom| denom * &numerator); + let numerator = one - y2; + let denominator = P::mul_by_a(&one) - (P::COEFF_D * y2); + let x2 = denominator.inverse().map(|denom| denom * numerator); x2.and_then(|x2| x2.sqrt()).map(|x| { let negx = -x; let x = if (x < negx) ^ greatest { x } else { negx }; @@ -206,8 +206,8 @@ impl AffineCurve for GroupAffine

{ let x2 = self.x.square(); let y2 = self.y.square(); - let lhs = y2 + &P::mul_by_a(&x2); - let rhs = P::BaseField::one() + (P::COEFF_D * &(x2 * &y2)); + let lhs = y2 + P::mul_by_a(&x2); + let rhs = P::BaseField::one() + (P::COEFF_D * (x2 * y2)); lhs == rhs } @@ -254,18 +254,18 @@ impl<'a, P: Parameters> Add<&'a Self> for GroupAffine

{ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupAffine

{ #[allow(clippy::suspicious_op_assign_impl)] fn add_assign(&mut self, other: &'a Self) { - let y1y2 = self.y * &other.y; - let x1x2 = self.x * &other.x; - let dx1x2y1y2 = P::COEFF_D * &y1y2 * &x1x2; + let y1y2 = self.y * other.y; + let x1x2 = self.x * other.x; + let dx1x2y1y2 = P::COEFF_D * y1y2 * x1x2; - let d1 = P::BaseField::one() + &dx1x2y1y2; - let d2 = P::BaseField::one() - &dx1x2y1y2; + let d1 = P::BaseField::one() + dx1x2y1y2; + let d2 = P::BaseField::one() - dx1x2y1y2; - let x1y2 = self.x * &other.y; - let y1x2 = self.y * &other.x; + let x1y2 = self.x * other.y; + let y1x2 = self.y * other.x; - self.x = (x1y2 + &y1x2) / &d1; - self.y = (y1y2 - &P::mul_by_a(&x1x2)) / &d2; + self.x = (x1y2 + y1x2) / &d1; + self.y = (y1y2 - P::mul_by_a(&x1x2)) / &d2; } } @@ -373,7 +373,7 @@ impl PartialEq for GroupProjective

{ } // x1/z1 == x2/z2 <==> x1 * z2 == x2 * z1 - (self.x * &other.z) == (other.x * &self.z) && (self.y * &other.z) == (other.y * &self.z) + (self.x * other.z) == (other.x * self.z) && (self.y * other.z) == (other.y * self.z) } } @@ -494,8 +494,8 @@ impl ProjectiveCurve for GroupProjective

{ ) { // tmp := tmp * g.z; g.z := tmp * s = 1/z - let newtmp = tmp * &g.z; - g.z = tmp * &s; + let newtmp = tmp * g.z; + g.z = tmp * s; tmp = newtmp; } @@ -511,29 +511,29 @@ impl ProjectiveCurve for GroupProjective

{ #[allow(clippy::many_single_char_names)] fn add_assign_mixed(&mut self, other: &Self::Affine) { // A = X1*X2 - let a = self.x * &other.x; + let a = self.x * other.x; // B = Y1*Y2 - let b = self.y * &other.y; + let b = self.y * other.y; // C = T1*d*T2 - let c = P::COEFF_D * &self.t * &other.x * &other.y; + let c = P::COEFF_D * self.t * other.x * other.y; // D = Z1 let d = self.z; // E = (X1+Y1)*(X2+Y2)-A-B - let e = (self.x + &self.y) * &(other.x + &other.y) - &a - &b; + let e = (self.x + self.y) * (other.x + other.y) - a - b; // F = D-C - let f = d - &c; + let f = d - c; // G = D+C - let g = d + &c; + let g = d + c; // H = B-a*A - let h = b - &P::mul_by_a(&a); + let h = b - P::mul_by_a(&a); // X3 = E*F - self.x = e * &f; + self.x = e * f; // Y3 = G*H - self.y = g * &h; + self.y = g * h; // T3 = E*H - self.t = e * &h; + self.t = e * h; // Z3 = F*G - self.z = f * &g; + self.z = f * g; } fn into_affine(&self) -> GroupAffine

{ @@ -598,40 +598,40 @@ impl<'a, P: Parameters> AddAssign<&'a Self> for GroupProjective

{ // 3.1 Unified Addition in E^e // A = x1 * x2 - let a = self.x * &other.x; + let a = self.x * other.x; // B = y1 * y2 - let b = self.y * &other.y; + let b = self.y * other.y; // C = d * t1 * t2 - let c = P::COEFF_D * &self.t * &other.t; + let c = P::COEFF_D * self.t * other.t; // D = z1 * z2 - let d = self.z * &other.z; + let d = self.z * other.z; // H = B - aA - let h = b - &P::mul_by_a(&a); + let h = b - P::mul_by_a(&a); // E = (x1 + y1) * (x2 + y2) - A - B - let e = (self.x + &self.y) * &(other.x + &other.y) - &a - &b; + let e = (self.x + self.y) * (other.x + other.y) - a - b; // F = D - C - let f = d - &c; + let f = d - c; // G = D + C - let g = d + &c; + let g = d + c; // x3 = E * F - self.x = e * &f; + self.x = e * f; // y3 = G * H - self.y = g * &h; + self.y = g * h; // t3 = E * H - self.t = e * &h; + self.t = e * h; // z3 = F * G - self.z = f * &g; + self.z = f * g; } } @@ -689,7 +689,7 @@ impl MulAssign for GroupProjective

{ // with Z = 1. impl From> for GroupProjective

{ fn from(p: GroupAffine

) -> GroupProjective

{ - Self::new(p.x, p.y, p.x * &p.y, P::BaseField::one()) + Self::new(p.x, p.y, p.x * p.y, P::BaseField::one()) } } @@ -705,8 +705,8 @@ impl From> for GroupAffine

{ } else { // Z is nonzero, so it must have an inverse in a field. let z_inv = p.z.inverse().unwrap(); - let x = p.x * &z_inv; - let y = p.y * &z_inv; + let x = p.x * z_inv; + let y = p.y * z_inv; GroupAffine::new(x, y) } } diff --git a/curves/src/templates/twisted_edwards_extended/tests.rs b/curves/src/templates/twisted_edwards_extended/tests.rs index bb73c46781..34afa98915 100644 --- a/curves/src/templates/twisted_edwards_extended/tests.rs +++ b/curves/src/templates/twisted_edwards_extended/tests.rs @@ -41,9 +41,9 @@ where P: TEModelParameters, { // A = 2 * (a + d) / (a - d) - let a = P::BaseField::one().double() * &(P::COEFF_A + &P::COEFF_D) * &(P::COEFF_A - &P::COEFF_D).inverse().unwrap(); + let a = P::BaseField::one().double() * (P::COEFF_A + P::COEFF_D) * (P::COEFF_A - P::COEFF_D).inverse().unwrap(); // B = 4 / (a - d) - let b = P::BaseField::one().double().double() * &(P::COEFF_A - &P::COEFF_D).inverse().unwrap(); + let b = P::BaseField::one().double().double() * (P::COEFF_A - P::COEFF_D).inverse().unwrap(); assert_eq!(a, P::MontgomeryModelParameters::COEFF_A); assert_eq!(b, P::MontgomeryModelParameters::COEFF_B); diff --git a/curves/src/traits/tests_curve.rs b/curves/src/traits/tests_curve.rs index b1ab163258..34b9611ba1 100644 --- a/curves/src/traits/tests_curve.rs +++ b/curves/src/traits/tests_curve.rs @@ -53,13 +53,13 @@ fn random_addition_test() { let mut tmp = vec![G::zero(); 6]; // (a + b) + c - tmp[0] = (a + &b) + &c; + tmp[0] = (a + b) + c; // a + (b + c) - tmp[1] = a + (b + &c); + tmp[1] = a + (b + c); // (a + c) + b - tmp[2] = (a + &c) + &b; + tmp[2] = (a + c) + b; // Mixed addition @@ -166,7 +166,7 @@ fn random_negation_test() { let s = G::ScalarField::rand(&mut rng); let sneg = -s; - assert!((s + &sneg).is_zero()); + assert!((s + sneg).is_zero()); let mut t1 = r; t1.mul_assign(s); diff --git a/curves/src/traits/tests_group.rs b/curves/src/traits/tests_group.rs index 3fbde63a4c..f717476d0c 100644 --- a/curves/src/traits/tests_group.rs +++ b/curves/src/traits/tests_group.rs @@ -27,38 +27,38 @@ pub fn group_test(a: G, mut b: G) { let zero = G::zero(); let fr_zero = G::ScalarField::zero(); let fr_one = G::ScalarField::one(); - let fr_two = fr_one + &fr_one; + let fr_two = fr_one + fr_one; assert!(zero == zero); assert_eq!(zero.is_zero(), true); assert_eq!(a.mul(fr_one), a); - assert_eq!(a.mul(fr_two), a + &a); + assert_eq!(a.mul(fr_two), a + a); assert_eq!(a.mul(fr_zero), zero); - assert_eq!(a.mul(fr_zero) - &a, -a); - assert_eq!(a.mul(fr_one) - &a, zero); - assert_eq!(a.mul(fr_two) - &a, a); + assert_eq!(a.mul(fr_zero) - a, -a); + assert_eq!(a.mul(fr_one) - a, zero); + assert_eq!(a.mul(fr_two) - a, a); // a == a assert!(a == a); // a + 0 = a - assert_eq!(a + &zero, a); + assert_eq!(a + zero, a); // a - 0 = a - assert_eq!(a - &zero, a); + assert_eq!(a - zero, a); // a - a = 0 - assert_eq!(a - &a, zero); + assert_eq!(a - a, zero); // 0 - a = -a - assert_eq!(zero - &a, -a); + assert_eq!(zero - a, -a); // a.double() = a + a - assert_eq!(a.double(), a + &a); + assert_eq!(a.double(), a + a); // b.double() = b + b - assert_eq!(b.double(), b + &b); + assert_eq!(b.double(), b + b); // a + b = b + a - assert_eq!(a + &b, b + &a); + assert_eq!(a + b, b + a); // a - b = -(b - a) - assert_eq!(a - &b, -(b - &a)); + assert_eq!(a - b, -(b - a)); // (a + b) + a = a + (b + a) - assert_eq!((a + &b) + &a, a + (b + &a)); + assert_eq!((a + b) + a, a + (b + a)); // (a + b).double() = (a + b) + (b + a) - assert_eq!((a + &b).double(), (a + &b) + (b + &a)); + assert_eq!((a + b).double(), (a + b) + (b + a)); // Check that double_in_place and double give the same result let original_b = b; @@ -69,10 +69,10 @@ pub fn group_test(a: G, mut b: G) { let fr_rand2 = G::ScalarField::rand(&mut rng); let a_rand1 = a.mul(fr_rand1); let a_rand2 = a.mul(fr_rand2); - let fr_three = fr_two + &fr_rand1; + let fr_three = fr_two + fr_rand1; let a_two = a.mul(fr_two); assert_eq!(a_two, a.double(), "(a * 2) != a.double()"); - let a_six = a.mul(fr_three * &fr_two); + let a_six = a.mul(fr_three * fr_two); assert_eq!(a_two.mul(fr_three), a_six, "(a * 2) * 3 != a * (2 * 3)"); assert_eq!( @@ -82,12 +82,12 @@ pub fn group_test(a: G, mut b: G) { ); assert_eq!( a_rand2.mul(fr_rand1), - a.mul(fr_rand1 * &fr_rand2), + a.mul(fr_rand1 * fr_rand2), "(a * r2) * r1 != a * (r1 * r2)" ); assert_eq!( a_rand1.mul(fr_rand2), - a.mul(fr_rand1 * &fr_rand2), + a.mul(fr_rand1 * fr_rand2), "(a * r1) * r2 != a * (r1 * r2)" ); } diff --git a/fields/src/fp12_2over3over2.rs b/fields/src/fp12_2over3over2.rs index bc6dff4b18..3898011973 100644 --- a/fields/src/fp12_2over3over2.rs +++ b/fields/src/fp12_2over3over2.rs @@ -101,10 +101,10 @@ impl Fp12

{ let c0 = *c0 + c3; let c1 = c4; - let mut e = self.c0 + &self.c1; + let mut e = self.c0 + self.c1; e.mul_by_01(&c0, &c1); - self.c1 = e - &(a + &b); - self.c0 = a + &Self::mul_fp6_by_nonresidue(&b); + self.c1 = e - (a + b); + self.c0 = a + Self::mul_fp6_by_nonresidue(&b); } pub fn mul_by_014(&mut self, c0: &Fp2>, c1: &Fp2>, c4: &Fp2>) { @@ -135,56 +135,56 @@ impl Fp12

{ let mut z5 = self.c1.c2; // t0 + t1*y = (z0 + z1*y)^2 = a^2 - let mut tmp = z0 * &z1; - let t0 = (z0 + &z1) * &(z0 + &fp2_nr(&z1)) - &tmp - &fp2_nr(&tmp); + let mut tmp = z0 * z1; + let t0 = (z0 + z1) * (z0 + fp2_nr(&z1)) - tmp - fp2_nr(&tmp); let t1 = tmp.double(); // t2 + t3*y = (z2 + z3*y)^2 = b^2 - tmp = z2 * &z3; - let t2 = (z2 + &z3) * &(z2 + &fp2_nr(&z3)) - &tmp - &fp2_nr(&tmp); + tmp = z2 * z3; + let t2 = (z2 + z3) * (z2 + fp2_nr(&z3)) - tmp - fp2_nr(&tmp); let t3 = tmp.double(); // t4 + t5*y = (z4 + z5*y)^2 = c^2 - tmp = z4 * &z5; - let t4 = (z4 + &z5) * &(z4 + &fp2_nr(&z5)) - &tmp - &fp2_nr(&tmp); + tmp = z4 * z5; + let t4 = (z4 + z5) * (z4 + fp2_nr(&z5)) - tmp - fp2_nr(&tmp); let t5 = tmp.double(); // for A // z0 = 3 * t0 - 2 * z0 - z0 = t0 - &z0; - z0 = z0 + &z0; - result.c0.c0 = z0 + &t0; + z0 = t0 - z0; + z0 = z0 + z0; + result.c0.c0 = z0 + t0; // z1 = 3 * t1 + 2 * z1 - z1 = t1 + &z1; - z1 = z1 + &z1; - result.c1.c1 = z1 + &t1; + z1 = t1 + z1; + z1 = z1 + z1; + result.c1.c1 = z1 + t1; // for B // z2 = 3 * (xi * t5) + 2 * z2 tmp = fp2_nr(&t5); - z2 = tmp + &z2; - z2 = z2 + &z2; - result.c1.c0 = z2 + &tmp; + z2 = tmp + z2; + z2 = z2 + z2; + result.c1.c0 = z2 + tmp; // z3 = 3 * t4 - 2 * z3 - z3 = t4 - &z3; - z3 = z3 + &z3; - result.c0.c2 = z3 + &t4; + z3 = t4 - z3; + z3 = z3 + z3; + result.c0.c2 = z3 + t4; // for C // z4 = 3 * t2 - 2 * z4 - z4 = t2 - &z4; - z4 = z4 + &z4; - result.c0.c1 = z4 + &t2; + z4 = t2 - z4; + z4 = z4 + z4; + result.c0.c1 = z4 + t2; // z5 = 3 * t3 + 2 * z5 - z5 = t3 + &z5; - z5 = z5 + &z5; - result.c1.c2 = z5 + &t3; + z5 = t3 + z5; + z5 = z5 + z5; + result.c1.c2 = z5 + t3; result } @@ -434,10 +434,10 @@ impl<'a, P: Fp12Parameters> MulAssign<&'a Self> for Fp12

{ #[inline] #[allow(clippy::suspicious_op_assign_impl)] fn mul_assign(&mut self, other: &Self) { - let v0 = self.c0 * &other.c0; - let v1 = self.c1 * &other.c1; - self.c1 = (self.c0 + &self.c1) * &(other.c0 + &other.c1) - &v0 - &v1; - self.c0 = v0 + &Self::mul_fp6_by_nonresidue(&v1); + let v0 = self.c0 * other.c0; + let v1 = self.c1 * other.c1; + self.c1 = (self.c0 + self.c1) * (other.c0 + other.c1) - v0 - v1; + self.c0 = v0 + Self::mul_fp6_by_nonresidue(&v1); } } diff --git a/fields/src/fp2.rs b/fields/src/fp2.rs index 032fea79d4..0d8a521bb9 100644 --- a/fields/src/fp2.rs +++ b/fields/src/fp2.rs @@ -156,18 +156,18 @@ impl Field for Fp2

{ fn square_in_place(&mut self) -> &mut Self { // v0 = c0 - c1 - let mut v0 = self.c0 - &self.c1; + let mut v0 = self.c0 - self.c1; // v3 = c0 - beta * c1 - let v3 = self.c0 - &P::mul_fp_by_nonresidue(&self.c1); + let v3 = self.c0 - P::mul_fp_by_nonresidue(&self.c1); // v2 = c0 * c1 - let v2 = self.c0 * &self.c1; + let v2 = self.c0 * self.c1; // v0 = (v0 * v3) + v2 v0 *= &v3; v0 += &v2; self.c1 = v2.double(); - self.c0 = v0 + &P::mul_fp_by_nonresidue(&v2); + self.c0 = v0 + P::mul_fp_by_nonresidue(&v2); self } @@ -184,8 +184,8 @@ impl Field for Fp2

{ // v0 = v0 - beta * v1 v0 -= &P::mul_fp_by_nonresidue(&v1); v0.inverse().map(|v1| { - let c0 = self.c0 * &v1; - let c1 = -(self.c1 * &v1); + let c0 = self.c0 * v1; + let c1 = -(self.c1 * v1); Self::new(c0, c1) }) } @@ -232,13 +232,13 @@ where .norm() .sqrt() .expect("We are in the QR case, the norm should have a square root"); - let mut delta = (alpha + &self.c0) * &two_inv; + let mut delta = (alpha + self.c0) * two_inv; if delta.legendre().is_qnr() { delta -= α } let c0 = delta.sqrt().expect("Delta must have a square root"); let c0_inv = c0.inverse().expect("c0 must have an inverse"); - Some(Self::new(c0, self.c1 * &two_inv * &c0_inv)) + Some(Self::new(c0, self.c1 * two_inv * c0_inv)) } } } @@ -406,14 +406,14 @@ impl<'a, P: Fp2Parameters> MulAssign<&'a Self> for Fp2

{ fn mul_assign(&mut self, other: &Self) { // Karatsuba multiplication; // Guide to Pairing-based cryprography, Algorithm 5.16. - let v0 = self.c0 * &other.c0; - let v1 = self.c1 * &other.c1; + let v0 = self.c0 * other.c0; + let v1 = self.c1 * other.c1; self.c1 += &self.c0; - self.c1 *= &(other.c0 + &other.c1); + self.c1 *= &(other.c0 + other.c1); self.c1 -= &v0; self.c1 -= &v1; - self.c0 = v0 + &P::mul_fp_by_nonresidue(&v1); + self.c0 = v0 + P::mul_fp_by_nonresidue(&v1); } } diff --git a/fields/src/fp3.rs b/fields/src/fp3.rs index cd5916c29a..91745eae1d 100644 --- a/fields/src/fp3.rs +++ b/fields/src/fp3.rs @@ -195,16 +195,16 @@ impl Field for Fp3

{ let c = self.c2; let s0 = a.square(); - let ab = a * &b; - let s1 = ab + &ab; - let s2 = (a - &b + &c).square(); - let bc = b * &c; - let s3 = bc + &bc; + let ab = a * b; + let s1 = ab + ab; + let s2 = (a - b + c).square(); + let bc = b * c; + let s3 = bc + bc; let s4 = c.square(); - self.c0 = s0 + &P::mul_fp_by_nonresidue(&s3); - self.c1 = s1 + &P::mul_fp_by_nonresidue(&s4); - self.c2 = s1 + &s2 + &s3 - &s0 - &s4; + self.c0 = s0 + P::mul_fp_by_nonresidue(&s3); + self.c1 = s1 + P::mul_fp_by_nonresidue(&s4); + self.c2 = s1 + s2 + s3 - s0 - s4; self } @@ -469,16 +469,16 @@ impl<'a, P: Fp3Parameters> MulAssign<&'a Self> for Fp3

{ let e = self.c1; let f = self.c2; - let ad = d * &a; - let be = e * &b; - let cf = f * &c; + let ad = d * a; + let be = e * b; + let cf = f * c; - let x = (e + &f) * &(b + &c) - &be - &cf; - let y = (d + &e) * &(a + &b) - &ad - &be; - let z = (d + &f) * &(a + &c) - &ad + &be - &cf; + let x = (e + f) * (b + c) - be - cf; + let y = (d + e) * (a + b) - ad - be; + let z = (d + f) * (a + c) - ad + be - cf; - self.c0 = ad + &P::mul_fp_by_nonresidue(&x); - self.c1 = y + &P::mul_fp_by_nonresidue(&cf); + self.c0 = ad + P::mul_fp_by_nonresidue(&x); + self.c1 = y + P::mul_fp_by_nonresidue(&cf); self.c2 = z; } } diff --git a/fields/src/fp6_2over3.rs b/fields/src/fp6_2over3.rs index 44e00355e7..a4af3ebeaa 100644 --- a/fields/src/fp6_2over3.rs +++ b/fields/src/fp6_2over3.rs @@ -103,12 +103,12 @@ impl Fp6

{ let mut tmp2 = x4; tmp2.mul_assign(&::NONRESIDUE); - self.c0.c0 = x0 * &z0 + (tmp1 * &z5) + (tmp2 * &z4); - self.c0.c1 = x0 * &z1 + (x3 * &z3) + (tmp2 * &z5); - self.c0.c2 = x0 * &z2 + (x3 * &z4) + (x4 * &z3); - self.c1.c0 = x0 * &z3 + (x3 * &z0) + (tmp2 * &z2); - self.c1.c1 = x0 * &z4 + (x3 * &z1) + (x4 * &z0); - self.c1.c2 = x0 * &z5 + (x3 * &z2) + (x4 * &z1); + self.c0.c0 = x0 * z0 + (tmp1 * z5) + (tmp2 * z4); + self.c0.c1 = x0 * z1 + (x3 * z3) + (tmp2 * z5); + self.c0.c2 = x0 * z2 + (x3 * z4) + (x4 * z3); + self.c1.c0 = x0 * z3 + (x3 * z0) + (tmp2 * z2); + self.c1.c1 = x0 * z4 + (x3 * z1) + (x4 * z0); + self.c1.c2 = x0 * z5 + (x3 * z2) + (x4 * z1); } pub fn mul_by_014( @@ -133,12 +133,12 @@ impl Fp6

{ let mut tmp2 = x4; tmp2.mul_assign(&::NONRESIDUE); - self.c0.c0 = x0 * &z0 + (tmp1 * &z2) + (tmp2 * &z4); - self.c0.c1 = x0 * &z1 + (x1 * &z0) + (tmp2 * &z5); - self.c0.c2 = x0 * &z2 + (x1 * &z1) + (x4 * &z3); - self.c1.c0 = x0 * &z3 + (tmp1 * &z5) + (tmp2 * &z2); - self.c1.c1 = x0 * &z4 + (x1 * &z3) + (x4 * &z0); - self.c1.c2 = x0 * &z5 + (x1 * &z4) + (x4 * &z1); + self.c0.c0 = x0 * z0 + (tmp1 * z2) + (tmp2 * z4); + self.c0.c1 = x0 * z1 + (x1 * z0) + (tmp2 * z5); + self.c0.c2 = x0 * z2 + (x1 * z1) + (x4 * z3); + self.c1.c0 = x0 * z3 + (tmp1 * z5) + (tmp2 * z2); + self.c1.c1 = x0 * z4 + (x1 * z3) + (x4 * z0); + self.c1.c2 = x0 * z5 + (x1 * z4) + (x4 * z1); } /// Multiply by quadratic nonresidue v. @@ -258,10 +258,10 @@ impl Field for Fp6

{ // Fields.pdf; Section 3 (Complex) let a = self.c0; let b = self.c1; - let ab_add = a + &b; - let ab_mul = a * &b; + let ab_add = a + b; + let ab_mul = a * b; - let c0 = ab_add * &(a + &Self::mul_by_nonresidue(&b)) - &ab_mul - &Self::mul_by_nonresidue(&ab_mul); + let c0 = ab_add * (a + Self::mul_by_nonresidue(&b)) - ab_mul - Self::mul_by_nonresidue(&ab_mul); let c1 = ab_mul.double(); self.c0 = c0; @@ -280,11 +280,11 @@ impl Field for Fp6

{ let b = self.c1; let t1 = b.square(); - let t0 = a.square() - &Self::mul_by_nonresidue(&t1); + let t0 = a.square() - Self::mul_by_nonresidue(&t1); let t2 = t0.inverse().unwrap(); - let c0 = a * &t2; - let c1 = (b * &t2).neg(); + let c0 = a * t2; + let c1 = (b * t2).neg(); Some(Self::new(c0, c1)) } @@ -466,12 +466,12 @@ impl<'a, P: Fp6Parameters> MulAssign<&'a Self> for Fp6

{ let a1 = other.c0; let b1 = other.c1; - let a0a1 = a0 * &a1; - let b0b1 = b0 * &b1; + let a0a1 = a0 * a1; + let b0b1 = b0 * b1; let beta_b0b1 = Self::mul_by_nonresidue(&b0b1); - let c0 = a0a1 + &beta_b0b1; - let c1 = (a0 + &b0) * &(a1 + &b1) - &a0a1 - &b0b1; + let c0 = a0a1 + beta_b0b1; + let c1 = (a0 + b0) * (a1 + b1) - a0a1 - b0b1; self.c0 = c0; self.c1 = c1; diff --git a/fields/src/fp6_3over2.rs b/fields/src/fp6_3over2.rs index 3f4f9abb8c..e2cd16acb9 100644 --- a/fields/src/fp6_3over2.rs +++ b/fields/src/fp6_3over2.rs @@ -231,14 +231,14 @@ impl Field for Fp6

{ fn square_in_place(&mut self) -> &mut Self { let s0 = self.c0.square(); - let s1 = (self.c0 * &self.c1).double(); - let s2 = (self.c0 - &self.c1 + &self.c2).square(); - let s3 = (self.c1 * &self.c2).double(); + let s1 = (self.c0 * self.c1).double(); + let s2 = (self.c0 - self.c1 + self.c2).square(); + let s3 = (self.c1 * self.c2).double(); let s4 = self.c2.square(); - self.c0 = s0 + &P::mul_fp2_by_nonresidue(&s3); - self.c1 = s1 + &P::mul_fp2_by_nonresidue(&s4); - self.c2 = s1 + &s2 + &s3 - &s0 - &s4; + self.c0 = s0 + P::mul_fp2_by_nonresidue(&s3); + self.c1 = s1 + P::mul_fp2_by_nonresidue(&s4); + self.c2 = s1 + s2 + s3 - s0 - s4; self } @@ -283,7 +283,7 @@ impl Field for Fp6

{ tmp1.add_assign(tmp2); match tmp1.inverse() { - Some(t) => Some(Self::new(t * &c0, t * &c1, t * &c2)), + Some(t) => Some(Self::new(t * c0, t * c1, t * c2)), None => None, } } @@ -403,13 +403,13 @@ impl<'a, P: Fp6Parameters> SubAssign<&'a Self> for Fp6

{ impl<'a, P: Fp6Parameters> MulAssign<&'a Self> for Fp6

{ #[inline] fn mul_assign(&mut self, other: &Self) { - let v0 = self.c0 * &other.c0; - let v1 = self.c1 * &other.c1; - let v2 = self.c2 * &other.c2; + let v0 = self.c0 * other.c0; + let v1 = self.c1 * other.c1; + let v2 = self.c2 * other.c2; - let c0 = P::mul_fp2_by_nonresidue(&((self.c1 + &self.c2) * &(other.c1 + &other.c2) - &v1 - &v2)) + &v0; - let c1 = (self.c0 + &self.c1) * &(other.c0 + &other.c1) - &v0 - &v1 + &P::mul_fp2_by_nonresidue(&v2); - let c2 = (self.c0 + &self.c2) * &(other.c0 + &other.c2) - &v0 - &v2 + &v1; + let c0 = P::mul_fp2_by_nonresidue(&((self.c1 + self.c2) * (other.c1 + other.c2) - v1 - v2)) + v0; + let c1 = (self.c0 + self.c1) * (other.c0 + other.c1) - v0 - v1 + P::mul_fp2_by_nonresidue(&v2); + let c2 = (self.c0 + self.c2) * (other.c0 + other.c2) - v0 - v2 + v1; self.c0 = c0; self.c1 = c1; diff --git a/fields/src/lib.rs b/fields/src/lib.rs index 575164b50b..c1cf37115d 100644 --- a/fields/src/lib.rs +++ b/fields/src/lib.rs @@ -117,7 +117,7 @@ pub fn batch_inversion(v: &mut [F]) { { // tmp := tmp * f; f := tmp * s = 1/f let new_tmp = tmp * *f; - *f = tmp * &s; + *f = tmp * s; tmp = new_tmp; } } diff --git a/fields/src/macros.rs b/fields/src/macros.rs index d61f62bc46..bc8045cba9 100644 --- a/fields/src/macros.rs +++ b/fields/src/macros.rs @@ -111,7 +111,7 @@ macro_rules! sqrt_impl { let mut z = $Self::qnr_to_t(); let mut w = $self.pow($P::T_MINUS_ONE_DIV_TWO); let mut x = w * $self; - let mut b = x * &w; + let mut b = x * w; let mut v = $P::TWO_ADICITY as usize; // t = self^t diff --git a/fields/src/tests_field.rs b/fields/src/tests_field.rs index de681e9652..a37f39280b 100644 --- a/fields/src/tests_field.rs +++ b/fields/src/tests_field.rs @@ -41,11 +41,11 @@ fn random_addition_tests(rng: &mut R) { let b = F::rand(rng); let c = F::rand(rng); - let t0 = (a + &b) + &c; // (a + b) + c + let t0 = (a + b) + c; // (a + b) + c - let t1 = (a + &c) + &b; // (a + c) + b + let t1 = (a + c) + b; // (a + c) + b - let t2 = (b + &c) + &a; // (b + c) + a + let t2 = (b + c) + a; // (b + c) + a assert_eq!(t0, t1); assert_eq!(t1, t2); @@ -57,7 +57,7 @@ fn random_subtraction_tests(rng: &mut R) { let a = F::rand(rng); let b = F::rand(rng); - let t0 = a - &b; // (a - b) + let t0 = a - b; // (a - b) let mut t1 = b; // (b - a) t1 -= &a; @@ -164,8 +164,8 @@ fn random_expansion_tests(rng: &mut R) { let b = F::rand(rng); let c = F::rand(rng); - let t0 = (a + &b) * &c; - let t2 = a * &c + (b * &c); + let t0 = (a + b) * c; + let t2 = a * c + (b * c); assert_eq!(t0, t2); } @@ -193,7 +193,7 @@ fn random_field_tests() { // Multiplication by zero { - let a = F::rand(&mut rng) * &F::zero(); + let a = F::rand(&mut rng) * F::zero(); assert!(a.is_zero()); } @@ -280,9 +280,9 @@ pub fn field_test(a: F, b: F) { assert!(one == one); assert_eq!(one.is_zero(), false); assert_eq!(one.is_one(), true); - assert_eq!(zero + &one, one); + assert_eq!(zero + one, one); - let two = one + &one; + let two = one + one; assert!(two == two); assert_ne!(zero, two); assert_ne!(one, two); @@ -290,46 +290,46 @@ pub fn field_test(a: F, b: F) { // a == a assert!(a == a); // a + 0 = a - assert_eq!(a + &zero, a); + assert_eq!(a + zero, a); // a - 0 = a - assert_eq!(a - &zero, a); + assert_eq!(a - zero, a); // a - a = 0 - assert_eq!(a - &a, zero); + assert_eq!(a - a, zero); // 0 - a = -a - assert_eq!(zero - &a, -a); + assert_eq!(zero - a, -a); // a.double() = a + a - assert_eq!(a.double(), a + &a); + assert_eq!(a.double(), a + a); // b.double() = b + b - assert_eq!(b.double(), b + &b); + assert_eq!(b.double(), b + b); // a + b = b + a - assert_eq!(a + &b, b + &a); + assert_eq!(a + b, b + a); // a - b = -(b - a) - assert_eq!(a - &b, -(b - &a)); + assert_eq!(a - b, -(b - a)); // (a + b) + a = a + (b + a) - assert_eq!((a + &b) + &a, a + (b + &a)); + assert_eq!((a + b) + a, a + (b + a)); // (a + b).double() = (a + b) + (b + a) - assert_eq!((a + &b).double(), (a + &b) + (b + &a)); + assert_eq!((a + b).double(), (a + b) + (b + a)); // a * 0 = 0 - assert_eq!(a * &zero, zero); + assert_eq!(a * zero, zero); // a * 1 = a - assert_eq!(a * &one, a); + assert_eq!(a * one, a); // a * 2 = a.double() - assert_eq!(a * &two, a.double()); + assert_eq!(a * two, a.double()); // a * a^-1 = 1 - assert_eq!(a * &a.inverse().unwrap(), one); + assert_eq!(a * a.inverse().unwrap(), one); // a * a = a^2 - assert_eq!(a * &a, a.square()); + assert_eq!(a * a, a.square()); // a * a * a = a^3 - assert_eq!(a * &(a * &a), a.pow([0x3, 0x0, 0x0, 0x0])); + assert_eq!(a * (a * a), a.pow([0x3, 0x0, 0x0, 0x0])); // a * b = b * a - assert_eq!(a * &b, b * &a); + assert_eq!(a * b, b * a); // (a * b) * a = a * (b * a) - assert_eq!((a * &b) * &a, a * &(b * &a)); + assert_eq!((a * b) * a, a * (b * a)); // (a + b)^2 = a^2 + 2ab + b^2 - assert_eq!((a + &b).square(), a.square() + ((a * &b) + (a * &b)) + &b.square()); + assert_eq!((a + b).square(), a.square() + ((a * b) + (a * b)) + b.square()); // (a - b)^2 = (-(b - a))^2 - assert_eq!((a - &b).square(), (-(b - &a)).square()); + assert_eq!((a - b).square(), (-(b - a)).square()); random_field_tests::(); } diff --git a/gadgets/src/algorithms/snark/groth16.rs b/gadgets/src/algorithms/snark/groth16.rs index ba793b77b1..728af63dac 100644 --- a/gadgets/src/algorithms/snark/groth16.rs +++ b/gadgets/src/algorithms/snark/groth16.rs @@ -457,7 +457,7 @@ mod test { let new_entry = { let (input_1_val, input_1_var) = variables[i]; let (input_2_val, input_2_var) = variables[i + 1]; - let result_val = input_1_val.and_then(|input_1| input_2_val.map(|input_2| input_1 * &input_2)); + let result_val = input_1_val.and_then(|input_1| input_2_val.map(|input_2| input_1 * input_2)); let result_var = cs.alloc( || format!("Result {}", i), || result_val.ok_or(SynthesisError::AssignmentMissing), diff --git a/gadgets/src/algorithms/snark/tests.rs b/gadgets/src/algorithms/snark/tests.rs index 648534e155..725f320d86 100644 --- a/gadgets/src/algorithms/snark/tests.rs +++ b/gadgets/src/algorithms/snark/tests.rs @@ -60,7 +60,7 @@ impl ConstraintSynthesizer for Bench { let new_entry = { let (input_1_val, input_1_var) = variables[i]; let (input_2_val, input_2_var) = variables[i + 1]; - let result_val = input_1_val.and_then(|input_1| input_2_val.map(|input_2| input_1 * &input_2)); + let result_val = input_1_val.and_then(|input_1| input_2_val.map(|input_2| input_1 * input_2)); let result_var = cs.alloc( || format!("Result {}", i), || result_val.ok_or(SynthesisError::AssignmentMissing), diff --git a/gadgets/src/bits/boolean.rs b/gadgets/src/bits/boolean.rs index 62eaa92cb2..7002b9be6f 100644 --- a/gadgets/src/bits/boolean.rs +++ b/gadgets/src/bits/boolean.rs @@ -364,7 +364,7 @@ fn cond_select_helper>( cs.enforce( || "conditionally_select", |_| cond.lc(one, F::one()), - |lc| (&first_var - &second_var) + lc, + |lc| (first_var - &second_var) + lc, |lc| ConstraintVariable::from(result_var) - &second_var + lc, ); @@ -877,8 +877,8 @@ impl ConditionalEqGadget for Boolean { } else { cs.enforce( || "conditional_equals", - |lc| difference + &lc, - |lc| condition.lc(one, F::one()) + &lc, + |lc| difference + lc, + |lc| condition.lc(one, F::one()) + lc, |lc| lc, ); Ok(()) diff --git a/gadgets/src/curves/bls12_377.rs b/gadgets/src/curves/bls12_377.rs index 7abd4b68c3..4760fa505c 100644 --- a/gadgets/src/curves/bls12_377.rs +++ b/gadgets/src/curves/bls12_377.rs @@ -127,7 +127,7 @@ mod test { assert_eq!(gadget_b.y.get_value().unwrap(), b_affine.y); // Check addition - let ab = a + &b; + let ab = a + b; let ab_affine = ab.into_affine(); let gadget_ab = gadget_a.add(&mut cs.ns(|| "ab"), &gadget_b).unwrap(); let gadget_ba = gadget_b.add(&mut cs.ns(|| "ba"), &gadget_a).unwrap(); @@ -153,7 +153,7 @@ mod test { // Check mul_bits let scalar = Fr::rand(&mut rng); - let native_result = aa.mul(scalar) + &b; + let native_result = aa.mul(scalar) + b; let native_result = native_result.into_affine(); let mut scalar: Vec = BitIteratorBE::new(scalar.into_repr()).collect(); @@ -192,7 +192,7 @@ mod test { assert_eq!(gadget_b.x.get_value().unwrap(), b_affine.x); assert_eq!(gadget_b.y.get_value().unwrap(), b_affine.y); - let ab = a + &b; + let ab = a + b; let ab_affine = ab.into_affine(); let gadget_ab = gadget_a.add(&mut cs.ns(|| "ab"), &gadget_b).unwrap(); let gadget_ba = gadget_b.add(&mut cs.ns(|| "ba"), &gadget_a).unwrap(); diff --git a/gadgets/src/curves/templates/bls12/affine.rs b/gadgets/src/curves/templates/bls12/affine.rs index f80e8bd6b0..d3c8256302 100644 --- a/gadgets/src/curves/templates/bls12/affine.rs +++ b/gadgets/src/curves/templates/bls12/affine.rs @@ -164,14 +164,14 @@ where let inv = x2_minus_x1.inverse(cs.ns(|| "compute inv"))?; let lambda = FG::alloc(cs.ns(|| "lambda"), || { - Ok(y2_minus_y1.get_value().get()? * &inv.get_value().get()?) + Ok(y2_minus_y1.get_value().get()? * inv.get_value().get()?) })?; let x_3 = FG::alloc(&mut cs.ns(|| "x_3"), || { let lambda_val = lambda.get_value().get()?; let x1 = self.x.get_value().get()?; let x2 = other.x.get_value().get()?; - Ok((lambda_val.square() - &x1) - &x2) + Ok((lambda_val.square() - x1) - x2) })?; let y_3 = FG::alloc(&mut cs.ns(|| "y_3"), || { @@ -179,7 +179,7 @@ where let x_1 = self.x.get_value().get()?; let y_1 = self.y.get_value().get()?; let x_3 = x_3.get_value().get()?; - Ok(lambda_val * &(x_1 - &x_3) - &y_1) + Ok(lambda_val * (x_1 - x_3) - y_1) })?; // Check lambda @@ -241,14 +241,14 @@ where let inv = x2_minus_x1.inverse(cs.ns(|| "compute inv"))?; let lambda = FG::alloc(cs.ns(|| "lambda"), || { - Ok(y2_minus_y1.get_value().get()? * &inv.get_value().get()?) + Ok(y2_minus_y1.get_value().get()? * inv.get_value().get()?) })?; let x_3 = FG::alloc(&mut cs.ns(|| "x_3"), || { let lambda_val = lambda.get_value().get()?; let x1 = self.x.get_value().get()?; let x2 = other_x; - Ok((lambda_val.square() - &x1) - &x2) + Ok((lambda_val.square() - x1) - x2) })?; let y_3 = FG::alloc(&mut cs.ns(|| "y_3"), || { @@ -256,7 +256,7 @@ where let x_1 = self.x.get_value().get()?; let y_1 = self.y.get_value().get()?; let x_3 = x_3.get_value().get()?; - Ok(lambda_val * &(x_1 - &x_3) - &y_1) + Ok(lambda_val * (x_1 - x_3) - y_1) })?; // Check lambda @@ -284,7 +284,7 @@ where let one = P::BaseField::one(); let two = one.double(); - let three = two + &one; + let three = two + one; let three_x_squared = x_squared.mul_by_constant(cs.ns(|| "3 * x^2"), &three)?; let three_x_squared_plus_a = three_x_squared.add_constant(cs.ns(|| "3 * x^2 + a"), &a)?; @@ -293,7 +293,7 @@ where let lambda = FG::alloc(cs.ns(|| "lambda"), || { let y_doubled_inv = two_y.get_value().get()?.inverse().get()?; - Ok(three_x_squared_plus_a.get_value().get()? * &y_doubled_inv) + Ok(three_x_squared_plus_a.get_value().get()? * y_doubled_inv) })?; // Check lambda diff --git a/gadgets/src/curves/templates/bls12/g2.rs b/gadgets/src/curves/templates/bls12/g2.rs index ffa046fc39..0430c7bff0 100644 --- a/gadgets/src/curves/templates/bls12/g2.rs +++ b/gadgets/src/curves/templates/bls12/g2.rs @@ -159,7 +159,7 @@ impl AllocGadget,

::Fp> projective_coeffs .iter() .zip(z_s) - .map(|((x, y, _), z_inv)| (*x * &z_inv, *y * &z_inv)) + .map(|((x, y, _), z_inv)| (*x * z_inv, *y * z_inv)) .collect::>() })?; @@ -195,7 +195,7 @@ impl AllocGadget,

::Fp> projective_coeffs .iter() .zip(z_s) - .map(|((x, y, _), z_inv)| (*x * &z_inv, *y * &z_inv)) + .map(|((x, y, _), z_inv)| (*x * z_inv, *y * z_inv)) .collect::>() })?; @@ -231,7 +231,7 @@ impl AllocGadget,

::Fp> projective_coeffs .iter() .zip(z_s) - .map(|((x, y, _), z_inv)| (*x * &z_inv, *y * &z_inv)) + .map(|((x, y, _), z_inv)| (*x * z_inv, *y * z_inv)) .collect::>() })?; diff --git a/gadgets/src/curves/templates/twisted_edwards/mod.rs b/gadgets/src/curves/templates/twisted_edwards/mod.rs index 1c6302d891..ffe40d008f 100644 --- a/gadgets/src/curves/templates/twisted_edwards/mod.rs +++ b/gadgets/src/curves/templates/twisted_edwards/mod.rs @@ -77,8 +77,8 @@ mod montgomery_affine_impl { } else if p.x == P::BaseField::zero() { GroupAffine::new(P::BaseField::zero(), P::BaseField::zero()) } else { - let u = (P::BaseField::one() + &p.y) * &(P::BaseField::one() - &p.y).inverse().unwrap(); - let v = u * &p.x.inverse().unwrap(); + let u = (P::BaseField::one() + p.y) * (P::BaseField::one() - p.y).inverse().unwrap(); + let v = u * p.x.inverse().unwrap(); GroupAffine::new(u, v) }; @@ -162,10 +162,10 @@ mod montgomery_affine_impl { // Compute x'' = B*lambda^2 - A - x - x' let xprime = FG::alloc(cs.ns(|| "xprime"), || { Ok( - lambda.get_value().get()?.square() * &P::MontgomeryModelParameters::COEFF_B - - &P::MontgomeryModelParameters::COEFF_A - - &self.x.get_value().get()? - - &other.x.get_value().get()?, + lambda.get_value().get()?.square() * P::MontgomeryModelParameters::COEFF_B + - P::MontgomeryModelParameters::COEFF_A + - self.x.get_value().get()? + - other.x.get_value().get()?, ) })?; @@ -180,7 +180,7 @@ mod montgomery_affine_impl { let yprime = FG::alloc(cs.ns(|| "yprime"), || { Ok(-(self.y.get_value().get()? - + (lambda.get_value().get()? * &(xprime.get_value().get()? - &self.x.get_value().get()?)))) + + (lambda.get_value().get()? * (xprime.get_value().get()? - self.x.get_value().get()?)))) })?; let xres = self.x.sub(cs.ns(|| "xres"), &xprime)?; @@ -303,9 +303,9 @@ mod affine_impl { // Compute x3 = (v0 + v1) / (1 + v2) let x3 = FG::alloc(&mut cs.ns(|| "x3"), || { - let t0 = v0.get_value().get()? + &v1.get_value().get()?; - let t1 = P::BaseField::one() + &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = v0.get_value().get()? + v1.get_value().get()?; + let t1 = P::BaseField::one() + v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one = P::BaseField::one(); @@ -315,9 +315,9 @@ mod affine_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; - let t1 = P::BaseField::one() - &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = u.get_value().get()? + (a * v0.get_value().get()?) - v1.get_value().get()?; + let t1 = P::BaseField::one() - v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one_minus_v2 = v2 @@ -348,7 +348,7 @@ mod affine_impl { .x .mul_by_constant(cs.ns(|| "-A * x1"), &a.neg())? .add(cs.ns(|| "-A * x1 + y1"), &self.y)?; - let u2 = other_x + &other_y; + let u2 = other_x + other_y; let u = u1.mul_by_constant(cs.ns(|| "(-A * x1 + y1) * (x2 + y2)"), &u2)?; @@ -365,9 +365,9 @@ mod affine_impl { // Compute x3 = (v0 + v1) / (1 + v2) let x3 = FG::alloc(&mut cs.ns(|| "x3"), || { - let t0 = v0.get_value().get()? + &v1.get_value().get()?; - let t1 = P::BaseField::one() + &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = v0.get_value().get()? + v1.get_value().get()?; + let t1 = P::BaseField::one() + v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one = P::BaseField::one(); @@ -377,9 +377,9 @@ mod affine_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; - let t1 = P::BaseField::one() - &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = u.get_value().get()? + (a * v0.get_value().get()?) - v1.get_value().get()?; + let t1 = P::BaseField::one() - v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one_minus_v2 = v2 @@ -408,8 +408,8 @@ mod affine_impl { // Compute x3 = (2xy) / (ax^2 + y^2) let x3 = FG::alloc(&mut cs.ns(|| "x3"), || { let t0 = xy.get_value().get()?.double(); - let t1 = a * &x2.get_value().get()? + &y2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t1 = a * x2.get_value().get()? + y2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let a_x2_plus_y2 = a_x2.add(cs.ns(|| "v2 + 1"), &y2)?; @@ -419,10 +419,10 @@ mod affine_impl { // Compute y3 = (y^2 - ax^2) / (2 - ax^2 - y^2) let two = P::BaseField::one().double(); let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let a_x2 = a * &x2.get_value().get()?; - let t0 = y2.get_value().get()? - &a_x2; - let t1 = two - &a_x2 - &y2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let a_x2 = a * x2.get_value().get()?; + let t0 = y2.get_value().get()? - a_x2; + let t1 = two - a_x2 - y2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let y2_minus_a_x2 = y2.sub(cs.ns(|| "y^2 - ax^2"), &a_x2)?; let two_minus_ax2_minus_y2 = a_x2 @@ -693,9 +693,9 @@ mod projective_impl { // Compute x3 = (v0 + v1) / (1 + v2) let x3 = FG::alloc(&mut cs.ns(|| "x3"), || { - let t0 = v0.get_value().get()? + &v1.get_value().get()?; - let t1 = P::BaseField::one() + &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = v0.get_value().get()? + v1.get_value().get()?; + let t1 = P::BaseField::one() + v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one = P::BaseField::one(); @@ -705,9 +705,9 @@ mod projective_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; - let t1 = P::BaseField::one() - &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = u.get_value().get()? + (a * v0.get_value().get()?) - v1.get_value().get()?; + let t1 = P::BaseField::one() - v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one_minus_v2 = v2 @@ -739,7 +739,7 @@ mod projective_impl { .x .mul_by_constant(cs.ns(|| "-A * x1"), &a.neg())? .add(cs.ns(|| "-A * x1 + y1"), &self.y)?; - let u2 = other_x + &other_y; + let u2 = other_x + other_y; let u = u1.mul_by_constant(cs.ns(|| "(-A * x1 + y1) * (x2 + y2)"), &u2)?; @@ -756,9 +756,9 @@ mod projective_impl { // Compute x3 = (v0 + v1) / (1 + v2) let x3 = FG::alloc(&mut cs.ns(|| "x3"), || { - let t0 = v0.get_value().get()? + &v1.get_value().get()?; - let t1 = P::BaseField::one() + &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = v0.get_value().get()? + v1.get_value().get()?; + let t1 = P::BaseField::one() + v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one = P::BaseField::one(); @@ -768,9 +768,9 @@ mod projective_impl { // Compute y3 = (U + a * v0 - v1) / (1 - v2) let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let t0 = u.get_value().get()? + (a * &v0.get_value().get()?) - &v1.get_value().get()?; - let t1 = P::BaseField::one() - &v2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t0 = u.get_value().get()? + (a * v0.get_value().get()?) - v1.get_value().get()?; + let t1 = P::BaseField::one() - v2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let one_minus_v2 = v2 @@ -799,8 +799,8 @@ mod projective_impl { // Compute x3 = (2xy) / (ax^2 + y^2) let x3 = FG::alloc(&mut cs.ns(|| "x3"), || { let t0 = xy.get_value().get()?.double(); - let t1 = a * &x2.get_value().get()? + &y2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let t1 = a * x2.get_value().get()? + y2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let a_x2_plus_y2 = a_x2.add(cs.ns(|| "v2 + 1"), &y2)?; @@ -810,10 +810,10 @@ mod projective_impl { // Compute y3 = (y^2 - ax^2) / (2 - ax^2 - y^2) let two = P::BaseField::one().double(); let y3 = FG::alloc(&mut cs.ns(|| "y3"), || { - let a_x2 = a * &x2.get_value().get()?; - let t0 = y2.get_value().get()? - &a_x2; - let t1 = two - &a_x2 - &y2.get_value().get()?; - Ok(t0 * &t1.inverse().get()?) + let a_x2 = a * x2.get_value().get()?; + let t0 = y2.get_value().get()? - a_x2; + let t1 = two - a_x2 - y2.get_value().get()?; + Ok(t0 * t1.inverse().get()?) })?; let y2_minus_a_x2 = y2.sub(cs.ns(|| "y^2 - ax^2"), &a_x2)?; let two_minus_ax2_minus_y2 = a_x2 @@ -851,7 +851,7 @@ mod projective_impl { if bits_base_powers.len() == 2 { let bits = [bits_base_powers[0].0, bits_base_powers[1].0]; let base_powers = [bits_base_powers[0].1, bits_base_powers[1].1]; - let table = [zero, base_powers[0], base_powers[1], base_powers[0] + &base_powers[1]]; + let table = [zero, base_powers[0], base_powers[1], base_powers[0] + base_powers[1]]; let adder: Self = two_bit_lookup_helper(cs.ns(|| "two bit lookup"), bits, table)?; *self = , F>>::add(self, &mut cs.ns(|| "Add"), &adder)?; } else if bits_base_powers.len() == 1 { @@ -889,10 +889,10 @@ mod projective_impl { let bits = [bits_base_powers[0].0, bits_base_powers[1].0]; let base_powers = [bits_base_powers[0].1, bits_base_powers[1].1]; let table = [ - base_powers[0] + &base_powers[1], - base_powers[0].neg() + &base_powers[1], - base_powers[0] + &base_powers[1].neg(), - base_powers[0].neg() + &base_powers[1].neg(), + base_powers[0] + base_powers[1], + base_powers[0].neg() + base_powers[1], + base_powers[0] + base_powers[1].neg(), + base_powers[0].neg() + base_powers[1].neg(), ]; let adder: Self = two_bit_lookup_helper(cs.ns(|| "two bit lookup"), bits, table)?; *self = , F>>::add(self, &mut cs.ns(|| "Add"), &adder)?; @@ -1024,17 +1024,17 @@ mod projective_impl { .conditionally_add_constant( cs.ns(|| format!("add bool 01 in window {}, {}", segment_i, i)), &bits[0], - x_coeffs[1] - &x_coeffs[0], + x_coeffs[1] - x_coeffs[0], )? .conditionally_add_constant( cs.ns(|| format!("add bool 10 in window {}, {}", segment_i, i)), &bits[1], - x_coeffs[2] - &x_coeffs[0], + x_coeffs[2] - x_coeffs[0], )? .conditionally_add_constant( cs.ns(|| format!("add bool 11 in window {}, {}", segment_i, i)), &precomp, - x_coeffs[3] - &x_coeffs[2] - &x_coeffs[1] + &x_coeffs[0], + x_coeffs[3] - x_coeffs[2] - x_coeffs[1] + x_coeffs[0], )?; let y = FG::three_bit_cond_neg_lookup( diff --git a/gadgets/src/curves/tests_curve.rs b/gadgets/src/curves/tests_curve.rs index 04237c13e5..408bb574f2 100644 --- a/gadgets/src/curves/tests_curve.rs +++ b/gadgets/src/curves/tests_curve.rs @@ -43,7 +43,7 @@ fn bls12_377_gadget_bilinearity_test() { let a: G1Projective = G1Projective::prime_subgroup_generator(); let b: G2Projective = G2Projective::prime_subgroup_generator(); - let s: Fr = Fr::one() + &Fr::one(); + let s: Fr = Fr::one() + Fr::one(); let sa = a.mul(s); let sb = b.mul(s); diff --git a/gadgets/src/curves/tests_field.rs b/gadgets/src/curves/tests_field.rs index 0e5537e801..b4587e0c37 100644 --- a/gadgets/src/curves/tests_field.rs +++ b/gadgets/src/curves/tests_field.rs @@ -93,31 +93,22 @@ fn field_test, CS: Constra let a_b = a.add(cs.ns(|| "a_plus_b"), &b).unwrap(); let b_a = b.add(cs.ns(|| "b_plus_a"), &a).unwrap(); assert_eq!(a_b, b_a); - assert_eq!(a_b.get_value().unwrap(), a_native + &b_native); + assert_eq!(a_b.get_value().unwrap(), a_native + b_native); a_b.enforce_equal(&mut cs.ns(|| "a+b == b+a"), &b_a).unwrap(); // (a + b) + a = a + (b + a) let ab_a = a_b.add(cs.ns(|| "a_b_plus_a"), &a).unwrap(); let a_ba = a.add(cs.ns(|| "a_plus_b_a"), &b_a).unwrap(); assert_eq!(ab_a, a_ba); - assert_eq!(ab_a.get_value().unwrap(), a_native + &b_native + &a_native); + assert_eq!(ab_a.get_value().unwrap(), a_native + b_native + a_native); ab_a.enforce_equal(&mut cs.ns(|| "a+b + a == a+ b+a"), &a_ba).unwrap(); let b_times_a_plus_b = a_b.mul(cs.ns(|| "b * (a + b)"), &b).unwrap(); let b_times_b_plus_a = b_a.mul(cs.ns(|| "b * (b + a)"), &b).unwrap(); assert_eq!(b_times_b_plus_a, b_times_a_plus_b); - assert_eq!( - b_times_a_plus_b.get_value().unwrap(), - b_native * &(b_native + &a_native) - ); - assert_eq!( - b_times_a_plus_b.get_value().unwrap(), - (b_native + &a_native) * &b_native - ); - assert_eq!( - b_times_a_plus_b.get_value().unwrap(), - (a_native + &b_native) * &b_native - ); + assert_eq!(b_times_a_plus_b.get_value().unwrap(), b_native * (b_native + a_native)); + assert_eq!(b_times_a_plus_b.get_value().unwrap(), (b_native + a_native) * b_native); + assert_eq!(b_times_a_plus_b.get_value().unwrap(), (a_native + b_native) * b_native); b_times_b_plus_a .enforce_equal(&mut cs.ns(|| "b*(a+b) == b * (b+a)"), &b_times_a_plus_b) .unwrap(); @@ -129,20 +120,20 @@ fn field_test, CS: Constra assert_eq!(a.mul(cs.ns(|| "a_times_one"), &one).unwrap(), a); assert_eq!( a.mul(cs.ns(|| "a_times_one2"), &one).unwrap().get_value().unwrap(), - a_native * &one_native + a_native * one_native ); // a * b = b * a let ab = a.mul(cs.ns(|| "a_times_b"), &b).unwrap(); let ba = b.mul(cs.ns(|| "b_times_a"), &a).unwrap(); assert_eq!(ab, ba); - assert_eq!(ab.get_value().unwrap(), a_native * &b_native); + assert_eq!(ab.get_value().unwrap(), a_native * b_native); // (a * b) * a = a * (b * a) let ab_a = ab.mul(cs.ns(|| "ab_times_a"), &a).unwrap(); let a_ba = a.mul(cs.ns(|| "a_times_ba"), &ba).unwrap(); assert_eq!(ab_a, a_ba); - assert_eq!(ab_a.get_value().unwrap(), a_native * &b_native * &a_native); + assert_eq!(ab_a.get_value().unwrap(), a_native * b_native * a_native); let aa = a.mul(cs.ns(|| "a * a"), &a).unwrap(); let a_squared = a.square(cs.ns(|| "a^2")).unwrap(); @@ -173,7 +164,7 @@ fn field_test, CS: Constra // a * a * a = a^3 let bits = BitIteratorBE::new([0x3]).map(Boolean::constant).collect::>(); assert_eq!( - a_native * &(a_native * &a_native), + a_native * (a_native * a_native), a.pow(cs.ns(|| "test_pow"), &bits).unwrap().get_value().unwrap() ); @@ -204,7 +195,7 @@ fn field_test, CS: Constra let ab_true = a .conditionally_add_constant(cs.ns(|| "Add bool with coeff true"), &Boolean::constant(true), b_native) .unwrap(); - assert_eq!(ab_true.get_value().unwrap(), a_native + &b_native); + assert_eq!(ab_true.get_value().unwrap(), a_native + b_native); } fn random_frobenius_tests, CS: ConstraintSystem>( diff --git a/gadgets/src/fields/fp12.rs b/gadgets/src/fields/fp12.rs index 03678c9ddf..1cb1729ae0 100644 --- a/gadgets/src/fields/fp12.rs +++ b/gadgets/src/fields/fp12.rs @@ -157,7 +157,7 @@ where // t0 + t1*y = (z0 + z1*y)^2 = a^2 let tmp = z0.mul(cs.ns(|| "first mul"), &z1)?; let t0 = { - // (z0 + &z1) * &(z0 + (fp2_nr * &z1)) - &tmp - &(tmp * &fp2_nr); + // (z0 + z1) * (z0 + (fp2_nr * z1)) - tmp - (tmp * fp2_nr); let mut cs = cs.ns(|| "t0"); let tmp1 = z0.add(cs.ns(|| "tmp1"), &z1)?; let tmp2 = z1 @@ -173,7 +173,7 @@ where // t2 + t3*y = (z2 + z3*y)^2 = b^2 let tmp = z2.mul(cs.ns(|| "second mul"), &z3)?; let t2 = { - // (z2 + &z3) * &(z2 + (fp2_nr * &z3)) - &tmp - &(tmp * &fp2_nr); + // (z2 + z3) * (z2 + (fp2_nr * z3)) - tmp - (tmp * fp2_nr); let mut cs = cs.ns(|| "t2"); let tmp1 = z2.add(cs.ns(|| "tmp1"), &z3)?; let tmp2 = z3 @@ -189,7 +189,7 @@ where // t4 + t5*y = (z4 + z5*y)^2 = c^2 let tmp = z4.mul(cs.ns(|| "third mul"), &z5)?; let t4 = { - // (z4 + &z5) * &(z4 + (fp2_nr * &z5)) - &tmp - &(tmp * &fp2_nr); + // (z4 + z5) * (z4 + (fp2_nr * z5)) - tmp - (tmp * fp2_nr); let mut cs = cs.ns(|| "t4"); let tmp1 = z4.add(cs.ns(|| "tmp1"), &z5)?; let tmp2 = z5 diff --git a/gadgets/src/fields/fp2.rs b/gadgets/src/fields/fp2.rs index ac5624c6bb..83393c6a36 100644 --- a/gadgets/src/fields/fp2.rs +++ b/gadgets/src/fields/fp2.rs @@ -218,7 +218,7 @@ impl, F: PrimeField> FieldGadget, F> for Fp2Gadg let non_residue_c1 = self.c1.mul_by_constant(cs.ns(|| "non_residue * a1"), &P::NONRESIDUE)?; let a0_plus_non_residue_c1 = self.c0.add(cs.ns(|| "a0 + non_residue * a1"), &non_residue_c1)?; let one_plus_non_residue_v0 = - v0.mul_by_constant(cs.ns(|| "1 + non_residue * v0"), &(P::Fp::one() + &P::NONRESIDUE))?; + v0.mul_by_constant(cs.ns(|| "1 + non_residue * v0"), &(P::Fp::one() + P::NONRESIDUE))?; let c0 = a0_plus_a1 .mul(cs.ns(|| "(a0 + a1) * (a0 + non_residue * a1)"), &a0_plus_non_residue_c1)? @@ -252,7 +252,7 @@ impl, F: PrimeField> FieldGadget, F> for Fp2Gadg .mul_by_constant_in_place(cs.ns(|| "non_residue * a1"), &P::NONRESIDUE)?; let a0_plus_non_residue_c1 = self.c0.add(cs.ns(|| "a0 + non_residue * a1"), &self.c1)?; let one_plus_non_residue_v0 = - v0.mul_by_constant(cs.ns(|| "1 + non_residue * v0"), &(P::Fp::one() + &P::NONRESIDUE))?; + v0.mul_by_constant(cs.ns(|| "1 + non_residue * v0"), &(P::Fp::one() + P::NONRESIDUE))?; self.c0 = a0_plus_a1 .mul(cs.ns(|| "(a0 + a1) * (a0 + non_residue * a1)"), &a0_plus_non_residue_c1)? @@ -296,7 +296,7 @@ impl, F: PrimeField> FieldGadget, F> for Fp2Gadg let one = P::Fp::one(); let rhs = v1 - .mul_by_constant_in_place(cs.ns(|| "(1 - nonresidue) * v1"), &(one - &P::NONRESIDUE))? + .mul_by_constant_in_place(cs.ns(|| "(1 - nonresidue) * v1"), &(one - P::NONRESIDUE))? .add_constant_in_place(cs.ns(|| "add one"), &one)?; a0_plus_a1.mul_equals(cs.ns(|| "inv_constraint_2"), &b0_plus_b1, rhs)?; Ok(inverse) @@ -394,7 +394,7 @@ impl, F: PrimeField> FieldGadget, F> for Fp2Gadg let (a0, a1) = (&self.c0, &self.c1); let (b0, b1) = (fe.c0, fe.c1); let mut v0 = a0.mul_by_constant(&mut cs.ns(|| "v0"), &b0)?; - let beta_v1 = a1.mul_by_constant(&mut cs.ns(|| "v1"), &(b1 * &P::NONRESIDUE))?; + let beta_v1 = a1.mul_by_constant(&mut cs.ns(|| "v1"), &(b1 * P::NONRESIDUE))?; v0.add_in_place(&mut cs.ns(|| "c0"), &beta_v1)?; let c0 = v0; diff --git a/gadgets/src/fields/fp6_3over2.rs b/gadgets/src/fields/fp6_3over2.rs index fff6e820eb..79114077e2 100644 --- a/gadgets/src/fields/fp6_3over2.rs +++ b/gadgets/src/fields/fp6_3over2.rs @@ -316,7 +316,7 @@ where let (two_inverse, six_inverse) = { let two = ::Fp::one().double(); - let six = two.double() + &two; + let six = two.double() + two; let mut two_and_six = [two, six]; batch_inversion(&mut two_and_six); @@ -420,7 +420,7 @@ where let (two_inverse, six_inverse) = { let two = ::Fp::one().double(); - let six = two.double() + &two; + let six = two.double() + two; let mut two_and_six = [two, six]; batch_inversion(&mut two_and_six); @@ -525,7 +525,7 @@ where .c0 .add(v1_cs.ns(|| "a0 + a1"), &self.c1)? .add(v1_cs.ns(|| "a0 + a1 + a2"), &self.c2)?; - let b0_plus_b1_plus_b2 = other.c0 + &other.c1 + &other.c2; + let b0_plus_b1_plus_b2 = other.c0 + other.c1 + other.c2; a0_plus_a1_plus_a2 .mul_by_constant_in_place(v1_cs.ns(|| "(a0 + a1 + a2)*(b0 + b1 + b2)"), &b0_plus_b1_plus_b2)?; @@ -539,7 +539,7 @@ where .c0 .sub(v2_cs.ns(|| "sub1"), &self.c1)? .add(v2_cs.ns(|| "add2"), &self.c2)?; - let b0_minus_b1_plus_b2 = other.c0 - &other.c1 + &other.c2; + let b0_minus_b1_plus_b2 = other.c0 - other.c1 + other.c2; a0_minus_a1_plus_a2 .mul_by_constant_in_place(v2_cs.ns(|| "(a0 - a1 + a2)*(b0 - b1 + b2)"), &b0_minus_b1_plus_b2)?; a0_minus_a1_plus_a2 @@ -557,7 +557,7 @@ where let b1_double = other.c1.double(); let b2_quad = other.c2.double().double(); - let b0_plus_2_b1_plus_4_b2 = other.c0 + &b1_double + &b2_quad; + let b0_plus_2_b1_plus_4_b2 = other.c0 + b1_double + b2_quad; a0_plus_2_a1_plus_4_a2.mul_by_constant_in_place( v3_cs.ns(|| "(a0 + 2a1 + 4a2)*(b0 + 2b1 + 4b2)"), @@ -571,7 +571,7 @@ where let (two_inverse, six_inverse) = { let two = ::Fp::one().double(); - let six = two.double() + &two; + let six = two.double() + two; let mut two_and_six = [two, six]; batch_inversion(&mut two_and_six); diff --git a/gadgets/src/nonnative/allocated_nonnative_field_mul_result_var.rs b/gadgets/src/nonnative/allocated_nonnative_field_mul_result_var.rs index 67380be248..f6d5e06f6f 100644 --- a/gadgets/src/nonnative/allocated_nonnative_field_mul_result_var.rs +++ b/gadgets/src/nonnative/allocated_nonnative_field_mul_result_var.rs @@ -63,7 +63,7 @@ impl AllocatedNonNativeFieldMulR limbs.resize(2 * field_parameters.num_limbs - 1, FpGadget::::zero(cs)?); limbs.reverse(); - let prod_of_num_of_additions = src.num_of_additions_over_normal_form + &BaseField::one(); + let prod_of_num_of_additions = src.num_of_additions_over_normal_form + BaseField::one(); Ok(Self { limbs, @@ -131,7 +131,7 @@ impl AllocatedNonNativeFieldMulR }; // Step 2: Compute surfeit - let surfeit = overhead!(self.prod_of_num_of_additions + &BaseField::one()) + 1 + 1; + let surfeit = overhead!(self.prod_of_num_of_additions + BaseField::one()) + 1 + 1; // Step 3: Allocate k let k_bits = { @@ -224,8 +224,8 @@ impl AllocatedNonNativeFieldMulR let mut kp_plus_r_gadget = Self { limbs: prod_limbs, - prod_of_num_of_additions: (p_gadget.num_of_additions_over_normal_form + &BaseField::one()) - * &(k_gadget.num_of_additions_over_normal_form + &BaseField::one()), + prod_of_num_of_additions: (p_gadget.num_of_additions_over_normal_form + BaseField::one()) + * (k_gadget.num_of_additions_over_normal_form + BaseField::one()), target_phantom: PhantomData, }; @@ -260,7 +260,7 @@ impl AllocatedNonNativeFieldMulR Ok(Self { limbs: new_limbs, - prod_of_num_of_additions: self.prod_of_num_of_additions + &other.prod_of_num_of_additions, + prod_of_num_of_additions: self.prod_of_num_of_additions + other.prod_of_num_of_additions, target_phantom: PhantomData, }) } @@ -291,7 +291,7 @@ impl AllocatedNonNativeFieldMulR Ok(Self { limbs: new_limbs, - prod_of_num_of_additions: self.prod_of_num_of_additions + &BaseField::one(), + prod_of_num_of_additions: self.prod_of_num_of_additions + BaseField::one(), target_phantom: PhantomData, }) } diff --git a/gadgets/src/nonnative/allocated_nonnative_field_var.rs b/gadgets/src/nonnative/allocated_nonnative_field_var.rs index 943bfa980d..84bee820dc 100644 --- a/gadgets/src/nonnative/allocated_nonnative_field_var.rs +++ b/gadgets/src/nonnative/allocated_nonnative_field_var.rs @@ -71,7 +71,7 @@ impl AllocatedNonNativeFieldVar< // This is because 2^{(params.bits_per_limb)} might indeed be larger than the target field's prime. base_repr.muln((params.bits_per_limb - 1) as u32); let mut base: TargetField = TargetField::from_repr(base_repr).unwrap(); - base = base + &base; + base = base + base; let mut result = TargetField::zero(); let mut power = TargetField::one(); @@ -88,7 +88,7 @@ impl AllocatedNonNativeFieldVar< cur.double_in_place(); } - result += &(val * &power); + result += &(val * power); power *= &base; } @@ -207,14 +207,14 @@ impl AllocatedNonNativeFieldVar< ); // Step 1: Reduce the `other` if needed - let mut surfeit = overhead!(other.num_of_additions_over_normal_form + &BaseField::one()) + 1; + let mut surfeit = overhead!(other.num_of_additions_over_normal_form + BaseField::one()) + 1; let mut other = other.clone(); if (surfeit + params.bits_per_limb > BaseField::size_in_bits() - 1) || (surfeit + (TargetField::size_in_bits() - params.bits_per_limb * (params.num_limbs - 1)) > BaseField::size_in_bits() - 1) { Reducer::reduce(cs, &mut other)?; - surfeit = overhead!(other.num_of_additions_over_normal_form + &BaseField::one()) + 1; + surfeit = overhead!(other.num_of_additions_over_normal_form + BaseField::one()) + 1; } // Step 2: Construct the padding @@ -248,14 +248,14 @@ impl AllocatedNonNativeFieldVar< .enumerate() { if i != 0 { - let temp = pad_non_top_limb + &*pad_to_kp_limb; + let temp = pad_non_top_limb + *pad_to_kp_limb; limbs.push( this_limb .add_constant(cs.ns(|| format!("add_constant_{}", i)), &temp)? .sub(cs.ns(|| format!("sub_{}", i)), &other_limb)?, ); } else { - let temp = pad_top_limb + &*pad_to_kp_limb; + let temp = pad_top_limb + *pad_to_kp_limb; limbs.push( this_limb .add_constant(cs.ns(|| format!("add_constant_{}", i)), &temp)? @@ -267,8 +267,8 @@ impl AllocatedNonNativeFieldVar< let result = AllocatedNonNativeFieldVar:: { limbs, num_of_additions_over_normal_form: self.num_of_additions_over_normal_form - + (other.num_of_additions_over_normal_form + &BaseField::one()) - + (other.num_of_additions_over_normal_form + &BaseField::one()), + + (other.num_of_additions_over_normal_form + BaseField::one()) + + (other.num_of_additions_over_normal_form + BaseField::one()), is_in_the_normal_form: false, target_phantom: PhantomData, }; @@ -457,8 +457,8 @@ impl AllocatedNonNativeFieldVar< Ok(AllocatedNonNativeFieldMulResultVar { limbs: prod_limbs, - prod_of_num_of_additions: (self_reduced.num_of_additions_over_normal_form + &BaseField::one()) - * &(other_reduced.num_of_additions_over_normal_form + &BaseField::one()), + prod_of_num_of_additions: (self_reduced.num_of_additions_over_normal_form + BaseField::one()) + * (other_reduced.num_of_additions_over_normal_form + BaseField::one()), target_phantom: PhantomData, }) } @@ -517,7 +517,7 @@ impl AllocatedNonNativeFieldVar< Ok(bigint_to_basefield::(&(delta_bigint / p_bigint))) })?; - let surfeit = overhead!(delta.num_of_additions_over_normal_form + &BaseField::one()) + 1; + let surfeit = overhead!(delta.num_of_additions_over_normal_form + BaseField::one()) + 1; Reducer::::limb_to_bits_be(&mut cs.ns(|| "limb_to_bits"), &k_gadget, surfeit)?; // Step 4: Compute k * p diff --git a/gadgets/src/nonnative/reduce.rs b/gadgets/src/nonnative/reduce.rs index c072cd958b..9f867b3dc8 100644 --- a/gadgets/src/nonnative/reduce.rs +++ b/gadgets/src/nonnative/reduce.rs @@ -75,7 +75,7 @@ pub fn bigint_to_basefield(bigint: &BigUint) -> BaseField for byte in bytes.iter().rev() { let bytes_basefield = BaseField::from(*byte as u128); - val += &(cur * &bytes_basefield); + val += &(cur * bytes_basefield); cur *= &basefield_256; } @@ -165,7 +165,7 @@ impl Reducer 2 * field_parameters.bits_per_limb + surfeit + 1 { Ok(()) @@ -195,8 +195,8 @@ impl Reducer::BigInteger::from( @@ -303,7 +303,7 @@ impl Reducer::alloc(cs.ns(|| "alloc a * b"), || Ok(a_times_b_expected)).unwrap(); @@ -115,7 +115,7 @@ fn edge_cases_test::one(cs.ns(|| "one")).unwrap(); let a_native = TargetField::rand(rng); - let minus_a_native = TargetField::zero() - &a_native; + let minus_a_native = TargetField::zero() - a_native; let a = NonNativeFieldVar::::alloc(cs.ns(|| "alloc_a"), || Ok(a_native)).unwrap(); let a_plus_zero = a.add(cs.ns(|| "a_plus_zero"), &zero).unwrap(); @@ -202,11 +202,11 @@ fn distribution_law_test< let b_native = TargetField::rand(rng); let c_native = TargetField::rand(rng); - let a_plus_b_native = a_native + &b_native; - let a_times_c_native = a_native * &c_native; - let b_times_c_native = b_native * &c_native; - let a_plus_b_times_c_native = a_plus_b_native * &c_native; - let a_times_c_plus_b_times_c_native = a_times_c_native + &b_times_c_native; + let a_plus_b_native = a_native + b_native; + let a_times_c_native = a_native * c_native; + let b_times_c_native = b_native * c_native; + let a_plus_b_times_c_native = a_plus_b_native * c_native; + let a_times_c_plus_b_times_c_native = a_times_c_native + b_times_c_native; assert!( a_plus_b_times_c_native.eq(&a_times_c_plus_b_times_c_native), @@ -363,7 +363,7 @@ fn mul_and_add_stress_test< ) .unwrap(); - num_native = num_native * &next_mul_native + &next_add_native; + num_native = num_native * next_mul_native + next_add_native; num = num.mul(cs.ns(|| format!("num_mul_next_{}", i)), &next_mul).unwrap(); num = num.add(cs.ns(|| format!("num_add_next_{}", i)), &next_add).unwrap(); @@ -398,7 +398,7 @@ fn square_mul_add_stress_test< ) .unwrap(); - num_native = num_native * &num_native * &next_mul_native + &next_add_native; + num_native = num_native * num_native * next_mul_native + next_add_native; let num_squared = num.mul(cs.ns(|| format!("num_squared_{}", i)), &num).unwrap(); let num_squared_times_next_mul = num_squared @@ -422,7 +422,7 @@ fn double_stress_test_1::alloc(cs.ns(|| "initial num"), || Ok(num_native)).unwrap(); for i in 0..TEST_COUNT { // double - num_native = num_native + &num_native; + num_native = num_native + num_native; num = num.double(cs.ns(|| format!("num_double_{}", i))).unwrap(); assert!(num.value().unwrap().eq(&num_native)); // square - let num_square_native = num_native * &num_native; + let num_square_native = num_native * num_native; let num_square = num.mul(cs.ns(|| format!("num_squared_{}", i)), &num).unwrap(); assert!(num_square.value().unwrap().eq(&num_square_native)); } @@ -459,13 +459,13 @@ fn double_stress_test_3::alloc(cs.ns(|| "initial num"), || Ok(num_native)).unwrap(); for i in 0..TEST_COUNT { // double - num_native = num_native + &num_native; + num_native = num_native + num_native; num = num.double(cs.ns(|| format!("num_double_{}", i))).unwrap(); assert!(num.value().unwrap().eq(&num_native)); // square - let num_square_native = num_native * &num_native; + let num_square_native = num_native * num_native; let num_square = num.mul(cs.ns(|| format!("num_squared_{}", i)), &num).unwrap(); let num_square_native_gadget = NonNativeFieldVar::::alloc( cs.ns(|| format!("repetition_{}: alloc_native num", i)), diff --git a/gadgets/tests/nonnative/to_constraint_field_test.rs b/gadgets/tests/nonnative/to_constraint_field_test.rs index 2fd7d5d811..d8cdefbcb7 100644 --- a/gadgets/tests/nonnative/to_constraint_field_test.rs +++ b/gadgets/tests/nonnative/to_constraint_field_test.rs @@ -30,7 +30,7 @@ // let a = NonNativeFieldVar::Constant(F::from(12u8)); // let b = NonNativeFieldVar::::alloc(cs.ns(|| "alloc"), || Ok(F::from(6u8))).unwrap(); // -// let b2 = &b + &b; +// let b2 = &b + b; // let b2 = b.double(cs.ns(|| "b_plus_b")).unwrap(); // // let a_to_constraint_field = a.to_constraint_field().unwrap(); diff --git a/marlin/src/ahp/ahp.rs b/marlin/src/ahp/ahp.rs index 2ae1a79d9c..6aabe98b35 100644 --- a/marlin/src/ahp/ahp.rs +++ b/marlin/src/ahp/ahp.rs @@ -180,8 +180,8 @@ impl AHPForR1CS { .evaluate_all_lagrange_coefficients(beta) .into_iter() .zip(public_input) - .map(|(l, x)| l * &x) - .fold(F::zero(), |x, y| x + &y); + .map(|(l, x)| l * x) + .fold(F::zero(), |x, y| x + y); #[rustfmt::skip] let outer_sumcheck = LinearCombination::new( @@ -189,14 +189,14 @@ impl AHPForR1CS { vec![ (F::one(), "mask_poly".into()), - (r_alpha_at_beta * &(eta_a + (eta_c * &z_b_at_beta)), "z_a".into()), - (r_alpha_at_beta * &eta_b * &z_b_at_beta, LCTerm::One), + (r_alpha_at_beta * (eta_a + (eta_c * z_b_at_beta)), "z_a".into()), + (r_alpha_at_beta * eta_b * z_b_at_beta, LCTerm::One), - (-t_at_beta * &v_X_at_beta, "w".into()), - (-t_at_beta * &x_at_beta, LCTerm::One), + (-t_at_beta * v_X_at_beta, "w".into()), + (-t_at_beta * x_at_beta, LCTerm::One), (-v_H_at_beta, "h_1".into()), - (-beta * &g_1_at_beta, LCTerm::One), + (-beta * g_1_at_beta, LCTerm::One), ], ); debug_assert!(evals.get_lc_eval(&outer_sumcheck, beta)?.is_zero()); @@ -207,7 +207,7 @@ impl AHPForR1CS { linear_combinations.push(outer_sumcheck); // Inner sumcheck: - let beta_alpha = beta * α + let beta_alpha = beta * alpha; let g_2 = LinearCombination::new("g_2", vec![(F::one(), "g_2")]); let a_denom = LinearCombination::new("a_denom", vec![ @@ -239,14 +239,14 @@ impl AHPForR1CS { let v_K_at_gamma = domain_k.evaluate_vanishing_polynomial(gamma); let mut a = LinearCombination::new("a_poly", vec![ - (eta_a * &b_denom_at_gamma * &c_denom_at_gamma, "a_val"), - (eta_b * &a_denom_at_gamma * &c_denom_at_gamma, "b_val"), - (eta_c * &b_denom_at_gamma * &a_denom_at_gamma, "c_val"), + (eta_a * b_denom_at_gamma * c_denom_at_gamma, "a_val"), + (eta_b * a_denom_at_gamma * c_denom_at_gamma, "b_val"), + (eta_c * b_denom_at_gamma * a_denom_at_gamma, "c_val"), ]); - a *= v_H_at_alpha * &v_H_at_beta; - let b_at_gamma = a_denom_at_gamma * &b_denom_at_gamma * &c_denom_at_gamma; - let b_expr_at_gamma = b_at_gamma * &(gamma * &g_2_at_gamma + (t_at_beta / &k_size)); + a *= v_H_at_alpha * v_H_at_beta; + let b_at_gamma = a_denom_at_gamma * b_denom_at_gamma * c_denom_at_gamma; + let b_expr_at_gamma = b_at_gamma * (gamma * g_2_at_gamma + (t_at_beta / &k_size)); a -= &LinearCombination::new("b_expr", vec![(b_expr_at_gamma, LCTerm::One)]); a -= &LinearCombination::new("h_2", vec![(v_K_at_gamma, "h_2")]); @@ -314,7 +314,7 @@ impl>> EvaluationsProvider for Vec { impl UnnormalizedBivariateLagrangePoly for EvaluationDomain { fn eval_unnormalized_bivariate_lagrange_poly(&self, x: F, y: F) -> F { if x != y { - (self.evaluate_vanishing_polynomial(x) - &self.evaluate_vanishing_polynomial(y)) / &(x - &y) + (self.evaluate_vanishing_polynomial(x) - self.evaluate_vanishing_polynomial(y)) / &(x - y) } else { - self.size_as_field_element * &x.pow(&[(self.size() - 1) as u64]) + self.size_as_field_element * x.pow(&[(self.size() - 1) as u64]) } } fn batch_eval_unnormalized_bivariate_lagrange_poly_with_diff_inputs(&self, x: F) -> Vec { let vanish_x = self.evaluate_vanishing_polynomial(x); - let mut inverses: Vec = self.elements().map(|y| x - &y).collect(); + let mut inverses: Vec = self.elements().map(|y| x - y).collect(); batch_inversion(&mut inverses); cfg_iter_mut!(inverses).for_each(|denominator| *denominator *= &vanish_x); @@ -351,7 +351,7 @@ impl UnnormalizedBivariateLagrangePoly for EvaluationDomain } fn batch_eval_unnormalized_bivariate_lagrange_poly_with_same_inputs(&self) -> Vec { - let mut elems: Vec = self.elements().map(|e| e * &self.size_as_field_element).collect(); + let mut elems: Vec = self.elements().map(|e| e * self.size_as_field_element).collect(); elems[1..].reverse(); elems } @@ -405,13 +405,13 @@ mod tests { for eval in domain.elements().map(|e| poly.evaluate(e)) { sum += &eval; } - let first = poly.coeffs[0] * &size_as_fe; - let last = *poly.coeffs.last().unwrap() * &size_as_fe; + let first = poly.coeffs[0] * size_as_fe; + let last = *poly.coeffs.last().unwrap() * size_as_fe; println!("sum: {:?}", sum); println!("a_0: {:?}", first); println!("a_n: {:?}", last); - println!("first + last: {:?}\n", first + &last); - assert_eq!(sum, first + &last); + println!("first + last: {:?}\n", first + last); + assert_eq!(sum, first + last); } #[test] diff --git a/marlin/src/ahp/prover/prover.rs b/marlin/src/ahp/prover/prover.rs index 63a1692b68..62b2c40ff4 100644 --- a/marlin/src/ahp/prover/prover.rs +++ b/marlin/src/ahp/prover/prover.rs @@ -234,7 +234,7 @@ impl AHPForR1CS { if k % ratio == 0 { F::zero() } else { - w_extended[k - (k / ratio) - 1] - &x_evals[k] + w_extended[k - (k / ratio) - 1] - x_evals[k] } }) .collect(); @@ -313,7 +313,7 @@ impl AHPForR1CS { for (r, row) in matrix.iter().enumerate() { for (coeff, c) in row.iter() { let index = domain_h.reindex_by_subdomain(input_domain, *c); - t_evals_on_h[index] += &(*eta * coeff * &r_alpha_x_on_h[r]); + t_evals_on_h[index] += &(*eta * coeff * r_alpha_x_on_h[r]); } } } @@ -515,19 +515,19 @@ impl AHPForR1CS { let mut inverses_c = Vec::with_capacity(domain_k.size()); for i in 0..domain_k.size() { - inverses_a.push((beta - &a_star.evals_on_K.row[i]) * &(alpha - &a_star.evals_on_K.col[i])); - inverses_b.push((beta - &b_star.evals_on_K.row[i]) * &(alpha - &b_star.evals_on_K.col[i])); - inverses_c.push((beta - &c_star.evals_on_K.row[i]) * &(alpha - &c_star.evals_on_K.col[i])); + inverses_a.push((beta - a_star.evals_on_K.row[i]) * (alpha - a_star.evals_on_K.col[i])); + inverses_b.push((beta - b_star.evals_on_K.row[i]) * (alpha - b_star.evals_on_K.col[i])); + inverses_c.push((beta - c_star.evals_on_K.row[i]) * (alpha - c_star.evals_on_K.col[i])); } batch_inversion(&mut inverses_a); batch_inversion(&mut inverses_b); batch_inversion(&mut inverses_c); for i in 0..domain_k.size() { - let t = eta_a * &a_star.evals_on_K.val[i] * &inverses_a[i] - + (eta_b * &b_star.evals_on_K.val[i] * &inverses_b[i]) - + (eta_c * &c_star.evals_on_K.val[i] * &inverses_c[i]); - let f_at_kappa = v_H_at_beta * &v_H_at_alpha * &t; + let t = eta_a * a_star.evals_on_K.val[i] * inverses_a[i] + + (eta_b * b_star.evals_on_K.val[i] * inverses_b[i]) + + (eta_c * c_star.evals_on_K.val[i] * inverses_c[i]); + let f_at_kappa = v_H_at_beta * v_H_at_alpha * t; f_vals_on_K.push(f_at_kappa); } end_timer!(f_evals_time); @@ -545,29 +545,29 @@ impl AHPForR1CS { let a_denom: Vec<_> = cfg_iter!(a_star.evals_on_B.row.evaluations) .zip(&a_star.evals_on_B.col.evaluations) .zip(&a_star.row_col_evals_on_B.evaluations) - .map(|((&r, c), r_c)| beta * &alpha - &(r * &alpha) - &(beta * c) + r_c) + .map(|((&r, c), r_c)| beta * alpha - (r * alpha) - (beta * c) + r_c) .collect(); let b_denom: Vec<_> = cfg_iter!(b_star.evals_on_B.row.evaluations) .zip(&b_star.evals_on_B.col.evaluations) .zip(&b_star.row_col_evals_on_B.evaluations) - .map(|((&r, c), r_c)| beta * &alpha - &(r * &alpha) - &(beta * c) + r_c) + .map(|((&r, c), r_c)| beta * alpha - (r * alpha) - (beta * c) + r_c) .collect(); let c_denom: Vec<_> = cfg_iter!(c_star.evals_on_B.row.evaluations) .zip(&c_star.evals_on_B.col.evaluations) .zip(&c_star.row_col_evals_on_B.evaluations) - .map(|((&r, c), r_c)| beta * &alpha - &(r * &alpha) - &(beta * c) + r_c) + .map(|((&r, c), r_c)| beta * alpha - (r * alpha) - (beta * c) + r_c) .collect(); end_timer!(denom_eval_time); let a_evals_time = start_timer!(|| "Computing a evals on B"); let a_poly_on_B = cfg_into_iter!(0..domain_b.size()) .map(|i| { - let t = eta_a * &a_star.evals_on_B.val.evaluations[i] * &b_denom[i] * &c_denom[i] - + (eta_b * &b_star.evals_on_B.val.evaluations[i] * &a_denom[i] * &c_denom[i]) - + (eta_c * &c_star.evals_on_B.val.evaluations[i] * &a_denom[i] * &b_denom[i]); - v_H_at_beta * &v_H_at_alpha * &t + let t = eta_a * a_star.evals_on_B.val.evaluations[i] * b_denom[i] * c_denom[i] + + (eta_b * b_star.evals_on_B.val.evaluations[i] * a_denom[i] * c_denom[i]) + + (eta_c * c_star.evals_on_B.val.evaluations[i] * a_denom[i] * b_denom[i]); + v_H_at_beta * v_H_at_alpha * t }) .collect(); end_timer!(a_evals_time); @@ -578,7 +578,7 @@ impl AHPForR1CS { let b_evals_time = start_timer!(|| "Computing b evals on B"); let b_poly_on_B = cfg_into_iter!(0..domain_b.size()) - .map(|i| a_denom[i] * &b_denom[i] * &c_denom[i]) + .map(|i| a_denom[i] * b_denom[i] * c_denom[i]) .collect(); end_timer!(b_evals_time); diff --git a/marlin/src/ahp/verifier/verifier.rs b/marlin/src/ahp/verifier/verifier.rs index 6b69230fee..68aedf7bee 100644 --- a/marlin/src/ahp/verifier/verifier.rs +++ b/marlin/src/ahp/verifier/verifier.rs @@ -200,7 +200,7 @@ impl AHPForR1CS { // let h_lc = LinearCombination::new("b_poly", vec![(v_K_at_gamma, "h_2")]); // // // This LC is the only one that is evaluated: - // let inner_sumcheck = a_poly_lc - (b_lc * (gamma * &g_2_at_gamma + (t_at_beta / &k_size))) - h_lc + // let inner_sumcheck = a_poly_lc - (b_lc * (gamma * g_2_at_gamma + (t_at_beta / &k_size))) - h_lc // main_lc.set_label("inner_sumcheck"); query_set.insert(("g_2".into(), gamma)); query_set.insert(("a_denom".into(), gamma)); diff --git a/marlin/src/constraints/lagrange_interpolation.rs b/marlin/src/constraints/lagrange_interpolation.rs index 05e692717b..83521c67aa 100644 --- a/marlin/src/constraints/lagrange_interpolation.rs +++ b/marlin/src/constraints/lagrange_interpolation.rs @@ -94,9 +94,9 @@ impl LagrangeInterpolator { let vp_t_inv = self.domain_vp.evaluate(&interpolation_point).inverse().unwrap(); let mut inverted_lagrange_coeffs: Vec = Vec::with_capacity(self.all_domain_elems.len()); for i in 0..poly_evaluations_size { - let l = vp_t_inv * &self.v_inv_elems[i]; + let l = vp_t_inv * self.v_inv_elems[i]; let r = self.all_domain_elems[i]; - inverted_lagrange_coeffs.push(l * &(interpolation_point - &r)); + inverted_lagrange_coeffs.push(l * (interpolation_point - r)); } let lagrange_coeffs = inverted_lagrange_coeffs.as_mut_slice(); batch_inversion::(lagrange_coeffs); diff --git a/marlin/src/fiat_shamir/fiat_shamir_algebraic_sponge.rs b/marlin/src/fiat_shamir/fiat_shamir_algebraic_sponge.rs index 39d82e14b4..d1c43a55dd 100644 --- a/marlin/src/fiat_shamir/fiat_shamir_algebraic_sponge.rs +++ b/marlin/src/fiat_shamir/fiat_shamir_algebraic_sponge.rs @@ -200,9 +200,9 @@ impl KZG10 { proof: &Proof, ) -> Result { let check_time = start_timer!(|| "Checking evaluation"); - let mut inner = commitment.0.into_projective() - &vk.g.into_projective().mul(value); + let mut inner = commitment.0.into_projective() - vk.g.into_projective().mul(value); if let Some(random_v) = proof.random_v { inner -= &vk.gamma_g.mul(random_v).into(); } @@ -333,7 +333,7 @@ impl KZG10 { let c = temp; g_multiplier += &(randomizer * v); if let Some(random_v) = proof.random_v { - gamma_g_multiplier += &(randomizer * &random_v); + gamma_g_multiplier += &(randomizer * random_v); } total_c += &c.mul(randomizer).into(); total_w += &w.mul(randomizer).into(); diff --git a/polycommit/src/lib.rs b/polycommit/src/lib.rs index a18126e014..3effb6ac7b 100644 --- a/polycommit/src/lib.rs +++ b/polycommit/src/lib.rs @@ -444,7 +444,7 @@ pub trait PolynomialCommitment: Sized + Clone + Debug { .ok_or(Error::MissingEvaluation { label: l.clone() })?, }; - actual_rhs += &(*coeff * &eval); + actual_rhs += &(*coeff * eval); } if claimed_rhs != actual_rhs { eprintln!("Claimed evaluation of {} is incorrect", lc.label()); @@ -848,7 +848,7 @@ pub mod tests { } else { assert!(poly.degree_bound().is_none()); let coeff = F::rand(rng); - value += &(coeff * &poly.evaluate(point)); + value += &(coeff * poly.evaluate(point)); lc.push((coeff, label.to_string().into())); } } diff --git a/polycommit/src/marlin_pc/mod.rs b/polycommit/src/marlin_pc/mod.rs index c9e75560c0..38aeeeb0b7 100644 --- a/polycommit/src/marlin_pc/mod.rs +++ b/polycommit/src/marlin_pc/mod.rs @@ -295,7 +295,7 @@ impl PolynomialCommitment for MarlinKZG10 { let shifted_rand = rand.shifted_rand.as_ref().unwrap(); let (witness, shifted_rand_witness) = kzg10::KZG10::compute_witness_polynomial(polynomial.polynomial(), point, &shifted_rand)?; - let challenge_j_1 = challenge_j * &opening_challenge; + let challenge_j_1 = challenge_j * opening_challenge; let shifted_witness = shift_polynomial(ck, &witness, degree_bound); @@ -325,7 +325,7 @@ impl PolynomialCommitment for MarlinKZG10 { w += &shifted_proof.w.into_projective(); if let Some(shifted_random_v) = shifted_proof.random_v { - random_v = random_v.map(|v| v + &shifted_random_v); + random_v = random_v.map(|v| v + shifted_random_v); } } @@ -841,7 +841,7 @@ impl MarlinKZG10 { w += &shifted_proof.w.into_projective(); if let Some(shifted_random_v) = shifted_proof.random_v { - random_v = random_v.map(|v| v + &shifted_random_v); + random_v = random_v.map(|v| v + shifted_random_v); } } @@ -988,7 +988,7 @@ impl MarlinKZG10 { if let Some(shifted_comm) = &comm.shifted_comm { let cur = shifted_comm.0.mul(coeff).into_projective(); - combined_shifted_comm = Some(combined_shifted_comm.map_or(cur, |c| c + &cur)); + combined_shifted_comm = Some(combined_shifted_comm.map_or(cur, |c| c + cur)); } } (combined_comm, combined_shifted_comm) @@ -1103,10 +1103,10 @@ impl MarlinKZG10 { assert_eq!(degree_bound.is_some(), commitment.shifted_comm.is_some()); combined_comm += &commitment.comm.0.mul(challenge_i).into(); - combined_value += &(value * &challenge_i); + combined_value += &(value * challenge_i); if let Some(degree_bound) = degree_bound { - let challenge_i_1 = challenge_i * &opening_challenge; + let challenge_i_1 = challenge_i * opening_challenge; let shifted_comm = commitment.shifted_comm.as_ref().unwrap().0.into_projective(); let shift_power = vk @@ -1143,7 +1143,7 @@ impl MarlinKZG10 { opening_challenge_counter += 1; combined_comm += &commitment.comm.0.mul(challenge_i).into(); - combined_value += &(value * &challenge_i); + combined_value += &(value * challenge_i); if let Some(degree_bound) = degree_bound { let challenge_i_1 = opening_challenges(opening_challenge_counter); diff --git a/polycommit/src/sonic_pc/mod.rs b/polycommit/src/sonic_pc/mod.rs index 09d9f7b76a..e576bcad4d 100644 --- a/polycommit/src/sonic_pc/mod.rs +++ b/polycommit/src/sonic_pc/mod.rs @@ -629,7 +629,7 @@ impl PolynomialCommitment for SonicKZG10 { .ok_or(Error::MissingEvaluation { label: l.clone() })?, }; - actual_rhs += &(*coeff * &eval); + actual_rhs += &(*coeff * eval); } if claimed_rhs != actual_rhs { eprintln!("Claimed evaluation of {} is incorrect", lc.label()); @@ -880,7 +880,7 @@ impl SonicKZG10 { // Iterates through all of the commitments and accumulates common degree_bound elements in a BTreeMap for (labeled_comm, value) in commitments.into_iter().zip(values) { - combined_values += &(value * &curr_challenge); + combined_values += &(value * curr_challenge); let comm = labeled_comm.commitment(); let degree_bound = labeled_comm.degree_bound(); @@ -899,7 +899,7 @@ impl SonicKZG10 { // Push expected results into list of elems. Power will be the negative of the expected power let mut witness: E::G1Projective = proof.w.into_projective(); - let mut adjusted_witness = vk.g.mul(combined_values) - &proof.w.mul(point); + let mut adjusted_witness = vk.g.mul(combined_values) - proof.w.mul(point); if let Some(random_v) = proof.random_v { adjusted_witness += &vk.gamma_g.mul(random_v); } @@ -937,7 +937,7 @@ impl SonicKZG10 { // Iterates through all of the commitments and accumulates common degree_bound elements in a BTreeMap for (labeled_comm, value) in commitments.into_iter().zip(values) { - combined_values += &(value * &curr_challenge); + combined_values += &(value * curr_challenge); let comm = labeled_comm.commitment(); let degree_bound = labeled_comm.degree_bound(); @@ -957,7 +957,7 @@ impl SonicKZG10 { // Push expected results into list of elems. Power will be the negative of the expected power let mut witness: E::G1Projective = proof.w.into_projective(); - let mut adjusted_witness = vk.g.mul(combined_values) - &proof.w.mul(point); + let mut adjusted_witness = vk.g.mul(combined_values) - proof.w.mul(point); if let Some(random_v) = proof.random_v { adjusted_witness += &vk.gamma_g.mul(random_v); } diff --git a/r1cs/src/linear_combination.rs b/r1cs/src/linear_combination.rs index 8dd9d057bd..de7de35389 100644 --- a/r1cs/src/linear_combination.rs +++ b/r1cs/src/linear_combination.rs @@ -229,7 +229,7 @@ impl Add<&LinearCombination> for &LinearCombination { self, other, |coeff| coeff, - |cur_coeff, other_coeff| cur_coeff + &other_coeff, + |cur_coeff, other_coeff| cur_coeff + other_coeff, ) } } @@ -247,7 +247,7 @@ impl Add> for &LinearCombination { self, &other, |coeff| coeff, - |cur_coeff, other_coeff| cur_coeff + &other_coeff, + |cur_coeff, other_coeff| cur_coeff + other_coeff, ) } } @@ -265,7 +265,7 @@ impl<'a, F: Field> Add<&'a LinearCombination> for LinearCombination { &self, other, |coeff| coeff, - |cur_coeff, other_coeff| cur_coeff + &other_coeff, + |cur_coeff, other_coeff| cur_coeff + other_coeff, ) } } @@ -283,7 +283,7 @@ impl Add> for LinearCombination { &self, &other, |coeff| coeff, - |cur_coeff, other_coeff| cur_coeff + &other_coeff, + |cur_coeff, other_coeff| cur_coeff + other_coeff, ) } } @@ -305,7 +305,7 @@ impl Sub<&LinearCombination> for &LinearCombination { self, other, |coeff| -coeff, - |cur_coeff, other_coeff| cur_coeff - &other_coeff, + |cur_coeff, other_coeff| cur_coeff - other_coeff, ) } } @@ -325,7 +325,7 @@ impl<'a, F: Field> Sub<&'a LinearCombination> for LinearCombination { &self, other, |coeff| -coeff, - |cur_coeff, other_coeff| cur_coeff - &other_coeff, + |cur_coeff, other_coeff| cur_coeff - other_coeff, ) } } @@ -345,7 +345,7 @@ impl Sub> for &LinearCombination { self, &other, |coeff| -coeff, - |cur_coeff, other_coeff| cur_coeff - &other_coeff, + |cur_coeff, other_coeff| cur_coeff - other_coeff, ) } } @@ -364,7 +364,7 @@ impl Sub> for LinearCombination { &self, &other, |coeff| -coeff, - |cur_coeff, other_coeff| cur_coeff - &other_coeff, + |cur_coeff, other_coeff| cur_coeff - other_coeff, ) } } @@ -384,8 +384,8 @@ impl Add<(F, &LinearCombination)> for &LinearCombination { op_impl( self, other, - |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), + |coeff| mul_coeff * coeff, + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * other_coeff), ) } } @@ -405,8 +405,8 @@ impl<'a, F: Field> Add<(F, &'a LinearCombination)> for LinearCombination { op_impl( &self, other, - |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), + |coeff| mul_coeff * coeff, + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * other_coeff), ) } } @@ -425,8 +425,8 @@ impl Add<(F, LinearCombination)> for &LinearCombination { op_impl( self, &other, - |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), + |coeff| mul_coeff * coeff, + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * other_coeff), ) } } @@ -446,8 +446,8 @@ impl Add<(F, Self)> for LinearCombination { op_impl( &self, &other, - |coeff| mul_coeff * &coeff, - |cur_coeff, other_coeff| cur_coeff + (mul_coeff * &other_coeff), + |coeff| mul_coeff * coeff, + |cur_coeff, other_coeff| cur_coeff + (mul_coeff * other_coeff), ) } } diff --git a/r1cs/src/test_constraint_system.rs b/r1cs/src/test_constraint_system.rs index 77155d64cb..0f1ec75400 100644 --- a/r1cs/src/test_constraint_system.rs +++ b/r1cs/src/test_constraint_system.rs @@ -176,12 +176,8 @@ impl TestConstraintSystem { parent_ns = interned_parent_ns.parent_namespace; } - reversed_uninterned_segments - .into_iter() - .map(|s| s.as_str()) - .rev() - .intersperse("/") - .collect() + let segments = reversed_uninterned_segments.into_iter().map(|s| s.as_str()).rev(); + Itertools::intersperse(segments, "/").collect() } pub fn print_named_objects(&self) { From 5b5acf3f83e71e770784b1cef298725d6f946a85 Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 20:14:52 -0700 Subject: [PATCH 11/13] Update benchmarks --- algorithms/benches/msm/variable_base.rs | 2 +- curves/benches/bls12_377/ec.rs | 6 ++++-- curves/benches/bw6_761/ec.rs | 6 ++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/algorithms/benches/msm/variable_base.rs b/algorithms/benches/msm/variable_base.rs index b5f70592be..da108e85b4 100644 --- a/algorithms/benches/msm/variable_base.rs +++ b/algorithms/benches/msm/variable_base.rs @@ -33,7 +33,7 @@ fn variable_base(c: &mut Criterion) { let mut rng = XorShiftRng::seed_from_u64(234872845u64); - let v = (0..SAMPLES).map(|_| Fr::rand(&mut rng)).collect::>(); + let v = (0..SAMPLES).map(|_| Fr::rand(&mut rng).into_repr()).collect::>(); let g = (0..SAMPLES) .map(|_| G1Projective::rand(&mut rng).into_affine()) .collect::>(); diff --git a/curves/benches/bls12_377/ec.rs b/curves/benches/bls12_377/ec.rs index db58d56292..b760532036 100644 --- a/curves/benches/bls12_377/ec.rs +++ b/curves/benches/bls12_377/ec.rs @@ -18,13 +18,14 @@ pub(crate) mod g1 { use snarkvm_curves::{ bls12_377::{Fr, G1Affine, G1Projective as G1}, traits::ProjectiveCurve, + Group, }; use snarkvm_utilities::rand::UniformRand; use criterion::Criterion; use rand::SeedableRng; use rand_xorshift::XorShiftRng; - use std::ops::AddAssign; + use std::ops::{AddAssign, MulAssign}; pub fn bench_g1_rand(c: &mut Criterion) { let mut rng = XorShiftRng::seed_from_u64(1231275789u64); @@ -109,13 +110,14 @@ pub(crate) mod g2 { use snarkvm_curves::{ bls12_377::{Fr, G2Affine, G2Projective as G2}, traits::ProjectiveCurve, + Group, }; use snarkvm_utilities::rand::UniformRand; use criterion::Criterion; use rand::SeedableRng; use rand_xorshift::XorShiftRng; - use std::ops::AddAssign; + use std::ops::{AddAssign, MulAssign}; pub fn bench_g2_rand(c: &mut Criterion) { let mut rng = XorShiftRng::seed_from_u64(1231275789u64); diff --git a/curves/benches/bw6_761/ec.rs b/curves/benches/bw6_761/ec.rs index b8370fe1a9..45c83924c1 100644 --- a/curves/benches/bw6_761/ec.rs +++ b/curves/benches/bw6_761/ec.rs @@ -18,13 +18,14 @@ pub(crate) mod g1 { use snarkvm_curves::{ bw6_761::{Fr, G1Affine, G1Projective as G1}, traits::ProjectiveCurve, + Group, }; use snarkvm_utilities::rand::UniformRand; use criterion::Criterion; use rand::SeedableRng; use rand_xorshift::XorShiftRng; - use std::ops::AddAssign; + use std::ops::{AddAssign, MulAssign}; pub fn bench_g1_rand(c: &mut Criterion) { let mut rng = XorShiftRng::seed_from_u64(1231275789u64); @@ -110,13 +111,14 @@ pub(crate) mod g2 { use snarkvm_curves::{ bw6_761::{Fr, G2Affine, G2Projective as G2}, traits::ProjectiveCurve, + Group, }; use snarkvm_utilities::rand::UniformRand; use criterion::Criterion; use rand::SeedableRng; use rand_xorshift::XorShiftRng; - use std::ops::AddAssign; + use std::ops::{AddAssign, MulAssign}; pub fn bench_g2_rand(c: &mut Criterion) { let mut rng = XorShiftRng::seed_from_u64(1231275789u64); From a9de5932c0a3335e4930934e5fa79cc1bbbb938f Mon Sep 17 00:00:00 2001 From: howardwu Date: Fri, 25 Jun 2021 20:36:02 -0700 Subject: [PATCH 12/13] Fix BLS120377 generator and two-adic root of unity --- curves/src/bls12_377/fr.rs | 42 ++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/curves/src/bls12_377/fr.rs b/curves/src/bls12_377/fr.rs index c2572f3a73..15ac8188f2 100644 --- a/curves/src/bls12_377/fr.rs +++ b/curves/src/bls12_377/fr.rs @@ -17,6 +17,27 @@ use snarkvm_fields::{FftParameters, FieldParameters, Fp256, Fp256Parameters}; use snarkvm_utilities::biginteger::BigInteger256 as BigInteger; +/// BLS12-377 scalar field. +/// +/// Roots of unity computed from modulus and R using this sage code: +/// +/// ```ignore +/// q = 8444461749428370424248824938781546531375899335154063827935233455917409239041 +/// R = 6014086494747379908336260804527802945383293308637734276299549080986809532403 # Montgomery R +/// s = 47 +/// o = q - 1 +/// F = GF(q) +/// g = F.multiplicative_generator() +/// g = F.multiplicative_generator() +/// assert g.multiplicative_order() == o +/// g2 = g ** (o/2**s) +/// assert g2.multiplicative_order() == 2**s +/// def into_chunks(val, width, n): +/// return [int(int(val) // (2 ** (width * i)) % 2 ** width) for i in range(n)] +/// print("Gen: ", g * R % q) +/// print("Gen: ", into_chunks(g * R % q, 64, 4)) +/// print("2-adic gen: ", into_chunks(g2 * R % q, 64, 4)) +/// ``` pub type Fr = Fp256; pub struct FrParameters; @@ -30,23 +51,26 @@ impl FftParameters for FrParameters { const TWO_ADICITY: u32 = 47; #[rustfmt::skip] const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ - 0x3c3d3ca739381fb2, - 0x9a14cda3ec99772b, - 0xd7aacc7c59724826, - 0xd1ba211c5cc349c, + 12646347781564978760u64, + 6783048705277173164u64, + 268534165941069093u64, + 1121515446318641358u64, ]); } impl FieldParameters for FrParameters { #[rustfmt::skip] const CAPACITY: u32 = Self::MODULUS_BITS - 1; - /// GENERATOR = 11 + /// GENERATOR = 22 + /// Encoded in Montgomery form, so the value is + /// (22 * R) % q = 5642976643016801619665363617888466827793962762719196659561577942948671127251 + #[rustfmt::skip] #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ - 1855201571499933546u64, - 8511318076631809892u64, - 6222514765367795509u64, - 1122129207579058019u64, + 2984901390528151251u64, + 10561528701063790279u64, + 5476750214495080041u64, + 898978044469942640u64, ]); #[rustfmt::skip] const INV: u64 = 725501752471715839u64; From d40d9541802eb4fe05fbbfd6c817c23c8c5528bd Mon Sep 17 00:00:00 2001 From: howardwu Date: Sat, 26 Jun 2021 00:33:48 -0700 Subject: [PATCH 13/13] Adds fft checks for root of unity usage --- curves/src/bls12_377/fr.rs | 19 ++- curves/src/bls12_377/tests.rs | 7 +- curves/src/edwards_bls12/fr.rs | 14 +- curves/src/edwards_sw6/fr.rs | 18 ++- fields/src/fp3.rs | 2 +- fields/src/fp_256.rs | 5 - fields/src/fp_320.rs | 5 - fields/src/fp_384.rs | 5 - fields/src/fp_768.rs | 5 - fields/src/fp_832.rs | 5 - fields/src/macros.rs | 2 +- fields/src/tests_field.rs | 38 +++++- fields/src/traits/prime_field.rs | 20 +-- posw/tests/mod.rs | 227 +++++++++++++++++++++++++++++++ 14 files changed, 314 insertions(+), 58 deletions(-) diff --git a/curves/src/bls12_377/fr.rs b/curves/src/bls12_377/fr.rs index 15ac8188f2..a2f2fd0c11 100644 --- a/curves/src/bls12_377/fr.rs +++ b/curves/src/bls12_377/fr.rs @@ -28,7 +28,6 @@ use snarkvm_utilities::biginteger::BigInteger256 as BigInteger; /// o = q - 1 /// F = GF(q) /// g = F.multiplicative_generator() -/// g = F.multiplicative_generator() /// assert g.multiplicative_order() == o /// g2 = g ** (o/2**s) /// assert g2.multiplicative_order() == 2**s @@ -49,12 +48,21 @@ impl FftParameters for FrParameters { #[rustfmt::skip] const TWO_ADICITY: u32 = 47; + /// TODO (howardwu): CRITICAL - Fix this after a migration plan has been determined. + /// - 0x3c3d3ca739381fb2, + /// - 0x9a14cda3ec99772b, + /// - 0xd7aacc7c59724826, + /// - 0xd1ba211c5cc349c, + /// + 12646347781564978760u64, + /// + 6783048705277173164u64, + /// + 268534165941069093u64, + /// + 1121515446318641358u64, #[rustfmt::skip] const TWO_ADIC_ROOT_OF_UNITY: BigInteger = BigInteger([ - 12646347781564978760u64, - 6783048705277173164u64, - 268534165941069093u64, - 1121515446318641358u64, + 0x3c3d3ca739381fb2, + 0x9a14cda3ec99772b, + 0xd7aacc7c59724826, + 0xd1ba211c5cc349c, ]); } @@ -65,7 +73,6 @@ impl FieldParameters for FrParameters { /// Encoded in Montgomery form, so the value is /// (22 * R) % q = 5642976643016801619665363617888466827793962762719196659561577942948671127251 #[rustfmt::skip] - #[rustfmt::skip] const GENERATOR: BigInteger = BigInteger([ 2984901390528151251u64, 10561528701063790279u64, diff --git a/curves/src/bls12_377/tests.rs b/curves/src/bls12_377/tests.rs index 81e8d56aab..ebb7bc696b 100644 --- a/curves/src/bls12_377/tests.rs +++ b/curves/src/bls12_377/tests.rs @@ -397,9 +397,12 @@ fn test_fq_root_of_unity() { 0xe9185f1443ab18ec, 0x6b8 ]), - Fq::root_of_unity() + Fq::two_adic_root_of_unity() + ); + assert_eq!( + Fq::two_adic_root_of_unity().pow([1 << FqParameters::TWO_ADICITY]), + Fq::one() ); - assert_eq!(Fq::root_of_unity().pow([1 << FqParameters::TWO_ADICITY]), Fq::one()); assert!(Fq::multiplicative_generator().sqrt().is_none()); } diff --git a/curves/src/edwards_bls12/fr.rs b/curves/src/edwards_bls12/fr.rs index 7aca1523d4..d881608ce0 100644 --- a/curves/src/edwards_bls12/fr.rs +++ b/curves/src/edwards_bls12/fr.rs @@ -83,7 +83,17 @@ impl FieldParameters for FrParameters { #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 5; #[rustfmt::skip] - const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); + const T: BigInteger = BigInteger([ + 6678124996694371583, + 2975139753996731775, + 14706092969812227584, + 168160046336021674 + ]); #[rustfmt::skip] - const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0]); + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 12562434535201961599, + 1487569876998365887, + 7353046484906113792, + 84080023168010837 + ]); } diff --git a/curves/src/edwards_sw6/fr.rs b/curves/src/edwards_sw6/fr.rs index 3638245e32..0d429093b0 100644 --- a/curves/src/edwards_sw6/fr.rs +++ b/curves/src/edwards_sw6/fr.rs @@ -95,7 +95,21 @@ impl FieldParameters for FrParameters { #[rustfmt::skip] const REPR_SHAVE_BITS: u32 = 10; #[rustfmt::skip] - const T: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); + const T: BigInteger = BigInteger([ + 5782852926996632741, + 10160572951715783904, + 8680081325396045328, + 15623293663189641372, + 6210983053257673289, + 3784322272077959 + ]); #[rustfmt::skip] - const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([0x0, 0x0, 0x0, 0x0, 0x0, 0x0]); + const T_MINUS_ONE_DIV_TWO: BigInteger = BigInteger([ + 2891426463498316370, + 5080286475857891952, + 4340040662698022664, + 17035018868449596494, + 12328863563483612452, + 1892161136038979 + ]); } diff --git a/fields/src/fp3.rs b/fields/src/fp3.rs index 91745eae1d..6ae530e218 100644 --- a/fields/src/fp3.rs +++ b/fields/src/fp3.rs @@ -102,7 +102,7 @@ impl Fp3

{ // Returns the value of QNR^T. #[inline] - pub fn qnr_to_t() -> Self { + pub fn two_adic_root_of_unity() -> Self { Self::new( P::QUADRATIC_NONRESIDUE_TO_T.0, P::QUADRATIC_NONRESIDUE_TO_T.1, diff --git a/fields/src/fp_256.rs b/fields/src/fp_256.rs index bea140568d..e06bd33e4a 100644 --- a/fields/src/fp_256.rs +++ b/fields/src/fp_256.rs @@ -329,11 +329,6 @@ impl PrimeField for Fp256

{ let r = *self; r.0 } - - #[inline] - fn root_of_unity() -> Self { - Fp256::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) - } } impl FftField for Fp256

{ diff --git a/fields/src/fp_320.rs b/fields/src/fp_320.rs index 8ee8a29930..635fa1321f 100644 --- a/fields/src/fp_320.rs +++ b/fields/src/fp_320.rs @@ -365,11 +365,6 @@ impl PrimeField for Fp320

{ let r = *self; r.0 } - - #[inline] - fn root_of_unity() -> Self { - Fp320::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) - } } impl FftField for Fp320

{ diff --git a/fields/src/fp_384.rs b/fields/src/fp_384.rs index bb2b2f870b..143f9017af 100644 --- a/fields/src/fp_384.rs +++ b/fields/src/fp_384.rs @@ -395,11 +395,6 @@ impl PrimeField for Fp384

{ fn into_repr_raw(&self) -> BigInteger { self.0 } - - #[inline] - fn root_of_unity() -> Self { - Fp384::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) - } } impl FftField for Fp384

{ diff --git a/fields/src/fp_768.rs b/fields/src/fp_768.rs index 27fbd51b25..cd054a088d 100644 --- a/fields/src/fp_768.rs +++ b/fields/src/fp_768.rs @@ -709,11 +709,6 @@ impl PrimeField for Fp768

{ r.0 } - #[inline] - fn root_of_unity() -> Self { - Fp768::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) - } - #[inline] fn size_in_bits() -> usize { P::MODULUS_BITS as usize diff --git a/fields/src/fp_832.rs b/fields/src/fp_832.rs index 858d9ef917..c5a31e1851 100644 --- a/fields/src/fp_832.rs +++ b/fields/src/fp_832.rs @@ -678,11 +678,6 @@ impl PrimeField for Fp832

{ r.0 } - #[inline] - fn root_of_unity() -> Self { - Fp832::

(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData) - } - #[inline] fn size_in_bits() -> usize { P::MODULUS_BITS as usize diff --git a/fields/src/macros.rs b/fields/src/macros.rs index bc8045cba9..47456dc747 100644 --- a/fields/src/macros.rs +++ b/fields/src/macros.rs @@ -108,7 +108,7 @@ macro_rules! sqrt_impl { Zero => Some(*$self), QuadraticNonResidue => None, QuadraticResidue => { - let mut z = $Self::qnr_to_t(); + let mut z = $Self::two_adic_root_of_unity(); let mut w = $self.pow($P::T_MINUS_ONE_DIV_TWO); let mut x = w * $self; let mut b = x * w; diff --git a/fields/src/tests_field.rs b/fields/src/tests_field.rs index a37f39280b..a4ed8e9de5 100644 --- a/fields/src/tests_field.rs +++ b/fields/src/tests_field.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkVM library. If not, see . -use crate::{Field, LegendreSymbol, PrimeField, SquareRootField}; +use crate::{traits::FftParameters, FftField, Field, LegendreSymbol, PrimeField, SquareRootField}; use snarkvm_utilities::{ io::Cursor, serialize::{CanonicalDeserialize, CanonicalSerialize, Flags, SWFlags}, @@ -334,10 +334,46 @@ pub fn field_test(a: F, b: F) { random_field_tests::(); } +pub fn fft_field_test() { + let modulus_minus_one_div_two = F::from_repr(F::modulus_minus_one_div_two()).unwrap(); + assert!(!modulus_minus_one_div_two.is_zero()); + + // modulus - 1 == 2^s * t + // => t == (modulus - 1) / 2^s + // => t == [(modulus - 1) / 2] * [1 / 2^(s-1)] + let two_adicity = F::FftParameters::TWO_ADICITY; + assert!(two_adicity > 0); + let two_s_minus_one = F::from(2_u32).pow(&[(two_adicity - 1) as u64]); + let trace = modulus_minus_one_div_two * two_s_minus_one.inverse().unwrap(); + assert_eq!(trace, F::from_repr(F::trace()).unwrap()); + + // (trace - 1) / 2 == trace_minus_one_div_two + let trace_minus_one_div_two = F::from_repr(F::trace_minus_one_div_two()).unwrap(); + assert!(!trace_minus_one_div_two.is_zero()); + assert_eq!((trace - F::one()) / F::one().double(), trace_minus_one_div_two); + + // multiplicative_generator^trace == root of unity + let generator = F::multiplicative_generator(); + assert!(!generator.is_zero()); + let two_adic_root_of_unity = F::two_adic_root_of_unity(); + assert!(!two_adic_root_of_unity.is_zero()); + assert_eq!(two_adic_root_of_unity.pow([1 << two_adicity]), F::one()); + // TODO (howardwu): CRITICAL - Reenable this after BLS12-377 Fr root_of_unity has been fixed. + // assert_eq!(generator.pow(trace.into_repr().as_ref()), two_adic_root_of_unity); +} + pub fn primefield_test() { let one = F::one(); assert_eq!(F::from_repr(one.into_repr()).unwrap(), one); assert_eq!(F::from_str("1").ok().unwrap(), one); + assert_eq!(F::from_str(&one.to_string()).ok().unwrap(), one); + + let two = F::one().double(); + assert_eq!(F::from_repr(two.into_repr()).unwrap(), two); + assert_eq!(F::from_str("2").ok().unwrap(), two); + assert_eq!(F::from_str(&two.to_string()).ok().unwrap(), two); + + fft_field_test::(); } pub fn sqrt_field_test(elem: F) { diff --git a/fields/src/traits/prime_field.rs b/fields/src/traits/prime_field.rs index afb2f918cd..c174de9ac4 100644 --- a/fields/src/traits/prime_field.rs +++ b/fields/src/traits/prime_field.rs @@ -37,14 +37,6 @@ pub trait PrimeField: FftField::Parameters> /// Returns the underlying raw representation of the prime field element. fn into_repr_raw(&self) -> Self::BigInteger; - /// Returns the 2^s root of unity. - fn root_of_unity() -> Self; - - /// Return the a QNR^T - fn qnr_to_t() -> Self { - Self::root_of_unity() - } - /// Returns the field size in bits. fn size_in_bits() -> usize { Self::Parameters::MODULUS_BITS as usize @@ -52,20 +44,12 @@ pub trait PrimeField: FftField::Parameters> /// Returns the trace. fn trace() -> Self::BigInteger { - // TODO (howardwu): This function has been disabled as - // `snarkvm_curves::edwards_bls12::Fr` and `snarkvm_curves::edwards_sw6::Fr` - // do NOT implement `FieldParameters::T` or `FieldParameters::T_MINUS_ONE_DIV_TWO`. - unimplemented!() - // Self::Parameters::T + Self::Parameters::T } /// Returns the trace minus one divided by two. fn trace_minus_one_div_two() -> Self::BigInteger { - // TODO (howardwu): This function has been disabled as - // `snarkvm_curves::edwards_bls12::Fr` and `snarkvm_curves::edwards_sw6::Fr` - // do NOT implement `FieldParameters::T` or `FieldParameters::T_MINUS_ONE_DIV_TWO`. - unimplemented!() - // Self::Parameters::T_MINUS_ONE_DIV_TWO + Self::Parameters::T_MINUS_ONE_DIV_TWO } /// Returns the modulus minus one divided by two. diff --git a/posw/tests/mod.rs b/posw/tests/mod.rs index aba90dc6ec..c4ff98aa0e 100644 --- a/posw/tests/mod.rs +++ b/posw/tests/mod.rs @@ -20,6 +20,8 @@ use snarkvm_dpc::block::PedersenMerkleRootHash; use snarkvm_posw::{txids_to_roots, Marlin, PoswMarlin}; use snarkvm_utilities::bytes::FromBytes; +use rand::SeedableRng; + #[test] fn test_posw_load_and_mine() { // Load the PoSW Marlin parameters. @@ -75,3 +77,228 @@ fn test_posw_verify_testnet1() { let posw = PoswMarlin::load().unwrap(); assert!(posw.verify(nonce, &proof, &pedersen_merkle_root).is_ok()); } + +#[test] +fn test_posw_setup_vs_load_weak_sanity_check() { + let generated_posw = { + // Load the PoSW Marlin parameters. + let rng = &mut rand_xorshift::XorShiftRng::seed_from_u64(1234567); + // Run the universal setup. + let universal_srs = snarkvm_marlin::MarlinTestnet1::universal_setup(10000, 10000, 100000, rng).unwrap(); + // Run the circuit setup. + PoswMarlin::index(universal_srs).unwrap() + }; + let loaded_posw = PoswMarlin::load().unwrap(); + + let generated_proving_key = generated_posw.pk.unwrap().proving_key; + let loaded_proving_key = loaded_posw.pk.unwrap().proving_key; + + let a = generated_proving_key.committer_key.max_degree; + let b = loaded_proving_key.committer_key.max_degree; + assert_eq!(a, b); + + let a = generated_proving_key.circuit_commitment_randomness.len(); + let b = loaded_proving_key.circuit_commitment_randomness.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.max_degree(); + let b = loaded_proving_key.circuit.max_degree(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.index_info.num_variables; + let b = loaded_proving_key.circuit.index_info.num_variables; + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.index_info.num_constraints; + let b = loaded_proving_key.circuit.index_info.num_constraints; + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.index_info.num_non_zero; + let b = loaded_proving_key.circuit.index_info.num_non_zero; + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.index_info.max_degree(); + let b = loaded_proving_key.circuit.index_info.max_degree(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + macro_rules! check_term_sizes { + ($term: ident) => { + let a = generated_proving_key.circuit.$term.len(); + let b = loaded_proving_key.circuit.$term.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + // TODO (howardwu): CRITICAL - Confirm expected circuit behavior and reenable inner checks. + // for i in 0..generated_proving_key.circuit.$term.len() { + // let a = generated_proving_key.circuit.$term[i].len(); + // let b = loaded_proving_key.circuit.$term[i].len(); + // println!("{:?} == {:?}? {}", a, b, a == b); + // assert_eq!(a, b); + // } + }; + } + + check_term_sizes!(a); + check_term_sizes!(b); + check_term_sizes!(c); + + macro_rules! check_arithmetization_sizes { + ($term: ident) => { + let a = generated_proving_key.circuit.$term.row.degree_bound(); + let b = loaded_proving_key.circuit.$term.row.degree_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.row.hiding_bound(); + let b = loaded_proving_key.circuit.$term.row.hiding_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.row.polynomial().degree(); + let b = loaded_proving_key.circuit.$term.row.polynomial().degree(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.col.degree_bound(); + let b = loaded_proving_key.circuit.$term.col.degree_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.col.hiding_bound(); + let b = loaded_proving_key.circuit.$term.col.hiding_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.col.polynomial().degree(); + let b = loaded_proving_key.circuit.$term.col.polynomial().degree(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.val.degree_bound(); + let b = loaded_proving_key.circuit.$term.val.degree_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.val.hiding_bound(); + let b = loaded_proving_key.circuit.$term.val.hiding_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.val.polynomial().degree(); + let b = loaded_proving_key.circuit.$term.val.polynomial().degree(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.row_col.degree_bound(); + let b = loaded_proving_key.circuit.$term.row_col.degree_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.row_col.hiding_bound(); + let b = loaded_proving_key.circuit.$term.row_col.hiding_bound(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key.circuit.$term.row_col.polynomial().degree(); + let b = loaded_proving_key.circuit.$term.row_col.polynomial().degree(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .evals_on_K + .row + .evaluations + .len(); + let b = loaded_proving_key.circuit.$term.evals_on_K.row.evaluations.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .evals_on_K + .col + .evaluations + .len(); + let b = loaded_proving_key.circuit.$term.evals_on_K.col.evaluations.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .evals_on_K + .val + .evaluations + .len(); + let b = loaded_proving_key.circuit.$term.evals_on_K.val.evaluations.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .evals_on_B + .row + .evaluations + .len(); + let b = loaded_proving_key.circuit.$term.evals_on_B.row.evaluations.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .evals_on_B + .col + .evaluations + .len(); + let b = loaded_proving_key.circuit.$term.evals_on_B.col.evaluations.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .evals_on_B + .val + .evaluations + .len(); + let b = loaded_proving_key.circuit.$term.evals_on_B.val.evaluations.len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + + let a = generated_proving_key + .circuit + .$term + .row_col_evals_on_B + .evaluations + .len(); + let b = loaded_proving_key + .circuit + .$term + .row_col_evals_on_B + .evaluations + .len(); + println!("{:?} == {:?}? {}", a, b, a == b); + assert_eq!(a, b); + }; + } + + println!("------ Checking circuit A arithmetization sizes ------"); + check_arithmetization_sizes!(a_star_arith); + + println!("------ Checking circuit B arithmetization sizes ------"); + check_arithmetization_sizes!(b_star_arith); + + println!("------ Checking circuit C arithmetization sizes ------"); + check_arithmetization_sizes!(c_star_arith); +}