Skip to main content

stratum_node_core/
id.rs

1//! Typed identifiers, digests, revisions and timestamps.
2//!
3//! Each type has one canonical text form. The byte-valued types use lowercase
4//! hexadecimal and reject uppercase input, so equal values always print the
5//! same way and text comparisons agree with value comparisons.
6
7use std::fmt;
8use std::str::FromStr;
9use std::time::Duration;
10
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12use sha2::{Digest, Sha256};
13
14use crate::encoding;
15
16/// The longest [`OperationId`] accepted, in characters.
17pub const OPERATION_ID_MAX_LEN: usize = 64;
18
19/// The reasons an identifier can fail to parse.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
21#[non_exhaustive]
22pub enum ParseIdError {
23    /// The text is not exactly `expected` lowercase hexadecimal digits.
24    #[error("expected {expected} lowercase hex digits")]
25    InvalidHex {
26        /// The number of hex digits the type requires.
27        expected: usize,
28    },
29    /// An operation identifier is empty.
30    #[error("operation id is empty")]
31    Empty,
32    /// An operation identifier is longer than [`OPERATION_ID_MAX_LEN`].
33    #[error("operation id is longer than {OPERATION_ID_MAX_LEN} characters")]
34    TooLong,
35    /// An operation identifier contains a character outside `[A-Za-z0-9_-]`.
36    #[error("operation id may contain only A-Z, a-z, 0-9, '_' and '-'")]
37    InvalidCharacter,
38}
39
40/// Implements the shared surface of a fixed-size byte identifier rendered as
41/// lowercase hex: `from_bytes`, `as_bytes`, `to_hex`, `Display`, `Debug`,
42/// `FromStr`, `From<[u8; N]>` and string serde.
43macro_rules! hex_bytes_type {
44    ($name:ident, $len:literal) => {
45        impl $name {
46            /// Wraps raw bytes.
47            pub const fn from_bytes(bytes: [u8; $len]) -> Self {
48                Self(bytes)
49            }
50
51            /// Returns the raw bytes.
52            pub const fn as_bytes(&self) -> &[u8; $len] {
53                &self.0
54            }
55
56            /// Returns the lowercase hexadecimal text form.
57            pub fn to_hex(&self) -> String {
58                hex::encode(self.0)
59            }
60        }
61
62        impl From<[u8; $len]> for $name {
63            fn from(bytes: [u8; $len]) -> Self {
64                Self(bytes)
65            }
66        }
67
68        impl fmt::Display for $name {
69            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70                f.write_str(&self.to_hex())
71            }
72        }
73
74        impl fmt::Debug for $name {
75            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76                write!(f, concat!(stringify!($name), "({})"), self.to_hex())
77            }
78        }
79
80        impl FromStr for $name {
81            type Err = ParseIdError;
82
83            /// Parses exactly the lowercase hexadecimal text form.
84            fn from_str(text: &str) -> Result<Self, Self::Err> {
85                encoding::decode_lower_hex::<$len>(text)
86                    .map(Self)
87                    .ok_or(ParseIdError::InvalidHex { expected: $len * 2 })
88            }
89        }
90
91        impl Serialize for $name {
92            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
93                serializer.serialize_str(&self.to_hex())
94            }
95        }
96
97        impl<'de> Deserialize<'de> for $name {
98            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
99                let text = String::deserialize(deserializer)?;
100                text.parse().map_err(serde::de::Error::custom)
101            }
102        }
103    };
104}
105
106/// A Nostr event identifier: the SHA-256 of the NIP-01 serialisation.
107///
108/// Its text form is 64 lowercase hexadecimal digits. Callers that need replay
109/// protection record verified event identifiers durably.
110///
111/// # Examples
112///
113/// ```
114/// use stratum_node_core::EventId;
115///
116/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
117/// let id: EventId = "00".repeat(32).parse()?;
118/// assert_eq!(id.as_bytes(), &[0u8; 32]);
119/// assert!("AB".repeat(32).parse::<EventId>().is_err());
120/// # Ok(())
121/// # }
122/// ```
123#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
124pub struct EventId([u8; 32]);
125hex_bytes_type!(EventId, 32);
126
127/// A SHA-256 digest, written as 64 lowercase hexadecimal digits.
128///
129/// # Examples
130///
131/// ```
132/// use stratum_node_core::Sha256Digest;
133///
134/// let digest = Sha256Digest::of(b"abc");
135/// assert_eq!(
136///     digest.to_hex(),
137///     "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
138/// );
139/// ```
140#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
141pub struct Sha256Digest([u8; 32]);
142hex_bytes_type!(Sha256Digest, 32);
143
144impl Sha256Digest {
145    /// Computes the SHA-256 digest of `data`.
146    pub fn of(data: &[u8]) -> Self {
147        Self(Sha256::digest(data).into())
148    }
149}
150
151/// The identifier of a single-use challenge, written as 32 lowercase hex
152/// digits.
153///
154/// This crate performs no I/O, so the caller supplies the 16 bytes; they must
155/// come from a cryptographically secure random source.
156///
157/// # Examples
158///
159/// ```
160/// use stratum_node_core::ChallengeId;
161///
162/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
163/// let id = ChallengeId::from_bytes([7; 16]);
164/// assert_eq!(id.to_string().parse::<ChallengeId>()?, id);
165/// # Ok(())
166/// # }
167/// ```
168#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
169pub struct ChallengeId([u8; 16]);
170hex_bytes_type!(ChallengeId, 16);
171
172/// The identifier of an invitation, written as 32 lowercase hex digits.
173///
174/// An invitation is bound to one public identity and can be redeemed only by
175/// a request that identity signs, so this identifier is a name, not a
176/// credential. This crate performs no I/O, so the caller supplies the 16
177/// bytes, normally from a secure random source so that identifiers do not
178/// collide.
179///
180/// # Examples
181///
182/// ```
183/// use stratum_node_core::InvitationId;
184///
185/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
186/// let id = InvitationId::from_bytes([0xab; 16]);
187/// assert_eq!(id.to_string(), "ab".repeat(16));
188/// assert_eq!(id.to_string().parse::<InvitationId>()?, id);
189/// assert!("AB".repeat(16).parse::<InvitationId>().is_err());
190/// # Ok(())
191/// # }
192/// ```
193#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub struct InvitationId([u8; 16]);
195hex_bytes_type!(InvitationId, 16);
196
197/// A configuration revision number.
198///
199/// Revisions count up from zero; [`next`](Self::next) refuses to wrap.
200///
201/// # Examples
202///
203/// ```
204/// use stratum_node_core::Revision;
205///
206/// let first = Revision::new(0);
207/// assert_eq!(first.next(), Some(Revision::new(1)));
208/// assert_eq!(Revision::new(u64::MAX).next(), None);
209/// ```
210#[derive(
211    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
212)]
213#[serde(transparent)]
214pub struct Revision(u64);
215
216impl Revision {
217    /// Wraps a revision number.
218    pub const fn new(value: u64) -> Self {
219        Self(value)
220    }
221
222    /// Returns the revision number.
223    pub const fn get(self) -> u64 {
224        self.0
225    }
226
227    /// Returns the following revision, or `None` if this is `u64::MAX`.
228    pub const fn next(self) -> Option<Self> {
229        match self.0.checked_add(1) {
230            Some(value) => Some(Self(value)),
231            None => None,
232        }
233    }
234}
235
236impl From<u64> for Revision {
237    fn from(value: u64) -> Self {
238        Self(value)
239    }
240}
241
242impl From<Revision> for u64 {
243    fn from(revision: Revision) -> Self {
244        revision.0
245    }
246}
247
248impl fmt::Display for Revision {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        fmt::Display::fmt(&self.0, f)
251    }
252}
253
254/// A point in time as whole seconds since the Unix epoch.
255///
256/// This crate never reads a clock; callers pass the current time in.
257///
258/// # Examples
259///
260/// ```
261/// use std::time::Duration;
262/// use stratum_node_core::UnixTime;
263///
264/// let now = UnixTime::from_secs(1_700_000_000);
265/// let later = now.checked_add(Duration::from_secs(300));
266/// assert_eq!(later, Some(UnixTime::from_secs(1_700_000_300)));
267/// ```
268#[derive(
269    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
270)]
271#[serde(transparent)]
272pub struct UnixTime(u64);
273
274impl UnixTime {
275    /// Wraps a number of seconds since the Unix epoch.
276    pub const fn from_secs(secs: u64) -> Self {
277        Self(secs)
278    }
279
280    /// Returns the number of seconds since the Unix epoch.
281    pub const fn as_secs(self) -> u64 {
282        self.0
283    }
284
285    /// Adds a duration, ignoring sub-second precision, or returns `None` on
286    /// overflow.
287    pub const fn checked_add(self, duration: Duration) -> Option<Self> {
288        match self.0.checked_add(duration.as_secs()) {
289            Some(secs) => Some(Self(secs)),
290            None => None,
291        }
292    }
293
294    /// Returns the absolute distance between two times, in seconds.
295    pub const fn abs_diff(self, other: Self) -> u64 {
296        self.0.abs_diff(other.0)
297    }
298}
299
300impl From<u64> for UnixTime {
301    fn from(secs: u64) -> Self {
302        Self(secs)
303    }
304}
305
306impl From<UnixTime> for u64 {
307    fn from(time: UnixTime) -> Self {
308        time.0
309    }
310}
311
312impl fmt::Display for UnixTime {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        fmt::Display::fmt(&self.0, f)
315    }
316}
317
318/// A caller-chosen identifier for a mutating operation.
319///
320/// It is 1 to [`OPERATION_ID_MAX_LEN`] characters drawn from `[A-Za-z0-9_-]`,
321/// and is compared exactly (case matters).
322///
323/// # Examples
324///
325/// ```
326/// use stratum_node_core::OperationId;
327///
328/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
329/// let op: OperationId = "apply-2026_12_03".parse()?;
330/// assert_eq!(op.as_str(), "apply-2026_12_03");
331/// assert!("has space".parse::<OperationId>().is_err());
332/// # Ok(())
333/// # }
334/// ```
335#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
336pub struct OperationId(String);
337
338impl OperationId {
339    /// Returns the identifier text.
340    pub fn as_str(&self) -> &str {
341        &self.0
342    }
343
344    /// Checks the length and character set.
345    fn validate(text: &str) -> Result<(), ParseIdError> {
346        if text.is_empty() {
347            return Err(ParseIdError::Empty);
348        }
349        if text.len() > OPERATION_ID_MAX_LEN {
350            return Err(ParseIdError::TooLong);
351        }
352        if !text
353            .bytes()
354            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
355        {
356            return Err(ParseIdError::InvalidCharacter);
357        }
358        Ok(())
359    }
360}
361
362impl FromStr for OperationId {
363    type Err = ParseIdError;
364
365    fn from_str(text: &str) -> Result<Self, Self::Err> {
366        Self::validate(text)?;
367        Ok(Self(text.to_owned()))
368    }
369}
370
371impl TryFrom<String> for OperationId {
372    type Error = ParseIdError;
373
374    fn try_from(text: String) -> Result<Self, Self::Error> {
375        Self::validate(&text)?;
376        Ok(Self(text))
377    }
378}
379
380impl AsRef<str> for OperationId {
381    fn as_ref(&self) -> &str {
382        &self.0
383    }
384}
385
386impl fmt::Display for OperationId {
387    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388        f.write_str(&self.0)
389    }
390}
391
392impl Serialize for OperationId {
393    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
394        serializer.serialize_str(&self.0)
395    }
396}
397
398impl<'de> Deserialize<'de> for OperationId {
399    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
400        let text = String::deserialize(deserializer)?;
401        Self::try_from(text).map_err(serde::de::Error::custom)
402    }
403}