Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Check for relay when storing address based on connection #170

Merged
merged 3 commits into from
Apr 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 0.11.5
- fix: Check for relay when storing address based on connection. [PR 170](httops://github.com/dariusc93/rust-ipfs/pull/170)

# 0.11.4
- fix: Send a wantlist of missing blocks.

Expand Down
148 changes: 63 additions & 85 deletions src/p2p/addressbook.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use std::{
collections::{hash_map::Entry, HashMap, VecDeque},
collections::{hash_map::Entry, HashMap, HashSet, VecDeque},
task::{Context, Poll},
};

use libp2p::{
core::{ConnectedPoint, Endpoint},
multiaddr::Protocol,
swarm::{
self, dummy::ConnectionHandler as DummyConnectionHandler, AddressChange, ConnectionDenied,
ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, ToSwarm,
self, behaviour::ConnectionEstablished, dummy::ConnectionHandler as DummyConnectionHandler,
AddressChange, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler,
THandlerInEvent, ToSwarm,
},
Multiaddr, PeerId,
};
Expand All @@ -22,7 +23,7 @@ pub struct Config {
#[derive(Default, Debug)]
pub struct Behaviour {
events: VecDeque<ToSwarm<<Self as NetworkBehaviour>::ToSwarm, THandlerInEvent<Self>>>,
peer_addresses: HashMap<PeerId, Vec<Multiaddr>>,
peer_addresses: HashMap<PeerId, HashSet<Multiaddr>>,
config: Config,
}

Expand All @@ -38,29 +39,20 @@ impl Behaviour {
addr.pop();
}

match self.peer_addresses.entry(peer_id) {
Entry::Occupied(mut e) => {
let entry = e.get_mut();
if entry.contains(&addr) {
return false;
}

entry.push(addr);
}
Entry::Vacant(e) => {
e.insert(vec![addr]);
}
}
true
self.peer_addresses.entry(peer_id).or_default().insert(addr)
}

pub fn remove_address(&mut self, peer_id: &PeerId, addr: &Multiaddr) -> bool {
if let Entry::Occupied(mut e) = self.peer_addresses.entry(*peer_id) {
let entry = e.get_mut();
if !entry.contains(addr) {

if !entry.remove(addr) {
return false;
}
entry.retain(|item| addr.ne(item));

if entry.is_empty() {
e.remove();
}
}
true
}
Expand All @@ -70,16 +62,20 @@ impl Behaviour {
}

pub fn contains(&self, peer_id: &PeerId, addr: &Multiaddr) -> bool {
self.get_peer_addresses(peer_id)
.map(|list| !list.is_empty() && list.contains(addr))
self.peer_addresses
.get(peer_id)
.map(|list| list.contains(addr))
.unwrap_or_default()
}

pub fn get_peer_addresses(&self, peer_id: &PeerId) -> Option<&Vec<Multiaddr>> {
self.peer_addresses.get(peer_id)
pub fn get_peer_addresses(&self, peer_id: &PeerId) -> Option<Vec<Multiaddr>> {
self.peer_addresses
.get(peer_id)
.cloned()
.map(Vec::from_iter)
}

pub fn iter(&self) -> impl Iterator<Item = (&PeerId, &Vec<Multiaddr>)> {
pub fn iter(&self) -> impl Iterator<Item = (&PeerId, &HashSet<Multiaddr>)> {
self.peer_addresses.iter()
}
}
Expand All @@ -88,81 +84,43 @@ impl NetworkBehaviour for Behaviour {
type ConnectionHandler = DummyConnectionHandler;
type ToSwarm = void::Void;

fn handle_pending_inbound_connection(
&mut self,
_: ConnectionId,
_: &Multiaddr,
_: &Multiaddr,
) -> Result<(), ConnectionDenied> {
Ok(())
}

fn handle_pending_outbound_connection(
&mut self,
_: ConnectionId,
peer_id: Option<PeerId>,
_: &[Multiaddr],
_: Endpoint,
) -> Result<Vec<Multiaddr>, ConnectionDenied> {
if let Some(peer_id) = peer_id {
if let Entry::Occupied(e) = self.peer_addresses.entry(peer_id) {
return Ok(e.get().clone());
}
}
Ok(vec![])
let Some(peer_id) = peer_id else {
return Ok(vec![]);
};

let list = self
.peer_addresses
.get(&peer_id)
.map(|list| Vec::from_iter(list.clone()))
.unwrap_or_default();

Ok(list)
}

fn handle_established_inbound_connection(
&mut self,
_: ConnectionId,
peer_id: PeerId,
_: PeerId,
_: &Multiaddr,
_: &Multiaddr,
remote: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
if self.config.store_on_connection {
let mut addr = remote.clone();
if matches!(addr.iter().last(), Some(Protocol::P2p(_))) {
addr.pop();
}
match self.peer_addresses.entry(peer_id) {
Entry::Occupied(mut e) => {
let entry = e.get_mut();
if !entry.contains(&addr) {
entry.push(addr);
}
}
Entry::Vacant(e) => {
e.insert(vec![addr]);
}
}
}
Ok(DummyConnectionHandler)
}

fn handle_established_outbound_connection(
&mut self,
_: ConnectionId,
peer_id: PeerId,
addr: &Multiaddr,
_: PeerId,
_: &Multiaddr,
_: Endpoint,
) -> Result<THandler<Self>, ConnectionDenied> {
if self.config.store_on_connection {
let mut addr = addr.clone();
if matches!(addr.iter().last(), Some(Protocol::P2p(_))) {
addr.pop();
}
match self.peer_addresses.entry(peer_id) {
Entry::Occupied(mut e) => {
let entry = e.get_mut();
if !entry.contains(&addr) {
entry.push(addr);
}
}
Entry::Vacant(e) => {
e.insert(vec![addr]);
}
}
}
Ok(DummyConnectionHandler)
}

Expand All @@ -181,6 +139,9 @@ impl NetworkBehaviour for Behaviour {
}) => {
let mut old = match old {
ConnectedPoint::Dialer { address, .. } => address.clone(),
ConnectedPoint::Listener { local_addr, .. } if old.is_relayed() => {
local_addr.clone()
}
ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr.clone(),
};

Expand All @@ -190,6 +151,9 @@ impl NetworkBehaviour for Behaviour {

let mut new = match new {
ConnectedPoint::Dialer { address, .. } => address.clone(),
ConnectedPoint::Listener { local_addr, .. } if new.is_relayed() => {
local_addr.clone()
}
ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr.clone(),
};

Expand All @@ -199,16 +163,31 @@ impl NetworkBehaviour for Behaviour {

if let Entry::Occupied(mut e) = self.peer_addresses.entry(peer_id) {
let entry = e.get_mut();
if !entry.contains(&new) {
entry.push(new);
}
entry.insert(new);
entry.remove(&old);
}
}
FromSwarm::ConnectionEstablished(ConnectionEstablished {
peer_id, endpoint, ..
}) => {
if !self.config.store_on_connection {
return;
}

if entry.contains(&old) {
entry.retain(|addr| addr != &old);
let mut addr = match endpoint {
ConnectedPoint::Dialer { address, .. } => address.clone(),
ConnectedPoint::Listener { local_addr, .. } if endpoint.is_relayed() => {
local_addr.clone()
}
ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr.clone(),
};

if matches!(addr.iter().last(), Some(Protocol::P2p(_))) {
addr.pop();
}

self.peer_addresses.entry(peer_id).or_default().insert(addr);
}
FromSwarm::ConnectionEstablished(_) => {}
FromSwarm::ConnectionClosed(_) => {}
FromSwarm::DialFailure(_) => {}
FromSwarm::ListenFailure(_) => {}
Expand Down Expand Up @@ -333,7 +312,6 @@ mod test {
let addrs = swarm1
.behaviour()
.get_peer_addresses(&peer2)
.cloned()
.expect("Exist");

for addr in addrs {
Expand Down
1 change: 0 additions & 1 deletion src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1394,7 +1394,6 @@ impl<C: NetworkBehaviour<ToSwarm = void::Void>> IpfsTask<C> {
.behaviour()
.addressbook
.get_peer_addresses(&peer_id)
.cloned()
.unwrap_or_default()
};

Expand Down