vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
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
//! One strict grammar for every protocol time.
//!
//! Credentials, status lists, receipts and every other signed object carry
//! their times as strings. If two modules (or two languages) read the same
//! string differently, a time one of them refuses can pass in another. So every
//! protocol time in the core goes through this module, and the grammar is the
//! same one the Python, TypeScript and Go implementations use
//! (`test-vectors/time/vector.json` is the shared contract):
//!
//! ```text
//! YYYY-MM-DDTHH:MM:SS[.fraction](Z | +HH:MM | -HH:MM)
//! ```
//!
//! * `T` and `Z` are upper case and nothing else may appear in the string (no
//!   spaces, no trailing newline, no missing offset).
//! * Years run 0001-9999, months and days are real calendar days, hours are
//!   00-23, minutes and seconds 00-59 (a leap second `:60` is refused).
//! * The fraction has 1 to 9 digits and is kept at full precision: compare
//!   instants with [`parse_protocol_time_ns`], never with whole seconds.
//! * The offset is at most 23:59 either way, and the instant it names, moved
//!   to UTC, must still fall inside 0001-01-01T00:00:00Z ..
//!   9999-12-31T23:59:59.999999999Z.
//!
//! A `now` without a timezone does not match the grammar, so it is refused like
//! any other malformed time. Clock skew is 0 to 120 seconds
//! ([`check_clock_skew`]); anything else is refused.

use crate::error::{CoreError, Result};

/// The largest clock skew a verifier may allow, in seconds.
pub const MAX_CLOCK_SKEW_SECONDS: i64 = 120;

const NS_PER_SECOND: i128 = 1_000_000_000;
/// 0001-01-01T00:00:00Z in nanoseconds since the Unix epoch.
const MIN_NS: i128 = -62_135_596_800 * NS_PER_SECOND;
/// 9999-12-31T23:59:59.999999999Z in nanoseconds since the Unix epoch.
const MAX_NS: i128 = 253_402_300_799 * NS_PER_SECOND + 999_999_999;

fn bad(s: &str) -> CoreError {
    // Bound the echoed input so a huge string is not copied into the error.
    let shown: String = s.chars().take(64).collect();
    CoreError::Json(format!("invalid protocol time: {shown:?}"))
}

fn days_in_month(year: i64, month: i64) -> i64 {
    match month {
        2 => {
            let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
            if leap {
                29
            } else {
                28
            }
        }
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Parse a protocol time into exact nanoseconds since 1970-01-01T00:00:00Z
/// (negative before 1970). Works on bytes and checks every position, so
/// malformed or non-ASCII input returns an error and never panics.
pub fn parse_protocol_time_ns(s: &str) -> Result<i128> {
    let b = s.as_bytes();
    // "YYYY-MM-DDTHH:MM:SSZ" is the shortest valid form; the longest is the
    // 9-digit fraction plus a numeric offset (35 bytes).
    if b.len() < 20 || b.len() > 35 {
        return Err(bad(s));
    }
    let digits = |i: usize, len: usize| -> Result<i64> {
        let mut v: i64 = 0;
        for &c in &b[i..i + len] {
            if !c.is_ascii_digit() {
                return Err(bad(s));
            }
            v = v * 10 + i64::from(c - b'0');
        }
        Ok(v)
    };
    if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
        return Err(bad(s));
    }
    let year = digits(0, 4)?;
    let month = digits(5, 2)?;
    let day = digits(8, 2)?;
    let hour = digits(11, 2)?;
    let minute = digits(14, 2)?;
    let second = digits(17, 2)?;
    if !(1..=9999).contains(&year)
        || !(1..=12).contains(&month)
        || day < 1
        || day > days_in_month(year, month)
        || hour > 23
        || minute > 59
        || second > 59
    {
        return Err(bad(s));
    }

    let mut j = 19usize;
    let mut nanos: i128 = 0;
    if b[j] == b'.' {
        j += 1;
        let start = j;
        while j < b.len() && b[j].is_ascii_digit() {
            j += 1;
        }
        let n = j - start;
        if n == 0 || n > 9 {
            return Err(bad(s));
        }
        let mut v: i128 = 0;
        for &c in &b[start..j] {
            v = v * 10 + i128::from(c - b'0');
        }
        for _ in n..9 {
            v *= 10;
        }
        nanos = v;
    }
    if j >= b.len() {
        return Err(bad(s)); // no offset
    }
    let offset_seconds: i64 = match b[j] {
        b'Z' => {
            if j + 1 != b.len() {
                return Err(bad(s));
            }
            0
        }
        b'+' | b'-' => {
            if j + 6 != b.len() || b[j + 3] != b':' {
                return Err(bad(s));
            }
            let oh = digits(j + 1, 2)?;
            let om = digits(j + 4, 2)?;
            if oh > 23 || om > 59 {
                return Err(bad(s));
            }
            let mag = oh * 3600 + om * 60;
            if b[j] == b'+' {
                mag
            } else {
                -mag
            }
        }
        _ => return Err(bad(s)),
    };

    let days = days_from_civil(year, month, day);
    let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_seconds;
    let total = i128::from(seconds) * NS_PER_SECOND + nanos;
    if !(MIN_NS..=MAX_NS).contains(&total) {
        return Err(bad(s));
    }
    Ok(total)
}

/// Parse a protocol time to whole Unix epoch seconds (the floor of the exact
/// instant). Uses the strict grammar of [`parse_protocol_time_ns`].
///
/// Whole seconds drop the fraction, so a validity comparison must use
/// [`parse_protocol_time_ns`] instead; this remains for callers that only need
/// second resolution (for example to derive and format a later time).
pub fn iso_to_epoch_seconds(s: &str) -> Result<i64> {
    let ns = parse_protocol_time_ns(s)?;
    // The parser's range check keeps this well inside i64.
    Ok(ns.div_euclid(NS_PER_SECOND) as i64)
}

/// Format whole seconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ`, the
/// inverse of [`iso_to_epoch_seconds`] for whole-second UTC instants. The
/// wrappers use it to turn the host clock into the `now` a verifier passes to
/// the core.
pub fn epoch_seconds_to_iso(epoch: i64) -> String {
    let days = epoch.div_euclid(86_400);
    let secs = epoch.rem_euclid(86_400);
    // Howard Hinnant's civil-from-days.
    let z = days + 719_468;
    let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        secs / 3600,
        (secs % 3600) / 60,
        secs % 60
    )
}

