elliptic-curve-tools 0.3.0

Extra Rust-Crypto elliptic-curve adaptors, functions, and macros
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use elliptic_curve::{Group, subtle::ConditionallySelectable};

/// A trait for a group that can compute the sum of products
/// of a slice of group elements and a slice of scalars.
/// The length of the slices must be equal.
pub trait SumOfProducts: Group {
    /// Compute the sum of products of a slice of group elements and a slice of scalars
    /// as `group[0] * scalar[0] + group[1] * scalar[1] + ... + group[n] * scalar[n]`.
    ///
    /// Avoids scalar-dependent table lookups by scanning each table and selecting
    /// entries with constant-time conditional selection. Use when any scalar
    /// is secret.
    fn sum_of_products(pairs: &[(Self::Scalar, Self)]) -> Self
    where
        Self: ConditionallySelectable;

    /// Compute the sum of products using variable-time table lookups.
    ///
    /// Uses scalar-derived window values as table indexes, which is faster
    /// than [`SumOfProducts::sum_of_products`] but potentially leaks scalar
    /// information through memory access patterns. Use only when every scalar
    /// is public, such as many verification-style workloads.
    fn sum_of_products_vartime(pairs: &[(Self::Scalar, Self)]) -> Self;

    /// Constant-time [`SumOfProducts::sum_of_products`] that reuses caller-owned
    /// scratch instead of allocating.
    ///
    /// Allocate `scratch` once with [`Scratch::new`](crate::Scratch::new) and reuse it
    /// across calls to avoid per-call heap traffic. The buffer sizes are validated at the
    /// start of the call; if `scratch` is too small for `pairs`, returns
    /// [`InsufficientScratch`](crate::InsufficientScratch) without mutating it.
    #[cfg(any(feature = "alloc", feature = "std"))]
    fn sum_of_products_inplace(
        pairs: &[(Self::Scalar, Self)],
        scratch: &mut crate::Scratch<Self>,
    ) -> Result<Self, crate::InsufficientScratch>
    where
        Self: ConditionallySelectable;

    /// Variable-time [`SumOfProducts::sum_of_products_vartime`] that reuses
    /// caller-owned scratch instead of allocating.
    ///
    /// Allocate `scratch` once with [`Scratch::new`](crate::Scratch::new) and reuse it
    /// across calls to avoid per-call heap traffic. The buffer sizes are validated at the
    /// start of the call; if `scratch` is too small for `pairs`, returns
    /// [`InsufficientScratch`](crate::InsufficientScratch) without mutating it.
    #[cfg(any(feature = "alloc", feature = "std"))]
    fn sum_of_products_vartime_inplace(
        pairs: &[(Self::Scalar, Self)],
        scratch: &mut crate::Scratch<Self>,
    ) -> Result<Self, crate::InsufficientScratch>;

    /// Constant-time [`SumOfProducts::sum_of_products`] reading pairs from an iterator,
    /// avoiding the need to first materialize a `&[(Scalar, Self)]` slice.
    ///
    /// Only the constant-time path offers this: it is always Straus, which streams over
    /// the pairs in a single pass. The variable-time path may use Pippenger, which
    /// revisits the points once per window and so cannot consume a one-pass iterator.
    #[cfg(any(feature = "alloc", feature = "std"))]
    fn sum_of_products_iter<I>(pairs: I) -> Self
    where
        Self: ConditionallySelectable,
        I: IntoIterator<Item = (Self::Scalar, Self)>,
        I::IntoIter: ExactSizeIterator;
}

