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
19 changed files with 253 additions and 240 deletions

View File

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

View File

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

View File

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

View File

@ -2,6 +2,14 @@
- 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-swarm` `v0.40.0`.

View File

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

View File

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

View File

@ -21,7 +21,7 @@
//! Implementation of the [Identify] protocol.
//!
//! 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
//! connection, beyond which the behaviour does not keep connections alive.
@ -35,20 +35,36 @@
//!
//! # Usage
//!
//! The [`Identify`] struct implements a `NetworkBehaviour` that negotiates
//! and executes the protocol on every established connection, emitting
//! [`IdentifyEvent`]s.
//!
//! [Identify]: https://github.com/libp2p/specs/tree/master/identify
//! [`Identify`]: self::Identify
//! [`IdentifyEvent`]: self::IdentifyEvent
//! [`IdentifyInfo`]: self::IdentifyInfo
//! The [`Behaviour`] struct implements a [`NetworkBehaviour`](libp2p_swarm::NetworkBehaviour)
//! that negotiates and executes the protocol on every established connection, emitting
//! [`Event`]s.
pub use self::identify::{Identify, IdentifyConfig, IdentifyEvent};
pub use self::protocol::{IdentifyInfo, UpgradeError, PROTOCOL_NAME, PUSH_PROTOCOL_NAME};
pub use self::behaviour::{Behaviour, Config, Event};
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 identify;
mod protocol;
#[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`.
#[derive(Debug, Clone)]
pub struct IdentifyProtocol;
pub struct Protocol;
/// Substream upgrade protocol for `/ipfs/id/push/1.0.0`.
#[derive(Debug, Clone)]
pub struct IdentifyPushProtocol<T>(T);
pub struct PushProtocol<T>(T);
pub struct InboundPush();
pub struct OutboundPush(IdentifyInfo);
pub struct OutboundPush(Info);
impl IdentifyPushProtocol<InboundPush> {
impl PushProtocol<InboundPush> {
pub fn inbound() -> Self {
IdentifyPushProtocol(InboundPush())
PushProtocol(InboundPush())
}
}
impl IdentifyPushProtocol<OutboundPush> {
pub fn outbound(info: IdentifyInfo) -> Self {
IdentifyPushProtocol(OutboundPush(info))
impl PushProtocol<OutboundPush> {
pub fn outbound(info: Info) -> Self {
PushProtocol(OutboundPush(info))
}
}
/// Information of a peer sent in protocol messages.
#[derive(Debug, Clone)]
pub struct IdentifyInfo {
pub struct Info {
/// The public key of the local peer.
pub public_key: PublicKey,
/// Application-specific version of the protocol family used by the peer,
@ -98,12 +98,12 @@ where
///
/// Consumes the substream, returning a future that resolves
/// 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)
}
}
impl UpgradeInfo for IdentifyProtocol {
impl UpgradeInfo for Protocol {
type Info = &'static [u8];
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 Error = 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
C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
type Output = IdentifyInfo;
type Output = Info;
type Error = UpgradeError;
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 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
C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
type Output = BoxFuture<'static, Result<IdentifyInfo, UpgradeError>>;
type Output = BoxFuture<'static, Result<Info, UpgradeError>>;
type Error = Void;
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
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
T: AsyncWrite + Unpin,
{
@ -205,7 +205,7 @@ where
Ok(())
}
async fn recv<T>(mut socket: T) -> Result<IdentifyInfo, UpgradeError>
async fn recv<T>(mut socket: T) -> Result<Info, UpgradeError>
where
T: AsyncRead + AsyncWrite + Unpin,
{
@ -225,7 +225,7 @@ where
Ok(info)
}
impl TryFrom<structs_proto::Identify> for IdentifyInfo {
impl TryFrom<structs_proto::Identify> for Info {
type Error = UpgradeError;
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 observed_addr = parse_multiaddr(msg.observed_addr.unwrap_or_default())?;
let info = IdentifyInfo {
let info = Info {
public_key,
protocol_version: msg.protocol_version.unwrap_or_default(),
agent_version: msg.agent_version.unwrap_or_default(),
@ -332,10 +332,10 @@ mod tests {
.await
.unwrap();
let sender = apply_inbound(socket, IdentifyProtocol).await.unwrap();
let sender = apply_inbound(socket, Protocol).await.unwrap();
sender
.send(IdentifyInfo {
.send(Info {
public_key: send_pubkey,
protocol_version: "proto_version".to_owned(),
agent_version: "agent_version".to_owned(),
@ -354,7 +354,7 @@ mod tests {
let mut transport = TcpTransport::default();
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
.unwrap();
assert_eq!(

View File

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

View File

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

View File

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