Skip to content

Commit

Permalink
feat: impl process_candidate_peers
Browse files Browse the repository at this point in the history
  • Loading branch information
niklaslong committed Nov 17, 2022
1 parent f964361 commit ddba949
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
8 changes: 7 additions & 1 deletion node/src/new_beacon/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,12 @@ impl<N: CurrentNetwork, C: ConsensusStorage<N>> Beacon<N, C> {
Ok(())
}

async fn process_peer_response(&self, source: SocketAddr, message: PeerResponse) -> anyhow::Result<()> {
self.router().insert_candidate_peers(&message.peers);

Ok(())
}

async fn process_unconfirmed_block(&self, source: SocketAddr, message: UnconfirmedBlock<N>) -> anyhow::Result<()> {
let message_clone = message.clone();

Expand Down Expand Up @@ -388,7 +394,7 @@ impl<N: CurrentNetwork, C: ConsensusStorage<N>> Reading for Beacon<N, C> {
Message::Pong(pong) => todo!(),

Message::PeerRequest(peer_request) => self.process_peer_request(source, peer_request).await,
Message::PeerResponse(peer_response) => todo!(),
Message::PeerResponse(peer_response) => self.process_peer_response(source, peer_response).await,

Message::UnconfirmedBlock(unconfirmed_block) => {
// TODO(nkls): spawn task.
Expand Down
27 changes: 27 additions & 0 deletions node/src/new_beacon/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ impl Router {
&self.network
}

pub fn is_local_addr(&self, addr: SocketAddr) -> bool {
let local_addr = self.network().listening_addr().expect("listening addr must be present");
addr == local_addr
|| (addr.ip().is_unspecified() || addr.ip().is_loopback()) && addr.port() == local_addr.port()
}

pub fn is_connected(&self, addr: SocketAddr) -> bool {
self.network().is_connected(addr)
|| self.current_peers.read().iter().find(|(_, meta)| meta.listening_addr() == addr).is_some()
}

pub fn is_restricted(&self, addr: SocketAddr) -> bool {
self.restricted_peers.read().contains_key(&addr)
}

pub fn insert_peer(&self, addr: SocketAddr, meta: PeerMeta) {
self.current_peers.write().insert(addr, meta);
}
Expand All @@ -77,6 +92,18 @@ impl Router {
self.candidate_peers.write().remove(&addr);
}

pub fn insert_candidate_peers(&self, addrs: &[SocketAddr]) {
let candidate_peers = self.candidate_peers.write();

for &addr in addrs {
if self.is_local_addr(addr) || self.is_connected(addr) || self.is_restricted(addr) {
continue;
}

self.candidate_peers.write().insert(addr);
}
}

pub fn insert_restricted_peer(&self, addr: SocketAddr) {
self.restricted_peers.write().insert(addr, OffsetDateTime::now_utc());
}
Expand Down

0 comments on commit ddba949

Please sign in to comment.