serai/crypto/multiexp/src/batch.rs

147 lines
4.9 KiB
Rust
Raw Normal View History

2022-06-07 04:02:10 +00:00
use rand_core::{RngCore, CryptoRng};
use zeroize::{Zeroize, Zeroizing};
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
use ff::{Field, PrimeFieldBits};
use group::Group;
2022-06-07 04:02:10 +00:00
use crate::{multiexp, multiexp_vartime};
// Flatten the contained statements to a single Vec.
// Wrapped in Zeroizing in case any of the included statements contain private values.
#[allow(clippy::type_complexity)]
fn flat<Id: Copy + Zeroize, G: Group + Zeroize>(
slice: &[(Id, Vec<(G::Scalar, G)>)],
) -> Zeroizing<Vec<(G::Scalar, G)>>
where
<G as Group>::Scalar: PrimeFieldBits + Zeroize,
{
Zeroizing::new(slice.iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>())
}
/// A batch verifier intended to verify a series of statements are each equivalent to zero.
#[allow(clippy::type_complexity)]
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
#[derive(Clone, Zeroize)]
pub struct BatchVerifier<Id: Copy + Zeroize, G: Group + Zeroize>(Zeroizing<Vec<(Id, Vec<(G::Scalar, G)>)>>)
where
<G as Group>::Scalar: PrimeFieldBits + Zeroize;
2022-06-07 04:02:10 +00:00
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
impl<Id: Copy + Zeroize, G: Group + Zeroize> BatchVerifier<Id, G>
2022-07-15 05:26:07 +00:00
where
Utilize zeroize (#76) * Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
2022-08-03 08:25:18 +00:00
<G as Group>::Scalar: PrimeFieldBits + Zeroize,
2022-07-15 05:26:07 +00:00
{
/// Create a new batch verifier, expected to verify the following amount of statements.
/// This is a size hint and is not required to be accurate.
pub fn new(capacity: usize) -> BatchVerifier<Id, G> {
BatchVerifier(Zeroizing::new(Vec::with_capacity(capacity)))
2022-06-07 04:02:10 +00:00
}
/// Queue a statement for batch verification.
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.is_empty() {
2022-06-07 04:02:10 +00:00
G::Scalar::one()
} else {
let mut weight;
while {
// Generate a random scalar
weight = G::Scalar::random(&mut *rng);
// Clears half the bits, maintaining security, to minimize scalar additions
// Is not practically faster for whatever reason
/*
// Generate a random scalar
let mut repr = G::Scalar::random(&mut *rng).to_repr();
// Calculate the amount of bytes to clear. We want to clear less than half
let repr_len = repr.as_ref().len();
let unused_bits = (repr_len * 8) - usize::try_from(G::Scalar::CAPACITY).unwrap();
// Don't clear any partial bytes
let to_clear = (repr_len / 2) - ((unused_bits + 7) / 8);
// Clear a safe amount of bytes
for b in &mut repr.as_mut()[.. to_clear] {
*b = 0;
}
// Ensure these bits are used as the low bits so low scalars multiplied by this don't
// become large scalars
weight = G::Scalar::from_repr(repr).unwrap();
// Tests if any bit we supposedly just cleared is set, and if so, reverses it
// Not a security issue if this fails, just a minor performance hit at ~2^-120 odds
if weight.to_le_bits().iter().take(to_clear * 8).any(|bit| *bit) {
repr.as_mut().reverse();
weight = G::Scalar::from_repr(repr).unwrap();
}
*/
// Ensure it's non-zero, as a zero scalar would cause this item to pass no matter what
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()));
2022-06-07 04:02:10 +00:00
}
/// Perform batch verification, returning a boolean of if the statements equaled zero.
#[must_use]
pub fn verify(&self) -> bool {
multiexp(&flat(&self.0)).is_identity().into()
2022-06-07 04:02:10 +00:00
}
/// Perform batch verification in variable time.
#[must_use]
2022-06-07 04:02:10 +00:00
pub fn verify_vartime(&self) -> bool {
multiexp_vartime(&flat(&self.0)).is_identity().into()
2022-06-07 04:02:10 +00:00
}
/// Perform a binary search to identify which statement does not equal 0, returning None if all
/// statements do. This function will only return the ID of one invalid statement, even if
/// multiple are invalid.
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();
2022-06-07 04:02:10 +00:00
while slice.len() > 1 {
let split = slice.len() / 2;
if multiexp_vartime(&flat(&slice[.. split])).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
}
/// Perform constant time batch verification, and if verification fails, identify one faulty
/// statement in variable time.
pub fn verify_with_vartime_blame(&self) -> Result<(), Id> {
if self.verify() {
Ok(())
} else {
Err(self.blame_vartime().unwrap())
}
2022-06-07 04:02:10 +00:00
}
/// Perform variable time batch verification, and if verification fails, identify one faulty
/// statement in variable time.
2022-06-07 04:02:10 +00:00
pub fn verify_vartime_with_vartime_blame(&self) -> Result<(), Id> {
if self.verify_vartime() {
Ok(())
} else {
Err(self.blame_vartime().unwrap())
}
}
}