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

elliptic_curve: add BatchInvert and BatchNormalize traits #1376

Merged
merged 42 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
3369beb
Introduced `InvertBatch` and implemented
ycscaly Nov 9, 2023
3436859
Update elliptic-curve/src/ops.rs
ycscaly Nov 12, 2023
1b235ab
Using `Choice` as the hard-coded `Output` for `InvertBatch`
ycscaly Nov 12, 2023
7e06df1
Merge remote-tracking branch 'yc/batch_invert' into batch_invert
ycscaly Nov 12, 2023
6460443
removed comment
ycscaly Nov 12, 2023
2a3d0c4
Taking slice instead of vector
ycscaly Nov 12, 2023
7694270
not in-place
ycscaly Nov 12, 2023
e8c3ea2
`ToAffineBatch`
ycscaly Nov 12, 2023
71521a5
temporary set `version = "0.13.0-pre.5"`
ycscaly Nov 12, 2023
a35e9f0
revert
ycscaly Nov 12, 2023
8b120bc
expose ToAffineBatch
ycscaly Nov 12, 2023
2ac2bf4
Refactor name
ycscaly Nov 12, 2023
caa8f04
Take ref
ycscaly Nov 12, 2023
99bc02c
Take slice
ycscaly Nov 12, 2023
71bf94c
rename
ycscaly Nov 12, 2023
6d80ad8
doc
ycscaly Nov 12, 2023
8133e50
Update elliptic-curve/src/ops.rs
ycscaly Nov 12, 2023
505af72
CR
ycscaly Nov 12, 2023
233ed7f
Merge remote-tracking branch 'yc/batch_invert' into batch_invert
ycscaly Nov 12, 2023
5a4dff8
Provided functions in `Invert`
ycscaly Nov 12, 2023
62521a9
Refactored `ToAffineBatch`
ycscaly Nov 12, 2023
91dea56
CR
ycscaly Nov 13, 2023
8ec02ee
Refactor `Normalize`
ycscaly Nov 13, 2023
aa1b462
Added `to_affine`
ycscaly Nov 13, 2023
b6061bd
Merge branch 'master' into batch_invert
ycscaly Nov 13, 2023
f6eca00
condition on `Curve`
ycscaly Nov 13, 2023
822a1ba
rename
ycscaly Nov 13, 2023
f536c74
change to `vec`
ycscaly Nov 13, 2023
51b9703
CR
ycscaly Nov 14, 2023
2d8eb47
rename
ycscaly Nov 14, 2023
0e90c0b
clippy
ycscaly Nov 14, 2023
719afbb
CR
ycscaly Nov 14, 2023
ef22c20
Refactored trait
ycscaly Nov 14, 2023
e557e01
Missing doc
ycscaly Nov 14, 2023
2555db1
Missing doc oops
ycscaly Nov 14, 2023
fe4d241
Remove `AsRef`
ycscaly Nov 14, 2023
ec3669b
Remove const parameter from trait fn
ycscaly Nov 14, 2023
0b9e030
Remove reference from trait fn
ycscaly Nov 14, 2023
b3bdfb1
Update elliptic-curve/src/arithmetic.rs
ycscaly Nov 14, 2023
0ced10a
Trying as-ref again
ycscaly Nov 14, 2023
dd7b7b6
compilation
ycscaly Nov 14, 2023
017fa29
as-ref suggestion
ycscaly Nov 14, 2023
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
18 changes: 18 additions & 0 deletions elliptic-curve/src/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,21 @@ pub trait PrimeCurveArithmetic:
/// Prime order elliptic curve group.
type CurveGroup: group::prime::PrimeCurve<Affine = <Self as CurveArithmetic>::AffinePoint>;
}

