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

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

Merged
merged 15 commits into from
Dec 14, 2022
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
2 changes: 1 addition & 1 deletion examples/chat-tokio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
}

// Create a Swarm to manage peers and events.
let mdns_behaviour = mdns::Behaviour::new(Default::default())?;
let mdns_behaviour = mdns::Behaviour::new(Default::default(), peer_id)?;
let behaviour = MyBehaviour {
floodsub: Floodsub::new(peer_id),
mdns: mdns_behaviour,
Expand Down
2 changes: 1 addition & 1 deletion examples/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ async fn main() -> Result<(), Box<dyn Error>> {

// Create a Swarm to manage peers and events
let mut swarm = {
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?;
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
let mut behaviour = MyBehaviour {
floodsub: Floodsub::new(local_peer_id),
mdns,
Expand Down
2 changes: 1 addition & 1 deletion examples/distributed-key-value-store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Create a Kademlia behaviour.
let store = MemoryStore::new(local_peer_id);
let kademlia = Kademlia::new(local_peer_id, store);
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?;
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
let behaviour = MyBehaviour { kademlia, mdns };
Swarm::with_async_std_executor(transport, behaviour, local_peer_id)
};
Expand Down
2 changes: 1 addition & 1 deletion examples/gossipsub-chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ async fn main() -> Result<(), Box<dyn Error>> {

// Create a Swarm to manage peers and events
let mut swarm = {
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?;
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
let behaviour = MyBehaviour { gossipsub, mdns };
Swarm::with_async_std_executor(transport, behaviour, local_peer_id)
};
Expand Down
2 changes: 1 addition & 1 deletion examples/mdns-passive-discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = libp2p::development_transport(id_keys).await?;

// Create an MDNS network behaviour.
let behaviour = mdns::async_io::Behaviour::new(mdns::Config::default())?;
let behaviour = mdns::async_io::Behaviour::new(mdns::Config::default(), peer_id)?;

// Create a Swarm that establishes connections through the given transport.
// Note that the MDNS behaviour itself will not actually inititiate any connections,
Expand Down
4 changes: 4 additions & 0 deletions protocols/autonat/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# 0.10.0 [unreleased]

- Require the node's local `PeerId` to be passed into the constructor of `libp2p_autonat::Behaviour`. See [PR 3153].

- Update to `libp2p-request-response` `v0.24.0`.

- Update to `libp2p-swarm` `v0.42.0`.

[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153

# 0.9.0

- Update to `libp2p-core` `v0.38.0`.
Expand Down
16 changes: 13 additions & 3 deletions protocols/autonat/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ use libp2p_swarm::{
AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr,
ExpiredListenAddr, FromSwarm,
},
ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
PollParameters,
ConnectionHandler, ExternalAddresses, IntoConnectionHandler, ListenAddresses, NetworkBehaviour,
NetworkBehaviourAction, PollParameters,
};
use std::{
collections::{HashMap, VecDeque},
Expand Down Expand Up @@ -212,6 +212,9 @@ pub struct Behaviour {
pending_out_events: VecDeque<<Self as NetworkBehaviour>::OutEvent>,

probe_id: ProbeId,

listen_addresses: ListenAddresses,
external_addresses: ExternalAddresses,
}

impl Behaviour {
Expand All @@ -236,6 +239,8 @@ impl Behaviour {
last_probe: None,
pending_out_events: VecDeque::new(),
probe_id: ProbeId(0),
listen_addresses: Default::default(),
external_addresses: Default::default(),
}
}

Expand Down Expand Up @@ -288,6 +293,8 @@ impl Behaviour {
ongoing_outbound: &mut self.ongoing_outbound,
last_probe: &mut self.last_probe,
schedule_probe: &mut self.schedule_probe,
listen_addresses: &self.listen_addresses,
external_addresses: &self.external_addresses,
}
}

Expand Down Expand Up @@ -457,7 +464,7 @@ impl NetworkBehaviour for Behaviour {
Poll::Pending => is_inner_pending = true,
}

match self.as_client().poll_auto_probe(params, cx) {
match self.as_client().poll_auto_probe(cx) {
Poll::Ready(event) => self
.pending_out_events
.push_back(Event::OutboundProbe(event)),
Expand All @@ -476,6 +483,9 @@ impl NetworkBehaviour for Behaviour {
}

fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
self.listen_addresses.on_swarm_event(&event);
self.external_addresses.on_swarn_event(&event);

match event {
FromSwarm::ConnectionEstablished(connection_established) => {
self.inner
Expand Down
23 changes: 15 additions & 8 deletions protocols/autonat/src/behaviour/as_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ use futures_timer::Delay;
use instant::Instant;
use libp2p_core::{connection::ConnectionId, Multiaddr, PeerId};
use libp2p_request_response::{self as request_response, OutboundFailure, RequestId};
use libp2p_swarm::{AddressScore, NetworkBehaviourAction, PollParameters};
use libp2p_swarm::{
AddressScore, ExternalAddresses, ListenAddresses, NetworkBehaviourAction, PollParameters,
};
use rand::{seq::SliceRandom, thread_rng};
use std::{
collections::{HashMap, VecDeque},
Expand Down Expand Up @@ -97,6 +99,9 @@ pub struct AsClient<'a> {

pub last_probe: &'a mut Option<Instant>,
pub schedule_probe: &'a mut Delay,

pub listen_addresses: &'a ListenAddresses,
pub external_addresses: &'a ExternalAddresses,
}

impl<'a> HandleInnerEvent for AsClient<'a> {
Expand Down Expand Up @@ -146,6 +151,8 @@ impl<'a> HandleInnerEvent for AsClient<'a> {

if let Ok(address) = response.result {
// Update observed address score if it is finite.
#[allow(deprecated)]
// TODO: Fix once we report `AddressScore` through `FromSwarm` event.
let score = params
.external_addresses()
.find_map(|r| (r.addr == address).then_some(r.score))
Expand Down Expand Up @@ -188,17 +195,17 @@ impl<'a> HandleInnerEvent for AsClient<'a> {
}

impl<'a> AsClient<'a> {
pub fn poll_auto_probe(
&mut self,
params: &mut impl PollParameters,
cx: &mut Context<'_>,
) -> Poll<OutboundProbeEvent> {
pub fn poll_auto_probe(&mut self, cx: &mut Context<'_>) -> Poll<OutboundProbeEvent> {
match self.schedule_probe.poll_unpin(cx) {
Poll::Ready(()) => {
self.schedule_probe.reset(self.config.retry_interval);

let mut addresses: Vec<_> = params.external_addresses().map(|r| r.addr).collect();
addresses.extend(params.listened_addresses());
let addresses = self
.external_addresses
.iter()
.chain(self.listen_addresses.iter())
.cloned()
.collect();

let probe_id = self.probe_id.next();
let event = match self.do_probe(probe_id, addresses) {
Expand Down
3 changes: 3 additions & 0 deletions protocols/dcutr/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
- Declare `InboundUpgradeError` and `OutboundUpgradeError` as type aliases instead of renames.
This is a workaround for a missing feature in `cargo semver-checks`. See [PR 3213].

- Require the node's local `PeerId` to be passed into the constructor of `libp2p_dcutr::Behaviour`. See [PR 3153].

[PR 3213]: https://github.com/libp2p/rust-libp2p/pull/3213
[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153

# 0.8.0

Expand Down
2 changes: 1 addition & 1 deletion protocols/dcutr/examples/dcutr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ fn main() -> Result<(), Box<dyn Error>> {
"/TODO/0.0.1".to_string(),
local_key.public(),
)),
dcutr: dcutr::behaviour::Behaviour::new(),
dcutr: dcutr::behaviour::Behaviour::new(local_peer_id),
};

let mut swarm = match ThreadPool::new() {
Expand Down
34 changes: 20 additions & 14 deletions protocols/dcutr/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm};
use libp2p_swarm::dial_opts::{self, DialOpts};
use libp2p_swarm::{
ConnectionHandler, ConnectionHandlerUpgrErr, IntoConnectionHandler, NetworkBehaviour,
NetworkBehaviourAction, NotifyHandler, PollParameters,
ConnectionHandler, ConnectionHandlerUpgrErr, ExternalAddresses, IntoConnectionHandler,
NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
};
use std::collections::{HashMap, HashSet, VecDeque};
use std::task::{Context, Poll};
Expand Down Expand Up @@ -66,20 +66,25 @@ pub enum UpgradeError {
Handler(ConnectionHandlerUpgrErr<void::Void>),
}

#[derive(Default)]
pub struct Behaviour {
/// Queue of actions to return when polled.
queued_actions: VecDeque<ActionBuilder>,

/// All direct (non-relayed) connections.
direct_connections: HashMap<PeerId, HashSet<ConnectionId>>,

external_addresses: ExternalAddresses,

local_peer_id: PeerId,
}

impl Behaviour {
pub fn new() -> Self {
pub fn new(local_peer_id: PeerId) -> Self {
Behaviour {
queued_actions: Default::default(),
direct_connections: Default::default(),
external_addresses: Default::default(),
local_peer_id,
}
}

Expand Down Expand Up @@ -308,16 +313,18 @@ impl NetworkBehaviour for Behaviour {
fn poll(
&mut self,
_cx: &mut Context<'_>,
poll_parameters: &mut impl PollParameters,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(action) = self.queued_actions.pop_front() {
return Poll::Ready(action.build(poll_parameters));
return Poll::Ready(action.build(self.local_peer_id, &self.external_addresses));
}

Poll::Pending
}

fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
self.external_addresses.on_swarn_event(&event);

match event {
FromSwarm::ConnectionEstablished(connection_established) => {
self.on_connection_established(connection_established)
Expand Down Expand Up @@ -364,16 +371,15 @@ impl From<NetworkBehaviourAction<Event, handler::Prototype>> for ActionBuilder {
impl ActionBuilder {
fn build(
self,
poll_parameters: &mut impl PollParameters,
local_peer_id: PeerId,
external_addresses: &ExternalAddresses,
) -> NetworkBehaviourAction<Event, handler::Prototype> {
let obs_addrs = || {
poll_parameters
.external_addresses()
.filter(|a| !a.addr.iter().any(|p| p == Protocol::P2pCircuit))
.map(|a| {
a.addr
.with(Protocol::P2p((*poll_parameters.local_peer_id()).into()))
})
external_addresses
.iter()
.cloned()
.filter(|a| !a.iter().any(|p| p == Protocol::P2pCircuit))
.map(|a| a.with(Protocol::P2p(local_peer_id.into())))
.collect()
};

Expand Down
2 changes: 1 addition & 1 deletion protocols/dcutr/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ fn build_client() -> Swarm<Client> {
transport,
Client {
relay: behaviour,
dcutr: dcutr::behaviour::Behaviour::new(),
dcutr: dcutr::behaviour::Behaviour::new(local_peer_id),
},
local_peer_id,
)
Expand Down
31 changes: 22 additions & 9 deletions protocols/identify/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ use libp2p_core::{
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm};
use libp2p_swarm::{
dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError,
IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
ExternalAddresses, IntoConnectionHandler, ListenAddresses, NetworkBehaviour,
NetworkBehaviourAction, NotifyHandler, PollParameters,
};
use lru::LruCache;
use std::num::NonZeroUsize;
Expand Down Expand Up @@ -56,6 +57,9 @@ pub struct Behaviour {
events: VecDeque<NetworkBehaviourAction<Event, Proto>>,
/// The addresses of all peers that we have discovered.
discovered_peers: PeerCache,

listen_addresses: ListenAddresses,
external_addresses: ExternalAddresses,
}

/// A `Behaviour` request to be fulfilled, either `Handler` requests for `Behaviour` info
Expand Down Expand Up @@ -177,6 +181,8 @@ impl Behaviour {
requests: Vec::new(),
events: VecDeque::new(),
discovered_peers,
listen_addresses: Default::default(),
external_addresses: Default::default(),
}
}

Expand Down Expand Up @@ -318,7 +324,12 @@ impl NetworkBehaviour for Behaviour {
peer_id,
handler: NotifyHandler::Any,
event: InEvent {
listen_addrs: listen_addrs(params),
listen_addrs: self
.listen_addresses
.iter()
.chain(self.external_addresses.iter())
.cloned()
.collect(),
supported_protocols: supported_protocols(params),
protocol: Protocol::Push,
},
Expand All @@ -330,7 +341,12 @@ impl NetworkBehaviour for Behaviour {
peer_id,
handler: NotifyHandler::One(connection_id),
event: InEvent {
listen_addrs: listen_addrs(params),
listen_addrs: self
.listen_addresses
.iter()
.chain(self.external_addresses.iter())
.cloned()
.collect(),
supported_protocols: supported_protocols(params),
protocol: Protocol::Identify(connection_id),
},
Expand All @@ -344,6 +360,9 @@ impl NetworkBehaviour for Behaviour {
}

fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
self.listen_addresses.on_swarm_event(&event);
self.external_addresses.on_swarn_event(&event);

match event {
FromSwarm::ConnectionEstablished(connection_established) => {
self.on_connection_established(connection_established)
Expand Down Expand Up @@ -453,12 +472,6 @@ fn supported_protocols(params: &impl PollParameters) -> Vec<String> {
.collect()
}

fn listen_addrs(params: &impl PollParameters) -> Vec<Multiaddr> {
let mut listen_addrs: Vec<_> = params.external_addresses().map(|r| r.addr).collect();
listen_addrs.extend(params.listened_addresses());
listen_addrs
}

/// If there is a given peer_id in the multiaddr, make sure it is the same as
/// the given peer_id. If there is no peer_id for the peer in the mutiaddr, this returns true.
fn multiaddr_matches_peer_id(addr: &Multiaddr, peer_id: &PeerId) -> bool {
Expand Down
Loading