#[cfg(any(feature = "alloc", feature = "std"))]
impl<G> SumOfProducts for G
where
    G: Group,
{
    fn sum_of_products(pairs: &[(Self::Scalar, Self)]) -> Self
    where
        Self: ConditionallySelectable,
    {
        crate::multiexp::multiexp(pairs)
    }

    fn sum_of_products_vartime(pairs: &[(Self::Scalar, Self)]) -> Self {
        crate::multiexp::multiexp_vartime(pairs)
    }

    fn sum_of_products_inplace(
        pairs: &[(Self::Scalar, Self)],
        scratch: &mut crate::Scratch<Self>,
    ) -> Result<Self, crate::InsufficientScratch>
    where
        Self: ConditionallySelectable,
    {
        crate::multiexp::multiexp_inplace(pairs, scratch)
    }

    fn sum_of_products_vartime_inplace(
        pairs: &[(Self::Scalar, Self)],
        scratch: &mut crate::Scratch<Self>,
    ) -> Result<Self, crate::InsufficientScratch> {
        crate::multiexp::multiexp_vartime_inplace(pairs, scratch)
    }

    fn sum_of_products_iter<I>(pairs: I) -> Self
    where
        Self: ConditionallySelectable,
        I: IntoIterator<Item = (Self::Scalar, Self)>,
        I::IntoIter: ExactSizeIterator,
    {
        crate::multiexp::multiexp_iter(pairs)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{LengthMismatch, Precomputed, Scratch, ScratchBuffer};
    #[cfg(all(feature = "alloc", not(feature = "std")))]
    use alloc::vec::Vec;
    use elliptic_curve::{Field, PrimeField};
    #[cfg(feature = "std")]
    use std::vec::Vec;

    fn pseudo_random_scalars<G>(n: usize, seed: u64) -> Vec<G::Scalar>
    where
        G: Group,
    {
        let mut state = seed | 1;
        (0..n)
            .map(|_| {
                let mut repr = <G::Scalar as PrimeField>::Repr::default();
                let bytes: &mut [u8] = repr.as_mut();
                for b in bytes.iter_mut() {
                    state ^= state << 13;
                    state ^= state >> 7;
                    state ^= state << 17;
                    *b = (state & 0xff) as u8;
                }
                bytes[0] = 0;
                Option::<G::Scalar>::from(G::Scalar::from_repr(repr)).unwrap_or(G::Scalar::ONE)
            })
            .collect()
    }

    fn assert_precomputed_matches<G>()
    where
        G: ConditionallySelectable + Group,
        G::Scalar: Field,
    {
        let generator = G::generator();
        for &n in &[1usize, 2, 5, 33, 64, 129] {
            let points: Vec<G> = pseudo_random_scalars::<G>(n, 0xA1 ^ n as u64)
                .iter()
                .map(|s| generator * s)
                .collect();
            let scalars = pseudo_random_scalars::<G>(n, 0xB2 ^ n as u64);
            let naive: G = points
                .iter()
                .zip(scalars.iter())
                .map(|(point, scalar)| *point * scalar)
                .sum();

            let precomputed = Precomputed::new(&points);
            assert_eq!(precomputed.len(), n);
            assert_eq!(precomputed.sum_of_products(&scalars), Ok(naive), "ct n={n}");
            assert_eq!(
                precomputed.sum_of_products_vartime(&scalars),
                Ok(naive),
                "vartime n={n}"
            );
            assert_eq!(
                precomputed.sum_of_products_iter(scalars.iter().copied()),
                Ok(naive),
                "iter n={n}"
            );
        }

        let precomputed = Precomputed::new(&[generator, generator, generator]);
        assert!(matches!(
            precomputed.sum_of_products_vartime(&[<G::Scalar as Field>::ONE; 2]),
            Err(LengthMismatch {
                points: 3,
                scalars: 2
            })
        ));
    }

    fn varied_pairs<G>(n: usize) -> Vec<(G::Scalar, G)>
    where
        G: Group,
        G::Scalar: Field,
    {
        let mut acc = <G::Scalar as Field>::ONE;
        (0..n)
            .map(|_| {
                acc = acc.double() + <G::Scalar as Field>::ONE;
                (acc, G::generator())
            })
            .collect()
    }

    // High-entropy (deterministic) scalars to stress the signed-digit recoder across
    // many bit patterns. Clearing the top byte keeps each value below the group order.
    fn pseudo_random_pairs<G>(n: usize, seed: u64) -> Vec<(G::Scalar, G)>
    where
        G: Group,
    {
        let g = G::generator();
        let mut state = seed | 1;
        (0..n)
            .map(|_| {
                let mut repr = <G::Scalar as PrimeField>::Repr::default();
                let bytes: &mut [u8] = repr.as_mut();
                for b in bytes.iter_mut() {
                    state ^= state << 13;
                    state ^= state >> 7;
                    state ^= state << 17;
                    *b = (state & 0xff) as u8;
                }
                bytes[0] = 0; // guarantee value < group order
                let scalar =
                    Option::<G::Scalar>::from(G::Scalar::from_repr(repr)).unwrap_or(G::Scalar::ONE);
                (scalar, g)
            })
            .collect()
    }

    fn assert_random_matches_naive<G>(sizes: &[usize])
    where
        G: ConditionallySelectable + Group + SumOfProducts,
    {
        for (i, &n) in sizes.iter().enumerate() {
            let pairs = pseudo_random_pairs::<G>(n, 0x9E37_79B9_7F4A_7C15 ^ (n as u64) ^ i as u64);
            let naive: G = pairs.iter().map(|(scalar, point)| *point * scalar).sum();
            assert_eq!(G::sum_of_products(&pairs), naive, "ct n={n}");
            assert_eq!(G::sum_of_products_vartime(&pairs), naive, "vartime n={n}");
            assert_eq!(
                G::sum_of_products_iter(pairs.iter().copied()),
                naive,
                "iter n={n}"
            );
        }
    }

    fn assert_inplace_matches_allocating<G>()
    where
        G: ConditionallySelectable + Group + SumOfProducts,
        G::Scalar: Field,
    {
        // One scratch sized for the largest case, reused for every size and for both
        // the constant- and variable-time paths, exercising the capacity contract.
        let mut scratch = Scratch::<G>::new(200);

        for &n in &[2usize, 5, 64, 130, 200] {
            let pairs = varied_pairs::<G>(n);
            let naive: G = pairs.iter().map(|(scalar, point)| *point * scalar).sum();

            assert_eq!(G::sum_of_products_inplace(&pairs, &mut scratch), Ok(naive));
            assert_eq!(
                G::sum_of_products_vartime_inplace(&pairs, &mut scratch),
                Ok(naive)
            );
        }
    }

    fn assert_undersized_scratch_errors<G>()
    where
        G: ConditionallySelectable + Group + SumOfProducts,
        G::Scalar: Field,
    {
        let pairs = varied_pairs::<G>(64);
        let mut tiny = Scratch::<G>::new(2);

        assert!(matches!(
            G::sum_of_products_inplace(&pairs, &mut tiny),
            Err(e) if e.buffer == ScratchBuffer::Digits && e.provided < e.required
        ));
        assert!(matches!(
            G::sum_of_products_vartime_inplace(&pairs, &mut tiny),
            Err(e) if e.buffer == ScratchBuffer::Digits && e.provided < e.required
        ));
    }

    fn assert_straus_sums_scalar_products<G>()
    where
        G: ConditionallySelectable + Group + SumOfProducts,
        G::Scalar: Field,
    {
        let pairs = [
            (<G::Scalar as Field>::ONE, G::generator()),
            (<G::Scalar as Field>::ONE.double(), G::generator()),
        ];

        let expected = G::generator() + G::generator().double();

        assert_eq!(G::sum_of_products(&pairs), expected);
    }

    fn assert_pippenger_sums_scalar_products<G>()
    where
        G: ConditionallySelectable + Group + SumOfProducts,
        G::Scalar: Field,
    {
        let scalar = <G::Scalar as Field>::ONE.double();
        let point = G::generator();
        let pairs = vec![(scalar, point); 130];
        let expected: G = pairs.iter().map(|(scalar, point)| *point * scalar).sum();

        assert_eq!(G::sum_of_products(&pairs), expected);
    }

    fn assert_variable_time_matches_constant_time<G>()
    where
        G: ConditionallySelectable + Group + SumOfProducts,
        G::Scalar: Field,
    {
        let scalar = <G::Scalar as Field>::ONE.double();
        let point = G::generator();
        let pairs = vec![(scalar, point); 130];

        assert_eq!(
            G::sum_of_products_vartime(&pairs),
            G::sum_of_products(&pairs)
        );
    }

    #[test]
    fn straus_sums_scalar_products() {
        assert_straus_sums_scalar_products::<k256::ProjectivePoint>();
        assert_straus_sums_scalar_products::<p256::ProjectivePoint>();
        assert_straus_sums_scalar_products::<p384::ProjectivePoint>();
        assert_straus_sums_scalar_products::<p521::ProjectivePoint>();
        assert_straus_sums_scalar_products::<bp256::r1::ProjectivePoint>();
        assert_straus_sums_scalar_products::<bp256::t1::ProjectivePoint>();
        assert_straus_sums_scalar_products::<bp384::r1::ProjectivePoint>();
        assert_straus_sums_scalar_products::<bp384::t1::ProjectivePoint>();
        assert_straus_sums_scalar_products::<curve25519_dalek::RistrettoPoint>();
        assert_straus_sums_scalar_products::<curve25519_dalek::EdwardsPoint>();
    }

    #[test]
    fn pippenger_sums_scalar_products() {
        assert_pippenger_sums_scalar_products::<k256::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<p256::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<p384::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<p521::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<bp256::r1::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<bp256::t1::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<bp384::r1::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<bp384::t1::ProjectivePoint>();
        assert_pippenger_sums_scalar_products::<curve25519_dalek::RistrettoPoint>();
        assert_pippenger_sums_scalar_products::<curve25519_dalek::EdwardsPoint>();
    }

    #[test]
    fn precomputed_matches_naive() {
        assert_precomputed_matches::<k256::ProjectivePoint>();
        assert_precomputed_matches::<p256::ProjectivePoint>();
        assert_precomputed_matches::<p384::ProjectivePoint>();
        assert_precomputed_matches::<p521::ProjectivePoint>();
        assert_precomputed_matches::<bp256::r1::ProjectivePoint>();
        assert_precomputed_matches::<bp256::t1::ProjectivePoint>();
        assert_precomputed_matches::<bp384::r1::ProjectivePoint>();
        assert_precomputed_matches::<bp384::t1::ProjectivePoint>();
        assert_precomputed_matches::<curve25519_dalek::RistrettoPoint>();
        assert_precomputed_matches::<curve25519_dalek::EdwardsPoint>();
    }

    #[test]
    fn random_matches_naive() {
        // Small/medium sizes across every curve (different bit lengths exercise the
        // recoder's window count and carry differently).
        let small = [2usize, 3, 7, 31, 63, 127, 130, 200];
        assert_random_matches_naive::<k256::ProjectivePoint>(&small);
        assert_random_matches_naive::<p256::ProjectivePoint>(&small);
        assert_random_matches_naive::<p384::ProjectivePoint>(&small);
        assert_random_matches_naive::<p521::ProjectivePoint>(&small);
        assert_random_matches_naive::<bp256::r1::ProjectivePoint>(&small);
        assert_random_matches_naive::<bp256::t1::ProjectivePoint>(&small);
        assert_random_matches_naive::<bp384::r1::ProjectivePoint>(&small);
        assert_random_matches_naive::<bp384::t1::ProjectivePoint>(&small);
        assert_random_matches_naive::<curve25519_dalek::RistrettoPoint>(&small);
        assert_random_matches_naive::<curve25519_dalek::EdwardsPoint>(&small);
        // Larger sizes (one representative curve) to cover every Pippenger window.
        assert_random_matches_naive::<k256::ProjectivePoint>(&[401, 801]);
    }

    #[test]
    fn variable_time_matches_constant_time() {
        assert_variable_time_matches_constant_time::<k256::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<p256::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<p384::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<p521::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<bp256::r1::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<bp256::t1::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<bp384::r1::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<bp384::t1::ProjectivePoint>();
        assert_variable_time_matches_constant_time::<curve25519_dalek::RistrettoPoint>();
        assert_variable_time_matches_constant_time::<curve25519_dalek::EdwardsPoint>();
    }

    #[test]
    fn inplace_matches_allocating() {
        assert_inplace_matches_allocating::<k256::ProjectivePoint>();
        assert_inplace_matches_allocating::<p256::ProjectivePoint>();
        assert_inplace_matches_allocating::<p384::ProjectivePoint>();
        assert_inplace_matches_allocating::<p521::ProjectivePoint>();
        assert_inplace_matches_allocating::<bp256::r1::ProjectivePoint>();
        assert_inplace_matches_allocating::<bp256::t1::ProjectivePoint>();
        assert_inplace_matches_allocating::<bp384::r1::ProjectivePoint>();
        assert_inplace_matches_allocating::<bp384::t1::ProjectivePoint>();
        assert_inplace_matches_allocating::<curve25519_dalek::RistrettoPoint>();
        assert_inplace_matches_allocating::<curve25519_dalek::EdwardsPoint>();
    }

    #[test]
    fn undersized_scratch_errors() {
        assert_undersized_scratch_errors::<k256::ProjectivePoint>();
        assert_undersized_scratch_errors::<p256::ProjectivePoint>();
        assert_undersized_scratch_errors::<p384::ProjectivePoint>();
        assert_undersized_scratch_errors::<p521::ProjectivePoint>();
        assert_undersized_scratch_errors::<bp256::r1::ProjectivePoint>();
        assert_undersized_scratch_errors::<bp256::t1::ProjectivePoint>();
        assert_undersized_scratch_errors::<bp384::r1::ProjectivePoint>();
        assert_undersized_scratch_errors::<bp384::t1::ProjectivePoint>();
        assert_undersized_scratch_errors::<curve25519_dalek::RistrettoPoint>();
        assert_undersized_scratch_errors::<curve25519_dalek::EdwardsPoint>();
    }
}