rust-libp2p/core/src/peer_id.rs

278 lines
8.9 KiB
Rust
Raw Normal View History

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.
use crate::PublicKey;
2018-05-24 00:54:08 +02:00
use bs58;
use quick_error::quick_error;
2018-05-24 00:54:08 +02:00
use multihash;
use std::{convert::TryFrom, fmt, str::FromStr};
/// Public keys with byte-lengths smaller than `MAX_INLINE_KEY_LENGTH` will be
/// automatically used as the peer id using an identity multihash.
Cherry-pick commits from master to stable-futures (#1296) * Implement Debug for (ed25519|secp256k1)::(Keypair|SecretKey) (#1285) * Fix possible arithmetic overflow in libp2p-kad. (#1291) When the number of active queries exceeds the (internal) JOBS_MAX_QUERIES limit, which is only supposed to bound the number of concurrent queries relating to background jobs, an arithmetic overflow occurs. This is fixed by using saturating subtraction. * protocols/plaintext: Add example on how to upgrade with PlainTextConfig1 (#1286) * [mdns] - Support for long mDNS names (Bug #1232) (#1287) * Dead code -- commenting out with a note referencing future implementation * Adding "std" feature so that cargo can build in other directories (notably `misc/mdns`, so that I could run these tests) * Permitting `PeerID` to be built from an `Identity` multihash * The length limit for DNS labels is 63 characters, as per RFC1035 * Allocates the vector with capacity for the service name plus additional QNAME encoding bytes * Added support for encoding/decoding peer IDs with an encoded length greater than 63 characters * Removing "std" from ring features Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com> * Retaining MAX_INLINE_KEY_LENGTH with comment about future usage * `segment_peer_id` consumes `peer_id` ... plus an early return for IDs that don't need to be segmented * Fixing logic * Bump most dependencies (#1268) * Bump most dependencies This actually builds 😊. * Bump all dependencies Includes the excellent work of @rschulman in #1265. * Remove use of ed25519-dalek fork * Monomorphize more dependencies * Add compatibility hack for rand Cargo allows a crate to depend on multiple versions of another, but `cargo-web` panics in that situation. Use a wrapper crate to work around the panic. * Use @tomaka’s idea for using a newer `rand` instead of my own ugly hack. * Switch to Parity master as its dependency-bumping PR has been merged. * Update some depenendencies again * Remove unwraps and `#[allow(deprecated)]`. * Remove spurious changes to dependencies Bumping minor or patch versions is not needed, and increases likelyhood of merge conflicts. * Remove some redundant Cargo.toml changes * Replace a retry loop with an expect `ed25519::SecretKey::from_bytes` will never fail for 32-byte inputs. * Revert changes that don’t belong in this PR * Remove using void to bypass ICE (#1295) * Publish 0.13.0 (#1294)
2019-11-06 16:09:15 +01:00
//
// Note: see `from_public_key` for how this value will be used in the future.
const MAX_INLINE_KEY_LENGTH: usize = 42;
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.
// TODO: maybe keep things in decoded version?
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PeerId {
multihash: 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 {
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.
#[inline]
pub fn from_public_key(key: PublicKey) -> PeerId {
let key_enc = key.into_protobuf_encoding();
// Note: the correct behaviour, according to the libp2p specifications, is the
// commented-out code, which consists it transmitting small keys un-hashed. However, this
// version and all previous versions of rust-libp2p always hash the key. Starting from
// version 0.13, rust-libp2p accepts both hashed and non-hashed keys as input
// (see `from_bytes`). Starting from version 0.14, rust-libp2p will switch to not hashing
// the key (a.k.a. the correct behaviour).
// In other words, rust-libp2p 0.13 is compatible with all versions of rust-libp2p.
// Rust-libp2p 0.12 and below is **NOT** compatible with rust-libp2p 0.14 and above.
/*let hash_algorithm = if key_enc.len() <= MAX_INLINE_KEY_LENGTH {
multihash::Hash::Identity
} else {
multihash::Hash::SHA2256
};*/
let hash_algorithm = multihash::Hash::SHA2256;
let multihash = multihash::encode(hash_algorithm, &key_enc)
.expect("identity and sha2-256 are always supported by known public key types");
PeerId { multihash }
2018-05-24 00:54:08 +02:00
}
/// Checks whether `data` is a valid `PeerId`. If so, returns the `PeerId`. If not, returns
/// back the data as an error.
#[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
|| multihash.algorithm() == multihash::Hash::Identity
{
Ok(PeerId { multihash })
} else {
Err(multihash.into_bytes())
}
}
Err(err) => Err(err.data),
2018-05-24 00:54:08 +02:00
}
}
/// Turns a `Multihash` into a `PeerId`. If the multihash doesn't use the correct algorithm,
/// returns back the data as an error.
#[inline]
pub fn from_multihash(data: multihash::Multihash) -> Result<PeerId, multihash::Multihash> {
Cherry-pick commits from master to stable-futures (#1296) * Implement Debug for (ed25519|secp256k1)::(Keypair|SecretKey) (#1285) * Fix possible arithmetic overflow in libp2p-kad. (#1291) When the number of active queries exceeds the (internal) JOBS_MAX_QUERIES limit, which is only supposed to bound the number of concurrent queries relating to background jobs, an arithmetic overflow occurs. This is fixed by using saturating subtraction. * protocols/plaintext: Add example on how to upgrade with PlainTextConfig1 (#1286) * [mdns] - Support for long mDNS names (Bug #1232) (#1287) * Dead code -- commenting out with a note referencing future implementation * Adding "std" feature so that cargo can build in other directories (notably `misc/mdns`, so that I could run these tests) * Permitting `PeerID` to be built from an `Identity` multihash * The length limit for DNS labels is 63 characters, as per RFC1035 * Allocates the vector with capacity for the service name plus additional QNAME encoding bytes * Added support for encoding/decoding peer IDs with an encoded length greater than 63 characters * Removing "std" from ring features Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com> * Retaining MAX_INLINE_KEY_LENGTH with comment about future usage * `segment_peer_id` consumes `peer_id` ... plus an early return for IDs that don't need to be segmented * Fixing logic * Bump most dependencies (#1268) * Bump most dependencies This actually builds 😊. * Bump all dependencies Includes the excellent work of @rschulman in #1265. * Remove use of ed25519-dalek fork * Monomorphize more dependencies * Add compatibility hack for rand Cargo allows a crate to depend on multiple versions of another, but `cargo-web` panics in that situation. Use a wrapper crate to work around the panic. * Use @tomaka’s idea for using a newer `rand` instead of my own ugly hack. * Switch to Parity master as its dependency-bumping PR has been merged. * Update some depenendencies again * Remove unwraps and `#[allow(deprecated)]`. * Remove spurious changes to dependencies Bumping minor or patch versions is not needed, and increases likelyhood of merge conflicts. * Remove some redundant Cargo.toml changes * Replace a retry loop with an expect `ed25519::SecretKey::from_bytes` will never fail for 32-byte inputs. * Revert changes that don’t belong in this PR * Remove using void to bypass ICE (#1295) * Publish 0.13.0 (#1294)
2019-11-06 16:09:15 +01:00
if data.algorithm() == multihash::Hash::SHA2256 || data.algorithm() == multihash::Hash::Identity {
Ok(PeerId { multihash: data })
} else {
Err(data)
}
}
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.
#[inline]
pub fn random() -> PeerId {
PeerId {
multihash: multihash::Multihash::random(multihash::Hash::SHA2256)
}
}
2018-05-24 00:54:08 +02:00
/// Returns a raw bytes representation of this `PeerId`.
///
/// Note that this is not the same as the public key of the peer.
2018-05-24 00:54:08 +02:00
#[inline]
pub fn into_bytes(self) -> Vec<u8> {
self.multihash.into_bytes()
2018-05-24 00:54:08 +02:00
}
/// Returns a raw bytes representation of this `PeerId`.
///
/// Note that this is not the same as the public key of the peer.
2018-05-24 00:54:08 +02:00
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.multihash.as_bytes()
2018-05-24 00:54:08 +02:00
}
/// Returns a base-58 encoded string of this `PeerId`.
#[inline]
pub fn to_base58(&self) -> String {
bs58::encode(self.multihash.as_bytes()).into_string()
2018-05-24 00:54:08 +02:00
}
/// Returns the raw bytes of the hash of this `PeerId`.
#[inline]
pub fn digest(&self) -> &[u8] {
self.multihash.digest()
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.
pub fn is_public_key(&self, public_key: &PublicKey) -> Option<bool> {
let alg = self.multihash.algorithm();
let enc = public_key.clone().into_protobuf_encoding();
match multihash::encode(alg, &enc) {
Ok(h) => Some(h == self.multihash),
Err(multihash::EncodeError::UnsupportedType) => None,
Err(multihash::EncodeError::UnsupportedInputLength) => None,
2018-05-24 00:54:08 +02:00
}
}
}
impl From<PublicKey> for PeerId {
#[inline]
fn from(key: PublicKey) -> PeerId {
PeerId::from_public_key(key)
}
}
impl TryFrom<Vec<u8>> for PeerId {
type Error = Vec<u8>;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
PeerId::from_bytes(value)
}
}
impl TryFrom<multihash::Multihash> for PeerId {
type Error = multihash::Multihash;
fn try_from(value: multihash::Multihash) -> Result<Self, Self::Error> {
PeerId::from_multihash(value)
}
}
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
}
}
2019-01-23 17:44:40 +01:00
impl AsRef<[u8]> for PeerId {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl Into<multihash::Multihash> for PeerId {
#[inline]
fn into(self) -> multihash::Multihash {
self.multihash
}
}
2018-05-24 00:54:08 +02:00
quick_error! {
#[derive(Debug)]
pub enum ParseError {
Update the stable-futures branch to master (#1288) * Configurable multistream-select protocol. Add V1Lazy variant. (#1245) Make the multistream-select protocol (version) configurable on transport upgrades as well as for individual substreams. Add a "lazy" variant of multistream-select 1.0 that delays sending of negotiation protocol frames as much as possible but is only safe to use under additional assumptions that go beyond what is required by the multistream-select v1 specification. * Improve the code readability of the chat example (#1253) * Add bridged chats (#1252) * Try fix CI (#1261) * Print Rust version on CI * Don't print where not appropriate * Change caching strategy * Remove win32 build * Remove win32 from list * Update libsecp256k1 dep to 0.3.0 (#1258) * Update libsecp256k1 dep to 0.3.0 * Sign now cannot fail * Upgrade url and percent-encoding deps to 2.1.0 (#1267) * Upgrade percent-encoding dep to 2.1.0 * Upgrade url dep to 2.1.0 * Revert CIPHERS set to null (#1273) * Update dependency versions (#1265) * Update versions of many dependencies * Bump version of rand * Updates for changed APIs in rand, ring, and webpki * Replace references to `snow::Session` `Session` no longer exists in `snow` but the replacement is two structs `HandshakeState` and `TransportState` Something will have to be done to harmonize `NoiseOutput.session` * Add precise type for UnparsedPublicKey * Update data structures/functions to match new snow's API * Delete diff.diff Remove accidentally committed diff file * Remove commented lines in identity/rsa.rs * Bump libsecp256k1 to 0.3.1 * Implement /plaintext/2.0.0 (#1236) * WIP * plaintext/2.0.0 * Refactor protobuf related issues to compatible with the spec * Rename: new PlainTextConfig -> PlainText2Config * Keep plaintext/1.0.0 as PlainText1Config * Config contains pubkey * Rename: proposition -> exchange * Add PeerId to Exchange * Check the validity of the remote's `Exchange` * Tweak * Delete unused import * Add debug log * Delete unused field: public_key_encoded * Delete unused field: local * Delete unused field: exchange_bytes * The inner instance should not be public * identity::Publickey::Rsa is not available on wasm * Delete PeerId from Config as it should be generated from the pubkey * Catch up for #1240 * Tweak * Update protocols/plaintext/src/error.rs Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com> * Update protocols/plaintext/src/handshake.rs Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com> * Update protocols/plaintext/src/error.rs Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com> * Update protocols/plaintext/src/error.rs Co-Authored-By: Roman Borschel <romanb@users.noreply.github.com> * Update protocols/plaintext/src/error.rs Co-Authored-By: Roman Borschel <romanb@users.noreply.github.com> * Rename: pubkey -> local_public_key * Delete unused error * Rename: PeerIdValidationFailed -> InvalidPeerId * Fix: HandShake -> Handshake * Use bytes insteadof Publickey to avoid code duplication * Replace with ProtobufError * Merge HandshakeContext<()> into HandshakeContext<Local> * Improve the peer ID validation to simplify the handshake * Propagate Remote to allow extracting the PeerId from the Remote * Collapse the same kind of errors into the variant * [noise]: `sodiumoxide 0.2.5` (#1276) Fixes https://github.com/RustSec/advisory-db/pull/192 * examples/ipfs-kad.rs: Remove outdated reference to `without_init` (#1280) * CircleCI Test Fix (#1282) * Disabling "Docker Layer Caching" because it breaks one of the circleci checks * Bump to trigger CircleCI build * unbump * zeroize: Upgrade to v1.0 (#1284) v1.0 final release is out. Release notes: https://github.com/iqlusioninc/crates/pull/279 * *: Consolidate protobuf scripts and update to rust-protobuf 2.8.1 (#1275) * *: Consolidate protobuf generation scripts * *: Update to rust-protobuf 2.8.1 * *: Mark protobuf generated modules with '_proto' * examples: Add distributed key value store (#1281) * examples: Add distributed key value store This commit adds a basic distributed key value store supporting GET and PUT commands using Kademlia and mDNS. * examples/distributed-key-value-store: Fix typo * Simple Warning Cleanup (#1278) * Cleaning up warnings - removing unused `use` * Cleaning up warnings - unused tuple value * Cleaning up warnings - removing dead code * Cleaning up warnings - fixing deprecated name * Cleaning up warnings - removing dead code * Revert "Cleaning up warnings - removing dead code" This reverts commit f18a765e4bf240b0ed9294ec3ae5dab5c186b801. * Enable the std feature of ring (#1289)
2019-10-28 18:04:01 +01:00
B58(e: bs58::decode::Error) {
2018-05-24 00:54:08 +02:00
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 crate::{PeerId, identity};
#[test]
fn peer_id_is_public_key() {
let key = identity::Keypair::generate_ed25519().public();
let peer_id = key.clone().into_peer_id();
assert_eq!(peer_id.is_public_key(&key), Some(true));
}
#[test]
fn peer_id_into_bytes_then_from_bytes() {
let peer_id = identity::Keypair::generate_ed25519().public().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 = identity::Keypair::generate_ed25519().public().into_peer_id();
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();
assert_eq!(peer_id, PeerId::from_bytes(peer_id.clone().into_bytes()).unwrap());
}
}
}