use crate::PublicKey;
use bs58;
use quick_error::quick_error;
use multihash;
use std::{fmt, str::FromStr};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PeerId {
multihash: multihash::Multihash,
}
impl fmt::Debug for PeerId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PeerId({})", self.to_base58())
}
}
impl PeerId {
#[inline]
pub fn from_public_key(public_key: PublicKey) -> PeerId {
let protobuf = public_key.into_protobuf_encoding();
let multihash = multihash::encode(multihash::Hash::SHA2256, &protobuf)
.expect("sha2-256 is always supported");
PeerId { multihash }
}
#[inline]
pub fn from_bytes(data: Vec<u8>) -> Result<PeerId, Vec<u8>> {
match multihash::Multihash::from_bytes(data) {
Ok(multihash) => {
if multihash.algorithm() == multihash::Hash::SHA2256 {
Ok(PeerId { multihash })
} else {
Err(multihash.into_bytes())
}
},
Err(err) => Err(err.data),
}
}
#[inline]
pub fn from_multihash(data: multihash::Multihash) -> Result<PeerId, multihash::Multihash> {
if data.algorithm() == multihash::Hash::SHA2256 {
Ok(PeerId { multihash: data })
} else {
Err(data)
}
}
#[inline]
pub fn random() -> PeerId {
PeerId {
multihash: multihash::Multihash::random(multihash::Hash::SHA2256)
}
}
#[inline]
pub fn into_bytes(self) -> Vec<u8> {
self.multihash.into_bytes()
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.multihash.as_bytes()
}
#[inline]
pub fn to_base58(&self) -> String {
bs58::encode(self.multihash.as_bytes()).into_string()
}
#[inline]
pub fn digest(&self) -> &[u8] {
self.multihash.digest()
}
pub fn is_public_key(&self, public_key: &PublicKey) -> Option<bool> {
let alg = self.multihash.algorithm();
match multihash::encode(alg, &public_key.clone().into_protobuf_encoding()) {
Ok(compare) => Some(compare == self.multihash),
Err(multihash::EncodeError::UnsupportedType) => None,
}
}
}
impl From<PublicKey> for PeerId {
#[inline]
fn from(key: PublicKey) -> PeerId {
PeerId::from_public_key(key)
}
}
impl PartialEq<multihash::Multihash> for PeerId {
#[inline]
fn eq(&self, other: &multihash::Multihash) -> bool {
&self.multihash == other
}
}
impl PartialEq<PeerId> for multihash::Multihash {
#[inline]
fn eq(&self, other: &PeerId) -> bool {
self == &other.multihash
}
}
impl AsRef<multihash::Multihash> for PeerId {
#[inline]
fn as_ref(&self) -> &multihash::Multihash {
&self.multihash
}
}
impl Into<multihash::Multihash> for PeerId {
#[inline]
fn into(self) -> multihash::Multihash {
self.multihash
}
}
quick_error! {
#[derive(Debug)]
pub enum ParseError {
B58(e: bs58::decode::DecodeError) {
display("base-58 decode error: {}", e)
cause(e)
from()
}
MultiHash {
display("decoding multihash failed")
}
}
}
impl FromStr for PeerId {
type Err = ParseError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bytes = bs58::decode(s).into_vec()?;
PeerId::from_bytes(bytes).map_err(|_| ParseError::MultiHash)
}
}
#[cfg(test)]
mod tests {
use rand::random;
use crate::{PeerId, PublicKey};
#[test]
fn peer_id_is_public_key() {
let key = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect());
let peer_id = PeerId::from_public_key(key.clone());
assert_eq!(peer_id.is_public_key(&key), Some(true));
}
#[test]
fn peer_id_into_bytes_then_from_bytes() {
let peer_id = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect()).into_peer_id();
let second = PeerId::from_bytes(peer_id.clone().into_bytes()).unwrap();
assert_eq!(peer_id, second);
}
#[test]
fn peer_id_to_base58_then_back() {
let peer_id = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect()).into_peer_id();
let second: PeerId = peer_id.to_base58().parse().unwrap();
assert_eq!(peer_id, second);
}
#[test]
fn random_peer_id_is_valid() {
for _ in 0 .. 5000 {
let peer_id = PeerId::random();
assert_eq!(peer_id, PeerId::from_bytes(peer_id.clone().into_bytes()).unwrap());
}
}
}