use crate::checksum::message_digest::{HashType, MessageDigest};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PieceValidationResult {
Verified {
piece_index: usize,
},
Failed {
piece_index: usize,
},
}
#[derive(Debug)]
pub enum ValidatorKind {
None,
PieceHash(PieceHashValidator),
}
impl ValidatorKind {
pub fn init(&mut self) {
match self {
ValidatorKind::None => {
tracing::trace!("ValidatorKind::init called on None variant — no-op");
}
ValidatorKind::PieceHash(v) => v.init(),
}
}
pub fn validate_chunk(&mut self) {
match self {
ValidatorKind::None => {
tracing::trace!("ValidatorKind::validate_chunk called on None variant — no-op");
}
ValidatorKind::PieceHash(v) => v.validate_chunk(),
}
}
pub fn is_finished(&self) -> bool {
match self {
ValidatorKind::None => true,
ValidatorKind::PieceHash(v) => v.is_finished(),
}
}
pub fn current_offset(&self) -> u64 {
match self {
ValidatorKind::None => 0,
ValidatorKind::PieceHash(v) => v.current_offset(),
}
}
pub fn total_length(&self) -> u64 {
match self {
ValidatorKind::None => 0,
ValidatorKind::PieceHash(v) => v.total_length(),
}
}
pub fn apply_validation_results(
&self,
ps: &mut dyn crate::segment::piece_storage::PieceStorage,
) {
match self {
ValidatorKind::None => {}
ValidatorKind::PieceHash(v) => v.apply_validation_results(ps),
}
}
}
pub struct PieceHashValidator {
download_context: std::sync::Arc<crate::download::DownloadContext>,
piece_storage: std::sync::Arc<dyn crate::segment::piece_storage::PieceStorage>,
current_piece_index: usize,
total_pieces: usize,
finished: bool,
current_offset: u64,
total_length: u64,
piece_length: u64,
pieces_ok: usize,
pieces_failed: usize,
validation_results: Vec<PieceValidationResult>,
}
impl std::fmt::Debug for PieceHashValidator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PieceHashValidator")
.field("current_piece_index", &self.current_piece_index)
.field("total_pieces", &self.total_pieces)
.field("finished", &self.finished)
.field("current_offset", &self.current_offset)
.field("total_length", &self.total_length)
.field("piece_length", &self.piece_length)
.field("pieces_ok", &self.pieces_ok)
.field("pieces_failed", &self.pieces_failed)
.field("validation_results_len", &self.validation_results.len())
.finish()
}
}
impl PieceHashValidator {
pub fn new(
download_context: std::sync::Arc<crate::download::DownloadContext>,
piece_storage: std::sync::Arc<dyn crate::segment::piece_storage::PieceStorage>,
total_pieces: usize,
total_length: u64,
piece_length: u64,
) -> Self {
Self {
download_context,
piece_storage,
current_piece_index: 0,
total_pieces,
finished: total_pieces == 0,
current_offset: 0,
total_length,
piece_length,
pieces_ok: 0,
pieces_failed: 0,
validation_results: Vec::new(),
}
}
pub fn init(&mut self) {
tracing::trace!(
total_pieces = self.total_pieces,
"PieceHashValidator initializing"
);
self.current_piece_index = 0;
self.current_offset = 0;
self.finished = self.total_pieces == 0;
self.pieces_ok = 0;
self.pieces_failed = 0;
self.validation_results.clear();
}
pub fn validate_chunk(&mut self) {
if self.finished {
tracing::trace!("PieceHashValidator::validate_chunk called after completion — no-op");
return;
}
let piece_index = self.current_piece_index;
let piece_len = if piece_index + 1 == self.total_pieces {
self.total_length.saturating_sub(self.current_offset)
} else {
self.piece_length
};
let expected_hash = self.download_context.get_piece_hash(piece_index);
let has_expected = !expected_hash.is_empty();
match self.piece_storage.read_data(piece_index) {
Ok(data) if data.len() as u64 == piece_len => {
let Some(computed_hash) = self.compute_hash(&data) else {
tracing::error!(
piece_index,
hash_type = %self.download_context.get_piece_hash_type(),
"Unsupported piece hash algorithm — cannot verify piece"
);
self.validation_results
.push(PieceValidationResult::Failed { piece_index });
self.pieces_failed += 1;
self.advance();
return;
};
if has_expected {
if computed_hash.eq_ignore_ascii_case(expected_hash) {
tracing::trace!(piece_index, "Piece hash verified OK");
self.validation_results
.push(PieceValidationResult::Verified { piece_index });
self.pieces_ok += 1;
} else {
tracing::warn!(
piece_index,
expected_hash_len = expected_hash.len(),
computed_hash_len = computed_hash.len(),
"Piece hash mismatch — marking for re-download"
);
self.validation_results
.push(PieceValidationResult::Failed { piece_index });
self.pieces_failed += 1;
}
} else {
tracing::trace!(
piece_index,
"No expected hash for piece — skipping verification"
);
}
}
Ok(data) => {
tracing::warn!(
piece_index,
expected_len = piece_len,
actual_len = data.len(),
"Piece data length mismatch during integrity check"
);
self.validation_results
.push(PieceValidationResult::Failed { piece_index });
self.pieces_failed += 1;
}
Err(e) => {
tracing::warn!(
piece_index,
error = %e,
"Failed to read piece data during integrity check"
);
self.validation_results
.push(PieceValidationResult::Failed { piece_index });
self.pieces_failed += 1;
}
}
self.advance();
}
fn advance(&mut self) {
self.current_piece_index += 1;
self.current_offset = self.current_piece_index as u64 * self.piece_length;
if self.current_offset > self.total_length {
self.current_offset = self.total_length;
}
if self.current_piece_index >= self.total_pieces {
self.finished = true;
tracing::info!(
total_pieces = self.total_pieces,
pieces_ok = self.pieces_ok,
pieces_failed = self.pieces_failed,
"PieceHashValidator completed all piece validation"
);
}
}
pub fn apply_validation_results(
&self,
ps: &mut dyn crate::segment::piece_storage::PieceStorage,
) {
for result in &self.validation_results {
match result {
PieceValidationResult::Verified { piece_index } => {
ps.mark_piece_verified(*piece_index);
}
PieceValidationResult::Failed { piece_index } => {
ps.mark_piece_failed(*piece_index);
}
}
}
}
pub(super) fn resolve_hash_type(&self) -> Option<HashType> {
let name = self.download_context.get_piece_hash_type();
if name.is_empty() {
return Some(HashType::Sha1);
}
HashType::from_str(name)
}
pub(super) fn compute_hash(&self, data: &[u8]) -> Option<String> {
Some(MessageDigest::hash_hex(self.resolve_hash_type()?, data))
}
pub fn is_finished(&self) -> bool {
self.finished
}
pub fn current_offset(&self) -> u64 {
self.current_offset
}
pub fn total_length(&self) -> u64 {
self.total_length
}
pub fn current_piece_index(&self) -> usize {
self.current_piece_index
}
pub fn total_pieces(&self) -> usize {
self.total_pieces
}
pub fn pieces_ok(&self) -> usize {
self.pieces_ok
}
pub fn pieces_failed(&self) -> usize {
self.pieces_failed
}
pub fn validation_results(&self) -> &[PieceValidationResult] {
&self.validation_results
}
pub fn download_context(&self) -> &std::sync::Arc<crate::download::DownloadContext> {
&self.download_context
}
pub fn piece_storage(
&self,
) -> &std::sync::Arc<dyn crate::segment::piece_storage::PieceStorage> {
&self.piece_storage
}
}