use crate::protocol;
use codec::Encode;
use libp2p::{multiaddr, Multiaddr, PeerId};
use std::{fmt, str, str::FromStr};
#[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)
}
}
pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> {
let addr: Multiaddr = addr_str.parse()?;
parse_addr(addr)
}
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))
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(try_from = "String", into = "String")]
pub struct MultiaddrWithPeerId {
pub multiaddr: Multiaddr,
pub peer_id: PeerId,
}
impl MultiaddrWithPeerId {
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()
}
}
#[derive(Debug)]
pub enum ParseErr {
MultiaddrParse(multiaddr::Error),
InvalidPeerId,
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)
}
}
#[derive(Clone, Debug)]
pub struct SetConfig {
pub in_peers: u32,
pub out_peers: u32,
pub reserved_nodes: Vec<MultiaddrWithPeerId>,
pub non_reserved_mode: NonReservedPeerMode,
}
impl Default for SetConfig {
fn default() -> Self {
Self {
in_peers: 25,
out_peers: 75,
reserved_nodes: Vec::new(),
non_reserved_mode: NonReservedPeerMode::Accept,
}
}
}
#[derive(Debug, Clone)]
pub struct NotificationHandshake(Vec<u8>);
impl NotificationHandshake {
pub fn new<H: Encode>(handshake: H) -> Self {
Self(handshake.encode())
}
pub fn from_bytes(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl std::ops::Deref for NotificationHandshake {
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Clone, Debug)]
pub struct NonDefaultSetConfig {
pub notifications_protocol: protocol::ProtocolName,
pub fallback_names: Vec<protocol::ProtocolName>,
pub handshake: Option<NotificationHandshake>,
pub max_notification_size: u64,
pub set_config: SetConfig,
}
impl NonDefaultSetConfig {
pub fn new(notifications_protocol: protocol::ProtocolName, max_notification_size: u64) -> Self {
Self {
notifications_protocol,
max_notification_size,
fallback_names: Vec::new(),
handshake: None,
set_config: SetConfig {
in_peers: 0,
out_peers: 0,
reserved_nodes: Vec::new(),
non_reserved_mode: NonReservedPeerMode::Deny,
},
}
}
pub fn allow_non_reserved(&mut self, in_peers: u32, out_peers: u32) {
self.set_config.in_peers = in_peers;
self.set_config.out_peers = out_peers;
self.set_config.non_reserved_mode = NonReservedPeerMode::Accept;
}
pub fn add_reserved(&mut self, peer: MultiaddrWithPeerId) {
self.set_config.reserved_nodes.push(peer);
}
pub fn add_fallback_names(&mut self, fallback_names: Vec<protocol::ProtocolName>) {
self.fallback_names.extend(fallback_names);
}
}
#[derive(Clone, Debug)]
pub enum TransportConfig {
Normal {
enable_mdns: bool,
allow_private_ip: bool,
},
MemoryOnly,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NonReservedPeerMode {
Accept,
Deny,
}
impl NonReservedPeerMode {
pub fn parse(s: &str) -> Option<Self> {
match s {
"accept" => Some(Self::Accept),
"deny" => Some(Self::Deny),
_ => None,
}
}
}