Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

to/into consistency for PublicKey and PeerId #2145

Merged
merged 7 commits into from
Jul 22, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
- 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

mxinden marked this conversation as resolved.
Show resolved Hide resolved
# 0.29.0 [2021-07-12]

- Switch from `parity-multiaddr` to upstream `multiaddr`.
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
6 changes: 3 additions & 3 deletions core/src/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ impl PublicKey {

/// Encode the public key into a protobuf structure for storage or
/// exchange with other nodes.
pub fn into_protobuf_encoding(self) -> Vec<u8> {
pub fn to_protobuf_encoding(&self) -> Vec<u8> {
use prost::Message;

let public_key = match self {
Expand Down 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
18 changes: 12 additions & 6 deletions core/src/peer_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ impl fmt::Display for PeerId {

impl PeerId {
/// Builds a `PeerId` from a public key.
pub fn from_public_key(key: PublicKey) -> PeerId {
let key_enc = key.into_protobuf_encoding();
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 {
Code::Identity
Expand Down Expand Up @@ -114,13 +114,19 @@ impl PeerId {
pub fn is_public_key(&self, public_key: &PublicKey) -> Option<bool> {
let alg = Code::try_from(self.multihash.code())
.expect("Internal multihash is always a valid `Code`");
let enc = public_key.clone().into_protobuf_encoding();
let enc = public_key.to_protobuf_encoding();
Some(alg.digest(&enc) == self.multihash)
}
}

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 @@ -184,20 +190,20 @@ mod tests {
#[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.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);
}
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
4 changes: 2 additions & 2 deletions protocols/gossipsub/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ impl From<MessageAuthenticity> for PublishConfig {
match authenticity {
MessageAuthenticity::Signed(keypair) => {
let public_key = keypair.public();
let key_enc = public_key.clone().into_protobuf_encoding();
let key_enc = public_key.to_protobuf_encoding();
let key = if key_enc.len() <= 42 {
// The public key can be inlined in [`rpc_proto::Message::from`], so we don't include it
// specifically in the [`rpc_proto::Message::key`] field.
Expand All @@ -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.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.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.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.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.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.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.to_peer_id()));
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion protocols/identify/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ where
.map(|addr| addr.to_vec())
.collect();

let pubkey_bytes = info.public_key.into_protobuf_encoding();
let pubkey_bytes = info.public_key.to_protobuf_encoding();

let message = structs_proto::Identify {
agent_version: Some(info.agent_version),
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.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
2 changes: 1 addition & 1 deletion protocols/relay/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
//! #
//! # let local_key = identity::Keypair::generate_ed25519();
//! # let local_public_key = local_key.public();
//! # let local_peer_id = local_public_key.clone().into_peer_id();
//! # let local_peer_id = local_public_key.to_peer_id();
//! # let plaintext = PlainText2Config {
//! # local_public_key: local_public_key.clone(),
//! # };
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.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.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.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
2 changes: 1 addition & 1 deletion transports/noise/src/io/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ where
let mut pb = payload_proto::NoiseHandshakePayload::default();

if state.send_identity {
pb.identity_key = state.identity.public.clone().into_protobuf_encoding()
pb.identity_key = state.identity.public.to_protobuf_encoding()
}

if let Some(ref sig) = state.identity.signature {
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
6 changes: 3 additions & 3 deletions transports/plaintext/src/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ 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()),
pubkey: Some(config.local_public_key.clone().into_protobuf_encoding())
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());
exchange.encode(&mut buf).expect("Vec<u8> provides capacity as needed");
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.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