src: use channel for discovery, filter uniques
This commit is contained in:
parent
808f979f06
commit
c80a600845
|
@ -3,12 +3,15 @@ use async_std::sync::Arc;
|
|||
use async_std::task;
|
||||
use ed25519_dalek::PublicKey;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::keypair::SSBPublicKey;
|
||||
use crate::peer::{Address, Handshake, Peer, Protocol};
|
||||
|
||||
pub async fn recv() {
|
||||
pub async fn recv(sender: async_std::channel::Sender<Peer>) {
|
||||
let socket = UdpSocket::bind(":::8008").await.unwrap();
|
||||
let mut buf = [0u8; 1024];
|
||||
let mut old = HashSet::new();
|
||||
|
||||
loop {
|
||||
let (amt, peer) = socket.recv_from(&mut buf).await.unwrap();
|
||||
|
@ -19,6 +22,11 @@ pub async fn recv() {
|
|||
peer,
|
||||
Peer::from_discovery_packet(&packet).to_discovery_packet()
|
||||
);
|
||||
let peer = Peer::from_discovery_packet(packet.as_str());
|
||||
if !old.contains(&peer) {
|
||||
old.insert(peer.clone());
|
||||
sender.send(peer).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -37,8 +37,11 @@ async fn main() {
|
|||
let keypair = Keypair::read_or_generate(path.join("secret")).await;
|
||||
println!("{}", keypair.to_json().pretty(2));
|
||||
|
||||
let pubkey = keypair.public.to_base64();
|
||||
let (psend, precv) = async_std::channel::unbounded();
|
||||
task::spawn(async move { discovery::recv(psend).await });
|
||||
task::spawn(discovery::send(Arc::new(keypair.public.to_base64())));
|
||||
|
||||
task::spawn(discovery::recv());
|
||||
task::spawn(discovery::send(Arc::new(pubkey))).await;
|
||||
while let Ok(peer) = precv.recv().await {
|
||||
println!("{}", peer.to_discovery_packet());
|
||||
};
|
||||
}
|
||||
|
|
19
src/peer.rs
19
src/peer.rs
|
@ -1,19 +1,24 @@
|
|||
use async_std::net::IpAddr;
|
||||
use ed25519_dalek::PublicKey;
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use crate::keypair::SSBPublicKey;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Protocol {
|
||||
Net,
|
||||
Ws,
|
||||
Wss,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Handshake {
|
||||
Shs,
|
||||
Shs2,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Address {
|
||||
protocol: Protocol,
|
||||
host: IpAddr,
|
||||
|
@ -32,6 +37,7 @@ impl Address {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Peer {
|
||||
addresses: Vec<Address>,
|
||||
key: PublicKey,
|
||||
|
@ -114,3 +120,16 @@ impl Peer {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for Peer {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.key.to_bytes().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl std::cmp::PartialEq for Peer {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.key == other.key
|
||||
}
|
||||
}
|
||||
impl std::cmp::Eq for Peer {}
|
||||
|
|
Loading…
Reference in New Issue