Skip to content

Commit 50b0957

Browse files
rubdosmxinden
andauthored
core/: Add Keypair::to_protobuf_encoding (#2142)
Co-authored-by: Max Inden <[email protected]>
1 parent 7877929 commit 50b0957

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

core/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# 0.30.0 [unreleased]
22

3+
- Add `Keypair::to_protobuf_encoding` (see [PR 2142]).
4+
35
- Change `PublicKey::into_protobuf_encoding` to `PublicKey::to_protobuf_encoding` (see [PR 2145]).
46

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

1113
[PR 2145]: https://github.com/libp2p/rust-libp2p/pull/2145
14+
[PR 2142]: https://github.com/libp2p/rust-libp2p/pull/2142
1215

1316
# 0.29.0 [2021-07-12]
1417

core/src/identity.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,33 @@ impl Keypair {
116116
}
117117
}
118118

119+
/// Encode a private key as protobuf structure.
120+
pub fn to_protobuf_encoding(&self) -> Result<Vec<u8>, DecodingError> {
121+
use prost::Message;
122+
123+
let pk = match self {
124+
Self::Ed25519(data) => keys_proto::PrivateKey {
125+
r#type: keys_proto::KeyType::Ed25519.into(),
126+
data: data.encode().into(),
127+
},
128+
#[cfg(not(target_arch = "wasm32"))]
129+
Self::Rsa(_) => {
130+
return Err(DecodingError::new(
131+
"Encoding RSA key into Protobuf is unsupported",
132+
))
133+
}
134+
#[cfg(feature = "secp256k1")]
135+
Self::Secp256k1(_) => {
136+
return Err(DecodingError::new(
137+
"Encoding Secp256k1 key into Protobuf is unsupported",
138+
))
139+
}
140+
};
141+
142+
Ok(pk.encode_to_vec())
143+
}
144+
145+
119146
/// Decode a private key from a protobuf structure and parse it as a [`Keypair`].
120147
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<Keypair, DecodingError> {
121148
use prost::Message;
@@ -255,6 +282,19 @@ mod tests {
255282
use super::*;
256283
use std::str::FromStr;
257284

285+
#[test]
286+
fn keypair_protobuf_roundtrip() {
287+
let expected_keypair = Keypair::generate_ed25519();
288+
let expected_peer_id = expected_keypair.public().to_peer_id();
289+
290+
let encoded = expected_keypair.to_protobuf_encoding().unwrap();
291+
292+
let keypair = Keypair::from_protobuf_encoding(&encoded).unwrap();
293+
let peer_id = keypair.public().to_peer_id();
294+
295+
assert_eq!(expected_peer_id, peer_id);
296+
}
297+
258298
#[test]
259299
fn keypair_from_protobuf_encoding() {
260300
// E.g. retrieved from an IPFS config file.

0 commit comments

Comments
 (0)