use std::sync::{Arc, Condvar, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::sched::io_pool::global_io_pool;
pub trait VerifyHasher: Send + 'static {
fn update(&mut self, chunk: &[u8]);
fn finalize(self: Box<Self>) -> [u8; 32];
}
#[cfg(feature = "verify-chain")]
mod blake3_impl {
use super::VerifyHasher;
pub struct Blake3Hasher(pub blake3::Hasher);
impl Blake3Hasher {
pub fn new() -> Self {
Self(blake3::Hasher::new())
}
}
impl Default for Blake3Hasher {
fn default() -> Self {
Self::new()
}
}
impl VerifyHasher for Blake3Hasher {
fn update(&mut self, chunk: &[u8]) {
self.0.update(chunk);
}
fn finalize(self: Box<Self>) -> [u8; 32] {
*self.0.finalize().as_bytes()
}
}
}
#[cfg(feature = "verify-chain")]
pub use blake3_impl::Blake3Hasher;
pub struct FxFallbackHasher {
state: u64,
}
impl FxFallbackHasher {
pub fn new() -> Self {
Self { state: 0xCBF2_9CE4_8422_2325 }
}
}
impl Default for FxFallbackHasher {
fn default() -> Self {
Self::new()
}
}
impl VerifyHasher for FxFallbackHasher {
fn update(&mut self, chunk: &[u8]) {
const PRIME: u64 = 0x100_0000_01B3;
for &b in chunk {
self.state = self.state.wrapping_mul(PRIME) ^ (b as u64);
}
}
fn finalize(self: Box<Self>) -> [u8; 32] {
let mut out = [0u8; 32];
let mut acc = self.state;
for i in 0..4 {
let mix = acc.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
out[i * 8..i * 8 + 8].copy_from_slice(&mix.to_le_bytes());
acc = mix.rotate_left(17);
}
out
}
}
#[cfg(feature = "verify-chain")]
pub fn default_hasher() -> Box<dyn VerifyHasher> {
Box::new(Blake3Hasher::new())
}
#[cfg(not(feature = "verify-chain"))]
pub fn default_hasher() -> Box<dyn VerifyHasher> {
Box::new(FxFallbackHasher::new())
}
struct ChainShared {
hasher: Mutex<Option<Box<dyn VerifyHasher>>>,
pending: AtomicUsize,
notify: (Mutex<()>, Condvar),
}
#[derive(Clone)]
pub struct VerifyChain {
inner: Arc<ChainShared>,
}
impl VerifyChain {
pub fn new() -> Self {
Self::with_hasher(default_hasher())
}
pub fn with_hasher(hasher: Box<dyn VerifyHasher>) -> Self {
Self {
inner: Arc::new(ChainShared {
hasher: Mutex::new(Some(hasher)),
pending: AtomicUsize::new(0),
notify: (Mutex::new(()), Condvar::new()),
}),
}
}
pub fn submit_chunk(&self, chunk: Vec<u8>) {
self.inner.pending.fetch_add(1, Ordering::AcqRel);
let inner = Arc::clone(&self.inner);
let task = move || {
if let Ok(mut guard) = inner.hasher.lock()
&& let Some(h) = guard.as_mut()
{
h.update(&chunk);
}
let prev = inner.pending.fetch_sub(1, Ordering::AcqRel);
if prev == 1 {
let _g = inner.notify.0.lock();
inner.notify.1.notify_all();
}
};
match global_io_pool() {
Some(pool) => pool.submit(task),
None => task(),
}
}
pub fn finalize(self) -> [u8; 32] {
loop {
if self.inner.pending.load(Ordering::Acquire) == 0 {
break;
}
let mut g = self.inner.notify.0.lock().unwrap();
if self.inner.pending.load(Ordering::Acquire) == 0 {
break;
}
g = self.inner.notify.1.wait(g).unwrap();
drop(g);
}
let mut guard = self.inner.hasher.lock().unwrap();
match guard.take() {
Some(hasher) => hasher.finalize(),
None => [0u8; 32],
}
}
pub fn pending_count(&self) -> usize {
self.inner.pending.load(Ordering::Acquire)
}
}
impl Default for VerifyChain {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for VerifyChain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VerifyChain")
.field("pending", &self.pending_count())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fx_fallback_finalize_with_no_chunks_returns_seeded_root() {
let h: Box<FxFallbackHasher> = Box::default();
let root = h.finalize();
assert!(root.iter().any(|&b| b != 0), "expected non-zero root for seeded empty input");
}
#[test]
fn chain_inline_single_chunk_produces_stable_root() {
let chain = VerifyChain::new();
chain.submit_chunk(b"hello world".to_vec());
let root1 = chain.finalize();
let chain2 = VerifyChain::new();
chain2.submit_chunk(b"hello world".to_vec());
let root2 = chain2.finalize();
assert_eq!(root1, root2, "same input should produce same root");
}
#[test]
fn chain_inline_different_chunks_produce_different_roots() {
let c1 = VerifyChain::new();
c1.submit_chunk(b"input A".to_vec());
let r1 = c1.finalize();
let c2 = VerifyChain::new();
c2.submit_chunk(b"input B".to_vec());
let r2 = c2.finalize();
assert_ne!(r1, r2, "different inputs should produce different roots");
}
#[test]
fn chain_inline_many_chunks_finalize_blocks_until_done() {
const N: usize = 32;
let chain = VerifyChain::new();
for i in 0..N {
let chunk = format!("stripe-{:08}", i).into_bytes();
chain.submit_chunk(chunk);
}
assert_eq!(chain.pending_count(), 0);
let root = chain.finalize();
assert!(root.iter().any(|&b| b != 0));
}
#[test]
fn chain_finalize_after_finalize_returns_zero_root() {
let chain = VerifyChain::new();
chain.submit_chunk(vec![1, 2, 3]);
let first = chain.clone().finalize();
let second = chain.finalize();
assert!(first.iter().any(|&b| b != 0));
assert_eq!(second, [0u8; 32]);
}
}