Skip to content

Commit

Permalink
elliptic-curve: add LinearCombinationExt trait (#1405)
Browse files Browse the repository at this point in the history
Adds a trait which is generic around its input parameters for computing
linear combinations.

This allows for different strategies depending on the input parameter
type, for example using stack-allocated intermediates sized to match an
input array, which works on `no_std` targets.

Or, if a slice is passed, intermediate `Vec`s can be used when the
`alloc` feature is available.

Also adds a blanket impl for the old `LinearCombination` trait which
calls the new trait.
  • Loading branch information
tarcieri authored Nov 15, 2023
1 parent ce2dc02 commit 37507fd
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions elliptic-curve/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,34 @@ pub trait LinearCombination: Group {
}
}

/// Linear combination (extended version).
///
/// This trait enables providing an optimized implementation of
/// linear combinations (e.g. Shamir's Trick).
// TODO(tarcieri): replace the current `LinearCombination` with this in the next release
pub trait LinearCombinationExt<PointsAndScalars>: group::Curve
where
PointsAndScalars: AsRef<[(Self, Self::Scalar)]>,
{
/// Calculates `x1 * k1 + ... + xn * kn`.
fn lincomb_ext(points_and_scalars: &PointsAndScalars) -> Self {
points_and_scalars
.as_ref()
.iter()
.copied()
.map(|(point, scalar)| point * scalar)
.sum()
}
}

/// Blanket impl of the legacy [`LinearCombination`] trait for types which impl the new
/// [`LinearCombinationExt`] trait for 2-element arrays.
impl<P: LinearCombinationExt<[(P, Self::Scalar); 2]>> LinearCombination for P {
fn lincomb(x: &Self, k: &Self::Scalar, y: &Self, l: &Self::Scalar) -> Self {
Self::lincomb_ext(&[(*x, *k), (*y, *l)])
}
}

/// Multiplication by the generator.
///
/// May use optimizations (e.g. precomputed tables) when available.
Expand Down

0 comments on commit 37507fd

Please sign in to comment.