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/// A configuration revision number.
173///
174/// Revisions count up from zero; [`next`](Self::next) refuses to wrap.
175///
176/// # Examples
177///
178/// ```
179/// use stratum_node_core::Revision;
180///
181/// let first = Revision::new(0);
182/// assert_eq!(first.next(), Some(Revision::new(1)));
183/// assert_eq!(Revision::new(u64::MAX).next(), None);
184/// ```
185#[derive(
186    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
187)]
188#[serde(transparent)]
189pub struct Revision(u64);
190
191impl Revision {
192    /// Wraps a revision number.
193    pub const fn new(value: u64) -> Self {
194        Self(value)
195    }
196
197    /// Returns the revision number.
198    pub const fn get(self) -> u64 {
199        self.0
200    }
201
202    /// Returns the following revision, or `None` if this is `u64::MAX`.
203    pub const fn next(self) -> Option<Self> {
204        match self.0.checked_add(1) {
205            Some(value) => Some(Self(value)),
206            None => None,
207        }
208    }
209}
210
211impl From<u64> for Revision {
212    fn from(value: u64) -> Self {
213        Self(value)
214    }
215}
216
217impl From<Revision> for u64 {
218    fn from(revision: Revision) -> Self {
219        revision.0
220    }
221}
222
223impl fmt::Display for Revision {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        fmt::Display::fmt(&self.0, f)
226    }
227}
228
229/// A point in time as whole seconds since the Unix epoch.
230///
231/// This crate never reads a clock; callers pass the current time in.
232///
233/// # Examples
234///
235/// ```
236/// use std::time::Duration;
237/// use stratum_node_core::UnixTime;
238///
239/// let now = UnixTime::from_secs(1_700_000_000);
240/// let later = now.checked_add(Duration::from_secs(300));
241/// assert_eq!(later, Some(UnixTime::from_secs(1_700_000_300)));
242/// ```
243#[derive(
244    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
245)]
246#[serde(transparent)]
247pub struct UnixTime(u64);
248
249impl UnixTime {
250    /// Wraps a number of seconds since the Unix epoch.
251    pub const fn from_secs(secs: u64) -> Self {
252        Self(secs)
253    }
254
255    /// Returns the number of seconds since the Unix epoch.
256    pub const fn as_secs(self) -> u64 {
257        self.0
258    }
259
260    /// Adds a duration, ignoring sub-second precision, or returns `None` on
261    /// overflow.
262    pub const fn checked_add(self, duration: Duration) -> Option<Self> {
263        match self.0.checked_add(duration.as_secs()) {
264            Some(secs) => Some(Self(secs)),
265            None => None,
266        }
267    }
268
269    /// Returns the absolute distance between two times, in seconds.
270    pub const fn abs_diff(self, other: Self) -> u64 {
271        self.0.abs_diff(other.0)
272    }
273}
274
275impl From<u64> for UnixTime {
276    fn from(secs: u64) -> Self {
277        Self(secs)
278    }
279}
280
281impl From<UnixTime> for u64 {
282    fn from(time: UnixTime) -> Self {
283        time.0
284    }
285}
286
287impl fmt::Display for UnixTime {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        fmt::Display::fmt(&self.0, f)
290    }
291}
292
293/// A caller-chosen identifier for a mutating operation.
294///
295/// It is 1 to [`OPERATION_ID_MAX_LEN`] characters drawn from `[A-Za-z0-9_-]`,
296/// and is compared exactly (case matters).
297///
298/// # Examples
299///
300/// ```
301/// use stratum_node_core::OperationId;
302///
303/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
304/// let op: OperationId = "apply-2026_12_03".parse()?;
305/// assert_eq!(op.as_str(), "apply-2026_12_03");
306/// assert!("has space".parse::<OperationId>().is_err());
307/// # Ok(())
308/// # }
309/// ```
310#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
311pub struct OperationId(String);
312
313impl OperationId {
314    /// Returns the identifier text.
315    pub fn as_str(&self) -> &str {
316        &self.0
317    }
318
319    /// Checks the length and character set.
320    fn validate(text: &str) -> Result<(), ParseIdError> {
321        if text.is_empty() {
322            return Err(ParseIdError::Empty);
323        }
324        if text.len() > OPERATION_ID_MAX_LEN {
325            return Err(ParseIdError::TooLong);
326        }
327        if !text
328            .bytes()
329            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
330        {
331            return Err(ParseIdError::InvalidCharacter);
332        }
333        Ok(())
334    }
335}
336
337impl FromStr for OperationId {
338    type Err = ParseIdError;
339
340    fn from_str(text: &str) -> Result<Self, Self::Err> {
341        Self::validate(text)?;
342        Ok(Self(text.to_owned()))
343    }
344}
345
346impl TryFrom<String> for OperationId {
347    type Error = ParseIdError;
348
349    fn try_from(text: String) -> Result<Self, Self::Error> {
350        Self::validate(&text)?;
351        Ok(Self(text))
352    }
353}
354
355impl AsRef<str> for OperationId {
356    fn as_ref(&self) -> &str {
357        &self.0
358    }
359}
360
361impl fmt::Display for OperationId {
362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363        f.write_str(&self.0)
364    }
365}
366
367impl Serialize for OperationId {
368    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
369        serializer.serialize_str(&self.0)
370    }
371}
372
373impl<'de> Deserialize<'de> for OperationId {
374    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
375        let text = String::deserialize(deserializer)?;
376        Self::try_from(text).map_err(serde::de::Error::custom)
377    }
378}