cesr-rs 0.7.0

CESR + KERI primitives for Rust as a single feature-gated, no_std-capable crate
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! KERI version string parsing and generation.
//!
//! Version strings are 17-byte ASCII headers that identify the protocol,
//! version, serialization kind, and serialized size of a KERI event.
//!
//! V1 format: `KERI10JSON00025d_`
//! - 4 chars protocol (`KERI` or `ACDC`)
//! - 1 hex char major version
//! - 1 hex char minor version
//! - 4 chars serialization kind (`JSON`, `CBOR`, `MGPK`, `CESR`)
//! - 6 hex chars size (zero-padded)
//! - `_` terminator

use crate::serder::error::SerderError;
#[cfg(feature = "alloc")]
#[allow(
    unused_imports,
    reason = "alloc prelude items; subset used per cfg/feature combination"
)]
use alloc::{format, string::String};
use core::ops::Range;

/// Total length of a V1 version string in bytes.
pub const VERSION_STRING_LEN: usize = 17;

const PROTO_LEN: usize = 4;
const VERSION_LEN: usize = 2;
const KIND_LEN: usize = 4;
const SIZE_LEN: usize = 6;

/// Largest event size encodable in the fixed [`SIZE_LEN`]-hex-digit size field.
pub(crate) const VERSION_SIZE_MAX: u32 = 0x00FF_FFFF;

/// Largest major/minor version encodable in one hex digit.
const VERSION_DIGIT_MAX: u8 = 0xF;

/// Serialization format for the event payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SerKind {
    /// JSON encoding.
    Json,
    /// CBOR encoding.
    Cbor,
    /// `MessagePack` encoding.
    Mgpk,
    /// Native CESR encoding.
    Cesr,
}

impl SerKind {
    /// The 4-character wire representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Json => "JSON",
            Self::Cbor => "CBOR",
            Self::Mgpk => "MGPK",
            Self::Cesr => "CESR",
        }
    }

    /// Parse from a 4-character wire representation.
    ///
    /// # Errors
    ///
    /// Returns [`SerderError::InvalidVersionString`] if the input is not a
    /// recognized serialization kind.
    pub fn from_repr(s: &str) -> Result<Self, SerderError> {
        match s {
            "JSON" => Ok(Self::Json),
            "CBOR" => Ok(Self::Cbor),
            "MGPK" => Ok(Self::Mgpk),
            "CESR" => Ok(Self::Cesr),
            _ => Err(SerderError::InvalidVersionString(format!(
                "unknown serialization kind: {s}"
            ))),
        }
    }
}

/// Protocol identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
    /// Key Event Receipt Infrastructure.
    Keri,
    /// Authentic Chained Data Container.
    Acdc,
}

impl Protocol {
    /// The 4-character wire representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Keri => "KERI",
            Self::Acdc => "ACDC",
        }
    }

    /// Parse from a 4-character wire representation.
    ///
    /// # Errors
    ///
    /// Returns [`SerderError::InvalidVersionString`] if the input is not a
    /// recognized protocol.
    pub fn from_repr(s: &str) -> Result<Self, SerderError> {
        match s {
            "KERI" => Ok(Self::Keri),
            "ACDC" => Ok(Self::Acdc),
            _ => Err(SerderError::InvalidVersionString(format!(
                "unknown protocol: {s}"
            ))),
        }
    }
}

/// A parsed KERI version string.
///
/// Encodes the protocol, version, serialization kind, and total serialized
/// size of a KERI event message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VersionString {
    /// The protocol identifier.
    pub proto: Protocol,
    /// Major version number (0..=15).
    pub major: u8,
    /// Minor version number (0..=15).
    pub minor: u8,
    /// Serialization format.
    pub kind: SerKind,
    /// Total serialized message size in bytes.
    pub size: u32,
}

impl VersionString {
    /// Create a new version string with the given parameters.
    #[must_use]
    pub const fn new(proto: Protocol, major: u8, minor: u8, kind: SerKind, size: u32) -> Self {
        Self {
            proto,
            major,
            minor,
            kind,
            size,
        }
    }

    /// KERI v1.0 JSON with zero size (to be filled after serialization).
    #[must_use]
    pub const fn keri_json_v1() -> Self {
        Self::new(Protocol::Keri, 1, 0, SerKind::Json, 0)
    }

    /// Return a copy with the size field updated.
    #[must_use]
    pub const fn with_size(self, size: u32) -> Self {
        Self {
            proto: self.proto,
            major: self.major,
            minor: self.minor,
            kind: self.kind,
            size,
        }
    }

