use alloc::vec::Vec;
use core::{borrow::Borrow, fmt::Debug};
use jubjub::{ExtendedNielsPoint, ExtendedPoint};
#[cfg(test)]
pub(crate) mod tests;
pub trait VartimeMultiscalarMul {
type Scalar;
type Point;
fn optional_multiscalar_mul<I, J>(scalars: I, points: J) -> Option<Self::Point>
where
I: IntoIterator,
I::Item: Borrow<Self::Scalar>,
J: IntoIterator<Item = Option<Self::Point>>;
fn vartime_multiscalar_mul<I, J>(scalars: I, points: J) -> Self::Point
where
I: IntoIterator,
I::Item: Borrow<Self::Scalar>,
J: IntoIterator,
J::Item: Borrow<Self::Point>,
Self::Point: Clone,
{
Self::optional_multiscalar_mul(
scalars,
points.into_iter().map(|p| Some(p.borrow().clone())),
)
.unwrap()
}
}
pub trait NonAdjacentForm {
fn inner_to_bytes(&self) -> [u8; 32];
fn naf_length() -> usize {
257
}
fn non_adjacent_form(&self, w: usize) -> Vec<i8> {
debug_assert!(w >= 2);
debug_assert!(w <= 8);
use byteorder::{ByteOrder, LittleEndian};
let naf_length = Self::naf_length();
let mut naf = vec![0; naf_length];
let mut x_u64 = [0u64; 5];
LittleEndian::read_u64_into(&self.inner_to_bytes(), &mut x_u64[0..4]);
let width = 1 << w;
let window_mask = width - 1;
let mut pos = 0;
let mut carry = 0;
while pos < naf_length {
let u64_idx = pos / 64;
let bit_idx = pos % 64;
let bit_buf: u64 = if bit_idx < 64 - w {
x_u64[u64_idx] >> bit_idx
} else {
(x_u64[u64_idx] >> bit_idx) | (x_u64[1 + u64_idx] << (64 - bit_idx))
};
let window = carry + (bit_buf & window_mask);
if window & 1 == 0 {
pos += 1;
continue;
}
if window < width / 2 {
carry = 0;
naf[pos] = window as i8;
} else {
carry = 1;
naf[pos] = (window as i8).wrapping_sub(width as i8);
}
pos += w;
}
naf
}
}
impl NonAdjacentForm for jubjub::Scalar {
fn inner_to_bytes(&self) -> [u8; 32] {
self.to_bytes()
}
fn naf_length() -> usize {
253
}
}
#[derive(Copy, Clone)]
pub(crate) struct LookupTable5<T>(pub(crate) [T; 8]);
impl<T: Copy> LookupTable5<T> {
pub fn select(&self, x: usize) -> T {
debug_assert_eq!(x & 1, 1);
debug_assert!(x < 16);
self.0[x / 2]
}
}
impl<T: Debug> Debug for LookupTable5<T> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "LookupTable5({:?})", self.0)
}
}
impl<'a> From<&'a ExtendedPoint> for LookupTable5<ExtendedNielsPoint> {
#[allow(non_snake_case)]
fn from(A: &'a ExtendedPoint) -> Self {
let mut Ai = [A.to_niels(); 8];
let A2 = A.double();
for i in 0..7 {
Ai[i + 1] = (A2 + Ai[i]).to_niels();
}
LookupTable5(Ai)
}
}
impl VartimeMultiscalarMul for ExtendedPoint {
type Scalar = jubjub::Scalar;
type Point = ExtendedPoint;
#[allow(non_snake_case)]
fn optional_multiscalar_mul<I, J>(scalars: I, points: J) -> Option<ExtendedPoint>
where
I: IntoIterator,
I::Item: Borrow<Self::Scalar>,
J: IntoIterator<Item = Option<ExtendedPoint>>,
{
let nafs: Vec<_> = scalars
.into_iter()
.map(|c| c.borrow().non_adjacent_form(5))
.collect();
let lookup_tables = points
.into_iter()
.map(|P_opt| P_opt.map(|P| LookupTable5::<ExtendedNielsPoint>::from(&P)))
.collect::<Option<Vec<_>>>()?;
let mut r = ExtendedPoint::identity();
let naf_size = Self::Scalar::naf_length();
for i in (0..naf_size).rev() {
let mut t = r.double();
for (naf, lookup_table) in nafs.iter().zip(lookup_tables.iter()) {
#[allow(clippy::comparison_chain)]
if naf[i] > 0 {
t += lookup_table.select(naf[i] as usize);
} else if naf[i] < 0 {
t -= lookup_table.select(-naf[i] as usize);
}
}
r = t;
}
Some(r)
}
}