Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compute Legendre symbol for hash_to_curve #77

Merged
merged 17 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,7 @@ required-features = ["reexport"]
[[bench]]
name = "group"
harness = false

[[bench]]
name = "hash_to_curve"
harness = false
59 changes: 59 additions & 0 deletions benches/hash_to_curve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use pasta_curves::arithmetic::CurveExt;
use rand_core::{OsRng, RngCore};
use std::iter;

fn hash_to_secp256k1(c: &mut Criterion) {
hash_to_curve::<halo2curves::secp256k1::Secp256k1>(c, "Secp256k1");
}

fn hash_to_secq256k1(c: &mut Criterion) {
hash_to_curve::<halo2curves::secq256k1::Secq256k1>(c, "Secq256k1");
}

fn hash_to_secp256r1(c: &mut Criterion) {
hash_to_curve::<halo2curves::secp256r1::Secp256r1>(c, "Secp256r1");
}

fn hash_to_pallas(c: &mut Criterion) {
hash_to_curve::<halo2curves::pasta::Ep>(c, "Pallas");
}

fn hash_to_vesta(c: &mut Criterion) {
hash_to_curve::<halo2curves::pasta::Eq>(c, "Vesta");
}

fn hash_to_bn256(c: &mut Criterion) {
hash_to_curve::<halo2curves::bn256::G1>(c, "Bn256");
}

fn hash_to_grumpkin(c: &mut Criterion) {
hash_to_curve::<halo2curves::grumpkin::G1>(c, "Grumpkin");
}

fn hash_to_curve<G: CurveExt>(c: &mut Criterion, name: &'static str) {
{
let hasher = G::hash_to_curve("test");
let mut rng = OsRng;
let message = iter::repeat_with(|| rng.next_u32().to_be_bytes())
.take(1024)
.flatten()
.collect::<Vec<_>>();

c.bench_function(&format!("Hash to {}", name), move |b| {
b.iter(|| hasher(black_box(&message)))
});
}
}

criterion_group!(
benches,
hash_to_secp256k1,
hash_to_secq256k1,
hash_to_secp256r1,
hash_to_pallas,
hash_to_vesta,
hash_to_bn256,
hash_to_grumpkin,
);
criterion_main!(benches);
33 changes: 8 additions & 25 deletions src/bn256/fq.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#[cfg(feature = "asm")]
use crate::bn256::assembly::field_arithmetic_asm;
#[cfg(not(feature = "asm"))]
use crate::{field_arithmetic, field_specific};
use crate::{arithmetic::macx, field_arithmetic, field_specific};