    /// Render the 17-byte version string.
    ///
    /// # Errors
    ///
    /// Returns [`SerderError::VersionStringOverflow`] if `major`, `minor`, or
    /// `size` does not fit its fixed-width hex field — rendering anyway would
    /// silently widen the string and break the 17-byte frame every parser
    /// depends on.
    pub fn to_str(&self) -> Result<String, SerderError> {
        if self.major > VERSION_DIGIT_MAX {
            return Err(SerderError::VersionStringOverflow {
                field: "major",
                max: u32::from(VERSION_DIGIT_MAX),
            });
        }
        if self.minor > VERSION_DIGIT_MAX {
            return Err(SerderError::VersionStringOverflow {
                field: "minor",
                max: u32::from(VERSION_DIGIT_MAX),
            });
        }
        if self.size > VERSION_SIZE_MAX {
            return Err(SerderError::VersionStringOverflow {
                field: "size",
                max: VERSION_SIZE_MAX,
            });
        }
        Ok(format!(
            "{}{:x}{:x}{}{:06x}_",
            self.proto.as_str(),
            self.major,
            self.minor,
            self.kind.as_str(),
            self.size,
        ))
    }

    /// Parse a version string from the first 17 bytes of `input`.
    ///
    /// # Errors
    ///
    /// Returns [`SerderError::InvalidVersionString`] if the input is too
    /// short, contains unrecognized or non-ASCII fields, or is missing the
    /// terminator.
    pub fn parse(input: &str) -> Result<Self, SerderError> {
        if input.len() < VERSION_STRING_LEN {
            return Err(SerderError::InvalidVersionString(format!(
                "input too short: expected {VERSION_STRING_LEN} bytes, got {}",
                input.len()
            )));
        }

        // Every field lives at a fixed byte offset; a multi-byte UTF-8 char
        // straddling a field boundary makes that offset a non-char-boundary,
        // so checked `get` (never panicking `[a..b]`) is load-bearing here.
        let segment = |range: Range<usize>| {
            input.get(range).ok_or_else(|| {
                SerderError::InvalidVersionString(
                    "non-ASCII or malformed version string segment".into(),
                )
            })
        };

        let proto_str = segment(0..PROTO_LEN)?;
        let proto = Protocol::from_repr(proto_str)?;

        let version_start = PROTO_LEN;
        let major_ch = segment(version_start..version_start + 1)?;
        let minor_ch = segment(version_start + 1..version_start + VERSION_LEN)?;

        let major = u8::from_str_radix(major_ch, 16).map_err(|_| {
            SerderError::InvalidVersionString(format!(
                "invalid major version hex digit: {major_ch}"
            ))
        })?;

        let minor = u8::from_str_radix(minor_ch, 16).map_err(|_| {
            SerderError::InvalidVersionString(format!(
                "invalid minor version hex digit: {minor_ch}"
            ))
        })?;

        let kind_start = PROTO_LEN + VERSION_LEN;
        let kind_str = segment(kind_start..kind_start + KIND_LEN)?;
        let kind = SerKind::from_repr(kind_str)?;

        let size_start = kind_start + KIND_LEN;
        let size_str = segment(size_start..size_start + SIZE_LEN)?;
        let size = u32::from_str_radix(size_str, 16).map_err(|_| {
            SerderError::InvalidVersionString(format!("invalid size hex: {size_str}"))
        })?;

        let terminator = segment(VERSION_STRING_LEN - 1..VERSION_STRING_LEN)?;
        if terminator != "_" {
            return Err(SerderError::InvalidVersionString(format!(
                "missing terminator '_', found '{terminator}'"
            )));
        }

        Ok(Self {
            proto,
            major,
            minor,
            kind,
            size,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keri_json_v1_defaults() {
        let vs = VersionString::keri_json_v1();
        assert_eq!(vs.proto, Protocol::Keri);
        assert_eq!(vs.major, 1);
        assert_eq!(vs.minor, 0);
        assert_eq!(vs.kind, SerKind::Json);
        assert_eq!(vs.size, 0);
    }

    #[test]
    fn to_str_zero_size() {
        let vs = VersionString::keri_json_v1();
        assert_eq!(vs.to_str().unwrap(), "KERI10JSON000000_");
    }

    #[test]
    fn to_str_nonzero_size() {
        let vs = VersionString::keri_json_v1().with_size(0x25d);
        assert_eq!(vs.to_str().unwrap(), "KERI10JSON00025d_");
    }

    #[test]
    fn to_str_renders_max_size_at_fixed_width() {
        let vs = VersionString::keri_json_v1().with_size(VERSION_SIZE_MAX);
        let rendered = vs.to_str().unwrap();
        assert_eq!(rendered, "KERI10JSONffffff_");
        assert_eq!(rendered.len(), VERSION_STRING_LEN);
    }

    #[test]
    fn to_str_rejects_size_beyond_fixed_width() {
        // Bug probe: {:06x} silently widened to 7 hex digits for sizes above
        // VERSION_SIZE_MAX, corrupting the 17-byte frame instead of erroring.
        let vs = VersionString::keri_json_v1().with_size(VERSION_SIZE_MAX + 1);
        assert!(matches!(
            vs.to_str().unwrap_err(),
            SerderError::VersionStringOverflow {
                field: "size",
                max: VERSION_SIZE_MAX,
            }
        ));
    }

    #[test]
    fn to_str_renders_max_versions_at_fixed_width() {
        let vs = VersionString::new(Protocol::Keri, 0xF, 0xF, SerKind::Json, 0);
        let rendered = vs.to_str().unwrap();
        assert_eq!(rendered, "KERIffJSON000000_");
        assert_eq!(rendered.len(), VERSION_STRING_LEN);
    }

    #[test]
    fn to_str_rejects_major_beyond_one_hex_digit() {
        let vs = VersionString::new(Protocol::Keri, 0x10, 0, SerKind::Json, 0);
        assert!(matches!(
            vs.to_str().unwrap_err(),
            SerderError::VersionStringOverflow { field: "major", .. }
        ));
    }

    #[test]
    fn to_str_rejects_minor_beyond_one_hex_digit() {
        let vs = VersionString::new(Protocol::Keri, 0, 0x10, SerKind::Json, 0);
        assert!(matches!(
            vs.to_str().unwrap_err(),
            SerderError::VersionStringOverflow { field: "minor", .. }
        ));
    }

    #[test]
    fn size_capacity_matches_size_field_width() {
        let width = u32::try_from(SIZE_LEN).unwrap();
        assert_eq!(VERSION_SIZE_MAX, (1_u32 << (4 * width)) - 1);
    }

    #[test]
    fn parse_valid() {
        let vs = VersionString::parse("KERI10JSON00025d_").unwrap();
        assert_eq!(vs.proto, Protocol::Keri);
        assert_eq!(vs.major, 1);
        assert_eq!(vs.minor, 0);
        assert_eq!(vs.kind, SerKind::Json);
        assert_eq!(vs.size, 0x25d);
    }

    #[test]
    fn parse_roundtrip() {
        let original = VersionString::new(Protocol::Acdc, 2, 5, SerKind::Cbor, 0x001a_2b3c);
        let rendered = original.to_str().unwrap();
        let parsed = VersionString::parse(&rendered).unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn parse_too_short() {
        let result = VersionString::parse("KERI10JSON");
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("too short"));
    }

    #[test]
    fn parse_unknown_protocol() {
        let result = VersionString::parse("XXXX10JSON000000_");
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("unknown protocol"));
    }

    #[test]
    fn parse_multibyte_char_straddling_proto_boundary_is_error_not_panic() {
        // 'é' occupies bytes 3..5, so byte offset 4 (the proto/major
        // boundary) is not a char boundary — previously panicked in the
        // fixed-offset &str slicing.
        let input = "KER\u{e9}AJSONAAAAAA_";
        assert_eq!(input.len(), VERSION_STRING_LEN);
        assert!(matches!(
            VersionString::parse(input),
            Err(SerderError::InvalidVersionString(_))
        ));
    }

    #[test]
    fn parse_multibyte_char_straddling_terminator_boundary_is_error_not_panic() {
        // 'é' occupies bytes 15..17, so byte offset 16 (the size/terminator
        // boundary) is not a char boundary.
        let input = "KERI10JSONAAAAA\u{e9}";
        assert_eq!(input.len(), VERSION_STRING_LEN);
        assert!(matches!(
            VersionString::parse(input),
            Err(SerderError::InvalidVersionString(_))
        ));
    }

    #[test]
    fn parse_unknown_kind() {
        let result = VersionString::parse("KERI10YAML000000_");
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("unknown serialization kind"));
    }

    #[test]
    fn parse_missing_terminator() {
        let result = VersionString::parse("KERI10JSON000000X");
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("terminator"));
    }

    #[test]
    fn ser_kind_roundtrip() {
        for kind in [SerKind::Json, SerKind::Cbor, SerKind::Mgpk, SerKind::Cesr] {
            let repr = kind.as_str();
            let parsed = SerKind::from_repr(repr).unwrap();
            assert_eq!(kind, parsed);
        }
    }

    #[test]
    fn protocol_roundtrip() {
        for proto in [Protocol::Keri, Protocol::Acdc] {
            let repr = proto.as_str();
            let parsed = Protocol::from_repr(repr).unwrap();
            assert_eq!(proto, parsed);
        }
    }
}