stratum-node-core 0.1.0-alpha.3

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Typed identifiers, digests, revisions and timestamps.
//!
//! Each type has one canonical text form. The byte-valued types use lowercase
//! hexadecimal and reject uppercase input, so equal values always print the
//! same way and text comparisons agree with value comparisons.

use std::fmt;
use std::str::FromStr;
use std::time::Duration;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};

use crate::encoding;

/// The longest [`OperationId`] accepted, in characters.
pub const OPERATION_ID_MAX_LEN: usize = 64;

/// The reasons an identifier can fail to parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseIdError {
    /// The text is not exactly `expected` lowercase hexadecimal digits.
    #[error("expected {expected} lowercase hex digits")]
    InvalidHex {
        /// The number of hex digits the type requires.
        expected: usize,
    },
    /// An operation identifier is empty.
    #[error("operation id is empty")]
    Empty,
    /// An operation identifier is longer than [`OPERATION_ID_MAX_LEN`].
    #[error("operation id is longer than {OPERATION_ID_MAX_LEN} characters")]
    TooLong,
    /// An operation identifier contains a character outside `[A-Za-z0-9_-]`.
    #[error("operation id may contain only A-Z, a-z, 0-9, '_' and '-'")]
    InvalidCharacter,
}

/// Implements the shared surface of a fixed-size byte identifier rendered as
/// lowercase hex: `from_bytes`, `as_bytes`, `to_hex`, `Display`, `Debug`,
/// `FromStr`, `From<[u8; N]>` and string serde.
macro_rules! hex_bytes_type {
    ($name:ident, $len:literal) => {
        impl $name {
            /// Wraps raw bytes.
            pub const fn from_bytes(bytes: [u8; $len]) -> Self {
                Self(bytes)
            }

            /// Returns the raw bytes.
            pub const fn as_bytes(&self) -> &[u8; $len] {
                &self.0
            }

            /// Returns the lowercase hexadecimal text form.
            pub fn to_hex(&self) -> String {
                hex::encode(self.0)
            }
        }

        impl From<[u8; $len]> for $name {
            fn from(bytes: [u8; $len]) -> Self {
                Self(bytes)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.to_hex())
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, concat!(stringify!($name), "({})"), self.to_hex())
            }
        }

        impl FromStr for $name {
            type Err = ParseIdError;

            /// Parses exactly the lowercase hexadecimal text form.
            fn from_str(text: &str) -> Result<Self, Self::Err> {
                encoding::decode_lower_hex::<$len>(text)
                    .map(Self)
                    .ok_or(ParseIdError::InvalidHex { expected: $len * 2 })
            }
        }

        impl Serialize for $name {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(&self.to_hex())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let text = String::deserialize(deserializer)?;
                text.parse().map_err(serde::de::Error::custom)
            }
        }
    };
}

/// A Nostr event identifier: the SHA-256 of the NIP-01 serialisation.
///
/// Its text form is 64 lowercase hexadecimal digits. Callers that need replay
/// protection record verified event identifiers durably.
///
/// # Examples
///
/// ```
/// use stratum_node_core::EventId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let id: EventId = "00".repeat(32).parse()?;
/// assert_eq!(id.as_bytes(), &[0u8; 32]);
/// assert!("AB".repeat(32).parse::<EventId>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EventId([u8; 32]);
hex_bytes_type!(EventId, 32);

/// A SHA-256 digest, written as 64 lowercase hexadecimal digits.
///
/// # Examples
///
/// ```
/// use stratum_node_core::Sha256Digest;
///
/// let digest = Sha256Digest::of(b"abc");
/// assert_eq!(
///     digest.to_hex(),
///     "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
/// );
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Sha256Digest([u8; 32]);
hex_bytes_type!(Sha256Digest, 32);

impl Sha256Digest {
    /// Computes the SHA-256 digest of `data`.
    pub fn of(data: &[u8]) -> Self {
        Self(Sha256::digest(data).into())
    }
}

/// The identifier of a single-use challenge, written as 32 lowercase hex
/// digits.
///
/// This crate performs no I/O, so the caller supplies the 16 bytes; they must
/// come from a cryptographically secure random source.
///
/// # Examples
///
/// ```
/// use stratum_node_core::ChallengeId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let id = ChallengeId::from_bytes([7; 16]);
/// assert_eq!(id.to_string().parse::<ChallengeId>()?, id);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChallengeId([u8; 16]);
hex_bytes_type!(ChallengeId, 16);

