From ee330a715a902e48fc9b61d662ffcd950a26379c Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 4 Jul 2023 19:47:26 +0300 Subject: [PATCH] fix(keypair): deserialize libp2p keypair from secret key (#116) * fix: Ed25519 keypair * Update keypair/src/key_pair.rs Co-authored-by: folex <0xdxdy@gmail.com> --------- Co-authored-by: folex <0xdxdy@gmail.com> --- keypair/src/ed25519.rs | 12 ++++++++++++ keypair/src/key_pair.rs | 4 +++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/keypair/src/ed25519.rs b/keypair/src/ed25519.rs index 38d4c50..842a0ad 100644 --- a/keypair/src/ed25519.rs +++ b/keypair/src/ed25519.rs @@ -201,6 +201,7 @@ pub struct Signature(pub Vec); #[cfg(test)] mod tests { use super::*; + use crate::KeyPair; use quickcheck::*; fn eq_keypairs(kp1: &Keypair, kp2: &Keypair) -> bool { @@ -218,6 +219,17 @@ mod tests { QuickCheck::new().tests(10).quickcheck(prop as fn() -> _); } + #[test] + fn ed25519_keypair_convert() { + fn prop() -> bool { + let kp1 = KeyPair::generate_ed25519(); + let libp2p_kp: libp2p_identity::Keypair = kp1.clone().into(); + let kp2: KeyPair = libp2p_kp.into(); + kp1.public() == kp2.public() && kp1.secret().unwrap() == kp2.secret().unwrap() + } + QuickCheck::new().tests(10).quickcheck(prop as fn() -> _); + } + #[test] fn ed25519_keypair_from_secret() { fn prop() -> bool { diff --git a/keypair/src/key_pair.rs b/keypair/src/key_pair.rs index 3c14da7..7b6e7a6 100644 --- a/keypair/src/key_pair.rs +++ b/keypair/src/key_pair.rs @@ -283,7 +283,9 @@ impl From for libp2p_identity::Keypair { fn convert_keypair(key: KeyPair) -> eyre::Result { match key { KeyPair::Ed25519(kp) => { - let kp = Keypair::ed25519_from_bytes(kp.encode().to_vec().as_mut_slice())?; + // for some reason, libp2p takes SecretKey's 32 bytes here instead of Keypair's 64 bytes + let secret_bytes = kp.secret().0.to_bytes(); + let kp = libp2p_identity::Keypair::ed25519_from_bytes(secret_bytes)?; Ok(kp) } #[cfg(not(target_arch = "wasm32"))]