Skip to content

Commit be3ec6c

Browse files
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.
1 parent 5fe0dc4 commit be3ec6c

28 files changed

+282
-112
lines changed

examples/chat-tokio.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
9191
}
9292

9393
// Create a Swarm to manage peers and events.
94-
let mdns_behaviour = mdns::Behaviour::new(Default::default())?;
94+
let mdns_behaviour = mdns::Behaviour::new(Default::default(), peer_id)?;
9595
let behaviour = MyBehaviour {
9696
floodsub: Floodsub::new(peer_id),
9797
mdns: mdns_behaviour,

examples/chat.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
107107

108108
// Create a Swarm to manage peers and events
109109
let mut swarm = {
110-
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?;
110+
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
111111
let mut behaviour = MyBehaviour {
112112
floodsub: Floodsub::new(local_peer_id),
113113
mdns,

examples/distributed-key-value-store.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
9797
// Create a Kademlia behaviour.
9898
let store = MemoryStore::new(local_peer_id);
9999
let kademlia = Kademlia::new(local_peer_id, store);
100-
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?;
100+
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
101101
let behaviour = MyBehaviour { kademlia, mdns };
102102
Swarm::with_async_std_executor(transport, behaviour, local_peer_id)
103103
};

examples/gossipsub-chat.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
104104

105105
// Create a Swarm to manage peers and events
106106
let mut swarm = {
107-
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default())?;
107+
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
108108
let behaviour = MyBehaviour { gossipsub, mdns };
109109
Swarm::with_async_std_executor(transport, behaviour, local_peer_id)
110110
};

examples/mdns-passive-discovery.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
3939
let transport = libp2p::development_transport(id_keys).await?;
4040

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

4444
// Create a Swarm that establishes connections through the given transport.
4545
// Note that the MDNS behaviour itself will not actually inititiate any connections,

protocols/autonat/CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
# 0.10.0 [unreleased]
22

3+
- Require the node's local `PeerId` to be passed into the constructor of `libp2p_autonat::Behaviour`. See [PR 3153].
4+
35
- Update to `libp2p-request-response` `v0.24.0`.
46

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

9+
[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153
10+
711
# 0.9.0
812

913
- Update to `libp2p-core` `v0.38.0`.

protocols/autonat/src/behaviour.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ use libp2p_swarm::{
3939
AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr,
4040
ExpiredListenAddr, FromSwarm,
4141
},
42-
ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
43-
PollParameters,
42+
ConnectionHandler, ExternalAddresses, IntoConnectionHandler, ListenAddresses, NetworkBehaviour,
43+
NetworkBehaviourAction, PollParameters,
4444
};
4545
use std::{
4646
collections::{HashMap, VecDeque},
@@ -212,6 +212,9 @@ pub struct Behaviour {
212212
pending_out_events: VecDeque<<Self as NetworkBehaviour>::OutEvent>,
213213

214214
probe_id: ProbeId,
215+
216+
listen_addresses: ListenAddresses,
217+
external_addresses: ExternalAddresses,
215218
}
216219

217220
impl Behaviour {
@@ -236,6 +239,8 @@ impl Behaviour {
236239
last_probe: None,
237240
pending_out_events: VecDeque::new(),
238241
probe_id: ProbeId(0),
242+
listen_addresses: Default::default(),
243+
external_addresses: Default::default(),
239244
}
240245
}
241246

@@ -288,6 +293,8 @@ impl Behaviour {
288293
ongoing_outbound: &mut self.ongoing_outbound,
289294
last_probe: &mut self.last_probe,
290295
schedule_probe: &mut self.schedule_probe,
296+
listen_addresses: &self.listen_addresses,
297+
external_addresses: &self.external_addresses,
291298
}
292299
}
293300

@@ -457,7 +464,7 @@ impl NetworkBehaviour for Behaviour {
457464
Poll::Pending => is_inner_pending = true,
458465
}
459466

460-
match self.as_client().poll_auto_probe(params, cx) {
467+
match self.as_client().poll_auto_probe(cx) {
461468
Poll::Ready(event) => self
462469
.pending_out_events
463470
.push_back(Event::OutboundProbe(event)),
@@ -476,6 +483,9 @@ impl NetworkBehaviour for Behaviour {
476483
}
477484

478485
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
486+
self.listen_addresses.on_swarm_event(&event);
487+
self.external_addresses.on_swarn_event(&event);
488+
479489
match event {
480490
FromSwarm::ConnectionEstablished(connection_established) => {
481491
self.inner

protocols/autonat/src/behaviour/as_client.rs

+15-8
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ use futures_timer::Delay;
2929
use instant::Instant;
3030
use libp2p_core::{connection::ConnectionId, Multiaddr, PeerId};
3131
use libp2p_request_response::{self as request_response, OutboundFailure, RequestId};
32-
use libp2p_swarm::{AddressScore, NetworkBehaviourAction, PollParameters};
32+
use libp2p_swarm::{
33+
AddressScore, ExternalAddresses, ListenAddresses, NetworkBehaviourAction, PollParameters,
34+
};
3335
use rand::{seq::SliceRandom, thread_rng};
3436
use std::{
3537
collections::{HashMap, VecDeque},
@@ -97,6 +99,9 @@ pub struct AsClient<'a> {
9799

98100
pub last_probe: &'a mut Option<Instant>,
99101
pub schedule_probe: &'a mut Delay,
102+
103+
pub listen_addresses: &'a ListenAddresses,
104+
pub external_addresses: &'a ExternalAddresses,
100105
}
101106

102107
impl<'a> HandleInnerEvent for AsClient<'a> {
@@ -146,6 +151,8 @@ impl<'a> HandleInnerEvent for AsClient<'a> {
146151

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

190197
impl<'a> AsClient<'a> {
191-
pub fn poll_auto_probe(
192-
&mut self,
193-
params: &mut impl PollParameters,
194-
cx: &mut Context<'_>,
195-
) -> Poll<OutboundProbeEvent> {
198+
pub fn poll_auto_probe(&mut self, cx: &mut Context<'_>) -> Poll<OutboundProbeEvent> {
196199
match self.schedule_probe.poll_unpin(cx) {
197200
Poll::Ready(()) => {
198201
self.schedule_probe.reset(self.config.retry_interval);
199202

200-
let mut addresses: Vec<_> = params.external_addresses().map(|r| r.addr).collect();
201-
addresses.extend(params.listened_addresses());
203+
let addresses = self
204+
.external_addresses
205+
.iter()
206+
.chain(self.listen_addresses.iter())
207+
.cloned()
208+
.collect();
202209

203210
let probe_id = self.probe_id.next();
204211
let event = match self.do_probe(probe_id, addresses) {

protocols/dcutr/CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55
- Declare `InboundUpgradeError` and `OutboundUpgradeError` as type aliases instead of renames.
66
This is a workaround for a missing feature in `cargo semver-checks`. See [PR 3213].
77

8+
- Require the node's local `PeerId` to be passed into the constructor of `libp2p_dcutr::Behaviour`. See [PR 3153].
9+
810
[PR 3213]: https://github.com/libp2p/rust-libp2p/pull/3213
11+
[PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153
912

1013
# 0.8.0
1114

protocols/dcutr/examples/dcutr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ fn main() -> Result<(), Box<dyn Error>> {
157157
"/TODO/0.0.1".to_string(),
158158
local_key.public(),
159159
)),
160-
dcutr: dcutr::behaviour::Behaviour::new(),
160+
dcutr: dcutr::behaviour::Behaviour::new(local_peer_id),
161161
};
162162

163163
let mut swarm = match ThreadPool::new() {

protocols/dcutr/src/behaviour.rs

+20-14
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ use libp2p_core::{Multiaddr, PeerId};
2929
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm};
3030
use libp2p_swarm::dial_opts::{self, DialOpts};
3131
use libp2p_swarm::{
32-
ConnectionHandler, ConnectionHandlerUpgrErr, IntoConnectionHandler, NetworkBehaviour,
33-
NetworkBehaviourAction, NotifyHandler, PollParameters,
32+
ConnectionHandler, ConnectionHandlerUpgrErr, ExternalAddresses, IntoConnectionHandler,
33+
NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
3434
};
3535
use std::collections::{HashMap, HashSet, VecDeque};
3636
use std::task::{Context, Poll};
@@ -66,20 +66,25 @@ pub enum UpgradeError {
6666
Handler(ConnectionHandlerUpgrErr<void::Void>),
6767
}
6868

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

7473
/// All direct (non-relayed) connections.
7574
direct_connections: HashMap<PeerId, HashSet<ConnectionId>>,
75+
76+
external_addresses: ExternalAddresses,
77+
78+
local_peer_id: PeerId,
7679
}
7780

7881
impl Behaviour {
79-
pub fn new() -> Self {
82+
pub fn new(local_peer_id: PeerId) -> Self {
8083
Behaviour {
8184
queued_actions: Default::default(),
8285
direct_connections: Default::default(),
86+
external_addresses: Default::default(),
87+
local_peer_id,
8388
}
8489
}
8590

@@ -308,16 +313,18 @@ impl NetworkBehaviour for Behaviour {
308313
fn poll(
309314
&mut self,
310315
_cx: &mut Context<'_>,
311-
poll_parameters: &mut impl PollParameters,
316+
_: &mut impl PollParameters,
312317
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
313318
if let Some(action) = self.queued_actions.pop_front() {
314-
return Poll::Ready(action.build(poll_parameters));
319+
return Poll::Ready(action.build(self.local_peer_id, &self.external_addresses));
315320
}
316321

317322
Poll::Pending
318323
}
319324

320325
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
326+
self.external_addresses.on_swarn_event(&event);
327+
321328
match event {
322329
FromSwarm::ConnectionEstablished(connection_established) => {
323330
self.on_connection_established(connection_established)
@@ -364,16 +371,15 @@ impl From<NetworkBehaviourAction<Event, handler::Prototype>> for ActionBuilder {
364371
impl ActionBuilder {
365372
fn build(
366373
self,
367-
poll_parameters: &mut impl PollParameters,
374+
local_peer_id: PeerId,
375+
external_addresses: &ExternalAddresses,
368376
) -> NetworkBehaviourAction<Event, handler::Prototype> {
369377
let obs_addrs = || {
370-
poll_parameters
371-
.external_addresses()
372-
.filter(|a| !a.addr.iter().any(|p| p == Protocol::P2pCircuit))
373-
.map(|a| {
374-
a.addr
375-
.with(Protocol::P2p((*poll_parameters.local_peer_id()).into()))
376-
})
378+
external_addresses
379+
.iter()
380+
.cloned()
381+
.filter(|a| !a.iter().any(|p| p == Protocol::P2pCircuit))
382+
.map(|a| a.with(Protocol::P2p(local_peer_id.into())))
377383
.collect()
378384
};
379385

protocols/dcutr/tests/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ fn build_client() -> Swarm<Client> {
126126
transport,
127127
Client {
128128
relay: behaviour,
129-
dcutr: dcutr::behaviour::Behaviour::new(),
129+
dcutr: dcutr::behaviour::Behaviour::new(local_peer_id),
130130
},
131131
local_peer_id,
132132
)

protocols/identify/src/behaviour.rs

+22-9
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ use libp2p_core::{
2626
use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm};
2727
use libp2p_swarm::{
2828
dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError,
29-
IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
29+
ExternalAddresses, IntoConnectionHandler, ListenAddresses, NetworkBehaviour,
30+
NetworkBehaviourAction, NotifyHandler, PollParameters,
3031
};
3132
use lru::LruCache;
3233
use std::num::NonZeroUsize;
@@ -56,6 +57,9 @@ pub struct Behaviour {
5657
events: VecDeque<NetworkBehaviourAction<Event, Proto>>,
5758
/// The addresses of all peers that we have discovered.
5859
discovered_peers: PeerCache,
60+
61+
listen_addresses: ListenAddresses,
62+
external_addresses: ExternalAddresses,
5963
}
6064

6165
/// A `Behaviour` request to be fulfilled, either `Handler` requests for `Behaviour` info
@@ -177,6 +181,8 @@ impl Behaviour {
177181
requests: Vec::new(),
178182
events: VecDeque::new(),
179183
discovered_peers,
184+
listen_addresses: Default::default(),
185+
external_addresses: Default::default(),
180186
}
181187
}
182188

@@ -318,7 +324,12 @@ impl NetworkBehaviour for Behaviour {
318324
peer_id,
319325
handler: NotifyHandler::Any,
320326
event: InEvent {
321-
listen_addrs: listen_addrs(params),
327+
listen_addrs: self
328+
.listen_addresses
329+
.iter()
330+
.chain(self.external_addresses.iter())
331+
.cloned()
332+
.collect(),
322333
supported_protocols: supported_protocols(params),
323334
protocol: Protocol::Push,
324335
},
@@ -330,7 +341,12 @@ impl NetworkBehaviour for Behaviour {
330341
peer_id,
331342
handler: NotifyHandler::One(connection_id),
332343
event: InEvent {
333-
listen_addrs: listen_addrs(params),
344+
listen_addrs: self
345+
.listen_addresses
346+
.iter()
347+
.chain(self.external_addresses.iter())
348+
.cloned()
349+
.collect(),
334350
supported_protocols: supported_protocols(params),
335351
protocol: Protocol::Identify(connection_id),
336352
},
@@ -344,6 +360,9 @@ impl NetworkBehaviour for Behaviour {
344360
}
345361

346362
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
363+
self.listen_addresses.on_swarm_event(&event);
364+
self.external_addresses.on_swarn_event(&event);
365+
347366
match event {
348367
FromSwarm::ConnectionEstablished(connection_established) => {
349368
self.on_connection_established(connection_established)
@@ -453,12 +472,6 @@ fn supported_protocols(params: &impl PollParameters) -> Vec<String> {
453472
.collect()
454473
}
455474

456-
fn listen_addrs(params: &impl PollParameters) -> Vec<Multiaddr> {
457-
let mut listen_addrs: Vec<_> = params.external_addresses().map(|r| r.addr).collect();
458-
listen_addrs.extend(params.listened_addresses());
459-
listen_addrs
460-
}
461-
462475
/// If there is a given peer_id in the multiaddr, make sure it is the same as
463476
/// the given peer_id. If there is no peer_id for the peer in the mutiaddr, this returns true.
464477
fn multiaddr_matches_peer_id(addr: &Multiaddr, peer_id: &PeerId) -> bool {

0 commit comments

Comments
 (0)