mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-05-09 18:47:59 +00:00
24d09fe8c7
* Add ProtocolName custom type * Use new ProtocolName in sc_network_common * Use new ProtocolName in sc_network * Use new ProtocolName for BEEFY and GRANDPA * Use new ProtocolName for notifications * Use new ProtocolName in sc_network (part 2) * Use new ProtocolName in sc_network_gossip * Use new ProtocolName in sc_offchain * Remove unused imports * Some more fixes * Add tests * Fix minor import issues * Re-export ProtocolName in sc_network * Revert "Re-export ProtocolName in sc_network" This reverts commit 8d8ff71927e7750757f29c9bbd88dc0ba181d214. * Re-export ProtocolName in sc_network * Remove dependency on sc-network-common from beefy-gadget
174 lines
5.3 KiB
Rust
174 lines
5.3 KiB
Rust
// This file is part of Substrate.
|
|
|
|
// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
|
|
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU General Public License for more details.
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
//! Configuration of the networking layer.
|
|
|
|
use libp2p::{multiaddr, Multiaddr, PeerId};
|
|
use std::{fmt, str, str::FromStr};
|
|
|
|
/// Protocol name prefix, transmitted on the wire for legacy protocol names.
|
|
/// I.e., `dot` in `/dot/sync/2`. Should be unique for each chain. Always UTF-8.
|
|
/// Deprecated in favour of genesis hash & fork ID based protocol names.
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub struct ProtocolId(smallvec::SmallVec<[u8; 6]>);
|
|
|
|
impl<'a> From<&'a str> for ProtocolId {
|
|
fn from(bytes: &'a str) -> ProtocolId {
|
|
Self(bytes.as_bytes().into())
|
|
}
|
|
}
|
|
|
|
impl AsRef<str> for ProtocolId {
|
|
fn as_ref(&self) -> &str {
|
|
str::from_utf8(&self.0[..])
|
|
.expect("the only way to build a ProtocolId is through a UTF-8 String; qed")
|
|
}
|
|
}
|
|
|
|
impl fmt::Debug for ProtocolId {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
fmt::Debug::fmt(self.as_ref(), f)
|
|
}
|
|
}
|
|
|
|
/// Parses a string address and splits it into Multiaddress and PeerId, if
|
|
/// valid.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```
|
|
/// # use libp2p::{Multiaddr, PeerId};
|
|
/// # use sc_network_common::config::parse_str_addr;
|
|
/// let (peer_id, addr) = parse_str_addr(
|
|
/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"
|
|
/// ).unwrap();
|
|
/// assert_eq!(peer_id, "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse::<PeerId>().unwrap());
|
|
/// assert_eq!(addr, "/ip4/198.51.100.19/tcp/30333".parse::<Multiaddr>().unwrap());
|
|
/// ```
|
|
pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> {
|
|
let addr: Multiaddr = addr_str.parse()?;
|
|
parse_addr(addr)
|
|
}
|
|
|
|
/// Splits a Multiaddress into a Multiaddress and PeerId.
|
|
pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> {
|
|
let who = match addr.pop() {
|
|
Some(multiaddr::Protocol::P2p(key)) =>
|
|
PeerId::from_multihash(key).map_err(|_| ParseErr::InvalidPeerId)?,
|
|
_ => return Err(ParseErr::PeerIdMissing),
|
|
};
|
|
|
|
Ok((who, addr))
|
|
}
|
|
|
|
/// Address of a node, including its identity.
|
|
///
|
|
/// This struct represents a decoded version of a multiaddress that ends with `/p2p/<peerid>`.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```
|
|
/// # use libp2p::{Multiaddr, PeerId};
|
|
/// # use sc_network_common::config::MultiaddrWithPeerId;
|
|
/// let addr: MultiaddrWithPeerId =
|
|
/// "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse().unwrap();
|
|
/// assert_eq!(addr.peer_id.to_base58(), "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV");
|
|
/// assert_eq!(addr.multiaddr.to_string(), "/ip4/198.51.100.19/tcp/30333");
|
|
/// ```
|
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
|
|
#[serde(try_from = "String", into = "String")]
|
|
pub struct MultiaddrWithPeerId {
|
|
/// Address of the node.
|
|
pub multiaddr: Multiaddr,
|
|
/// Its identity.
|
|
pub peer_id: PeerId,
|
|
}
|
|
|
|
impl MultiaddrWithPeerId {
|
|
/// Concatenates the multiaddress and peer ID into one multiaddress containing both.
|
|
pub fn concat(&self) -> Multiaddr {
|
|
let proto = multiaddr::Protocol::P2p(From::from(self.peer_id));
|
|
self.multiaddr.clone().with(proto)
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for MultiaddrWithPeerId {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
fmt::Display::fmt(&self.concat(), f)
|
|
}
|
|
}
|
|
|
|
impl FromStr for MultiaddrWithPeerId {
|
|
type Err = ParseErr;
|
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
let (peer_id, multiaddr) = parse_str_addr(s)?;
|
|
Ok(Self { peer_id, multiaddr })
|
|
}
|
|
}
|
|
|
|
impl From<MultiaddrWithPeerId> for String {
|
|
fn from(ma: MultiaddrWithPeerId) -> String {
|
|
format!("{}", ma)
|
|
}
|
|
}
|
|
|
|
impl TryFrom<String> for MultiaddrWithPeerId {
|
|
type Error = ParseErr;
|
|
fn try_from(string: String) -> Result<Self, Self::Error> {
|
|
string.parse()
|
|
}
|
|
}
|
|
|
|
/// Error that can be generated by `parse_str_addr`.
|
|
#[derive(Debug)]
|
|
pub enum ParseErr {
|
|
/// Error while parsing the multiaddress.
|
|
MultiaddrParse(multiaddr::Error),
|
|
/// Multihash of the peer ID is invalid.
|
|
InvalidPeerId,
|
|
/// The peer ID is missing from the address.
|
|
PeerIdMissing,
|
|
}
|
|
|
|
impl fmt::Display for ParseErr {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::MultiaddrParse(err) => write!(f, "{}", err),
|
|
Self::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"),
|
|
Self::PeerIdMissing => write!(f, "Peer id is missing from the address"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for ParseErr {
|
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
match self {
|
|
Self::MultiaddrParse(err) => Some(err),
|
|
Self::InvalidPeerId => None,
|
|
Self::PeerIdMissing => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<multiaddr::Error> for ParseErr {
|
|
fn from(err: multiaddr::Error) -> ParseErr {
|
|
Self::MultiaddrParse(err)
|
|
}
|
|
}
|