use std::io::{Read, Write};
use std::net::TcpStream;
use crate::error::{Error, Result};
use crate::peer::extension::enable_extensions;
use crate::torrent::InfoHash;
pub type PeerId = [u8; 20];
#[derive(Debug, Clone)]
pub struct Handshake {
pub info_hash: InfoHash,
pub peer_id: PeerId,
pub extensions: bool,
pub fast: bool,
pub v2: bool,
}
impl Handshake {
pub fn new(info_hash: InfoHash, peer_id: PeerId) -> Self {
Self {
info_hash,
peer_id,
extensions: false,
fast: false,
v2: false,
}
}
pub fn with_extensions(mut self) -> Self {
self.extensions = true;
self
}
pub fn with_fast(mut self) -> Self {
self.fast = true;
self
}
pub fn with_v2(mut self) -> Self {
self.v2 = true;
self
}
pub fn with_swarm_features(mut self) -> Self {
self.extensions = true;
self.fast = true;
self.v2 = true;
self
}
pub fn write_to(&self, stream: &mut TcpStream) -> Result<()> {
let mut buf = Vec::with_capacity(68);
buf.push(19);
buf.extend(b"BitTorrent protocol");
let mut reserved = [0u8; 8];
if self.extensions {
enable_extensions(&mut reserved);
}
if self.fast {
crate::peer::fast::enable_fast(&mut reserved);
}
if self.v2 {
crate::peer::hash_messages::enable_v2(&mut reserved);
}
buf.extend(reserved);
buf.extend(self.info_hash.as_bytes());
buf.extend(self.peer_id);
stream.write_all(&buf).map_err(Error::from)
}
pub fn read_from(stream: &mut TcpStream) -> Result<(Self, [u8; 8])> {
let mut len = [0u8; 1];
stream.read_exact(&mut len).map_err(Error::from)?;
if len[0] != 19 {
return Err(Error::Peer("invalid handshake length".into()));
}
let mut protocol = [0u8; 19];
stream.read_exact(&mut protocol).map_err(Error::from)?;
if &protocol != b"BitTorrent protocol" {
return Err(Error::Peer("invalid protocol string".into()));
}
let mut reserved = [0u8; 8];
stream.read_exact(&mut reserved).map_err(Error::from)?;
let mut info_hash = [0u8; 20];
stream.read_exact(&mut info_hash).map_err(Error::from)?;
let mut peer_id = [0u8; 20];
stream.read_exact(&mut peer_id).map_err(Error::from)?;
Ok((
Self {
info_hash: InfoHash::from_bytes(info_hash),
peer_id,
extensions: crate::peer::extension::supports_extensions(&reserved),
fast: crate::peer::fast::supports_fast(&reserved),
v2: crate::peer::hash_messages::supports_v2(&reserved),
},
reserved,
))
}
}