Skip to content

Support 5 mod 8 case in SqrtPrecomputation #968

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions ff/src/biginteger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,13 @@ impl<const N: usize> BigInt<N> {
(((self.0[0] << 62) >> 62) % 4) as u8
}

#[doc(hidden)]
pub const fn mod_8(&self) -> u8 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, this and the above mod_4 generalize to any modulo power two and could be rewritten in a general way correct?

https://www.geeksforgeeks.org/compute-modulus-division-by-a-power-of-2-number

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exactly, the value a % (2^d) is equal to a & (2^d - 1) and this evaluation is more efficient, however I wrote implementation similar to the existing code for the sake of simplicity.

// To compute n % 8, we need to simply look at the
// 3 least significant bits of n, and check their value mod 8.
(((self.0[0] << 61) >> 61) % 8) as u8
}

/// Compute a right shift of `self`
/// This is equivalent to a (saturating) division by 2.
#[doc(hidden)]
Expand Down
58 changes: 52 additions & 6 deletions ff/src/fields/models/fp/montgomery_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,37 @@ pub trait MontConfig<const N: usize>: 'static + Sync + Send + Sized {
}
};

/// (MODULUS + 3) / 8 when MODULUS % 8 == 5. Used for square root precomputations.
#[doc(hidden)]
const MODULUS_PLUS_THREE_DIV_EIGHT: Option<BigInt<N>> = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very interesting! I too think it would be helpful to reference a source—perhaps from Hacker's Delight, a university lecture, or an ePrint paper—for further context.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is just a partial case of Tonneli-Shanks algorithm https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
For the case p=3 mod 4 the solution is straightforward and simple, for the case p=5 mod 8 we need one probing Legendre symbol evaluation and after that multiply by non-residue in appropriate power if needed. The most complicated case is p=1 mod 8 where the number of Legendre symbol evaluations can be different for different values.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @serhii023, thanks for the link—this adds some context. And BTW in general, optimizations are great and appreciated.

That being said, a reasonable concern here is that proof by example is not generally sufficient for a cryptographic library (which has a higher standard than general purpose software).

What are your thoughts? Would you be interested in writing a proof for the cases you've referenced?

TBH, maybe a cool side-project in Lean etc.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is a proof:
Let $x^2 \equiv a \pmod p$ is our quadratic equation where we need to find $x$ if one exists. Firstly, note that solutions modullo p exists iff $a$ is quadratic residue modullo p. Recall that $a \in \mathbb{F}_p$ is quadratic residue iff $a^{(p-1)/2} \equiv 1 \pmod p$ by Euler criterion or equivalently Legendre symbol $(\frac{a}{p}) = 1$ so that solutions to the equation $x^2 \equiv a \pmod p$ exist.

Consider than partial case where $p$ takes form $p=4k+3$ (case that arkworks already implements):
$x^2 \equiv a \pmod p$, so that $a$ is quadratic residue iff $a^{2k+1} \equiv 1 \pmod p$, multiplying by $a$ both sides of conjugation we obtain $a^{2k+2} \equiv a \pmod p$ so that $a^{2k+2} \equiv x^2 \pmod p$ so we can easily take square root of both sides as every exponent is even: $x = \pm a^{k+1} \pmod p \quad \square$

Consider our case $p=8k+5$ (@serhii023 proposal):
$x^2 \equiv a \pmod p$, so that $a$ is quadratic residue iff $a^{4k+2} \equiv 1 \pmod p$, here we could not simply multiply each side by $a$ as in previous case since the exponent will be odd. But instead since $a^{4k+2} \equiv 1^2 \equiv 1 \pmod p$ taking square root of $1$ gives us either $a^{2k+1} \equiv 1 \pmod p$ or $a^{2k+1} \equiv -1 \pmod p$. Consider each case separately:

  • If $a^{2k+1} \equiv 1 \pmod p$ than using the same technique as in $p=4k+3$ case multiplying both sides by $a$ we get $a^{2k+2} \equiv a \equiv x^2 \pmod p$ so that $x = \pm a^{k+1} \pmod p \quad \square$
  • If $a^{2k+1} \equiv -1 \pmod p$ than we could not obtain square root using the same technique, but recalling Tonneli-Shanks trick of multiplying each side by some non-residue we could obtain the square root. Firstly, $2 \in \mathbb{F}_p$ is always quadratic non-residue modullo $p$ as by Legendre symbol properties $(\frac{2}{p})=(-1)^{\frac{p^2 - 1}{8}} = (-1)^{8k^2 +10k + 3} = -1$. So that by Euler criterion: $2^{(p-1)/2} \equiv 2^{4k+2} \equiv -1 \pmod p$. So multiplying both sides of $a^{2k+1} \equiv -1 \pmod p$ by $2^{4k+2}$ we get the following conjugation: $a^{2k+1} 2^{4k+2} \equiv 1 \pmod p$. Multiplying both sides by $a$ we get $a^{2k+2} 2^{4k+2} \equiv a \equiv x^2 \pmod p$ so that $x = \pm a^{k+1} 2^{2k+1} \pmod p \quad \square$

