serai/crypto/multiexp/src/batch.rs

94 lines
2.4 KiB
Rust
Raw Normal View History

2022-06-07 04:02:10 +00:00
use rand_core::{RngCore, CryptoRng};
use ff::{Field, PrimeFieldBits};
use group::Group;
2022-06-07 04:02:10 +00:00
use crate::{multiexp, multiexp_vartime};
#[cfg(feature = "batch")]
pub struct BatchVerifier<Id: Copy, G: Group>(Vec<(Id, Vec<(G::Scalar, G)>)>);
2022-06-07 04:02:10 +00:00
#[cfg(feature = "batch")]
2022-07-15 05:26:07 +00:00
impl<Id: Copy, G: Group> BatchVerifier<Id, G>
where
<G as Group>::Scalar: PrimeFieldBits,
{
pub fn new(capacity: usize) -> BatchVerifier<Id, G> {
BatchVerifier(Vec::with_capacity(capacity))
2022-06-07 04:02:10 +00:00
}
2022-07-15 05:26:07 +00:00
pub fn queue<R: RngCore + CryptoRng, I: IntoIterator<Item = (G::Scalar, G)>>(
&mut self,
rng: &mut R,
id: Id,
pairs: I,
) {
2022-06-07 04:02:10 +00:00
// Define a unique scalar factor for this set of variables so individual items can't overlap
let u = if self.0.len() == 0 {
G::Scalar::one()
} else {
let mut weight;
// Ensure it's non-zero, as a zero scalar would cause this item to pass no matter what
while {
weight = G::Scalar::random(&mut *rng);
weight.is_zero().into()
} {}
weight
2022-06-07 04:02:10 +00:00
};
self.0.push((id, pairs.into_iter().map(|(scalar, point)| (scalar * u, point)).collect()));
}
#[must_use]
2022-06-07 04:02:10 +00:00
pub fn verify(&self) -> bool {
2022-07-15 05:26:07 +00:00
multiexp(&self.0.iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>())
.is_identity()
.into()
2022-06-07 04:02:10 +00:00
}
#[must_use]
2022-06-07 04:02:10 +00:00
pub fn verify_vartime(&self) -> bool {
2022-07-15 05:26:07 +00:00
multiexp_vartime(&self.0.iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>())
.is_identity()
.into()
2022-06-07 04:02:10 +00:00
}
// A constant time variant may be beneficial for robust protocols
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(
2022-07-15 05:26:07 +00:00
&slice[.. split].iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>(),
)
.is_identity()
.into()
{
2022-06-07 04:02:10 +00:00
slice = &slice[split ..];
} else {
slice = &slice[.. split];
}
}
2022-07-15 05:26:07 +00:00
slice
.get(0)
.filter(|(_, value)| !bool::from(multiexp_vartime(value).is_identity()))
.map(|(id, _)| *id)
2022-06-07 04:02:10 +00:00
}
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())
}
}
}