#[cfg(not(feature = "std"))]
use alloc::string::ToString;
use alloc::{format, vec::Vec};
use k256::ecdsa::signature::hazmat::PrehashSigner;
use k256::ecdsa::{Signature, SigningKey, VerifyingKey};
use zeroize::ZeroizeOnDrop;
use crate::{SignError, SignOutput};
pub struct Secp256k1Signer {
key: SigningKey,
}
impl core::fmt::Debug for Secp256k1Signer {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Secp256k1Signer")
.field("key", &"[REDACTED]")
.finish()
}
}
impl ZeroizeOnDrop for Secp256k1Signer {}
impl Secp256k1Signer {
pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, SignError> {
let key =
SigningKey::from_slice(bytes).map_err(|e| SignError::InvalidKey(e.to_string()))?;
Ok(Self { key })
}
pub fn from_hex(hex_str: &str) -> Result<Self, SignError> {
let stripped = hex_str.strip_prefix("0x").unwrap_or(hex_str);
let decoded = hex::decode(stripped).map_err(|e| SignError::InvalidKey(e.to_string()))?;
let bytes: [u8; 32] = decoded.try_into().map_err(|v: Vec<u8>| {
SignError::InvalidKey(format!("expected 32 bytes, got {}", v.len()))
})?;
Self::from_bytes(&bytes)
}
#[cfg(feature = "getrandom")]
#[must_use]
#[allow(
clippy::expect_used,
reason = "getrandom failure is unrecoverable; secp256k1 rejection has p ≈ 2⁻¹²⁸"
)]
pub fn random() -> Self {
use zeroize::Zeroize as _;
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).expect("getrandom failed");
let key = SigningKey::from_slice(&bytes).expect("invalid random key");
bytes.zeroize();
Self { key }
}
#[must_use]
pub const fn signing_key(&self) -> &SigningKey {
&self.key
}
#[must_use]
pub fn verifying_key(&self) -> &VerifyingKey {
self.key.verifying_key()
}
#[must_use]
pub fn compressed_public_key(&self) -> Vec<u8> {
self.key
.verifying_key()
.to_encoded_point(true)
.as_bytes()
.to_vec()
}
#[must_use]
pub fn uncompressed_public_key(&self) -> Vec<u8> {
self.key
.verifying_key()
.to_encoded_point(false)
.as_bytes()
.to_vec()
}
pub fn sign_prehash_recoverable(&self, hash: &[u8]) -> Result<SignOutput, SignError> {
if hash.len() != 32 {
return Err(SignError::InvalidMessage(format!(
"expected 32-byte hash, got {}",
hash.len()
)));
}
let (sig, rid) = self
.key
.sign_prehash_recoverable(hash)
.map_err(|e| SignError::SigningFailed(e.to_string()))?;
let mut out = sig.to_bytes().to_vec();
out.push(rid.to_byte());
Ok(SignOutput::secp256k1(out, rid.to_byte()))
}
pub fn sign_prehash_der(&self, hash: &[u8]) -> Result<SignOutput, SignError> {
let digest: [u8; 32] = hash.try_into().map_err(|_| {
SignError::InvalidMessage(format!("expected 32-byte hash, got {}", hash.len()))
})?;
let sig: Signature = self
.key
.sign_prehash(&digest)
.map_err(|e| SignError::SigningFailed(e.to_string()))?;
Ok(SignOutput {
signature: sig.to_der().as_bytes().to_vec(),
recovery_id: None,
public_key: None,
})
}
}