Skip to content

Commit 37507fd

Browse files
authored
elliptic-curve: add LinearCombinationExt trait (#1405)
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.
1 parent ce2dc02 commit 37507fd

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

elliptic-curve/src/ops.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,34 @@ pub trait LinearCombination: Group {
160160
}
161161
}
162162

163+
/// Linear combination (extended version).
164+
///
165+
/// This trait enables providing an optimized implementation of
166+
/// linear combinations (e.g. Shamir's Trick).
167+
// TODO(tarcieri): replace the current `LinearCombination` with this in the next release
168+
pub trait LinearCombinationExt<PointsAndScalars>: group::Curve
169+
where
170+
PointsAndScalars: AsRef<[(Self, Self::Scalar)]>,
171+
{
172+
/// Calculates `x1 * k1 + ... + xn * kn`.
173+
fn lincomb_ext(points_and_scalars: &PointsAndScalars) -> Self {
174+
points_and_scalars
175+
.as_ref()
176+
.iter()
177+
.copied()
178+
.map(|(point, scalar)| point * scalar)
179+
.sum()
180+
}
181+
}
182+
183+
/// Blanket impl of the legacy [`LinearCombination`] trait for types which impl the new
184+
/// [`LinearCombinationExt`] trait for 2-element arrays.
185+
impl<P: LinearCombinationExt<[(P, Self::Scalar); 2]>> LinearCombination for P {
186+
fn lincomb(x: &Self, k: &Self::Scalar, y: &Self, l: &Self::Scalar) -> Self {
187+
Self::lincomb_ext(&[(*x, *k), (*y, *l)])
188+
}
189+
}
190+
163191
/// Multiplication by the generator.
164192
///
165193
/// May use optimizations (e.g. precomputed tables) when available.

0 commit comments

Comments
 (0)