Skip to content

Commit

Permalink
into/to correctness for PublicKey -> PeerId
Browse files Browse the repository at this point in the history
  • Loading branch information
rubdos committed Jul 16, 2021
1 parent a38d214 commit 99d0834
Show file tree
Hide file tree
Showing 19 changed files with 57 additions and 44 deletions.
6 changes: 5 additions & 1 deletion core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
- Change `PublicKey::into_protobuf_encoding` to `PublicKey::to_protobuf_encoding` (see [PR 2145])
- Change `PublicKey::into_protobuf_encoding` to `PublicKey::to_protobuf_encoding`.
Change `PublicKey::into_peer_id` to `PublicKey::to_peer_id`.
Change `PeerId::from_public_key(PublicKey)` to `PeerId::from_public_key(PublicKey)`.
Add `From<&PublicKey> for PeerId`.
See [PR 2145]

[PR 2145]: https://github.com/libp2p/rust-libp2p/pull/2145

Expand Down
6 changes: 3 additions & 3 deletions core/benches/peer_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use libp2p_core::{identity, PeerId};
fn from_bytes(c: &mut Criterion) {
let peer_id_bytes = identity::Keypair::generate_ed25519()
.public()
.into_peer_id()
.to_peer_id()
.to_bytes();

c.bench_function("from_bytes", |b| {
Expand All @@ -37,7 +37,7 @@ fn from_bytes(c: &mut Criterion) {
fn clone(c: &mut Criterion) {
let peer_id = identity::Keypair::generate_ed25519()
.public()
.into_peer_id();
.to_peer_id();

c.bench_function("clone", |b| {
b.iter(|| {
Expand All @@ -51,7 +51,7 @@ fn sort_vec(c: &mut Criterion) {
.map(|_| {
identity::Keypair::generate_ed25519()
.public()
.into_peer_id()
.to_peer_id()
})
.collect();

Expand Down
4 changes: 2 additions & 2 deletions core/src/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ impl PublicKey {
}

/// Convert the `PublicKey` into the corresponding `PeerId`.
pub fn into_peer_id(self) -> PeerId {
pub fn to_peer_id(&self) -> PeerId {
self.into()
}
}
Expand All @@ -264,7 +264,7 @@ mod tests {
let encoded = base64::decode(base_64_encoded).unwrap();

let keypair = Keypair::from_protobuf_encoding(&encoded).unwrap();
let peer_id = keypair.public().into_peer_id();
let peer_id = keypair.public().to_peer_id();

assert_eq!(expected_peer_id, peer_id);
}
Expand Down
35 changes: 22 additions & 13 deletions core/src/peer_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ pub struct PeerId {

impl fmt::Debug for PeerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PeerId")
.field(&self.to_base58())
.finish()
f.debug_tuple("PeerId").field(&self.to_base58()).finish()
}
}

Expand All @@ -52,7 +50,7 @@ impl fmt::Display for PeerId {

impl PeerId {
/// Builds a `PeerId` from a public key.
pub fn from_public_key(key: PublicKey) -> PeerId {
pub fn from_public_key(key: &PublicKey) -> PeerId {
let key_enc = key.to_protobuf_encoding();

let hash_algorithm = if key_enc.len() <= MAX_INLINE_KEY_LENGTH {
Expand Down Expand Up @@ -80,9 +78,10 @@ impl PeerId {
pub fn from_multihash(multihash: Multihash) -> Result<PeerId, Multihash> {
match Code::try_from(multihash.code()) {
Ok(Code::Sha2_256) => Ok(PeerId { multihash }),
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH
=> Ok(PeerId { multihash }),
_ => Err(multihash)
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH => {
Ok(PeerId { multihash })
}
_ => Err(multihash),
}
}

Expand All @@ -93,7 +92,7 @@ impl PeerId {
let peer_id = rand::thread_rng().gen::<[u8; 32]>();
PeerId {
multihash: Multihash::wrap(Code::Identity.into(), &peer_id)
.expect("The digest size is never too large")
.expect("The digest size is never too large"),
}
}

Expand Down Expand Up @@ -121,6 +120,12 @@ impl PeerId {

impl From<PublicKey> for PeerId {
fn from(key: PublicKey) -> PeerId {
PeerId::from_public_key(&key)
}
}

impl From<&PublicKey> for PeerId {
fn from(key: &PublicKey) -> PeerId {
PeerId::from_public_key(key)
}
}
Expand Down Expand Up @@ -179,32 +184,36 @@ impl FromStr for PeerId {

#[cfg(test)]
mod tests {
use crate::{PeerId, identity};
use crate::{identity, PeerId};

#[test]
fn peer_id_is_public_key() {
let key = identity::Keypair::generate_ed25519().public();
let peer_id = key.clone().into_peer_id();
let peer_id = key.clone().to_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 peer_id = identity::Keypair::generate_ed25519()
.public()
.to_peer_id();
let second = PeerId::from_bytes(&peer_id.to_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 peer_id = identity::Keypair::generate_ed25519()
.public()
.to_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 {
for _ in 0..5000 {
let peer_id = PeerId::random();
assert_eq!(peer_id, PeerId::from_bytes(&peer_id.to_bytes()).unwrap());
}
Expand Down
4 changes: 2 additions & 2 deletions core/tests/transport_upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ where
#[test]
fn upgrade_pipeline() {
let listener_keys = identity::Keypair::generate_ed25519();
let listener_id = listener_keys.public().into_peer_id();
let listener_id = listener_keys.public().to_peer_id();
let listener_noise_keys = noise::Keypair::<noise::X25519Spec>::new().into_authentic(&listener_keys).unwrap();
let listener_transport = MemoryTransport::default()
.upgrade(upgrade::Version::V1)
Expand All @@ -96,7 +96,7 @@ fn upgrade_pipeline() {
});

let dialer_keys = identity::Keypair::generate_ed25519();
let dialer_id = dialer_keys.public().into_peer_id();
let dialer_id = dialer_keys.public().to_peer_id();
let dialer_noise_keys = noise::Keypair::<noise::X25519Spec>::new().into_authentic(&dialer_keys).unwrap();
let dialer_transport = MemoryTransport::default()
.upgrade(upgrade::Version::V1)
Expand Down
2 changes: 1 addition & 1 deletion misc/multistream-select/tests/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ type TestNetwork = Network<TestTransport, (), (), TestHandler>;

fn mk_transport(up: upgrade::Version) -> (PeerId, TestTransport) {
let keys = identity::Keypair::generate_ed25519();
let id = keys.public().into_peer_id();
let id = keys.public().to_peer_id();
(id, MemoryTransport::default()
.upgrade(up)
.authenticate(PlainText2Config { local_public_key: keys.public() })
Expand Down
2 changes: 1 addition & 1 deletion misc/peer-id-generator/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ fn main() {
thread::spawn(move || loop {
let keypair = identity::ed25519::Keypair::generate();
let secret = keypair.secret();
let peer_id = identity::PublicKey::Ed25519(keypair.public()).into_peer_id();
let peer_id = identity::PublicKey::Ed25519(keypair.public()).to_peer_id();
let base58 = peer_id.to_base58();
if base58[2..].starts_with(&prefix) {
println!("Found {:?}", peer_id);
Expand Down
2 changes: 1 addition & 1 deletion protocols/gossipsub/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ impl From<MessageAuthenticity> for PublishConfig {

PublishConfig::Signing {
keypair,
author: public_key.into_peer_id(),
author: public_key.to_peer_id(),
inline_key: key,
}
}
Expand Down
2 changes: 1 addition & 1 deletion protocols/gossipsub/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ impl GossipsubCodec {
};

// The key must match the peer_id
if source != public_key.clone().into_peer_id() {
if source != public_key.clone().to_peer_id() {
warn!("Signature verification failed: Public key doesn't match source peer id");
return false;
}
Expand Down
4 changes: 2 additions & 2 deletions protocols/gossipsub/tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ fn build_node() -> (Multiaddr, Swarm<Gossipsub>) {
.multiplex(yamux::YamuxConfig::default())
.boxed();

let peer_id = public_key.clone().into_peer_id();
let peer_id = public_key.clone().to_peer_id();

// NOTE: The graph of created nodes can be disconnected from the mesh point of view as nodes
// can reach their d_lo value and not add other nodes to their mesh. To speed up this test, we
Expand All @@ -176,7 +176,7 @@ fn build_node() -> (Multiaddr, Swarm<Gossipsub>) {
swarm.listen_on(addr.clone()).unwrap();

addr = addr.with(libp2p_core::multiaddr::Protocol::P2p(
public_key.into_peer_id().into(),
public_key.to_peer_id().into(),
));

(addr, swarm)
Expand Down
10 changes: 5 additions & 5 deletions protocols/identify/src/identify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ mod tests {
let protocol = Identify::new(
IdentifyConfig::new("a".to_string(), pubkey.clone())
.with_agent_version("b".to_string()));
let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id());
let swarm = Swarm::new(transport, protocol, pubkey.clone().to_peer_id());
(swarm, pubkey)
};

Expand All @@ -487,7 +487,7 @@ mod tests {
let protocol = Identify::new(
IdentifyConfig::new("c".to_string(), pubkey.clone())
.with_agent_version("d".to_string()));
let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id());
let swarm = Swarm::new(transport, protocol, pubkey.clone().to_peer_id());
(swarm, pubkey)
};

Expand Down Expand Up @@ -555,7 +555,7 @@ mod tests {
IdentifyConfig::new("a".to_string(), pubkey.clone())
// Delay identification requests so we can test the push protocol.
.with_initial_delay(Duration::from_secs(u32::MAX as u64)));
let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id());
let swarm = Swarm::new(transport, protocol, pubkey.clone().to_peer_id());
(swarm, pubkey)
};

Expand All @@ -566,7 +566,7 @@ mod tests {
.with_agent_version("b".to_string())
// Delay identification requests so we can test the push protocol.
.with_initial_delay(Duration::from_secs(u32::MAX as u64)));
let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id());
let swarm = Swarm::new(transport, protocol, pubkey.clone().to_peer_id());
(swarm, pubkey)
};

Expand Down Expand Up @@ -612,7 +612,7 @@ mod tests {
}
}

swarm2.behaviour_mut().push(std::iter::once(pubkey1.clone().into_peer_id()));
swarm2.behaviour_mut().push(std::iter::once(pubkey1.clone().to_peer_id()));
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion protocols/kad/src/behaviour/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ fn build_node_with_config(cfg: KademliaConfig) -> (Multiaddr, TestSwarm) {
.multiplex(yamux::YamuxConfig::default())
.boxed();

let local_id = local_public_key.clone().into_peer_id();
let local_id = local_public_key.clone().to_peer_id();
let store = MemoryStore::new(local_id.clone());
let behaviour = Kademlia::with_config(local_id.clone(), store, cfg.clone());

Expand Down
2 changes: 1 addition & 1 deletion protocols/mdns/src/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ mod tests {
fn build_query_response_correct() {
let my_peer_id = identity::Keypair::generate_ed25519()
.public()
.into_peer_id();
.to_peer_id();
let addr1 = "/ip4/1.2.3.4/tcp/5000".parse().unwrap();
let addr2 = "/ip6/::1/udp/10000".parse().unwrap();
let packets = build_query_response(
Expand Down
2 changes: 1 addition & 1 deletion protocols/ping/tests/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ fn mk_transport(muxer: MuxerChoice) -> (
transport::Boxed<(PeerId, StreamMuxerBox)>
) {
let id_keys = identity::Keypair::generate_ed25519();
let peer_id = id_keys.public().into_peer_id();
let peer_id = id_keys.public().to_peer_id();
let noise_keys = noise::Keypair::<noise::X25519Spec>::new().into_authentic(&id_keys).unwrap();
(peer_id, TcpConfig::new()
.nodelay(true)
Expand Down
6 changes: 3 additions & 3 deletions protocols/relay/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1249,7 +1249,7 @@ fn build_swarm(reachability: Reachability, relay_mode: RelayMode) -> Swarm<Combi
let plaintext = PlainText2Config {
local_public_key: local_public_key.clone(),
};
let local_peer_id = local_public_key.clone().into_peer_id();
let local_peer_id = local_public_key.clone().to_peer_id();

let transport = MemoryTransport::default();

Expand Down Expand Up @@ -1295,7 +1295,7 @@ fn build_keep_alive_swarm() -> Swarm<CombinedKeepAliveBehaviour> {
let plaintext = PlainText2Config {
local_public_key: local_public_key.clone(),
};
let local_peer_id = local_public_key.clone().into_peer_id();
let local_peer_id = local_public_key.clone().to_peer_id();

let transport = MemoryTransport::default();

Expand All @@ -1322,7 +1322,7 @@ fn build_keep_alive_only_swarm() -> Swarm<KeepAliveBehaviour> {
let plaintext = PlainText2Config {
local_public_key: local_public_key.clone(),
};
let local_peer_id = local_public_key.clone().into_peer_id();
let local_peer_id = local_public_key.clone().to_peer_id();

let transport = MemoryTransport::default();

Expand Down
2 changes: 1 addition & 1 deletion protocols/request-response/tests/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ fn ping_protocol_throttled() {

fn mk_transport() -> (PeerId, transport::Boxed<(PeerId, StreamMuxerBox)>) {
let id_keys = identity::Keypair::generate_ed25519();
let peer_id = id_keys.public().into_peer_id();
let peer_id = id_keys.public().to_peer_id();
let noise_keys = Keypair::<X25519Spec>::new().into_authentic(&id_keys).unwrap();
(peer_id, TcpConfig::new()
.nodelay(true)
Expand Down
4 changes: 2 additions & 2 deletions transports/noise/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ where
fn upgrade_inbound(self, socket: T, info: Self::Info) -> Self::Future {
Box::pin(self.config.upgrade_inbound(socket, info)
.and_then(|(remote, io)| match remote {
RemoteIdentity::IdentityKey(pk) => future::ok((pk.into_peer_id(), io)),
RemoteIdentity::IdentityKey(pk) => future::ok((pk.to_peer_id(), io)),
_ => future::err(NoiseError::AuthenticationFailed)
}))
}
Expand All @@ -377,7 +377,7 @@ where
fn upgrade_outbound(self, socket: T, info: Self::Info) -> Self::Future {
Box::pin(self.config.upgrade_outbound(socket, info)
.and_then(|(remote, io)| match remote {
RemoteIdentity::IdentityKey(pk) => future::ok((pk.into_peer_id(), io)),
RemoteIdentity::IdentityKey(pk) => future::ok((pk.to_peer_id(), io)),
_ => future::err(NoiseError::AuthenticationFailed)
}))
}
Expand Down
4 changes: 2 additions & 2 deletions transports/plaintext/src/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub struct Remote {
impl HandshakeContext<Local> {
fn new(config: PlainText2Config) -> Self {
let exchange = Exchange {
id: Some(config.local_public_key.clone().into_peer_id().to_bytes()),
id: Some(config.local_public_key.to_peer_id().to_bytes()),
pubkey: Some(config.local_public_key.to_protobuf_encoding())
};
let mut buf = Vec::with_capacity(exchange.encoded_len());
Expand Down Expand Up @@ -95,7 +95,7 @@ impl HandshakeContext<Local> {
};

// Check the validity of the remote's `Exchange`.
if peer_id != public_key.clone().into_peer_id() {
if peer_id != public_key.clone().to_peer_id() {
debug!("the remote's `PeerId` isn't consistent with the remote's public key");
return Err(PlainTextError::InvalidPeerId)
}
Expand Down
2 changes: 1 addition & 1 deletion transports/plaintext/tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ fn variable_msg_length() {
let client_fut = async {
debug!("dialing {:?}", server_address);
let (received_server_id, mut client_channel) = client_transport.dial(server_address).unwrap().await.unwrap();
assert_eq!(received_server_id, server_id.public().into_peer_id());
assert_eq!(received_server_id, server_id.public().to_peer_id());

debug!("Client: writing message.");
client_channel.write_all(&mut msg_to_send).await.expect("no error");
Expand Down

0 comments on commit 99d0834

Please sign in to comment.