@@ -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