use crate::error::Result;
use alloc::{string::String, vec::Vec};
use core::{fmt::Debug, hash::Hash};
pub trait CryptoScheme: Debug + Clone + Copy + Send + Sync + 'static {
const NAME: &'static str;
const NAMESPACE: &'static str;
const PUBLIC_KEY_SIZE: usize;
const SIGNATURE_SIZE: usize;
type PrivateKey: Clone + Debug + Send + Sync;
type PublicKey: Clone + Debug + Send + Sync + Eq + Hash + Ord;
type Signature: Clone + Debug + Send + Sync;
type Address: Clone + Debug + Send + Sync + PartialEq;
type Seed: Clone + Default + AsRef<[u8]> + AsMut<[u8]> + Send + Sync + 'static;
#[cfg(feature = "std")]
fn generate_keypair() -> (Self::PrivateKey, Self::PublicKey);
fn public_key(private_key: &Self::PrivateKey) -> Self::PublicKey;
fn sign(private_key: &Self::PrivateKey, data: &[u8]) -> Result<Self::Signature>;
fn verify(public_key: &Self::PublicKey, data: &[u8], signature: &Self::Signature)
-> Result<()>;
fn to_address(public_key: &Self::PublicKey) -> Self::Address;
fn public_key_to_bytes(public_key: &Self::PublicKey) -> Vec<u8>;
fn public_key_from_bytes(bytes: &[u8]) -> Result<Self::PublicKey>;
fn public_key_to_hex(public_key: &Self::PublicKey) -> String {
hex::encode(Self::public_key_to_bytes(public_key))
}
fn public_key_from_hex(hex_str: &str) -> Result<Self::PublicKey> {
let bytes = crate::utils::decode_hex(hex_str)?;
Self::public_key_from_bytes(&bytes)
}
fn signature_to_bytes(signature: &Self::Signature) -> Vec<u8>;
fn signature_from_bytes(bytes: &[u8]) -> Result<Self::Signature>;
fn signature_to_hex(signature: &Self::Signature) -> String {
hex::encode(Self::signature_to_bytes(signature))
}
fn signature_from_hex(hex_str: &str) -> Result<Self::Signature> {
let bytes = crate::utils::decode_hex(hex_str)?;
Self::signature_from_bytes(&bytes)
}
fn address_to_string(address: &Self::Address) -> String;
fn private_key_from_seed(seed: Self::Seed) -> Result<Self::PrivateKey>;
fn private_key_to_seed(private_key: &Self::PrivateKey) -> Self::Seed;
#[cfg(feature = "std")]
fn private_key_from_suri(suri: &str, password: Option<&str>) -> Result<Self::PrivateKey>;
}
#[cfg(feature = "keyring")]
pub trait KeystoreOps<S: CryptoScheme>: crate::keyring::KeystoreEntry {
fn from_private_key(
name: &str,
private_key: &S::PrivateKey,
password: Option<&str>,
) -> Result<Self>
where
Self: Sized;
fn to_private_key(&self, password: Option<&str>) -> Result<S::PrivateKey>;
fn to_public_key(&self) -> Result<S::PublicKey>;
fn to_address(&self) -> Result<S::Address>;
}
#[cfg(test)]
mod tests {
fn _assert_send_sync<T: Send + Sync>() {}
#[cfg(feature = "secp256k1")]
fn _check_secp256k1_impl() {
use crate::schemes::secp256k1::Secp256k1;
_assert_send_sync::<Secp256k1>();
}
#[cfg(feature = "sr25519")]
fn _check_sr25519_impl() {
use crate::schemes::sr25519::Sr25519;
_assert_send_sync::<Sr25519>();
}
#[cfg(feature = "ed25519")]
fn _check_ed25519_impl() {
use crate::schemes::ed25519::Ed25519;
_assert_send_sync::<Ed25519>();
}
}