Skip to content

Commit

Permalink
Make it compile
Browse files Browse the repository at this point in the history
  • Loading branch information
thomaseizinger committed Apr 24, 2023
1 parent 244fc7f commit f909139
Show file tree
Hide file tree
Showing 21 changed files with 125 additions and 273 deletions.
11 changes: 1 addition & 10 deletions core/src/either.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::muxing::StreamMuxerEvent;
use crate::{
muxing::StreamMuxer,
transport::{ListenerId, Transport, TransportError, TransportEvent},
Multiaddr, ProtocolName,
Multiaddr,
};
use either::Either;
use futures::prelude::*;
Expand Down Expand Up @@ -121,15 +121,6 @@ pub enum EitherName<A, B> {
B(B),
}

impl<A: ProtocolName, B: ProtocolName> ProtocolName for EitherName<A, B> {
fn protocol_name(&self) -> &[u8] {
match self {
EitherName::A(a) => a.protocol_name(),
EitherName::B(b) => b.protocol_name(),
}
}
}

impl<A, B> Transport for Either<A, B>
where
B: Transport,
Expand Down
4 changes: 3 additions & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ pub use peer_record::PeerRecord;
pub use signed_envelope::SignedEnvelope;
pub use translation::address_translation;
pub use transport::Transport;
pub use upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeError, UpgradeProtocols};
#[allow(deprecated)]
pub use upgrade::ProtocolName;
pub use upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeError, UpgradeProtocols};

#[allow(deprecated)]
pub use upgrade::UpgradeInfo;
Expand Down
4 changes: 4 additions & 0 deletions core/src/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ pub use multistream_select::{NegotiatedComplete, NegotiationError, ProtocolError
/// }
/// ```
///
#[deprecated(note = "Use the `Protocol` new-type instead.")]
pub trait ProtocolName {
/// The protocol name as bytes. Transmitted on the network.
///
Expand All @@ -129,6 +130,7 @@ pub trait ProtocolName {
fn protocol_name(&self) -> &[u8];
}

#[allow(deprecated)]
impl<T: AsRef<[u8]>> ProtocolName for T {
fn protocol_name(&self) -> &[u8] {
self.as_ref()
Expand All @@ -138,6 +140,7 @@ impl<T: AsRef<[u8]>> ProtocolName for T {
/// Common trait for upgrades that can be applied on inbound substreams, outbound substreams,
/// or both.
#[deprecated(note = "Implement `UpgradeProtocols` instead.")]
#[allow(deprecated)]
pub trait UpgradeInfo {
/// Opaque type representing a negotiable protocol.
type Info: ProtocolName + Clone;
Expand Down Expand Up @@ -237,6 +240,7 @@ where
}
}

#[allow(deprecated)]
fn filter_non_utf8_protocols(p: impl ProtocolName) -> Option<Protocol> {
let name = p.protocol_name();

Expand Down
7 changes: 5 additions & 2 deletions core/src/upgrade/from_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
// DEALINGS IN THE SOFTWARE.

#[allow(deprecated)]
use crate::upgrade::UpgradeInfo;
use crate::upgrade::{ProtocolName, UpgradeInfo};
use crate::{
upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName},
upgrade::{InboundUpgrade, OutboundUpgrade},
Endpoint,
};

Expand Down Expand Up @@ -55,6 +55,7 @@ use std::iter;
/// });
/// ```
///
#[allow(deprecated)]
pub fn from_fn<P, F, C, Fut, Out, Err>(protocol_name: P, fun: F) -> FromFnUpgrade<P, F>
where
// Note: these bounds are there in order to help the compiler infer types
Expand Down Expand Up @@ -87,6 +88,7 @@ where
}
}

#[allow(deprecated)]
impl<C, P, F, Fut, Err, Out> InboundUpgrade<C> for FromFnUpgrade<P, F>
where
P: ProtocolName + Clone,
Expand All @@ -102,6 +104,7 @@ where
}
}

#[allow(deprecated)]
impl<C, P, F, Fut, Err, Out> OutboundUpgrade<C> for FromFnUpgrade<P, F>
where
P: ProtocolName + Clone,
Expand Down
25 changes: 10 additions & 15 deletions examples/file-sharing/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use futures::prelude::*;

