use std::time::SystemTime;
use tracing::debug;
use crate::error::{Aria2Error, Result};
use super::types::{BtProgress, DownloadStats, InFlightPiece};
const EXT_BT: u32 = 0x0000_0001;
const INFO_HASH_LENGTH: u32 = 20;
pub fn serialize_binary(progress: &BtProgress) -> Result<Vec<u8>> {
let mut buf = Vec::new();
buf.extend_from_slice(&[0x00, 0x01]);
let extension: u32 = if progress.is_torrent { EXT_BT } else { 0 };
buf.extend_from_slice(&extension.to_be_bytes());
let info_hash_len: u32 = if progress.is_torrent {
INFO_HASH_LENGTH
} else {
0
};
buf.extend_from_slice(&info_hash_len.to_be_bytes());
if progress.is_torrent {
buf.extend_from_slice(&progress.info_hash);
}
buf.extend_from_slice(&progress.piece_length.to_be_bytes());
buf.extend_from_slice(&progress.total_size.to_be_bytes());
buf.extend_from_slice(&progress.upload_length.to_be_bytes());
buf.extend_from_slice(&(progress.bitfield.len() as u32).to_be_bytes());
buf.extend_from_slice(&progress.bitfield);
buf.extend_from_slice(&(progress.in_flight_pieces.len() as u32).to_be_bytes());
for piece in &progress.in_flight_pieces {
buf.extend_from_slice(&piece.index.to_be_bytes());
buf.extend_from_slice(&piece.length.to_be_bytes());
buf.extend_from_slice(&(piece.bitfield.len() as u32).to_be_bytes());
buf.extend_from_slice(&piece.bitfield);
}
Ok(buf)
}
pub fn deserialize_binary(data: &[u8], expected_info_hash: &[u8; 20]) -> Result<BtProgress> {
let min_size = 2 + 4 + 4 + 4 + 8 + 8 + 4 + 4;
if data.len() < min_size {
return Err(Aria2Error::InvalidArgument(
"Binary progress file too short".to_string(),
));
}
let mut pos = 0;
let version_hi = data[pos];
let version_lo = data[pos + 1];
pos += 2;
let version = ((version_hi as u32) << 8) | (version_lo as u32);
if version != 1 {
return Err(Aria2Error::InvalidArgument(format!(
"Unsupported binary progress file version: {}",
version
)));
}
let extension = read_u32_be(data, &mut pos)?;
let is_torrent = (extension & EXT_BT) != 0;
let info_hash_len = read_u32_be(data, &mut pos)? as usize;
if info_hash_len > INFO_HASH_LENGTH as usize {
return Err(Aria2Error::InvalidArgument(format!(
"Invalid info hash length: {}",
info_hash_len
)));
}
if is_torrent && info_hash_len != INFO_HASH_LENGTH as usize {
return Err(Aria2Error::InvalidArgument(format!(
"BT download requires info hash length {}, got {}",
INFO_HASH_LENGTH, info_hash_len
)));
}
let mut info_hash = [0u8; 20];
if info_hash_len > 0 {
if pos + info_hash_len > data.len() {
return Err(Aria2Error::InvalidArgument(
"Binary progress file truncated (info hash)".to_string(),
));
}
info_hash[..info_hash_len].copy_from_slice(&data[pos..pos + info_hash_len]);
pos += info_hash_len;
if is_torrent && &info_hash != expected_info_hash {
let expected_hex: String = expected_info_hash
.iter()
.map(|b| format!("{:02x}", b))
.collect();
let actual_hex: String = info_hash.iter().map(|b| format!("{:02x}", b)).collect();
return Err(Aria2Error::InvalidArgument(format!(
"info hash mismatch. expected: {}, actual: {}",
expected_hex, actual_hex
)));
}
debug!("Binary progress file info_hash validated successfully");
}
let piece_length = read_u32_be(data, &mut pos)?;
if piece_length == 0 {
return Err(Aria2Error::InvalidArgument(
"piece length must not be 0".to_string(),
));
}
let total_size = read_u64_be(data, &mut pos)?;
let upload_length = read_u64_be(data, &mut pos)?;
let bf_len = read_u32_be(data, &mut pos)? as usize;
if pos + bf_len > data.len() {
return Err(Aria2Error::InvalidArgument(
"Binary progress file truncated (bitfield)".to_string(),
));
}
let bitfield = data[pos..pos + bf_len].to_vec();
pos += bf_len;
let num_pieces = total_size.div_ceil(piece_length as u64);
let num_in_flight = read_u32_be(data, &mut pos)?;
let mut in_flight_pieces = Vec::with_capacity(num_in_flight as usize);
for _ in 0..num_in_flight {
let index = read_u32_be(data, &mut pos)?;
let length = read_u32_be(data, &mut pos)?;
let inner_bf_len = read_u32_be(data, &mut pos)? as usize;
if pos + inner_bf_len > data.len() {
return Err(Aria2Error::InvalidArgument(
"Binary progress file truncated (in-flight bitfield)".to_string(),
));
}
let piece_bf = data[pos..pos + inner_bf_len].to_vec();
pos += inner_bf_len;
in_flight_pieces.push(InFlightPiece::new(index, length, piece_bf));
}
Ok(BtProgress {
info_hash: if is_torrent {
info_hash
} else {
*expected_info_hash
},
bitfield,
peers: Vec::new(), stats: DownloadStats {
uploaded_bytes: upload_length,
..DownloadStats::default()
},
piece_length,
total_size,
num_pieces: num_pieces as u32,
upload_length,
in_flight_pieces,
is_torrent,
save_time: SystemTime::now(),
version,
})
}
fn read_u32_be(data: &[u8], pos: &mut usize) -> Result<u32> {
if *pos + 4 > data.len() {
return Err(Aria2Error::InvalidArgument(
"Binary progress file truncated (u32)".to_string(),
));
}
let value = u32::from_be_bytes([data[*pos], data[*pos + 1], data[*pos + 2], data[*pos + 3]]);
*pos += 4;
Ok(value)
}
fn read_u64_be(data: &[u8], pos: &mut usize) -> Result<u64> {
if *pos + 8 > data.len() {
return Err(Aria2Error::InvalidArgument(
"Binary progress file truncated (u64)".to_string(),
));
}
let mut bytes = [0u8; 8];
bytes.copy_from_slice(&data[*pos..*pos + 8]);
let value = u64::from_be_bytes(bytes);
*pos += 8;
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_binary_roundtrip() {
let info_hash = [0xAA; 20];
let progress = BtProgress {
info_hash,
bitfield: vec![0xFF, 0x0F],
peers: Vec::new(),
stats: DownloadStats::default(),
piece_length: 262144,
total_size: 524288,
num_pieces: 2,
upload_length: 1024,
in_flight_pieces: vec![InFlightPiece::new(0, 16384, vec![0xFF])],
is_torrent: true,
save_time: SystemTime::now(),
version: 1,
};
let data = serialize_binary(&progress).expect("serialize failed");
let loaded = deserialize_binary(&data, &info_hash).expect("deserialize failed");
assert_eq!(loaded.info_hash, info_hash);
assert_eq!(loaded.bitfield, progress.bitfield);
assert_eq!(loaded.piece_length, progress.piece_length);
assert_eq!(loaded.total_size, progress.total_size);
assert_eq!(loaded.upload_length, progress.upload_length);
assert_eq!(loaded.stats.uploaded_bytes, progress.upload_length);
assert_eq!(loaded.in_flight_pieces.len(), 1);
assert_eq!(loaded.in_flight_pieces[0].index, 0);
assert_eq!(loaded.in_flight_pieces[0].length, 16384);
assert_eq!(loaded.in_flight_pieces[0].bitfield, vec![0xFF]);
}
#[test]
fn test_binary_info_hash_mismatch() {
let info_hash = [0xAA; 20];
let progress = BtProgress {
info_hash,
bitfield: vec![0xFF],
peers: Vec::new(),
stats: DownloadStats::default(),
piece_length: 262144,
total_size: 262144,
num_pieces: 1,
upload_length: 0,
in_flight_pieces: Vec::new(),
is_torrent: true,
save_time: SystemTime::now(),
version: 1,
};
let data = serialize_binary(&progress).expect("serialize failed");
let wrong_hash = [0xBB; 20];
let result = deserialize_binary(&data, &wrong_hash);
assert!(result.is_err(), "info hash mismatch should return error");
}
#[test]
fn test_binary_non_bt_format() {
let info_hash = [0x00; 20];
let progress = BtProgress {
info_hash,
bitfield: vec![0xFF],
peers: Vec::new(),
stats: DownloadStats::default(),
piece_length: 262144,
total_size: 262144,
num_pieces: 1,
upload_length: 0,
in_flight_pieces: Vec::new(),
is_torrent: false,
save_time: SystemTime::now(),
version: 1,
};
let data = serialize_binary(&progress).expect("serialize failed");
let loaded = deserialize_binary(&data, &info_hash).expect("deserialize failed");
assert!(!loaded.is_torrent);
assert_eq!(loaded.piece_length, 262144);
assert_eq!(loaded.total_size, 262144);
}
#[test]
fn test_binary_endianness() {
let info_hash = [0x11; 20];
let progress = BtProgress {
info_hash,
bitfield: vec![0xF0],
peers: Vec::new(),
stats: DownloadStats::default(),
piece_length: 0x01020304, total_size: 0,
num_pieces: 1,
upload_length: 0,
in_flight_pieces: Vec::new(),
is_torrent: true,
save_time: SystemTime::now(),
version: 1,
};
let data = serialize_binary(&progress).expect("serialize failed");
let offset = 2 + 4 + 4 + 20;
assert_eq!(data[offset], 0x01);
assert_eq!(data[offset + 1], 0x02);
assert_eq!(data[offset + 2], 0x03);
assert_eq!(data[offset + 3], 0x04);
}
#[test]
fn test_binary_extension_bit() {
let info_hash = [0x22; 20];
let bt_progress = BtProgress {
info_hash,
bitfield: vec![0xFF],
peers: Vec::new(),
stats: DownloadStats::default(),
piece_length: 1024,
total_size: 1024,
num_pieces: 1,
upload_length: 0,
in_flight_pieces: Vec::new(),
is_torrent: true,
save_time: SystemTime::now(),
version: 1,
};
let data = serialize_binary(&bt_progress).expect("serialize failed");
assert_eq!(data[2], 0x00);
assert_eq!(data[3], 0x00);
assert_eq!(data[4], 0x00);
assert_eq!(data[5], 0x01);
let non_bt_progress = BtProgress {
is_torrent: false,
..bt_progress.clone()
};
let data = serialize_binary(&non_bt_progress).expect("serialize failed");
assert_eq!(data[2..6], [0x00, 0x00, 0x00, 0x00]);
}
}