From cc6b474b0d35f5fa3f00a742b1c0e18a9a1a25a3 Mon Sep 17 00:00:00 2001 From: hozan23 Date: Mon, 24 Jun 2024 19:25:57 +0200 Subject: p2p: use base64 to encode PeerID to string --- p2p/src/error.rs | 10 ++++++++-- p2p/src/peer/peer_id.rs | 29 ++++++++++++++++++++++------- 2 files changed, 30 insertions(+), 9 deletions(-) (limited to 'p2p/src') diff --git a/p2p/src/error.rs b/p2p/src/error.rs index 97b7b7f..a490b57 100644 --- a/p2p/src/error.rs +++ b/p2p/src/error.rs @@ -11,8 +11,11 @@ pub enum Error { #[error("Unsupported protocol error: {0}")] UnsupportedProtocol(String), - #[error("Try from public key Error: {0}")] - TryFromPublicKey(&'static str), + #[error("PeerID try from PublicKey Error")] + PeerIDTryFromPublicKey, + + #[error("PeerID try from String Error")] + PeerIDTryFromString, #[error("Invalid message error: {0}")] InvalidMsg(String), @@ -23,6 +26,9 @@ pub enum Error { #[error(transparent)] ParseIntError(#[from] std::num::ParseIntError), + #[error(transparent)] + ParseIntError2(#[from] base64::DecodeError), + #[error(transparent)] ParseFloatError(#[from] std::num::ParseFloatError), diff --git a/p2p/src/peer/peer_id.rs b/p2p/src/peer/peer_id.rs index a769c86..145c199 100644 --- a/p2p/src/peer/peer_id.rs +++ b/p2p/src/peer/peer_id.rs @@ -1,3 +1,4 @@ +use base64::{engine::general_purpose::STANDARD, Engine}; use bincode::{Decode, Encode}; use rand::{rngs::OsRng, RngCore}; use sha2::{Digest, Sha256}; @@ -12,16 +13,12 @@ use crate::Error; /// Represents a unique identifier for a peer. #[derive(Clone, Debug, Eq, PartialEq, Hash, Decode, Encode)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", serde(into = "String"))] pub struct PeerID(pub [u8; 32]); impl std::fmt::Display for PeerID { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - let id = self.0[0..8] - .iter() - .map(|b| format!("{:x}", b)) - .collect::>() - .join(""); - + let id = STANDARD.encode(self.0); write!(f, "{}", id) } } @@ -48,6 +45,24 @@ impl From<[u8; 32]> for PeerID { } } +impl From for String { + fn from(pid: PeerID) -> Self { + pid.to_string() + } +} + +impl TryFrom for PeerID { + type Error = Error; + + fn try_from(i: String) -> Result { + let result: [u8; 32] = STANDARD + .decode(i)? + .try_into() + .map_err(|_| Error::PeerIDTryFromString)?; + Ok(PeerID(result)) + } +} + impl TryFrom for PeerID { type Error = Error; @@ -55,7 +70,7 @@ impl TryFrom for PeerID { let pk: [u8; 32] = pk .as_bytes() .try_into() - .map_err(|_| Error::TryFromPublicKey("Failed to convert public key to [u8;32]"))?; + .map_err(|_| Error::PeerIDTryFromPublicKey)?; Ok(PeerID(pk)) } -- cgit v1.2.3