feat: replace ProtocolName with AsRef<str>

Previously, a protocol could be any sequence of bytes as long as it started with `/`. Now, we directly parse a protocol as `String` which enforces it to be valid UTF8.

To notify users of this change, we delete the `ProtocolName` trait. The new requirement is that users need to provide a type that implements `AsRef<str>`.

We also add a `StreamProtocol` newtype in `libp2p-swarm` which provides an easy way for users to ensure their protocol strings are compliant. The newtype enforces that protocol strings start with `/`. `StreamProtocol` also implements `AsRef<str>`, meaning users can directly use it in their upgrades.

`multistream-select` by itself only changes marginally with this patch. The only thing we enforce in the type-system is that protocols must implement `AsRef<str>`.

Resolves: #2831.

Pull-Request: #3746.
This commit is contained in:
Thomas Eizinger
2023-05-04 05:47:11 +01:00
committed by GitHub
parent 30d0f598ef
commit c93f753018
68 changed files with 539 additions and 561 deletions

View File

@ -20,6 +20,7 @@
use crate::protocol_stack;
use libp2p_identity::PeerId;
use libp2p_swarm::StreamProtocol;
use prometheus_client::encoding::{EncodeLabelSet, EncodeMetric, MetricEncoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
@ -134,11 +135,11 @@ 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(|p| {
let allowed_protocols: &[&[u8]] = &[
let allowed_protocols: &[StreamProtocol] = &[
#[cfg(feature = "dcutr")]
libp2p_dcutr::PROTOCOL_NAME,
// #[cfg(feature = "gossipsub")]
@ -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.