use crate::arithmetic::{adc, mac, macx, sbb};
use crate::bn256::LegendreSymbol;
use crate::ff::{Field, FromUniformBytes, PrimeField, WithSmallOrderMulGroup};
use crate::arithmetic::{adc, mac, sbb};
use crate::ff::{FromUniformBytes, PrimeField, WithSmallOrderMulGroup};
use crate::{
field_bits, field_common, impl_add_binop_specify_output, impl_binops_additive,
impl_binops_additive_specify_output, impl_binops_multiplicative,
Expand Down Expand Up @@ -160,27 +159,10 @@ impl Fq {
pub const fn size() -> usize {
32
}

pub fn legendre(&self) -> LegendreSymbol {
// s = self^((modulus - 1) // 2)
// 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3
let s = &[
0x9e10460b6c3e7ea3u64,
0xcbc0b548b438e546u64,
0xdc2822db40c0ac2eu64,
0x183227397098d014u64,
];
let s = self.pow(s);
if s == Self::zero() {
LegendreSymbol::Zero
} else if s == Self::one() {
LegendreSymbol::QuadraticResidue
} else {
LegendreSymbol::QuadraticNonResidue
}
}
}

prime_field_legendre!(Fq);

impl ff::Field for Fq {
const ZERO: Self = Self::zero();
const ONE: Self = Self::one();
Expand Down Expand Up @@ -310,6 +292,7 @@ impl WithSmallOrderMulGroup<3> for Fq {
#[cfg(test)]
mod test {
use super::*;
use crate::legendre::Legendre;
use ff::Field;
use rand_core::OsRng;

Expand All @@ -322,7 +305,7 @@ mod test {
let a = Fq::random(OsRng);
let mut b = a;
b = b.square();
assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue);
assert_eq!(b.legendre(), Fq::ONE);

let b = b.sqrt().unwrap();
let mut negb = b;
Expand All @@ -335,7 +318,7 @@ mod test {
for _ in 0..10000 {
let mut b = c;
b = b.square();
assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue);
assert_eq!(b.legendre(), Fq::ONE);

b = b.sqrt().unwrap();

Expand Down
56 changes: 28 additions & 28 deletions src/bn256/fq2.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::fq::{Fq, NEGATIVE_ONE};
use super::LegendreSymbol;
use crate::ff::{Field, FromUniformBytes, PrimeField, WithSmallOrderMulGroup};
use crate::legendre::Legendre;
use core::convert::TryInto;
use core::ops::{Add, Mul, Neg, Sub};
use rand::RngCore;
Expand Down Expand Up @@ -125,6 +125,30 @@ impl_binops_additive!(Fq2, Fq2);
impl_binops_multiplicative!(Fq2, Fq2);
impl_sum_prod!(Fq2);

impl Legendre for Fq2 {
type BasePrimeField = Fq;

#[inline]
fn legendre_exp() -> &'static [u64] {
lazy_static::lazy_static! {
// (p-1) / 2
static ref LEGENDRE_EXP: Vec<u64> =
(num_bigint::BigUint::from_bytes_le((-<Fq as ff::Field>::ONE).to_repr().as_ref())/2usize).to_u64_digits();
}
&*LEGENDRE_EXP
}

/// Norm of Fq2 as extension field in i over Fq
#[inline]
fn norm(&self) -> Self::BasePrimeField {
let mut t0 = self.c0;
let mut t1 = self.c1;
t0 = t0.square();
t1 = t1.square();
t1 + t0
}
}

impl Fq2 {
#[inline]
pub const fn zero() -> Fq2 {
Expand Down Expand Up @@ -174,10 +198,6 @@ impl Fq2 {
res
}

pub fn legendre(&self) -> LegendreSymbol {
self.norm().legendre()
}

pub fn mul_assign(&mut self, other: &Self) {
let mut t1 = self.c0 * other.c0;
let mut t0 = self.c0 + self.c1;
Expand Down Expand Up @@ -298,15 +318,6 @@ impl Fq2 {
self.c1 += &t0;
}

/// Norm of Fq2 as extension field in i over Fq
pub fn norm(&self) -> Fq {
let mut t0 = self.c0;
let mut t1 = self.c1;
t0 = t0.square();
t1 = t1.square();
t1 + t0
}

pub fn invert(&self) -> CtOption<Self> {
let mut t1 = self.c1;
t1 = t1.square();
Expand Down Expand Up @@ -696,17 +707,6 @@ fn test_fq2_mul_nonresidue() {
}
}

#[test]
fn test_fq2_legendre() {
assert_eq!(LegendreSymbol::Zero, Fq2::ZERO.legendre());
// i^2 = -1
let mut m1 = Fq2::ONE;
m1 = m1.neg();
assert_eq!(LegendreSymbol::QuadraticResidue, m1.legendre());
m1.mul_by_nonresidue();
assert_eq!(LegendreSymbol::QuadraticNonResidue, m1.legendre());
}

#[test]
pub fn test_sqrt() {
let mut rng = XorShiftRng::from_seed([
Expand All @@ -716,7 +716,7 @@ pub fn test_sqrt() {

for _ in 0..10000 {
let a = Fq2::random(&mut rng);
if a.legendre() == LegendreSymbol::QuadraticNonResidue {
if a.legendre() == -Fq::ONE {
assert!(bool::from(a.sqrt().is_none()));
}
}
Expand All @@ -725,7 +725,7 @@ pub fn test_sqrt() {
let a = Fq2::random(&mut rng);
let mut b = a;
b.square_assign();
assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue);
assert_eq!(b.legendre(), Fq::ONE);

let b = b.sqrt().unwrap();
let mut negb = b;
Expand All @@ -738,7 +738,7 @@ pub fn test_sqrt() {
for _ in 0..10000 {
let mut b = c;
b.square_assign();
assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue);
assert_eq!(b.legendre(), Fq::ONE);

b = b.sqrt().unwrap();

Expand Down
10 changes: 8 additions & 2 deletions src/bn256/fr.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(feature = "asm")]
use crate::bn256::assembly::field_arithmetic_asm;
#[cfg(not(feature = "asm"))]
use crate::{field_arithmetic, field_specific};
use crate::{arithmetic::macx, field_arithmetic, field_specific};

#[cfg(feature = "bn256-table")]
#[rustfmt::skip]
Expand All @@ -18,7 +18,7 @@ pub use table::FR_TABLE;
#[cfg(not(feature = "bn256-table"))]
use crate::impl_from_u64;

use crate::arithmetic::{adc, mac, macx, sbb};
use crate::arithmetic::{adc, mac, sbb};
use crate::ff::{FromUniformBytes, PrimeField, WithSmallOrderMulGroup};
use crate::{
field_bits, field_common, impl_add_binop_specify_output, impl_binops_additive,
Expand Down Expand Up @@ -166,6 +166,7 @@ field_common!(
R3
);
impl_sum_prod!(Fr);
prime_field_legendre!(Fr);

#[cfg(not(feature = "bn256-table"))]
impl_from_u64!(Fr, R2);
Expand Down Expand Up @@ -470,4 +471,9 @@ mod test {

end_timer!(timer);
}

#[test]
fn test_quadratic_residue() {
crate::tests::field::random_quadratic_residue_test::<Fr>();
}
}
7 changes: 0 additions & 7 deletions src/bn256/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,3 @@ pub use fq12::*;
pub use fq2::*;
pub use fq6::*;
pub use fr::*;

#[derive(Debug, PartialEq, Eq)]
pub enum LegendreSymbol {
Zero = 0,
QuadraticResidue = 1,
QuadraticNonResidue = -1,
}
9 changes: 6 additions & 3 deletions src/hash_to_curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use pasta_curves::arithmetic::CurveExt;
use static_assertions::const_assert;
use subtle::{ConditionallySelectable, ConstantTimeEq};

use crate::legendre::Legendre;

/// Hashes over a message and writes the output to all of `buf`.
/// Modified from https://github.com/zcash/pasta_curves/blob/7e3fc6a4919f6462a32b79dd226cb2587b7961eb/src/hashtocurve.rs#L11.
fn hash_to_field<F: FromUniformBytes<64>>(
Expand Down Expand Up @@ -94,6 +96,7 @@ pub(crate) fn svdw_map_to_curve<C>(
) -> C
where
C: CurveExt,
C::Base: Legendre,
{
let one = C::Base::ONE;
let a = C::a();
Expand Down Expand Up @@ -128,7 +131,7 @@ where
// 14. gx1 = gx1 + B
let gx1 = gx1 + b;
// 15. e1 = is_square(gx1)
let e1 = gx1.sqrt().is_some();
let e1 = !gx1.ct_quadratic_non_residue();
han0110 marked this conversation as resolved.
Show resolved Hide resolved
// 16. x2 = c2 + tv4
let x2 = c2 + tv4;
// 17. gx2 = x2^2
Expand All @@ -140,7 +143,7 @@ where
// 20. gx2 = gx2 + B
let gx2 = gx2 + b;
// 21. e2 = is_square(gx2) AND NOT e1 # Avoid short-circuit logic ops
let e2 = gx2.sqrt().is_some() & (!e1);
let e2 = !gx2.ct_quadratic_non_residue() & (!e1);
han0110 marked this conversation as resolved.
Show resolved Hide resolved
// 22. x3 = tv2^2
let x3 = tv2.square();
// 23. x3 = x3 * tv3
Expand Down Expand Up @@ -182,7 +185,7 @@ pub(crate) fn svdw_hash_to_curve<'a, C>(
) -> Box<dyn Fn(&[u8]) -> C + 'a>
where
C: CurveExt,
C::Base: FromUniformBytes<64>,
C::Base: FromUniformBytes<64> + Legendre,
{
let [c1, c2, c3, c4] = svdw_precomputed_constants::<C>(z);

Expand Down
50 changes: 50 additions & 0 deletions src/legendre.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use ff::{Field, PrimeField};
use subtle::{Choice, ConstantTimeEq};

pub trait Legendre: Field {
type BasePrimeField: PrimeField;

// This is (p-1)/2 where p is the modulus of the base prime field
fn legendre_exp() -> &'static [u64];

fn norm(&self) -> Self::BasePrimeField;

#[inline]
fn legendre(&self) -> Self::BasePrimeField {
self.norm().pow(Self::legendre_exp())
}

#[inline]
fn ct_quadratic_residue(&self) -> Choice {
self.legendre().ct_eq(&Self::BasePrimeField::ONE)
}

#[inline]
fn ct_quadratic_non_residue(&self) -> Choice {
self.legendre().ct_eq(&-Self::BasePrimeField::ONE)
}
}

#[macro_export]
macro_rules! prime_field_legendre {
($field:ident ) => {
impl crate::legendre::Legendre for $field {
type BasePrimeField = Self;

#[inline]
fn legendre_exp() -> &'static [u64] {
lazy_static::lazy_static! {
// (p-1) / 2
static ref LEGENDRE_EXP: Vec<u64> =
(num_bigint::BigUint::from_bytes_le((-<$field as ff::Field>::ONE).to_repr().as_ref())/2usize).to_u64_digits();
}
&*LEGENDRE_EXP
}

#[inline]
fn norm(&self) -> Self::BasePrimeField {
self.clone()
}
}
};
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod arithmetic;
pub mod hash_to_curve;
#[macro_use]
pub mod legendre;
pub mod serde;

pub mod bn256;
Expand Down
Loading