use crate::ed25519::{Keypair as Libp2pKeyPair, PublicKey, SecretKey};
use libp2p_core::identity::error::DecodingError;
pub type Signature = Vec<u8>;
#[derive(Clone, Debug)]
pub struct KeyPair {
pub key_pair: Libp2pKeyPair,
}
impl KeyPair {
#[allow(dead_code)]
pub fn generate() -> Self {
let kp = Libp2pKeyPair::generate();
kp.into()
}
pub fn from_bytes(sk_bytes: impl AsMut<[u8]>) -> Result<Self, DecodingError> {
let sk = SecretKey::from_bytes(sk_bytes)?;
Ok(Libp2pKeyPair::from(sk).into())
}
#[allow(dead_code)]
pub fn encode(&self) -> [u8; 64] {
self.key_pair.encode()
}
#[allow(dead_code)]
pub fn decode(kp: &mut [u8]) -> Result<KeyPair, DecodingError> {
let kp = Libp2pKeyPair::decode(kp)?;
Ok(Self { key_pair: kp })
}
#[allow(dead_code)]
pub fn public_key(&self) -> PublicKey {
self.key_pair.public()
}
pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
self.key_pair.sign(msg)
}
pub fn verify(pk: &PublicKey, msg: &[u8], signature: &[u8]) -> Result<(), String> {
if pk.verify(msg, signature) {
return Ok(());
}
Err("Signature is not valid.".to_string())
}
}
impl From<Libp2pKeyPair> for KeyPair {
fn from(kp: Libp2pKeyPair) -> Self {
Self { key_pair: kp }
}
}