use libp2p::{
core::{
upgrade::{read_length_prefixed, write_length_prefixed, ProtocolName},
upgrade::{read_length_prefixed, write_length_prefixed},
Multiaddr,
},
identity,
Expand All @@ -19,6 +19,7 @@ use libp2p::{
PeerId,
};

use libp2p::core::upgrade;
use std::collections::{hash_map, HashMap, HashSet};
use std::error::Error;
use std::iter;
Expand Down Expand Up @@ -53,7 +54,7 @@ pub async fn new(
kademlia: Kademlia::new(peer_id, MemoryStore::new(peer_id)),
request_response: request_response::Behaviour::new(
FileExchangeCodec(),
iter::once((FileExchangeProtocol(), ProtocolSupport::Full)),
iter::once((FILE_EXCHANGE_PROTOCOL, ProtocolSupport::Full)),
Default::default(),
),
},
Expand Down Expand Up @@ -453,30 +454,24 @@ pub enum Event {

// Simple file exchange protocol

#[derive(Debug, Clone)]
struct FileExchangeProtocol();
const FILE_EXCHANGE_PROTOCOL: upgrade::Protocol =
upgrade::Protocol::from_static("/file-exchange/1");

#[derive(Clone)]
struct FileExchangeCodec();
#[derive(Debug, Clone, PartialEq, Eq)]
struct FileRequest(String);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileResponse(Vec<u8>);

impl ProtocolName for FileExchangeProtocol {
fn protocol_name(&self) -> &[u8] {
"/file-exchange/1".as_bytes()
}
}

#[async_trait]
impl request_response::Codec for FileExchangeCodec {
type Protocol = FileExchangeProtocol;
type Request = FileRequest;
type Response = FileResponse;

async fn read_request<T>(
&mut self,
_: &FileExchangeProtocol,
_: &upgrade::Protocol,
io: &mut T,
) -> io::Result<Self::Request>
where
Expand All @@ -493,7 +488,7 @@ impl request_response::Codec for FileExchangeCodec {

async fn read_response<T>(
&mut self,
_: &FileExchangeProtocol,
_: &upgrade::Protocol,
io: &mut T,
) -> io::Result<Self::Response>
where
Expand All @@ -510,7 +505,7 @@ impl request_response::Codec for FileExchangeCodec {

async fn write_request<T>(
&mut self,
_: &FileExchangeProtocol,
_: &upgrade::Protocol,
io: &mut T,
FileRequest(data): FileRequest,
) -> io::Result<()>
Expand All @@ -525,7 +520,7 @@ impl request_response::Codec for FileExchangeCodec {

async fn write_response<T>(
&mut self,
_: &FileExchangeProtocol,
_: &upgrade::Protocol,
io: &mut T,
FileResponse(data): FileResponse,
) -> io::Result<()>
Expand Down
13 changes: 7 additions & 6 deletions misc/metrics/src/identify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
// DEALINGS IN THE SOFTWARE.

use crate::protocol_stack;
use libp2p_core::upgrade::Protocol;
use libp2p_identity::PeerId;
use prometheus_client::encoding::{EncodeLabelSet, EncodeMetric, MetricEncoder};
use prometheus_client::metrics::counter::Counter;
Expand Down Expand Up @@ -134,12 +135,12 @@ impl super::Recorder<libp2p_identify::Event> for Metrics {
}
libp2p_identify::Event::Received { peer_id, info, .. } => {
{
let mut protocols: Vec<String> = info
let mut protocols = info
.protocols
.iter()
.filter_map(|p| Protocol::try_from_owned(p.to_owned()).ok())
.filter(|p| {
let allowed_protocols: &[&[u8]] = &[
#[cfg(feature = "dcutr")]
let allowed_protocols = [
libp2p_dcutr::PROTOCOL_NAME,
// #[cfg(feature = "gossipsub")]
// #[cfg(not(target_os = "unknown"))]
Expand All @@ -156,10 +157,10 @@ impl super::Recorder<libp2p_identify::Event> for Metrics {
libp2p_relay::HOP_PROTOCOL_NAME,
];

allowed_protocols.contains(&p.as_bytes())
allowed_protocols.contains(p)
})
.cloned()
.collect();
.map(|p| p.to_string())
.collect::<Vec<_>>();

// Signal via an additional label value that one or more
// protocols of the remote peer have not been recognized.
Expand Down
5 changes: 3 additions & 2 deletions protocols/autonat/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
mod as_client;
mod as_server;

use crate::protocol::{AutoNatCodec, AutoNatProtocol, DialRequest, DialResponse, ResponseError};
use crate::protocol::{AutoNatCodec, DialRequest, DialResponse, ResponseError};
use crate::DEFAULT_PROTOCOL_NAME;
use as_client::AsClient;
pub use as_client::{OutboundProbeError, OutboundProbeEvent};
use as_server::AsServer;
Expand Down Expand Up @@ -218,7 +219,7 @@ pub struct Behaviour {

impl Behaviour {
pub fn new(local_peer_id: PeerId, config: Config) -> Self {
let protocols = iter::once((AutoNatProtocol, ProtocolSupport::Full));
let protocols = iter::once((DEFAULT_PROTOCOL_NAME, ProtocolSupport::Full));
let mut cfg = request_response::Config::default();
cfg.set_request_timeout(config.timeout);
let inner = request_response::Behaviour::new(AutoNatCodec, protocols, cfg);
Expand Down
31 changes: 7 additions & 24 deletions protocols/autonat/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,38 +21,25 @@
use crate::proto;
use async_trait::async_trait;
use futures::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
use libp2p_core::upgrade::Protocol;
use libp2p_core::{upgrade, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_request_response::{self as request_response, ProtocolName};
use libp2p_request_response::{self as request_response};
use quick_protobuf::{BytesReader, Writer};
use std::{convert::TryFrom, io};

#[derive(Clone, Debug)]
pub struct AutoNatProtocol;

/// The protocol name used for negotiating with multistream-select.
pub const DEFAULT_PROTOCOL_NAME: &[u8] = b"/libp2p/autonat/1.0.0";

impl ProtocolName for AutoNatProtocol {
fn protocol_name(&self) -> &[u8] {
DEFAULT_PROTOCOL_NAME
}
}
pub const DEFAULT_PROTOCOL_NAME: Protocol = Protocol::from_static("/libp2p/autonat/1.0.0");

#[derive(Clone)]
pub struct AutoNatCodec;

#[async_trait]
impl request_response::Codec for AutoNatCodec {
type Protocol = AutoNatProtocol;
type Request = DialRequest;
type Response = DialResponse;

async fn read_request<T>(
&mut self,
_: &AutoNatProtocol,
io: &mut T,
) -> io::Result<Self::Request>
async fn read_request<T>(&mut self, _: &Protocol, io: &mut T) -> io::Result<Self::Request>
where
T: AsyncRead + Send + Unpin,
{
Expand All @@ -61,11 +48,7 @@ impl request_response::Codec for AutoNatCodec {
Ok(request)
}

async fn read_response<T>(
&mut self,
_: &AutoNatProtocol,
io: &mut T,
) -> io::Result<Self::Response>
async fn read_response<T>(&mut self, _: &Protocol, io: &mut T) -> io::Result<Self::Response>
where
T: AsyncRead + Send + Unpin,
{
Expand All @@ -76,7 +59,7 @@ impl request_response::Codec for AutoNatCodec {

async fn write_request<T>(
&mut self,
_: &AutoNatProtocol,
_: &Protocol,
io: &mut T,
data: Self::Request,
) -> io::Result<()>
Expand All @@ -89,7 +72,7 @@ impl request_response::Codec for AutoNatCodec {

async fn write_response<T>(
&mut self,
_: &AutoNatProtocol,
_: &Protocol,
io: &mut T,
data: Self::Response,
) -> io::Result<()>
Expand Down
4 changes: 2 additions & 2 deletions protocols/gossipsub/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3249,7 +3249,7 @@ where
.get(&peer_id)
.expect("Connected peer must be registered")
.kind;
metrics.peer_protocol_disconnected(peer_kind.clone());
metrics.peer_protocol_disconnected(*peer_kind);
}

self.connected_peers.remove(&peer_id);
Expand Down Expand Up @@ -3346,7 +3346,7 @@ where
// We have identified the protocol this peer is using

if let Some(metrics) = self.metrics.as_mut() {
metrics.peer_protocol_connected(kind.clone());
metrics.peer_protocol_connected(kind);
}

if let PeerKind::NotSupported = kind {
Expand Down
20 changes: 10 additions & 10 deletions protocols/gossipsub/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -886,9 +886,9 @@ mod test {
use super::*;
use crate::protocol::ProtocolConfig;
use crate::topic::IdentityHash;
use crate::types::PeerKind;
use crate::Topic;
use libp2p_core::UpgradeInfo;
use libp2p_core::upgrade::Protocol;
use libp2p_core::UpgradeProtocols;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

Expand Down Expand Up @@ -991,15 +991,15 @@ mod test {
assert_eq!(builder.custom_id_version(), &None);

let protocol_config = ProtocolConfig::new(&builder);
let protocol_ids = protocol_config.protocol_info();
let protocol_ids = protocol_config.protocols().collect::<Vec<Protocol>>();

assert_eq!(protocol_ids.len(), 2);

assert_eq!(protocol_ids[0].protocol_id, b"/purple/1.1.0".to_vec());
assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsubv1_1);
assert_eq!(protocol_ids[0], Protocol::from_static("/purple/1.1.0"));
// assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsubv1_1); // TODO

assert_eq!(protocol_ids[1].protocol_id, b"/purple/1.0.0".to_vec());
assert_eq!(protocol_ids[1].kind, PeerKind::Gossipsub);
assert_eq!(protocol_ids[1], Protocol::from_static("/purple/1.0.0"));
// assert_eq!(protocol_ids[1].kind, PeerKind::Gossipsub); // TODO
}

#[test]
Expand All @@ -1015,11 +1015,11 @@ mod test {
assert_eq!(builder.custom_id_version(), &Some(Version::V1_0));

let protocol_config = ProtocolConfig::new(&builder);
let protocol_ids = protocol_config.protocol_info();
let protocol_ids = protocol_config.protocols().collect::<Vec<_>>();

assert_eq!(protocol_ids.len(), 1);

assert_eq!(protocol_ids[0].protocol_id, b"purple".to_vec());
assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsub);
assert_eq!(protocol_ids[0], Protocol::from_static("purple"));
// assert_eq!(protocol_ids[0].kind, PeerKind::Gossipsub);
}
}
Loading

0 comments on commit f909139

Please sign in to comment.