cargo fmt

This commit is contained in:
Michael Rosenberg 2022-10-28 17:00:24 -04:00
parent a959787c2e
commit d2bf310330
No known key found for this signature in database
25 changed files with 1480 additions and 3432 deletions

View file

@ -176,41 +176,43 @@ mod multiscalar_benches {
for multiscalar_size in &MULTISCALAR_SIZES {
let bench_id = BenchmarkId::new(
"Variable-time mixed-base",
format!("(size: {:?}), ({:.0}pct dyn)", multiscalar_size, 100.0 * dynamic_fraction),
format!(
"(size: {:?}), ({:.0}pct dyn)",
multiscalar_size,
100.0 * dynamic_fraction
),
);
c.bench_with_input(bench_id, &multiscalar_size,
move |b, &&total_size| {
let dynamic_size = ((total_size as f64) * dynamic_fraction) as usize;
let static_size = total_size - dynamic_size;
c.bench_with_input(bench_id, &multiscalar_size, move |b, &&total_size| {
let dynamic_size = ((total_size as f64) * dynamic_fraction) as usize;
let static_size = total_size - dynamic_size;
let static_points = construct_points(static_size);
let dynamic_points = construct_points(dynamic_size);
let precomp = VartimeEdwardsPrecomputation::new(&static_points);
// Rerandomize the scalars for every call to prevent
// false timings from better caching (e.g., the CPU
// cache lifts exactly the right table entries for the
// benchmark into the highest cache levels). Timings
// should be independent of points so we don't
// randomize them.
b.iter_batched(
|| {
(
construct_scalars(static_size),
construct_scalars(dynamic_size),
)
},
|(static_scalars, dynamic_scalars)| {
precomp.vartime_mixed_multiscalar_mul(
&static_scalars,
&dynamic_scalars,
&dynamic_points,
)
},
BatchSize::SmallInput,
);
},
);
let static_points = construct_points(static_size);
let dynamic_points = construct_points(dynamic_size);
let precomp = VartimeEdwardsPrecomputation::new(&static_points);
// Rerandomize the scalars for every call to prevent
// false timings from better caching (e.g., the CPU
// cache lifts exactly the right table entries for the
// benchmark into the highest cache levels). Timings
// should be independent of points so we don't
// randomize them.
b.iter_batched(
|| {
(
construct_scalars(static_size),
construct_scalars(dynamic_size),
)
},
|(static_scalars, dynamic_scalars)| {
precomp.vartime_mixed_multiscalar_mul(
&static_scalars,
&dynamic_scalars,
&dynamic_points,
)
},
BatchSize::SmallInput,
);
});
}
}

View file

