From 3b3a1d2b99512aa3bb52a2af6fe6adc8c63ac984 Mon Sep 17 00:00:00 2001
From: Dmitry Markin <dmitry@markin.tech>
Date: Fri, 21 Jun 2024 17:38:22 +0300
Subject: [PATCH] sc-network-types: implement `From<IpAddr> for Multiaddr`
 (#4855)

Add `From` implementation used by downstream project.

Ref.
https://github.com/paritytech/polkadot-sdk/pull/4198#discussion_r1648676102

CC @nazar-pc
---
 .../client/network/types/src/multiaddr.rs     | 22 ++++++++++++++++
 .../network/types/src/multiaddr/protocol.rs   | 26 ++++++++++++++++++-
 2 files changed, 47 insertions(+), 1 deletion(-)

diff --git a/substrate/client/network/types/src/multiaddr.rs b/substrate/client/network/types/src/multiaddr.rs
index 312bef9baab..de317e2aa1c 100644
--- a/substrate/client/network/types/src/multiaddr.rs
+++ b/substrate/client/network/types/src/multiaddr.rs
@@ -22,6 +22,7 @@ use litep2p::types::multiaddr::{
 };
 use std::{
 	fmt::{self, Debug, Display},
+	net::{IpAddr, Ipv4Addr, Ipv6Addr},
 	str::FromStr,
 };
 
@@ -102,6 +103,27 @@ impl From<Multiaddr> for LiteP2pMultiaddr {
 	}
 }
 
+impl From<IpAddr> for Multiaddr {
+	fn from(v: IpAddr) -> Multiaddr {
+		match v {
+			IpAddr::V4(a) => a.into(),
+			IpAddr::V6(a) => a.into(),
+		}
+	}
+}
+
+impl From<Ipv4Addr> for Multiaddr {
+	fn from(v: Ipv4Addr) -> Multiaddr {
+		Protocol::Ip4(v).into()
+	}
+}
+
+impl From<Ipv6Addr> for Multiaddr {
+	fn from(v: Ipv6Addr) -> Multiaddr {
+		Protocol::Ip6(v).into()
+	}
+}
+
 impl TryFrom<Vec<u8>> for Multiaddr {
 	type Error = ParseError;
 
diff --git a/substrate/client/network/types/src/multiaddr/protocol.rs b/substrate/client/network/types/src/multiaddr/protocol.rs
index 800d08fe36b..2a3b59e6a68 100644
--- a/substrate/client/network/types/src/multiaddr/protocol.rs
+++ b/substrate/client/network/types/src/multiaddr/protocol.rs
@@ -20,7 +20,7 @@ use crate::multihash::Multihash;
 use litep2p::types::multiaddr::Protocol as LiteP2pProtocol;
 use std::{
 	borrow::Cow,
-	net::{Ipv4Addr, Ipv6Addr},
+	net::{IpAddr, Ipv4Addr, Ipv6Addr},
 };
 
 /// [`Protocol`] describes all possible multiaddress protocols.
@@ -60,6 +60,30 @@ pub enum Protocol<'a> {
 	Wss(Cow<'a, str>),
 }
 
+impl<'a> From<IpAddr> for Protocol<'a> {
+	#[inline]
+	fn from(addr: IpAddr) -> Self {
+		match addr {
+			IpAddr::V4(addr) => Protocol::Ip4(addr),
+			IpAddr::V6(addr) => Protocol::Ip6(addr),
+		}
+	}
+}
+
+impl<'a> From<Ipv4Addr> for Protocol<'a> {
+	#[inline]
+	fn from(addr: Ipv4Addr) -> Self {
+		Protocol::Ip4(addr)
+	}
+}
+
+impl<'a> From<Ipv6Addr> for Protocol<'a> {
+	#[inline]
+	fn from(addr: Ipv6Addr) -> Self {
+		Protocol::Ip6(addr)
+	}
+}
+
 impl<'a> From<LiteP2pProtocol<'a>> for Protocol<'a> {
 	fn from(protocol: LiteP2pProtocol<'a>) -> Self {
 		match protocol {
-- 
GitLab