use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::encoding::{self, Bech32Error};
const DID_PREFIX: &str = "did:nostr:";
const NPUB_HRP: &str = "npub";
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DidNostr([u8; 32]);
impl DidNostr {
pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, ParseDidError> {
if crate::schnorr::is_valid_xonly(&bytes) {
Ok(Self(bytes))
} else {
Err(ParseDidError::NotOnCurve)
}
}
pub fn from_hex(hex: &str) -> Result<Self, ParseDidError> {
let bytes = encoding::decode_lower_hex::<32>(hex).ok_or(ParseDidError::InvalidHex)?;
Self::from_bytes(bytes)
}
pub fn from_npub(npub: &str) -> Result<Self, ParseDidError> {
let mut bytes = [0u8; 32];
encoding::decode_bech32(npub, NPUB_HRP, &mut bytes).map_err(|err| match err {
Bech32Error::Invalid => ParseDidError::InvalidBech32,
Bech32Error::WrongPrefix => ParseDidError::WrongBech32Prefix,
Bech32Error::WrongLength => ParseDidError::InvalidLength,
})?;
Self::from_bytes(bytes)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn to_npub(&self) -> String {
encoding::encode_bech32(NPUB_HRP, &self.0)
}
}
impl fmt::Display for DidNostr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{DID_PREFIX}{}", self.to_hex())
}
}
impl fmt::Debug for DidNostr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DidNostr({self})")
}
}
impl FromStr for DidNostr {
type Err = ParseDidError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let hex = text
.strip_prefix(DID_PREFIX)
.ok_or(ParseDidError::MissingPrefix)?;
Self::from_hex(hex)
}
}
impl TryFrom<[u8; 32]> for DidNostr {
type Error = ParseDidError;
fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
Self::from_bytes(bytes)
}
}
impl Serialize for DidNostr {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for DidNostr {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseDidError {
#[error("missing did:nostr: prefix")]
MissingPrefix,
#[error("public key is not 64 lowercase hex digits")]
InvalidHex,
#[error("invalid bech32 public key")]
InvalidBech32,
#[error("bech32 prefix is not npub")]
WrongBech32Prefix,
#[error("public key is not 32 bytes")]
InvalidLength,
#[error("public key is not a valid x-only secp256k1 point")]
NotOnCurve,
}