@ -180,9 +180,9 @@ pub struct CompletedPoint {
#[derive(Copy, Clone, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct AffineNielsPoint {
pub y_plus_x: FieldElement,
pub y_plus_x: FieldElement,
pub y_minus_x: FieldElement,
pub xy2d: FieldElement,
pub xy2d: FieldElement,
}
impl Zeroize for AffineNielsPoint {
@ -200,10 +200,10 @@ impl Zeroize for AffineNielsPoint {
/// can be found in the module-level documentation.
#[derive(Copy, Clone)]
pub struct ProjectiveNielsPoint {
pub Y_plus_X: FieldElement,
pub Y_plus_X: FieldElement,
pub Y_minus_X: FieldElement,
pub Z: FieldElement,
pub T2d: FieldElement,
pub Z: FieldElement,
pub T2d: FieldElement,
}
impl Zeroize for ProjectiveNielsPoint {
@ -233,11 +233,11 @@ impl Identity for ProjectivePoint {
impl Identity for ProjectiveNielsPoint {
fn identity() -> ProjectiveNielsPoint {
ProjectiveNielsPoint{
Y_plus_X: FieldElement::one(),
ProjectiveNielsPoint {
Y_plus_X: FieldElement::one(),
Y_minus_X: FieldElement::one(),
Z: FieldElement::one(),
T2d: FieldElement::zero(),
Z: FieldElement::one(),
T2d: FieldElement::zero(),
}
}
}
@ -250,10 +250,10 @@ impl Default for ProjectiveNielsPoint {
impl Identity for AffineNielsPoint {
fn identity() -> AffineNielsPoint {
AffineNielsPoint{
y_plus_x: FieldElement::one(),
AffineNielsPoint {
y_plus_x: FieldElement::one(),
y_minus_x: FieldElement::one(),
xy2d: FieldElement::zero(),
xy2d: FieldElement::zero(),
}
}
}
@ -373,20 +373,21 @@ impl CompletedPoint {
impl ProjectivePoint {
/// Double this point: return self + self
pub fn double(&self) -> CompletedPoint { // Double()
let XX = self.X.square();
let YY = self.Y.square();
let ZZ2 = self.Z.square2();
let X_plus_Y = &self.X + &self.Y;
pub fn double(&self) -> CompletedPoint {
// Double()
let XX = self.X.square();
let YY = self.Y.square();
let ZZ2 = self.Z.square2();
let X_plus_Y = &self.X + &self.Y;
let X_plus_Y_sq = X_plus_Y.square();
let YY_plus_XX = &YY + &XX;
let YY_plus_XX = &YY + &XX;
let YY_minus_XX = &YY - &XX;
CompletedPoint{
CompletedPoint {
X: &X_plus_Y_sq - &YY_plus_XX,
Y: YY_plus_XX,
Z: YY_minus_XX,
T: &ZZ2 - &YY_minus_XX
T: &ZZ2 - &YY_minus_XX,
}
}
}
@ -406,19 +407,19 @@ impl<'a, 'b> Add<&'b ProjectiveNielsPoint> for &'a EdwardsPoint {
type Output = CompletedPoint;
fn add(self, other: &'b ProjectiveNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PP = &Y_plus_X * &other.Y_plus_X;
let PP = &Y_plus_X * &other.Y_plus_X;
let MM = &Y_minus_X * &other.Y_minus_X;
let TT2d = &self.T * &other.T2d;
let ZZ = &self.Z * &other.Z;
let ZZ2 = &ZZ + &ZZ;
let ZZ = &self.Z * &other.Z;
let ZZ2 = &ZZ + &ZZ;
CompletedPoint{
CompletedPoint {
X: &PP - &MM,
Y: &PP + &MM,
Z: &ZZ2 + &TT2d,
T: &ZZ2 - &TT2d
T: &ZZ2 - &TT2d,
}
}
}
@ -428,19 +429,19 @@ impl<'a, 'b> Sub<&'b ProjectiveNielsPoint> for &'a EdwardsPoint {
type Output = CompletedPoint;
fn sub(self, other: &'b ProjectiveNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PM = &Y_plus_X * &other.Y_minus_X;
let MP = &Y_minus_X * &other.Y_plus_X;
let MP = &Y_minus_X * &other.Y_plus_X;
let TT2d = &self.T * &other.T2d;
let ZZ = &self.Z * &other.Z;
let ZZ2 = &ZZ + &ZZ;
let ZZ = &self.Z * &other.Z;
let ZZ2 = &ZZ + &ZZ;
CompletedPoint{
CompletedPoint {
X: &PM - &MP,
Y: &PM + &MP,
Z: &ZZ2 - &TT2d,
T: &ZZ2 + &TT2d
T: &ZZ2 + &TT2d,
}
}
}
@ -450,18 +451,18 @@ impl<'a, 'b> Add<&'b AffineNielsPoint> for &'a EdwardsPoint {
type Output = CompletedPoint;
fn add(self, other: &'b AffineNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PP = &Y_plus_X * &other.y_plus_x;
let MM = &Y_minus_X * &other.y_minus_x;
let Txy2d = &self.T * &other.xy2d;
let Z2 = &self.Z + &self.Z;
let PP = &Y_plus_X * &other.y_plus_x;
let MM = &Y_minus_X * &other.y_minus_x;
let Txy2d = &self.T * &other.xy2d;
let Z2 = &self.Z + &self.Z;
CompletedPoint{
CompletedPoint {
X: &PP - &MM,
Y: &PP + &MM,
Z: &Z2 + &Txy2d,
T: &Z2 - &Txy2d
T: &Z2 - &Txy2d,
}
}
}
@ -471,18 +472,18 @@ impl<'a, 'b> Sub<&'b AffineNielsPoint> for &'a EdwardsPoint {
type Output = CompletedPoint;
fn sub(self, other: &'b AffineNielsPoint) -> CompletedPoint {
let Y_plus_X = &self.Y + &self.X;
let Y_plus_X = &self.Y + &self.X;
let Y_minus_X = &self.Y - &self.X;
let PM = &Y_plus_X * &other.y_minus_x;
let MP = &Y_minus_X * &other.y_plus_x;
let Txy2d = &self.T * &other.xy2d;
let Z2 = &self.Z + &self.Z;
let PM = &Y_plus_X * &other.y_minus_x;
let MP = &Y_minus_X * &other.y_plus_x;
let Txy2d = &self.T * &other.xy2d;
let Z2 = &self.Z + &self.Z;
CompletedPoint{
CompletedPoint {
X: &PM - &MP,
Y: &PM + &MP,
Z: &Z2 - &Txy2d,
T: &Z2 + &Txy2d
T: &Z2 + &Txy2d,
}
}
}
@ -495,11 +496,11 @@ impl<'a> Neg for &'a ProjectiveNielsPoint {
type Output = ProjectiveNielsPoint;
fn neg(self) -> ProjectiveNielsPoint {
ProjectiveNielsPoint{
Y_plus_X: self.Y_minus_X,
Y_minus_X: self.Y_plus_X,
Z: self.Z,
T2d: -(&self.T2d),
ProjectiveNielsPoint {
Y_plus_X: self.Y_minus_X,
Y_minus_X: self.Y_plus_X,
Z: self.Z,
T2d: -(&self.T2d),
}
}
}
@ -508,10 +509,10 @@ impl<'a> Neg for &'a AffineNielsPoint {
type Output = AffineNielsPoint;
fn neg(self) -> AffineNielsPoint {
AffineNielsPoint{
y_plus_x: self.y_minus_x,
y_minus_x: self.y_plus_x,
xy2d: -(&self.xy2d)
AffineNielsPoint {
y_plus_x: self.y_minus_x,
y_minus_x: self.y_plus_x,
xy2d: -(&self.xy2d),
}
}
}
@ -522,22 +523,31 @@ impl<'a> Neg for &'a AffineNielsPoint {
impl Debug for ProjectivePoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "ProjectivePoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?}\n}}",
&self.X, &self.Y, &self.Z)
write!(
f,
"ProjectivePoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?}\n}}",
&self.X, &self.Y, &self.Z
)
}
}
impl Debug for CompletedPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "CompletedPoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?},\n\tT: {:?}\n}}",
&self.X, &self.Y, &self.Z, &self.T)
write!(
f,
"CompletedPoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?},\n\tT: {:?}\n}}",
&self.X, &self.Y, &self.Z, &self.T
)
}
}
impl Debug for AffineNielsPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "AffineNielsPoint{{\n\ty_plus_x: {:?},\n\ty_minus_x: {:?},\n\txy2d: {:?}\n}}",
&self.y_plus_x, &self.y_minus_x, &self.xy2d)
write!(
f,
"AffineNielsPoint{{\n\ty_plus_x: {:?},\n\ty_minus_x: {:?},\n\txy2d: {:?}\n}}",
&self.y_plus_x, &self.y_minus_x, &self.xy2d
)
}
}
@ -547,5 +557,3 @@ impl Debug for ProjectiveNielsPoint {
&self.Y_plus_X, &self.Y_minus_X, &self.Z, &self.T2d)
}
}

View file

@ -93,8 +93,7 @@ impl VartimeMultiscalarMul for Pippenger {
// Collect optimized scalars and points in buffers for repeated access
// (scanning the whole set per digit position).
let scalars = scalars
.map(|s| s.borrow().to_radix_2w(w));
let scalars = scalars.map(|s| s.borrow().to_radix_2w(w));
let points = points
.into_iter()
@ -155,10 +154,7 @@ impl VartimeMultiscalarMul for Pippenger {
// `unwrap()` always succeeds because we know we have more than zero digits.
let hi_column = columns.next().unwrap();
Some(
columns
.fold(hi_column, |total, p| total.mul_by_pow_2(w as u32) + p),
)
Some(columns.fold(hi_column, |total, p| total.mul_by_pow_2(w as u32) + p))
}
}

View file

@ -110,8 +110,8 @@ impl MultiscalarMul for Straus {
use zeroize::Zeroizing;
use crate::backend::serial::curve_models::ProjectiveNielsPoint;
use crate::window::LookupTable;
use crate::traits::Identity;
use crate::window::LookupTable;
let lookup_tables: Vec<_> = points
.into_iter()
@ -161,9 +161,11 @@ impl VartimeMultiscalarMul for Straus {
I::Item: Borrow<Scalar>,
J: IntoIterator<Item = Option<EdwardsPoint>>,
{
use crate::backend::serial::curve_models::{CompletedPoint, ProjectiveNielsPoint, ProjectivePoint};
use crate::window::NafLookupTable5;
use crate::backend::serial::curve_models::{
CompletedPoint, ProjectiveNielsPoint, ProjectivePoint,
};
use crate::traits::Identity;
use crate::window::NafLookupTable5;
let nafs: Vec<_> = scalars
.into_iter()

View file

@ -1,9 +1,9 @@
#![allow(non_snake_case)]
use crate::traits::Identity;
use crate::scalar::Scalar;
use crate::edwards::EdwardsPoint;
use crate::backend::serial::curve_models::ProjectiveNielsPoint;
use crate::edwards::EdwardsPoint;
use crate::scalar::Scalar;
use crate::traits::Identity;
use crate::window::LookupTable;
/// Perform constant-time, variable-base scalar multiplication.

View file

@ -50,7 +50,7 @@ use zeroize::Zeroize;
/// The backend-specific type `FieldElement2625` should not be used
/// outside of the `curve25519_dalek::field` module.
#[derive(Copy, Clone)]
pub struct FieldElement2625(pub (crate) [u32; 10]);
pub struct FieldElement2625(pub(crate) [u32; 10]);
impl Debug for FieldElement2625 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
@ -98,7 +98,8 @@ impl<'b> SubAssign<&'b FieldElement2625> for FieldElement2625 {
((self.0[7] + (0x1ffffff << 4)) - b[7]) as u64,
((self.0[8] + (0x3ffffff << 4)) - b[8]) as u64,
((self.0[9] + (0x1ffffff << 4)) - b[9]) as u64,
]).0;
])
.0;
}
}
@ -301,25 +302,25 @@ impl FieldElement2625 {
/// Construct zero.
pub fn zero() -> FieldElement2625 {
FieldElement2625([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
FieldElement2625([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
}
/// Construct one.
pub fn one() -> FieldElement2625 {
FieldElement2625([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ])
FieldElement2625([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])
}
/// Construct -1.
pub fn minus_one() -> FieldElement2625 {
FieldElement2625([
0x3ffffec, 0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff,
0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff, 0x1ffffff,
0x3ffffec, 0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff, 0x1ffffff,
0x3ffffff, 0x1ffffff,
])
}
/// Given `k > 0`, return `self^(2^k)`.
pub fn pow2k(&self, k: u32) -> FieldElement2625 {
debug_assert!( k > 0 );
debug_assert!(k > 0);
let mut z = self.square();
for _ in 1..k {
z = z.square();
@ -432,14 +433,22 @@ impl FieldElement2625 {
/// Serialize this `FieldElement51` to a 32-byte array. The
/// encoding is canonical.
pub fn to_bytes(&self) -> [u8; 32] {
let inp = &self.0;
// Reduce the value represented by `in` to the range [0,2*p)
let mut h: [u32; 10] = FieldElement2625::reduce([
// XXX this cast is annoying
inp[0] as u64, inp[1] as u64, inp[2] as u64, inp[3] as u64, inp[4] as u64,
inp[5] as u64, inp[6] as u64, inp[7] as u64, inp[8] as u64, inp[9] as u64,
]).0;
inp[0] as u64,
inp[1] as u64,
inp[2] as u64,
inp[3] as u64,
inp[4] as u64,
inp[5] as u64,
inp[6] as u64,
inp[7] as u64,
inp[8] as u64,
inp[9] as u64,
])
.0;
// Let h be the value to encode.
//
@ -468,7 +477,7 @@ impl FieldElement2625 {
const LOW_25_BITS: u32 = (1 << 25) - 1;
const LOW_26_BITS: u32 = (1 << 26) - 1;
h[0] += 19*q;
h[0] += 19 * q;
// Now carry the result to compute r + 19q...
h[1] += h[0] >> 26;

View file

@ -18,7 +18,7 @@ use zeroize::Zeroize;
use crate::constants;
/// The `Scalar29` struct represents an element in ℤ/lℤ as 9 29-bit limbs
#[derive(Copy,Clone)]
#[derive(Copy, Clone)]
pub struct Scalar29(pub [u32; 9]);
impl Debug for Scalar29 {
@ -55,7 +55,7 @@ fn m(x: u32, y: u32) -> u64 {
impl Scalar29 {
/// Return the zero scalar.
pub fn zero() -> Scalar29 {
Scalar29([0,0,0,0,0,0,0,0,0])
Scalar29([0, 0, 0, 0, 0, 0, 0, 0, 0])
}
/// Unpack a 32 byte / 256 bit scalar into 9 29-bit limbs.
@ -399,65 +399,65 @@ mod test {
/// x = 2^253-1 = 14474011154664524427946373126085988481658748083205070504932198000989141204991
/// x = 7237005577332262213973186563042994240801631723825162898930247062703686954002 mod l
/// x = 5147078182513738803124273553712992179887200054963030844803268920753008712037*R mod l in Montgomery form
pub static X: Scalar29 = Scalar29(
[0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff,
0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff,
0x001fffff]);
pub static X: Scalar29 = Scalar29([
0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff,
0x1fffffff, 0x001fffff,
]);
/// x^2 = 3078544782642840487852506753550082162405942681916160040940637093560259278169 mod l
pub static XX: Scalar29 = Scalar29(
[0x00217559, 0x000b3401, 0x103ff43b, 0x1462a62c,
0x1d6f9f38, 0x18e7a42f, 0x09a3dcee, 0x008dbe18,
0x0006ce65]);
pub static XX: Scalar29 = Scalar29([
0x00217559, 0x000b3401, 0x103ff43b, 0x1462a62c, 0x1d6f9f38, 0x18e7a42f, 0x09a3dcee,
0x008dbe18, 0x0006ce65,
]);
/// x^2 = 2912514428060642753613814151688322857484807845836623976981729207238463947987*R mod l in Montgomery form
pub static XX_MONT: Scalar29 = Scalar29(
[0x152b4d2e, 0x0571d53b, 0x1da6d964, 0x188663b6,
0x1d1b5f92, 0x19d50e3f, 0x12306c29, 0x0c6f26fe,
0x00030edb]);
pub static XX_MONT: Scalar29 = Scalar29([
0x152b4d2e, 0x0571d53b, 0x1da6d964, 0x188663b6, 0x1d1b5f92, 0x19d50e3f, 0x12306c29,
0x0c6f26fe, 0x00030edb,
]);
/// y = 6145104759870991071742105800796537629880401874866217824609283457819451087098
pub static Y: Scalar29 = Scalar29(
[0x1e1458fa, 0x165ba838, 0x1d787b36, 0x0e577f3a,
0x1d2baf06, 0x1d689a19, 0x1fff3047, 0x117704ab,
0x000d9601]);
pub static Y: Scalar29 = Scalar29([
0x1e1458fa, 0x165ba838, 0x1d787b36, 0x0e577f3a, 0x1d2baf06, 0x1d689a19, 0x1fff3047,
0x117704ab, 0x000d9601,
]);
/// x*y = 36752150652102274958925982391442301741
pub static XY: Scalar29 = Scalar29(
[0x0ba7632d, 0x017736bb, 0x15c76138, 0x0c69daa1,
0x000001ba, 0x00000000, 0x00000000, 0x00000000,
0x00000000]);
pub static XY: Scalar29 = Scalar29([
0x0ba7632d, 0x017736bb, 0x15c76138, 0x0c69daa1, 0x000001ba, 0x00000000, 0x00000000,
0x00000000, 0x00000000,
]);
/// x*y = 3783114862749659543382438697751927473898937741870308063443170013240655651591*R mod l in Montgomery form
pub static XY_MONT: Scalar29 = Scalar29(
[0x077b51e1, 0x1c64e119, 0x02a19ef5, 0x18d2129e,
0x00de0430, 0x045a7bc8, 0x04cfc7c9, 0x1c002681,
0x000bdc1c]);
pub static XY_MONT: Scalar29 = Scalar29([
0x077b51e1, 0x1c64e119, 0x02a19ef5, 0x18d2129e, 0x00de0430, 0x045a7bc8, 0x04cfc7c9,
0x1c002681, 0x000bdc1c,
]);
/// a = 2351415481556538453565687241199399922945659411799870114962672658845158063753
pub static A: Scalar29 = Scalar29(
[0x07b3be89, 0x02291b60, 0x14a99f03, 0x07dc3787,
0x0a782aae, 0x16262525, 0x0cfdb93f, 0x13f5718d,
0x000532da]);
pub static A: Scalar29 = Scalar29([
0x07b3be89, 0x02291b60, 0x14a99f03, 0x07dc3787, 0x0a782aae, 0x16262525, 0x0cfdb93f,
0x13f5718d, 0x000532da,
]);
/// b = 4885590095775723760407499321843594317911456947580037491039278279440296187236
pub static B: Scalar29 = Scalar29(
[0x15421564, 0x1e69fd72, 0x093d9692, 0x161785be,
0x1587d69f, 0x09d9dada, 0x130246c0, 0x0c0a8e72,
0x000acd25]);
pub static B: Scalar29 = Scalar29([
0x15421564, 0x1e69fd72, 0x093d9692, 0x161785be, 0x1587d69f, 0x09d9dada, 0x130246c0,
0x0c0a8e72, 0x000acd25,
]);
/// a+b = 0
/// a-b = 4702830963113076907131374482398799845891318823599740229925345317690316127506
pub static AB: Scalar29 = Scalar29(
[0x0f677d12, 0x045236c0, 0x09533e06, 0x0fb86f0f,
0x14f0555c, 0x0c4c4a4a, 0x19fb727f, 0x07eae31a,
0x000a65b5]);
pub static AB: Scalar29 = Scalar29([
0x0f677d12, 0x045236c0, 0x09533e06, 0x0fb86f0f, 0x14f0555c, 0x0c4c4a4a, 0x19fb727f,
0x07eae31a, 0x000a65b5,
]);
// c = (2^512 - 1) % l = 1627715501170711445284395025044413883736156588369414752970002579683115011840
pub static C: Scalar29 = Scalar29(
[0x049c0f00, 0x00308f1a, 0x0164d1e9, 0x1c374ed1,
0x1be65d00, 0x19e90bfa, 0x08f73bb1, 0x036f8613,
0x00039941]);
pub static C: Scalar29 = Scalar29([
0x049c0f00, 0x00308f1a, 0x0164d1e9, 0x1c374ed1, 0x1be65d00, 0x19e90bfa, 0x08f73bb1,
0x036f8613, 0x00039941,
]);
#[test]
fn mul_max() {

View file

@ -11,9 +11,9 @@
//! This module contains backend-specific constant values, such as the 64-bit limbs of curve constants.
use crate::backend::serial::curve_models::AffineNielsPoint;
use super::field::FieldElement51;
use super::scalar::Scalar52;
use crate::backend::serial::curve_models::AffineNielsPoint;
use crate::edwards::{EdwardsBasepointTable, EdwardsPoint};
use crate::window::{LookupTable, NafLookupTable8};
@ -23,7 +23,7 @@ pub(crate) const MINUS_ONE: FieldElement51 = FieldElement51([
2251799813685247,
2251799813685247,
2251799813685247,
2251799813685247
2251799813685247,
]);
/// Edwards `d` value, equal to `-121665/121666 mod p`.
@ -50,7 +50,7 @@ pub(crate) const ONE_MINUS_EDWARDS_D_SQUARED: FieldElement51 = FieldElement51([
1998550399581263,
496427632559748,
118527312129759,
45110755273534
45110755273534,
]);
/// Edwards `d` value minus one squared, equal to `(((-121665/121666) mod p) - 1) pow 2`
@ -59,7 +59,7 @@ pub(crate) const EDWARDS_D_MINUS_ONE_SQUARED: FieldElement51 = FieldElement51([
1572317787530805,
683053064812840,
317374165784489,
1572899562415810
1572899562415810,
]);
/// `= sqrt(a*d - 1)`, where `a = -1 (mod p)`, `d` are the Edwards curve parameters.

View file

@ -39,7 +39,7 @@ use zeroize::Zeroize;
/// The backend-specific type `FieldElement51` should not be used
/// outside of the `curve25519_dalek::field` module.
#[derive(Copy, Clone)]
pub struct FieldElement51(pub (crate) [u64; 5]);
pub struct FieldElement51(pub(crate) [u64; 5]);
impl Debug for FieldElement51 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
@ -268,17 +268,23 @@ impl FieldElement51 {
/// Construct zero.
pub fn zero() -> FieldElement51 {
FieldElement51([ 0, 0, 0, 0, 0 ])
FieldElement51([0, 0, 0, 0, 0])
}
/// Construct one.
pub fn one() -> FieldElement51 {
FieldElement51([ 1, 0, 0, 0, 0 ])
FieldElement51([1, 0, 0, 0, 0])
}
/// Construct -1.
pub fn minus_one() -> FieldElement51 {
FieldElement51([2251799813685228, 2251799813685247, 2251799813685247, 2251799813685247, 2251799813685247])
FieldElement51([
2251799813685228,
2251799813685247,
2251799813685247,
2251799813685247,
2251799813685247,
])
}
/// Given 64-bit input limbs, reduce to enforce the bound 2^(51 + epsilon).

View file

@ -20,7 +20,7 @@ use crate::constants;
/// The `Scalar52` struct represents an element in
/// \\(\mathbb Z / \ell \mathbb Z\\) as 5 \\(52\\)-bit limbs.
#[derive(Copy,Clone)]
#[derive(Copy, Clone)]
pub struct Scalar52(pub [u64; 5]);
impl Debug for Scalar52 {
@ -57,7 +57,7 @@ fn m(x: u64, y: u64) -> u128 {
impl Scalar52 {
/// Return the zero scalar
pub fn zero() -> Scalar52 {
Scalar52([0,0,0,0,0])
Scalar52([0, 0, 0, 0, 0])
}
/// Unpack a 32 byte / 256 bit scalar into 5 52-bit limbs.
@ -319,7 +319,6 @@ impl Scalar52 {
}
}
#[cfg(test)]
mod test {
use super::*;
@ -330,55 +329,95 @@ mod test {
/// x = 14474011154664524427946373126085988481658748083205070504932198000989141204991
/// x = 7237005577332262213973186563042994240801631723825162898930247062703686954002 mod l
/// x = 3057150787695215392275360544382990118917283750546154083604586903220563173085*R mod l in Montgomery form
pub static X: Scalar52 = Scalar52(
[0x000fffffffffffff, 0x000fffffffffffff, 0x000fffffffffffff, 0x000fffffffffffff,
0x00001fffffffffff]);
pub static X: Scalar52 = Scalar52([
0x000fffffffffffff,
0x000fffffffffffff,
0x000fffffffffffff,
0x000fffffffffffff,
0x00001fffffffffff,
]);
/// x^2 = 3078544782642840487852506753550082162405942681916160040940637093560259278169 mod l
pub static XX: Scalar52 = Scalar52(
[0x0001668020217559, 0x000531640ffd0ec0, 0x00085fd6f9f38a31, 0x000c268f73bb1cf4,
0x000006ce65046df0]);
pub static XX: Scalar52 = Scalar52([
0x0001668020217559,
0x000531640ffd0ec0,
0x00085fd6f9f38a31,
0x000c268f73bb1cf4,
0x000006ce65046df0,
]);
/// x^2 = 4413052134910308800482070043710297189082115023966588301924965890668401540959*R mod l in Montgomery form
pub static XX_MONT: Scalar52 = Scalar52(
[0x000c754eea569a5c, 0x00063b6ed36cb215, 0x0008ffa36bf25886, 0x000e9183614e7543,
0x0000061db6c6f26f]);
pub static XX_MONT: Scalar52 = Scalar52([
0x000c754eea569a5c,
0x00063b6ed36cb215,
0x0008ffa36bf25886,
0x000e9183614e7543,
0x0000061db6c6f26f,
]);
/// y = 6145104759870991071742105800796537629880401874866217824609283457819451087098
pub static Y: Scalar52 = Scalar52(
[0x000b75071e1458fa, 0x000bf9d75e1ecdac, 0x000433d2baf0672b, 0x0005fffcc11fad13,
0x00000d96018bb825]);
pub static Y: Scalar52 = Scalar52([
0x000b75071e1458fa,
0x000bf9d75e1ecdac,
0x000433d2baf0672b,
0x0005fffcc11fad13,
0x00000d96018bb825,
]);
/// x*y = 36752150652102274958925982391442301741 mod l
pub static XY: Scalar52 = Scalar52(
[0x000ee6d76ba7632d, 0x000ed50d71d84e02, 0x00000000001ba634, 0x0000000000000000,
0x0000000000000000]);
pub static XY: Scalar52 = Scalar52([
0x000ee6d76ba7632d,
0x000ed50d71d84e02,
0x00000000001ba634,
0x0000000000000000,
0x0000000000000000,
]);
/// x*y = 658448296334113745583381664921721413881518248721417041768778176391714104386*R mod l in Montgomery form
pub static XY_MONT: Scalar52 = Scalar52(
[0x0006d52bf200cfd5, 0x00033fb1d7021570, 0x000f201bc07139d8, 0x0001267e3e49169e,
0x000007b839c00268]);
pub static XY_MONT: Scalar52 = Scalar52([
0x0006d52bf200cfd5,
0x00033fb1d7021570,
0x000f201bc07139d8,
0x0001267e3e49169e,
0x000007b839c00268,
]);
/// a = 2351415481556538453565687241199399922945659411799870114962672658845158063753
pub static A: Scalar52 = Scalar52(
[0x0005236c07b3be89, 0x0001bc3d2a67c0c4, 0x000a4aa782aae3ee, 0x0006b3f6e4fec4c4,
0x00000532da9fab8c]);
pub static A: Scalar52 = Scalar52([
0x0005236c07b3be89,
0x0001bc3d2a67c0c4,
0x000a4aa782aae3ee,
0x0006b3f6e4fec4c4,
0x00000532da9fab8c,
]);
/// b = 4885590095775723760407499321843594317911456947580037491039278279440296187236
pub static B: Scalar52 = Scalar52(
[0x000d3fae55421564, 0x000c2df24f65a4bc, 0x0005b5587d69fb0b, 0x00094c091b013b3b,
0x00000acd25605473]);
pub static B: Scalar52 = Scalar52([
0x000d3fae55421564,
0x000c2df24f65a4bc,
0x0005b5587d69fb0b,
0x00094c091b013b3b,
0x00000acd25605473,
]);
/// a+b = 0
/// a-b = 4702830963113076907131374482398799845891318823599740229925345317690316127506
pub static AB: Scalar52 = Scalar52(
[0x000a46d80f677d12, 0x0003787a54cf8188, 0x0004954f0555c7dc, 0x000d67edc9fd8989,
0x00000a65b53f5718]);
pub static AB: Scalar52 = Scalar52([
0x000a46d80f677d12,
0x0003787a54cf8188,
0x0004954f0555c7dc,
0x000d67edc9fd8989,
0x00000a65b53f5718,
]);
// c = (2^512 - 1) % l = 1627715501170711445284395025044413883736156588369414752970002579683115011840
pub static C: Scalar52 = Scalar52(
[0x000611e3449c0f00, 0x000a768859347a40, 0x0007f5be65d00e1b, 0x0009a3dceec73d21,
0x00000399411b7c30]);
pub static C: Scalar52 = Scalar52([
0x000611e3449c0f00,
0x000a768859347a40,
0x0007f5be65d00e1b,
0x0009a3dceec73d21,
0x00000399411b7c30,
]);
#[test]
fn mul_max() {

File diff suppressed because it is too large Load diff

View file

@ -526,10 +526,11 @@ mod test {
#[test]
fn basepoint_odd_lookup_table_verify() {
use crate::backend::vector::avx2::constants::BASEPOINT_ODD_LOOKUP_TABLE;
use crate::constants;
use crate::backend::vector::avx2::constants::{BASEPOINT_ODD_LOOKUP_TABLE};
let basepoint_odd_table = NafLookupTable8::<CachedPoint>::from(&constants::ED25519_BASEPOINT_POINT);
let basepoint_odd_table =
NafLookupTable8::<CachedPoint>::from(&constants::ED25519_BASEPOINT_POINT);
println!("basepoint_odd_lookup_table = {:?}", basepoint_odd_table);
let table_B = &BASEPOINT_ODD_LOOKUP_TABLE;

View file

@ -43,10 +43,10 @@ const D_LANES64: u8 = 0b11_00_00_00;
use core::ops::{Add, Mul, Neg};
use packed_simd::{i32x8, u32x8, u64x4, IntoBits};
use crate::backend::serial::u64::field::FieldElement51;
use crate::backend::vector::avx2::constants::{
P_TIMES_16_HI, P_TIMES_16_LO, P_TIMES_2_HI, P_TIMES_2_LO,
};
use crate::backend::serial::u64::field::FieldElement51;
/// Unpack 32-bit lanes into 64-bit lanes:
/// ```ascii,no_run
@ -166,11 +166,7 @@ impl ConditionallySelectable for FieldElement2625x4 {
])
}
fn conditional_assign(
&mut self,
other: &FieldElement2625x4,
choice: Choice,
) {
fn conditional_assign(&mut self, other: &FieldElement2625x4, choice: Choice) {
let mask = (-(choice.unwrap_u8() as i32)) as u32;
let mask_vec = u32x8::splat(mask);
self.0[0] ^= mask_vec & (self.0[0] ^ other.0[0]);
@ -309,7 +305,8 @@ impl FieldElement2625x4 {
x.into_bits(),
y.into_bits(),
(A_LANES | B_LANES | C_LANES | D_LANES) as i32,
).into_bits(),
)
.into_bits(),
}
}
}
@ -436,8 +433,8 @@ impl FieldElement2625x4 {
// The carryouts are bounded by 2^(32 - 25) = 2^7.
let rotated_carryout = |v: u32x8| -> u32x8 {
unsafe {
use core::arch::x86_64::_mm256_srlv_epi32;
use core::arch::x86_64::_mm256_shuffle_epi32;
use core::arch::x86_64::_mm256_srlv_epi32;
let c = _mm256_srlv_epi32(v.into_bits(), shifts.into_bits());
_mm256_shuffle_epi32(c, 0b01_00_11_10).into_bits()
@ -715,7 +712,8 @@ impl Neg for FieldElement2625x4 {
P_TIMES_16_HI - self.0[2],
P_TIMES_16_HI - self.0[3],
P_TIMES_16_HI - self.0[4],
]).reduce()
])
.reduce()
}
}
@ -889,7 +887,7 @@ mod test {
fn scale_by_curve_constants() {
let mut x = FieldElement2625x4::splat(&FieldElement51::one());
x = x * (121666, 121666, 2*121666, 2*121665);
x = x * (121666, 121666, 2 * 121666, 2 * 121665);
let xs = x.split();
assert_eq!(xs[0], FieldElement51([121666, 0, 0, 0, 0]));

View file

@ -9,10 +9,7 @@
// - isis agora lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca>
#![cfg_attr(
feature = "nightly",
doc(include = "../../../../docs/avx2-notes.md")
)]
#![cfg_attr(feature = "nightly", doc(include = "../../../../docs/avx2-notes.md"))]
pub(crate) mod field;

View file

@ -76,7 +76,7 @@ impl ExtendedPoint {
// (Y1 X1 T1 Z1) -- uses vpshufd (1c latency @ 1/c)
let mut tmp0 = self.0.shuffle(Shuffle::BADC);
// (X1+Y1 X1+Y1 X1+Y1 X1+Y1) -- can use vpinserti128
// (X1+Y1 X1+Y1 X1+Y1 X1+Y1) -- can use vpinserti128
let mut tmp1 = (self.0 + tmp0).shuffle(Shuffle::ABAB);
// (X1 Y1 Z1 X1+Y1)

View file

@ -7,10 +7,7 @@
// Authors:
// - Henry de Valence <hdevalence@hdevalence.ca>
#![cfg_attr(
feature = "nightly",
doc(include = "../../../../docs/ifma-notes.md")
)]
#![cfg_attr(feature = "nightly", doc(include = "../../../../docs/ifma-notes.md"))]
pub mod field;

View file

@ -23,7 +23,6 @@ use crate::window::{NafLookupTable5, NafLookupTable8};
#[allow(unused_imports)]
use crate::prelude::*;
pub struct VartimePrecomputedStraus {
static_lookup_tables: Vec<NafLookupTable8<CachedPoint>>,
}

View file

@ -18,8 +18,8 @@ use zeroize::Zeroizing;
use crate::backend::vector::{CachedPoint, ExtendedPoint};
use crate::edwards::EdwardsPoint;
use crate::scalar::Scalar;
use crate::window::{LookupTable, NafLookupTable5};
use crate::traits::{Identity, MultiscalarMul, VartimeMultiscalarMul};
use crate::window::{LookupTable, NafLookupTable5};
#[allow(unused_imports)]
use crate::prelude::*;

View file

@ -121,11 +121,11 @@ use crate::backend::serial::curve_models::CompletedPoint;
use crate::backend::serial::curve_models::ProjectiveNielsPoint;
use crate::backend::serial::curve_models::ProjectivePoint;
use crate::window::LookupTableRadix128;
use crate::window::LookupTableRadix16;
use crate::window::LookupTableRadix256;
use crate::window::LookupTableRadix32;
use crate::window::LookupTableRadix64;
use crate::window::LookupTableRadix128;
use crate::window::LookupTableRadix256;
#[allow(unused_imports)]
use crate::prelude::*;
@ -217,15 +217,16 @@ impl CompressedEdwardsY {
// structs containing `EdwardsPoint`s and use Serde's derived
// serializers to serialize those structures.
#[cfg(feature = "serde")]
use serde::{self, Serialize, Deserialize, Serializer, Deserializer};
#[cfg(feature = "serde")]
use serde::de::Visitor;
#[cfg(feature = "serde")]
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
impl Serialize for EdwardsPoint {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
where
S: Serializer,
{
use serde::ser::SerializeTuple;
let mut tup = serializer.serialize_tuple(32)?;
@ -239,7 +240,8 @@ impl Serialize for EdwardsPoint {
#[cfg(feature = "serde")]
impl Serialize for CompressedEdwardsY {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
where
S: Serializer,
{
use serde::ser::SerializeTuple;
let mut tup = serializer.serialize_tuple(32)?;
@ -253,7 +255,8 @@ impl Serialize for CompressedEdwardsY {
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for EdwardsPoint {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
struct EdwardsPointVisitor;
@ -265,11 +268,13 @@ impl<'de> Deserialize<'de> for EdwardsPoint {
}
fn visit_seq<A>(self, mut seq: A) -> Result<EdwardsPoint, A::Error>
where A: serde::de::SeqAccess<'de>
where
A: serde::de::SeqAccess<'de>,
{
let mut bytes = [0u8; 32];
for i in 0..32 {
bytes[i] = seq.next_element()?
bytes[i] = seq
.next_element()?
.ok_or(serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
}
CompressedEdwardsY(bytes)
@ -285,7 +290,8 @@ impl<'de> Deserialize<'de> for EdwardsPoint {
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for CompressedEdwardsY {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
struct CompressedEdwardsYVisitor;
@ -297,11 +303,13 @@ impl<'de> Deserialize<'de> for CompressedEdwardsY {
}
fn visit_seq<A>(self, mut seq: A) -> Result<CompressedEdwardsY, A::Error>
where A: serde::de::SeqAccess<'de>
where
A: serde::de::SeqAccess<'de>,
{
let mut bytes = [0u8; 32];
for i in 0..32 {
bytes[i] = seq.next_element()?
bytes[i] = seq
.next_element()?
.ok_or(serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
}
Ok(CompressedEdwardsY(bytes))
@ -332,10 +340,10 @@ pub struct EdwardsPoint {
impl Identity for CompressedEdwardsY {
fn identity() -> CompressedEdwardsY {
CompressedEdwardsY([1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0])
CompressedEdwardsY([
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
])
}
}
@ -459,11 +467,11 @@ impl Eq for EdwardsPoint {}
impl EdwardsPoint {
/// Convert to a ProjectiveNielsPoint
pub(crate) fn to_projective_niels(&self) -> ProjectiveNielsPoint {
ProjectiveNielsPoint{
Y_plus_X: &self.Y + &self.X,
ProjectiveNielsPoint {
Y_plus_X: &self.Y + &self.X,
Y_minus_X: &self.Y - &self.X,
Z: self.Z,
T2d: &self.T * &constants::EDWARDS_D2,
Z: self.Z,
T2d: &self.T * &constants::EDWARDS_D2,
}
}
@ -472,7 +480,7 @@ impl EdwardsPoint {
///
/// Free.
pub(crate) fn to_projective(&self) -> ProjectivePoint {
ProjectivePoint{
ProjectivePoint {
X: self.X,
Y: self.Y,
Z: self.Z,
@ -486,10 +494,10 @@ impl EdwardsPoint {
let x = &self.X * &recip;
let y = &self.Y * &recip;
let xy2d = &(&x * &y) * &constants::EDWARDS_D2;
AffineNielsPoint{
y_plus_x: &y + &x,
AffineNielsPoint {
y_plus_x: &y + &x,
y_minus_x: &y - &x,
xy2d
xy2d,
}
}
@ -574,7 +582,11 @@ impl<'a, 'b> Add<&'b EdwardsPoint> for &'a EdwardsPoint {
}
}
define_add_variants!(LHS = EdwardsPoint, RHS = EdwardsPoint, Output = EdwardsPoint);
define_add_variants!(
LHS = EdwardsPoint,
RHS = EdwardsPoint,
Output = EdwardsPoint
);
impl<'b> AddAssign<&'b EdwardsPoint> for EdwardsPoint {
fn add_assign(&mut self, _rhs: &'b EdwardsPoint) {
@ -591,7 +603,11 @@ impl<'a, 'b> Sub<&'b EdwardsPoint> for &'a EdwardsPoint {
}
}
define_sub_variants!(LHS = EdwardsPoint, RHS = EdwardsPoint, Output = EdwardsPoint);
define_sub_variants!(
LHS = EdwardsPoint,
RHS = EdwardsPoint,
Output = EdwardsPoint
);
impl<'b> SubAssign<&'b EdwardsPoint> for EdwardsPoint {
fn sub_assign(&mut self, _rhs: &'b EdwardsPoint) {
@ -603,17 +619,16 @@ define_sub_assign_variants!(LHS = EdwardsPoint, RHS = EdwardsPoint);
impl<T> Sum<T> for EdwardsPoint
where
T: Borrow<EdwardsPoint>
T: Borrow<EdwardsPoint>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>
I: Iterator<Item = T>,
{
iter.fold(EdwardsPoint::identity(), |acc, item| acc + item.borrow())
}
}
// ------------------------------------------------------------------------
// Negation
// ------------------------------------------------------------------------
@ -622,10 +637,10 @@ impl<'a> Neg for &'a EdwardsPoint {
type Output = EdwardsPoint;
fn neg(self) -> EdwardsPoint {
EdwardsPoint{
EdwardsPoint {
X: -(&self.X),
Y: self.Y,
Z: self.Z,
Y: self.Y,
Z: self.Z,
T: -(&self.T),
}
}
@ -802,153 +817,152 @@ impl EdwardsPoint {
macro_rules! impl_basepoint_table {
(Name = $name:ident, LookupTable = $table:ident, Point = $point:ty, Radix = $radix:expr, Additions = $adds:expr) => {
/// A precomputed table of multiples of a basepoint, for accelerating
/// fixed-base scalar multiplication. One table, for the Ed25519
/// basepoint, is provided in the `constants` module.
///
/// The basepoint tables are reasonably large, so they should probably be boxed.
///
/// The sizes for the tables and the number of additions required for one scalar
/// multiplication are as follows:
///
/// * [`EdwardsBasepointTableRadix16`]: 30KB, 64A
/// (this is the default size, and is used for [`ED25519_BASEPOINT_TABLE`])
/// * [`EdwardsBasepointTableRadix64`]: 120KB, 43A
/// * [`EdwardsBasepointTableRadix128`]: 240KB, 37A
/// * [`EdwardsBasepointTableRadix256`]: 480KB, 33A
///
/// # Why 33 additions for radix-256?
///
/// Normally, the radix-256 tables would allow for only 32 additions per scalar
/// multiplication. However, due to the fact that standardised definitions of
/// legacy protocols—such as x25519—require allowing unreduced 255-bit scalar
/// invariants, when converting such an unreduced scalar's representation to
/// radix-\\(2^{8}\\), we cannot guarantee the carry bit will fit in the last
/// coefficient (the coefficients are `i8`s). When, \\(w\\), the power-of-2 of
/// the radix, is \\(w < 8\\), we can fold the final carry onto the last
/// coefficient, \\(d\\), because \\(d < 2^{w/2}\\), so
/// $$
/// d + carry \cdot 2^{w} = d + 1 \cdot 2^{w} < 2^{w+1} < 2^{8}
/// $$
/// When \\(w = 8\\), we can't fit \\(carry \cdot 2^{w}\\) into an `i8`, so we
/// add the carry bit onto an additional coefficient.
#[derive(Clone)]
pub struct $name(pub(crate) [$table<AffineNielsPoint>; 32]);
/// A precomputed table of multiples of a basepoint, for accelerating
/// fixed-base scalar multiplication. One table, for the Ed25519
/// basepoint, is provided in the `constants` module.
///
/// The basepoint tables are reasonably large, so they should probably be boxed.
///
/// The sizes for the tables and the number of additions required for one scalar
/// multiplication are as follows:
///
/// * [`EdwardsBasepointTableRadix16`]: 30KB, 64A
/// (this is the default size, and is used for [`ED25519_BASEPOINT_TABLE`])
/// * [`EdwardsBasepointTableRadix64`]: 120KB, 43A
/// * [`EdwardsBasepointTableRadix128`]: 240KB, 37A
/// * [`EdwardsBasepointTableRadix256`]: 480KB, 33A
///
/// # Why 33 additions for radix-256?
///
/// Normally, the radix-256 tables would allow for only 32 additions per scalar
/// multiplication. However, due to the fact that standardised definitions of
/// legacy protocols—such as x25519—require allowing unreduced 255-bit scalar
/// invariants, when converting such an unreduced scalar's representation to
/// radix-\\(2^{8}\\), we cannot guarantee the carry bit will fit in the last
/// coefficient (the coefficients are `i8`s). When, \\(w\\), the power-of-2 of
/// the radix, is \\(w < 8\\), we can fold the final carry onto the last
/// coefficient, \\(d\\), because \\(d < 2^{w/2}\\), so
/// $$
/// d + carry \cdot 2^{w} = d + 1 \cdot 2^{w} < 2^{w+1} < 2^{8}
/// $$
/// When \\(w = 8\\), we can't fit \\(carry \cdot 2^{w}\\) into an `i8`, so we
/// add the carry bit onto an additional coefficient.
#[derive(Clone)]
pub struct $name(pub(crate) [$table<AffineNielsPoint>; 32]);
impl BasepointTable for $name {
type Point = $point;
impl BasepointTable for $name {
type Point = $point;
/// Create a table of precomputed multiples of `basepoint`.
fn create(basepoint: &$point) -> $name {
// XXX use init_with
let mut table = $name([$table::default(); 32]);
let mut P = *basepoint;
for i in 0..32 {
// P = (2w)^i * B
table.0[i] = $table::from(&P);
P = P.mul_by_pow_2($radix + $radix);
}
table
}
/// Create a table of precomputed multiples of `basepoint`.
fn create(basepoint: &$point) -> $name {
// XXX use init_with
let mut table = $name([$table::default(); 32]);
let mut P = *basepoint;
for i in 0..32 {
// P = (2w)^i * B
table.0[i] = $table::from(&P);
P = P.mul_by_pow_2($radix + $radix);
}
table
}
/// Get the basepoint for this table as an `EdwardsPoint`.
fn basepoint(&self) -> $point {
// self.0[0].select(1) = 1*(16^2)^0*B
// but as an `AffineNielsPoint`, so add identity to convert to extended.
(&<$point>::identity() + &self.0[0].select(1)).to_extended()
}
/// Get the basepoint for this table as an `EdwardsPoint`.
fn basepoint(&self) -> $point {
// self.0[0].select(1) = 1*(16^2)^0*B
// but as an `AffineNielsPoint`, so add identity to convert to extended.
(&<$point>::identity() + &self.0[0].select(1)).to_extended()
}
/// The computation uses Pippeneger's algorithm, as described for the
/// specific case of radix-16 on page 13 of the Ed25519 paper.
///
/// # Piggenger's Algorithm Generalised
///
/// Write the scalar \\(a\\) in radix-\\(w\\), where \\(w\\) is a power of
/// 2, with coefficients in \\([\frac{-w}{2},\frac{w}{2})\\), i.e.,
/// $$
/// a = a\_0 + a\_1 w\^1 + \cdots + a\_{x} w\^{x},
/// $$
/// with
/// $$
/// \frac{-w}{2} \leq a_i < \frac{w}{2}, \cdots, \frac{-w}{2} \leq a\_{x} \leq \frac{w}{2}
/// $$
/// and the number of additions, \\(x\\), is given by \\(x = \lceil \frac{256}{w} \rceil\\).
/// Then
/// $$
/// a B = a\_0 B + a\_1 w\^1 B + \cdots + a\_{x-1} w\^{x-1} B.
/// $$
/// Grouping even and odd coefficients gives
/// $$
/// \begin{aligned}
/// a B = \quad a\_0 w\^0 B +& a\_2 w\^2 B + \cdots + a\_{x-2} w\^{x-2} B \\\\
/// + a\_1 w\^1 B +& a\_3 w\^3 B + \cdots + a\_{x-1} w\^{x-1} B \\\\
/// = \quad(a\_0 w\^0 B +& a\_2 w\^2 B + \cdots + a\_{x-2} w\^{x-2} B) \\\\
/// + w(a\_1 w\^0 B +& a\_3 w\^2 B + \cdots + a\_{x-1} w\^{x-2} B). \\\\
/// \end{aligned}
/// $$
/// For each \\(i = 0 \ldots 31\\), we create a lookup table of
/// $$
/// [w\^{2i} B, \ldots, \frac{w}{2}\cdotw\^{2i} B],
/// $$
/// and use it to select \\( y \cdot w\^{2i} \cdot B \\) in constant time.
///
/// The radix-\\(w\\) representation requires that the scalar is bounded
/// by \\(2\^{255}\\), which is always the case.
///
/// The above algorithm is trivially generalised to other powers-of-2 radices.
fn basepoint_mul(&self, scalar: &Scalar) -> $point {
let a = scalar.to_radix_2w($radix);
/// The computation uses Pippeneger's algorithm, as described for the
/// specific case of radix-16 on page 13 of the Ed25519 paper.
///
/// # Piggenger's Algorithm Generalised
///
/// Write the scalar \\(a\\) in radix-\\(w\\), where \\(w\\) is a power of
/// 2, with coefficients in \\([\frac{-w}{2},\frac{w}{2})\\), i.e.,
/// $$
/// a = a\_0 + a\_1 w\^1 + \cdots + a\_{x} w\^{x},
/// $$
/// with
/// $$
/// \frac{-w}{2} \leq a_i < \frac{w}{2}, \cdots, \frac{-w}{2} \leq a\_{x} \leq \frac{w}{2}
/// $$
/// and the number of additions, \\(x\\), is given by \\(x = \lceil \frac{256}{w} \rceil\\).
/// Then
/// $$
/// a B = a\_0 B + a\_1 w\^1 B + \cdots + a\_{x-1} w\^{x-1} B.
/// $$
/// Grouping even and odd coefficients gives
/// $$
/// \begin{aligned}
/// a B = \quad a\_0 w\^0 B +& a\_2 w\^2 B + \cdots + a\_{x-2} w\^{x-2} B \\\\
/// + a\_1 w\^1 B +& a\_3 w\^3 B + \cdots + a\_{x-1} w\^{x-1} B \\\\
/// = \quad(a\_0 w\^0 B +& a\_2 w\^2 B + \cdots + a\_{x-2} w\^{x-2} B) \\\\
/// + w(a\_1 w\^0 B +& a\_3 w\^2 B + \cdots + a\_{x-1} w\^{x-2} B). \\\\
/// \end{aligned}
/// $$
/// For each \\(i = 0 \ldots 31\\), we create a lookup table of
/// $$
/// [w\^{2i} B, \ldots, \frac{w}{2}\cdotw\^{2i} B],
/// $$
/// and use it to select \\( y \cdot w\^{2i} \cdot B \\) in constant time.
///
/// The radix-\\(w\\) representation requires that the scalar is bounded
/// by \\(2\^{255}\\), which is always the case.
///
/// The above algorithm is trivially generalised to other powers-of-2 radices.
fn basepoint_mul(&self, scalar: &Scalar) -> $point {
let a = scalar.to_radix_2w($radix);
let tables = &self.0;
let mut P = <$point>::identity();
let tables = &self.0;
let mut P = <$point>::identity();
for i in (0..$adds).filter(|x| x % 2 == 1) {
P = (&P + &tables[i / 2].select(a[i])).to_extended();
}
for i in (0..$adds).filter(|x| x % 2 == 1) {
P = (&P + &tables[i/2].select(a[i])).to_extended();
P = P.mul_by_pow_2($radix);
for i in (0..$adds).filter(|x| x % 2 == 0) {
P = (&P + &tables[i / 2].select(a[i])).to_extended();
}
P
}
}
P = P.mul_by_pow_2($radix);
impl<'a, 'b> Mul<&'b Scalar> for &'a $name {
type Output = $point;
for i in (0..$adds).filter(|x| x % 2 == 0) {
P = (&P + &tables[i/2].select(a[i])).to_extended();
/// Construct an `EdwardsPoint` from a `Scalar` \\(a\\) by
/// computing the multiple \\(aB\\) of this basepoint \\(B\\).
fn mul(self, scalar: &'b Scalar) -> $point {
// delegate to a private function so that its documentation appears in internal docs
self.basepoint_mul(scalar)
}
}
P
}
}
impl<'a, 'b> Mul<&'a $name> for &'b Scalar {
type Output = $point;
impl<'a, 'b> Mul<&'b Scalar> for &'a $name {
type Output = $point;
/// Construct an `EdwardsPoint` from a `Scalar` \\(a\\) by
/// computing the multiple \\(aB\\) of this basepoint \\(B\\).
fn mul(self, scalar: &'b Scalar) -> $point {
// delegate to a private function so that its documentation appears in internal docs
self.basepoint_mul(scalar)
}
}
impl<'a, 'b> Mul<&'a $name> for &'b Scalar {
type Output = $point;
/// Construct an `EdwardsPoint` from a `Scalar` \\(a\\) by
/// computing the multiple \\(aB\\) of this basepoint \\(B\\).
fn mul(self, basepoint_table: &'a $name) -> $point {
basepoint_table * self
}
}
impl Debug for $name {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{:?}([\n", stringify!($name))?;
for i in 0..32 {
write!(f, "\t{:?},\n", &self.0[i])?;
/// Construct an `EdwardsPoint` from a `Scalar` \\(a\\) by
/// computing the multiple \\(aB\\) of this basepoint \\(B\\).
fn mul(self, basepoint_table: &'a $name) -> $point {
basepoint_table * self
}
}
write!(f, "])")
}
}
}} // End macro_rules! impl_basepoint_table
impl Debug for $name {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{:?}([\n", stringify!($name))?;
for i in 0..32 {
write!(f, "\t{:?},\n", &self.0[i])?;
}
write!(f, "])")
}
}
};
} // End macro_rules! impl_basepoint_table
// The number of additions required is ceil(256/w) where w is the radix representation.
impl_basepoint_table! {Name = EdwardsBasepointTable, LookupTable = LookupTableRadix16, Point = EdwardsPoint, Radix = 4, Additions = 64}
@ -978,22 +992,22 @@ macro_rules! impl_basepoint_table_conversions {
<$lhs>::create(&table.basepoint())
}
}
}
};
}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix32}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix64}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix128}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix32}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix64}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix128}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix16, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix32, RHS = EdwardsBasepointTableRadix64}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix32, RHS = EdwardsBasepointTableRadix128}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix32, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix32, RHS = EdwardsBasepointTableRadix64}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix32, RHS = EdwardsBasepointTableRadix128}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix32, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix64, RHS = EdwardsBasepointTableRadix128}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix64, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix64, RHS = EdwardsBasepointTableRadix128}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix64, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions!{LHS = EdwardsBasepointTableRadix128, RHS = EdwardsBasepointTableRadix256}
impl_basepoint_table_conversions! {LHS = EdwardsBasepointTableRadix128, RHS = EdwardsBasepointTableRadix256}
impl EdwardsPoint {
/// Multiply by the cofactor: return \\([8]P\\).
@ -1003,11 +1017,12 @@ impl EdwardsPoint {
/// Compute \\([2\^k] P \\) by successive doublings. Requires \\( k > 0 \\).
pub(crate) fn mul_by_pow_2(&self, k: u32) -> EdwardsPoint {
debug_assert!( k > 0 );
debug_assert!(k > 0);
let mut r: CompletedPoint;
let mut s = self.to_projective();
for _ in 0..(k-1) {
r = s.double(); s = r.to_projective();
for _ in 0..(k - 1) {
r = s.double();
s = r.to_projective();
}
// Unroll last iteration so we can go directly to_extended()
s.double().to_extended()
@ -1077,8 +1092,11 @@ impl EdwardsPoint {
impl Debug for EdwardsPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "EdwardsPoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?},\n\tT: {:?}\n}}",
&self.X, &self.Y, &self.Z, &self.T)
write!(
f,
"EdwardsPoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?},\n\tT: {:?}\n}}",
&self.X, &self.Y, &self.Z, &self.T
)
}
}
@ -1088,72 +1106,74 @@ impl Debug for EdwardsPoint {
#[cfg(test)]
mod test {
use super::*;
use crate::constants;
use crate::field::FieldElement;
use crate::scalar::Scalar;
use subtle::ConditionallySelectable;
use crate::constants;
use super::*;
/// X coordinate of the basepoint.
/// = 15112221349535400772501151409588531511454012693041857206046113283949847762202
static BASE_X_COORD_BYTES: [u8; 32] =
[0x1a, 0xd5, 0x25, 0x8f, 0x60, 0x2d, 0x56, 0xc9, 0xb2, 0xa7, 0x25, 0x95, 0x60, 0xc7, 0x2c, 0x69,
0x5c, 0xdc, 0xd6, 0xfd, 0x31, 0xe2, 0xa4, 0xc0, 0xfe, 0x53, 0x6e, 0xcd, 0xd3, 0x36, 0x69, 0x21];
static BASE_X_COORD_BYTES: [u8; 32] = [
0x1a, 0xd5, 0x25, 0x8f, 0x60, 0x2d, 0x56, 0xc9, 0xb2, 0xa7, 0x25, 0x95, 0x60, 0xc7, 0x2c,
0x69, 0x5c, 0xdc, 0xd6, 0xfd, 0x31, 0xe2, 0xa4, 0xc0, 0xfe, 0x53, 0x6e, 0xcd, 0xd3, 0x36,
0x69, 0x21,
];
/// Compressed Edwards Y form of 2*basepoint.
static BASE2_CMPRSSD: CompressedEdwardsY =
CompressedEdwardsY([0xc9, 0xa3, 0xf8, 0x6a, 0xae, 0x46, 0x5f, 0xe,
0x56, 0x51, 0x38, 0x64, 0x51, 0x0f, 0x39, 0x97,
0x56, 0x1f, 0xa2, 0xc9, 0xe8, 0x5e, 0xa2, 0x1d,
0xc2, 0x29, 0x23, 0x09, 0xf3, 0xcd, 0x60, 0x22]);
static BASE2_CMPRSSD: CompressedEdwardsY = CompressedEdwardsY([
0xc9, 0xa3, 0xf8, 0x6a, 0xae, 0x46, 0x5f, 0xe, 0x56, 0x51, 0x38, 0x64, 0x51, 0x0f, 0x39,
0x97, 0x56, 0x1f, 0xa2, 0xc9, 0xe8, 0x5e, 0xa2, 0x1d, 0xc2, 0x29, 0x23, 0x09, 0xf3, 0xcd,
0x60, 0x22,
]);
/// Compressed Edwards Y form of 16*basepoint.
static BASE16_CMPRSSD: CompressedEdwardsY =
CompressedEdwardsY([0xeb, 0x27, 0x67, 0xc1, 0x37, 0xab, 0x7a, 0xd8,
0x27, 0x9c, 0x07, 0x8e, 0xff, 0x11, 0x6a, 0xb0,
0x78, 0x6e, 0xad, 0x3a, 0x2e, 0x0f, 0x98, 0x9f,
0x72, 0xc3, 0x7f, 0x82, 0xf2, 0x96, 0x96, 0x70]);
static BASE16_CMPRSSD: CompressedEdwardsY = CompressedEdwardsY([
0xeb, 0x27, 0x67, 0xc1, 0x37, 0xab, 0x7a, 0xd8, 0x27, 0x9c, 0x07, 0x8e, 0xff, 0x11, 0x6a,
0xb0, 0x78, 0x6e, 0xad, 0x3a, 0x2e, 0x0f, 0x98, 0x9f, 0x72, 0xc3, 0x7f, 0x82, 0xf2, 0x96,
0x96, 0x70,
]);
/// 4493907448824000747700850167940867464579944529806937181821189941592931634714
pub static A_SCALAR: Scalar = Scalar{
pub static A_SCALAR: Scalar = Scalar {
bytes: [
0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d,
0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8, 0x26, 0x4d,
0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1,
0x58, 0x9e, 0x7b, 0x7f, 0x23, 0x76, 0xef, 0x09,
0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d, 0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8,
0x26, 0x4d, 0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1, 0x58, 0x9e, 0x7b, 0x7f,
0x23, 0x76, 0xef, 0x09,
],
};
/// 2506056684125797857694181776241676200180934651973138769173342316833279714961
pub static B_SCALAR: Scalar = Scalar{
pub static B_SCALAR: Scalar = Scalar {
bytes: [
0x91, 0x26, 0x7a, 0xcf, 0x25, 0xc2, 0x09, 0x1b,
0xa2, 0x17, 0x74, 0x7b, 0x66, 0xf0, 0xb3, 0x2e,
0x9d, 0xf2, 0xa5, 0x67, 0x41, 0xcf, 0xda, 0xc4,
0x56, 0xa7, 0xd4, 0xaa, 0xb8, 0x60, 0x8a, 0x05,
0x91, 0x26, 0x7a, 0xcf, 0x25, 0xc2, 0x09, 0x1b, 0xa2, 0x17, 0x74, 0x7b, 0x66, 0xf0,
0xb3, 0x2e, 0x9d, 0xf2, 0xa5, 0x67, 0x41, 0xcf, 0xda, 0xc4, 0x56, 0xa7, 0xd4, 0xaa,
0xb8, 0x60, 0x8a, 0x05,
],
};
/// A_SCALAR * basepoint, computed with ed25519.py
pub static A_TIMES_BASEPOINT: CompressedEdwardsY = CompressedEdwardsY([
0xea, 0x27, 0xe2, 0x60, 0x53, 0xdf, 0x1b, 0x59,
0x56, 0xf1, 0x4d, 0x5d, 0xec, 0x3c, 0x34, 0xc3,
0x84, 0xa2, 0x69, 0xb7, 0x4c, 0xc3, 0x80, 0x3e,
0xa8, 0xe2, 0xe7, 0xc9, 0x42, 0x5e, 0x40, 0xa5]);
0xea, 0x27, 0xe2, 0x60, 0x53, 0xdf, 0x1b, 0x59, 0x56, 0xf1, 0x4d, 0x5d, 0xec, 0x3c, 0x34,
0xc3, 0x84, 0xa2, 0x69, 0xb7, 0x4c, 0xc3, 0x80, 0x3e, 0xa8, 0xe2, 0xe7, 0xc9, 0x42, 0x5e,
0x40, 0xa5,
]);
/// A_SCALAR * (A_TIMES_BASEPOINT) + B_SCALAR * BASEPOINT
/// computed with ed25519.py
static DOUBLE_SCALAR_MULT_RESULT: CompressedEdwardsY = CompressedEdwardsY([
0x7d, 0xfd, 0x6c, 0x45, 0xaf, 0x6d, 0x6e, 0x0e,
0xba, 0x20, 0x37, 0x1a, 0x23, 0x64, 0x59, 0xc4,
0xc0, 0x46, 0x83, 0x43, 0xde, 0x70, 0x4b, 0x85,
0x09, 0x6f, 0xfe, 0x35, 0x4f, 0x13, 0x2b, 0x42]);
0x7d, 0xfd, 0x6c, 0x45, 0xaf, 0x6d, 0x6e, 0x0e, 0xba, 0x20, 0x37, 0x1a, 0x23, 0x64, 0x59,
0xc4, 0xc0, 0x46, 0x83, 0x43, 0xde, 0x70, 0x4b, 0x85, 0x09, 0x6f, 0xfe, 0x35, 0x4f, 0x13,
0x2b, 0x42,
]);
/// Test round-trip decompression for the basepoint.
#[test]
fn basepoint_decompression_compression() {
let base_X = FieldElement::from_bytes(&BASE_X_COORD_BYTES);
let bp = constants::ED25519_BASEPOINT_COMPRESSED.decompress().unwrap();
let bp = constants::ED25519_BASEPOINT_COMPRESSED
.decompress()
.unwrap();
assert!(bp.is_valid());
// Check that decompression actually gives the correct X coordinate
assert_eq!(base_X, bp.X);
@ -1167,12 +1187,13 @@ mod test {
let mut minus_basepoint_bytes = constants::ED25519_BASEPOINT_COMPRESSED.as_bytes().clone();
minus_basepoint_bytes[31] |= 1 << 7;
let minus_basepoint = CompressedEdwardsY(minus_basepoint_bytes)
.decompress().unwrap();
.decompress()
.unwrap();
// Test projective coordinates exactly since we know they should
// only differ by a flipped sign.
assert_eq!(minus_basepoint.X, -(&constants::ED25519_BASEPOINT_POINT.X));
assert_eq!(minus_basepoint.Y, constants::ED25519_BASEPOINT_POINT.Y);
assert_eq!(minus_basepoint.Z, constants::ED25519_BASEPOINT_POINT.Z);
assert_eq!(minus_basepoint.Y, constants::ED25519_BASEPOINT_POINT.Y);
assert_eq!(minus_basepoint.Z, constants::ED25519_BASEPOINT_POINT.Z);
assert_eq!(minus_basepoint.T, -(&constants::ED25519_BASEPOINT_POINT.T));
}
@ -1223,13 +1244,14 @@ mod test {
/// coordinates correctly.
#[test]
fn extended_point_equality_handles_scaling() {
let mut two_bytes = [0u8; 32]; two_bytes[0] = 2;
let mut two_bytes = [0u8; 32];
two_bytes[0] = 2;
let id1 = EdwardsPoint::identity();
let id2 = EdwardsPoint{
let id2 = EdwardsPoint {
X: FieldElement::zero(),
Y: FieldElement::from_bytes(&two_bytes),
Z: FieldElement::from_bytes(&two_bytes),
T: FieldElement::zero()
T: FieldElement::zero(),
};
assert_eq!(id1.ct_eq(&id2).unwrap_u8(), 1u8);
}
@ -1241,8 +1263,7 @@ mod test {
let aB = &constants::ED25519_BASEPOINT_TABLE * &A_SCALAR;
let aB_affine_niels = aB.to_affine_niels();
let also_aB = (&EdwardsPoint::identity() + &aB_affine_niels).to_extended();
assert_eq!( aB.compress(),
also_aB.compress());
assert_eq!(aB.compress(), also_aB.compress());
}
/// Test basepoint_mult versus a known scalar multiple from ed25519.py
@ -1278,8 +1299,10 @@ mod test {
/// Test basepoint.double() versus the 2*basepoint constant.
#[test]
fn basepoint_double_vs_basepoint2() {
assert_eq!(constants::ED25519_BASEPOINT_POINT.double().compress(),
BASE2_CMPRSSD);
assert_eq!(
constants::ED25519_BASEPOINT_POINT.double().compress(),
BASE2_CMPRSSD
);
}
/// Test that computing 2*basepoint is the same as basepoint.double()
@ -1321,10 +1344,9 @@ mod test {
fn basepoint_tables_unreduced_scalar() {
let P = &constants::ED25519_BASEPOINT_POINT;
let a = Scalar::from_bits([
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
]);
let table_radix16 = EdwardsBasepointTableRadix16::create(&P);
@ -1350,9 +1372,13 @@ mod test {
/// Check that converting to projective and then back to extended round-trips.
#[test]
fn basepoint_projective_extended_round_trip() {
assert_eq!(constants::ED25519_BASEPOINT_POINT
.to_projective().to_extended().compress(),
constants::ED25519_BASEPOINT_COMPRESSED);
assert_eq!(
constants::ED25519_BASEPOINT_POINT
.to_projective()
.to_extended()
.compress(),
constants::ED25519_BASEPOINT_COMPRESSED
);
}
/// Test computing 16*basepoint vs mul_by_pow_2(4)
@ -1364,7 +1390,6 @@ mod test {
#[test]
fn impl_sum() {
// Test that sum works for non-empty iterators
let BASE = constants::ED25519_BASEPOINT_POINT;
@ -1391,15 +1416,14 @@ mod test {
let sum: EdwardsPoint = mapped.sum();
assert_eq!(sum, &P1 * &s + &P2 * &s);
}
}
/// Test that the conditional assignment trait works for AffineNielsPoints.
#[test]
fn conditional_assign_for_affine_niels_point() {
let id = AffineNielsPoint::identity();
let id = AffineNielsPoint::identity();
let mut p1 = AffineNielsPoint::identity();
let bp = constants::ED25519_BASEPOINT_POINT.to_affine_niels();
let bp = constants::ED25519_BASEPOINT_POINT.to_affine_niels();
p1.conditional_assign(&bp, Choice::from(0));
assert_eq!(p1, id);
@ -1419,13 +1443,15 @@ mod test {
#[test]
fn compressed_identity() {
assert_eq!(EdwardsPoint::identity().compress(),
CompressedEdwardsY::identity());
assert_eq!(
EdwardsPoint::identity().compress(),
CompressedEdwardsY::identity()
);
}
#[test]
fn is_identity() {
assert!( EdwardsPoint::identity().is_identity());
assert!(EdwardsPoint::identity().is_identity());
assert!(!constants::ED25519_BASEPOINT_POINT.is_identity());
}
@ -1472,12 +1498,11 @@ mod test {
// The largest scalar allowed by the type system, 2^255-1
.chain(iter::once(Scalar::from_bits([0xff; 32])))
.collect::<Vec<_>>();
let check = xs.iter()
.map(|xi| xi * xi)
.sum::<Scalar>();
let check = xs.iter().map(|xi| xi * xi).sum::<Scalar>();
// Construct points G_i = x_i * B
let Gs = xs.iter()
let Gs = xs
.iter()
.map(|xi| xi * &constants::ED25519_BASEPOINT_TABLE)
.collect::<Vec<_>>();
@ -1572,13 +1597,14 @@ mod test {
mod vartime {
use super::super::*;
use super::{A_SCALAR, B_SCALAR, A_TIMES_BASEPOINT, DOUBLE_SCALAR_MULT_RESULT};
use super::{A_SCALAR, A_TIMES_BASEPOINT, B_SCALAR, DOUBLE_SCALAR_MULT_RESULT};
/// Test double_scalar_mul_vartime vs ed25519.py
#[test]
fn double_scalar_mul_basepoint_vs_ed25519py() {
let A = A_TIMES_BASEPOINT.decompress().unwrap();
let result = EdwardsPoint::vartime_double_scalar_mul_basepoint(&A_SCALAR, &A, &B_SCALAR);
let result =
EdwardsPoint::vartime_double_scalar_mul_basepoint(&A_SCALAR, &A, &B_SCALAR);
assert_eq!(result.compress(), DOUBLE_SCALAR_MULT_RESULT);
}
@ -1587,7 +1613,7 @@ mod test {
let A = A_TIMES_BASEPOINT.decompress().unwrap();
let result = EdwardsPoint::vartime_multiscalar_mul(
&[A_SCALAR, B_SCALAR],
&[A, constants::ED25519_BASEPOINT_POINT]
&[A, constants::ED25519_BASEPOINT_POINT],
);
assert_eq!(result.compress(), DOUBLE_SCALAR_MULT_RESULT);
}
@ -1597,11 +1623,11 @@ mod test {
let A = A_TIMES_BASEPOINT.decompress().unwrap();
let result_vartime = EdwardsPoint::vartime_multiscalar_mul(
&[A_SCALAR, B_SCALAR],
&[A, constants::ED25519_BASEPOINT_POINT]
&[A, constants::ED25519_BASEPOINT_POINT],
);
let result_consttime = EdwardsPoint::multiscalar_mul(
&[A_SCALAR, B_SCALAR],
&[A, constants::ED25519_BASEPOINT_POINT]
&[A, constants::ED25519_BASEPOINT_POINT],
);
assert_eq!(result_vartime.compress(), result_consttime.compress());

View file

@ -25,13 +25,13 @@
use core::cmp::{Eq, PartialEq};
use subtle::ConditionallySelectable;
use subtle::ConditionallyNegatable;
use subtle::Choice;
use subtle::ConditionallyNegatable;
use subtle::ConditionallySelectable;
use subtle::ConstantTimeEq;
use crate::constants;
use crate::backend;
use crate::constants;
#[cfg(feature = "fiat_u32_backend")]
pub use backend::serial::fiat_u32::field::*;
@ -254,16 +254,16 @@ impl FieldElement {
//
// If v is zero, r is also zero.
let v3 = &v.square() * v;
let v3 = &v.square() * v;
let v7 = &v3.square() * v;
let mut r = &(u * &v3) * &(u * &v7).pow_p58();
let check = v * &r.square();
let i = &constants::SQRT_M1;
let correct_sign_sqrt = check.ct_eq( u);
let flipped_sign_sqrt = check.ct_eq( &(-u));
let flipped_sign_sqrt_i = check.ct_eq(&(&(-u)*i));
let correct_sign_sqrt = check.ct_eq(u);
let flipped_sign_sqrt = check.ct_eq(&(-u));
let flipped_sign_sqrt_i = check.ct_eq(&(&(-u) * i));
let r_prime = &constants::SQRT_M1 * &r;
r.conditional_assign(&r_prime, flipped_sign_sqrt | flipped_sign_sqrt_i);
@ -302,32 +302,32 @@ mod test {
/// Random element a of GF(2^255-19), from Sage
/// a = 1070314506888354081329385823235218444233221\
/// 2228051251926706380353716438957572
static A_BYTES: [u8; 32] =
[ 0x04, 0xfe, 0xdf, 0x98, 0xa7, 0xfa, 0x0a, 0x68,
0x84, 0x92, 0xbd, 0x59, 0x08, 0x07, 0xa7, 0x03,
0x9e, 0xd1, 0xf6, 0xf2, 0xe1, 0xd9, 0xe2, 0xa4,
0xa4, 0x51, 0x47, 0x36, 0xf3, 0xc3, 0xa9, 0x17];
static A_BYTES: [u8; 32] = [
0x04, 0xfe, 0xdf, 0x98, 0xa7, 0xfa, 0x0a, 0x68, 0x84, 0x92, 0xbd, 0x59, 0x08, 0x07, 0xa7,
0x03, 0x9e, 0xd1, 0xf6, 0xf2, 0xe1, 0xd9, 0xe2, 0xa4, 0xa4, 0x51, 0x47, 0x36, 0xf3, 0xc3,
0xa9, 0x17,
];
/// Byte representation of a**2
static ASQ_BYTES: [u8; 32] =
[ 0x75, 0x97, 0x24, 0x9e, 0xe6, 0x06, 0xfe, 0xab,
0x24, 0x04, 0x56, 0x68, 0x07, 0x91, 0x2d, 0x5d,
0x0b, 0x0f, 0x3f, 0x1c, 0xb2, 0x6e, 0xf2, 0xe2,
0x63, 0x9c, 0x12, 0xba, 0x73, 0x0b, 0xe3, 0x62];
static ASQ_BYTES: [u8; 32] = [
0x75, 0x97, 0x24, 0x9e, 0xe6, 0x06, 0xfe, 0xab, 0x24, 0x04, 0x56, 0x68, 0x07, 0x91, 0x2d,
0x5d, 0x0b, 0x0f, 0x3f, 0x1c, 0xb2, 0x6e, 0xf2, 0xe2, 0x63, 0x9c, 0x12, 0xba, 0x73, 0x0b,
0xe3, 0x62,
];
/// Byte representation of 1/a
static AINV_BYTES: [u8; 32] =
[0x96, 0x1b, 0xcd, 0x8d, 0x4d, 0x5e, 0xa2, 0x3a,
0xe9, 0x36, 0x37, 0x93, 0xdb, 0x7b, 0x4d, 0x70,
0xb8, 0x0d, 0xc0, 0x55, 0xd0, 0x4c, 0x1d, 0x7b,
0x90, 0x71, 0xd8, 0xe9, 0xb6, 0x18, 0xe6, 0x30];
static AINV_BYTES: [u8; 32] = [
0x96, 0x1b, 0xcd, 0x8d, 0x4d, 0x5e, 0xa2, 0x3a, 0xe9, 0x36, 0x37, 0x93, 0xdb, 0x7b, 0x4d,
0x70, 0xb8, 0x0d, 0xc0, 0x55, 0xd0, 0x4c, 0x1d, 0x7b, 0x90, 0x71, 0xd8, 0xe9, 0xb6, 0x18,
0xe6, 0x30,
];
/// Byte representation of a^((p-5)/8)
static AP58_BYTES: [u8; 32] =
[0x6a, 0x4f, 0x24, 0x89, 0x1f, 0x57, 0x60, 0x36,
0xd0, 0xbe, 0x12, 0x3c, 0x8f, 0xf5, 0xb1, 0x59,
0xe0, 0xf0, 0xb8, 0x1b, 0x20, 0xd2, 0xb5, 0x1f,
0x15, 0x21, 0xf9, 0xe3, 0xe1, 0x61, 0x21, 0x55];
static AP58_BYTES: [u8; 32] = [
0x6a, 0x4f, 0x24, 0x89, 0x1f, 0x57, 0x60, 0x36, 0xd0, 0xbe, 0x12, 0x3c, 0x8f, 0xf5, 0xb1,
0x59, 0xe0, 0xf0, 0xb8, 0x1b, 0x20, 0xd2, 0xb5, 0x1f, 0x15, 0x21, 0xf9, 0xe3, 0xe1, 0x61,
0x21, 0x55,
];
#[test]
fn a_mul_a_vs_a_squared_constant() {
@ -347,12 +347,12 @@ mod test {
fn a_square2_vs_a_squared_constant() {
let a = FieldElement::from_bytes(&A_BYTES);
let asq = FieldElement::from_bytes(&ASQ_BYTES);
assert_eq!(a.square2(), &asq+&asq);
assert_eq!(a.square2(), &asq + &asq);
}
#[test]
fn a_invert_vs_inverse_of_a_constant() {
let a = FieldElement::from_bytes(&A_BYTES);
let a = FieldElement::from_bytes(&A_BYTES);
let ainv = FieldElement::from_bytes(&AINV_BYTES);
let should_be_inverse = a.invert();
assert_eq!(ainv, should_be_inverse);
@ -361,11 +361,11 @@ mod test {
#[test]
fn batch_invert_a_matches_nonbatched() {
let a = FieldElement::from_bytes(&A_BYTES);
let a = FieldElement::from_bytes(&A_BYTES);
let ap58 = FieldElement::from_bytes(&AP58_BYTES);
let asq = FieldElement::from_bytes(&ASQ_BYTES);
let asq = FieldElement::from_bytes(&ASQ_BYTES);
let ainv = FieldElement::from_bytes(&AINV_BYTES);
let a2 = &a + &a;
let a2 = &a + &a;
let a_list = vec![a, ap58, asq, ainv, a2];
let mut ainv_list = a_list.clone();
FieldElement::batch_invert(&mut ainv_list[..]);
@ -415,14 +415,14 @@ mod test {
#[test]
fn a_p58_vs_ap58_constant() {
let a = FieldElement::from_bytes(&A_BYTES);
let a = FieldElement::from_bytes(&A_BYTES);
let ap58 = FieldElement::from_bytes(&AP58_BYTES);
assert_eq!(ap58, a.pow_p58());
}
#[test]
fn equality() {
let a = FieldElement::from_bytes(&A_BYTES);
let a = FieldElement::from_bytes(&A_BYTES);
let ainv = FieldElement::from_bytes(&AINV_BYTES);
assert!(a == a);
assert!(a != ainv);
@ -430,24 +430,23 @@ mod test {
/// Notice that the last element has the high bit set, which
/// should be ignored
static B_BYTES: [u8;32] =
[113, 191, 169, 143, 91, 234, 121, 15,
241, 131, 217, 36, 230, 101, 92, 234,
8, 208, 170, 251, 97, 127, 70, 210,
58, 23, 166, 87, 240, 169, 184, 178];
static B_BYTES: [u8; 32] = [
113, 191, 169, 143, 91, 234, 121, 15, 241, 131, 217, 36, 230, 101, 92, 234, 8, 208, 170,
251, 97, 127, 70, 210, 58, 23, 166, 87, 240, 169, 184, 178,
];
#[test]
fn from_bytes_highbit_is_ignored() {
let mut cleared_bytes = B_BYTES;
cleared_bytes[31] &= 127u8;
let with_highbit_set = FieldElement::from_bytes(&B_BYTES);
let with_highbit_set = FieldElement::from_bytes(&B_BYTES);
let without_highbit_set = FieldElement::from_bytes(&cleared_bytes);
assert_eq!(without_highbit_set, with_highbit_set);
}
#[test]
fn conditional_negate() {
let one = FieldElement::one();
let one = FieldElement::one();
let minus_one = FieldElement::minus_one();
let mut x = one;
x.conditional_negate(Choice::from(1));
@ -461,7 +460,11 @@ mod test {
#[test]
fn encoding_is_canonical() {
// Encode 1 wrongly as 1 + (2^255 - 19) = 2^255 - 18
let one_encoded_wrongly_bytes: [u8;32] = [0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f];
let one_encoded_wrongly_bytes: [u8; 32] = [
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x7f,
];
// Decode to a field element
let one = FieldElement::from_bytes(&one_encoded_wrongly_bytes);
// .. then check that the encoding is correct

View file

@ -34,7 +34,7 @@ macro_rules! define_add_variants {
&self + &rhs
}
}
}
};
}
/// Define non-borrow variants of `AddAssign`.
@ -45,7 +45,7 @@ macro_rules! define_add_assign_variants {
*self += &rhs;
}
}
}
};
}
/// Define borrow and non-borrow variants of `Sub`.
@ -71,7 +71,7 @@ macro_rules! define_sub_variants {
&self - &rhs
}
}
}
};
}
/// Define non-borrow variants of `SubAssign`.
@ -82,7 +82,7 @@ macro_rules! define_sub_assign_variants {
*self -= &rhs;
}
}
}
};
}
/// Define borrow and non-borrow variants of `Mul`.
@ -108,7 +108,7 @@ macro_rules! define_mul_variants {
&self * &rhs
}
}
}
};
}
/// Define non-borrow variants of `MulAssign`.
@ -119,6 +119,5 @@ macro_rules! define_mul_assign_variants {
*self *= &rhs;
}
}
}
};
}

View file

@ -151,7 +151,9 @@ impl MontgomeryPoint {
let u = FieldElement::from_bytes(&self.0);
if u == FieldElement::minus_one() { return None; }
if u == FieldElement::minus_one() {
return None;
}
let one = FieldElement::one();
@ -300,8 +302,16 @@ fn differential_add_and_double(
define_mul_assign_variants!(LHS = MontgomeryPoint, RHS = Scalar);
define_mul_variants!(LHS = MontgomeryPoint, RHS = Scalar, Output = MontgomeryPoint);
define_mul_variants!(LHS = Scalar, RHS = MontgomeryPoint, Output = MontgomeryPoint);
define_mul_variants!(
LHS = MontgomeryPoint,
RHS = Scalar,
Output = MontgomeryPoint
);
define_mul_variants!(
LHS = Scalar,
RHS = MontgomeryPoint,
Output = MontgomeryPoint
);
/// Multiply this `MontgomeryPoint` by a `Scalar`.
impl<'a, 'b> Mul<&'b Scalar> for &'a MontgomeryPoint {
@ -397,7 +407,7 @@ mod test {
);
// sign bit = 1 => minus basepoint
assert_eq!(
- constants::ED25519_BASEPOINT_POINT,
-constants::ED25519_BASEPOINT_POINT,
constants::X25519_BASEPOINT.to_edwards(1).unwrap()
);
}
@ -417,7 +427,7 @@ mod test {
let one = FieldElement::one();
// u = 2 corresponds to a point on the twist.
let two = MontgomeryPoint((&one+&one).to_bytes());
let two = MontgomeryPoint((&one + &one).to_bytes());
assert!(two.to_edwards(0).is_none());
@ -431,7 +441,8 @@ mod test {
#[test]
fn eq_defined_mod_p() {
let mut u18_bytes = [0u8; 32]; u18_bytes[0] = 18;
let mut u18_bytes = [0u8; 32];
u18_bytes[0] = 18;
let u18 = MontgomeryPoint(u18_bytes);
let u18_unred = MontgomeryPoint([255; 32]);

View file

@ -174,8 +174,8 @@ use crate::constants;
use crate::field::FieldElement;
use subtle::Choice;
use subtle::ConditionallySelectable;
use subtle::ConditionallyNegatable;
use subtle::ConditionallySelectable;
use subtle::ConstantTimeEq;
use zeroize::Zeroize;
@ -266,8 +266,7 @@ impl CompressedRistretto {
let s = FieldElement::from_bytes(self.as_bytes());
let s_bytes_check = s.to_bytes();
let s_encoding_is_canonical =
&s_bytes_check[..].ct_eq(self.as_bytes());
let s_encoding_is_canonical = &s_bytes_check[..].ct_eq(self.as_bytes());
let s_is_negative = s.is_negative();
if s_encoding_is_canonical.unwrap_u8() == 0u8 || s_is_negative.unwrap_u8() == 1u8 {
@ -277,8 +276,8 @@ impl CompressedRistretto {
// Step 2. Compute (X:Y:Z:T).
let one = FieldElement::one();
let ss = s.square();
let u1 = &one - &ss; // 1 + as²
let u2 = &one + &ss; // 1 - as² where a=-1
let u1 = &one - &ss; // 1 + as²
let u2 = &one + &ss; // 1 - as² where a=-1
let u2_sqr = u2.square(); // (1 - as²)²
// v == ad(1+as²)² - (1-as²)² where d=-121665/121666
@ -286,7 +285,7 @@ impl CompressedRistretto {
let (ok, I) = (&v * &u2_sqr).invsqrt(); // 1/sqrt(v*u_2²)
let Dx = &I * &u2; // 1/sqrt(v)
let Dx = &I * &u2; // 1/sqrt(v)
let Dy = &I * &(&Dx * &v); // 1/u2
// x == | 2s/sqrt(v) | == + sqrt(4s²/(ad(1+as²)² - (1-as²)²))
@ -300,10 +299,18 @@ impl CompressedRistretto {
// t == ((1+as²) sqrt(4s²/(ad(1+as²)² - (1-as²)²)))/(1-as²)
let t = &x * &y;
if ok.unwrap_u8() == 0u8 || t.is_negative().unwrap_u8() == 1u8 || y.is_zero().unwrap_u8() == 1u8 {
if ok.unwrap_u8() == 0u8
|| t.is_negative().unwrap_u8() == 1u8
|| y.is_zero().unwrap_u8() == 1u8
{
None
} else {
Some(RistrettoPoint(EdwardsPoint{X: x, Y: y, Z: one, T: t}))
Some(RistrettoPoint(EdwardsPoint {
X: x,
Y: y,
Z: one,
T: t,
}))
}
}
}
@ -328,15 +335,16 @@ impl Default for CompressedRistretto {
// structs containing `RistrettoPoint`s and use Serde's derived
// serializers to serialize those structures.
#[cfg(feature = "serde")]
use serde::{self, Serialize, Deserialize, Serializer, Deserializer};
#[cfg(feature = "serde")]
use serde::de::Visitor;
#[cfg(feature = "serde")]
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
impl Serialize for RistrettoPoint {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
where
S: Serializer,
{
use serde::ser::SerializeTuple;
let mut tup = serializer.serialize_tuple(32)?;
@ -350,7 +358,8 @@ impl Serialize for RistrettoPoint {
#[cfg(feature = "serde")]
impl Serialize for CompressedRistretto {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
where
S: Serializer,
{
use serde::ser::SerializeTuple;
let mut tup = serializer.serialize_tuple(32)?;
@ -364,7 +373,8 @@ impl Serialize for CompressedRistretto {
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for RistrettoPoint {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
struct RistrettoPointVisitor;
@ -376,11 +386,13 @@ impl<'de> Deserialize<'de> for RistrettoPoint {
}
fn visit_seq<A>(self, mut seq: A) -> Result<RistrettoPoint, A::Error>
where A: serde::de::SeqAccess<'de>
where
A: serde::de::SeqAccess<'de>,
{
let mut bytes = [0u8; 32];
for i in 0..32 {
bytes[i] = seq.next_element()?
bytes[i] = seq
.next_element()?
.ok_or(serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
}
CompressedRistretto(bytes)
@ -396,7 +408,8 @@ impl<'de> Deserialize<'de> for RistrettoPoint {
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for CompressedRistretto {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
struct CompressedRistrettoVisitor;
@ -408,11 +421,13 @@ impl<'de> Deserialize<'de> for CompressedRistretto {
}
fn visit_seq<A>(self, mut seq: A) -> Result<CompressedRistretto, A::Error>
where A: serde::de::SeqAccess<'de>
where
A: serde::de::SeqAccess<'de>,
{
let mut bytes = [0u8; 32];
for i in 0..32 {
bytes[i] = seq.next_element()?
bytes[i] = seq
.next_element()?
.ok_or(serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
}
Ok(CompressedRistretto(bytes))
@ -506,7 +521,8 @@ impl RistrettoPoint {
/// ```
#[cfg(feature = "alloc")]
pub fn double_and_compress_batch<'a, I>(points: I) -> Vec<CompressedRistretto>
where I: IntoIterator<Item = &'a RistrettoPoint>
where
I: IntoIterator<Item = &'a RistrettoPoint>,
{
#[derive(Copy, Clone, Debug)]
struct BatchCompressState {
@ -544,53 +560,58 @@ impl RistrettoPoint {
}
}
let states: Vec<BatchCompressState> = points.into_iter().map(BatchCompressState::from).collect();
let states: Vec<BatchCompressState> =
points.into_iter().map(BatchCompressState::from).collect();
let mut invs: Vec<FieldElement> = states.iter().map(|state| state.efgh()).collect();
FieldElement::batch_invert(&mut invs[..]);
states.iter().zip(invs.iter()).map(|(state, inv): (&BatchCompressState, &FieldElement)| {
let Zinv = &state.eg * &inv;
let Tinv = &state.fh * &inv;
states
.iter()
.zip(invs.iter())
.map(|(state, inv): (&BatchCompressState, &FieldElement)| {
let Zinv = &state.eg * &inv;
let Tinv = &state.fh * &inv;
let mut magic = constants::INVSQRT_A_MINUS_D;
let mut magic = constants::INVSQRT_A_MINUS_D;
let negcheck1 = (&state.eg * &Zinv).is_negative();
let negcheck1 = (&state.eg * &Zinv).is_negative();
let mut e = state.e;
let mut g = state.g;
let mut h = state.h;
let mut e = state.e;
let mut g = state.g;
let mut h = state.h;
let minus_e = -&e;
let f_times_sqrta = &state.f * &constants::SQRT_M1;
let minus_e = -&e;
let f_times_sqrta = &state.f * &constants::SQRT_M1;
e.conditional_assign(&state.g, negcheck1);
g.conditional_assign(&minus_e, negcheck1);
h.conditional_assign(&f_times_sqrta, negcheck1);
e.conditional_assign(&state.g, negcheck1);
g.conditional_assign(&minus_e, negcheck1);
h.conditional_assign(&f_times_sqrta, negcheck1);
magic.conditional_assign(&constants::SQRT_M1, negcheck1);
magic.conditional_assign(&constants::SQRT_M1, negcheck1);
let negcheck2 = (&(&h * &e) * &Zinv).is_negative();
let negcheck2 = (&(&h * &e) * &Zinv).is_negative();
g.conditional_negate(negcheck2);
g.conditional_negate(negcheck2);
let mut s = &(&h - &g) * &(&magic * &(&g * &Tinv));
let mut s = &(&h - &g) * &(&magic * &(&g * &Tinv));
let s_is_negative = s.is_negative();
s.conditional_negate(s_is_negative);
let s_is_negative = s.is_negative();
s.conditional_negate(s_is_negative);
CompressedRistretto(s.to_bytes())
}).collect()
CompressedRistretto(s.to_bytes())
})
.collect()
}
/// Return the coset self + E[4], for debugging.
fn coset4(&self) -> [EdwardsPoint; 4] {
[ self.0
, &self.0 + &constants::EIGHT_TORSION[2]
, &self.0 + &constants::EIGHT_TORSION[4]
, &self.0 + &constants::EIGHT_TORSION[6]
[
self.0,
&self.0 + &constants::EIGHT_TORSION[2],
&self.0 + &constants::EIGHT_TORSION[4],
&self.0 + &constants::EIGHT_TORSION[6],
]
}
@ -627,12 +648,15 @@ impl RistrettoPoint {
use crate::backend::serial::curve_models::CompletedPoint;
// The conversion from W_i is exactly the conversion from P1xP1.
RistrettoPoint(CompletedPoint{
X: &(&s + &s) * &D,
Z: &N_t * &constants::SQRT_AD_MINUS_ONE,
Y: &FieldElement::one() - &s_sq,
T: &FieldElement::one() + &s_sq,
}.to_extended())
RistrettoPoint(
CompletedPoint {
X: &(&s + &s) * &D,
Z: &N_t * &constants::SQRT_AD_MINUS_ONE,
Y: &FieldElement::one() - &s_sq,
T: &FieldElement::one() + &s_sq,
}
.to_extended(),
)
}
/// Return a `RistrettoPoint` chosen uniformly at random using a user-provided RNG.
@ -687,7 +711,8 @@ impl RistrettoPoint {
/// ```
///
pub fn hash_from_bytes<D>(input: &[u8]) -> RistrettoPoint
where D: Digest<OutputSize = U64> + Default
where
D: Digest<OutputSize = U64> + Default,
{
let mut hash = D::default();
hash.update(input);
@ -700,7 +725,8 @@ impl RistrettoPoint {
/// to stream data into the `Digest` than to pass a single byte
/// slice.
pub fn from_hash<D>(hash: D) -> RistrettoPoint
where D: Digest<OutputSize = U64> + Default
where
D: Digest<OutputSize = U64> + Default,
{
// dealing with generic arrays is clumsy, until const generics land
let output = hash.finalize();
@ -791,7 +817,11 @@ impl<'a, 'b> Add<&'b RistrettoPoint> for &'a RistrettoPoint {
}
}
define_add_variants!(LHS = RistrettoPoint, RHS = RistrettoPoint, Output = RistrettoPoint);
define_add_variants!(
LHS = RistrettoPoint,
RHS = RistrettoPoint,
Output = RistrettoPoint
);
impl<'b> AddAssign<&'b RistrettoPoint> for RistrettoPoint {
fn add_assign(&mut self, _rhs: &RistrettoPoint) {
@ -809,7 +839,11 @@ impl<'a, 'b> Sub<&'b RistrettoPoint> for &'a RistrettoPoint {
}
}
define_sub_variants!(LHS = RistrettoPoint, RHS = RistrettoPoint, Output = RistrettoPoint);
define_sub_variants!(
LHS = RistrettoPoint,
RHS = RistrettoPoint,
Output = RistrettoPoint
);
impl<'b> SubAssign<&'b RistrettoPoint> for RistrettoPoint {
fn sub_assign(&mut self, _rhs: &RistrettoPoint) {
@ -821,11 +855,11 @@ define_sub_assign_variants!(LHS = RistrettoPoint, RHS = RistrettoPoint);
impl<T> Sum<T> for RistrettoPoint
where
T: Borrow<RistrettoPoint>
T: Borrow<RistrettoPoint>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>
I: Iterator<Item = T>,
{
iter.fold(RistrettoPoint::identity(), |acc, item| acc + item.borrow())
}
@ -895,9 +929,7 @@ impl MultiscalarMul for RistrettoPoint {
J::Item: Borrow<RistrettoPoint>,
{
let extended_points = points.into_iter().map(|P| P.borrow().0);
RistrettoPoint(
EdwardsPoint::multiscalar_mul(scalars, extended_points)
)
RistrettoPoint(EdwardsPoint::multiscalar_mul(scalars, extended_points))
}
}
@ -971,9 +1003,9 @@ impl RistrettoPoint {
A: &RistrettoPoint,
b: &Scalar,
) -> RistrettoPoint {
RistrettoPoint(
EdwardsPoint::vartime_double_scalar_mul_basepoint(a, &A.0, b)
)
RistrettoPoint(EdwardsPoint::vartime_double_scalar_mul_basepoint(
a, &A.0, b,
))
}
}
@ -1071,8 +1103,11 @@ impl Debug for CompressedRistretto {
impl Debug for RistrettoPoint {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let coset = self.coset4();
write!(f, "RistrettoPoint: coset \n{:?}\n{:?}\n{:?}\n{:?}",
coset[0], coset[1], coset[2], coset[3])
write!(
f,
"RistrettoPoint: coset \n{:?}\n{:?}\n{:?}\n{:?}",
coset[0], coset[1], coset[2], coset[3]
)
}
}
@ -1100,11 +1135,11 @@ impl Zeroize for RistrettoPoint {
mod test {
use rand_core::OsRng;
use crate::scalar::Scalar;
use super::*;
use crate::constants;
use crate::edwards::CompressedEdwardsY;
use crate::traits::{Identity};
use super::*;
use crate::scalar::Scalar;
use crate::traits::Identity;
#[test]
#[cfg(feature = "serde")]
@ -1112,7 +1147,8 @@ mod test {
use bincode;
let encoded = bincode::serialize(&constants::RISTRETTO_BASEPOINT_POINT).unwrap();
let enc_compressed = bincode::serialize(&constants::RISTRETTO_BASEPOINT_COMPRESSED).unwrap();
let enc_compressed =
bincode::serialize(&constants::RISTRETTO_BASEPOINT_COMPRESSED).unwrap();
assert_eq!(encoded, enc_compressed);
// Check that the encoding is 32 bytes exactly
@ -1143,7 +1179,6 @@ mod test {
#[test]
fn impl_sum() {
// Test that sum works for non-empty iterators
let BASE = constants::RISTRETTO_BASEPOINT_POINT;
@ -1213,22 +1248,70 @@ mod test {
// Table of encodings of i*basepoint
// Generated using ristretto.sage
let compressed = [
CompressedRistretto([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
CompressedRistretto([226, 242, 174, 10, 106, 188, 78, 113, 168, 132, 169, 97, 197, 0, 81, 95, 88, 227, 11, 106, 165, 130, 221, 141, 182, 166, 89, 69, 224, 141, 45, 118]),
CompressedRistretto([106, 73, 50, 16, 247, 73, 156, 209, 127, 236, 181, 16, 174, 12, 234, 35, 161, 16, 232, 213, 185, 1, 248, 172, 173, 211, 9, 92, 115, 163, 185, 25]),
CompressedRistretto([148, 116, 31, 93, 93, 82, 117, 94, 206, 79, 35, 240, 68, 238, 39, 213, 209, 234, 30, 43, 209, 150, 180, 98, 22, 107, 22, 21, 42, 157, 2, 89]),
CompressedRistretto([218, 128, 134, 39, 115, 53, 139, 70, 111, 250, 223, 224, 179, 41, 58, 179, 217, 253, 83, 197, 234, 108, 149, 83, 88, 245, 104, 50, 45, 175, 106, 87]),
CompressedRistretto([232, 130, 177, 49, 1, 107, 82, 193, 211, 51, 112, 128, 24, 124, 247, 104, 66, 62, 252, 203, 181, 23, 187, 73, 90, 184, 18, 196, 22, 15, 244, 78]),
CompressedRistretto([246, 71, 70, 211, 201, 43, 19, 5, 14, 216, 216, 2, 54, 167, 240, 0, 124, 59, 63, 150, 47, 91, 167, 147, 209, 154, 96, 30, 187, 29, 244, 3]),
CompressedRistretto([68, 245, 53, 32, 146, 110, 200, 31, 189, 90, 56, 120, 69, 190, 183, 223, 133, 169, 106, 36, 236, 225, 135, 56, 189, 207, 166, 167, 130, 42, 23, 109]),
CompressedRistretto([144, 50, 147, 216, 242, 40, 126, 190, 16, 226, 55, 77, 193, 165, 62, 11, 200, 135, 229, 146, 105, 159, 2, 208, 119, 213, 38, 60, 221, 85, 96, 28]),
CompressedRistretto([2, 98, 42, 206, 143, 115, 3, 163, 28, 175, 198, 63, 143, 196, 143, 220, 22, 225, 200, 200, 210, 52, 178, 240, 214, 104, 82, 130, 169, 7, 96, 49]),
CompressedRistretto([32, 112, 111, 215, 136, 178, 114, 10, 30, 210, 165, 218, 212, 149, 43, 1, 244, 19, 188, 240, 231, 86, 77, 232, 205, 200, 22, 104, 158, 45, 185, 95]),
CompressedRistretto([188, 232, 63, 139, 165, 221, 47, 165, 114, 134, 76, 36, 186, 24, 16, 249, 82, 43, 198, 0, 74, 254, 149, 135, 122, 199, 50, 65, 202, 253, 171, 66]),
CompressedRistretto([228, 84, 158, 225, 107, 154, 160, 48, 153, 202, 32, 140, 103, 173, 175, 202, 250, 76, 63, 62, 78, 83, 3, 222, 96, 38, 227, 202, 143, 248, 68, 96]),
CompressedRistretto([170, 82, 224, 0, 223, 46, 22, 245, 95, 177, 3, 47, 195, 59, 196, 39, 66, 218, 214, 189, 90, 143, 192, 190, 1, 103, 67, 108, 89, 72, 80, 31]),
CompressedRistretto([70, 55, 107, 128, 244, 9, 178, 157, 194, 181, 246, 240, 197, 37, 145, 153, 8, 150, 229, 113, 111, 65, 71, 124, 211, 0, 133, 171, 127, 16, 48, 30]),
CompressedRistretto([224, 196, 24, 247, 200, 217, 196, 205, 215, 57, 91, 147, 234, 18, 79, 58, 217, 144, 33, 187, 104, 29, 252, 51, 2, 169, 217, 154, 46, 83, 230, 78]),
CompressedRistretto([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
]),
CompressedRistretto([
226, 242, 174, 10, 106, 188, 78, 113, 168, 132, 169, 97, 197, 0, 81, 95, 88, 227,
11, 106, 165, 130, 221, 141, 182, 166, 89, 69, 224, 141, 45, 118,
]),
CompressedRistretto([
106, 73, 50, 16, 247, 73, 156, 209, 127, 236, 181, 16, 174, 12, 234, 35, 161, 16,
232, 213, 185, 1, 248, 172, 173, 211, 9, 92, 115, 163, 185, 25,
]),
CompressedRistretto([
148, 116, 31, 93, 93, 82, 117, 94, 206, 79, 35, 240, 68, 238, 39, 213, 209, 234,
30, 43, 209, 150, 180, 98, 22, 107, 22, 21, 42, 157, 2, 89,
]),
CompressedRistretto([
218, 128, 134, 39, 115, 53, 139, 70, 111, 250, 223, 224, 179, 41, 58, 179, 217,
253, 83, 197, 234, 108, 149, 83, 88, 245, 104, 50, 45, 175, 106, 87,
]),
CompressedRistretto([
232, 130, 177, 49, 1, 107, 82, 193, 211, 51, 112, 128, 24, 124, 247, 104, 66, 62,
252, 203, 181, 23, 187, 73, 90, 184, 18, 196, 22, 15, 244, 78,
]),
CompressedRistretto([
246, 71, 70, 211, 201, 43, 19, 5, 14, 216, 216, 2, 54, 167, 240, 0, 124, 59, 63,
150, 47, 91, 167, 147, 209, 154, 96, 30, 187, 29, 244, 3,
]),
CompressedRistretto([
68, 245, 53, 32, 146, 110, 200, 31, 189, 90, 56, 120, 69, 190, 183, 223, 133, 169,
106, 36, 236, 225, 135, 56, 189, 207, 166, 167, 130, 42, 23, 109,
]),
CompressedRistretto([
144, 50, 147, 216, 242, 40, 126, 190, 16, 226, 55, 77, 193, 165, 62, 11, 200, 135,
229, 146, 105, 159, 2, 208, 119, 213, 38, 60, 221, 85, 96, 28,
]),
CompressedRistretto([
2, 98, 42, 206, 143, 115, 3, 163, 28, 175, 198, 63, 143, 196, 143, 220, 22, 225,
200, 200, 210, 52, 178, 240, 214, 104, 82, 130, 169, 7, 96, 49,
]),
CompressedRistretto([
32, 112, 111, 215, 136, 178, 114, 10, 30, 210, 165, 218, 212, 149, 43, 1, 244, 19,
188, 240, 231, 86, 77, 232, 205, 200, 22, 104, 158, 45, 185, 95,
]),
CompressedRistretto([
188, 232, 63, 139, 165, 221, 47, 165, 114, 134, 76, 36, 186, 24, 16, 249, 82, 43,
198, 0, 74, 254, 149, 135, 122, 199, 50, 65, 202, 253, 171, 66,
]),
CompressedRistretto([
228, 84, 158, 225, 107, 154, 160, 48, 153, 202, 32, 140, 103, 173, 175, 202, 250,
76, 63, 62, 78, 83, 3, 222, 96, 38, 227, 202, 143, 248, 68, 96,
]),
CompressedRistretto([
170, 82, 224, 0, 223, 46, 22, 245, 95, 177, 3, 47, 195, 59, 196, 39, 66, 218, 214,
189, 90, 143, 192, 190, 1, 103, 67, 108, 89, 72, 80, 31,
]),
CompressedRistretto([
70, 55, 107, 128, 244, 9, 178, 157, 194, 181, 246, 240, 197, 37, 145, 153, 8, 150,
229, 113, 111, 65, 71, 124, 211, 0, 133, 171, 127, 16, 48, 30,
]),
CompressedRistretto([
224, 196, 24, 247, 200, 217, 196, 205, 215, 57, 91, 147, 234, 18, 79, 58, 217, 144,
33, 187, 104, 29, 252, 51, 2, 169, 217, 154, 46, 83, 230, 78,
]),
];
let mut bp = RistrettoPoint::identity();
for i in 0..16 {
@ -1265,41 +1348,137 @@ mod test {
// ristretto.sage does not mask the high bit of a field element. When the high bit is set,
// the ristretto.sage elligator implementation gives different results, since it takes a
// different field element as input.
let bytes: [[u8;32]; 16] = [
[184, 249, 135, 49, 253, 123, 89, 113, 67, 160, 6, 239, 7, 105, 211, 41, 192, 249, 185, 57, 9, 102, 70, 198, 15, 127, 7, 26, 160, 102, 134, 71],
[229, 14, 241, 227, 75, 9, 118, 60, 128, 153, 226, 21, 183, 217, 91, 136, 98, 0, 231, 156, 124, 77, 82, 139, 142, 134, 164, 169, 169, 62, 250, 52],
[115, 109, 36, 220, 180, 223, 99, 6, 204, 169, 19, 29, 169, 68, 84, 23, 21, 109, 189, 149, 127, 205, 91, 102, 172, 35, 112, 35, 134, 69, 186, 34],
[16, 49, 96, 107, 171, 199, 164, 9, 129, 16, 64, 62, 241, 63, 132, 173, 209, 160, 112, 215, 105, 50, 157, 81, 253, 105, 1, 154, 229, 25, 120, 83],
[156, 131, 161, 162, 236, 251, 5, 187, 167, 171, 17, 178, 148, 210, 90, 207, 86, 21, 79, 161, 167, 215, 234, 1, 136, 242, 182, 248, 38, 85, 79, 86],
[251, 177, 124, 54, 18, 101, 75, 235, 245, 186, 19, 46, 133, 157, 229, 64, 10, 136, 181, 185, 78, 144, 254, 167, 137, 49, 107, 10, 61, 10, 21, 25],
[232, 193, 20, 68, 240, 77, 186, 77, 183, 40, 44, 86, 150, 31, 198, 212, 76, 81, 3, 217, 197, 8, 126, 128, 126, 152, 164, 208, 153, 44, 189, 77],
[173, 229, 149, 177, 37, 230, 30, 69, 61, 56, 172, 190, 219, 115, 167, 194, 71, 134, 59, 75, 28, 244, 118, 26, 162, 97, 64, 16, 15, 189, 30, 64],
[106, 71, 61, 107, 250, 117, 42, 151, 91, 202, 212, 100, 52, 188, 190, 21, 125, 218, 31, 18, 253, 241, 160, 133, 57, 242, 3, 164, 189, 68, 111, 75],
[112, 204, 182, 90, 220, 198, 120, 73, 173, 107, 193, 17, 227, 40, 162, 36, 150, 141, 235, 55, 172, 183, 12, 39, 194, 136, 43, 153, 244, 118, 91, 89],
[111, 24, 203, 123, 254, 189, 11, 162, 51, 196, 163, 136, 204, 143, 10, 222, 33, 112, 81, 205, 34, 35, 8, 66, 90, 6, 164, 58, 170, 177, 34, 25],
[225, 183, 30, 52, 236, 82, 6, 183, 109, 25, 227, 181, 25, 82, 41, 193, 80, 77, 161, 80, 242, 203, 79, 204, 136, 245, 131, 110, 237, 106, 3, 58],
[207, 246, 38, 56, 30, 86, 176, 90, 27, 200, 61, 42, 221, 27, 56, 210, 79, 178, 189, 120, 68, 193, 120, 167, 77, 185, 53, 197, 124, 128, 191, 126],
[1, 136, 215, 80, 240, 46, 63, 147, 16, 244, 230, 207, 82, 189, 74, 50, 106, 169, 138, 86, 30, 131, 214, 202, 166, 125, 251, 228, 98, 24, 36, 21],
[210, 207, 228, 56, 155, 116, 207, 54, 84, 195, 251, 215, 249, 199, 116, 75, 109, 239, 196, 251, 194, 246, 252, 228, 70, 146, 156, 35, 25, 39, 241, 4],
[34, 116, 123, 9, 8, 40, 93, 189, 9, 103, 57, 103, 66, 227, 3, 2, 157, 107, 134, 219, 202, 74, 230, 154, 78, 107, 219, 195, 214, 14, 84, 80],
let bytes: [[u8; 32]; 16] = [
[
184, 249, 135, 49, 253, 123, 89, 113, 67, 160, 6, 239, 7, 105, 211, 41, 192, 249,
185, 57, 9, 102, 70, 198, 15, 127, 7, 26, 160, 102, 134, 71,
],
[
229, 14, 241, 227, 75, 9, 118, 60, 128, 153, 226, 21, 183, 217, 91, 136, 98, 0,
231, 156, 124, 77, 82, 139, 142, 134, 164, 169, 169, 62, 250, 52,
],
[
115, 109, 36, 220, 180, 223, 99, 6, 204, 169, 19, 29, 169, 68, 84, 23, 21, 109,
189, 149, 127, 205, 91, 102, 172, 35, 112, 35, 134, 69, 186, 34,
],
[
16, 49, 96, 107, 171, 199, 164, 9, 129, 16, 64, 62, 241, 63, 132, 173, 209, 160,
112, 215, 105, 50, 157, 81, 253, 105, 1, 154, 229, 25, 120, 83,
],
[
156, 131, 161, 162, 236, 251, 5, 187, 167, 171, 17, 178, 148, 210, 90, 207, 86, 21,
79, 161, 167, 215, 234, 1, 136, 242, 182, 248, 38, 85, 79, 86,
],
[
251, 177, 124, 54, 18, 101, 75, 235, 245, 186, 19, 46, 133, 157, 229, 64, 10, 136,
181, 185, 78, 144, 254, 167, 137, 49, 107, 10, 61, 10, 21, 25,
],
[
232, 193, 20, 68, 240, 77, 186, 77, 183, 40, 44, 86, 150, 31, 198, 212, 76, 81, 3,
217, 197, 8, 126, 128, 126, 152, 164, 208, 153, 44, 189, 77,
],
[
173, 229, 149, 177, 37, 230, 30, 69, 61, 56, 172, 190, 219, 115, 167, 194, 71, 134,
59, 75, 28, 244, 118, 26, 162, 97, 64, 16, 15, 189, 30, 64,
],
[
106, 71, 61, 107, 250, 117, 42, 151, 91, 202, 212, 100, 52, 188, 190, 21, 125, 218,
31, 18, 253, 241, 160, 133, 57, 242, 3, 164, 189, 68, 111, 75,
],
[
112, 204, 182, 90, 220, 198, 120, 73, 173, 107, 193, 17, 227, 40, 162, 36, 150,
141, 235, 55, 172, 183, 12, 39, 194, 136, 43, 153, 244, 118, 91, 89,
],
[
111, 24, 203, 123, 254, 189, 11, 162, 51, 196, 163, 136, 204, 143, 10, 222, 33,
112, 81, 205, 34, 35, 8, 66, 90, 6, 164, 58, 170, 177, 34, 25,
],
[
225, 183, 30, 52, 236, 82, 6, 183, 109, 25, 227, 181, 25, 82, 41, 193, 80, 77, 161,
80, 242, 203, 79, 204, 136, 245, 131, 110, 237, 106, 3, 58,
],
[
207, 246, 38, 56, 30, 86, 176, 90, 27, 200, 61, 42, 221, 27, 56, 210, 79, 178, 189,
120, 68, 193, 120, 167, 77, 185, 53, 197, 124, 128, 191, 126,
],
[
1, 136, 215, 80, 240, 46, 63, 147, 16, 244, 230, 207, 82, 189, 74, 50, 106, 169,
138, 86, 30, 131, 214, 202, 166, 125, 251, 228, 98, 24, 36, 21,
],
[
210, 207, 228, 56, 155, 116, 207, 54, 84, 195, 251, 215, 249, 199, 116, 75, 109,
239, 196, 251, 194, 246, 252, 228, 70, 146, 156, 35, 25, 39, 241, 4,
],
[
34, 116, 123, 9, 8, 40, 93, 189, 9, 103, 57, 103, 66, 227, 3, 2, 157, 107, 134,
219, 202, 74, 230, 154, 78, 107, 219, 195, 214, 14, 84, 80,
],
];
let encoded_images: [CompressedRistretto; 16] = [
CompressedRistretto([176, 157, 237, 97, 66, 29, 140, 166, 168, 94, 26, 157, 212, 216, 229, 160, 195, 246, 232, 239, 169, 112, 63, 193, 64, 32, 152, 69, 11, 190, 246, 86]),
CompressedRistretto([234, 141, 77, 203, 181, 225, 250, 74, 171, 62, 15, 118, 78, 212, 150, 19, 131, 14, 188, 238, 194, 244, 141, 138, 166, 162, 83, 122, 228, 201, 19, 26]),
CompressedRistretto([232, 231, 51, 92, 5, 168, 80, 36, 173, 179, 104, 68, 186, 149, 68, 40, 140, 170, 27, 103, 99, 140, 21, 242, 43, 62, 250, 134, 208, 255, 61, 89]),
CompressedRistretto([208, 120, 140, 129, 177, 179, 237, 159, 252, 160, 28, 13, 206, 5, 211, 241, 192, 218, 1, 97, 130, 241, 20, 169, 119, 46, 246, 29, 79, 80, 77, 84]),
CompressedRistretto([202, 11, 236, 145, 58, 12, 181, 157, 209, 6, 213, 88, 75, 147, 11, 119, 191, 139, 47, 142, 33, 36, 153, 193, 223, 183, 178, 8, 205, 120, 248, 110]),
CompressedRistretto([26, 66, 231, 67, 203, 175, 116, 130, 32, 136, 62, 253, 215, 46, 5, 214, 166, 248, 108, 237, 216, 71, 244, 173, 72, 133, 82, 6, 143, 240, 104, 41]),
CompressedRistretto([40, 157, 102, 96, 201, 223, 200, 197, 150, 181, 106, 83, 103, 126, 143, 33, 145, 230, 78, 6, 171, 146, 210, 143, 112, 5, 245, 23, 183, 138, 18, 120]),
CompressedRistretto([220, 37, 27, 203, 239, 196, 176, 131, 37, 66, 188, 243, 185, 250, 113, 23, 167, 211, 154, 243, 168, 215, 54, 171, 159, 36, 195, 81, 13, 150, 43, 43]),
CompressedRistretto([232, 121, 176, 222, 183, 196, 159, 90, 238, 193, 105, 52, 101, 167, 244, 170, 121, 114, 196, 6, 67, 152, 80, 185, 221, 7, 83, 105, 176, 208, 224, 121]),
CompressedRistretto([226, 181, 183, 52, 241, 163, 61, 179, 221, 207, 220, 73, 245, 242, 25, 236, 67, 84, 179, 222, 167, 62, 167, 182, 32, 9, 92, 30, 165, 127, 204, 68]),
CompressedRistretto([226, 119, 16, 242, 200, 139, 240, 87, 11, 222, 92, 146, 156, 243, 46, 119, 65, 59, 1, 248, 92, 183, 50, 175, 87, 40, 206, 53, 208, 220, 148, 13]),
CompressedRistretto([70, 240, 79, 112, 54, 157, 228, 146, 74, 122, 216, 88, 232, 62, 158, 13, 14, 146, 115, 117, 176, 222, 90, 225, 244, 23, 94, 190, 150, 7, 136, 96]),
CompressedRistretto([22, 71, 241, 103, 45, 193, 195, 144, 183, 101, 154, 50, 39, 68, 49, 110, 51, 44, 62, 0, 229, 113, 72, 81, 168, 29, 73, 106, 102, 40, 132, 24]),
CompressedRistretto([196, 133, 107, 11, 130, 105, 74, 33, 204, 171, 133, 221, 174, 193, 241, 36, 38, 179, 196, 107, 219, 185, 181, 253, 228, 47, 155, 42, 231, 73, 41, 78]),
CompressedRistretto([58, 255, 225, 197, 115, 208, 160, 143, 39, 197, 82, 69, 143, 235, 92, 170, 74, 40, 57, 11, 171, 227, 26, 185, 217, 207, 90, 185, 197, 190, 35, 60]),
CompressedRistretto([88, 43, 92, 118, 223, 136, 105, 145, 238, 186, 115, 8, 214, 112, 153, 253, 38, 108, 205, 230, 157, 130, 11, 66, 101, 85, 253, 110, 110, 14, 148, 112]),
CompressedRistretto([
176, 157, 237, 97, 66, 29, 140, 166, 168, 94, 26, 157, 212, 216, 229, 160, 195,
246, 232, 239, 169, 112, 63, 193, 64, 32, 152, 69, 11, 190, 246, 86,
]),
CompressedRistretto([
234, 141, 77, 203, 181, 225, 250, 74, 171, 62, 15, 118, 78, 212, 150, 19, 131, 14,
188, 238, 194, 244, 141, 138, 166, 162, 83, 122, 228, 201, 19, 26,
]),
CompressedRistretto([
232, 231, 51, 92, 5, 168, 80, 36, 173, 179, 104, 68, 186, 149, 68, 40, 140, 170,
27, 103, 99, 140, 21, 242, 43, 62, 250, 134, 208, 255, 61, 89,
]),
CompressedRistretto([
208, 120, 140, 129, 177, 179, 237, 159, 252, 160, 28, 13, 206, 5, 211, 241, 192,
218, 1, 97, 130, 241, 20, 169, 119, 46, 246, 29, 79, 80, 77, 84,
]),
CompressedRistretto([
202, 11, 236, 145, 58, 12, 181, 157, 209, 6, 213, 88, 75, 147, 11, 119, 191, 139,
47, 142, 33, 36, 153, 193, 223, 183, 178, 8, 205, 120, 248, 110,
]),
CompressedRistretto([
26, 66, 231, 67, 203, 175, 116, 130, 32, 136, 62, 253, 215, 46, 5, 214, 166, 248,
108, 237, 216, 71, 244, 173, 72, 133, 82, 6, 143, 240, 104, 41,
]),
CompressedRistretto([
40, 157, 102, 96, 201, 223, 200, 197, 150, 181, 106, 83, 103, 126, 143, 33, 145,
230, 78, 6, 171, 146, 210, 143, 112, 5, 245, 23, 183, 138, 18, 120,
]),
CompressedRistretto([
220, 37, 27, 203, 239, 196, 176, 131, 37, 66, 188, 243, 185, 250, 113, 23, 167,
211, 154, 243, 168, 215, 54, 171, 159, 36, 195, 81, 13, 150, 43, 43,
]),
CompressedRistretto([
232, 121, 176, 222, 183, 196, 159, 90, 238, 193, 105, 52, 101, 167, 244, 170, 121,
114, 196, 6, 67, 152, 80, 185, 221, 7, 83, 105, 176, 208, 224, 121,
]),
CompressedRistretto([
226, 181, 183, 52, 241, 163, 61, 179, 221, 207, 220, 73, 245, 242, 25, 236, 67, 84,
179, 222, 167, 62, 167, 182, 32, 9, 92, 30, 165, 127, 204, 68,
]),
CompressedRistretto([
226, 119, 16, 242, 200, 139, 240, 87, 11, 222, 92, 146, 156, 243, 46, 119, 65, 59,
1, 248, 92, 183, 50, 175, 87, 40, 206, 53, 208, 220, 148, 13,
]),
CompressedRistretto([
70, 240, 79, 112, 54, 157, 228, 146, 74, 122, 216, 88, 232, 62, 158, 13, 14, 146,
115, 117, 176, 222, 90, 225, 244, 23, 94, 190, 150, 7, 136, 96,
]),
CompressedRistretto([
22, 71, 241, 103, 45, 193, 195, 144, 183, 101, 154, 50, 39, 68, 49, 110, 51, 44,
62, 0, 229, 113, 72, 81, 168, 29, 73, 106, 102, 40, 132, 24,
]),
CompressedRistretto([
196, 133, 107, 11, 130, 105, 74, 33, 204, 171, 133, 221, 174, 193, 241, 36, 38,
179, 196, 107, 219, 185, 181, 253, 228, 47, 155, 42, 231, 73, 41, 78,
]),
CompressedRistretto([
58, 255, 225, 197, 115, 208, 160, 143, 39, 197, 82, 69, 143, 235, 92, 170, 74, 40,
57, 11, 171, 227, 26, 185, 217, 207, 90, 185, 197, 190, 35, 60,
]),
CompressedRistretto([
88, 43, 92, 118, 223, 136, 105, 145, 238, 186, 115, 8, 214, 112, 153, 253, 38, 108,
205, 230, 157, 130, 11, 66, 101, 85, 253, 110, 110, 14, 148, 112,
]),
];
for i in 0..16 {
let r_0 = FieldElement::from_bytes(&bytes[i]);
@ -1324,8 +1503,9 @@ mod test {
fn double_and_compress_1024_random_points() {
let mut rng = OsRng;
let points: Vec<RistrettoPoint> =
(0..1024).map(|_| RistrettoPoint::random(&mut rng)).collect();
let points: Vec<RistrettoPoint> = (0..1024)
.map(|_| RistrettoPoint::random(&mut rng))
.collect();
let compressed = RistrettoPoint::double_and_compress_batch(&points);

View file

@ -187,7 +187,6 @@ type UnpackedScalar = backend::serial::u64::scalar::Scalar52;
#[cfg(feature = "u32_backend")]
type UnpackedScalar = backend::serial::u32::scalar::Scalar29;
/// The `Scalar` struct holds an integer \\(s < 2\^{255} \\) which
/// represents an element of \\(\mathbb Z / \ell\\).
#[derive(Copy, Clone, Hash)]
@ -212,7 +211,7 @@ impl Scalar {
/// modulo the group order \\( \ell \\).
pub fn from_bytes_mod_order(bytes: [u8; 32]) -> Scalar {
// Temporarily allow s_unreduced.bytes > 2^255 ...
let s_unreduced = Scalar{bytes};
let s_unreduced = Scalar { bytes };
// Then reduce mod the group order and return the reduced representative.
let s = s_unreduced.reduce();
@ -236,7 +235,9 @@ impl Scalar {
/// - `None` if `bytes` is not a canonical byte representation.
pub fn from_canonical_bytes(bytes: [u8; 32]) -> Option<Scalar> {
// Check that the high bit is not set
if (bytes[31] >> 7) != 0u8 { return None; }
if (bytes[31] >> 7) != 0u8 {
return None;
}
let candidate = Scalar::from_bits(bytes);
if candidate.is_canonical() {
@ -252,7 +253,7 @@ impl Scalar {
/// require specific bit-patterns when performing scalar
/// multiplication.
pub const fn from_bits(bytes: [u8; 32]) -> Scalar {
let mut s = Scalar{bytes};
let mut s = Scalar { bytes };
// Ensure that s < 2^255 by masking the high bit
s.bytes[31] &= 0b0111_1111;
@ -385,15 +386,16 @@ impl ConditionallySelectable for Scalar {
}
}
#[cfg(feature = "serde")]
use serde::{self, Serialize, Deserialize, Serializer, Deserializer};
#[cfg(feature = "serde")]
use serde::de::Visitor;
#[cfg(feature = "serde")]
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "serde")]
impl Serialize for Scalar {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
where
S: Serializer,
{
use serde::ser::SerializeTuple;
let mut tup = serializer.serialize_tuple(32)?;
@ -407,7 +409,8 @@ impl Serialize for Scalar {
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Scalar {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
where
D: Deserializer<'de>,
{
struct ScalarVisitor;
@ -419,17 +422,18 @@ impl<'de> Deserialize<'de> for Scalar {
}
fn visit_seq<A>(self, mut seq: A) -> Result<Scalar, A::Error>
where A: serde::de::SeqAccess<'de>
where
A: serde::de::SeqAccess<'de>,
{
let mut bytes = [0u8; 32];
for i in 0..32 {
bytes[i] = seq.next_element()?
bytes[i] = seq
.next_element()?
.ok_or(serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
}
Scalar::from_canonical_bytes(bytes)
.ok_or(serde::de::Error::custom(
&"scalar was not canonically encoded"
))
Scalar::from_canonical_bytes(bytes).ok_or(serde::de::Error::custom(
&"scalar was not canonically encoded",
))
}
}
@ -439,11 +443,11 @@ impl<'de> Deserialize<'de> for Scalar {
impl<T> Product<T> for Scalar
where
T: Borrow<Scalar>
T: Borrow<Scalar>,
{
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = T>
I: Iterator<Item = T>,
{
iter.fold(Scalar::one(), |acc, item| acc * item.borrow())
}
@ -451,11 +455,11 @@ where
impl<T> Sum<T> for Scalar
where
T: Borrow<Scalar>
T: Borrow<Scalar>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>
I: Iterator<Item = T>,
{
iter.fold(Scalar::zero(), |acc, item| acc + item.borrow())
}
@ -471,7 +475,7 @@ impl From<u8> for Scalar {
fn from(x: u8) -> Scalar {
let mut s_bytes = [0u8; 32];
s_bytes[0] = x;
Scalar{ bytes: s_bytes }
Scalar { bytes: s_bytes }
}
}
@ -587,7 +591,8 @@ impl Scalar {
/// # }
/// ```
pub fn hash_from_bytes<D>(input: &[u8]) -> Scalar
where D: Digest<OutputSize = U64> + Default
where
D: Digest<OutputSize = U64> + Default,
{
let mut hash = D::default();
hash.update(input);
@ -628,7 +633,8 @@ impl Scalar {
/// # }
/// ```
pub fn from_hash<D>(hash: D) -> Scalar
where D: Digest<OutputSize = U64>
where
D: Digest<OutputSize = U64>,
{
let mut output = [0u8; 64];
output.copy_from_slice(hash.finalize().as_slice());
@ -667,15 +673,15 @@ impl Scalar {
/// Construct the scalar \\( 0 \\).
pub fn zero() -> Self {
Scalar { bytes: [0u8; 32]}
Scalar { bytes: [0u8; 32] }
}
/// Construct the scalar \\( 1 \\).
pub fn one() -> Self {
Scalar {
bytes: [
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
],
}
}
@ -817,7 +823,7 @@ impl Scalar {
for i in 0..256 {
// As i runs from 0..256, the bottom 3 bits index the bit,
// while the upper bits index the byte.
bits[i] = ((self.bytes[i>>3] >> (i&7)) & 1u8) as i8;
bits[i] = ((self.bytes[i >> 3] >> (i & 7)) & 1u8) as i8;
}
bits
}
@ -896,7 +902,7 @@ impl Scalar {
/// initially, we don't need to emit anything.
pub(crate) fn non_adjacent_form(&self, w: usize) -> [i8; 256] {
// required by the NAF definition
debug_assert!( w >= 2 );
debug_assert!(w >= 2);
// required so that the NAF digits fit in i8
debug_assert!(w <= 8);
@ -920,7 +926,7 @@ impl Scalar {
bit_buf = x_u64[u64_idx] >> bit_idx;
} else {
// Combine the current u64's bits with the bits from the next u64
bit_buf = (x_u64[u64_idx] >> bit_idx) | (x_u64[1+u64_idx] << (64 - bit_idx));
bit_buf = (x_u64[u64_idx] >> bit_idx) | (x_u64[1 + u64_idx] << (64 - bit_idx));
}
// Add the carry into the current window
@ -935,7 +941,7 @@ impl Scalar {
continue;
}
if window < width/2 {
if window < width / 2 {
carry = 0;
naf[pos] = window as i8;
} else {
@ -962,21 +968,25 @@ impl Scalar {
// Step 1: change radix.
// Convert from radix 256 (bytes) to radix 16 (nibbles)
#[inline(always)]
fn bot_half(x: u8) -> u8 { (x >> 0) & 15 }
fn bot_half(x: u8) -> u8 {
(x >> 0) & 15
}
#[inline(always)]
fn top_half(x: u8) -> u8 { (x >> 4) & 15 }
fn top_half(x: u8) -> u8 {
(x >> 4) & 15
}
for i in 0..32 {
output[2*i ] = bot_half(self[i]) as i8;
output[2*i+1] = top_half(self[i]) as i8;
output[2 * i] = bot_half(self[i]) as i8;
output[2 * i + 1] = top_half(self[i]) as i8;
}
// Precondition note: since self[31] <= 127, output[63] <= 7
// Step 2: recenter coefficients from [0,16) to [-8,8)
for i in 0..63 {
let carry = (output[i] + 8) >> 4;
output[i ] -= carry << 4;
output[i+1] += carry;
let carry = (output[i] + 8) >> 4;
output[i] -= carry << 4;
output[i + 1] += carry;
}
// Precondition note: output[63] is not recentered. It
// increases by carry <= 1. Thus output[63] <= 8.
@ -991,12 +1001,12 @@ impl Scalar {
debug_assert!(w <= 8);
let digits_count = match w {
4 => (256 + w - 1)/w as usize,
5 => (256 + w - 1)/w as usize,
6 => (256 + w - 1)/w as usize,
7 => (256 + w - 1)/w as usize,
4 => (256 + w - 1) / w as usize,
5 => (256 + w - 1) / w as usize,
6 => (256 + w - 1) / w as usize,
7 => (256 + w - 1) / w as usize,
// See comment in to_radix_2w on handling the terminal carry.
8 => (256 + w - 1)/w + 1 as usize,
8 => (256 + w - 1) / w + 1 as usize,
_ => panic!("invalid radix parameter"),
};
@ -1038,29 +1048,30 @@ impl Scalar {
let mut carry = 0u64;
let mut digits = [0i8; 64];
let digits_count = (256 + w - 1)/w as usize;
let digits_count = (256 + w - 1) / w as usize;
for i in 0..digits_count {
// Construct a buffer of bits of the scalar, starting at `bit_offset`.
let bit_offset = i*w;
let bit_offset = i * w;
let u64_idx = bit_offset / 64;
let bit_idx = bit_offset % 64;
// Read the bits from the scalar
let bit_buf: u64;
if bit_idx < 64 - w || u64_idx == 3 {
if bit_idx < 64 - w || u64_idx == 3 {
// This window's bits are contained in a single u64,
// or it's the last u64 anyway.
bit_buf = scalar64x4[u64_idx] >> bit_idx;
} else {
// Combine the current u64's bits with the bits from the next u64
bit_buf = (scalar64x4[u64_idx] >> bit_idx) | (scalar64x4[1+u64_idx] << (64 - bit_idx));
bit_buf =
(scalar64x4[u64_idx] >> bit_idx) | (scalar64x4[1 + u64_idx] << (64 - bit_idx));
}
// Read the actual coefficient value from the window
let coef = carry + (bit_buf & window_mask); // coef = [0, 2^r)
// Recenter coefficients from [0,2^w) to [-2^w/2, 2^w/2)
carry = (coef + (radix/2) as u64) >> w;
// Recenter coefficients from [0,2^w) to [-2^w/2, 2^w/2)
carry = (coef + (radix / 2) as u64) >> w;
digits[i] = ((coef as i64) - (carry << w) as i64) as i8;
}
@ -1074,7 +1085,7 @@ impl Scalar {
// and accumulate the final carry onto another digit.
match w {
8 => digits[digits_count] += carry as i8,
_ => digits[digits_count-1] += (carry << w) as i8,
_ => digits[digits_count - 1] += (carry << w) as i8,
}
digits
@ -1118,7 +1129,9 @@ impl Scalar {
impl UnpackedScalar {
/// Pack the limbs of this `UnpackedScalar` into a `Scalar`.
fn pack(&self) -> Scalar {
Scalar{ bytes: self.to_bytes() }
Scalar {
bytes: self.to_bytes(),
}
}
/// Inverts an UnpackedScalar in Montgomery form.
@ -1210,109 +1223,110 @@ mod test {
use crate::constants;
/// x = 2238329342913194256032495932344128051776374960164957527413114840482143558222
pub static X: Scalar = Scalar{
pub static X: Scalar = Scalar {
bytes: [
0x4e, 0x5a, 0xb4, 0x34, 0x5d, 0x47, 0x08, 0x84,
0x59, 0x13, 0xb4, 0x64, 0x1b, 0xc2, 0x7d, 0x52,
0x52, 0xa5, 0x85, 0x10, 0x1b, 0xcc, 0x42, 0x44,
0xd4, 0x49, 0xf4, 0xa8, 0x79, 0xd9, 0xf2, 0x04,
0x4e, 0x5a, 0xb4, 0x34, 0x5d, 0x47, 0x08, 0x84, 0x59, 0x13, 0xb4, 0x64, 0x1b, 0xc2,
0x7d, 0x52, 0x52, 0xa5, 0x85, 0x10, 0x1b, 0xcc, 0x42, 0x44, 0xd4, 0x49, 0xf4, 0xa8,
0x79, 0xd9, 0xf2, 0x04,
],
};
/// 1/x = 6859937278830797291664592131120606308688036382723378951768035303146619657244
pub static XINV: Scalar = Scalar{
pub static XINV: Scalar = Scalar {
bytes: [
0x1c, 0xdc, 0x17, 0xfc, 0xe0, 0xe9, 0xa5, 0xbb,
0xd9, 0x24, 0x7e, 0x56, 0xbb, 0x01, 0x63, 0x47,
0xbb, 0xba, 0x31, 0xed, 0xd5, 0xa9, 0xbb, 0x96,
0xd5, 0x0b, 0xcd, 0x7a, 0x3f, 0x96, 0x2a, 0x0f,
0x1c, 0xdc, 0x17, 0xfc, 0xe0, 0xe9, 0xa5, 0xbb, 0xd9, 0x24, 0x7e, 0x56, 0xbb, 0x01,
0x63, 0x47, 0xbb, 0xba, 0x31, 0xed, 0xd5, 0xa9, 0xbb, 0x96, 0xd5, 0x0b, 0xcd, 0x7a,
0x3f, 0x96, 0x2a, 0x0f,
],
};
/// y = 2592331292931086675770238855846338635550719849568364935475441891787804997264
pub static Y: Scalar = Scalar{
pub static Y: Scalar = Scalar {
bytes: [
0x90, 0x76, 0x33, 0xfe, 0x1c, 0x4b, 0x66, 0xa4,
0xa2, 0x8d, 0x2d, 0xd7, 0x67, 0x83, 0x86, 0xc3,
0x53, 0xd0, 0xde, 0x54, 0x55, 0xd4, 0xfc, 0x9d,
0xe8, 0xef, 0x7a, 0xc3, 0x1f, 0x35, 0xbb, 0x05,
0x90, 0x76, 0x33, 0xfe, 0x1c, 0x4b, 0x66, 0xa4, 0xa2, 0x8d, 0x2d, 0xd7, 0x67, 0x83,
0x86, 0xc3, 0x53, 0xd0, 0xde, 0x54, 0x55, 0xd4, 0xfc, 0x9d, 0xe8, 0xef, 0x7a, 0xc3,
0x1f, 0x35, 0xbb, 0x05,
],
};
/// x*y = 5690045403673944803228348699031245560686958845067437804563560795922180092780
static X_TIMES_Y: Scalar = Scalar{
static X_TIMES_Y: Scalar = Scalar {
bytes: [
0x6c, 0x33, 0x74, 0xa1, 0x89, 0x4f, 0x62, 0x21,
0x0a, 0xaa, 0x2f, 0xe1, 0x86, 0xa6, 0xf9, 0x2c,
0xe0, 0xaa, 0x75, 0xc2, 0x77, 0x95, 0x81, 0xc2,
0x95, 0xfc, 0x08, 0x17, 0x9a, 0x73, 0x94, 0x0c,
0x6c, 0x33, 0x74, 0xa1, 0x89, 0x4f, 0x62, 0x21, 0x0a, 0xaa, 0x2f, 0xe1, 0x86, 0xa6,
0xf9, 0x2c, 0xe0, 0xaa, 0x75, 0xc2, 0x77, 0x95, 0x81, 0xc2, 0x95, 0xfc, 0x08, 0x17,
0x9a, 0x73, 0x94, 0x0c,
],
};
/// sage: l = 2^252 + 27742317777372353535851937790883648493
/// sage: big = 2^256 - 1
/// sage: repr((big % l).digits(256))
static CANONICAL_2_256_MINUS_1: Scalar = Scalar{
static CANONICAL_2_256_MINUS_1: Scalar = Scalar {
bytes: [
28, 149, 152, 141, 116, 49, 236, 214,
112, 207, 125, 115, 244, 91, 239, 198,
254, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 15,
28, 149, 152, 141, 116, 49, 236, 214, 112, 207, 125, 115, 244, 91, 239, 198, 254, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15,
],
};
static A_SCALAR: Scalar = Scalar{
static A_SCALAR: Scalar = Scalar {
bytes: [
0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d,
0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8, 0x26, 0x4d,
0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1,
0x58, 0x9e, 0x7b, 0x7f, 0x23, 0x76, 0xef, 0x09,
0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d, 0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8,
0x26, 0x4d, 0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1, 0x58, 0x9e, 0x7b, 0x7f,
0x23, 0x76, 0xef, 0x09,
],
};
static A_NAF: [i8; 256] =
[0,13,0,0,0,0,0,0,0,7,0,0,0,0,0,0,-9,0,0,0,0,-11,0,0,0,0,3,0,0,0,0,1,
0,0,0,0,9,0,0,0,0,-5,0,0,0,0,0,0,3,0,0,0,0,11,0,0,0,0,11,0,0,0,0,0,
-9,0,0,0,0,0,-3,0,0,0,0,9,0,0,0,0,0,1,0,0,0,0,0,0,-1,0,0,0,0,0,9,0,
0,0,0,-15,0,0,0,0,-7,0,0,0,0,-9,0,0,0,0,0,5,0,0,0,0,13,0,0,0,0,0,-3,0,
0,0,0,-11,0,0,0,0,-7,0,0,0,0,-13,0,0,0,0,11,0,0,0,0,-9,0,0,0,0,0,1,0,0,
0,0,0,-15,0,0,0,0,1,0,0,0,0,7,0,0,0,0,0,0,0,0,5,0,0,0,0,0,13,0,0,0,
0,0,0,11,0,0,0,0,0,15,0,0,0,0,0,-9,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,7,
0,0,0,0,0,-15,0,0,0,0,0,15,0,0,0,0,15,0,0,0,0,15,0,0,0,0,0,1,0,0,0,0];
static A_NAF: [i8; 256] = [
0, 13, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, -11, 0, 0, 0, 0, 3, 0, 0,
0, 0, 1, 0, 0, 0, 0, 9, 0, 0, 0, 0, -5, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 11, 0, 0, 0, 0,
11, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, -1, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, -15, 0, 0, 0, 0, -7, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, 5,
0, 0, 0, 0, 13, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, -11, 0, 0, 0, 0, -7, 0, 0, 0, 0, -13, 0, 0,
0, 0, 11, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -15, 0, 0, 0, 0, 1, 0, 0, 0, 0,
7, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 15,
0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, -15, 0,
0, 0, 0, 0, 15, 0, 0, 0, 0, 15, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
];
static LARGEST_ED25519_S: Scalar = Scalar {
bytes: [
0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x7f,
],
};
static CANONICAL_LARGEST_ED25519_S_PLUS_ONE: Scalar = Scalar {
bytes: [
0x7e, 0x34, 0x47, 0x75, 0x47, 0x4a, 0x7f, 0x97,
0x23, 0xb6, 0x3a, 0x8b, 0xe9, 0x2a, 0xe7, 0x6d,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f,
0x7e, 0x34, 0x47, 0x75, 0x47, 0x4a, 0x7f, 0x97, 0x23, 0xb6, 0x3a, 0x8b, 0xe9, 0x2a,
0xe7, 0x6d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x0f,
],
};
static CANONICAL_LARGEST_ED25519_S_MINUS_ONE: Scalar = Scalar {
bytes: [
0x7c, 0x34, 0x47, 0x75, 0x47, 0x4a, 0x7f, 0x97,
0x23, 0xb6, 0x3a, 0x8b, 0xe9, 0x2a, 0xe7, 0x6d,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f,
0x7c, 0x34, 0x47, 0x75, 0x47, 0x4a, 0x7f, 0x97, 0x23, 0xb6, 0x3a, 0x8b, 0xe9, 0x2a,
0xe7, 0x6d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x0f,
],
};
#[test]
fn fuzzer_testcase_reduction() {
// LE bytes of 24519928653854221733733552434404946937899825954937634815
let a_bytes = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let a_bytes = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
// LE bytes of 4975441334397345751130612518500927154628011511324180036903450236863266160640
let b_bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 210, 210, 210, 255, 255, 255, 255, 10];
let b_bytes = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 210, 210,
210, 255, 255, 255, 255, 10,
];
// LE bytes of 6432735165214683820902750800207468552549813371247423777071615116673864412038
let c_bytes = [134, 171, 119, 216, 180, 128, 178, 62, 171, 132, 32, 62, 34, 119, 104, 193, 47, 215, 181, 250, 14, 207, 172, 93, 75, 207, 211, 103, 144, 204, 56, 14];
let c_bytes = [
134, 171, 119, 216, 180, 128, 178, 62, 171, 132, 32, 62, 34, 119, 104, 193, 47, 215,
181, 250, 14, 207, 172, 93, 75, 207, 211, 103, 144, 204, 56, 14,
];
let a = Scalar::from_bytes_mod_order(a_bytes);
let b = Scalar::from_bytes_mod_order(b_bytes);
@ -1441,10 +1455,9 @@ mod test {
// This test is adapted from the one suggested by Quarkslab.
let large_bytes = [
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x7f,
];
let a = Scalar::from_bytes_mod_order(large_bytes);
@ -1503,7 +1516,7 @@ mod test {
let xs = [Scalar::from(2u64); 10];
let ys = [Scalar::from(3u64); 10];
// now zs is an iterator with Item = Scalar
let zs = xs.iter().zip(ys.iter()).map(|(x,y)| x * y);
let zs = xs.iter().zip(ys.iter()).map(|(x, y)| x * y);
let x_prod: Scalar = xs.iter().product();
let y_prod: Scalar = ys.iter().product();
@ -1513,12 +1526,10 @@ mod test {
assert_eq!(y_prod, Scalar::from(59049u64));
assert_eq!(z_prod, Scalar::from(60466176u64));
assert_eq!(x_prod * y_prod, z_prod);
}
#[test]
fn impl_sum() {
// Test that sum works for non-empty iterators
let two = Scalar::from(2u64);
let one_vector = vec![Scalar::one(), Scalar::one()];
@ -1535,7 +1546,7 @@ mod test {
let xs = [Scalar::from(1u64); 10];
let ys = [Scalar::from(2u64); 10];
// now zs is an iterator with Item = Scalar
let zs = xs.iter().zip(ys.iter()).map(|(x,y)| x + y);
let zs = xs.iter().zip(ys.iter()).map(|(x, y)| x + y);
let x_sum: Scalar = xs.iter().sum();
let y_sum: Scalar = ys.iter().sum();
@ -1567,17 +1578,15 @@ mod test {
let mut bignum = [0u8; 64];
// set bignum = x + 2^256x
for i in 0..32 {
bignum[ i] = X[i];
bignum[32+i] = X[i];
bignum[i] = X[i];
bignum[32 + i] = X[i];
}
// 3958878930004874126169954872055634648693766179881526445624823978500314864344
// = x + 2^256x (mod l)
let reduced = Scalar{
let reduced = Scalar {
bytes: [
216, 154, 179, 139, 210, 121, 2, 71,
69, 99, 158, 216, 23, 173, 63, 100,
204, 0, 91, 50, 219, 153, 57, 249,
28, 82, 31, 197, 100, 165, 192, 8,
216, 154, 179, 139, 210, 121, 2, 71, 69, 99, 158, 216, 23, 173, 63, 100, 204, 0,
91, 50, 219, 153, 57, 249, 28, 82, 31, 197, 100, 165, 192, 8,
],
};
let test_red = Scalar::from_bytes_mod_order_wide(&bignum);
@ -1620,17 +1629,15 @@ mod test {
// set bignum = x + 2^256x
for i in 0..32 {
bignum[ i] = X[i];
bignum[32+i] = X[i];
bignum[i] = X[i];
bignum[32 + i] = X[i];
}
// x + 2^256x (mod l)
// = 3958878930004874126169954872055634648693766179881526445624823978500314864344
let expected = Scalar{
let expected = Scalar {
bytes: [
216, 154, 179, 139, 210, 121, 2, 71,
69, 99, 158, 216, 23, 173, 63, 100,
204, 0, 91, 50, 219, 153, 57, 249,
28, 82, 31, 197, 100, 165, 192, 8
216, 154, 179, 139, 210, 121, 2, 71, 69, 99, 158, 216, 23, 173, 63, 100, 204, 0,
91, 50, 219, 153, 57, 249, 28, 82, 31, 197, 100, 165, 192, 8,
],
};
let reduced = Scalar::from_bytes_mod_order_wide(&bignum);
@ -1639,8 +1646,8 @@ mod test {
assert_eq!(reduced.bytes, expected.bytes);
// (x + 2^256x) * R
let interim = UnpackedScalar::mul_internal(&UnpackedScalar::from_bytes_wide(&bignum),
&constants::R);
let interim =
UnpackedScalar::mul_internal(&UnpackedScalar::from_bytes_wide(&bignum), &constants::R);
// ((x + 2^256x) * R) / R (mod l)
let montgomery_reduced = UnpackedScalar::montgomery_reduce(&interim);
@ -1652,7 +1659,10 @@ mod test {
#[test]
fn canonical_decoding() {
// canonical encoding of 1667457891
let canonical_bytes = [99, 99, 99, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];
let canonical_bytes = [
99, 99, 99, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
];
// encoding of
// 7265385991361016183439748078976496179028704920197054998554201349516117938192
@ -1661,11 +1671,14 @@ mod test {
let non_canonical_bytes_because_unreduced = [16; 32];
// encoding with high bit set, to check that the parser isn't pre-masking the high bit
let non_canonical_bytes_because_highbit = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128];
let non_canonical_bytes_because_highbit = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 128,
];
assert!( Scalar::from_canonical_bytes(canonical_bytes).is_some() );
assert!( Scalar::from_canonical_bytes(non_canonical_bytes_because_unreduced).is_none() );
assert!( Scalar::from_canonical_bytes(non_canonical_bytes_because_highbit).is_none() );
assert!(Scalar::from_canonical_bytes(canonical_bytes).is_some());
assert!(Scalar::from_canonical_bytes(non_canonical_bytes_because_unreduced).is_none());
assert!(Scalar::from_canonical_bytes(non_canonical_bytes_because_highbit).is_none());
}
#[test]
@ -1680,10 +1693,7 @@ mod test {
assert_eq!(encoded.len(), 32);
// Check that the encoding itself matches the usual one
assert_eq!(
X,
bincode::deserialize(X.as_bytes()).unwrap(),
);
assert_eq!(X, bincode::deserialize(X.as_bytes()).unwrap(),);
}
#[cfg(debug_assertions)]
@ -1704,7 +1714,13 @@ mod test {
#[test]
fn batch_invert_consistency() {
let mut x = Scalar::from(1u64);
let mut v1: Vec<_> = (0..16).map(|_| {let tmp = x; x = x + x; tmp}).collect();
let mut v1: Vec<_> = (0..16)
.map(|_| {
let tmp = x;
x = x + x;
tmp
})
.collect();
let v2 = v1.clone();
let expected: Scalar = v1.iter().product();
@ -1721,7 +1737,7 @@ mod test {
let digits_count = Scalar::to_radix_2w_size_hint(w);
let digits = scalar.to_radix_2w(w);
let radix = Scalar::from((1<<w) as u64);
let radix = Scalar::from((1 << w) as u64);
let mut term = Scalar::one();
let mut recovered_scalar = Scalar::zero();
for digit in &digits[0..digits_count] {

View file

@ -15,116 +15,115 @@
use core::fmt::Debug;
use subtle::Choice;
use subtle::ConditionallyNegatable;
use subtle::ConditionallySelectable;
use subtle::ConstantTimeEq;
use subtle::Choice;
use crate::traits::Identity;
use crate::edwards::EdwardsPoint;
use crate::backend::serial::curve_models::ProjectiveNielsPoint;
use crate::backend::serial::curve_models::AffineNielsPoint;
use crate::backend::serial::curve_models::ProjectiveNielsPoint;
use crate::edwards::EdwardsPoint;
use zeroize::Zeroize;
macro_rules! impl_lookup_table {
(Name = $name:ident, Size = $size:expr, SizeNeg = $neg:expr, SizeRange = $range:expr, ConversionRange = $conv_range:expr) => {
/// A lookup table of precomputed multiples of a point \\(P\\), used to
/// compute \\( xP \\) for \\( -8 \leq x \leq 8 \\).
///
/// The computation of \\( xP \\) is done in constant time by the `select` function.
///
/// Since `LookupTable` does not implement `Index`, it's more difficult
/// to accidentally use the table directly. Unfortunately the table is
/// only `pub(crate)` so that we can write hardcoded constants, so it's
/// still technically possible. It would be nice to prevent direct
/// access to the table.
#[derive(Copy, Clone)]
pub struct $name<T>(pub(crate) [T; $size]);
/// A lookup table of precomputed multiples of a point \\(P\\), used to
/// compute \\( xP \\) for \\( -8 \leq x \leq 8 \\).
///
/// The computation of \\( xP \\) is done in constant time by the `select` function.
///
/// Since `LookupTable` does not implement `Index`, it's more difficult
/// to accidentally use the table directly. Unfortunately the table is
/// only `pub(crate)` so that we can write hardcoded constants, so it's
/// still technically possible. It would be nice to prevent direct
/// access to the table.
#[derive(Copy, Clone)]
pub struct $name<T>(pub(crate) [T; $size]);
impl<T> $name<T>
where
T: Identity + ConditionallySelectable + ConditionallyNegatable,
{
/// Given \\(-8 \leq x \leq 8\\), return \\(xP\\) in constant time.
pub fn select(&self, x: i8) -> T {
debug_assert!(x >= $neg);
debug_assert!(x as i16 <= $size as i16); // XXX We have to convert to i16s here for the radix-256 case.. this is wrong.
impl<T> $name<T>
where
T: Identity + ConditionallySelectable + ConditionallyNegatable,
{
/// Given \\(-8 \leq x \leq 8\\), return \\(xP\\) in constant time.
pub fn select(&self, x: i8) -> T {
debug_assert!(x >= $neg);
debug_assert!(x as i16 <= $size as i16); // XXX We have to convert to i16s here for the radix-256 case.. this is wrong.
// Compute xabs = |x|
let xmask = x as i16 >> 7;
let xabs = (x as i16 + xmask) ^ xmask;
// Compute xabs = |x|
let xmask = x as i16 >> 7;
let xabs = (x as i16 + xmask) ^ xmask;
// Set t = 0 * P = identity
let mut t = T::identity();
for j in $range {
// Copy `points[j-1] == j*P` onto `t` in constant time if `|x| == j`.
let c = (xabs as u16).ct_eq(&(j as u16));
t.conditional_assign(&self.0[j - 1], c);
}
// Now t == |x| * P.
// Set t = 0 * P = identity
let mut t = T::identity();
for j in $range {
// Copy `points[j-1] == j*P` onto `t` in constant time if `|x| == j`.
let c = (xabs as u16).ct_eq(&(j as u16));
t.conditional_assign(&self.0[j - 1], c);
}
// Now t == |x| * P.
let neg_mask = Choice::from((xmask & 1) as u8);
t.conditional_negate(neg_mask);
// Now t == x * P.
let neg_mask = Choice::from((xmask & 1) as u8);
t.conditional_negate(neg_mask);
// Now t == x * P.
t
}
}
impl<T: Copy + Default> Default for $name<T> {
fn default() -> $name<T> {
$name([T::default(); $size])
}
}
impl<T: Debug> Debug for $name<T> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{:?}(", stringify!($name))?;
for x in self.0.iter() {
write!(f, "{:?}", x)?;
t
}
}
write!(f, ")")
}
}
impl<'a> From<&'a EdwardsPoint> for $name<ProjectiveNielsPoint> {
fn from(P: &'a EdwardsPoint) -> Self {
let mut points = [P.to_projective_niels(); $size];
for j in $conv_range {
points[j + 1] = (P + &points[j]).to_extended().to_projective_niels();
impl<T: Copy + Default> Default for $name<T> {
fn default() -> $name<T> {
$name([T::default(); $size])
}
}
$name(points)
}
}
impl<'a> From<&'a EdwardsPoint> for $name<AffineNielsPoint> {
fn from(P: &'a EdwardsPoint) -> Self {
let mut points = [P.to_affine_niels(); $size];
// XXX batch inversion would be good if perf mattered here
for j in $conv_range {
points[j + 1] = (P + &points[j]).to_extended().to_affine_niels()
impl<T: Debug> Debug for $name<T> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{:?}(", stringify!($name))?;
for x in self.0.iter() {
write!(f, "{:?}", x)?;
}
write!(f, ")")
}
}
$name(points)
}
}
impl<T> Zeroize for $name<T>
where
T: Copy + Default + Zeroize
{
fn zeroize(&mut self) {
for x in self.0.iter_mut() {
x.zeroize();
impl<'a> From<&'a EdwardsPoint> for $name<ProjectiveNielsPoint> {
fn from(P: &'a EdwardsPoint) -> Self {
let mut points = [P.to_projective_niels(); $size];
for j in $conv_range {
points[j + 1] = (P + &points[j]).to_extended().to_projective_niels();
}
$name(points)
}
}
}
}
}} // End macro_rules! impl_lookup_table
impl<'a> From<&'a EdwardsPoint> for $name<AffineNielsPoint> {
fn from(P: &'a EdwardsPoint) -> Self {
let mut points = [P.to_affine_niels(); $size];
// XXX batch inversion would be good if perf mattered here
for j in $conv_range {
points[j + 1] = (P + &points[j]).to_extended().to_affine_niels()
}
$name(points)
}
}
impl<T> Zeroize for $name<T>
where
T: Copy + Default + Zeroize,
{
fn zeroize(&mut self) {
for x in self.0.iter_mut() {
x.zeroize();
}
}
}
};
} // End macro_rules! impl_lookup_table
// The first one has to be named "LookupTable" because it's used as a constructor for consts.
impl_lookup_table! {Name = LookupTable, Size = 8, SizeNeg = -8, SizeRange = 1 .. 9, ConversionRange = 0 .. 7} // radix-16