use crate::types::Error;
use k256::{elliptic_curve::rand_core, NonZeroScalar, ProjectivePoint, PublicKey};
use crate::normalize_hex;
pub fn hex_to_point(pubkey_hex: &str) -> Result<ProjectivePoint, Error> {
let hex_norm = normalize_hex(pubkey_hex)?;
let point_bytes = match hex_norm.len() {
64 => hex::decode(format!("02{}", hex_norm))?,
66 => {
if !hex_norm.starts_with("02") && !hex_norm.starts_with("03") {
return Err(Error::PublicKeyFormat(format!(
"Invalid prefix: {}",
&hex_norm[..2]
)));
}
hex::decode(&hex_norm)?
}
130 => {
if !hex_norm.starts_with("04") {
return Err(Error::PublicKeyFormat(format!(
"Invalid prefix: {}",
&hex_norm[..2]
)));
}
hex::decode(&hex_norm)?
}
_ => {
return Err(Error::PublicKeyFormat(format!(
"Invalid length: {}",
hex_norm.len()
)));
}
};
let public_key = PublicKey::from_sec1_bytes(&point_bytes)
.map_err(|e| Error::PublicKeyFormat(format!("SEC1 parse error: {}", e)))?;
Ok(public_key.to_projective())
}
pub fn random_non_zero_scalar(
mut rng: impl rand_core::RngCore + rand_core::CryptoRng,
) -> NonZeroScalar {
NonZeroScalar::random(&mut rng)
}