/// The identifier of an invitation, written as 32 lowercase hex digits.
///
/// An invitation is bound to one public identity and can be redeemed only by
/// a request that identity signs, so this identifier is a name, not a
/// credential. This crate performs no I/O, so the caller supplies the 16
/// bytes, normally from a secure random source so that identifiers do not
/// collide.
///
/// # Examples
///
/// ```
/// use stratum_node_core::InvitationId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let id = InvitationId::from_bytes([0xab; 16]);
/// assert_eq!(id.to_string(), "ab".repeat(16));
/// assert_eq!(id.to_string().parse::<InvitationId>()?, id);
/// assert!("AB".repeat(16).parse::<InvitationId>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InvitationId([u8; 16]);
hex_bytes_type!(InvitationId, 16);

/// A configuration revision number.
///
/// Revisions count up from zero; [`next`](Self::next) refuses to wrap.
///
/// # Examples
///
/// ```
/// use stratum_node_core::Revision;
///
/// let first = Revision::new(0);
/// assert_eq!(first.next(), Some(Revision::new(1)));
/// assert_eq!(Revision::new(u64::MAX).next(), None);
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct Revision(u64);

impl Revision {
    /// Wraps a revision number.
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Returns the revision number.
    pub const fn get(self) -> u64 {
        self.0
    }

    /// Returns the following revision, or `None` if this is `u64::MAX`.
    pub const fn next(self) -> Option<Self> {
        match self.0.checked_add(1) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }
}

impl From<u64> for Revision {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl From<Revision> for u64 {
    fn from(revision: Revision) -> Self {
        revision.0
    }
}

impl fmt::Display for Revision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A point in time as whole seconds since the Unix epoch.
///
/// This crate never reads a clock; callers pass the current time in.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use stratum_node_core::UnixTime;
///
/// let now = UnixTime::from_secs(1_700_000_000);
/// let later = now.checked_add(Duration::from_secs(300));
/// assert_eq!(later, Some(UnixTime::from_secs(1_700_000_300)));
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct UnixTime(u64);

impl UnixTime {
    /// Wraps a number of seconds since the Unix epoch.
    pub const fn from_secs(secs: u64) -> Self {
        Self(secs)
    }

    /// Returns the number of seconds since the Unix epoch.
    pub const fn as_secs(self) -> u64 {
        self.0
    }

    /// Adds a duration, ignoring sub-second precision, or returns `None` on
    /// overflow.
    pub const fn checked_add(self, duration: Duration) -> Option<Self> {
        match self.0.checked_add(duration.as_secs()) {
            Some(secs) => Some(Self(secs)),
            None => None,
        }
    }

    /// Returns the absolute distance between two times, in seconds.
    pub const fn abs_diff(self, other: Self) -> u64 {
        self.0.abs_diff(other.0)
    }
}

impl From<u64> for UnixTime {
    fn from(secs: u64) -> Self {
        Self(secs)
    }
}

impl From<UnixTime> for u64 {
    fn from(time: UnixTime) -> Self {
        time.0
    }
}

impl fmt::Display for UnixTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A caller-chosen identifier for a mutating operation.
///
/// It is 1 to [`OPERATION_ID_MAX_LEN`] characters drawn from `[A-Za-z0-9_-]`,
/// and is compared exactly (case matters).
///
/// # Examples
///
/// ```
/// use stratum_node_core::OperationId;
///
/// # fn main() -> Result<(), stratum_node_core::ParseIdError> {
/// let op: OperationId = "apply-2026_12_03".parse()?;
/// assert_eq!(op.as_str(), "apply-2026_12_03");
/// assert!("has space".parse::<OperationId>().is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OperationId(String);

impl OperationId {
    /// Returns the identifier text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Checks the length and character set.
    fn validate(text: &str) -> Result<(), ParseIdError> {
        if text.is_empty() {
            return Err(ParseIdError::Empty);
        }
        if text.len() > OPERATION_ID_MAX_LEN {
            return Err(ParseIdError::TooLong);
        }
        if !text
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
        {
            return Err(ParseIdError::InvalidCharacter);
        }
        Ok(())
    }
}

impl FromStr for OperationId {
    type Err = ParseIdError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::validate(text)?;
        Ok(Self(text.to_owned()))
    }
}

impl TryFrom<String> for OperationId {
    type Error = ParseIdError;

    fn try_from(text: String) -> Result<Self, Self::Error> {
        Self::validate(&text)?;
        Ok(Self(text))
    }
}

impl AsRef<str> for OperationId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for OperationId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Serialize for OperationId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for OperationId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Self::try_from(text).map_err(serde::de::Error::custom)
    }
}