/// Return the clock skew in nanoseconds when it is an allowed value (0 to
/// [`MAX_CLOCK_SKEW_SECONDS`] seconds), else an error.
pub fn check_clock_skew(clock_skew_seconds: i64) -> Result<i128> {
    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
        return Err(CoreError::Json(format!(
            "clock skew must be between 0 and {MAX_CLOCK_SKEW_SECONDS} seconds, got {clock_skew_seconds}"
        )));
    }
    Ok(i128::from(clock_skew_seconds) * NS_PER_SECOND)
}

/// Read a clock skew from a JSON request: a whole number of seconds (an
/// integral float such as 30.0 counts as 30) in 0 to
/// [`MAX_CLOCK_SKEW_SECONDS`]. Booleans, strings, null, fractions and numbers
/// outside the range are refused.
pub fn clock_skew_from_json(value: &serde_json::Value) -> Result<i64> {
    crate::attenuation::as_int(value, 0, MAX_CLOCK_SKEW_SECONDS).ok_or_else(|| {
        CoreError::Json(format!(
            "clock skew must be a whole number of seconds from 0 to {MAX_CLOCK_SKEW_SECONDS}"
        ))
    })
}

/// Seconds to nanoseconds, for comparing a whole-second bound (a max age, an
/// interval) against parsed instants.
pub fn seconds_to_ns(seconds: i64) -> i128 {
    i128::from(seconds) * NS_PER_SECOND
}

/// Where `now` falls against a validity window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowState {
    /// Inside the window (allowing the skew at each edge).
    Ok,
    /// `validFrom` is more than the skew ahead of `now`.
    NotYetValid,
    /// `now` is more than the skew past `validUntil`.
    Expired,
    /// `validFrom` is after `validUntil`: the window is empty.
    Inverted,
}

impl WindowState {
    pub fn as_str(self) -> &'static str {
        match self {
            WindowState::Ok => "ok",
            WindowState::NotYetValid => "not_yet_valid",
            WindowState::Expired => "expired",
            WindowState::Inverted => "inverted",
        }
    }
}

/// Place `now_ns` against `[from - skew, until + skew]` at full precision. A
/// missing bound is open on that side. An inverted window is reported first.
pub fn window_state_ns(
    now_ns: i128,
    from_ns: Option<i128>,
    until_ns: Option<i128>,
    skew_ns: i128,
) -> WindowState {
    if let (Some(f), Some(u)) = (from_ns, until_ns) {
        if f > u {
            return WindowState::Inverted;
        }
    }
    if let Some(f) = from_ns {
        if f - now_ns > skew_ns {
            return WindowState::NotYetValid;
        }
    }
    if let Some(u) = until_ns {
        if now_ns - u > skew_ns {
            return WindowState::Expired;
        }
    }
    WindowState::Ok
}

