use crate::messages::{Message, NetworkTopic};
use futures::{Future, FutureExt};
use libp2p::PeerId;
use pchain_types::cryptography::PublicAddress;
use std::{collections::HashMap, sync::Arc};
use tokio::{
sync::Mutex,
task::{JoinError, JoinHandle},
};
pub struct Network {
pub(crate) network_thread: JoinHandle<()>,
pub(crate) peer_public_addrs: Arc<Mutex<HashMap<PeerId, PublicAddress>>>,
pub(crate) sender: tokio::sync::mpsc::Sender<SendCommand>,
}
impl Network {
pub fn sender(&self) -> tokio::sync::mpsc::Sender<SendCommand> {
self.sender.clone()
}
pub async fn list_addresses(&self) -> Vec<PublicAddress> {
self.peer_public_addrs
.lock()
.await
.values()
.copied()
.collect()
}
pub async fn stop(self) {
self.network_thread.abort();
log::debug!("pchain network stop!");
}
}
impl Future for Network {
type Output = Result<(), JoinError>;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
let mut s = self;
s.network_thread.poll_unpin(cx)
}
}
pub enum SendCommand {
SendTo(PublicAddress, Message),
Broadcast(NetworkTopic, Message),
}