use super::peer_id::{from_core_peer_id, to_core_peer_id};
use arrayvec::ArrayVec;
use log::{debug, warn};
use mixnet::core::{AddressedPacket, NetworkStatus, Packet, PeerId as CorePeerId};
use parking_lot::Mutex;
use sc_network::NotificationService;
use sc_network_types::PeerId;
use std::{collections::HashMap, future::Future, sync::Arc};
const LOG_TARGET: &str = "mixnet";
struct PeerQueue(Mutex<ArrayVec<Box<Packet>, 2>>);
impl PeerQueue {
fn new() -> Self {
Self(Mutex::new(ArrayVec::new()))
}
fn push(&self, packet: Box<Packet>) -> Result<bool, ()> {
let mut queue = self.0.lock();
if queue.is_full() {
Err(())
} else {
let was_empty = queue.is_empty();
queue.push(packet);
Ok(was_empty)
}
}
fn clear(&self) {
let mut queue = self.0.lock();
queue.clear();
}
fn pop(&self) -> (Option<Box<Packet>>, bool) {
let mut queue = self.0.lock();
let packet = queue.pop();
(packet, !queue.is_empty())
}
}
pub struct ReadyPeer {
id: PeerId,
queue: Arc<PeerQueue>,
}
impl ReadyPeer {
pub fn send_packet(
self,
notification_service: &Box<dyn NotificationService>,
) -> Option<impl Future<Output = Option<Self>>> {
match notification_service.message_sink(&self.id) {
None => {
debug!(
target: LOG_TARGET,
"Failed to get message sink for peer ID {}", self.id,
);
self.queue.clear();
None
},
Some(sink) => Some(async move {
let (packet, more_packets) = self.queue.pop();
let packet = packet.expect("Should only be called if there is a packet to send");
match sink.send_async_notification((packet as Box<[_]>).into()).await {
Ok(_) => more_packets.then_some(self),
Err(err) => {
debug!(
target: LOG_TARGET,
"Failed to send packet to peer ID {}: {err}", self.id,
);
self.queue.clear();
None
},
}
}),
}
}
}
pub struct PacketDispatcher {
local_peer_id: CorePeerId,
peer_queues: HashMap<CorePeerId, Arc<PeerQueue>>,
}
impl PacketDispatcher {
pub fn new(local_peer_id: &CorePeerId) -> Self {
Self { local_peer_id: *local_peer_id, peer_queues: HashMap::new() }
}
pub fn add_peer(&mut self, id: &PeerId) {
let Some(core_id) = to_core_peer_id(id) else {
debug!(target: LOG_TARGET,
"Cannot add peer; failed to convert libp2p peer ID {id} to mixnet peer ID");
return
};
if self.peer_queues.insert(core_id, Arc::new(PeerQueue::new())).is_some() {
warn!(target: LOG_TARGET, "Two stream opened notifications for peer ID {id}");
}
}
pub fn remove_peer(&mut self, id: &PeerId) {
let Some(core_id) = to_core_peer_id(id) else {
debug!(target: LOG_TARGET,
"Cannot remove peer; failed to convert libp2p peer ID {id} to mixnet peer ID");
return
};
if self.peer_queues.remove(&core_id).is_none() {
warn!(target: LOG_TARGET, "Stream closed notification for unknown peer ID {id}");
}
}
pub fn dispatch(&mut self, packet: AddressedPacket) -> Option<ReadyPeer> {
let Some(queue) = self.peer_queues.get_mut(&packet.peer_id) else {
debug!(target: LOG_TARGET, "Dropped packet to mixnet peer ID {:x?}; not connected",
packet.peer_id);
return None
};
match queue.push(packet.packet) {
Err(_) => {
debug!(
target: LOG_TARGET,
"Dropped packet to mixnet peer ID {:x?}; peer queue full", packet.peer_id
);
None
},
Ok(true) => {
let Some(id) = from_core_peer_id(&packet.peer_id) else {
debug!(target: LOG_TARGET, "Cannot send packet; \
failed to convert mixnet peer ID {:x?} to libp2p peer ID",
packet.peer_id);
queue.clear();
return None
};
Some(ReadyPeer { id, queue: queue.clone() })
},
Ok(false) => None, }
}
}
impl NetworkStatus for PacketDispatcher {
fn local_peer_id(&self) -> CorePeerId {
self.local_peer_id
}
fn is_connected(&self, peer_id: &CorePeerId) -> bool {
self.peer_queues.contains_key(peer_id)
}
}