Skip to content

Commit

Permalink
core/: Add Keypair::to_protobuf_encoding (#2142)
Browse files Browse the repository at this point in the history
Co-authored-by: Max Inden <[email protected]>
rubdos and mxinden authored Jul 28, 2021

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 7877929 commit 50b0957
Showing 2 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# 0.30.0 [unreleased]

- Add `Keypair::to_protobuf_encoding` (see [PR 2142]).

- Change `PublicKey::into_protobuf_encoding` to `PublicKey::to_protobuf_encoding` (see [PR 2145]).

- Change `PublicKey::into_peer_id` to `PublicKey::to_peer_id` (see [PR 2145]).
@@ -9,6 +11,7 @@
- Add `From<&PublicKey> for PeerId` (see [PR 2145]).

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

# 0.29.0 [2021-07-12]

40 changes: 40 additions & 0 deletions core/src/identity.rs
Original file line number Diff line number Diff line change
@@ -116,6 +116,33 @@ impl Keypair {
}
}

/// Encode a private key as protobuf structure.
pub fn to_protobuf_encoding(&self) -> Result<Vec<u8>, DecodingError> {
use prost::Message;

let pk = match self {
Self::Ed25519(data) => keys_proto::PrivateKey {
r#type: keys_proto::KeyType::Ed25519.into(),
data: data.encode().into(),
},
#[cfg(not(target_arch = "wasm32"))]
Self::Rsa(_) => {
return Err(DecodingError::new(
"Encoding RSA key into Protobuf is unsupported",
))
}
#[cfg(feature = "secp256k1")]
Self::Secp256k1(_) => {
return Err(DecodingError::new(
"Encoding Secp256k1 key into Protobuf is unsupported",
))
}
};

Ok(pk.encode_to_vec())
}


/// Decode a private key from a protobuf structure and parse it as a [`Keypair`].
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<Keypair, DecodingError> {
use prost::Message;
@@ -255,6 +282,19 @@ mod tests {
use super::*;
use std::str::FromStr;

#[test]
fn keypair_protobuf_roundtrip() {
let expected_keypair = Keypair::generate_ed25519();
let expected_peer_id = expected_keypair.public().to_peer_id();

let encoded = expected_keypair.to_protobuf_encoding().unwrap();

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

assert_eq!(expected_peer_id, peer_id);
}

#[test]
fn keypair_from_protobuf_encoding() {
// E.g. retrieved from an IPFS config file.

0 comments on commit 50b0957

Please sign in to comment.