/// [`window_state_ns`] over protocol-time strings. Errors on a malformed time
/// or an out-of-range skew.
pub fn window_state(
    now_iso: &str,
    valid_from: Option<&str>,
    valid_until: Option<&str>,
    clock_skew_seconds: i64,
) -> Result<WindowState> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?;
    let from = valid_from.map(parse_protocol_time_ns).transpose()?;
    let until = valid_until.map(parse_protocol_time_ns).transpose()?;
    Ok(window_state_ns(now, from, until, skew))
}

/// Days since the Unix epoch (1970-01-01) for a civil date.
/// Howard Hinnant's algorithm; valid for the full proleptic Gregorian range.
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let y = if month <= 2 { year - 1 } else { year };
    let era = (if y >= 0 { y } else { y - 399 }) / 400;
    let yoe = y - era * 400;
    let mp = if month > 2 { month - 3 } else { month + 9 };
    let doy = (153 * mp + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

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

    #[test]
    fn epoch_seconds_to_iso_round_trips() {
        for iso in [
            "1970-01-01T00:00:00Z",
            "2000-02-29T23:59:59Z",
            "2026-12-03T09:54:03Z",
            "2100-03-01T00:00:00Z",
            "9999-12-31T23:59:59Z",
        ] {
            let secs = iso_to_epoch_seconds(iso).unwrap();
            assert_eq!(epoch_seconds_to_iso(secs), iso);
        }
    }

    #[test]
    fn parses_known_instants() {
        assert_eq!(iso_to_epoch_seconds("1970-01-01T00:00:00Z").unwrap(), 0);
        assert_eq!(
            iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap(),
            1777197600
        );
    }

    #[test]
    fn window_ordering() {
        let a = iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap();
        let b = iso_to_epoch_seconds("2026-04-26T10:05:00Z").unwrap();
        assert_eq!(b - a, 300);
    }

    #[test]
    fn rejects_malformed_without_panic() {
        for s in [
            "",
            "garbage",
            "2026-13-99T10:00:00Z",
            "20\u{00e9}6-04-26T10:00:00Z",
            "2026-04-26 10:00:00",
            "2026-04-26T10:0",
            "2026-04-26T25:00:00Z",
            "2026-04-26T10:00:00+9999",
            "2026-04-26T10:00:00",
            "2026-04-26T10:00:00z",
            "2026-04-26t10:00:00Z",
            "2026-02-29T10:00:00Z",
            "2016-12-31T23:59:60Z",
            "2026-04-26T10:00:00+24:00",
            "2026-04-26T10:00:00Z\n",
            "2026-04-26T10:00:00.Z",
            "2026-04-26T10:00:00.1234567890Z",
            "0000-01-01T00:00:00Z",
            "0001-01-01T00:00:00+00:01",
            "9999-12-31T23:59:59-00:01",
            "2026-04-26T10:00:00\u{00e9}",
            "2026-04-26T10:00:00.\u{00e9}Z",
        ] {
            assert!(parse_protocol_time_ns(s).is_err(), "{s:?} should error");
        }
    }

    #[test]
    fn keeps_fractions_and_offsets() {
        let z = parse_protocol_time_ns("2026-04-26T10:00:00Z").unwrap();
        assert_eq!(
            parse_protocol_time_ns("2026-04-26T10:00:00.250Z").unwrap(),
            z + 250_000_000
        );
        assert_eq!(
            parse_protocol_time_ns("2026-04-26T10:00:00.000000001Z").unwrap(),
            z + 1
        );
        assert_eq!(
            parse_protocol_time_ns("2026-04-26T12:00:00+02:00").unwrap(),
            z
        );
        assert_eq!(
            iso_to_epoch_seconds("1969-12-31T23:59:59.5Z").unwrap(),
            -1,
            "whole seconds are the floor, also before the epoch"
        );
    }

    #[test]
    fn skew_bounds() {
        assert!(check_clock_skew(0).is_ok());
        assert!(check_clock_skew(120).is_ok());
        for s in [-1, 121, i64::MAX, i64::MIN] {
            assert!(check_clock_skew(s).is_err(), "{s}");
        }
    }

    #[test]
    fn window_edges() {
        let w = |now, f, u, s| window_state(now, Some(f), Some(u), s).unwrap();
        assert_eq!(
            w(
                "2026-04-26T11:00:00Z",
                "2026-04-26T09:00:00Z",
                "2026-04-26T11:00:00Z",
                0
            ),
            WindowState::Ok
        );
        assert_eq!(
            w(
                "2026-04-26T11:00:00.000000001Z",
                "2026-04-26T09:00:00Z",
                "2026-04-26T11:00:00Z",
                0
            ),
            WindowState::Expired
        );
        assert_eq!(
            w(
                "2026-04-26T10:00:00Z",
                "2026-04-26T11:00:00Z",
                "2026-04-26T09:00:00Z",
                0
            ),
            WindowState::Inverted
        );
    }
}