use std::fmt;
use k256::schnorr::{signature::hazmat::PrehashVerifier, SigningKey, VerifyingKey};
use zeroize::Zeroizing;
use crate::{hash::sha256, Address, Error, Network, Result};
#[derive(Clone)]
pub struct PrivateKey {
bytes: Zeroizing<[u8; 32]>,
signing: SigningKey,
}
impl PrivateKey {
pub fn generate() -> Result<Self> {
loop {
let mut raw = Zeroizing::new([0u8; 32]);
getrandom::getrandom(raw.as_mut()).map_err(|_| Error::InvalidPrivateKey)?;
if let Ok(key) = Self::from_bytes(&raw) {
return Ok(key);
}
}
}
pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self> {
let signing = SigningKey::from_bytes(bytes).map_err(|_| Error::InvalidPrivateKey)?;
Ok(Self {
bytes: Zeroizing::new(*bytes),
signing,
})
}
pub fn from_hex(s: &str) -> Result<Self> {
let mut raw = Zeroizing::new([0u8; 32]);
hex::decode_to_slice(s.trim(), raw.as_mut()).map_err(|_| Error::InvalidPrivateKey)?;
Self::from_bytes(&raw)
}
pub fn to_bytes(&self) -> Zeroizing<[u8; 32]> {
self.bytes.clone()
}
pub fn to_hex(&self) -> Zeroizing<String> {
Zeroizing::new(hex::encode(self.to_bytes().as_ref()))
}
pub fn public_key(&self) -> PublicKey {
PublicKey(self.signing.verifying_key().to_bytes().into())
}
pub fn address(&self) -> Address {
self.public_key().address()
}
pub fn address_for_network(&self, network: Network) -> Address {
self.public_key().address_for_network(network)
}
pub fn sign(&self, message: &[u8]) -> Result<Signature> {
self.sign_digest(&sha256(message))
}
pub fn sign_digest(&self, digest: &[u8; 32]) -> Result<Signature> {
let mut aux = [0u8; 32];
getrandom::getrandom(&mut aux).map_err(|_| Error::InvalidSignature)?;
let sig = self
.signing
.sign_raw(digest, &aux)
.map_err(|_| Error::InvalidSignature)?;
Ok(Signature(sig.to_bytes()))
}
}
impl fmt::Debug for PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("PrivateKey(<redacted>)")
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct PublicKey([u8; 32]);
impl PublicKey {
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let arr: [u8; 32] = bytes.try_into().map_err(|_| Error::InvalidPublicKey)?;
VerifyingKey::from_bytes(&arr).map_err(|_| Error::InvalidPublicKey)?;
Ok(Self(arr))
}
pub fn from_hex(s: &str) -> Result<Self> {
Self::from_bytes(&hex::decode(s.trim()).map_err(|_| Error::InvalidPublicKey)?)
}
pub fn to_bytes(&self) -> [u8; 32] {
self.0
}
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn address(&self) -> Address {
Address::from_public_key_bytes(&self.0)
}
pub fn address_for_network(&self, network: Network) -> Address {
Address::from_public_key_bytes_for_network(&self.0, network)
}
pub fn verify(&self, message: &[u8], signature: &Signature) -> bool {
self.verify_digest(&sha256(message), signature)
}
pub fn verify_digest(&self, digest: &[u8; 32], signature: &Signature) -> bool {
let (Ok(key), Ok(sig)) = (
VerifyingKey::from_bytes(&self.0),
k256::schnorr::Signature::try_from(&signature.0[..]),
) else {
return false;
};
key.verify_prehash(digest, &sig).is_ok()
}
}
impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "PublicKey({})", self.to_hex())
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Signature([u8; 64]);
impl Signature {
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
bytes.try_into().map(Self).map_err(|_| Error::InvalidSignature)
}
pub fn from_hex(s: &str) -> Result<Self> {
Self::from_bytes(&hex::decode(s.trim()).map_err(|_| Error::InvalidSignature)?)
}
pub fn to_bytes(&self) -> [u8; 64] {
self.0
}
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
}
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Signature({})", self.to_hex())
}
}