refactor(swarm)!: deprecate PollParameters where possible (#3153)

This patch deprecates 3 out of 4 functions on `PollParameters`:

- `local_peer_id`
- `listened_addresses`
- `external_addresses`

The addresses can be obtained by inspecting the `FromSwarm` event. To make this easier, we introduce two utility structs in `libp2p-swarm`:

- `ExternalAddresses`
- `ListenAddresses`

A node's `PeerId` is always known to the caller, thus we can require them to pass it in.

Related: #3124.
This commit is contained in:
Thomas Eizinger
2022-12-14 11:50:08 +11:00
committed by GitHub
parent 5fe0dc44bd
commit be3ec6c62b
28 changed files with 282 additions and 112 deletions

View File

@ -30,7 +30,8 @@ use if_watch::IfEvent;
use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::behaviour::{ConnectionClosed, FromSwarm};
use libp2p_swarm::{
dummy, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters,
dummy, ConnectionHandler, ListenAddresses, NetworkBehaviour, NetworkBehaviourAction,
PollParameters,
};
use smallvec::SmallVec;
use std::collections::hash_map::{Entry, HashMap};
@ -121,6 +122,10 @@ where
///
/// `None` if `discovered_nodes` is empty.
closest_expiration: Option<P::Timer>,
listen_addresses: ListenAddresses,
local_peer_id: PeerId,
}
impl<P> Behaviour<P>
@ -128,13 +133,15 @@ where
P: Provider,
{
/// Builds a new `Mdns` behaviour.
pub fn new(config: Config) -> io::Result<Self> {
pub fn new(config: Config, local_peer_id: PeerId) -> io::Result<Self> {
Ok(Self {
config,
if_watch: P::new_watcher()?,
iface_states: Default::default(),
discovered_nodes: Default::default(),
closest_expiration: Default::default(),
listen_addresses: Default::default(),
local_peer_id,
})
}
@ -189,6 +196,8 @@ where
}
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
self.listen_addresses.on_swarm_event(&event);
match event {
FromSwarm::ConnectionClosed(ConnectionClosed {
peer_id,
@ -221,7 +230,7 @@ where
fn poll(
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, dummy::ConnectionHandler>> {
// Poll ifwatch.
while let Poll::Ready(Some(event)) = Pin::new(&mut self.if_watch).poll_next(cx) {
@ -237,7 +246,7 @@ where
continue;
}
if let Entry::Vacant(e) = self.iface_states.entry(addr) {
match InterfaceState::new(addr, self.config.clone()) {
match InterfaceState::new(addr, self.config.clone(), self.local_peer_id) {
Ok(iface_state) => {
e.insert(iface_state);
}
@ -257,7 +266,9 @@ where
// Emit discovered event.
let mut discovered = SmallVec::<[(PeerId, Multiaddr); 4]>::new();
for iface_state in self.iface_states.values_mut() {
while let Poll::Ready((peer, addr, expiration)) = iface_state.poll(cx, params) {
while let Poll::Ready((peer, addr, expiration)) =
iface_state.poll(cx, &self.listen_addresses)
{
if let Some((_, _, cur_expires)) = self
.discovered_nodes
.iter_mut()

View File

@ -26,7 +26,7 @@ use self::query::MdnsPacket;
use crate::behaviour::{socket::AsyncSocket, timer::Builder};
use crate::Config;
use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::PollParameters;
use libp2p_swarm::ListenAddresses;
use socket2::{Domain, Socket, Type};
use std::{
collections::VecDeque,
@ -66,6 +66,8 @@ pub struct InterfaceState<U, T> {
discovered: VecDeque<(PeerId, Multiaddr, Instant)>,
/// TTL
ttl: Duration,
local_peer_id: PeerId,
}
impl<U, T> InterfaceState<U, T>
@ -74,7 +76,7 @@ where
T: Builder + futures::Stream,
{
/// Builds a new [`InterfaceState`].
pub fn new(addr: IpAddr, config: Config) -> io::Result<Self> {
pub fn new(addr: IpAddr, config: Config, local_peer_id: PeerId) -> io::Result<Self> {
log::info!("creating instance on iface {}", addr);
let recv_socket = match addr {
IpAddr::V4(addr) => {
@ -134,6 +136,7 @@ where
timeout: T::interval_at(Instant::now(), query_interval),
multicast_addr,
ttl: config.ttl,
local_peer_id,
})
}
@ -148,7 +151,7 @@ where
pub fn poll(
&mut self,
cx: &mut Context,
params: &impl PollParameters,
listen_addresses: &ListenAddresses,
) -> Poll<(PeerId, Multiaddr, Instant)> {
loop {
// 1st priority: Low latency: Create packet ASAP after timeout.
@ -198,8 +201,8 @@ where
self.send_buffer.extend(build_query_response(
query.query_id(),
*params.local_peer_id(),
params.listened_addresses(),
self.local_peer_id,
listen_addresses.iter(),
self.ttl,
));
continue;
@ -211,9 +214,8 @@ where
self.addr
);
self.discovered.extend(
response.extract_discovered(Instant::now(), *params.local_peer_id()),
);
self.discovered
.extend(response.extract_discovered(Instant::now(), self.local_peer_id));
continue;
}
Poll::Ready(Ok(Ok(Some(MdnsPacket::ServiceDiscovery(disc))))) => {

View File

@ -103,10 +103,10 @@ pub fn build_query() -> MdnsPacket {
/// Builds the response to an address discovery DNS query.
///
/// If there are more than 2^16-1 addresses, ignores the rest.
pub fn build_query_response(
pub fn build_query_response<'a>(
id: u16,
peer_id: PeerId,
addresses: impl ExactSizeIterator<Item = Multiaddr>,
addresses: impl ExactSizeIterator<Item = &'a Multiaddr>,
ttl: Duration,
) -> Vec<MdnsPacket> {
// Convert the TTL into seconds.
@ -413,7 +413,7 @@ mod tests {
let packets = build_query_response(
0xf8f8,
my_peer_id,
vec![addr1, addr2].into_iter(),
vec![&addr1, &addr2].into_iter(),
Duration::from_secs(60),
);
for packet in packets {

View File

@ -335,7 +335,7 @@ mod tests {
let packets = build_query_response(
0xf8f8,
peer_id,
vec![addr1, addr2].into_iter(),
vec![&addr1, &addr2].into_iter(),
Duration::from_secs(60),
);