protocols/identify: Revise symbol naming (#2927)

This commit is contained in:
João Oliveira 2022-10-04 01:17:31 +01:00 committed by GitHub
parent 1da75b2b25
commit a7a96e5502
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 253 additions and 240 deletions

View File

@ -77,6 +77,8 @@
- [PR 2918]: https://github.com/libp2p/rust-libp2p/pull/2918 - [PR 2918]: https://github.com/libp2p/rust-libp2p/pull/2918
- Update to [`libp2p-identify` `v0.39.1`](protocols/identify/CHANGELOG.md#0391).
# 0.48.0 # 0.48.0
- Update to [`libp2p-core` `v0.36.0`](core/CHANGELOG.md#0360). - Update to [`libp2p-core` `v0.36.0`](core/CHANGELOG.md#0360).

View File

@ -39,8 +39,7 @@ use libp2p::{
either::EitherTransport, muxing::StreamMuxerBox, transport, transport::upgrade::Version, either::EitherTransport, muxing::StreamMuxerBox, transport, transport::upgrade::Version,
}, },
gossipsub::{self, Gossipsub, GossipsubConfigBuilder, GossipsubEvent, MessageAuthenticity}, gossipsub::{self, Gossipsub, GossipsubConfigBuilder, GossipsubEvent, MessageAuthenticity},
identify::{Identify, IdentifyConfig, IdentifyEvent}, identify, identity,
identity,
multiaddr::Protocol, multiaddr::Protocol,
noise, ping, noise, ping,
pnet::{PnetConfig, PreSharedKey}, pnet::{PnetConfig, PreSharedKey},
@ -157,13 +156,13 @@ async fn main() -> Result<(), Box<dyn Error>> {
#[behaviour(out_event = "MyBehaviourEvent")] #[behaviour(out_event = "MyBehaviourEvent")]
struct MyBehaviour { struct MyBehaviour {
gossipsub: Gossipsub, gossipsub: Gossipsub,
identify: Identify, identify: identify::Behaviour,
ping: ping::Behaviour, ping: ping::Behaviour,
} }
enum MyBehaviourEvent { enum MyBehaviourEvent {
Gossipsub(GossipsubEvent), Gossipsub(GossipsubEvent),
Identify(IdentifyEvent), Identify(identify::Event),
Ping(ping::Event), Ping(ping::Event),
} }
@ -173,8 +172,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
} }
} }
impl From<IdentifyEvent> for MyBehaviourEvent { impl From<identify::Event> for MyBehaviourEvent {
fn from(event: IdentifyEvent) -> Self { fn from(event: identify::Event) -> Self {
MyBehaviourEvent::Identify(event) MyBehaviourEvent::Identify(event)
} }
} }
@ -197,7 +196,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
gossipsub_config, gossipsub_config,
) )
.expect("Valid configuration"), .expect("Valid configuration"),
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"/ipfs/0.1.0".into(), "/ipfs/0.1.0".into(),
local_key.public(), local_key.public(),
)), )),

View File

@ -1,7 +1,7 @@
# 0.10.0 [unreleased] # 0.10.0 [unreleased]
- Update to `libp2p-kad` `v0.41.0`. - Update to `libp2p-kad` `v0.41.0`.
-
- Update to `libp2p-identify` `v0.39.1`. - Update to `libp2p-identify` `v0.39.1`.
- Update to `libp2p-swarm` `v0.40.0`. - Update to `libp2p-swarm` `v0.40.0`.

View File

