use crate::engine::bt_peer_connection::BtPeerConn;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HandshakeValidationError {
SelfConnection {
peer_id: [u8; 20],
},
DuplicatePeerId {
peer_id: [u8; 20],
},
}
impl std::fmt::Display for HandshakeValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SelfConnection { peer_id } => write!(
f,
"Drop connection from the same Peer ID: {}",
hex::encode(peer_id)
),
Self::DuplicatePeerId { peer_id } => write!(
f,
"Same Peer ID has been already seen: {}",
hex::encode(peer_id)
),
}
}
}
impl std::error::Error for HandshakeValidationError {}
pub fn validate_received_peer_id(
remote_peer_id: &[u8; 20],
local_peer_id: &[u8; 20],
active_peer_ids: &[[u8; 20]],
) -> std::result::Result<(), HandshakeValidationError> {
if remote_peer_id == local_peer_id {
tracing::warn!(
"Self-connection detected: remote peer ID matches local peer ID ({})",
hex::encode(remote_peer_id)
);
return Err(HandshakeValidationError::SelfConnection {
peer_id: *remote_peer_id,
});
}
for existing_id in active_peer_ids {
if remote_peer_id == existing_id {
tracing::warn!(
"Duplicate peer connection: peer ID {} already active",
hex::encode(remote_peer_id)
);
return Err(HandshakeValidationError::DuplicatePeerId {
peer_id: *remote_peer_id,
});
}
}
Ok(())
}
pub fn filter_duplicate_peer_connections(
connections: &mut Vec<BtPeerConn>,
local_peer_id: &[u8; 20],
) -> usize {
let mut validated_ids: Vec<[u8; 20]> = Vec::new();
let mut indices_to_remove: Vec<usize> = Vec::new();
for (i, conn) in connections.iter().enumerate() {
let Some(remote_peer_id) = conn.peer_id else {
continue;
};
if remote_peer_id == *local_peer_id {
tracing::warn!(
"[BT] Dropping self-connection from {}:{} (peer ID matches local)",
conn.ip_addr,
conn.port
);
indices_to_remove.push(i);
continue;
}
if validated_ids.contains(&remote_peer_id) {
tracing::warn!(
"[BT] Dropping duplicate peer connection from {}:{} (peer ID {} already seen)",
conn.ip_addr,
conn.port,
hex::encode(remote_peer_id)
);
indices_to_remove.push(i);
continue;
}
validated_ids.push(remote_peer_id);
}
let removed_count = indices_to_remove.len();
for idx in indices_to_remove.into_iter().rev() {
connections.remove(idx);
}
if removed_count > 0 {
tracing::info!(
"[BT] Removed {} invalid peer connections (self/duplicate), {} remaining",
removed_count,
connections.len()
);
}
removed_count
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_self_connection_detected() {
let local_peer_id = [0x11; 20];
let remote_peer_id = [0x11; 20];
let result = validate_received_peer_id(&remote_peer_id, &local_peer_id, &[]);
assert_eq!(
result,
Err(HandshakeValidationError::SelfConnection {
peer_id: [0x11; 20],
})
);
}
#[test]
fn test_validate_duplicate_peer_id_detected() {
let local_peer_id = [0x01; 20];
let remote_peer_id = [0x22; 20];
let active_ids = [[0x22; 20]];
let result = validate_received_peer_id(&remote_peer_id, &local_peer_id, &active_ids);
assert_eq!(
result,
Err(HandshakeValidationError::DuplicatePeerId {
peer_id: [0x22; 20],
})
);
}
#[test]
fn test_validate_valid_peer_id() {
let local_peer_id = [0x01; 20];
let remote_peer_id = [0x99; 20];
let active_ids = [[0x22; 20], [0x33; 20]];
let result = validate_received_peer_id(&remote_peer_id, &local_peer_id, &active_ids);
assert_eq!(result, Ok(()));
}
#[test]
fn test_validate_empty_active_list() {
let local_peer_id = [0x01; 20];
let remote_peer_id = [0x99; 20];
let result = validate_received_peer_id(&remote_peer_id, &local_peer_id, &[]);
assert_eq!(result, Ok(()));
}
#[test]
fn test_validate_self_connection_precedence() {
let local_peer_id = [0x11; 20];
let remote_peer_id = [0x11; 20];
let active_ids = [[0x11; 20]];
let result = validate_received_peer_id(&remote_peer_id, &local_peer_id, &active_ids);
assert_eq!(
result,
Err(HandshakeValidationError::SelfConnection {
peer_id: [0x11; 20],
})
);
}
#[test]
fn test_error_display_self_connection() {
let error = HandshakeValidationError::SelfConnection {
peer_id: [0xAB; 20],
};
let msg = format!("{}", error);
assert!(msg.contains("Drop connection from the same Peer ID"));
assert!(msg.contains("abab"));
}
#[test]
fn test_error_display_duplicate() {
let error = HandshakeValidationError::DuplicatePeerId {
peer_id: [0xCD; 20],
};
let msg = format!("{}", error);
assert!(msg.contains("Same Peer ID has been already seen"));
assert!(msg.contains("cdcd"));
}
#[test]
fn test_filter_removes_self_connection() {
let local_peer_id = [0x01; 20];
let mut connections = vec![BtPeerConn::new_stub(&[0x01; 20])];
connections[0].peer_id = Some([0x01; 20]);
connections[0].ip_addr = "192.168.1.1".to_string();
connections[0].port = 6881;
let removed = filter_duplicate_peer_connections(&mut connections, &local_peer_id);
assert_eq!(removed, 1);
assert!(connections.is_empty());
}
#[test]
fn test_filter_removes_duplicate() {
let local_peer_id = [0x01; 20];
let mut connections = vec![
BtPeerConn::new_stub(&[0x22; 20]),
BtPeerConn::new_stub(&[0x22; 20]), ];
connections[0].peer_id = Some([0x22; 20]);
connections[0].ip_addr = "192.168.1.1".to_string();
connections[0].port = 6881;
connections[1].peer_id = Some([0x22; 20]);
connections[1].ip_addr = "192.168.1.2".to_string();
connections[1].port = 6882;
let removed = filter_duplicate_peer_connections(&mut connections, &local_peer_id);
assert_eq!(removed, 1);
assert_eq!(connections.len(), 1);
}
#[test]
fn test_filter_keeps_valid_connections() {
let local_peer_id = [0x01; 20];
let mut connections = vec![
BtPeerConn::new_stub(&[0x22; 20]),
BtPeerConn::new_stub(&[0x33; 20]),
];
connections[0].peer_id = Some([0x22; 20]);
connections[0].ip_addr = "192.168.1.1".to_string();
connections[0].port = 6881;
connections[1].peer_id = Some([0x33; 20]);
connections[1].ip_addr = "192.168.1.2".to_string();
connections[1].port = 6882;
let removed = filter_duplicate_peer_connections(&mut connections, &local_peer_id);
assert_eq!(removed, 0);
assert_eq!(connections.len(), 2);
}
#[test]
fn test_filter_keeps_connection_without_peer_id() {
let local_peer_id = [0x01; 20];
let mut connections = vec![BtPeerConn::new_stub(&[0x99; 20])];
connections[0].peer_id = None;
let removed = filter_duplicate_peer_connections(&mut connections, &local_peer_id);
assert_eq!(removed, 0);
assert_eq!(connections.len(), 1);
}
#[test]
fn test_filter_mixed_invalid_connections() {
let local_peer_id = [0x01; 20];
let mut connections = vec![
BtPeerConn::new_stub(&[0x22; 20]), BtPeerConn::new_stub(&[0x01; 20]), BtPeerConn::new_stub(&[0x22; 20]), BtPeerConn::new_stub(&[0x33; 20]), BtPeerConn::new_stub(&[0x33; 20]), ];
connections[0].peer_id = Some([0x22; 20]);
connections[0].ip_addr = "10.0.0.1".to_string();
connections[0].port = 6881;
connections[1].peer_id = Some([0x01; 20]); connections[1].ip_addr = "10.0.0.2".to_string();
connections[1].port = 6882;
connections[2].peer_id = Some([0x22; 20]); connections[2].ip_addr = "10.0.0.3".to_string();
connections[2].port = 6883;
connections[3].peer_id = Some([0x33; 20]);
connections[3].ip_addr = "10.0.0.4".to_string();
connections[3].port = 6884;
connections[4].peer_id = Some([0x33; 20]); connections[4].ip_addr = "10.0.0.5".to_string();
connections[4].port = 6885;
let removed = filter_duplicate_peer_connections(&mut connections, &local_peer_id);
assert_eq!(removed, 3); assert_eq!(connections.len(), 2);
let remaining_ids: Vec<[u8; 20]> = connections.iter().filter_map(|c| c.peer_id).collect();
assert_eq!(remaining_ids, [[0x22; 20], [0x33; 20]]);
}
}