mod optimistic;
mod selection;
use std::collections::HashSet;
use super::peer_stats::PeerStats;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PeerIdentity {
pub peer_id: [u8; 20],
pub addr: std::net::SocketAddr,
}
impl From<&PeerStats> for PeerIdentity {
fn from(peer: &PeerStats) -> Self {
Self {
peer_id: peer.peer_id,
addr: peer.addr,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ChokeAction {
Unchoke(usize),
Choke(usize),
NoChange(usize),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IdentityChokeAction {
Unchoke(PeerIdentity),
Choke(PeerIdentity),
NoChange(PeerIdentity),
}
impl IdentityChokeAction {
pub fn identity(&self) -> PeerIdentity {
match self {
Self::Unchoke(identity) | Self::Choke(identity) | Self::NoChange(identity) => *identity,
}
}
}
#[derive(Debug, Clone)]
pub struct ChokingConfig {
pub max_upload_slots: usize,
pub optimistic_unchoke_interval_secs: u64,
pub snubbed_timeout_secs: u64,
pub choke_rotation_interval_secs: u64,
}
impl Default for ChokingConfig {
fn default() -> Self {
Self {
max_upload_slots: 4,
optimistic_unchoke_interval_secs: 30,
snubbed_timeout_secs: 60,
choke_rotation_interval_secs: 10,
}
}
}
pub struct ChokingAlgorithm {
pub(crate) peers: Vec<PeerStats>,
pub(crate) config: ChokingConfig,
pub(crate) snubbed_peers: HashSet<PeerIdentity>,
pub(crate) current_optimistic_peer: Option<PeerIdentity>,
pub(crate) optimistic_rotation_counter: usize,
}
impl ChokingAlgorithm {
pub fn new(config: ChokingConfig) -> Self {
Self {
peers: Vec::new(),
config,
snubbed_peers: HashSet::new(),
current_optimistic_peer: None,
optimistic_rotation_counter: 0,
}
}
pub fn add_peer(&mut self, stats: PeerStats) {
self.peers.push(stats);
}
pub fn remove_peers_by_identity(&mut self, identities: &[PeerIdentity]) {
self.peers
.retain(|peer| !identities.contains(&PeerIdentity::from(peer)));
self.snubbed_peers
.retain(|identity| !identities.contains(identity));
if self
.current_optimistic_peer
.is_some_and(|identity| identities.contains(&identity))
{
self.current_optimistic_peer = None;
}
self.optimistic_rotation_counter %= self.peers.len().max(1);
}
pub fn remove_peers_by_addr(&mut self, addresses: &[std::net::SocketAddr]) {
self.peers.retain(|peer| !addresses.contains(&peer.addr));
self.snubbed_peers
.retain(|identity| !addresses.contains(&identity.addr));
if self
.current_optimistic_peer
.is_some_and(|identity| addresses.contains(&identity.addr))
{
self.current_optimistic_peer = None;
}
self.optimistic_rotation_counter %= self.peers.len().max(1);
}
pub fn remove_peers(&mut self, indices: &[usize]) {
let mut removed = vec![false; self.peers.len()];
for &index in indices {
if let Some(slot) = removed.get_mut(index) {
*slot = true;
}
}
self.peers = self
.peers
.drain(..)
.enumerate()
.filter_map(|(index, peer)| (!removed[index]).then_some(peer))
.collect();
self.snubbed_peers.retain(|identity| {
self.peers
.iter()
.any(|peer| PeerIdentity::from(peer) == *identity)
});
if self.current_optimistic_peer.is_some_and(|identity| {
!self
.peers
.iter()
.any(|peer| PeerIdentity::from(peer) == identity)
}) {
self.current_optimistic_peer = None;
}
self.optimistic_rotation_counter %= self.peers.len().max(1);
}
pub fn remove_peer(&mut self, idx: usize) {
self.remove_peers(&[idx]);
}
pub fn len(&self) -> usize {
self.peers.len()
}
pub fn is_empty(&self) -> bool {
self.peers.is_empty()
}
pub fn rotate_choke(&mut self) -> Vec<ChokeAction> {
selection::rotate_choke(self)
}
pub fn rotate_choke_by_identity(&mut self) -> Vec<IdentityChokeAction> {
selection::rotate_choke_by_identity(self)
}
pub fn optimistically_unchoke(&mut self) -> Option<usize> {
optimistic::optimistically_unchoke(self)
}
pub fn optimistically_unchoke_by_identity(&mut self) -> Option<PeerIdentity> {
optimistic::optimistically_unchoke_by_identity(self)
}
pub fn rotate_optimistic_unchoked(&mut self, eligible_peers: &[usize]) -> usize {
optimistic::rotate_optimistic_unchoked(self, eligible_peers)
}
pub fn on_data_received_by_identity(&mut self, identity: PeerIdentity, bytes: u64) {
if let Some(peer) = self
.peers
.iter_mut()
.find(|peer| PeerIdentity::from(&**peer) == identity)
{
peer.on_data_received(bytes);
}
self.snubbed_peers.remove(&identity);
}
pub fn on_data_received(&mut self, peer_idx: usize, bytes: u64) {
if let Some(peer) = self.peers.get_mut(peer_idx) {
peer.on_data_received(bytes);
}
self.unsnub_peer(peer_idx);
}
pub fn mark_peer_snubbed(&mut self, peer_id: usize) {
if let Some(peer) = self.peers.get(peer_id)
&& self.snubbed_peers.insert(PeerIdentity::from(peer))
{
tracing::debug!("[BT] Peer {} explicitly marked as snubbed", peer.addr);
}
}
pub fn unsnub_peer(&mut self, peer_id: usize) -> bool {
let Some(identity) = self.peers.get(peer_id).map(PeerIdentity::from) else {
return false;
};
if self.snubbed_peers.remove(&identity) {
tracing::debug!("[BT] Peer {} un-snubbed (data received)", identity.addr);
true
} else {
false
}
}
pub fn is_explicitly_snubbed(&self, peer_id: usize) -> bool {
self.peers
.get(peer_id)
.is_some_and(|peer| self.snubbed_peers.contains(&PeerIdentity::from(peer)))
}
pub fn snubbed_count(&self) -> usize {
self.snubbed_peers.len()
}
pub fn check_snubbed_peers(&mut self) -> Vec<usize> {
selection::check_snubbed_peers_internal(self)
}
#[allow(dead_code)] pub(crate) fn calculate_peer_score(peer: &PeerStats, is_explicitly_snubbed: bool) -> f64 {
selection::calculate_peer_score(peer, is_explicitly_snubbed)
}
pub fn get_peer_mut(&mut self, idx: usize) -> Option<&mut PeerStats> {
self.peers.get_mut(idx)
}
pub fn get_peer(&self, idx: usize) -> Option<&PeerStats> {
self.peers.get(idx)
}
pub fn peers(&self) -> &[PeerStats] {
&self.peers
}
pub fn config(&self) -> &ChokingConfig {
&self.config
}
}
#[cfg(test)]
mod tests;