2023-11-18 14:00:33 +00:00
|
|
|
use std::cell::UnsafeCell;
|
|
|
|
|
|
|
|
use multiexp::BatchVerifier as InternalBatchVerifier;
|
|
|
|
use rayon::prelude::*;
|
|
|
|
use thread_local::ThreadLocal;
|
|
|
|
|
|
|
|
use crate::ConsensusError;
|
|
|
|
|
|
|
|
/// A multi threaded batch verifier.
|
|
|
|
pub struct MultiThreadedBatchVerifier {
|
2023-12-27 23:50:18 +00:00
|
|
|
internal: ThreadLocal<UnsafeCell<InternalBatchVerifier<(), dalek_ff_group::EdwardsPoint>>>,
|
2023-11-18 14:00:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl MultiThreadedBatchVerifier {
|
|
|
|
/// Create a new multithreaded batch verifier,
|
|
|
|
pub fn new(numb_threads: usize) -> MultiThreadedBatchVerifier {
|
|
|
|
MultiThreadedBatchVerifier {
|
|
|
|
internal: ThreadLocal::with_capacity(numb_threads),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-27 23:50:18 +00:00
|
|
|
pub fn queue_statement<R>(
|
2023-11-18 14:00:33 +00:00
|
|
|
&self,
|
|
|
|
stmt: impl FnOnce(
|
2023-12-27 23:50:18 +00:00
|
|
|
&mut InternalBatchVerifier<(), dalek_ff_group::EdwardsPoint>,
|
|
|
|
) -> Result<R, ConsensusError>,
|
|
|
|
) -> Result<R, ConsensusError> {
|
2023-11-18 14:00:33 +00:00
|
|
|
let verifier_cell = self
|
|
|
|
.internal
|
|
|
|
.get_or(|| UnsafeCell::new(InternalBatchVerifier::new(0)));
|
|
|
|
// SAFETY: This is safe for 2 reasons:
|
|
|
|
// 1. each thread gets a different batch verifier.
|
|
|
|
// 2. only this function `queue_statement` will get the inner batch verifier, it's private.
|
|
|
|
//
|
|
|
|
// TODO: it's probably ok to just use RefCell
|
|
|
|
stmt(unsafe { &mut *verifier_cell.get() })
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn verify(self) -> bool {
|
|
|
|
self.internal
|
|
|
|
.into_iter()
|
|
|
|
.map(UnsafeCell::into_inner)
|
|
|
|
.par_bridge()
|
2024-02-15 16:03:04 +00:00
|
|
|
.find_any(|batch_verifier| !batch_verifier.verify_vartime())
|
2023-11-18 14:00:33 +00:00
|
|
|
.is_none()
|
|
|
|
}
|
|
|
|
}
|