use borsh::{BorshDeserialize, BorshSerialize};
use core::fmt;
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::error::SdkError;
pub const FALCON_PUBKEY_LEN: usize = 897;
pub const FALCON_SECRET_LEN: usize = 1281;
pub const FALCON_SIG_MAX_LEN: usize = 690;
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct FalconPubkey(#[serde(with = "serde_arr_897")] pub [u8; FALCON_PUBKEY_LEN]);
impl FalconPubkey {
#[must_use]
pub const fn new(bytes: [u8; FALCON_PUBKEY_LEN]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; FALCON_PUBKEY_LEN] {
&self.0
}
#[must_use]
pub fn from_slice(bytes: &[u8]) -> Option<Self> {
if bytes.len() != FALCON_PUBKEY_LEN {
return None;
}
let mut out = [0u8; FALCON_PUBKEY_LEN];
out.copy_from_slice(bytes);
Some(Self(out))
}
#[must_use]
pub fn to_hex(&self) -> String {
format!("0x{}", hex::encode(self.0))
}
pub fn from_hex(s: &str) -> Result<Self, SdkError> {
let h = s.trim_start_matches("0x");
let bytes = hex::decode(h)
.map_err(|e| SdkError::InvalidArgument(format!("invalid pubkey hex: {e}")))?;
Self::from_slice(&bytes).ok_or_else(|| {
SdkError::InvalidArgument(format!(
"expected {FALCON_PUBKEY_LEN}-byte pubkey, got {}",
bytes.len()
))
})
}
}
impl fmt::Debug for FalconPubkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FalconPubkey(0x{}…)", hex::encode(&self.0[..8]))
}
}
impl PartialEq for FalconPubkey {
fn eq(&self, other: &Self) -> bool {
use subtle::ConstantTimeEq;
self.0.ct_eq(&other.0).into()
}
}
impl Eq for FalconPubkey {}
impl core::hash::Hash for FalconPubkey {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl From<[u8; FALCON_PUBKEY_LEN]> for FalconPubkey {
fn from(bytes: [u8; FALCON_PUBKEY_LEN]) -> Self {
Self(bytes)
}
}
impl From<&pyde_crypto::falcon::FalconPublicKey> for FalconPubkey {
fn from(pk: &pyde_crypto::falcon::FalconPublicKey) -> Self {
Self::from_slice(pk.as_bytes()).unwrap_or(Self([0u8; FALCON_PUBKEY_LEN]))
}
}
impl From<&FalconPubkey> for pyde_crypto::falcon::FalconPublicKey {
fn from(pk: &FalconPubkey) -> Self {
pyde_crypto::falcon::FalconPublicKey::from_bytes(&pk.0).unwrap_or_else(|| {
pyde_crypto::falcon::FalconPublicKey::from_bytes(&[0u8; FALCON_PUBKEY_LEN])
.unwrap_or_else(|| unreachable!("897-byte zero buffer is valid"))
})
}
}
#[derive(Clone, Eq, PartialEq, Hash, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct FalconSignature(pub Vec<u8>);
impl FalconSignature {
#[must_use]
pub fn new(bytes: Vec<u8>) -> Self {
Self(bytes)
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn to_hex(&self) -> String {
format!("0x{}", hex::encode(&self.0))
}
}
impl fmt::Debug for FalconSignature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0.len() >= 8 {
write!(
f,
"FalconSignature({} B; 0x{}…)",
self.0.len(),
hex::encode(&self.0[..8])
)
} else {
write!(f, "FalconSignature(0x{})", hex::encode(&self.0))
}
}
}
impl From<Vec<u8>> for FalconSignature {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl From<&pyde_crypto::falcon::FalconSignature> for FalconSignature {
fn from(sig: &pyde_crypto::falcon::FalconSignature) -> Self {
Self(sig.to_vec())
}
}
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct FalconSecret(pub [u8; FALCON_SECRET_LEN]);
impl FalconSecret {
#[must_use]
pub const fn new(bytes: [u8; FALCON_SECRET_LEN]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; FALCON_SECRET_LEN] {
&self.0
}
#[must_use]
pub fn from_slice(bytes: &[u8]) -> Option<Self> {
if bytes.len() != FALCON_SECRET_LEN {
return None;
}
let mut out = [0u8; FALCON_SECRET_LEN];
out.copy_from_slice(bytes);
Some(Self(out))
}
}
impl fmt::Debug for FalconSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("FalconSecret(<redacted>)")
}
}
impl From<&pyde_crypto::falcon::FalconSecretKey> for FalconSecret {
fn from(sk: &pyde_crypto::falcon::FalconSecretKey) -> Self {
Self::from_slice(sk.as_bytes()).unwrap_or(Self([0u8; FALCON_SECRET_LEN]))
}
}
impl From<&FalconSecret> for pyde_crypto::falcon::FalconSecretKey {
fn from(sk: &FalconSecret) -> Self {
pyde_crypto::falcon::FalconSecretKey::from_bytes(&sk.0).unwrap_or_else(|| {
pyde_crypto::falcon::FalconSecretKey::from_bytes(&[0u8; FALCON_SECRET_LEN])
.unwrap_or_else(|| unreachable!("1281-byte zero buffer is valid"))
})
}
}
mod serde_arr_897 {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S: Serializer>(
bytes: &[u8; super::FALCON_PUBKEY_LEN],
s: S,
) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
let hex = format!("0x{}", hex::encode(bytes));
hex.serialize(s)
} else {
bytes.as_slice().serialize(s)
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> Result<[u8; super::FALCON_PUBKEY_LEN], D::Error> {
use serde::de::Error;
if d.is_human_readable() {
let s = String::deserialize(d)?;
let hex = s.trim_start_matches("0x");
let bytes = hex::decode(hex).map_err(D::Error::custom)?;
if bytes.len() != super::FALCON_PUBKEY_LEN {
return Err(D::Error::custom(format!(
"expected {} bytes, got {}",
super::FALCON_PUBKEY_LEN,
bytes.len()
)));
}
let mut out = [0u8; super::FALCON_PUBKEY_LEN];
out.copy_from_slice(&bytes);
Ok(out)
} else {
let v = Vec::<u8>::deserialize(d)?;
if v.len() != super::FALCON_PUBKEY_LEN {
return Err(D::Error::custom(format!(
"expected {} bytes, got {}",
super::FALCON_PUBKEY_LEN,
v.len()
)));
}
let mut out = [0u8; super::FALCON_PUBKEY_LEN];
out.copy_from_slice(&v);
Ok(out)
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn pubkey_borsh_round_trip() {
let pk = FalconPubkey::new([0x42; FALCON_PUBKEY_LEN]);
let bytes = borsh::to_vec(&pk).unwrap();
assert_eq!(bytes.len(), FALCON_PUBKEY_LEN);
let decoded: FalconPubkey = borsh::from_slice(&bytes).unwrap();
assert_eq!(pk, decoded);
}
#[test]
fn pubkey_hex_round_trip() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let parsed = FalconPubkey::from_hex(&pk.to_hex()).unwrap();
assert_eq!(pk, parsed);
}
#[test]
fn pubkey_debug_redacts() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
let dbg = format!("{pk:?}");
assert!(dbg.len() < 100);
assert!(dbg.contains('…'));
}
#[test]
fn signature_borsh_round_trip() {
let sig = FalconSignature::new(vec![0xCD; 666]);
let bytes = borsh::to_vec(&sig).unwrap();
assert_eq!(bytes.len(), 4 + 666);
let decoded: FalconSignature = borsh::from_slice(&bytes).unwrap();
assert_eq!(sig, decoded);
}
#[test]
fn secret_debug_never_leaks_bytes() {
let sk = FalconSecret::new([0xAB; FALCON_SECRET_LEN]);
let dbg = format!("{sk:?}");
assert!(!dbg.contains("ab"));
assert!(dbg.contains("redacted"));
}
#[test]
fn pubkey_conversion_round_trips_via_pyde_crypto() {
let pk = FalconPubkey::new([0x7E; FALCON_PUBKEY_LEN]);
let crypto_pk: pyde_crypto::falcon::FalconPublicKey = (&pk).into();
let back: FalconPubkey = (&crypto_pk).into();
assert_eq!(pk, back);
}
}