/// Normalize point(s) in projective representation by converting them to their affine ones.
pub trait Normalize: group::Curve {
/// Perform a batched conversion to affine representation on a sequence of projective points
/// at an amortized cost that should be practically as efficient as a single conversion.
/// Internally, implementors should rely upon `InvertBatch`.
/// This variation takes a const-generic array and thus does not require `alloc`.
fn batch_normalize_array<const N: usize>(points: &[Self; N]) -> [Self::AffineRepr; N];

/// Perform a batched conversion to affine representation on a sequence of projective points
/// at an amortized cost that should be practically as efficient as a single conversion.
/// Internally, implementors should rely upon `InvertBatch`.
/// This variation takes a (possibly dynamically allocated) slice and returns `FromIterator<Self::AffinePoint>`
/// allowing it to work with any container.
/// However, this also requires to make dynamic allocations and as such requires `alloc`.
#[cfg(feature = "alloc")]
fn batch_normalize_vec(points: alloc::vec::Vec<Self>) -> alloc::vec::Vec<Self::AffineRepr>;
ycscaly marked this conversation as resolved.
Show resolved Hide resolved
}
2 changes: 1 addition & 1 deletion elliptic-curve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ pub use zeroize;
#[cfg(feature = "arithmetic")]
pub use {
crate::{
arithmetic::{CurveArithmetic, PrimeCurveArithmetic},
arithmetic::{CurveArithmetic, Normalize, PrimeCurveArithmetic},
point::{AffinePoint, ProjectivePoint},
public_key::PublicKey,
scalar::{NonZeroScalar, Scalar},
Expand Down
112 changes: 112 additions & 0 deletions elliptic-curve/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub use core::ops::{Add, AddAssign, Mul, Neg, Shr, ShrAssign, Sub, SubAssign};

use crypto_bigint::Integer;
use group::Group;
use subtle::{Choice, ConditionallySelectable, CtOption};

/// Perform an inversion on a field element (i.e. base field element or scalar)
pub trait Invert {
Expand All @@ -23,6 +24,117 @@ pub trait Invert {
// Fall back on constant-time implementation by default.
self.invert()
}

/// Perform a batched inversion on a sequence of field elements (i.e. base field elements or scalars)
/// at an amortized cost that should be practically as efficient as a single inversion.
/// This variation takes a const-generic array and thus does not require `alloc`.
fn batch_invert_array<const N: usize>(field_elements: &[Self; N]) -> CtOption<[Self; N]>
where
Self: Invert<Output = CtOption<Self>>
+ Mul<Self, Output = Self>
+ Copy
+ Default
+ ConditionallySelectable,
{
let mut field_elements_multiples = [field_elements[0]; N];
let mut field_elements_multiples_inverses = [field_elements[0]; N];
let mut field_elements_inverses = [field_elements[0]; N];

let inversion_succeeded = invert_batch_internal(
field_elements,
&mut field_elements_multiples,
&mut field_elements_multiples_inverses,
&mut field_elements_inverses,
);

CtOption::new(field_elements_inverses, inversion_succeeded)
}

/// Perform a batched inversion on a sequence of field elements (i.e. base field elements or scalars)
/// at an amortized cost that should be practically as efficient as a single inversion.
/// This variation takes a (possibly dynamically allocated) sequence and returns `FromIterator<T>`, which allows it to work with any container (e.g. `Vec<_>`).
/// However, this also requires to make dynamic allocations and as such requires `alloc`.
#[cfg(feature = "alloc")]
fn batch_invert_vec(field_elements: alloc::vec::Vec<Self>) -> CtOption<alloc::vec::Vec<Self>>
where
Self: Invert<Output = CtOption<Self>>
+ Mul<Self, Output = Self>
+ Copy
+ Default
+ ConditionallySelectable,
{
let mut field_elements_multiples: alloc::vec::Vec<Self> = (0..field_elements.len())
.map(|i| field_elements[i])
.collect();
let mut field_elements_multiples_inverses: alloc::vec::Vec<Self> = (0..field_elements
.len())
.map(|i| field_elements[i])
.collect();
let mut field_elements_inverses: alloc::vec::Vec<Self> = (0..field_elements.len())
.map(|i| field_elements[i])
.collect();

let inversion_succeeded = invert_batch_internal(
&field_elements,
field_elements_multiples.as_mut(),
field_elements_multiples_inverses.as_mut(),
field_elements_inverses.as_mut(),
);

CtOption::new(
field_elements_inverses.into_iter().collect(),
inversion_succeeded,
)
}
}

/// Implements "Montgomery's trick", a trick for computing many modular inverses at once.
///
/// "Montgomery's trick" works by reducing the problem of computing `n` inverses
/// to computing a single inversion, plus some storage and `O(n)` extra multiplications.
///
/// See: https://iacr.org/archive/pkc2004/29470042/29470042.pdf section 2.2.
fn invert_batch_internal<
T: Invert<Output = CtOption<T>> + Mul<T, Output = T> + Default + ConditionallySelectable,
>(
field_elements: &[T],
field_elements_multiples: &mut [T],
field_elements_multiples_inverses: &mut [T],
field_elements_inverses: &mut [T],
) -> Choice {
let batch_size = field_elements.len();
if batch_size == 0
|| batch_size != field_elements_multiples.len()
|| batch_size != field_elements_multiples_inverses.len()
{
return Choice::from(0);
}

field_elements_multiples[0] = field_elements[0];
for i in 1..batch_size {
// $ a_n = a_{n-1}*x_n $
field_elements_multiples[i] = field_elements_multiples[i - 1] * field_elements[i];
}

field_elements_multiples[batch_size - 1]
.invert()
.map(|multiple_of_inverses_of_all_field_elements| {
field_elements_multiples_inverses[batch_size - 1] =
multiple_of_inverses_of_all_field_elements;
for i in (1..batch_size).rev() {
// $ a_{n-1} = {a_n}^{-1}*x_n $
field_elements_multiples_inverses[i - 1] =
field_elements_multiples_inverses[i] * field_elements[i];
}

field_elements_inverses[0] = field_elements_multiples_inverses[0];
for i in 1..batch_size {
// $ {x_n}^{-1} = a_{n}^{-1}*a_{n-1} $
field_elements_inverses[i] =
field_elements_multiples_inverses[i] * field_elements_multiples[i - 1];
}
})
.is_some()
}

/// Linear combination.
Expand Down