use std_shims::vec::Vec;
use rand_core::{RngCore, CryptoRng};
use zeroize::{Zeroize, Zeroizing};
use ff::{Field, PrimeFieldBits};
use group::Group;
use crate::{multiexp, multiexp_vartime};
#[allow(clippy::type_complexity)]
fn flat<Id: Copy + Zeroize, G: Zeroize + Group>(
slice: &[(Id, Vec<(G::Scalar, G)>)],
) -> Zeroizing<Vec<(G::Scalar, G)>>
where
G::Scalar: Zeroize + PrimeFieldBits,
{
Zeroizing::new(slice.iter().flat_map(|pairs| pairs.1.iter()).copied().collect::<Vec<_>>())
}
#[allow(clippy::type_complexity)]
#[derive(Clone, Zeroize)]
pub struct BatchVerifier<Id: Copy + Zeroize, G: Zeroize + Group>(
Zeroizing<Vec<(Id, Vec<(G::Scalar, G)>)>>,
)
where
G::Scalar: Zeroize + PrimeFieldBits;
impl<Id: Copy + Zeroize, G: Zeroize + Group> BatchVerifier<Id, G>
where
G::Scalar: Zeroize + PrimeFieldBits,
{
pub fn new(capacity: usize) -> BatchVerifier<Id, G> {
BatchVerifier(Zeroizing::new(Vec::with_capacity(capacity)))
}
pub fn queue<R: RngCore + CryptoRng, I: IntoIterator<Item = (G::Scalar, G)>>(
&mut self,
rng: &mut R,
id: Id,
pairs: I,
) {
let u = if self.0.is_empty() {
G::Scalar::ONE
} else {
let mut weight;
while {
weight = G::Scalar::random(&mut *rng);
weight.is_zero().into()
} {}
weight
};
self.0.push((id, pairs.into_iter().map(|(scalar, point)| (scalar * u, point)).collect()));
}
#[must_use]
pub fn verify(&self) -> bool {
multiexp(&flat(&self.0)).is_identity().into()
}
#[must_use]
pub fn verify_vartime(&self) -> bool {
multiexp_vartime(&flat(&self.0)).is_identity().into()
}
pub fn blame_vartime(&self) -> Option<Id> {
let mut slice = self.0.as_slice();
while slice.len() > 1 {
let split = slice.len() / 2;
if multiexp_vartime(&flat(&slice[.. split])).is_identity().into() {
slice = &slice[split ..];
} else {
slice = &slice[.. split];
}
}
slice
.first()
.filter(|(_, value)| !bool::from(multiexp_vartime(value).is_identity()))
.map(|(id, _)| *id)
}
pub fn verify_with_vartime_blame(&self) -> Result<(), Id> {
if self.verify() {
Ok(())
} else {
Err(self.blame_vartime().unwrap())
}
}
pub fn verify_vartime_with_vartime_blame(&self) -> Result<(), Id> {
if self.verify_vartime() {
Ok(())
} else {
Err(self.blame_vartime().unwrap())
}
}
}