Above proof is not a proof by example, but a general proof for all primes of form $p=8k+5$ and exactly this construction is implemented in @serhii023 PR.

match Self::MODULUS.mod_8() == 5 {
true => {
let (modulus_plus_three, carry) = Self::MODULUS.const_add_with_carry(&BigInt!("3"));
let mut result = modulus_plus_three.divide_by_2_round_down();
// Since modulus_plus_one is even, dividing by 2 results in a MSB of 0.
// Thus we can set MSB to `carry` to get the correct result of (MODULUS + 1) // 2:
result.0[N - 1] |= (carry as u64) << 63;
result = result.divide_by_2_round_down();

Some(result.divide_by_2_round_down())
},
false => None,
}
};

/// (MODULUS - 1) / 4 when MODULUS % 8 == 5. Used for square root precomputations.
#[doc(hidden)]
const MODULUS_MINUS_ONE_DIV_FOUR: Option<BigInt<N>> = {
match Self::MODULUS.mod_8() == 5 {
true => {
let (modulus_plus_three, _) = Self::MODULUS.const_sub_with_borrow(&BigInt::one());
let result = modulus_plus_three.divide_by_2_round_down();
Some(result.divide_by_2_round_down())
},
false => None,
}
};

/// Sets `a = a + b`.
#[inline(always)]
fn add_assign(a: &mut Fp<MontBackend<Self, N>, N>, b: &Fp<MontBackend<Self, N>, N>) {
Expand Down Expand Up @@ -548,12 +579,27 @@ pub const fn sqrt_precomputation<const N: usize, T: MontConfig<N>>(
}),
None => None,
},
_ => Some(SqrtPrecomputation::TonelliShanks {
two_adicity: <MontBackend<T, N>>::TWO_ADICITY,
quadratic_nonresidue_to_trace: T::TWO_ADIC_ROOT_OF_UNITY,
trace_of_modulus_minus_one_div_two:
&<Fp<MontBackend<T, N>, N>>::TRACE_MINUS_ONE_DIV_TWO.0,
}),
_ => match T::MODULUS.mod_8() {
5 => match (
T::MODULUS_PLUS_THREE_DIV_EIGHT.as_ref(),
T::MODULUS_MINUS_ONE_DIV_FOUR.as_ref(),
) {
(
Some(BigInt(modulus_plus_three_div_eight)),
Some(BigInt(modulus_minus_one_div_four)),
) => Some(SqrtPrecomputation::Case5Mod8 {
modulus_plus_three_div_eight,
modulus_minus_one_div_four,
}),
_ => None,
},
_ => Some(SqrtPrecomputation::TonelliShanks {
two_adicity: <MontBackend<T, N>>::TWO_ADICITY,
quadratic_nonresidue_to_trace: T::TWO_ADIC_ROOT_OF_UNITY,
trace_of_modulus_minus_one_div_two:
&<Fp<MontBackend<T, N>, N>>::TRACE_MINUS_ONE_DIV_TWO.0,
}),
},
}
}

Expand Down
30 changes: 30 additions & 0 deletions ff/src/fields/sqrt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ pub enum SqrtPrecomputation<F: crate::Field> {
Case3Mod4 {
modulus_plus_one_div_four: &'static [u64],
},
/// To be used when the modulus is 5 mod 8.
Case5Mod8 {
modulus_plus_three_div_eight: &'static [u64],
modulus_minus_one_div_four: &'static [u64],
},
}

impl<F: crate::Field> SqrtPrecomputation<F> {
Expand Down Expand Up @@ -144,6 +149,31 @@ impl<F: crate::Field> SqrtPrecomputation<F> {
let result = elem.pow(modulus_plus_one_div_four.as_ref());
(result.square() == *elem).then_some(result)
},
Self::Case5Mod8 {
modulus_plus_three_div_eight,
modulus_minus_one_div_four,
} => {
if elem.is_zero() {
return Some(F::zero());
}

let result;

// We have different solutions, if check_value is 1 or -1.
let check_value = elem.pow(modulus_minus_one_div_four.as_ref());
if check_value.is_one() {
result = elem.pow(modulus_plus_three_div_eight.as_ref());
} else if check_value.neg().is_one() {
let two: F = 2.into();
result = elem
.pow(modulus_plus_three_div_eight.as_ref())
.mul(two.pow(modulus_minus_one_div_four.as_ref()))
} else {
return None;
}

(result.square() == *elem).then_some(result)
},
}
}
}
Loading