Search code examples
rustlibp2p

Rust libp2p Keypair encoding and subsequent decoding fails


I don't understand why the following code runs into the expect panic

let keypair = identity::Keypair::generate_ed25519();
let key_bytes = keypair.clone().try_into_ed25519().unwrap().to_bytes();
let restored_keypair = identity::Keypair::ed25519_from_bytes(key_bytes)
    .expect("Keypair to be restored");

Solution

  • Found a hint to the answer in the rust-libp2p dcutr example

    Turns out, to_bytes returns [u8; 64], which is both the private and the public key. But ::ed25519_from_bytes expects a [u8; 32], which is just the private key.

    So this works fine

    #[test]
    fn test_generate_encode_decode_from_bytes_does_not_error() {
        let keypair = identity::Keypair::generate_ed25519();
        let key_bytes = keypair.clone().try_into_ed25519().unwrap().to_bytes();
    
        let private_key_bytes: [u8; 32] = key_bytes[..32].try_into().unwrap();
    
        let restored_keypair = identity::Keypair::ed25519_from_bytes(private_key_bytes)
            .expect("Keypair to be restored");
        
        assert_eq!(keypair.public().to_peer_id().to_base58(), restored_keypair.public().to_peer_id().to_base58());
    }