dalek_ff_group_mirror/
lib.rs

1#![allow(deprecated)]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![no_std] // Prevents writing new code, in what should be a simple wrapper, which requires std
4#![doc = include_str!("../README.md")]
5#![allow(clippy::redundant_closure_call)]
6
7use core::{
8  borrow::Borrow,
9  ops::{Deref, Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign},
10  iter::{Iterator, Sum, Product},
11  hash::{Hash, Hasher},
12};
13
14use zeroize::Zeroize;
15use subtle::{ConstantTimeEq, ConditionallySelectable};
16
17use rand_core::RngCore;
18use digest::{consts::U64, Digest, HashMarker};
19
20use subtle::{Choice, CtOption};
21
22pub use curve25519_dalek as dalek;
23
24use dalek::{
25  constants::{self, BASEPOINT_ORDER},
26  scalar::Scalar as DScalar,
27  edwards::{EdwardsPoint as DEdwardsPoint, EdwardsBasepointTable, CompressedEdwardsY},
28  ristretto::{RistrettoPoint as DRistrettoPoint, RistrettoBasepointTable, CompressedRistretto},
29};
30pub use constants::{ED25519_BASEPOINT_TABLE, RISTRETTO_BASEPOINT_TABLE};
31
32use group::{
33  ff::{Field, PrimeField, FieldBits, PrimeFieldBits},
34  Group, GroupEncoding,
35  prime::PrimeGroup,
36};
37
38mod field;
39pub use field::FieldElement;
40
41// Use black_box when possible
42#[rustversion::since(1.66)]
43use core::hint::black_box;
44#[rustversion::before(1.66)]
45fn black_box<T>(val: T) -> T {
46  val
47}
48
49fn u8_from_bool(bit_ref: &mut bool) -> u8 {
50  let bit_ref = black_box(bit_ref);
51
52  let mut bit = black_box(*bit_ref);
53  #[allow(clippy::cast_lossless)]
54  let res = black_box(bit as u8);
55  bit.zeroize();
56  debug_assert!((res | 1) == 1);
57
58  bit_ref.zeroize();
59  res
60}
61
62// Convert a boolean to a Choice in a *presumably* constant time manner
63fn choice(mut value: bool) -> Choice {
64  Choice::from(u8_from_bool(&mut value))
65}
66
67macro_rules! deref_borrow {
68  ($Source: ident, $Target: ident) => {
69    impl Deref for $Source {
70      type Target = $Target;
71
72      fn deref(&self) -> &Self::Target {
73        &self.0
74      }
75    }
76
77    impl Borrow<$Target> for $Source {
78      fn borrow(&self) -> &$Target {
79        &self.0
80      }
81    }
82
83    impl Borrow<$Target> for &$Source {
84      fn borrow(&self) -> &$Target {
85        &self.0
86      }
87    }
88  };
89}
90
91macro_rules! constant_time {
92  ($Value: ident, $Inner: ident) => {
93    impl ConstantTimeEq for $Value {
94      fn ct_eq(&self, other: &Self) -> Choice {
95        self.0.ct_eq(&other.0)
96      }
97    }
98
99    impl ConditionallySelectable for $Value {
100      fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
101        $Value($Inner::conditional_select(&a.0, &b.0, choice))
102      }
103    }
104  };
105}
106pub(crate) use constant_time;
107
108macro_rules! math_op {
109  (
110    $Value: ident,
111    $Other: ident,
112    $Op: ident,
113    $op_fn: ident,
114    $Assign: ident,
115    $assign_fn: ident,
116    $function: expr
117  ) => {
118    impl $Op<$Other> for $Value {
119      type Output = $Value;
120      fn $op_fn(self, other: $Other) -> Self::Output {
121        Self($function(self.0, other.0))
122      }
123    }
124    impl $Assign<$Other> for $Value {
125      fn $assign_fn(&mut self, other: $Other) {
126        self.0 = $function(self.0, other.0);
127      }
128    }
129    impl<'a> $Op<&'a $Other> for $Value {
130      type Output = $Value;
131      fn $op_fn(self, other: &'a $Other) -> Self::Output {
132        Self($function(self.0, other.0))
133      }
134    }
135    impl<'a> $Assign<&'a $Other> for $Value {
136      fn $assign_fn(&mut self, other: &'a $Other) {
137        self.0 = $function(self.0, other.0);
138      }
139    }
140  };
141}
142pub(crate) use math_op;
143
144macro_rules! math {
145  ($Value: ident, $Factor: ident, $add: expr, $sub: expr, $mul: expr) => {
146    math_op!($Value, $Value, Add, add, AddAssign, add_assign, $add);
147    math_op!($Value, $Value, Sub, sub, SubAssign, sub_assign, $sub);
148    math_op!($Value, $Factor, Mul, mul, MulAssign, mul_assign, $mul);
149  };
150}
151pub(crate) use math;
152
153macro_rules! math_neg {
154  ($Value: ident, $Factor: ident, $add: expr, $sub: expr, $mul: expr) => {
155    math!($Value, $Factor, $add, $sub, $mul);
156
157    impl Neg for $Value {
158      type Output = Self;
159      fn neg(self) -> Self::Output {
160        Self(-self.0)
161      }
162    }
163  };
164}
165
166/// Wrapper around the dalek Scalar type.
167#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Zeroize)]
168pub struct Scalar(pub DScalar);
169deref_borrow!(Scalar, DScalar);
170constant_time!(Scalar, DScalar);
171math_neg!(Scalar, Scalar, DScalar::add, DScalar::sub, DScalar::mul);
172
173macro_rules! from_wrapper {
174  ($uint: ident) => {
175    impl From<$uint> for Scalar {
176      fn from(a: $uint) -> Scalar {
177        Scalar(DScalar::from(a))
178      }
179    }
180  };
181}
182
183from_wrapper!(u8);
184from_wrapper!(u16);
185from_wrapper!(u32);
186from_wrapper!(u64);
187from_wrapper!(u128);
188
189impl Scalar {
190  pub fn pow(&self, other: Scalar) -> Scalar {
191    let mut table = [Scalar::ONE; 16];
192    table[1] = *self;
193    for i in 2 .. 16 {
194      table[i] = table[i - 1] * self;
195    }
196
197    let mut res = Scalar::ONE;
198    let mut bits = 0;
199    for (i, mut bit) in other.to_le_bits().iter_mut().rev().enumerate() {
200      bits <<= 1;
201      let mut bit = u8_from_bool(&mut bit);
202      bits |= bit;
203      bit.zeroize();
204
205      if ((i + 1) % 4) == 0 {
206        if i != 3 {
207          for _ in 0 .. 4 {
208            res *= res;
209          }
210        }
211        res *= table[usize::from(bits)];
212        bits = 0;
213      }
214    }
215    res
216  }
217
218  /// Perform wide reduction on a 64-byte array to create a Scalar without bias.
219  pub fn from_bytes_mod_order_wide(bytes: &[u8; 64]) -> Scalar {
220    Self(DScalar::from_bytes_mod_order_wide(bytes))
221  }
222
223  /// Derive a Scalar without bias from a digest via wide reduction.
224  pub fn from_hash<D: Digest<OutputSize = U64> + HashMarker>(hash: D) -> Scalar {
225    let mut output = [0u8; 64];
226    output.copy_from_slice(&hash.finalize());
227    let res = Scalar(DScalar::from_bytes_mod_order_wide(&output));
228    output.zeroize();
229    res
230  }
231}
232
233impl Field for Scalar {
234  const ZERO: Scalar = Scalar(DScalar::ZERO);
235  const ONE: Scalar = Scalar(DScalar::ONE);
236
237  fn random(rng: impl RngCore) -> Self {
238    Self(<DScalar as Field>::random(rng))
239  }
240
241  fn square(&self) -> Self {
242    Self(self.0.square())
243  }
244  fn double(&self) -> Self {
245    Self(self.0.double())
246  }
247  fn invert(&self) -> CtOption<Self> {
248    <DScalar as Field>::invert(&self.0).map(Self)
249  }
250
251  fn sqrt(&self) -> CtOption<Self> {
252    self.0.sqrt().map(Self)
253  }
254
255  fn sqrt_ratio(num: &Self, div: &Self) -> (Choice, Self) {
256    let (choice, res) = DScalar::sqrt_ratio(num, div);
257    (choice, Self(res))
258  }
259}
260
261impl PrimeField for Scalar {
262  type Repr = [u8; 32];
263
264  const MODULUS: &'static str = <DScalar as PrimeField>::MODULUS;
265
266  const NUM_BITS: u32 = <DScalar as PrimeField>::NUM_BITS;
267  const CAPACITY: u32 = <DScalar as PrimeField>::CAPACITY;
268
269  const TWO_INV: Scalar = Scalar(<DScalar as PrimeField>::TWO_INV);
270
271  const MULTIPLICATIVE_GENERATOR: Scalar =
272    Scalar(<DScalar as PrimeField>::MULTIPLICATIVE_GENERATOR);
273  const S: u32 = <DScalar as PrimeField>::S;
274
275  const ROOT_OF_UNITY: Scalar = Scalar(<DScalar as PrimeField>::ROOT_OF_UNITY);
276  const ROOT_OF_UNITY_INV: Scalar = Scalar(<DScalar as PrimeField>::ROOT_OF_UNITY_INV);
277
278  const DELTA: Scalar = Scalar(<DScalar as PrimeField>::DELTA);
279
280  fn from_repr(bytes: [u8; 32]) -> CtOption<Self> {
281    <DScalar as PrimeField>::from_repr(bytes).map(Scalar)
282  }
283  fn to_repr(&self) -> [u8; 32] {
284    self.0.to_repr()
285  }
286
287  fn is_odd(&self) -> Choice {
288    self.0.is_odd()
289  }
290
291  fn from_u128(num: u128) -> Self {
292    Scalar(DScalar::from_u128(num))
293  }
294}
295
296impl PrimeFieldBits for Scalar {
297  type ReprBits = [u8; 32];
298
299  fn to_le_bits(&self) -> FieldBits<Self::ReprBits> {
300    self.to_repr().into()
301  }
302
303  fn char_le_bits() -> FieldBits<Self::ReprBits> {
304    BASEPOINT_ORDER.to_bytes().into()
305  }
306}
307
308impl Sum<Scalar> for Scalar {
309  fn sum<I: Iterator<Item = Scalar>>(iter: I) -> Scalar {
310    Self(DScalar::sum(iter))
311  }
312}
313
314impl<'a> Sum<&'a Scalar> for Scalar {
315  fn sum<I: Iterator<Item = &'a Scalar>>(iter: I) -> Scalar {
316    Self(DScalar::sum(iter))
317  }
318}
319
320impl Product<Scalar> for Scalar {
321  fn product<I: Iterator<Item = Scalar>>(iter: I) -> Scalar {
322    Self(DScalar::product(iter))
323  }
324}
325
326impl<'a> Product<&'a Scalar> for Scalar {
327  fn product<I: Iterator<Item = &'a Scalar>>(iter: I) -> Scalar {
328    Self(DScalar::product(iter))
329  }
330}
331
332macro_rules! dalek_group {
333  (
334    $Point: ident,
335    $DPoint: ident,
336    $torsion_free: expr,
337
338    $Table: ident,
339
340    $DCompressed: ident,
341
342    $BASEPOINT_POINT: ident,
343    $BASEPOINT_TABLE: ident
344  ) => {
345    /// Wrapper around the dalek Point type. For Ed25519, this is restricted to the prime subgroup.
346    #[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
347    pub struct $Point(pub $DPoint);
348    deref_borrow!($Point, $DPoint);
349    constant_time!($Point, $DPoint);
350    math_neg!($Point, Scalar, $DPoint::add, $DPoint::sub, $DPoint::mul);
351
352    /// The basepoint for this curve.
353    pub const $BASEPOINT_POINT: $Point = $Point(constants::$BASEPOINT_POINT);
354
355    impl Sum<$Point> for $Point {
356      fn sum<I: Iterator<Item = $Point>>(iter: I) -> $Point {
357        Self($DPoint::sum(iter))
358      }
359    }
360    impl<'a> Sum<&'a $Point> for $Point {
361      fn sum<I: Iterator<Item = &'a $Point>>(iter: I) -> $Point {
362        Self($DPoint::sum(iter))
363      }
364    }
365
366    impl Group for $Point {
367      type Scalar = Scalar;
368      fn random(mut rng: impl RngCore) -> Self {
369        loop {
370          let mut bytes = [0; 32];
371          rng.fill_bytes(&mut bytes);
372          let Some(point) = Option::<$Point>::from($Point::from_bytes(&bytes)) else {
373            continue;
374          };
375          // Ban identity, per the trait specification
376          if !bool::from(point.is_identity()) {
377            return point;
378          }
379        }
380      }
381      fn identity() -> Self {
382        Self($DPoint::identity())
383      }
384      fn generator() -> Self {
385        $BASEPOINT_POINT
386      }
387      fn is_identity(&self) -> Choice {
388        self.0.ct_eq(&$DPoint::identity())
389      }
390      fn double(&self) -> Self {
391        Self(self.0.double())
392      }
393    }
394
395    impl GroupEncoding for $Point {
396      type Repr = [u8; 32];
397
398      fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
399        let decompressed = $DCompressed(*bytes).decompress();
400        // TODO: Same note on unwrap_or as above
401        let point = decompressed.unwrap_or($DPoint::identity());
402        CtOption::new(
403          $Point(point),
404          choice(black_box(decompressed).is_some()) & choice($torsion_free(point)),
405        )
406      }
407
408      fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
409        $Point::from_bytes(bytes)
410      }
411
412      fn to_bytes(&self) -> Self::Repr {
413        self.0.to_bytes()
414      }
415    }
416
417    impl PrimeGroup for $Point {}
418
419    impl Mul<Scalar> for &$Table {
420      type Output = $Point;
421      fn mul(self, b: Scalar) -> $Point {
422        $Point(&b.0 * self)
423      }
424    }
425
426    // Support being used as a key in a table
427    // While it is expensive as a key, due to the field operations required, there's frequently
428    // use cases for public key -> value lookups
429    #[allow(unknown_lints, renamed_and_removed_lints)]
430    #[allow(clippy::derived_hash_with_manual_eq, clippy::derive_hash_xor_eq)]
431    impl Hash for $Point {
432      fn hash<H: Hasher>(&self, state: &mut H) {
433        self.to_bytes().hash(state);
434      }
435    }
436  };
437}
438
439dalek_group!(
440  EdwardsPoint,
441  DEdwardsPoint,
442  |point: DEdwardsPoint| point.is_torsion_free(),
443  EdwardsBasepointTable,
444  CompressedEdwardsY,
445  ED25519_BASEPOINT_POINT,
446  ED25519_BASEPOINT_TABLE
447);
448
449impl EdwardsPoint {
450  pub fn mul_by_cofactor(&self) -> EdwardsPoint {
451    EdwardsPoint(self.0.mul_by_cofactor())
452  }
453}
454
455dalek_group!(
456  RistrettoPoint,
457  DRistrettoPoint,
458  |_| true,
459  RistrettoBasepointTable,
460  CompressedRistretto,
461  RISTRETTO_BASEPOINT_POINT,
462  RISTRETTO_BASEPOINT_TABLE
463);
464
465#[test]
466fn test_ed25519_group() {
467  ff_group_tests::group::test_prime_group_bits::<_, EdwardsPoint>(&mut rand_core::OsRng);
468}
469
470#[test]
471fn test_ristretto_group() {
472  ff_group_tests::group::test_prime_group_bits::<_, RistrettoPoint>(&mut rand_core::OsRng);
473}