Skip to main content

stratum_node_core/
did.rs

1//! The `did:nostr` principal: a DID over a BIP-340 x-only public key.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::encoding::{self, Bech32Error};
9
10/// The method prefix every `did:nostr` identifier starts with.
11const DID_PREFIX: &str = "did:nostr:";
12
13/// The NIP-19 human-readable prefix for public keys.
14const NPUB_HRP: &str = "npub";
15
16/// A `did:nostr` principal over a 32-byte x-only secp256k1 public key.
17///
18/// Every value holds a key that is a valid BIP-340 x-only point, so a
19/// `DidNostr` can always be used to verify a signature. The canonical text
20/// form is `did:nostr:` followed by 64 lowercase hexadecimal digits, which is
21/// what [`Display`](fmt::Display), [`FromStr`] and serde use. Ordering and
22/// hashing follow the key bytes, which agrees with the order of the hex text.
23///
24/// # Examples
25///
26/// ```
27/// use stratum_node_core::DidNostr;
28///
29/// # fn main() -> Result<(), stratum_node_core::ParseDidError> {
30/// let did: DidNostr =
31///     "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
32/// assert_eq!(DidNostr::from_npub(&did.to_npub())?, did);
33/// assert_eq!(DidNostr::from_hex(&did.to_hex())?, did);
34/// # Ok(())
35/// # }
36/// ```
37#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct DidNostr([u8; 32]);
39
40impl DidNostr {
41    /// Builds a principal from the raw 32-byte x-only public key.
42    ///
43    /// # Errors
44    ///
45    /// Returns [`ParseDidError::NotOnCurve`] when the bytes are not the
46    /// x-coordinate of a point on secp256k1.
47    pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, ParseDidError> {
48        if crate::schnorr::is_valid_xonly(&bytes) {
49            Ok(Self(bytes))
50        } else {
51            Err(ParseDidError::NotOnCurve)
52        }
53    }
54
55    /// Parses the key from 64 lowercase hexadecimal digits, with no prefix.
56    ///
57    /// Uppercase digits are rejected so that each key has one text form.
58    ///
59    /// # Errors
60    ///
61    /// Returns [`ParseDidError::InvalidHex`] for anything other than 64
62    /// lowercase hex digits, and [`ParseDidError::NotOnCurve`] for a value
63    /// that is not a valid point.
64    pub fn from_hex(hex: &str) -> Result<Self, ParseDidError> {
65        let bytes = encoding::decode_lower_hex::<32>(hex).ok_or(ParseDidError::InvalidHex)?;
66        Self::from_bytes(bytes)
67    }
68
69    /// Parses a NIP-19 `npub1…` bech32 public key.
70    ///
71    /// # Errors
72    ///
73    /// Returns [`ParseDidError::InvalidBech32`] for a malformed string, a
74    /// bech32m checksum or non-zero padding bits (so each key has exactly
75    /// one accepted encoding, up to letter case), [`ParseDidError::WrongBech32Prefix`] for a prefix
76    /// other than `npub`, [`ParseDidError::InvalidLength`] when the payload
77    /// is not 32 bytes, and [`ParseDidError::NotOnCurve`] for a value that is
78    /// not a valid point.
79    pub fn from_npub(npub: &str) -> Result<Self, ParseDidError> {
80        let mut bytes = [0u8; 32];
81        encoding::decode_bech32(npub, NPUB_HRP, &mut bytes).map_err(|err| match err {
82            Bech32Error::Invalid => ParseDidError::InvalidBech32,
83            Bech32Error::WrongPrefix => ParseDidError::WrongBech32Prefix,
84            Bech32Error::WrongLength => ParseDidError::InvalidLength,
85        })?;
86        Self::from_bytes(bytes)
87    }
88
89    /// Returns the raw 32-byte x-only public key.
90    pub fn as_bytes(&self) -> &[u8; 32] {
91        &self.0
92    }
93
94    /// Returns the key as 64 lowercase hexadecimal digits, as used in the
95    /// `pubkey` field of a Nostr event.
96    pub fn to_hex(&self) -> String {
97        hex::encode(self.0)
98    }
99
100    /// Returns the key as a NIP-19 `npub1…` string.
101    pub fn to_npub(&self) -> String {
102        encoding::encode_bech32(NPUB_HRP, &self.0)
103    }
104}
105
106impl fmt::Display for DidNostr {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        write!(f, "{DID_PREFIX}{}", self.to_hex())
109    }
110}
111
112impl fmt::Debug for DidNostr {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        write!(f, "DidNostr({self})")
115    }
116}
117
118impl FromStr for DidNostr {
119    type Err = ParseDidError;
120
121    /// Parses `did:nostr:<64 lowercase hex>`.
122    fn from_str(text: &str) -> Result<Self, Self::Err> {
123        let hex = text
124            .strip_prefix(DID_PREFIX)
125            .ok_or(ParseDidError::MissingPrefix)?;
126        Self::from_hex(hex)
127    }
128}
129
130impl TryFrom<[u8; 32]> for DidNostr {
131    type Error = ParseDidError;
132
133    fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
134        Self::from_bytes(bytes)
135    }
136}
137
138impl Serialize for DidNostr {
139    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
140        serializer.collect_str(self)
141    }
142}
143
144impl<'de> Deserialize<'de> for DidNostr {
145    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
146        let text = String::deserialize(deserializer)?;
147        text.parse().map_err(serde::de::Error::custom)
148    }
149}
150
151/// The reasons a `did:nostr` principal can fail to parse.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
153#[non_exhaustive]
154pub enum ParseDidError {
155    /// The text does not start with `did:nostr:`.
156    #[error("missing did:nostr: prefix")]
157    MissingPrefix,
158    /// The key is not exactly 64 lowercase hexadecimal digits.
159    #[error("public key is not 64 lowercase hex digits")]
160    InvalidHex,
161    /// The string is not valid bech32 with a bech32 (not bech32m) checksum
162    /// and zero padding bits.
163    #[error("invalid bech32 public key")]
164    InvalidBech32,
165    /// The bech32 prefix is not `npub`.
166    #[error("bech32 prefix is not npub")]
167    WrongBech32Prefix,
168    /// The decoded payload is not 32 bytes.
169    #[error("public key is not 32 bytes")]
170    InvalidLength,
171    /// The bytes are not the x-coordinate of a point on secp256k1.
172    #[error("public key is not a valid x-only secp256k1 point")]
173    NotOnCurve,
174}