2018-05-24 00:54:08 +02:00
|
|
|
// Copyright 2018 Parity Technologies (UK) Ltd.
|
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a
|
|
|
|
// copy of this software and associated documentation files (the "Software"),
|
|
|
|
// to deal in the Software without restriction, including without limitation
|
|
|
|
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
|
|
// and/or sell copies of the Software, and to permit persons to whom the
|
|
|
|
// Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in
|
|
|
|
// all copies or substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
|
|
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
|
|
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
2019-01-07 11:21:09 +01:00
|
|
|
use crate::PublicKey;
|
2020-12-15 14:40:39 +01:00
|
|
|
use multihash::{Code, Error, Multihash, MultihashDigest};
|
2020-03-05 16:49:36 +01:00
|
|
|
use rand::Rng;
|
2020-12-15 14:40:39 +01:00
|
|
|
use std::{convert::TryFrom, fmt, str::FromStr};
|
|
|
|
use thiserror::Error;
|
2018-06-05 12:29:59 +02:00
|
|
|
|
2019-09-04 19:40:28 +02:00
|
|
|
/// Public keys with byte-lengths smaller than `MAX_INLINE_KEY_LENGTH` will be
|
|
|
|
/// automatically used as the peer id using an identity multihash.
|
2020-03-24 11:56:06 +01:00
|
|
|
const MAX_INLINE_KEY_LENGTH: usize = 42;
|
2019-09-04 19:40:28 +02:00
|
|
|
|
2018-05-24 00:54:08 +02:00
|
|
|
/// Identifier of a peer of the network.
|
|
|
|
///
|
|
|
|
/// The data is a multihash of the public key of the peer.
|
2020-12-15 14:40:39 +01:00
|
|
|
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
2018-05-24 00:54:08 +02:00
|
|
|
pub struct PeerId {
|
2020-12-15 14:40:39 +01:00
|
|
|
multihash: Multihash,
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Debug for PeerId {
|
2019-02-11 14:58:15 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2019-03-23 10:08:07 +01:00
|
|
|
f.debug_tuple("PeerId")
|
|
|
|
.field(&self.to_base58())
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for PeerId {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
self.to_base58().fmt(f)
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PeerId {
|
|
|
|
/// Builds a `PeerId` from a public key.
|
2019-03-11 13:42:53 +01:00
|
|
|
pub fn from_public_key(key: PublicKey) -> PeerId {
|
|
|
|
let key_enc = key.into_protobuf_encoding();
|
2019-09-04 19:40:28 +02:00
|
|
|
|
2020-08-26 13:03:35 +02:00
|
|
|
let hash_algorithm = if key_enc.len() <= MAX_INLINE_KEY_LENGTH {
|
|
|
|
Code::Identity
|
2020-03-24 11:56:06 +01:00
|
|
|
} else {
|
2020-08-26 13:03:35 +02:00
|
|
|
Code::Sha2_256
|
2020-03-24 11:56:06 +01:00
|
|
|
};
|
2020-01-29 11:33:19 +01:00
|
|
|
|
2020-12-15 14:40:39 +01:00
|
|
|
let multihash = hash_algorithm.digest(&key_enc);
|
2020-02-13 10:36:14 +01:00
|
|
|
|
2020-08-26 13:03:35 +02:00
|
|
|
PeerId { multihash }
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
|
2020-12-15 14:40:39 +01:00
|
|
|
/// Parses a `PeerId` from bytes.
|
|
|
|
pub fn from_bytes(data: &[u8]) -> Result<PeerId, Error> {
|
|
|
|
Ok(PeerId::from_multihash(Multihash::from_bytes(&data)?)
|
|
|
|
.map_err(|mh| Error::UnsupportedCode(mh.code()))?)
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
|
2020-08-26 13:03:35 +02:00
|
|
|
/// Tries to turn a `Multihash` into a `PeerId`.
|
|
|
|
///
|
|
|
|
/// If the multihash does not use a valid hashing algorithm for peer IDs,
|
|
|
|
/// or the hash value does not satisfy the constraints for a hashed
|
|
|
|
/// peer ID, it is returned as an `Err`.
|
|
|
|
pub fn from_multihash(multihash: Multihash) -> Result<PeerId, Multihash> {
|
2020-11-17 11:15:20 +01:00
|
|
|
match Code::try_from(multihash.code()) {
|
2020-12-15 14:40:39 +01:00
|
|
|
Ok(Code::Sha2_256) => Ok(PeerId { multihash }),
|
2020-11-17 11:15:20 +01:00
|
|
|
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH
|
2020-12-15 14:40:39 +01:00
|
|
|
=> Ok(PeerId { multihash }),
|
2020-08-26 13:03:35 +02:00
|
|
|
_ => Err(multihash)
|
2018-08-10 17:47:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-20 13:44:36 +01:00
|
|
|
/// Generates a random peer ID from a cryptographically secure PRNG.
|
|
|
|
///
|
|
|
|
/// This is useful for randomly walking on a DHT, or for testing purposes.
|
|
|
|
pub fn random() -> PeerId {
|
2020-03-05 16:49:36 +01:00
|
|
|
let peer_id = rand::thread_rng().gen::<[u8; 32]>();
|
2018-11-20 13:44:36 +01:00
|
|
|
PeerId {
|
2020-11-17 11:15:20 +01:00
|
|
|
multihash: Multihash::wrap(Code::Identity.into(), &peer_id)
|
2020-12-15 14:40:39 +01:00
|
|
|
.expect("The digest size is never too large")
|
2018-11-20 13:44:36 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-24 00:54:08 +02:00
|
|
|
/// Returns a raw bytes representation of this `PeerId`.
|
2020-12-15 14:40:39 +01:00
|
|
|
pub fn to_bytes(&self) -> Vec<u8> {
|
|
|
|
self.multihash.to_bytes()
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a base-58 encoded string of this `PeerId`.
|
|
|
|
pub fn to_base58(&self) -> String {
|
2020-12-15 14:40:39 +01:00
|
|
|
bs58::encode(self.to_bytes()).into_string()
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Checks whether the public key passed as parameter matches the public key of this `PeerId`.
|
|
|
|
///
|
|
|
|
/// Returns `None` if this `PeerId`s hash algorithm is not supported when encoding the
|
|
|
|
/// given public key, otherwise `Some` boolean as the result of an equality check.
|
2018-06-25 17:56:36 +02:00
|
|
|
pub fn is_public_key(&self, public_key: &PublicKey) -> Option<bool> {
|
2020-12-15 14:40:39 +01:00
|
|
|
let alg = Code::try_from(self.multihash.code())
|
2020-11-17 11:15:20 +01:00
|
|
|
.expect("Internal multihash is always a valid `Code`");
|
2019-03-11 13:42:53 +01:00
|
|
|
let enc = public_key.clone().into_protobuf_encoding();
|
2020-12-15 14:40:39 +01:00
|
|
|
Some(alg.digest(&enc) == self.multihash)
|
2020-01-29 11:33:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-25 17:56:36 +02:00
|
|
|
impl From<PublicKey> for PeerId {
|
|
|
|
fn from(key: PublicKey) -> PeerId {
|
|
|
|
PeerId::from_public_key(key)
|
2018-06-05 12:29:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-17 14:16:50 +02:00
|
|
|
impl TryFrom<Vec<u8>> for PeerId {
|
|
|
|
type Error = Vec<u8>;
|
|
|
|
|
|
|
|
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
|
2020-12-15 14:40:39 +01:00
|
|
|
PeerId::from_bytes(&value).map_err(|_| value)
|
2019-04-17 14:16:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-26 13:03:35 +02:00
|
|
|
impl TryFrom<Multihash> for PeerId {
|
|
|
|
type Error = Multihash;
|
2019-04-17 14:16:50 +02:00
|
|
|
|
2020-08-26 13:03:35 +02:00
|
|
|
fn try_from(value: Multihash) -> Result<Self, Self::Error> {
|
2019-04-17 14:16:50 +02:00
|
|
|
PeerId::from_multihash(value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-15 14:40:39 +01:00
|
|
|
impl AsRef<Multihash> for PeerId {
|
|
|
|
fn as_ref(&self) -> &Multihash {
|
2020-11-17 11:15:20 +01:00
|
|
|
&self.multihash
|
2018-11-29 12:11:35 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-15 14:40:39 +01:00
|
|
|
impl From<PeerId> for Multihash {
|
|
|
|
fn from(peer_id: PeerId) -> Self {
|
|
|
|
peer_id.multihash
|
2019-01-23 17:44:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-15 14:40:39 +01:00
|
|
|
impl From<PeerId> for Vec<u8> {
|
2020-01-29 11:33:19 +01:00
|
|
|
fn from(peer_id: PeerId) -> Self {
|
2020-12-15 14:40:39 +01:00
|
|
|
peer_id.to_bytes()
|
2018-08-10 17:47:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-10 21:03:59 +08:00
|
|
|
#[derive(Debug, Error)]
|
|
|
|
pub enum ParseError {
|
|
|
|
#[error("base-58 decode error: {0}")]
|
|
|
|
B58(#[from] bs58::decode::Error),
|
|
|
|
#[error("decoding multihash failed")]
|
|
|
|
MultiHash,
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for PeerId {
|
|
|
|
type Err = ParseError;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
|
|
let bytes = bs58::decode(s).into_vec()?;
|
2020-12-15 14:40:39 +01:00
|
|
|
PeerId::from_bytes(&bytes).map_err(|_| ParseError::MultiHash)
|
2018-05-24 00:54:08 +02:00
|
|
|
}
|
|
|
|
}
|
2018-06-05 19:01:18 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2019-03-11 13:42:53 +01:00
|
|
|
use crate::{PeerId, identity};
|
2018-06-05 19:01:18 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn peer_id_is_public_key() {
|
2019-03-11 13:42:53 +01:00
|
|
|
let key = identity::Keypair::generate_ed25519().public();
|
|
|
|
let peer_id = key.clone().into_peer_id();
|
2018-06-25 17:56:36 +02:00
|
|
|
assert_eq!(peer_id.is_public_key(&key), Some(true));
|
2018-06-05 19:01:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn peer_id_into_bytes_then_from_bytes() {
|
2019-03-11 13:42:53 +01:00
|
|
|
let peer_id = identity::Keypair::generate_ed25519().public().into_peer_id();
|
2020-12-15 14:40:39 +01:00
|
|
|
let second = PeerId::from_bytes(&peer_id.to_bytes()).unwrap();
|
2018-06-05 19:01:18 +02:00
|
|
|
assert_eq!(peer_id, second);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn peer_id_to_base58_then_back() {
|
2019-03-11 13:42:53 +01:00
|
|
|
let peer_id = identity::Keypair::generate_ed25519().public().into_peer_id();
|
2018-06-05 19:01:18 +02:00
|
|
|
let second: PeerId = peer_id.to_base58().parse().unwrap();
|
|
|
|
assert_eq!(peer_id, second);
|
|
|
|
}
|
2018-11-20 13:44:36 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn random_peer_id_is_valid() {
|
|
|
|
for _ in 0 .. 5000 {
|
|
|
|
let peer_id = PeerId::random();
|
2020-12-15 14:40:39 +01:00
|
|
|
assert_eq!(peer_id, PeerId::from_bytes(&peer_id.to_bytes()).unwrap());
|
2018-11-20 13:44:36 +01:00
|
|
|
}
|
|
|
|
}
|
2018-06-05 19:01:18 +02:00
|
|
|
}
|