use k256::{AffinePoint, NonZeroScalar};
use k256::elliptic_curve::group::prime::PrimeCurveAffine;
use k256::elliptic_curve::sec1::ToEncodedPoint;
use crate::error::{Error, Result};
const SIZE: usize = 65;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct PublicKey {
bytes: [u8; SIZE],
}
impl PublicKey {
pub fn from_bytes(bytes: [u8; SIZE]) -> Self {
Self { bytes }
}
pub fn from_slice(slice: &[u8]) -> Result<Self> {
if slice.len() != SIZE {
Err(Error::LengthError(format!(
"PublicKey size must be {} bytes got {} bytes.",
SIZE,
slice.len()
)))
} else {
let mut new_bytes = [0u8; SIZE];
new_bytes.copy_from_slice(slice);
Ok(Self::from_bytes(new_bytes))
}
}
pub fn from_hex(hex: &str) -> Result<Self> {
if hex.len() != SIZE * 2 {
Err(Error::LengthError(format!(
"PublicKey hex must be {} characters got {} characters.",
SIZE * 2,
hex.len()
)))
} else {
let bytes = hex::decode(hex)?;
Self::from_slice(&bytes)
}
}
pub fn as_bytes(&self) -> [u8; SIZE] {
self.bytes
}
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
pub fn as_hex(&self) -> String {
hex::encode(&self.bytes)
}
pub fn derive_child(&self, other: [u8; 32]) -> Result<Self> {
let current = k256::PublicKey::from_sec1_bytes(&self.bytes).unwrap();
let child_scalar = Option::<NonZeroScalar>::from(NonZeroScalar::from_repr(other.into())).ok_or(Error::InvalidPublicKey)?;
let child_point = current.to_projective() + (AffinePoint::generator() * *child_scalar);
let derived = k256::PublicKey::from_affine(child_point.into()).map_err(|_| Error::InvalidPublicKey)?;
let bytes = derived.to_encoded_point(false);
Self::from_slice(bytes.as_bytes())
}
}