@ -112,16 +112,16 @@ impl Metrics {
} }
} }
impl super::Recorder<libp2p_identify::IdentifyEvent> for Metrics { impl super::Recorder<libp2p_identify::Event> for Metrics {
fn record(&self, event: &libp2p_identify::IdentifyEvent) { fn record(&self, event: &libp2p_identify::Event) {
match event { match event {
libp2p_identify::IdentifyEvent::Error { .. } => { libp2p_identify::Event::Error { .. } => {
self.error.inc(); self.error.inc();
} }
libp2p_identify::IdentifyEvent::Pushed { .. } => { libp2p_identify::Event::Pushed { .. } => {
self.pushed.inc(); self.pushed.inc();
} }
libp2p_identify::IdentifyEvent::Received { peer_id, info, .. } => { libp2p_identify::Event::Received { peer_id, info, .. } => {
{ {
let mut protocols: Vec<String> = info let mut protocols: Vec<String> = info
.protocols .protocols
@ -168,7 +168,7 @@ impl super::Recorder<libp2p_identify::IdentifyEvent> for Metrics {
self.received_info_listen_addrs self.received_info_listen_addrs
.observe(info.listen_addrs.len() as f64); .observe(info.listen_addrs.len() as f64);
} }
libp2p_identify::IdentifyEvent::Sent { .. } => { libp2p_identify::Event::Sent { .. } => {
self.sent.inc(); self.sent.inc();
} }
} }

View File

@ -112,8 +112,8 @@ impl Recorder<libp2p_gossipsub::GossipsubEvent> for Metrics {
} }
#[cfg(feature = "identify")] #[cfg(feature = "identify")]
impl Recorder<libp2p_identify::IdentifyEvent> for Metrics { impl Recorder<libp2p_identify::Event> for Metrics {
fn record(&self, event: &libp2p_identify::IdentifyEvent) { fn record(&self, event: &libp2p_identify::Event) {
self.identify.record(event) self.identify.record(event)
} }
} }

View File

@ -32,7 +32,7 @@
use clap::Parser; use clap::Parser;
use futures::prelude::*; use futures::prelude::*;
use libp2p::autonat; use libp2p::autonat;
use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent}; use libp2p::identify;
use libp2p::multiaddr::Protocol; use libp2p::multiaddr::Protocol;
use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::{identity, Multiaddr, NetworkBehaviour, PeerId}; use libp2p::{identity, Multiaddr, NetworkBehaviour, PeerId};
@ -91,14 +91,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
#[derive(NetworkBehaviour)] #[derive(NetworkBehaviour)]
#[behaviour(out_event = "Event")] #[behaviour(out_event = "Event")]
struct Behaviour { struct Behaviour {
identify: Identify, identify: identify::Behaviour,
auto_nat: autonat::Behaviour, auto_nat: autonat::Behaviour,
} }
impl Behaviour { impl Behaviour {
fn new(local_public_key: identity::PublicKey) -> Self { fn new(local_public_key: identity::PublicKey) -> Self {
Self { Self {
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"/ipfs/0.1.0".into(), "/ipfs/0.1.0".into(),
local_public_key.clone(), local_public_key.clone(),
)), )),
@ -119,11 +119,11 @@ impl Behaviour {
#[derive(Debug)] #[derive(Debug)]
enum Event { enum Event {
AutoNat(autonat::Event), AutoNat(autonat::Event),
Identify(IdentifyEvent), Identify(identify::Event),
} }
impl From<IdentifyEvent> for Event { impl From<identify::Event> for Event {
fn from(v: IdentifyEvent) -> Self { fn from(v: identify::Event) -> Self {
Self::Identify(v) Self::Identify(v)
} }
} }

View File

@ -29,7 +29,7 @@
use clap::Parser; use clap::Parser;
use futures::prelude::*; use futures::prelude::*;
use libp2p::autonat; use libp2p::autonat;
use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent}; use libp2p::identify;
use libp2p::multiaddr::Protocol; use libp2p::multiaddr::Protocol;
use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::{identity, Multiaddr, NetworkBehaviour, PeerId}; use libp2p::{identity, Multiaddr, NetworkBehaviour, PeerId};
@ -76,14 +76,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
#[derive(NetworkBehaviour)] #[derive(NetworkBehaviour)]
#[behaviour(out_event = "Event")] #[behaviour(out_event = "Event")]
struct Behaviour { struct Behaviour {
identify: Identify, identify: identify::Behaviour,
auto_nat: autonat::Behaviour, auto_nat: autonat::Behaviour,
} }
impl Behaviour { impl Behaviour {
fn new(local_public_key: identity::PublicKey) -> Self { fn new(local_public_key: identity::PublicKey) -> Self {
Self { Self {
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"/ipfs/0.1.0".into(), "/ipfs/0.1.0".into(),
local_public_key.clone(), local_public_key.clone(),
)), )),
@ -98,11 +98,11 @@ impl Behaviour {
#[derive(Debug)] #[derive(Debug)]
enum Event { enum Event {
AutoNat(autonat::Event), AutoNat(autonat::Event),
Identify(IdentifyEvent), Identify(identify::Event),
} }
impl From<IdentifyEvent> for Event { impl From<identify::Event> for Event {
fn from(v: IdentifyEvent) -> Self { fn from(v: identify::Event) -> Self {
Self::Identify(v) Self::Identify(v)
} }
} }

View File

@ -26,7 +26,7 @@ use libp2p::core::multiaddr::{Multiaddr, Protocol};
use libp2p::core::transport::OrTransport; use libp2p::core::transport::OrTransport;
use libp2p::core::upgrade; use libp2p::core::upgrade;
use libp2p::dns::DnsConfig; use libp2p::dns::DnsConfig;
use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent, IdentifyInfo}; use libp2p::identify;
use libp2p::noise; use libp2p::noise;
use libp2p::relay::v2::client::{self, Client}; use libp2p::relay::v2::client::{self, Client};
use libp2p::swarm::{SwarmBuilder, SwarmEvent}; use libp2p::swarm::{SwarmBuilder, SwarmEvent};
@ -108,14 +108,14 @@ fn main() -> Result<(), Box<dyn Error>> {
struct Behaviour { struct Behaviour {
relay_client: Client, relay_client: Client,
ping: ping::Behaviour, ping: ping::Behaviour,
identify: Identify, identify: identify::Behaviour,
dcutr: dcutr::behaviour::Behaviour, dcutr: dcutr::behaviour::Behaviour,
} }
#[derive(Debug)] #[derive(Debug)]
enum Event { enum Event {
Ping(ping::Event), Ping(ping::Event),
Identify(IdentifyEvent), Identify(identify::Event),
Relay(client::Event), Relay(client::Event),
Dcutr(dcutr::behaviour::Event), Dcutr(dcutr::behaviour::Event),
} }
@ -126,8 +126,8 @@ fn main() -> Result<(), Box<dyn Error>> {
} }
} }
impl From<IdentifyEvent> for Event { impl From<identify::Event> for Event {
fn from(e: IdentifyEvent) -> Self { fn from(e: identify::Event) -> Self {
Event::Identify(e) Event::Identify(e)
} }
} }
@ -147,7 +147,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let behaviour = Behaviour { let behaviour = Behaviour {
relay_client: client, relay_client: client,
ping: ping::Behaviour::new(ping::Config::new()), ping: ping::Behaviour::new(ping::Config::new()),
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"/TODO/0.0.1".to_string(), "/TODO/0.0.1".to_string(),
local_key.public(), local_key.public(),
)), )),
@ -200,12 +200,12 @@ fn main() -> Result<(), Box<dyn Error>> {
SwarmEvent::Dialing { .. } => {} SwarmEvent::Dialing { .. } => {}
SwarmEvent::ConnectionEstablished { .. } => {} SwarmEvent::ConnectionEstablished { .. } => {}
SwarmEvent::Behaviour(Event::Ping(_)) => {} SwarmEvent::Behaviour(Event::Ping(_)) => {}
SwarmEvent::Behaviour(Event::Identify(IdentifyEvent::Sent { .. })) => { SwarmEvent::Behaviour(Event::Identify(identify::Event::Sent { .. })) => {
info!("Told relay its public address."); info!("Told relay its public address.");
told_relay_observed_addr = true; told_relay_observed_addr = true;
} }
SwarmEvent::Behaviour(Event::Identify(IdentifyEvent::Received { SwarmEvent::Behaviour(Event::Identify(identify::Event::Received {
info: IdentifyInfo { observed_addr, .. }, info: identify::Info { observed_addr, .. },
.. ..
})) => { })) => {
info!("Relay told us our public address: {:?}", observed_addr); info!("Relay told us our public address: {:?}", observed_addr);

View File

@ -2,6 +2,14 @@
- Update dependencies. - Update dependencies.
- Rename types as per [discussion 2174].
`Identify` has been renamed to `Behaviour`.
The `Identify` prefix has been removed from various types like `IdentifyEvent`.
Users should prefer importing the identify protocol as a module (`use libp2p::identify;`),
and refer to its types via `identify::`. For example: `identify::Behaviour` or `identify::Event`.
[discussion 2174]: https://github.com/libp2p/rust-libp2p/discussions/2174
- Update to `libp2p-core` `v0.37.0`. - Update to `libp2p-core` `v0.37.0`.
- Update to `libp2p-swarm` `v0.40.0`. - Update to `libp2p-swarm` `v0.40.0`.

View File

@ -37,8 +37,7 @@
//! and will send each other identify info which is then printed to the console. //! and will send each other identify info which is then printed to the console.
use futures::prelude::*; use futures::prelude::*;
use libp2p::{identity, Multiaddr, PeerId}; use libp2p::{identify, identity, Multiaddr, PeerId};
use libp2p_identify::{Identify, IdentifyConfig, IdentifyEvent};
use libp2p_swarm::{Swarm, SwarmEvent}; use libp2p_swarm::{Swarm, SwarmEvent};
use std::error::Error; use std::error::Error;
@ -51,7 +50,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let transport = libp2p::development_transport(local_key.clone()).await?; let transport = libp2p::development_transport(local_key.clone()).await?;
// Create a identify network behaviour. // Create a identify network behaviour.
let behaviour = Identify::new(IdentifyConfig::new( let behaviour = identify::Behaviour::new(identify::Config::new(
"/ipfs/id/1.0.0".to_string(), "/ipfs/id/1.0.0".to_string(),
local_key.public(), local_key.public(),
)); ));
@ -74,11 +73,11 @@ async fn main() -> Result<(), Box<dyn Error>> {
match swarm.select_next_some().await { match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address), SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address),
// Prints peer id identify info is being sent to. // Prints peer id identify info is being sent to.
SwarmEvent::Behaviour(IdentifyEvent::Sent { peer_id, .. }) => { SwarmEvent::Behaviour(identify::Event::Sent { peer_id, .. }) => {
println!("Sent identify info to {:?}", peer_id) println!("Sent identify info to {:?}", peer_id)
} }
// Prints out the info received via the identify event // Prints out the info received via the identify event
SwarmEvent::Behaviour(IdentifyEvent::Received { info, .. }) => { SwarmEvent::Behaviour(identify::Event::Received { info, .. }) => {
println!("Received {:?}", info) println!("Received {:?}", info)
} }
_ => {} _ => {}

View File

@ -18,8 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::handler::{IdentifyHandlerEvent, IdentifyHandlerProto, IdentifyPush}; use crate::handler::{self, Proto, Push};
use crate::protocol::{IdentifyInfo, ReplySubstream, UpgradeError}; use crate::protocol::{Info, ReplySubstream, UpgradeError};
use futures::prelude::*; use futures::prelude::*;
use libp2p_core::{ use libp2p_core::{
connection::ConnectionId, multiaddr::Protocol, transport::ListenerId, ConnectedPoint, connection::ConnectionId, multiaddr::Protocol, transport::ListenerId, ConnectedPoint,
@ -47,14 +47,14 @@ use std::{
/// All external addresses of the local node supposedly observed by remotes /// All external addresses of the local node supposedly observed by remotes
/// are reported via [`NetworkBehaviourAction::ReportObservedAddr`] with a /// are reported via [`NetworkBehaviourAction::ReportObservedAddr`] with a
/// [score](AddressScore) of `1`. /// [score](AddressScore) of `1`.
pub struct Identify { pub struct Behaviour {
config: IdentifyConfig, config: Config,
/// For each peer we're connected to, the observed address to send back to it. /// For each peer we're connected to, the observed address to send back to it.
connected: HashMap<PeerId, HashMap<ConnectionId, Multiaddr>>, connected: HashMap<PeerId, HashMap<ConnectionId, Multiaddr>>,
/// Pending replies to send. /// Pending replies to send.
pending_replies: VecDeque<Reply>, pending_replies: VecDeque<Reply>,
/// Pending events to be emitted when polled. /// Pending events to be emitted when polled.
events: VecDeque<NetworkBehaviourAction<IdentifyEvent, IdentifyHandlerProto>>, events: VecDeque<NetworkBehaviourAction<Event, Proto>>,
/// Peers to which an active push with current information about /// Peers to which an active push with current information about
/// the local peer should be sent. /// the local peer should be sent.
pending_push: HashSet<PeerId>, pending_push: HashSet<PeerId>,
@ -77,10 +77,10 @@ enum Reply {
}, },
} }
/// Configuration for the [`Identify`] [`NetworkBehaviour`]. /// Configuration for the [`identify::Behaviour`](Behaviour).
#[non_exhaustive] #[non_exhaustive]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct IdentifyConfig { pub struct Config {
/// Application-specific version of the protocol family used by the peer, /// Application-specific version of the protocol family used by the peer,
/// e.g. `ipfs/1.0.0` or `polkadot/1.0.0`. /// e.g. `ipfs/1.0.0` or `polkadot/1.0.0`.
pub protocol_version: String, pub protocol_version: String,
@ -120,11 +120,11 @@ pub struct IdentifyConfig {
pub cache_size: usize, pub cache_size: usize,
} }
impl IdentifyConfig { impl Config {
/// Creates a new configuration for the `Identify` behaviour that /// Creates a new configuration for the identify [`Behaviour`] that
/// advertises the given protocol version and public key. /// advertises the given protocol version and public key.
pub fn new(protocol_version: String, local_public_key: PublicKey) -> Self { pub fn new(protocol_version: String, local_public_key: PublicKey) -> Self {
IdentifyConfig { Self {
protocol_version, protocol_version,
agent_version: format!("rust-libp2p/{}", env!("CARGO_PKG_VERSION")), agent_version: format!("rust-libp2p/{}", env!("CARGO_PKG_VERSION")),
local_public_key, local_public_key,
@ -166,22 +166,22 @@ impl IdentifyConfig {
/// Configures the size of the LRU cache, caching addresses of discovered peers. /// Configures the size of the LRU cache, caching addresses of discovered peers.
/// ///
/// The [`Swarm`](libp2p_swarm::Swarm) may extend the set of addresses of an outgoing connection attempt via /// The [`Swarm`](libp2p_swarm::Swarm) may extend the set of addresses of an outgoing connection attempt via
/// [`Identify::addresses_of_peer`]. /// [`Behaviour::addresses_of_peer`].
pub fn with_cache_size(mut self, cache_size: usize) -> Self { pub fn with_cache_size(mut self, cache_size: usize) -> Self {
self.cache_size = cache_size; self.cache_size = cache_size;
self self
} }
} }
impl Identify { impl Behaviour {
/// Creates a new `Identify` network behaviour. /// Creates a new identify [`Behaviour`].
pub fn new(config: IdentifyConfig) -> Self { pub fn new(config: Config) -> Self {
let discovered_peers = match NonZeroUsize::new(config.cache_size) { let discovered_peers = match NonZeroUsize::new(config.cache_size) {
None => PeerCache::disabled(), None => PeerCache::disabled(),
Some(size) => PeerCache::enabled(size), Some(size) => PeerCache::enabled(size),
}; };
Identify { Self {
config, config,
connected: HashMap::new(), connected: HashMap::new(),
pending_replies: VecDeque::new(), pending_replies: VecDeque::new(),
@ -208,12 +208,12 @@ impl Identify {
} }
} }
impl NetworkBehaviour for Identify { impl NetworkBehaviour for Behaviour {
type ConnectionHandler = IdentifyHandlerProto; type ConnectionHandler = Proto;
type OutEvent = IdentifyEvent; type OutEvent = Event;
fn new_handler(&mut self) -> Self::ConnectionHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
IdentifyHandlerProto::new(self.config.initial_delay, self.config.interval) Proto::new(self.config.initial_delay, self.config.interval)
} }
fn inject_connection_established( fn inject_connection_established(
@ -300,7 +300,7 @@ impl NetworkBehaviour for Identify {
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent, event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
) { ) {
match event { match event {
IdentifyHandlerEvent::Identified(mut info) => { handler::Event::Identified(mut info) => {
// Remove invalid multiaddrs. // Remove invalid multiaddrs.
info.listen_addrs info.listen_addrs
.retain(|addr| multiaddr_matches_peer_id(addr, &peer_id)); .retain(|addr| multiaddr_matches_peer_id(addr, &peer_id));
@ -310,21 +310,24 @@ impl NetworkBehaviour for Identify {
.put(peer_id, info.listen_addrs.iter().cloned()); .put(peer_id, info.listen_addrs.iter().cloned());
let observed = info.observed_addr.clone(); let observed = info.observed_addr.clone();
self.events.push_back(NetworkBehaviourAction::GenerateEvent( self.events
IdentifyEvent::Received { peer_id, info }, .push_back(NetworkBehaviourAction::GenerateEvent(Event::Received {
)); peer_id,
info,
}));
self.events self.events
.push_back(NetworkBehaviourAction::ReportObservedAddr { .push_back(NetworkBehaviourAction::ReportObservedAddr {
address: observed, address: observed,
score: AddressScore::Finite(1), score: AddressScore::Finite(1),
}); });
} }
IdentifyHandlerEvent::IdentificationPushed => { handler::Event::IdentificationPushed => {
self.events.push_back(NetworkBehaviourAction::GenerateEvent( self.events
IdentifyEvent::Pushed { peer_id }, .push_back(NetworkBehaviourAction::GenerateEvent(Event::Pushed {
)); peer_id,
}));
} }
IdentifyHandlerEvent::Identify(sender) => { handler::Event::Identify(sender) => {
let observed = self let observed = self
.connected .connected
.get(&peer_id) .get(&peer_id)
@ -339,10 +342,12 @@ impl NetworkBehaviour for Identify {
observed: observed.clone(), observed: observed.clone(),
}); });
} }
IdentifyHandlerEvent::IdentificationError(error) => { handler::Event::IdentificationError(error) => {
self.events.push_back(NetworkBehaviourAction::GenerateEvent( self.events
IdentifyEvent::Error { peer_id, error }, .push_back(NetworkBehaviourAction::GenerateEvent(Event::Error {
)); peer_id,
error,
}));
} }
} }
} }
@ -368,7 +373,7 @@ impl NetworkBehaviour for Identify {
let listen_addrs = listen_addrs(params); let listen_addrs = listen_addrs(params);
let protocols = supported_protocols(params); let protocols = supported_protocols(params);
let info = IdentifyInfo { let info = Info {
public_key: self.config.local_public_key.clone(), public_key: self.config.local_public_key.clone(),
protocol_version: self.config.protocol_version.clone(), protocol_version: self.config.protocol_version.clone(),
agent_version: self.config.agent_version.clone(), agent_version: self.config.agent_version.clone(),
@ -377,7 +382,7 @@ impl NetworkBehaviour for Identify {
observed_addr, observed_addr,
}; };
(*peer, IdentifyPush(info)) (*peer, Push(info))
}) })
}); });
@ -398,7 +403,7 @@ impl NetworkBehaviour for Identify {
loop { loop {
match reply { match reply {
Some(Reply::Queued { peer, io, observed }) => { Some(Reply::Queued { peer, io, observed }) => {
let info = IdentifyInfo { let info = Info {
listen_addrs: listen_addrs(params), listen_addrs: listen_addrs(params),
protocols: supported_protocols(params), protocols: supported_protocols(params),
public_key: self.config.local_public_key.clone(), public_key: self.config.local_public_key.clone(),
@ -413,7 +418,7 @@ impl NetworkBehaviour for Identify {
sending += 1; sending += 1;
match Future::poll(Pin::new(&mut io), cx) { match Future::poll(Pin::new(&mut io), cx) {
Poll::Ready(Ok(())) => { Poll::Ready(Ok(())) => {
let event = IdentifyEvent::Sent { peer_id: peer }; let event = Event::Sent { peer_id: peer };
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
} }
Poll::Pending => { Poll::Pending => {
@ -426,7 +431,7 @@ impl NetworkBehaviour for Identify {
} }
} }
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
let event = IdentifyEvent::Error { let event = Event::Error {
peer_id: peer, peer_id: peer,
error: ConnectionHandlerUpgrErr::Upgrade( error: ConnectionHandlerUpgrErr::Upgrade(
libp2p_core::upgrade::UpgradeError::Apply(err), libp2p_core::upgrade::UpgradeError::Apply(err),
@ -452,13 +457,13 @@ impl NetworkBehaviour for Identify {
/// Event emitted by the `Identify` behaviour. /// Event emitted by the `Identify` behaviour.
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
#[derive(Debug)] #[derive(Debug)]
pub enum IdentifyEvent { pub enum Event {
/// Identification information has been received from a peer. /// Identification information has been received from a peer.
Received { Received {
/// The peer that has been identified. /// The peer that has been identified.
peer_id: PeerId, peer_id: PeerId,
/// The information provided by the peer. /// The information provided by the peer.
info: IdentifyInfo, info: Info,
}, },
/// Identification information of the local node has been sent to a peer in /// Identification information of the local node has been sent to a peer in
/// response to an identification request. /// response to an identification request.
@ -576,9 +581,8 @@ mod tests {
fn periodic_identify() { fn periodic_identify() {
let (mut swarm1, pubkey1) = { let (mut swarm1, pubkey1) = {
let (pubkey, transport) = transport(); let (pubkey, transport) = transport();
let protocol = Identify::new( let protocol = Behaviour::new(
IdentifyConfig::new("a".to_string(), pubkey.clone()) Config::new("a".to_string(), pubkey.clone()).with_agent_version("b".to_string()),
.with_agent_version("b".to_string()),
); );
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id()); let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
(swarm, pubkey) (swarm, pubkey)
@ -586,9 +590,8 @@ mod tests {
let (mut swarm2, pubkey2) = { let (mut swarm2, pubkey2) = {
let (pubkey, transport) = transport(); let (pubkey, transport) = transport();
let protocol = Identify::new( let protocol = Behaviour::new(
IdentifyConfig::new("c".to_string(), pubkey.clone()) Config::new("c".to_string(), pubkey.clone()).with_agent_version("d".to_string()),
.with_agent_version("d".to_string()),
); );
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id()); let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
(swarm, pubkey) (swarm, pubkey)
@ -626,9 +629,8 @@ mod tests {
.factor_second() .factor_second()
.0 .0
{ {
future::Either::Left(SwarmEvent::Behaviour(IdentifyEvent::Received { future::Either::Left(SwarmEvent::Behaviour(Event::Received {
info, info, ..
..
})) => { })) => {
assert_eq!(info.public_key, pubkey2); assert_eq!(info.public_key, pubkey2);
assert_eq!(info.protocol_version, "c"); assert_eq!(info.protocol_version, "c");
@ -637,9 +639,8 @@ mod tests {
assert!(info.listen_addrs.is_empty()); assert!(info.listen_addrs.is_empty());
return; return;
} }
future::Either::Right(SwarmEvent::Behaviour(IdentifyEvent::Received { future::Either::Right(SwarmEvent::Behaviour(Event::Received {
info, info, ..
..
})) => { })) => {
assert_eq!(info.public_key, pubkey1); assert_eq!(info.public_key, pubkey1);
assert_eq!(info.protocol_version, "a"); assert_eq!(info.protocol_version, "a");
@ -660,16 +661,15 @@ mod tests {
let (mut swarm1, pubkey1) = { let (mut swarm1, pubkey1) = {
let (pubkey, transport) = transport(); let (pubkey, transport) = transport();
let protocol = Identify::new(IdentifyConfig::new("a".to_string(), pubkey.clone())); let protocol = Behaviour::new(Config::new("a".to_string(), pubkey.clone()));
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id()); let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
(swarm, pubkey) (swarm, pubkey)
}; };
let (mut swarm2, pubkey2) = { let (mut swarm2, pubkey2) = {
let (pubkey, transport) = transport(); let (pubkey, transport) = transport();
let protocol = Identify::new( let protocol = Behaviour::new(
IdentifyConfig::new("a".to_string(), pubkey.clone()) Config::new("a".to_string(), pubkey.clone()).with_agent_version("b".to_string()),
.with_agent_version("b".to_string()),
); );
let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id()); let swarm = Swarm::new(transport, protocol, pubkey.to_peer_id());
(swarm, pubkey) (swarm, pubkey)
@ -703,7 +703,7 @@ mod tests {
.factor_second() .factor_second()
.0 .0
{ {
future::Either::Left(SwarmEvent::Behaviour(IdentifyEvent::Received { future::Either::Left(SwarmEvent::Behaviour(Event::Received {
info, info,
.. ..
})) => { })) => {
@ -735,8 +735,8 @@ mod tests {
let mut swarm1 = { let mut swarm1 = {
let (pubkey, transport) = transport(); let (pubkey, transport) = transport();
let protocol = Identify::new( let protocol = Behaviour::new(
IdentifyConfig::new("a".to_string(), pubkey.clone()) Config::new("a".to_string(), pubkey.clone())
// `swarm1` will set `KeepAlive::No` once it identified `swarm2` and thus // `swarm1` will set `KeepAlive::No` once it identified `swarm2` and thus
// closes the connection. At this point in time `swarm2` might not yet have // closes the connection. At this point in time `swarm2` might not yet have
// identified `swarm1`. To give `swarm2` enough time, set an initial delay on // identified `swarm1`. To give `swarm2` enough time, set an initial delay on
@ -749,8 +749,8 @@ mod tests {
let mut swarm2 = { let mut swarm2 = {
let (pubkey, transport) = transport(); let (pubkey, transport) = transport();
let protocol = Identify::new( let protocol = Behaviour::new(
IdentifyConfig::new("a".to_string(), pubkey.clone()) Config::new("a".to_string(), pubkey.clone())
.with_cache_size(100) .with_cache_size(100)
.with_agent_version("b".to_string()), .with_agent_version("b".to_string()),
); );
@ -787,7 +787,7 @@ mod tests {
// Wait until we identified. // Wait until we identified.
async_std::task::block_on(async { async_std::task::block_on(async {
loop { loop {
if let SwarmEvent::Behaviour(IdentifyEvent::Received { .. }) = if let SwarmEvent::Behaviour(Event::Received { .. }) =
swarm2.select_next_some().await swarm2.select_next_some().await
{ {
break; break;

View File

@ -19,8 +19,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocol::{ use crate::protocol::{
IdentifyInfo, IdentifyProtocol, IdentifyPushProtocol, InboundPush, OutboundPush, InboundPush, Info, OutboundPush, Protocol, PushProtocol, ReplySubstream, UpgradeError,
ReplySubstream, UpgradeError,
}; };
use futures::future::BoxFuture; use futures::future::BoxFuture;
use futures::prelude::*; use futures::prelude::*;
@ -36,29 +35,29 @@ use log::warn;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{io, pin::Pin, task::Context, task::Poll, time::Duration}; use std::{io, pin::Pin, task::Context, task::Poll, time::Duration};
pub struct IdentifyHandlerProto { pub struct Proto {
initial_delay: Duration, initial_delay: Duration,
interval: Duration, interval: Duration,
} }
impl IdentifyHandlerProto { impl Proto {
pub fn new(initial_delay: Duration, interval: Duration) -> Self { pub fn new(initial_delay: Duration, interval: Duration) -> Self {
IdentifyHandlerProto { Proto {
initial_delay, initial_delay,
interval, interval,
} }
} }
} }
impl IntoConnectionHandler for IdentifyHandlerProto { impl IntoConnectionHandler for Proto {
type Handler = IdentifyHandler; type Handler = Handler;
fn into_handler(self, remote_peer_id: &PeerId, _endpoint: &ConnectedPoint) -> Self::Handler { fn into_handler(self, remote_peer_id: &PeerId, _endpoint: &ConnectedPoint) -> Self::Handler {
IdentifyHandler::new(self.initial_delay, self.interval, *remote_peer_id) Handler::new(self.initial_delay, self.interval, *remote_peer_id)
} }
fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
SelectUpgrade::new(IdentifyProtocol, IdentifyPushProtocol::inbound()) SelectUpgrade::new(Protocol, PushProtocol::inbound())
} }
} }
@ -67,15 +66,15 @@ impl IntoConnectionHandler for IdentifyHandlerProto {
/// Outbound requests are sent periodically. The handler performs expects /// Outbound requests are sent periodically. The handler performs expects
/// at least one identification request to be answered by the remote before /// at least one identification request to be answered by the remote before
/// permitting the underlying connection to be closed. /// permitting the underlying connection to be closed.
pub struct IdentifyHandler { pub struct Handler {
remote_peer_id: PeerId, remote_peer_id: PeerId,
inbound_identify_push: Option<BoxFuture<'static, Result<IdentifyInfo, UpgradeError>>>, inbound_identify_push: Option<BoxFuture<'static, Result<Info, UpgradeError>>>,
/// Pending events to yield. /// Pending events to yield.
events: SmallVec< events: SmallVec<
[ConnectionHandlerEvent< [ConnectionHandlerEvent<
EitherUpgrade<IdentifyProtocol, IdentifyPushProtocol<OutboundPush>>, EitherUpgrade<Protocol, PushProtocol<OutboundPush>>,
(), (),
IdentifyHandlerEvent, Event,
io::Error, io::Error,
>; 4], >; 4],
>, >,
@ -92,9 +91,9 @@ pub struct IdentifyHandler {
/// Event produced by the `IdentifyHandler`. /// Event produced by the `IdentifyHandler`.
#[derive(Debug)] #[derive(Debug)]
pub enum IdentifyHandlerEvent { pub enum Event {
/// We obtained identification information from the remote. /// We obtained identification information from the remote.
Identified(IdentifyInfo), Identified(Info),
/// We actively pushed our identification information to the remote. /// We actively pushed our identification information to the remote.
IdentificationPushed, IdentificationPushed,
/// We received a request for identification. /// We received a request for identification.
@ -105,12 +104,12 @@ pub enum IdentifyHandlerEvent {
/// Identifying information of the local node that is pushed to a remote. /// Identifying information of the local node that is pushed to a remote.
#[derive(Debug)] #[derive(Debug)]
pub struct IdentifyPush(pub IdentifyInfo); pub struct Push(pub Info);
impl IdentifyHandler { impl Handler {
/// Creates a new `IdentifyHandler`. /// Creates a new `IdentifyHandler`.
pub fn new(initial_delay: Duration, interval: Duration, remote_peer_id: PeerId) -> Self { pub fn new(initial_delay: Duration, interval: Duration, remote_peer_id: PeerId) -> Self {
IdentifyHandler { Self {
remote_peer_id, remote_peer_id,
inbound_identify_push: Default::default(), inbound_identify_push: Default::default(),
events: SmallVec::new(), events: SmallVec::new(),
@ -121,20 +120,17 @@ impl IdentifyHandler {
} }
} }
impl ConnectionHandler for IdentifyHandler { impl ConnectionHandler for Handler {
type InEvent = IdentifyPush; type InEvent = Push;
type OutEvent = IdentifyHandlerEvent; type OutEvent = Event;
type Error = io::Error; type Error = io::Error;
type InboundProtocol = SelectUpgrade<IdentifyProtocol, IdentifyPushProtocol<InboundPush>>; type InboundProtocol = SelectUpgrade<Protocol, PushProtocol<InboundPush>>;
type OutboundProtocol = EitherUpgrade<IdentifyProtocol, IdentifyPushProtocol<OutboundPush>>; type OutboundProtocol = EitherUpgrade<Protocol, PushProtocol<OutboundPush>>;
type OutboundOpenInfo = (); type OutboundOpenInfo = ();
type InboundOpenInfo = (); type InboundOpenInfo = ();
fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> { fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
SubstreamProtocol::new( SubstreamProtocol::new(SelectUpgrade::new(Protocol, PushProtocol::inbound()), ())
SelectUpgrade::new(IdentifyProtocol, IdentifyPushProtocol::inbound()),
(),
)
} }
fn inject_fully_negotiated_inbound( fn inject_fully_negotiated_inbound(
@ -143,9 +139,9 @@ impl ConnectionHandler for IdentifyHandler {
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
) { ) {
match output { match output {
EitherOutput::First(substream) => self.events.push(ConnectionHandlerEvent::Custom( EitherOutput::First(substream) => self
IdentifyHandlerEvent::Identify(substream), .events
)), .push(ConnectionHandlerEvent::Custom(Event::Identify(substream))),
EitherOutput::Second(fut) => { EitherOutput::Second(fut) => {
if self.inbound_identify_push.replace(fut).is_some() { if self.inbound_identify_push.replace(fut).is_some() {
warn!( warn!(
@ -165,22 +161,23 @@ impl ConnectionHandler for IdentifyHandler {
) { ) {
match output { match output {
EitherOutput::First(remote_info) => { EitherOutput::First(remote_info) => {
self.events.push(ConnectionHandlerEvent::Custom( self.events
IdentifyHandlerEvent::Identified(remote_info), .push(ConnectionHandlerEvent::Custom(Event::Identified(
)); remote_info,
)));
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
} }
EitherOutput::Second(()) => self.events.push(ConnectionHandlerEvent::Custom( EitherOutput::Second(()) => self
IdentifyHandlerEvent::IdentificationPushed, .events
)), .push(ConnectionHandlerEvent::Custom(Event::IdentificationPushed)),
} }
} }
fn inject_event(&mut self, IdentifyPush(push): Self::InEvent) { fn inject_event(&mut self, Push(push): Self::InEvent) {
self.events self.events
.push(ConnectionHandlerEvent::OutboundSubstreamRequest { .push(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
EitherUpgrade::B(IdentifyPushProtocol::outbound(push)), EitherUpgrade::B(PushProtocol::outbound(push)),
(), (),
), ),
}); });
@ -200,9 +197,10 @@ impl ConnectionHandler for IdentifyHandler {
UpgradeError::Apply(EitherError::A(ioe)) => UpgradeError::Apply(ioe), UpgradeError::Apply(EitherError::A(ioe)) => UpgradeError::Apply(ioe),
UpgradeError::Apply(EitherError::B(ioe)) => UpgradeError::Apply(ioe), UpgradeError::Apply(EitherError::B(ioe)) => UpgradeError::Apply(ioe),
}); });
self.events.push(ConnectionHandlerEvent::Custom( self.events
IdentifyHandlerEvent::IdentificationError(err), .push(ConnectionHandlerEvent::Custom(Event::IdentificationError(
)); err,
)));
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
self.trigger_next_identify.reset(self.interval); self.trigger_next_identify.reset(self.interval);
} }
@ -215,12 +213,7 @@ impl ConnectionHandler for IdentifyHandler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ConnectionHandlerEvent< ConnectionHandlerEvent<Self::OutboundProtocol, Self::OutboundOpenInfo, Event, Self::Error>,
Self::OutboundProtocol,
Self::OutboundOpenInfo,
IdentifyHandlerEvent,
Self::Error,
>,
> { > {
if !self.events.is_empty() { if !self.events.is_empty() {
return Poll::Ready(self.events.remove(0)); return Poll::Ready(self.events.remove(0));
@ -232,7 +225,7 @@ impl ConnectionHandler for IdentifyHandler {
Poll::Ready(()) => { Poll::Ready(()) => {
self.trigger_next_identify.reset(self.interval); self.trigger_next_identify.reset(self.interval);
let ev = ConnectionHandlerEvent::OutboundSubstreamRequest { let ev = ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new(EitherUpgrade::A(IdentifyProtocol), ()), protocol: SubstreamProtocol::new(EitherUpgrade::A(Protocol), ()),
}; };
return Poll::Ready(ev); return Poll::Ready(ev);
} }
@ -246,9 +239,7 @@ impl ConnectionHandler for IdentifyHandler {
self.inbound_identify_push.take(); self.inbound_identify_push.take();
if let Ok(info) = res { if let Ok(info) = res {
return Poll::Ready(ConnectionHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(Event::Identified(info)));
IdentifyHandlerEvent::Identified(info),
));
} }
} }

View File

@ -21,7 +21,7 @@
//! Implementation of the [Identify] protocol. //! Implementation of the [Identify] protocol.
//! //!
//! This implementation of the protocol periodically exchanges //! This implementation of the protocol periodically exchanges
//! [`IdentifyInfo`] messages between the peers on an established connection. //! [`Info`] messages between the peers on an established connection.
//! //!
//! At least one identification request is sent on a newly established //! At least one identification request is sent on a newly established
//! connection, beyond which the behaviour does not keep connections alive. //! connection, beyond which the behaviour does not keep connections alive.
@ -35,20 +35,36 @@
//! //!
//! # Usage //! # Usage
//! //!
//! The [`Identify`] struct implements a `NetworkBehaviour` that negotiates //! The [`Behaviour`] struct implements a [`NetworkBehaviour`](libp2p_swarm::NetworkBehaviour)
//! and executes the protocol on every established connection, emitting //! that negotiates and executes the protocol on every established connection, emitting
//! [`IdentifyEvent`]s. //! [`Event`]s.
//!
//! [Identify]: https://github.com/libp2p/specs/tree/master/identify
//! [`Identify`]: self::Identify
//! [`IdentifyEvent`]: self::IdentifyEvent
//! [`IdentifyInfo`]: self::IdentifyInfo
pub use self::identify::{Identify, IdentifyConfig, IdentifyEvent}; pub use self::behaviour::{Behaviour, Config, Event};
pub use self::protocol::{IdentifyInfo, UpgradeError, PROTOCOL_NAME, PUSH_PROTOCOL_NAME}; pub use self::protocol::{Info, UpgradeError, PROTOCOL_NAME, PUSH_PROTOCOL_NAME};
#[deprecated(
since = "0.40.0",
note = "Use re-exports that omit `Identify` prefix, i.e. `libp2p::identify::Config`"
)]
pub type IdentifyConfig = Config;
#[deprecated(
since = "0.40.0",
note = "Use re-exports that omit `Identify` prefix, i.e. `libp2p::identify::Event`"
)]
pub type IdentifyEvent = Event;
#[deprecated(since = "0.40.0", note = "Use libp2p::identify::Behaviour instead.")]
pub type Identify = Behaviour;
#[deprecated(
since = "0.40.0",
note = "Use re-exports that omit `Identify` prefix, i.e. `libp2p::identify::Info`"
)]
pub type IdentifyInfo = Info;
mod behaviour;
mod handler; mod handler;
mod identify;
mod protocol; mod protocol;
#[allow(clippy::derive_partial_eq_without_eq)] #[allow(clippy::derive_partial_eq_without_eq)]

View File

@ -40,29 +40,29 @@ pub const PUSH_PROTOCOL_NAME: &[u8; 19] = b"/ipfs/id/push/1.0.0";
/// Substream upgrade protocol for `/ipfs/id/1.0.0`. /// Substream upgrade protocol for `/ipfs/id/1.0.0`.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct IdentifyProtocol; pub struct Protocol;
/// Substream upgrade protocol for `/ipfs/id/push/1.0.0`. /// Substream upgrade protocol for `/ipfs/id/push/1.0.0`.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct IdentifyPushProtocol<T>(T); pub struct PushProtocol<T>(T);
pub struct InboundPush(); pub struct InboundPush();
pub struct OutboundPush(IdentifyInfo); pub struct OutboundPush(Info);
impl IdentifyPushProtocol<InboundPush> { impl PushProtocol<InboundPush> {
pub fn inbound() -> Self { pub fn inbound() -> Self {
IdentifyPushProtocol(InboundPush()) PushProtocol(InboundPush())
} }
} }
impl IdentifyPushProtocol<OutboundPush> { impl PushProtocol<OutboundPush> {
pub fn outbound(info: IdentifyInfo) -> Self { pub fn outbound(info: Info) -> Self {
IdentifyPushProtocol(OutboundPush(info)) PushProtocol(OutboundPush(info))
} }
} }
/// Information of a peer sent in protocol messages. /// Information of a peer sent in protocol messages.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct IdentifyInfo { pub struct Info {
/// The public key of the local peer. /// The public key of the local peer.
pub public_key: PublicKey, pub public_key: PublicKey,
/// Application-specific version of the protocol family used by the peer, /// Application-specific version of the protocol family used by the peer,
@ -98,12 +98,12 @@ where
/// ///
/// Consumes the substream, returning a future that resolves /// Consumes the substream, returning a future that resolves
/// when the reply has been sent on the underlying connection. /// when the reply has been sent on the underlying connection.
pub async fn send(self, info: IdentifyInfo) -> Result<(), UpgradeError> { pub async fn send(self, info: Info) -> Result<(), UpgradeError> {
send(self.inner, info).await.map_err(Into::into) send(self.inner, info).await.map_err(Into::into)
} }
} }
impl UpgradeInfo for IdentifyProtocol { impl UpgradeInfo for Protocol {
type Info = &'static [u8]; type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>; type InfoIter = iter::Once<Self::Info>;
@ -112,7 +112,7 @@ impl UpgradeInfo for IdentifyProtocol {
} }
} }
impl<C> InboundUpgrade<C> for IdentifyProtocol { impl<C> InboundUpgrade<C> for Protocol {
type Output = ReplySubstream<C>; type Output = ReplySubstream<C>;
type Error = UpgradeError; type Error = UpgradeError;
type Future = future::Ready<Result<Self::Output, UpgradeError>>; type Future = future::Ready<Result<Self::Output, UpgradeError>>;
@ -122,11 +122,11 @@ impl<C> InboundUpgrade<C> for IdentifyProtocol {
} }
} }
impl<C> OutboundUpgrade<C> for IdentifyProtocol impl<C> OutboundUpgrade<C> for Protocol
where where
C: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{ {
type Output = IdentifyInfo; type Output = Info;
type Error = UpgradeError; type Error = UpgradeError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>; type Future = Pin<Box<dyn Future<Output = Result<Self::Output, Self::Error>> + Send>>;
@ -135,7 +135,7 @@ where
} }
} }
impl<T> UpgradeInfo for IdentifyPushProtocol<T> { impl<T> UpgradeInfo for PushProtocol<T> {
type Info = &'static [u8]; type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>; type InfoIter = iter::Once<Self::Info>;
@ -144,11 +144,11 @@ impl<T> UpgradeInfo for IdentifyPushProtocol<T> {
} }
} }
impl<C> InboundUpgrade<C> for IdentifyPushProtocol<InboundPush> impl<C> InboundUpgrade<C> for PushProtocol<InboundPush>
where where
C: AsyncRead + AsyncWrite + Unpin + Send + 'static, C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{ {
type Output = BoxFuture<'static, Result<IdentifyInfo, UpgradeError>>; type Output = BoxFuture<'static, Result<Info, UpgradeError>>;
type Error = Void; type Error = Void;
type Future = future::Ready<Result<Self::Output, Self::Error>>; type Future = future::Ready<Result<Self::Output, Self::Error>>;
@ -158,7 +158,7 @@ where
} }
} }
impl<C> OutboundUpgrade<C> for IdentifyPushProtocol<OutboundPush> impl<C> OutboundUpgrade<C> for PushProtocol<OutboundPush>
where where
C: AsyncWrite + Unpin + Send + 'static, C: AsyncWrite + Unpin + Send + 'static,
{ {
@ -171,7 +171,7 @@ where
} }
} }
async fn send<T>(io: T, info: IdentifyInfo) -> Result<(), UpgradeError> async fn send<T>(io: T, info: Info) -> Result<(), UpgradeError>
where where
T: AsyncWrite + Unpin, T: AsyncWrite + Unpin,
{ {
@ -205,7 +205,7 @@ where
Ok(()) Ok(())
} }
async fn recv<T>(mut socket: T) -> Result<IdentifyInfo, UpgradeError> async fn recv<T>(mut socket: T) -> Result<Info, UpgradeError>
where where
T: AsyncRead + AsyncWrite + Unpin, T: AsyncRead + AsyncWrite + Unpin,
{ {
@ -225,7 +225,7 @@ where
Ok(info) Ok(info)
} }
impl TryFrom<structs_proto::Identify> for IdentifyInfo { impl TryFrom<structs_proto::Identify> for Info {
type Error = UpgradeError; type Error = UpgradeError;
fn try_from(msg: structs_proto::Identify) -> Result<Self, Self::Error> { fn try_from(msg: structs_proto::Identify) -> Result<Self, Self::Error> {
@ -244,7 +244,7 @@ impl TryFrom<structs_proto::Identify> for IdentifyInfo {
let public_key = PublicKey::from_protobuf_encoding(&msg.public_key.unwrap_or_default())?; let public_key = PublicKey::from_protobuf_encoding(&msg.public_key.unwrap_or_default())?;
let observed_addr = parse_multiaddr(msg.observed_addr.unwrap_or_default())?; let observed_addr = parse_multiaddr(msg.observed_addr.unwrap_or_default())?;
let info = IdentifyInfo { let info = Info {
public_key, public_key,
protocol_version: msg.protocol_version.unwrap_or_default(), protocol_version: msg.protocol_version.unwrap_or_default(),
agent_version: msg.agent_version.unwrap_or_default(), agent_version: msg.agent_version.unwrap_or_default(),
@ -332,10 +332,10 @@ mod tests {
.await .await
.unwrap(); .unwrap();
let sender = apply_inbound(socket, IdentifyProtocol).await.unwrap(); let sender = apply_inbound(socket, Protocol).await.unwrap();
sender sender
.send(IdentifyInfo { .send(Info {
public_key: send_pubkey, public_key: send_pubkey,
protocol_version: "proto_version".to_owned(), protocol_version: "proto_version".to_owned(),
agent_version: "agent_version".to_owned(), agent_version: "agent_version".to_owned(),
@ -354,7 +354,7 @@ mod tests {
let mut transport = TcpTransport::default(); let mut transport = TcpTransport::default();
let socket = transport.dial(rx.await.unwrap()).unwrap().await.unwrap(); let socket = transport.dial(rx.await.unwrap()).unwrap().await.unwrap();
let info = apply_outbound(socket, IdentifyProtocol, upgrade::Version::V1) let info = apply_outbound(socket, Protocol, upgrade::Version::V1)
.await .await
.unwrap(); .unwrap();
assert_eq!( assert_eq!(

View File

@ -23,7 +23,7 @@ use clap::Parser;
use futures::executor::block_on; use futures::executor::block_on;
use futures::stream::StreamExt; use futures::stream::StreamExt;
use libp2p::core::upgrade; use libp2p::core::upgrade;
use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent}; use libp2p::identify;
use libp2p::multiaddr::Protocol; use libp2p::multiaddr::Protocol;
use libp2p::relay::v2::relay::{self, Relay}; use libp2p::relay::v2::relay::{self, Relay};
use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::swarm::{Swarm, SwarmEvent};
@ -59,7 +59,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let behaviour = Behaviour { let behaviour = Behaviour {
relay: Relay::new(local_peer_id, Default::default()), relay: Relay::new(local_peer_id, Default::default()),
ping: ping::Behaviour::new(ping::Config::new()), ping: ping::Behaviour::new(ping::Config::new()),
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"/TODO/0.0.1".to_string(), "/TODO/0.0.1".to_string(),
local_key.public(), local_key.public(),
)), )),
@ -96,13 +96,13 @@ fn main() -> Result<(), Box<dyn Error>> {
struct Behaviour { struct Behaviour {
relay: Relay, relay: Relay,
ping: ping::Behaviour, ping: ping::Behaviour,
identify: Identify, identify: identify::Behaviour,
} }
#[derive(Debug)] #[derive(Debug)]
enum Event { enum Event {
Ping(ping::Event), Ping(ping::Event),
Identify(IdentifyEvent), Identify(identify::Event),
Relay(relay::Event), Relay(relay::Event),
} }
@ -112,8 +112,8 @@ impl From<ping::Event> for Event {
} }
} }
impl From<IdentifyEvent> for Event { impl From<identify::Event> for Event {
fn from(e: IdentifyEvent) -> Self { fn from(e: identify::Event) -> Self {
Event::Identify(e) Event::Identify(e)
} }
} }

View File

@ -21,7 +21,7 @@
use futures::StreamExt; use futures::StreamExt;
use libp2p::core::identity; use libp2p::core::identity;
use libp2p::core::PeerId; use libp2p::core::PeerId;
use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent}; use libp2p::identify;
use libp2p::ping; use libp2p::ping;
use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::{development_transport, rendezvous}; use libp2p::{development_transport, rendezvous};
@ -42,7 +42,7 @@ async fn main() {
let mut swarm = Swarm::new( let mut swarm = Swarm::new(
development_transport(identity.clone()).await.unwrap(), development_transport(identity.clone()).await.unwrap(),
MyBehaviour { MyBehaviour {
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"rendezvous-example/1.0.0".to_string(), "rendezvous-example/1.0.0".to_string(),
identity.public(), identity.public(),
)), )),
@ -75,7 +75,7 @@ async fn main() {
log::error!("Lost connection to rendezvous point {}", error); log::error!("Lost connection to rendezvous point {}", error);
} }
// once `/identify` did its job, we know our external address and can register // once `/identify` did its job, we know our external address and can register
SwarmEvent::Behaviour(MyEvent::Identify(IdentifyEvent::Received { .. })) => { SwarmEvent::Behaviour(MyEvent::Identify(identify::Event::Received { .. })) => {
swarm.behaviour_mut().rendezvous.register( swarm.behaviour_mut().rendezvous.register(
rendezvous::Namespace::from_static("rendezvous"), rendezvous::Namespace::from_static("rendezvous"),
rendezvous_point, rendezvous_point,
@ -116,7 +116,7 @@ async fn main() {
#[derive(Debug)] #[derive(Debug)]
enum MyEvent { enum MyEvent {
Rendezvous(rendezvous::client::Event), Rendezvous(rendezvous::client::Event),
Identify(IdentifyEvent), Identify(identify::Event),
Ping(ping::Event), Ping(ping::Event),
} }
@ -126,8 +126,8 @@ impl From<rendezvous::client::Event> for MyEvent {
} }
} }
impl From<IdentifyEvent> for MyEvent { impl From<identify::Event> for MyEvent {
fn from(event: IdentifyEvent) -> Self { fn from(event: identify::Event) -> Self {
MyEvent::Identify(event) MyEvent::Identify(event)
} }
} }
@ -142,7 +142,7 @@ impl From<ping::Event> for MyEvent {
#[behaviour(event_process = false)] #[behaviour(event_process = false)]
#[behaviour(out_event = "MyEvent")] #[behaviour(out_event = "MyEvent")]
struct MyBehaviour { struct MyBehaviour {
identify: Identify, identify: identify::Behaviour,
rendezvous: rendezvous::client::Behaviour, rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour, ping: ping::Behaviour,
} }

View File

@ -21,9 +21,7 @@
use futures::StreamExt; use futures::StreamExt;
use libp2p::core::identity; use libp2p::core::identity;
use libp2p::core::PeerId; use libp2p::core::PeerId;
use libp2p::identify::Identify; use libp2p::identify;
use libp2p::identify::IdentifyConfig;
use libp2p::identify::IdentifyEvent;
use libp2p::ping; use libp2p::ping;
use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::NetworkBehaviour; use libp2p::NetworkBehaviour;
@ -48,7 +46,7 @@ async fn main() {
let mut swarm = Swarm::new( let mut swarm = Swarm::new(
development_transport(identity.clone()).await.unwrap(), development_transport(identity.clone()).await.unwrap(),
MyBehaviour { MyBehaviour {
identify: Identify::new(IdentifyConfig::new( identify: identify::Behaviour::new(identify::Config::new(
"rendezvous-example/1.0.0".to_string(), "rendezvous-example/1.0.0".to_string(),
identity.public(), identity.public(),
)), )),
@ -104,7 +102,7 @@ async fn main() {
enum MyEvent { enum MyEvent {
Rendezvous(rendezvous::server::Event), Rendezvous(rendezvous::server::Event),
Ping(ping::Event), Ping(ping::Event),
Identify(IdentifyEvent), Identify(identify::Event),
} }
impl From<rendezvous::server::Event> for MyEvent { impl From<rendezvous::server::Event> for MyEvent {
@ -119,8 +117,8 @@ impl From<ping::Event> for MyEvent {
} }
} }
impl From<IdentifyEvent> for MyEvent { impl From<identify::Event> for MyEvent {
fn from(event: IdentifyEvent) -> Self { fn from(event: identify::Event) -> Self {
MyEvent::Identify(event) MyEvent::Identify(event)
} }
} }
@ -129,7 +127,7 @@ impl From<IdentifyEvent> for MyEvent {
#[behaviour(event_process = false)] #[behaviour(event_process = false)]
#[behaviour(out_event = "MyEvent")] #[behaviour(out_event = "MyEvent")]
struct MyBehaviour { struct MyBehaviour {
identify: Identify, identify: identify::Behaviour,
rendezvous: rendezvous::server::Behaviour, rendezvous: rendezvous::server::Behaviour,
ping: ping::Behaviour, ping: ping::Behaviour,
} }

View File

@ -19,8 +19,8 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use futures::prelude::*; use futures::prelude::*;
use libp2p::ping;
use libp2p::swarm::{NetworkBehaviour, SwarmEvent}; use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::{identify, ping};
use libp2p_swarm_derive::*; use libp2p_swarm_derive::*;
use std::fmt::Debug; use std::fmt::Debug;
@ -60,7 +60,7 @@ fn two_fields() {
#[derive(NetworkBehaviour)] #[derive(NetworkBehaviour)]
struct Foo { struct Foo {
ping: ping::Behaviour, ping: ping::Behaviour,
identify: libp2p::identify::Identify, identify: identify::Behaviour,
} }
#[allow(dead_code)] #[allow(dead_code)]
@ -70,7 +70,7 @@ fn two_fields() {
match _out_event { match _out_event {
FooEvent::Ping(ping::Event { .. }) => {} FooEvent::Ping(ping::Event { .. }) => {}
FooEvent::Identify(event) => { FooEvent::Identify(event) => {
let _: libp2p::identify::IdentifyEvent = event; let _: identify::Event = event;
} }
} }
} }
@ -82,7 +82,7 @@ fn three_fields() {
#[derive(NetworkBehaviour)] #[derive(NetworkBehaviour)]
struct Foo { struct Foo {
ping: ping::Behaviour, ping: ping::Behaviour,
identify: libp2p::identify::Identify, identify: identify::Behaviour,
kad: libp2p::kad::Kademlia<libp2p::kad::record::store::MemoryStore>, kad: libp2p::kad::Kademlia<libp2p::kad::record::store::MemoryStore>,
} }
@ -93,7 +93,7 @@ fn three_fields() {
match _out_event { match _out_event {
FooEvent::Ping(ping::Event { .. }) => {} FooEvent::Ping(ping::Event { .. }) => {}
FooEvent::Identify(event) => { FooEvent::Identify(event) => {
let _: libp2p::identify::IdentifyEvent = event; let _: identify::Event = event;
} }
FooEvent::Kad(event) => { FooEvent::Kad(event) => {
let _: libp2p::kad::KademliaEvent = event; let _: libp2p::kad::KademliaEvent = event;
@ -109,12 +109,12 @@ fn custom_event() {
#[behaviour(out_event = "MyEvent")] #[behaviour(out_event = "MyEvent")]
struct Foo { struct Foo {
ping: ping::Behaviour, ping: ping::Behaviour,
identify: libp2p::identify::Identify, identify: identify::Behaviour,
} }
enum MyEvent { enum MyEvent {
Ping(ping::Event), Ping(ping::Event),
Identify(libp2p::identify::IdentifyEvent), Identify(identify::Event),
} }
impl From<ping::Event> for MyEvent { impl From<ping::Event> for MyEvent {
@ -123,8 +123,8 @@ fn custom_event() {
} }
} }
impl From<libp2p::identify::IdentifyEvent> for MyEvent { impl From<libp2p::identify::Event> for MyEvent {
fn from(event: libp2p::identify::IdentifyEvent) -> Self { fn from(event: libp2p::identify::Event) -> Self {
MyEvent::Identify(event) MyEvent::Identify(event)
} }
} }
@ -142,12 +142,12 @@ fn custom_event_mismatching_field_names() {
#[behaviour(out_event = "MyEvent")] #[behaviour(out_event = "MyEvent")]
struct Foo { struct Foo {
a: ping::Behaviour, a: ping::Behaviour,
b: libp2p::identify::Identify, b: libp2p::identify::Behaviour,
} }
enum MyEvent { enum MyEvent {
Ping(ping::Event), Ping(ping::Event),
Identify(libp2p::identify::IdentifyEvent), Identify(libp2p::identify::Event),
} }
impl From<ping::Event> for MyEvent { impl From<ping::Event> for MyEvent {
@ -156,8 +156,8 @@ fn custom_event_mismatching_field_names() {
} }
} }
impl From<libp2p::identify::IdentifyEvent> for MyEvent { impl From<libp2p::identify::Event> for MyEvent {
fn from(event: libp2p::identify::IdentifyEvent) -> Self { fn from(event: libp2p::identify::Event) -> Self {
MyEvent::Identify(event) MyEvent::Identify(event)
} }
} }
@ -223,7 +223,7 @@ fn nested_derives_with_import() {
fn custom_event_emit_event_through_poll() { fn custom_event_emit_event_through_poll() {
enum BehaviourOutEvent { enum BehaviourOutEvent {
Ping(ping::Event), Ping(ping::Event),
Identify(libp2p::identify::IdentifyEvent), Identify(identify::Event),
} }
impl From<ping::Event> for BehaviourOutEvent { impl From<ping::Event> for BehaviourOutEvent {
@ -232,8 +232,8 @@ fn custom_event_emit_event_through_poll() {
} }
} }
impl From<libp2p::identify::IdentifyEvent> for BehaviourOutEvent { impl From<libp2p::identify::Event> for BehaviourOutEvent {
fn from(event: libp2p::identify::IdentifyEvent) -> Self { fn from(event: libp2p::identify::Event) -> Self {
BehaviourOutEvent::Identify(event) BehaviourOutEvent::Identify(event)
} }
} }
@ -243,7 +243,7 @@ fn custom_event_emit_event_through_poll() {
#[behaviour(out_event = "BehaviourOutEvent")] #[behaviour(out_event = "BehaviourOutEvent")]
struct Foo { struct Foo {
ping: ping::Behaviour, ping: ping::Behaviour,
identify: libp2p::identify::Identify, identify: identify::Behaviour,
} }
#[allow(dead_code, unreachable_code)] #[allow(dead_code, unreachable_code)]
@ -272,7 +272,7 @@ fn with_toggle() {
#[allow(dead_code)] #[allow(dead_code)]
#[derive(NetworkBehaviour)] #[derive(NetworkBehaviour)]
struct Foo { struct Foo {
identify: libp2p::identify::Identify, identify: identify::Behaviour,
ping: Toggle<ping::Behaviour>, ping: Toggle<ping::Behaviour>,
} }
@ -290,7 +290,7 @@ fn with_either() {
#[derive(NetworkBehaviour)] #[derive(NetworkBehaviour)]
struct Foo { struct Foo {
kad: libp2p::kad::Kademlia<libp2p::kad::record::store::MemoryStore>, kad: libp2p::kad::Kademlia<libp2p::kad::record::store::MemoryStore>,
ping_or_identify: Either<ping::Behaviour, libp2p::identify::Identify>, ping_or_identify: Either<ping::Behaviour, identify::Behaviour>,
} }
#[allow(dead_code)] #[allow(dead_code)]
@ -305,7 +305,7 @@ fn custom_event_with_either() {
enum BehaviourOutEvent { enum BehaviourOutEvent {
Kad(libp2p::kad::KademliaEvent), Kad(libp2p::kad::KademliaEvent),
PingOrIdentify(Either<ping::Event, libp2p::identify::IdentifyEvent>), PingOrIdentify(Either<ping::Event, identify::Event>),
} }
impl From<libp2p::kad::KademliaEvent> for BehaviourOutEvent { impl From<libp2p::kad::KademliaEvent> for BehaviourOutEvent {
@ -314,8 +314,8 @@ fn custom_event_with_either() {
} }
} }
impl From<Either<ping::Event, libp2p::identify::IdentifyEvent>> for BehaviourOutEvent { impl From<Either<ping::Event, identify::Event>> for BehaviourOutEvent {
fn from(event: Either<ping::Event, libp2p::identify::IdentifyEvent>) -> Self { fn from(event: Either<ping::Event, identify::Event>) -> Self {
BehaviourOutEvent::PingOrIdentify(event) BehaviourOutEvent::PingOrIdentify(event)
} }
} }
@ -325,7 +325,7 @@ fn custom_event_with_either() {
#[behaviour(out_event = "BehaviourOutEvent")] #[behaviour(out_event = "BehaviourOutEvent")]
struct Foo { struct Foo {
kad: libp2p::kad::Kademlia<libp2p::kad::record::store::MemoryStore>, kad: libp2p::kad::Kademlia<libp2p::kad::record::store::MemoryStore>,
ping_or_identify: Either<ping::Behaviour, libp2p::identify::Identify>, ping_or_identify: Either<ping::Behaviour, identify::Behaviour>,
} }
#[allow(dead_code)] #[allow(dead_code)]

View File

@ -90,23 +90,23 @@ pub(crate) type THandlerOutEvent<THandler> =
/// addition to the event `enum` itself. /// addition to the event `enum` itself.
/// ///
/// ``` rust /// ``` rust
/// # use libp2p::identify::{Identify, IdentifyEvent}; /// # use libp2p::identify;
/// # use libp2p::ping; /// # use libp2p::ping;
/// # use libp2p::NetworkBehaviour; /// # use libp2p::NetworkBehaviour;
/// #[derive(NetworkBehaviour)] /// #[derive(NetworkBehaviour)]
/// #[behaviour(out_event = "Event")] /// #[behaviour(out_event = "Event")]
/// struct MyBehaviour { /// struct MyBehaviour {
/// identify: Identify, /// identify: identify::Behaviour,
/// ping: ping::Behaviour, /// ping: ping::Behaviour,
/// } /// }
/// ///
/// enum Event { /// enum Event {
/// Identify(IdentifyEvent), /// Identify(identify::Event),
/// Ping(ping::Event), /// Ping(ping::Event),
/// } /// }
/// ///
/// impl From<IdentifyEvent> for Event { /// impl From<identify::Event> for Event {
/// fn from(event: IdentifyEvent) -> Self { /// fn from(event: identify::Event) -> Self {
/// Self::Identify(event) /// Self::Identify(event)
/// } /// }
/// } /// }